diff --git a/AGENTS.md b/AGENTS.md index 2aa63ab8ca..c8cf9e8f6c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -80,6 +80,7 @@ Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them): this worktree's running MCP bridges and actual ports. - `pnpm build` — typecheck + bundle frontend. - `pnpm dogfood:build` / `pnpm dogfood:install` (or `mise run dogfood:build` / `mise run dogfood:install`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data. +- `pnpm dogfood:remote [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote `) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development. - `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`. - `cargo test -p ide-host --test language_smoke -- --ignored --exact ` — code intelligence on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions). diff --git a/Cargo.lock b/Cargo.lock index a40d71c834..45753db2e2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4146,6 +4146,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" name = "ide-agent" version = "0.1.50" dependencies = [ + "base64 0.22.1", "blake3", "dunce", "encoding_rs", @@ -4845,6 +4846,7 @@ dependencies = [ name = "ide-sdk" version = "0.1.50" dependencies = [ + "dirs 6.0.0", "dunce", "flate2", "ide-core", diff --git a/crates/ide-agent/Cargo.toml b/crates/ide-agent/Cargo.toml index 52200335db..7ba46213c1 100644 --- a/crates/ide-agent/Cargo.toml +++ b/crates/ide-agent/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [dependencies] encoding_rs.workspace = true +base64.workspace = true blake3.workspace = true ide-vfs.workspace = true ide-core.workspace = true diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index fa879b7df2..4b4d94027f 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -23,6 +23,7 @@ mod provider; pub mod registry; pub mod security; mod shell; +pub mod skill_installer; pub mod skills; mod timeline; mod worktree; @@ -31,6 +32,10 @@ pub use catalogs::AgentCatalogs; pub use cli_update::{AgentCliOffer, AgentCliUpdateResult}; pub use external::ExternalSession; pub use model::*; +pub use skill_installer::{ + InstallRemoteSkillRequest, RemoteSkillBrowseResult, RemoteSkillCandidate, RemoteSkillFile, RemoteSkillPreview, + SkillScanWarning, SkillScanWarningKind, +}; use conversation::{Conversation, SavedSubagent, Session}; use ide_core::{IdeError, IdeResult, IpcPath}; @@ -58,6 +63,9 @@ pub type NewTaskApprovalsHook = Arc ide_core::settings::NewTaskAppro /// attached projects the user trusts. pub type WorkspaceRootsHook = Arc Vec + Send + Sync>; +/// Returns the project's git executable (`None`: the default), which the tasks' git runs. +pub type GitExecutableHook = Arc Option + Send + Sync>; + /// Entry changes are batched for this long before they are sent. const FLUSH_DELAY: Duration = Duration::from_millis(40); /// Updates that arrive this late after `session/load` returns are still replayed history. @@ -145,11 +153,19 @@ pub struct SkillsPolicy { pub workspace_trusted: bool, /// All workspace folders (the project root plus any multi-repo workspace members). pub workspace_roots: Vec, + /// Validated `` folders contributed by live OpenIDEA plugins (`[[contributes.skills]]`). + pub plugin_dirs: Vec, } impl Default for SkillsPolicy { fn default() -> Self { - Self { user: BTreeMap::new(), workspace: BTreeMap::new(), workspace_trusted: true, workspace_roots: Vec::new() } + Self { + user: BTreeMap::new(), + workspace: BTreeMap::new(), + workspace_trusted: true, + workspace_roots: Vec::new(), + plugin_dirs: Vec::new(), + } } } @@ -172,6 +188,7 @@ struct Shared { security: RwLock>, new_task_approvals: RwLock>, workspace_roots: RwLock>, + git_executable: RwLock>, known: Arc>>, providers: RwLock>, /// Last probe of each provider. @@ -586,6 +603,7 @@ impl AgentManager { security: RwLock::new(None), new_task_approvals: RwLock::new(None), workspace_roots: RwLock::new(None), + git_executable: RwLock::new(None), known, providers, probes: Mutex::new(HashMap::new()), @@ -658,6 +676,11 @@ impl AgentManager { *self.shared.workspace_roots.write() = Some(hook); } + /// Sets the callback that reads the project's git executable. + pub fn set_git_executable_hook(&self, hook: GitExecutableHook) { + *self.shared.git_executable.write() = Some(hook); + } + /// The agents (custom ones re-read), whether each is installed, and what they offered last time. pub fn providers(&self) -> Vec { let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets()); @@ -818,10 +841,11 @@ impl AgentManager { (policy, shared.paths.project_root.clone()) }; let roots = if policy.workspace_roots.is_empty() { vec![root] } else { policy.workspace_roots }; + let plugin_dirs = policy.plugin_dirs; let home = self.shared.paths.home_dir.clone(); blocking(move || { Ok(skills::resolve( - skills::discover_skills_in(&roots, home.as_deref()), + skills::discover_skills_with_plugins(&roots, home.as_deref(), &plugin_dirs), None, &policy.workspace, &policy.user, @@ -969,14 +993,15 @@ impl AgentManager { } let dir = self.shared.paths.worktrees_dir.clone(); let (t, b) = (title.clone(), req.base.clone()); - let c = blocking(move || worktree::create(&root, &dir, &t, b.as_deref())).await?; + let c = vcs(&self.shared, move || worktree::create(&root, &dir, &t, b.as_deref())).await?; (c.path, Some(c.branch), Some(c.base), Some(c.base_commit), BTreeMap::new()) } Isolation::Local => { let r = root.clone(); - let (head, before) = - blocking(move || Ok((worktree::head_of(&r).ok(), worktree::snapshot(&r).unwrap_or_default()))) - .await?; + let (head, before) = vcs(&self.shared, move || { + Ok((worktree::head_of(&r).ok(), worktree::snapshot(&r).unwrap_or_default())) + }) + .await?; let (base, commit) = head.unzip(); (root, None, base, commit, before) } @@ -1010,7 +1035,7 @@ impl AgentManager { } else { let name = format!("{id}.before"); let (dir, at, files) = (self.shared.paths.store_dir.join(&name), cwd.clone(), before.clone()); - match blocking(move || worktree::save_before(&at, &files, &dir)).await { + match vcs(&self.shared, move || worktree::save_before(&at, &files, &dir)).await { Ok(saved) => saved.then_some(name), Err(e) => { tracing::warn!("saving the changed files of agent task {id}: {e}"); @@ -1812,7 +1837,7 @@ impl AgentManager { let _ = tokio::time::timeout(EXIT_WAIT, peer.exited()).await; } let worktrees = self.shared.paths.worktrees_dir.clone(); - blocking(move || worktree::remove(&root, &worktrees, &cwd)).await?; + vcs(&self.shared, move || worktree::remove(&root, &worktrees, &cwd)).await?; } Ok(()) } @@ -1822,7 +1847,7 @@ impl AgentManager { let task = self.task(id)?; let at = task.base(); let (before, touched) = task.attribution(); - blocking(move || Ok(worktree::made_by_task(at.changes(&before)?, touched.as_deref()))).await + vcs(&self.shared, move || Ok(worktree::made_by_task(at.changes(&before)?, touched.as_deref()))).await } /// The task's uncommitted changes and, for a worktree task, the commits made since it @@ -1831,7 +1856,7 @@ impl AgentManager { let task = self.task(id)?; let at = task.base(); let (before, touched) = task.attribution(); - blocking(move || { + vcs(&self.shared, move || { let mut grouped = at.grouped_changes(&before)?; grouped.uncommitted = worktree::made_by_task(grouped.uncommitted, touched.as_deref()); Ok(grouped) @@ -1844,7 +1869,7 @@ impl AgentManager { pub async fn turn_changes(&self, id: &str) -> IdeResult> { let (cwd, turn, dir) = self.task(id)?.last_turn(); let Some(turn) = turn else { return Ok(Vec::new()) }; - blocking(move || { + vcs(&self.shared, move || { let changed = match &turn.changed { Some(changed) => changed.clone(), None => worktree::changed_in_turn(&cwd, &turn)?.1, @@ -1861,10 +1886,10 @@ impl AgentManager { if view == AgentChangesView::LastTurn { let (cwd, turn, dir) = task.last_turn(); let Some(turn) = turn else { return Ok(None) }; - return blocking(move || worktree::turn_text(&cwd, &path, &turn, &dir)).await; + return vcs(&self.shared, move || worktree::turn_text(&cwd, &path, &turn, &dir)).await; } let at = task.base(); - blocking(move || { + vcs(&self.shared, move || { let rev = match view { AgentChangesView::Group => worktree::head_commit(at.cwd())?, _ => at.rev()?, @@ -1898,7 +1923,7 @@ impl AgentManager { let s = task.state.lock(); (s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)), s.touched.clone()) }; - let (restamped, restored) = blocking(move || { + let (restamped, restored) = vcs(&self.shared, move || { let (changes, rev) = match view { AgentChangesView::Group => (at.grouped_changes(&before)?.uncommitted, worktree::head_commit(at.cwd())?), AgentChangesView::SinceStart | AgentChangesView::LastTurn => (at.changes(&before)?, at.rev()?), @@ -1954,7 +1979,7 @@ impl AgentManager { let s = task.state.lock(); (s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name))) }; - let restamped = blocking(move || { + let restamped = vcs(&self.shared, move || { let changed = match &turn.changed { Some(changed) => changed.clone(), None => worktree::changed_in_turn(&cwd, &turn)?.1, @@ -2011,7 +2036,7 @@ impl AgentManager { let Some(base) = base else { return Err(IdeError::invalid("the task has no base revision to accept from")); }; - blocking(move || { + vcs(&self.shared, move || { let wanted: Vec = worktree::without_untouched(worktree::changes(&cwd, &base)?, &before) .into_iter() .filter(|c| rel_paths.as_ref().is_none_or(|p| p.contains(&c.rel_path))) @@ -2142,7 +2167,7 @@ impl Task { }; blocking(move || { Ok(skills::resolve( - skills::discover_skills_in(&roots, home.as_deref()), + skills::discover_skills_with_plugins(&roots, home.as_deref(), &policy.plugin_dirs), Some(&overrides), &policy.workspace, &policy.user, @@ -2266,7 +2291,7 @@ impl Task { /// Records the checkout as a turn starts: what the turn's changes are compared with. async fn checkout_before_turn(&self) { let (cwd, previous, dir) = self.last_turn(); - let turn = match blocking(move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await { + let turn = match vcs(&self.shared, move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await { Ok(turn) => Some(Arc::new(turn)), Err(e) => { tracing::warn!("recording the checkout as a turn of agent task {} starts: {e}", self.id); @@ -2283,7 +2308,9 @@ impl Task { let (cwd, turn, _) = self.last_turn(); let Some(turn) = turn else { return }; let start = turn.clone(); - let Ok((in_worktree, all)) = blocking(move || worktree::changed_in_turn(&cwd, &start)).await else { return }; + let Ok((in_worktree, all)) = vcs(&self.shared, move || worktree::changed_in_turn(&cwd, &start)).await else { + return; + }; { let mut s = self.state.lock(); if !in_worktree.is_empty() @@ -4237,6 +4264,12 @@ async fn blocking(f: impl FnOnce() -> IdeResult + Send + ' tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))? } +/// [`blocking`] for work that runs git: the repositories it opens run the project's git. +async fn vcs(shared: &Shared, f: impl FnOnce() -> IdeResult + Send + 'static) -> IdeResult { + let git = shared.git_executable.read().as_ref().and_then(|hook| hook()); + blocking(move || ide_vcs::with_git_executable(git.as_deref(), f)).await +} + #[cfg(test)] mod replay; #[cfg(test)] diff --git a/crates/ide-agent/src/model.rs b/crates/ide-agent/src/model.rs index 9052a3fdab..6af16727d8 100644 --- a/crates/ide-agent/src/model.rs +++ b/crates/ide-agent/src/model.rs @@ -898,6 +898,8 @@ pub enum AgentSkillSource { Workspace, /// The user's `~/.agents/skills` (what `npx skills add` fills). User, + /// Contributed by an enabled OpenIDEA plugin (`[[contributes.skills]]`). + Plugin, /// The project's `.claude/skills`. ClaudeWorkspace, /// `~/.claude/skills`. @@ -920,7 +922,7 @@ impl AgentSkillSource { /// Whether skills of this source are only read, never delivered by OpenIDEA: the CLI /// discovers them itself, so "off" holds only where the CLI supports a native disable. pub fn discovered(&self) -> bool { - !matches!(self, Self::Workspace | Self::User) + !matches!(self, Self::Workspace | Self::User | Self::Plugin) } } @@ -946,6 +948,12 @@ pub struct AgentSkill { /// True when frontmatter sets `disable-model-invocation: true` (defaults to `slashOnly`). #[serde(default)] pub disable_model_invocation: bool, + /// True when frontmatter sets `context: fork` (passed through natively to supporting CLIs). + #[serde(default)] + pub context_fork: bool, + /// Optional `paths` / `globs` patterns from frontmatter (passed through natively to supporting CLIs). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub paths: Vec, /// The `SKILL.md` passes validation (`name` matches its folder, `description` present). pub valid: bool, /// What validation found (`name` mismatch, missing or over-long description…). diff --git a/crates/ide-agent/src/skill_installer.rs b/crates/ide-agent/src/skill_installer.rs new file mode 100644 index 0000000000..e4d493edeb --- /dev/null +++ b/crates/ide-agent/src/skill_installer.rs @@ -0,0 +1,1384 @@ +//! Native Agent Skill browser, previewer, static security scanner, and subtree installer (#5115). +//! +//! Accepts the same direct GitHub source forms `npx skills add` accepts (`owner/repo`, +//! `owner/repo@ref_or_skill`, `owner/repo#ref`, `owner/repo/subpath[@ref]`, +//! `https://github.com/owner/repo[/tree/[/]]`, and pasted +//! `https://skills.sh//[/]` links), resolves the repository tree +//! through [`ide_tools::Http`] without spawning `git` or `npx`, scans `SKILL.md` and +//! bundled files before writing to disk, and installs only the selected skill's subtree +//! into `~/.agents/skills/` (User) or `/.agents/skills/` (Workspace). + +use crate::McpScope; +use base64::Engine as _; +use ide_core::error::ErrorKind; +use ide_core::{CancellationToken, IdeError, IdeResult}; +use ide_tools::Http; +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::path::{Component, Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// Maximum JSON response size for GitHub repository metadata (1 MiB). +const MAX_REPO_META_BYTES: u64 = 1 << 20; +/// Maximum JSON response size for recursive Git tree listing (8 MiB). +const MAX_TREE_JSON_BYTES: u64 = 8 << 20; +/// Maximum total unpacked size of one installed skill subtree (2 MiB). +pub const MAX_SKILL_SUBTREE_BYTES: u64 = 2 << 20; +/// Maximum single blob size inside a skill subtree (1 MiB). +const MAX_SINGLE_BLOB_BYTES: u64 = 1 << 20; +/// Maximum number of files inside one installed skill subtree. +const MAX_SKILL_FILES: usize = 256; + +const SCRIPT_EXTENSIONS: &[&str] = &[ + "sh", "bash", "zsh", "fish", "py", "ps1", "bat", "cmd", "js", "mjs", "cjs", "ts", "mts", "cts", "rb", "pl", "exe", + "dll", "so", "dylib", "wasm", +]; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct RemoteSkillCandidate { + /// Target folder name (`` under `.agents/skills/`). + pub folder_name: String, + /// Repository-relative directory holding `SKILL.md` (`""` when at repository root). + pub subpath: String, + pub file_count: u32, + pub total_bytes: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct RemoteSkillBrowseResult { + pub owner: String, + pub repo: String, + pub git_ref: String, + pub tree_sha: String, + pub truncated: bool, + pub skills: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct RemoteSkillFile { + /// Path relative to the skill folder (e.g. `"SKILL.md"`, `"scripts/check.sh"`). + pub path: String, + pub size: u64, + pub executable: bool, + pub symlink: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum SkillScanWarningKind { + HiddenUnicode, + OutOfRootSymlink, + ExecutableScript, + AllowedToolsShell, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SkillScanWarning { + pub kind: SkillScanWarningKind, + pub file: String, + pub message: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct RemoteSkillPreview { + pub owner: String, + pub repo: String, + pub git_ref: String, + pub tree_sha: String, + pub subpath: String, + pub skill_name: String, + pub description: String, + pub skill_markdown: String, + pub files: Vec, + pub scan_warnings: Vec, + pub already_installed_user: bool, + pub already_installed_workspace: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct InstallRemoteSkillRequest { + pub owner: String, + pub repo: String, + pub git_ref: String, + pub subpath: String, + pub scope: McpScope, + /// Must be `true` when the static security scan produces any warnings. + #[serde(default)] + pub confirm_warnings: bool, + /// Must be `true` to replace an existing folder of the same name in `scope`. + #[serde(default)] + pub overwrite: bool, +} + +/// Parsed user source input (`owner/repo[/subpath][@ref]`, GitHub URL, or `skills.sh` URL). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ParsedSource { + pub owner: String, + pub repo: String, + /// Explicit `#ref`, `/tree/`, or `subpath@ref`. + pub explicit_ref: Option, + /// `@suffix` on bare `owner/repo@suffix`, which may be either a Git ref or a skill name. + pub ref_or_skill: Option, + /// Explicit repository subpath filter (normalized forward-slash relative path, no `SKILL.md` leaf). + pub subpath: Option, + /// Explicit skill folder name filter (e.g. from `https://skills.sh/owner/repo/skill`). + pub skill_filter: Option, +} + +#[derive(Clone, Debug, Deserialize)] +pub struct GitTree { + pub sha: String, + #[serde(default)] + pub truncated: bool, + pub tree: Vec, +} + +#[derive(Clone, Debug, Deserialize)] +pub struct GitTreeEntry { + pub path: String, + pub mode: String, + #[serde(rename = "type")] + pub kind: String, + pub sha: String, + #[serde(default)] + pub size: Option, +} + +#[derive(Clone, Copy, Debug)] +pub struct RepoRef<'a> { + pub owner: &'a str, + pub repo: &'a str, + pub git_ref: &'a str, +} + +pub trait SkillSourceFetcher: Send + Sync { + fn default_branch(&self, owner: &str, repo: &str, cancel: &CancellationToken) -> IdeResult; + fn git_tree(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult; + fn read_blob( + &self, + target: RepoRef<'_>, + repo_path: &str, + blob_sha: &str, + max_bytes: u64, + cancel: &CancellationToken, + ) -> IdeResult>; +} + +pub struct GitHubHttpFetcher { + json_http: Http, + unauth_json_http: Http, + raw_http: Http, +} + +impl GitHubHttpFetcher { + pub fn new(search_path: &std::ffi::OsStr) -> IdeResult { + let json_http = Http::new(search_path)?.https_only().accept("application/vnd.github+json"); + let unauth_json_http = + Http::new(search_path)?.https_only().without_github_auth().accept("application/vnd.github+json"); + let raw_http = Http::new(search_path)?.https_only().without_github_auth(); + Ok(Self { json_http, unauth_json_http, raw_http }) + } + + /// Retries unauthenticated when an expired ambient `GITHUB_TOKEN` / `gh` login returns HTTP 401 on a public repo. + fn get_github_json(&self, url: &str, max_bytes: u64, cancel: &CancellationToken) -> IdeResult { + match self.json_http.get_text_limited(url, Some(max_bytes), cancel) { + Ok(body) => Ok(body), + Err(err) if !cancel.is_cancelled() && err.message.contains("401") => { + self.unauth_json_http.get_text_limited(url, Some(max_bytes), cancel) + } + Err(err) => Err(err), + } + } +} + +#[derive(Deserialize)] +struct RepoMeta { + default_branch: String, +} + +#[derive(Deserialize)] +struct BlobResponse { + #[serde(default)] + encoding: String, + #[serde(default)] + content: String, +} + +impl SkillSourceFetcher for GitHubHttpFetcher { + fn default_branch(&self, owner: &str, repo: &str, cancel: &CancellationToken) -> IdeResult { + validate_repo_coord(owner, "owner")?; + validate_repo_coord(repo, "repository")?; + let url = format!("https://api.github.com/repos/{owner}/{repo}"); + let body = self.get_github_json(&url, MAX_REPO_META_BYTES, cancel)?; + let meta: RepoMeta = serde_json::from_str(&body) + .map_err(|e| IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}: invalid GitHub metadata: {e}")))?; + validate_git_ref(&meta.default_branch)?; + Ok(meta.default_branch) + } + + fn git_tree(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult { + let RepoRef { owner, repo, git_ref } = target; + validate_repo_coord(owner, "owner")?; + validate_repo_coord(repo, "repository")?; + validate_git_ref(git_ref)?; + let encoded_ref = encode_url_segment(git_ref); + let url = format!("https://api.github.com/repos/{owner}/{repo}/git/trees/{encoded_ref}?recursive=1"); + let body = self.get_github_json(&url, MAX_TREE_JSON_BYTES, cancel)?; + serde_json::from_str(&body) + .map_err(|e| IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{git_ref}: invalid Git tree: {e}"))) + } + + fn read_blob( + &self, + target: RepoRef<'_>, + repo_path: &str, + blob_sha: &str, + max_bytes: u64, + cancel: &CancellationToken, + ) -> IdeResult> { + let RepoRef { owner, repo, git_ref } = target; + validate_repo_coord(owner, "owner")?; + validate_repo_coord(repo, "repository")?; + validate_git_ref(git_ref)?; + if blob_sha.is_empty() || !blob_sha.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(IdeError::invalid("invalid Git blob SHA")); + } + // Base64 expands by ~4/3 plus JSON wrapper. + let json_limit = max_bytes.saturating_mul(2).saturating_add(4096); + let blob_url = format!("https://api.github.com/repos/{owner}/{repo}/git/blobs/{blob_sha}"); + match self.get_github_json(&blob_url, json_limit, cancel) { + Ok(text) => { + let parsed: BlobResponse = serde_json::from_str(&text) + .map_err(|e| IdeError::new(ErrorKind::Protocol, format!("invalid Git blob JSON: {e}")))?; + if parsed.encoding != "base64" { + return Err(IdeError::new( + ErrorKind::Protocol, + format!("unsupported Git blob encoding {:?}", parsed.encoding), + )); + } + let cleaned: Vec = parsed.content.bytes().filter(|b| !b.is_ascii_whitespace()).collect(); + let bytes = base64::engine::general_purpose::STANDARD + .decode(cleaned) + .map_err(|e| IdeError::new(ErrorKind::Protocol, format!("invalid base64 blob: {e}")))?; + if bytes.len() as u64 > max_bytes { + return Err(IdeError::invalid(format!("{repo_path}: exceeds {} KiB limit", max_bytes >> 10))); + } + Ok(bytes) + } + Err(api_err) => { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + // Fallback for unauthenticated public GitHub API rate limits. + let encoded_ref = encode_url_segment(git_ref); + let encoded_path = repo_path.split('/').map(encode_url_segment).collect::>().join("/"); + let raw_url = format!("https://raw.githubusercontent.com/{owner}/{repo}/{encoded_ref}/{encoded_path}"); + let tmp = tempfile::NamedTempFile::new()?; + let silent = |_: ide_tools::InstallEvent| {}; + self.raw_http.download(&raw_url, tmp.path(), Some(max_bytes), cancel, &silent).map_err(|_| api_err)?; + let bytes = std::fs::read(tmp.path())?; + if bytes.len() as u64 > max_bytes { + return Err(IdeError::invalid(format!("{repo_path}: exceeds {} KiB limit", max_bytes >> 10))); + } + Ok(bytes) + } + } + } +} + +fn encode_url_segment(seg: &str) -> String { + let mut out = String::with_capacity(seg.len()); + for b in seg.bytes() { + if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { + out.push(b as char); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + +fn validate_repo_coord(value: &str, what: &str) -> IdeResult<()> { + if value.is_empty() + || value.len() > 100 + || value == "." + || value == ".." + || !value.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) + { + return Err(IdeError::invalid(format!("Invalid GitHub {what} {value:?}"))); + } + Ok(()) +} + +fn validate_git_ref(git_ref: &str) -> IdeResult<()> { + if git_ref.is_empty() + || git_ref.len() > 200 + || git_ref.starts_with('-') + || git_ref.contains("..") + || git_ref.bytes().any(|b| b.is_ascii_control() || matches!(b, b' ' | b'?' | b'#' | b'\\' | b'~' | b'^' | b':')) + { + return Err(IdeError::invalid(format!("Invalid Git ref {git_ref:?}"))); + } + Ok(()) +} + +fn normalize_subpath(raw: &str) -> IdeResult> { + let trimmed = raw.trim().trim_matches('/'); + if trimmed.is_empty() { + return Ok(None); + } + let stripped = trimmed.strip_suffix("/SKILL.md").unwrap_or(if trimmed == "SKILL.md" { "" } else { trimmed }); + if stripped.is_empty() { + return Ok(None); + } + let mut parts = Vec::new(); + for seg in stripped.split('/') { + if seg.is_empty() || seg == "." || seg == ".." || seg.contains('\\') { + return Err(IdeError::invalid(format!("Invalid skill path {raw:?}"))); + } + parts.push(seg); + } + Ok(Some(parts.join("/"))) +} + +/// Parses `owner/repo[/path][@ref]`, `owner/repo#ref`, GitHub URLs, and `skills.sh` URLs. +pub fn parse_source(input: &str) -> IdeResult { + let s = input.trim(); + if s.is_empty() { + return Err(IdeError::invalid("Enter a GitHub repository such as owner/repo or owner/repo@skill")); + } + + // Pasted https://skills.sh//[/] URL -> resolve directly from GitHub. + if let Some(rest) = s.strip_prefix("https://skills.sh/").or_else(|| s.strip_prefix("http://skills.sh/")) { + let rest = rest.split(['?', '#']).next().unwrap_or(rest).trim_matches('/'); + let parts: Vec<&str> = rest.split('/').filter(|p| !p.is_empty()).collect(); + if parts.len() < 2 || parts.len() > 3 { + return Err(IdeError::invalid("Expected https://skills.sh//[/]")); + } + validate_repo_coord(parts[0], "owner")?; + validate_repo_coord(parts[1], "repository")?; + let skill_filter = if parts.len() == 3 { + let name = parts[2].trim(); + if !valid_skill_name(name) { + return Err(IdeError::invalid(format!("Invalid skill name {name:?}"))); + } + Some(name.to_owned()) + } else { + None + }; + return Ok(ParsedSource { + owner: parts[0].to_owned(), + repo: parts[1].to_owned(), + explicit_ref: None, + ref_or_skill: None, + subpath: None, + skill_filter, + }); + } + + // Full GitHub HTTPS URL. + if let Some(rest) = s.strip_prefix("https://github.com/").or_else(|| s.strip_prefix("http://github.com/")) { + let (path_part, hash_ref) = match rest.split_once('#') { + Some((p, h)) if !h.is_empty() => (p, Some(h)), + _ => (rest.split('?').next().unwrap_or(rest), None), + }; + let parts: Vec<&str> = path_part.trim_matches('/').split('/').filter(|p| !p.is_empty()).collect(); + if parts.len() < 2 { + return Err(IdeError::invalid("Expected https://github.com//")); + } + let owner = parts[0]; + let repo = parts[1].strip_suffix(".git").unwrap_or(parts[1]); + validate_repo_coord(owner, "owner")?; + validate_repo_coord(repo, "repository")?; + if parts.len() == 2 { + if let Some(r) = hash_ref { + validate_git_ref(r)?; + } + return Ok(ParsedSource { + owner: owner.to_owned(), + repo: repo.to_owned(), + explicit_ref: hash_ref.map(str::to_owned), + ref_or_skill: None, + subpath: None, + skill_filter: None, + }); + } + if matches!(parts[2], "tree" | "blob") { + if parts.len() < 4 { + return Err(IdeError::invalid("Expected https://github.com///tree/[/]")); + } + let git_ref = parts[3]; + validate_git_ref(git_ref)?; + let subpath = if parts.len() > 4 { normalize_subpath(&parts[4..].join("/"))? } else { None }; + return Ok(ParsedSource { + owner: owner.to_owned(), + repo: repo.to_owned(), + explicit_ref: Some(git_ref.to_owned()), + ref_or_skill: None, + subpath, + skill_filter: None, + }); + } + return Err(IdeError::invalid( + "Unsupported GitHub URL path; use https://github.com//[/tree//]", + )); + } + + if s.contains("://") { + return Err(IdeError::invalid("Only GitHub (`owner/repo`) sources are supported")); + } + + // Shorthand: `owner/repo[/subpath][@ref|#ref]` or `owner/repo@skill`. + let (lhs, explicit_hash_ref) = match s.split_once('#') { + Some((l, r)) => { + validate_git_ref(r)?; + (l, Some(r.to_owned())) + } + None => (s, None), + }; + let (path_spec, at_suffix) = match lhs.rsplit_once('@') { + Some((l, r)) if explicit_hash_ref.is_none() => { + if r.is_empty() { + return Err(IdeError::invalid("Missing ref or skill name after `@`")); + } + validate_git_ref(r)?; + (l, Some(r.to_owned())) + } + _ => (lhs, None), + }; + let segs: Vec<&str> = path_spec.trim_matches('/').split('/').filter(|p| !p.is_empty()).collect(); + if segs.len() < 2 { + return Err(IdeError::invalid("Expected `/` (for example `vercel-labs/agent-skills`)")); + } + let owner = segs[0]; + let repo = segs[1].strip_suffix(".git").unwrap_or(segs[1]); + validate_repo_coord(owner, "owner")?; + validate_repo_coord(repo, "repository")?; + let subpath = if segs.len() > 2 { normalize_subpath(&segs[2..].join("/"))? } else { None }; + + // When a subpath is already present (`owner/repo/skills/foo@v1`), `@v1` is unambiguously a Git ref. + // On bare `owner/repo@suffix`, `suffix` may be either a Git ref (`main`, `v1.0.0`) or a skill name (`find-skills`). + let (explicit_ref, ref_or_skill) = if let Some(h) = explicit_hash_ref { + (Some(h), None) + } else if subpath.is_some() { + (at_suffix, None) + } else { + (None, at_suffix) + }; + + Ok(ParsedSource { + owner: owner.to_owned(), + repo: repo.to_owned(), + explicit_ref, + ref_or_skill, + subpath, + skill_filter: None, + }) +} + +fn valid_skill_name(name: &str) -> bool { + (1..=64).contains(&name.len()) && name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') +} + +/// Resolves `source` and lists matching `SKILL.md` directories in the repository. +pub fn browse_skills( + fetcher: &dyn SkillSourceFetcher, + source: &str, + cancel: &CancellationToken, +) -> IdeResult { + let parsed = parse_source(source)?; + let (git_ref, tree, skill_filter) = if let Some(explicit_ref) = parsed.explicit_ref { + let tree = + fetcher.git_tree(RepoRef { owner: &parsed.owner, repo: &parsed.repo, git_ref: &explicit_ref }, cancel)?; + (explicit_ref, tree, parsed.skill_filter) + } else if let Some(suffix) = parsed.ref_or_skill { + // Try `suffix` as a Git ref first; if absent, fall back to the default branch and treat `suffix` as a skill filter. + match fetcher.git_tree(RepoRef { owner: &parsed.owner, repo: &parsed.repo, git_ref: &suffix }, cancel) { + Ok(tree) => (suffix, tree, parsed.skill_filter), + Err(_) => { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let default_branch = fetcher.default_branch(&parsed.owner, &parsed.repo, cancel)?; + let tree = fetcher + .git_tree(RepoRef { owner: &parsed.owner, repo: &parsed.repo, git_ref: &default_branch }, cancel)?; + (default_branch, tree, Some(suffix)) + } + } + } else { + let default_branch = fetcher.default_branch(&parsed.owner, &parsed.repo, cancel)?; + let tree = + fetcher.git_tree(RepoRef { owner: &parsed.owner, repo: &parsed.repo, git_ref: &default_branch }, cancel)?; + (default_branch, tree, parsed.skill_filter) + }; + + let mut skill_dirs: Vec<(String, String)> = Vec::new(); + for entry in &tree.tree { + if entry.kind != "blob" { + continue; + } + if entry.path == "SKILL.md" { + let fallback = sanitize_repo_as_skill_name(&parsed.repo); + skill_dirs.push((String::new(), fallback)); + } else if let Some(dir) = entry.path.strip_suffix("/SKILL.md") + && let Some(folder) = dir.rsplit('/').next() + && !folder.starts_with('.') + { + skill_dirs.push((dir.to_owned(), folder.to_owned())); + } + } + + let mut candidates = Vec::new(); + for (dir, folder_name) in skill_dirs { + if let Some(sub) = parsed.subpath.as_deref() + && dir != sub + && !dir.starts_with(&format!("{sub}/")) + { + continue; + } + if let Some(filter) = skill_filter.as_deref() + && !folder_name.eq_ignore_ascii_case(filter) + && !dir.eq_ignore_ascii_case(filter) + { + continue; + } + let prefix = if dir.is_empty() { String::new() } else { format!("{dir}/") }; + let mut file_count = 0u32; + let mut total_bytes = 0u64; + for e in &tree.tree { + if e.kind == "blob" && (dir.is_empty() || e.path.starts_with(&prefix)) { + file_count = file_count.saturating_add(1); + total_bytes = total_bytes.saturating_add(e.size.unwrap_or(0)); + } + } + candidates.push(RemoteSkillCandidate { folder_name, subpath: dir, file_count, total_bytes }); + } + candidates.sort_by(|a, b| a.folder_name.cmp(&b.folder_name).then_with(|| a.subpath.cmp(&b.subpath))); + + if candidates.is_empty() { + return Err(IdeError::not_found(format!("No SKILL.md found in {}/{} ({git_ref})", parsed.owner, parsed.repo))); + } + + Ok(RemoteSkillBrowseResult { + owner: parsed.owner, + repo: parsed.repo, + git_ref, + tree_sha: tree.sha, + truncated: tree.truncated, + skills: candidates, + }) +} + +fn sanitize_repo_as_skill_name(repo: &str) -> String { + let mut out = String::new(); + for c in repo.chars() { + if c.is_ascii_alphanumeric() { + out.push(c.to_ascii_lowercase()); + } else if (c == '-' || c == '_' || c == '.') && !out.ends_with('-') { + out.push('-'); + } + if out.len() >= 64 { + break; + } + } + out.trim_matches('-').to_owned() +} + +struct PreparedSkillBundle { + tree_sha: String, + skill_name: String, + description: String, + skill_markdown: String, + files: Vec, + scan_warnings: Vec, + /// `(relative_path, bytes, executable)` for safe non-symlink files to write on disk; + /// `in_root_symlinks` holds `(relative_path, relative_target)` for safe internal symlinks. + regular_files: Vec<(PathBuf, Vec, bool)>, + in_root_symlinks: Vec<(PathBuf, PathBuf)>, +} + +fn fetch_and_scan_bundle( + fetcher: &dyn SkillSourceFetcher, + target: RepoRef<'_>, + subpath: &str, + cancel: &CancellationToken, +) -> IdeResult { + let RepoRef { owner, repo, git_ref } = target; + validate_repo_coord(owner, "owner")?; + validate_repo_coord(repo, "repository")?; + validate_git_ref(git_ref)?; + let normalized_subpath = normalize_subpath(subpath)?.unwrap_or_default(); + + let tree = fetcher.git_tree(target, cancel)?; + let prefix = if normalized_subpath.is_empty() { String::new() } else { format!("{normalized_subpath}/") }; + + let subtree_entries: Vec<&GitTreeEntry> = tree + .tree + .iter() + .filter(|e| { + e.kind == "blob" && if prefix.is_empty() { !e.path.is_empty() } else { e.path.starts_with(&prefix) } + }) + .collect(); + + if subtree_entries.is_empty() { + return Err(IdeError::not_found(format!( + "Skill path {:?} was not found in {owner}/{repo}@{git_ref}", + normalized_subpath + ))); + } + if subtree_entries.len() > MAX_SKILL_FILES { + return Err(IdeError::invalid(format!( + "Skill exceeds maximum of {MAX_SKILL_FILES} files ({} found)", + subtree_entries.len() + ))); + } + + let declared_total: u64 = subtree_entries.iter().map(|e| e.size.unwrap_or(0)).sum(); + if declared_total > MAX_SKILL_SUBTREE_BYTES { + return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20))); + } + + let mut files = Vec::with_capacity(subtree_entries.len()); + let mut scan_warnings = Vec::new(); + let mut regular_files = Vec::new(); + let mut in_root_symlinks = Vec::new(); + let mut skill_markdown: Option = None; + let mut actual_total = 0u64; + + for entry in subtree_entries { + let rel_str = if prefix.is_empty() { + entry.path.as_str() + } else { + entry.path.strip_prefix(&prefix).unwrap_or(entry.path.as_str()) + }; + let rel_path = validate_rel_skill_file(rel_str)?; + let is_symlink = entry.mode == "120000"; + let is_exec_mode = entry.mode == "100755"; + + let bytes = fetcher.read_blob( + target, + &entry.path, + &entry.sha, + MAX_SINGLE_BLOB_BYTES.min(MAX_SKILL_SUBTREE_BYTES - actual_total), + cancel, + )?; + actual_total = actual_total.saturating_add(bytes.len() as u64); + if actual_total > MAX_SKILL_SUBTREE_BYTES { + return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20))); + } + + if is_symlink { + let target_raw = String::from_utf8_lossy(&bytes).trim().to_owned(); + match resolve_in_root_symlink(&rel_path, &target_raw) { + Some(safe_target) => { + in_root_symlinks.push((rel_path.clone(), safe_target)); + } + None => { + scan_warnings.push(SkillScanWarning { + kind: SkillScanWarningKind::OutOfRootSymlink, + file: rel_str.to_owned(), + message: format!("Symlink target {target_raw:?} leaves the skill folder (omitted on install)"), + }); + } + } + files.push(RemoteSkillFile { + path: rel_str.to_owned(), + size: bytes.len() as u64, + executable: false, + symlink: true, + }); + continue; + } + + let has_shebang = bytes.starts_with(b"#!"); + let is_script_path = is_executable_or_script_path(&rel_path); + if is_exec_mode || has_shebang || is_script_path { + let reason = if is_exec_mode { + "executable file mode (100755)" + } else if has_shebang { + "script with `#!` interpreter header" + } else { + "bundled script or native binary" + }; + scan_warnings.push(SkillScanWarning { + kind: SkillScanWarningKind::ExecutableScript, + file: rel_str.to_owned(), + message: format!("Contains {reason}"), + }); + } + + if let Ok(text) = std::str::from_utf8(&bytes) { + scan_hidden_unicode(rel_str, text, &mut scan_warnings); + if rel_str == "SKILL.md" { + skill_markdown = Some(text.to_owned()); + } + } else if rel_str == "SKILL.md" { + return Err(IdeError::invalid("SKILL.md is not valid UTF-8 text")); + } + + files.push(RemoteSkillFile { + path: rel_str.to_owned(), + size: bytes.len() as u64, + executable: is_exec_mode || has_shebang, + symlink: false, + }); + regular_files.push((rel_path, bytes, is_exec_mode)); + } + + files.sort_by(|a, b| a.path.cmp(&b.path)); + regular_files.sort_by(|a, b| a.0.cmp(&b.0)); + + let Some(skill_markdown) = skill_markdown else { + return Err(IdeError::invalid("Selected folder does not contain a regular SKILL.md file")); + }; + + let folder_hint = normalized_subpath + .rsplit('/') + .next() + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .unwrap_or_else(|| sanitize_repo_as_skill_name(repo)); + + let parsed_meta = parse_skill_markdown_metadata(&folder_hint, &skill_markdown)?; + for tool in &parsed_meta.shell_tools { + scan_warnings.push(SkillScanWarning { + kind: SkillScanWarningKind::AllowedToolsShell, + file: "SKILL.md".into(), + message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"), + }); + } + + Ok(PreparedSkillBundle { + tree_sha: tree.sha, + skill_name: parsed_meta.name, + description: parsed_meta.description, + skill_markdown, + files, + scan_warnings, + regular_files, + in_root_symlinks, + }) +} + +struct ParsedSkillMetadata { + name: String, + description: String, + shell_tools: Vec, +} + +fn parse_skill_markdown_metadata(folder_hint: &str, markdown: &str) -> IdeResult { + let mut name: Option = None; + let mut description: Option = None; + let mut allowed_tools_raw: Vec = Vec::new(); + + let normalized = markdown.strip_prefix('\u{feff}').unwrap_or(markdown); + if let Some(after_open) = normalized.strip_prefix("---\n").or_else(|| normalized.strip_prefix("---\r\n")) { + let mut current_list_key: Option = None; + for raw_line in after_open.lines() { + let trimmed_end = raw_line.trim_end_matches('\r'); + if matches!(trimmed_end.trim(), "---" | "...") { + break; + } + let trimmed = trimmed_end.trim(); + if trimmed.is_empty() || trimmed.starts_with('#') { + continue; + } + if (trimmed_end.starts_with(' ') || trimmed_end.starts_with('\t')) + && let Some(item) = trimmed.strip_prefix('-') + { + if matches!(current_list_key.as_deref(), Some("allowed-tools" | "allowed_tools")) { + let val = unquote(item.trim()); + if !val.is_empty() { + allowed_tools_raw.push(val.to_owned()); + } + } + continue; + } + current_list_key = None; + if let Some((k, v)) = trimmed.split_once(':') { + let key = k.trim().to_ascii_lowercase(); + let val = unquote(v.trim()); + match key.as_str() { + "name" if !val.is_empty() => name = Some(val.to_owned()), + "description" if !val.is_empty() && !matches!(val, ">" | "|" | ">-" | "|-") => { + description = Some(val.to_owned()); + } + "allowed-tools" | "allowed_tools" => { + if val.is_empty() { + current_list_key = Some(key); + } else { + let inner = val.strip_prefix('[').and_then(|s| s.strip_suffix(']')).unwrap_or(val); + for token in split_allowed_tools(inner) { + allowed_tools_raw.push(token); + } + } + } + _ => {} + } + } + } + } + + let skill_name = name.unwrap_or_else(|| folder_hint.to_owned()); + if !valid_skill_name(&skill_name) { + return Err(IdeError::invalid(format!( + "Skill name {skill_name:?} must be 1-64 lowercase letters, digits, or hyphens" + ))); + } + let description = description.unwrap_or_default(); + let shell_tools = allowed_tools_raw.into_iter().filter(|t| is_shell_tool_entry(t)).collect(); + Ok(ParsedSkillMetadata { name: skill_name, description, shell_tools }) +} + +fn split_allowed_tools(raw: &str) -> Vec { + let mut out = Vec::new(); + let mut cur = String::new(); + let mut depth = 0usize; + for ch in raw.chars() { + match ch { + '(' => { + depth += 1; + cur.push(ch); + } + ')' => { + depth = depth.saturating_sub(1); + cur.push(ch); + } + ',' | ' ' if depth == 0 => { + let tok = unquote(cur.trim()); + if !tok.is_empty() { + out.push(tok.to_owned()); + } + cur.clear(); + } + _ => cur.push(ch), + } + } + let tok = unquote(cur.trim()); + if !tok.is_empty() { + out.push(tok.to_owned()); + } + out +} + +fn is_shell_tool_entry(entry: &str) -> bool { + let head = entry.split(['(', ':', '/']).next().unwrap_or(entry).trim().to_ascii_lowercase(); + matches!( + head.as_str(), + "*" | "bash" + | "sh" + | "zsh" + | "shell" + | "terminal" + | "cmd" + | "powershell" + | "pwsh" + | "run_command" + | "exec" + | "execute" + ) +} + +fn unquote(value: &str) -> &str { + for q in ['"', '\''] { + if let Some(inner) = value.strip_prefix(q).and_then(|v| v.strip_suffix(q)) { + return inner; + } + } + value +} + +fn validate_rel_skill_file(rel: &str) -> IdeResult { + if rel.is_empty() || rel.contains('\\') { + return Err(IdeError::invalid(format!("Invalid relative file path {rel:?}"))); + } + let path = Path::new(rel); + if !path.components().all(|c| matches!(c, Component::Normal(_))) { + return Err(IdeError::invalid(format!("Path {rel:?} escapes the skill folder"))); + } + Ok(path.to_path_buf()) +} + +/// Returns `Some(target_path)` only when `target_raw` is a relative link that stays strictly inside the skill root. +fn resolve_in_root_symlink(link_rel: &Path, target_raw: &str) -> Option { + if target_raw.is_empty() + || target_raw.starts_with('/') + || target_raw.starts_with('~') + || target_raw.contains('\\') + || target_raw.as_bytes().get(1) == Some(&b':') + { + return None; + } + let mut stack: Vec<&std::ffi::OsStr> = link_rel + .parent() + .map(|p| { + p.components() + .filter_map(|c| match c { + Component::Normal(s) => Some(s), + _ => None, + }) + .collect() + }) + .unwrap_or_default(); + for seg in target_raw.split('/') { + match seg { + "" | "." => {} + ".." => { + stack.pop()?; + } + _ => stack.push(std::ffi::OsStr::new(seg)), + } + } + if stack.is_empty() { + return None; + } + Some(PathBuf::from(target_raw)) +} + +fn is_executable_or_script_path(rel: &Path) -> bool { + if rel.components().next().and_then(|c| c.as_os_str().to_str()) == Some("scripts") { + return true; + } + rel.extension() + .and_then(|e| e.to_str()) + .is_some_and(|ext| SCRIPT_EXTENSIONS.iter().any(|s| ext.eq_ignore_ascii_case(s))) +} + +fn is_hidden_or_bidi_unicode(ch: char, at_file_start: bool) -> Option<&'static str> { + match ch { + '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{061C}' | '\u{200E}' | '\u{200F}' => { + Some("bidirectional control character") + } + '\u{200B}'..='\u{200D}' | '\u{2060}' => Some("zero-width character"), + '\u{FEFF}' if !at_file_start => Some("zero-width no-break space"), + '\u{E0000}'..='\u{E007F}' | '\u{E0100}'..='\u{E01EF}' => Some("invisible Unicode tag/variation character"), + _ => None, + } +} + +fn scan_hidden_unicode(file: &str, text: &str, warnings: &mut Vec) { + for (line_idx, line) in text.lines().enumerate() { + for (char_idx, ch) in line.chars().enumerate() { + let at_start = line_idx == 0 && char_idx == 0; + if let Some(label) = is_hidden_or_bidi_unicode(ch, at_start) { + warnings.push(SkillScanWarning { + kind: SkillScanWarningKind::HiddenUnicode, + file: file.to_owned(), + message: format!("Line {} contains {} (U+{:04X})", line_idx + 1, label, ch as u32), + }); + // Report once per file to keep the warning list readable. + return; + } + } + } +} + +/// Previews a single skill from `target` (`subpath`) and runs the static security scan. +pub fn preview_skill( + fetcher: &dyn SkillSourceFetcher, + target: RepoRef<'_>, + subpath: &str, + user_home: Option<&Path>, + workspace_root: Option<&Path>, + cancel: &CancellationToken, +) -> IdeResult { + let RepoRef { owner, repo, git_ref } = target; + let bundle = fetch_and_scan_bundle(fetcher, target, subpath, cancel)?; + let already_installed_user = user_home.is_some_and(|h| h.join(".agents/skills").join(&bundle.skill_name).exists()); + let already_installed_workspace = + workspace_root.is_some_and(|w| w.join(".agents/skills").join(&bundle.skill_name).exists()); + Ok(RemoteSkillPreview { + owner: owner.to_owned(), + repo: repo.to_owned(), + git_ref: git_ref.to_owned(), + tree_sha: bundle.tree_sha, + subpath: normalize_subpath(subpath)?.unwrap_or_default(), + skill_name: bundle.skill_name, + description: bundle.description, + skill_markdown: bundle.skill_markdown, + files: bundle.files, + scan_warnings: bundle.scan_warnings, + already_installed_user, + already_installed_workspace, + }) +} + +/// Downloads only the skill's subtree, enforces static scan confirmation, and installs atomically +/// into `~/.agents/skills/` (`McpScope::User`) or `/.agents/skills/` (`McpScope::Workspace`). +pub fn install_skill( + fetcher: &dyn SkillSourceFetcher, + req: &InstallRemoteSkillRequest, + user_home: Option<&Path>, + workspace_root: Option<&Path>, + cancel: &CancellationToken, +) -> IdeResult { + let target_root = match req.scope { + McpScope::User => { + let home = user_home.ok_or_else(|| IdeError::unavailable("Cannot locate user home directory"))?; + home.join(".agents").join("skills") + } + McpScope::Workspace => { + let ws = workspace_root + .ok_or_else(|| IdeError::invalid("Open a trusted project to install workspace skills"))?; + ws.join(".agents").join("skills") + } + }; + + let bundle = fetch_and_scan_bundle( + fetcher, + RepoRef { owner: &req.owner, repo: &req.repo, git_ref: &req.git_ref }, + &req.subpath, + cancel, + )?; + if !bundle.scan_warnings.is_empty() && !req.confirm_warnings { + return Err(IdeError::invalid( + "Review and confirm the static security scan warnings before installing this skill", + )); + } + + std::fs::create_dir_all(&target_root)?; + let final_dir = target_root.join(&bundle.skill_name); + if final_dir.exists() && !req.overwrite { + return Err(IdeError::new( + ErrorKind::AlreadyExists, + format!("Skill `{}` is already installed in {}", bundle.skill_name, target_root.display()), + )); + } + + let nonce = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default(); + let staging = target_root.join(format!(".staging-{}-{nonce}-{}", bundle.skill_name, std::process::id())); + let write_res = (|| -> IdeResult<()> { + std::fs::create_dir_all(&staging)?; + for (rel_path, bytes, is_exec) in &bundle.regular_files { + let dest = staging.join(rel_path); + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(&dest, bytes)?; + #[cfg(unix)] + if *is_exec { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o755)); + } + #[cfg(not(unix))] + let _ = is_exec; + } + for (rel_link, target) in &bundle.in_root_symlinks { + let dest = staging.join(rel_link); + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent)?; + } + #[cfg(unix)] + std::os::unix::fs::symlink(target, &dest)?; + #[cfg(not(unix))] + { + let resolved = dest.parent().unwrap_or(&staging).join(target); + if resolved.is_file() { + std::fs::copy(&resolved, &dest)?; + } + } + } + let backup = if final_dir.exists() { + let bak = target_root.join(format!(".old-{}-{nonce}", bundle.skill_name)); + std::fs::rename(&final_dir, &bak)?; + Some(bak) + } else { + None + }; + if let Err(err) = std::fs::rename(&staging, &final_dir) { + if let Some(bak) = backup { + let _ = std::fs::rename(&bak, &final_dir); + } + return Err(err.into()); + } + if let Some(bak) = backup { + let _ = std::fs::remove_dir_all(bak); + } + Ok(()) + })(); + + if write_res.is_err() { + let _ = std::fs::remove_dir_all(&staging); + } + write_res?; + Ok(final_dir) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + + struct FakeFetcher { + default_branch: String, + trees: BTreeMap, + blobs: BTreeMap>, + } + + impl FakeFetcher { + fn new() -> Self { + Self { default_branch: "main".into(), trees: BTreeMap::new(), blobs: BTreeMap::new() } + } + + fn add_tree(&mut self, git_ref: &str, entries: Vec<(&str, &str, &[u8])>) { + let mut tree_entries = Vec::new(); + for (idx, (path, mode, content)) in entries.into_iter().enumerate() { + let sha = format!("{idx:040x}"); + self.blobs.insert(sha.clone(), content.to_vec()); + tree_entries.push(GitTreeEntry { + path: path.to_owned(), + mode: mode.to_owned(), + kind: "blob".into(), + sha, + size: Some(content.len() as u64), + }); + } + self.trees.insert( + git_ref.to_owned(), + GitTree { sha: "deadbeef".repeat(5), truncated: false, tree: tree_entries }, + ); + } + } + + impl SkillSourceFetcher for FakeFetcher { + fn default_branch(&self, _owner: &str, _repo: &str, _cancel: &CancellationToken) -> IdeResult { + Ok(self.default_branch.clone()) + } + + fn git_tree(&self, target: RepoRef<'_>, _cancel: &CancellationToken) -> IdeResult { + self.trees + .get(target.git_ref) + .cloned() + .ok_or_else(|| IdeError::not_found(format!("unknown ref {}", target.git_ref))) + } + + fn read_blob( + &self, + _target: RepoRef<'_>, + repo_path: &str, + blob_sha: &str, + max_bytes: u64, + _cancel: &CancellationToken, + ) -> IdeResult> { + let bytes = self.blobs.get(blob_sha).cloned().ok_or_else(|| IdeError::not_found(repo_path))?; + if bytes.len() as u64 > max_bytes { + return Err(IdeError::invalid("blob too large")); + } + Ok(bytes) + } + } + + #[test] + fn parses_npx_skills_add_inputs_and_rejects_traversal() { + let plain = parse_source("vercel-labs/agent-skills").unwrap(); + assert_eq!((plain.owner.as_str(), plain.repo.as_str(), plain.subpath), ("vercel-labs", "agent-skills", None)); + + let at_skill = parse_source("vercel-labs/agent-skills@find-skills").unwrap(); + assert_eq!(at_skill.ref_or_skill.as_deref(), Some("find-skills")); + + let subpath_ref = parse_source("acme/skills/skills/tdd@v1.2.0").unwrap(); + assert_eq!(subpath_ref.subpath.as_deref(), Some("skills/tdd")); + assert_eq!(subpath_ref.explicit_ref.as_deref(), Some("v1.2.0")); + + let gh_url = parse_source("https://github.com/acme/skills/tree/release/skills/tdd/SKILL.md").unwrap(); + assert_eq!(gh_url.explicit_ref.as_deref(), Some("release")); + assert_eq!(gh_url.subpath.as_deref(), Some("skills/tdd")); + + let skills_sh = parse_source("https://skills.sh/vercel-labs/skills/find-skills").unwrap(); + assert_eq!((skills_sh.owner.as_str(), skills_sh.repo.as_str()), ("vercel-labs", "skills")); + assert_eq!(skills_sh.skill_filter.as_deref(), Some("find-skills")); + + assert!(parse_source("acme/skills/../escape").is_err()); + assert!(parse_source("https://evil.example.com/acme/skills").is_err()); + } + + #[test] + fn browses_filters_scans_and_installs_only_selected_subtree() { + let mut fetcher = FakeFetcher::new(); + fetcher.add_tree( + "main", + vec![ + ("README.md", "100644", b"# Repo root README (must not be downloaded)\n"), + ( + "skills/clean-skill/SKILL.md", + "100644", + b"---\nname: clean-skill\ndescription: Clean markdown-only skill\n---\nFollow clean steps.\n", + ), + ("skills/clean-skill/references/guide.md", "100644", b"# Guide\n"), + ( + "skills/risky-skill/SKILL.md", + "100644", + "---\nname: risky-skill\ndescription: Runs deploy script\nallowed-tools:\n - Bash(git:*)\n - Read\n---\nHidden \u{202E}bidi text.\n".as_bytes(), + ), + ("skills/risky-skill/scripts/deploy.sh", "100755", b"#!/bin/sh\necho hi\n"), + ("skills/risky-skill/escape-link", "120000", b"../../README.md"), + ], + ); + let cancel = CancellationToken::new(); + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + let ws = tmp.path().join("ws"); + + // Bare `owner/repo` lists both skills; `owner/repo@clean-skill` falls back from ref lookup to skill filter! + let all = browse_skills(&fetcher, "acme/skills", &cancel).unwrap(); + assert_eq!(all.skills.len(), 2); + let filtered = browse_skills(&fetcher, "acme/skills@clean-skill", &cancel).unwrap(); + assert_eq!(filtered.skills.len(), 1); + assert_eq!(filtered.skills[0].folder_name, "clean-skill"); + + // Clean skill has 0 warnings and installs into ~/.agents/skills/clean-skill without touching repo root files. + let clean_preview = preview_skill( + &fetcher, + RepoRef { owner: "acme", repo: "skills", git_ref: "main" }, + "skills/clean-skill", + Some(&home), + Some(&ws), + &cancel, + ) + .unwrap(); + assert!(clean_preview.scan_warnings.is_empty(), "{:?}", clean_preview.scan_warnings); + assert_eq!(clean_preview.files.len(), 2); + + let installed_dir = install_skill( + &fetcher, + &InstallRemoteSkillRequest { + owner: "acme".into(), + repo: "skills".into(), + git_ref: "main".into(), + subpath: "skills/clean-skill".into(), + scope: McpScope::User, + confirm_warnings: false, + overwrite: false, + }, + Some(&home), + Some(&ws), + &cancel, + ) + .unwrap(); + assert_eq!(installed_dir, home.join(".agents/skills/clean-skill")); + assert!(installed_dir.join("SKILL.md").is_file()); + assert!(installed_dir.join("references/guide.md").is_file()); + assert!(!home.join(".agents/skills/README.md").exists()); + + // Re-installing without `overwrite: true` is refused. + let dup_err = install_skill( + &fetcher, + &InstallRemoteSkillRequest { + owner: "acme".into(), + repo: "skills".into(), + git_ref: "main".into(), + subpath: "skills/clean-skill".into(), + scope: McpScope::User, + confirm_warnings: false, + overwrite: false, + }, + Some(&home), + Some(&ws), + &cancel, + ) + .unwrap_err(); + assert_eq!(dup_err.kind, ErrorKind::AlreadyExists); + + // Risky skill triggers all 4 static security scan categories and requires `confirm_warnings: true`. + let risky_preview = preview_skill( + &fetcher, + RepoRef { owner: "acme", repo: "skills", git_ref: "main" }, + "skills/risky-skill", + Some(&home), + Some(&ws), + &cancel, + ) + .unwrap(); + let kinds: Vec = risky_preview.scan_warnings.iter().map(|w| w.kind).collect(); + assert!(kinds.contains(&SkillScanWarningKind::HiddenUnicode), "{kinds:?}"); + assert!(kinds.contains(&SkillScanWarningKind::OutOfRootSymlink), "{kinds:?}"); + assert!(kinds.contains(&SkillScanWarningKind::ExecutableScript), "{kinds:?}"); + assert!(kinds.contains(&SkillScanWarningKind::AllowedToolsShell), "{kinds:?}"); + + let unconfirmed = install_skill( + &fetcher, + &InstallRemoteSkillRequest { + owner: "acme".into(), + repo: "skills".into(), + git_ref: "main".into(), + subpath: "skills/risky-skill".into(), + scope: McpScope::Workspace, + confirm_warnings: false, + overwrite: false, + }, + Some(&home), + Some(&ws), + &cancel, + ) + .unwrap_err(); + assert!(unconfirmed.message.contains("confirm"), "{unconfirmed:?}"); + + let ws_installed = install_skill( + &fetcher, + &InstallRemoteSkillRequest { + owner: "acme".into(), + repo: "skills".into(), + git_ref: "main".into(), + subpath: "skills/risky-skill".into(), + scope: McpScope::Workspace, + confirm_warnings: true, + overwrite: false, + }, + Some(&home), + Some(&ws), + &cancel, + ) + .unwrap(); + assert_eq!(ws_installed, ws.join(".agents/skills/risky-skill")); + assert!(ws_installed.join("SKILL.md").is_file()); + assert!(ws_installed.join("scripts/deploy.sh").is_file()); + assert!(!ws_installed.join("escape-link").exists(), "out-of-root symlink omitted on disk"); + } + + #[test] + #[ignore = "hits live GitHub API"] + fn live_github_browse_preview_and_install_smoke() { + let fetcher = GitHubHttpFetcher::new(&ide_core::tool_path::search_path()).unwrap(); + let cancel = CancellationToken::new(); + let browsed = browse_skills(&fetcher, "l0ng-ai/openidea@verify", &cancel).unwrap(); + assert_eq!(browsed.skills.len(), 1); + assert_eq!(browsed.skills[0].folder_name, "verify"); + + let tmp = tempfile::tempdir().unwrap(); + let preview = preview_skill( + &fetcher, + RepoRef { owner: &browsed.owner, repo: &browsed.repo, git_ref: &browsed.git_ref }, + &browsed.skills[0].subpath, + Some(tmp.path()), + None, + &cancel, + ) + .unwrap(); + assert_eq!(preview.skill_name, "verify"); + assert!(preview.files.iter().any(|f| f.path == "SKILL.md")); + + let dest = install_skill( + &fetcher, + &InstallRemoteSkillRequest { + owner: browsed.owner, + repo: browsed.repo, + git_ref: browsed.git_ref, + subpath: browsed.skills[0].subpath.clone(), + scope: McpScope::User, + confirm_warnings: true, + overwrite: false, + }, + Some(tmp.path()), + None, + &cancel, + ) + .unwrap(); + assert!(dest.join("SKILL.md").is_file()); + } +} diff --git a/crates/ide-agent/src/skills.rs b/crates/ide-agent/src/skills.rs index dff3d2b288..a1697fef91 100644 --- a/crates/ide-agent/src/skills.rs +++ b/crates/ide-agent/src/skills.rs @@ -125,10 +125,9 @@ fn file_name(path: &Path) -> Option { path.file_name()?.to_str().map(str::to_owned) } -/// The `key: value` lines between the leading `---` fences (folded `>` / `|` values joined). struct Frontmatter { fields: Vec<(String, String)>, - /// Where the body starts. + lists: Vec<(String, Vec)>, body: usize, } @@ -138,22 +137,42 @@ impl Frontmatter { let mut lines = text.split_inclusive('\n'); let mut offset = 0; let mut fields: Vec<(String, String)> = Vec::new(); + let mut lists: Vec<(String, Vec)> = Vec::new(); match lines.next() { Some(first) if first.trim_end() == "---" => offset += first.len(), - _ => return Self { fields, body: 0 }, + _ => return Self { fields, lists, body: 0 }, } for line in lines { offset += line.len(); let line = line.trim_end(); if line == "---" { - return Self { fields, body: offset }; + return Self { fields, lists, body: offset }; } - if line.starts_with([' ', '\t']) { + let unindented_list_item = (line == "-" || line.starts_with("- ") || line.starts_with("-\t")) + && fields.last().is_some_and(|(_, v)| v.is_empty()); + if line.starts_with([' ', '\t']) || unindented_list_item { + let trimmed = line.trim(); + if let Some(rest) = trimmed.strip_prefix('-') + && (rest.is_empty() || rest.starts_with([' ', '\t'])) + && let Some((key, _)) = fields.last() + { + let item = unquote(rest.trim()); + if !item.is_empty() { + if let Some((_, existing)) = lists.iter_mut().find(|(k, _)| k == key) { + existing.push(item.to_owned()); + } else { + lists.push((key.clone(), vec![item.to_owned()])); + } + } + if unindented_list_item { + continue; + } + } if let Some((_, value)) = fields.last_mut() { if !value.is_empty() { value.push(' '); } - value.push_str(line.trim()); + value.push_str(trimmed); } continue; } @@ -164,11 +183,15 @@ impl Frontmatter { } } // No closing fence: not frontmatter. - Self { fields: Vec::new(), body: 0 } + Self { fields: Vec::new(), lists: Vec::new(), body: 0 } } fn get(&self, key: &str) -> Option<&str> { - self.fields.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str()) + self.fields.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v.as_str()) + } + + fn list(&self, key: &str) -> Option<&[String]> { + self.lists.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v.as_slice()) } /// `description`, else the body's first line. @@ -247,6 +270,17 @@ pub fn discover_skills(workspace: &Path, home: Option<&Path>) -> Vec /// folders) and `home`, in source precedence order, symlinked duplicates collapsed by /// canonical path while recording secondary sources in [`AgentSkill::also_in`]. pub fn discover_skills_in(workspaces: &[PathBuf], home: Option<&Path>) -> Vec { + discover_skills_with_plugins(workspaces, home, &[]) +} + +/// [`discover_skills_in`] plus the `` skill folders contributed by enabled OpenIDEA +/// plugins (`[[contributes.skills]]`). Workspace and user skills take precedence on a name +/// clash; a plugin skill is never silently renamed. +pub fn discover_skills_with_plugins( + workspaces: &[PathBuf], + home: Option<&Path>, + plugin_skill_dirs: &[PathBuf], +) -> Vec { let mut out: Vec = Vec::new(); let mut seen_paths: HashSet = HashSet::new(); let mut seen_names: HashSet = HashSet::new(); @@ -273,29 +307,59 @@ pub fn discover_skills_in(workspaces: &[PathBuf], home: Option<&Path>) -> Vec/SKILL.md` against the hub's folder-name and +/// frontmatter rules (`name` 1–64 `[a-z0-9-]`, matching `folder`, non-empty `description` ≤ 1024 chars). +pub fn validate_plugin_skill(dir: &Path, folder: &str, text: &str) -> Result { + if !valid_name(folder) { + return Err(format!("skill folder `{folder}` must be 1-64 lowercase letters, digits or hyphens")); + } + let skill = parse_skill_file(dir, folder, text, AgentSkillSource::Plugin); + if !skill.valid { + return Err(skill.warnings.join("; ")); + } + Ok(skill) +} + const SKIP_MONOREPO_DIRS: &[&str] = &["node_modules", "target", "dist", "build", "out", "vendor", "coverage", ".git", ".openidea", ".idea"]; @@ -464,6 +528,8 @@ fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSour let hint = meta.get("argument-hint").map(|h| strip_ansi(h).trim().to_owned()).filter(|h| !h.is_empty()); let user_invocable = !meta.get("user-invocable").is_some_and(|v| v.eq_ignore_ascii_case("false")); let disable_model_invocation = meta.get("disable-model-invocation").is_some_and(|v| v.eq_ignore_ascii_case("true")); + let context_fork = meta.get("context").is_some_and(|v| strip_ansi(v).trim().eq_ignore_ascii_case("fork")); + let paths = parse_skill_paths(&meta); AgentSkill { name, description: truncate(&description), @@ -473,11 +539,35 @@ fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSour also_in: Vec::new(), user_invocable, disable_model_invocation, + context_fork, + paths, valid: warnings.is_empty(), warnings, } } +fn parse_skill_paths(meta: &Frontmatter) -> Vec { + for key in ["paths", "globs"] { + if let Some(items) = meta.list(key) { + let cleaned: Vec = + items.iter().map(|s| strip_ansi(s).trim().to_owned()).filter(|s| !s.is_empty()).collect(); + if !cleaned.is_empty() { + return cleaned; + } + } + if let Some(raw) = meta.get(key) { + let trimmed = strip_ansi(raw); + let inner = trimmed.trim().strip_prefix('[').and_then(|s| s.strip_suffix(']')).unwrap_or(trimmed.trim()); + let cleaned: Vec = + inner.split(',').map(|p| unquote(p.trim()).trim().to_owned()).filter(|p| !p.is_empty()).collect(); + if !cleaned.is_empty() { + return cleaned; + } + } + } + Vec::new() +} + /// A skill's mode, as one policy layer of the settings has it. type Policies = BTreeMap; @@ -662,11 +752,12 @@ pub fn stage( /// Codex `[[skills.config]]` matches `path` against the canonical `SKILL.md` document path. fn codex_skill_md_path(skill_dir: &Path) -> String { let md = skill_dir.join("SKILL.md"); - dunce::canonicalize(&md) + let md = dunce::canonicalize(&md) .or_else(|_| dunce::canonicalize(skill_dir).map(|dir| dir.join("SKILL.md"))) - .unwrap_or(md) - .to_string_lossy() - .into_owned() + .unwrap_or(md); + // Skill roots are joined as `.agents/skills`; rebuilding from components gives Windows + // one separator when the path could not be canonicalized. + md.components().collect::().to_string_lossy().into_owned() } fn direct_link_matches(root: &Path, name: &str, target: &Path) -> bool { @@ -992,6 +1083,8 @@ mod tests { also_in: Vec::new(), user_invocable: true, disable_model_invocation: false, + context_fork: false, + paths: Vec::new(), valid: true, warnings: Vec::new(), } @@ -1330,4 +1423,103 @@ mod tests { ); } } + + #[test] + fn plugin_skills_yield_to_workspace_and_user_and_stage_to_all_clis() { + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap(); + let ws = root.join("ws"); + let home = root.join("home"); + let plugin_pkg = root.join("plugins/acme.tools/1.0.0"); + + write(&ws.join(".agents/skills/clash-ws/SKILL.md"), "---\nname: clash-ws\ndescription: workspace copy\n---\n"); + write(&home.join(".agents/skills/clash-user/SKILL.md"), "---\nname: clash-user\ndescription: user copy\n---\n"); + write(&plugin_pkg.join("skills/clash-ws/SKILL.md"), "---\nname: clash-ws\ndescription: plugin copy\n---\n"); + write(&plugin_pkg.join("skills/clash-user/SKILL.md"), "---\nname: clash-user\ndescription: plugin copy\n---\n"); + write( + &plugin_pkg.join("skills/release-notes/SKILL.md"), + "---\nname: release-notes\ndescription: draft release notes\n---\n", + ); + + let plugin_dirs = vec![ + plugin_pkg.join("skills/clash-ws"), + plugin_pkg.join("skills/clash-user"), + plugin_pkg.join("skills/release-notes"), + ]; + let found = discover_skills_with_plugins(std::slice::from_ref(&ws), Some(&home), &plugin_dirs); + let summary: Vec<(&str, AgentSkillSource, &str)> = + found.iter().map(|s| (s.name.as_str(), s.source, s.description.as_str())).collect(); + assert_eq!( + summary, + [ + ("clash-ws", AgentSkillSource::Workspace, "workspace copy"), + ("clash-user", AgentSkillSource::User, "user copy"), + ("release-notes", AgentSkillSource::Plugin, "draft release notes"), + ], + "workspace and user skills win on name clash without renaming plugin skills" + ); + assert!(!AgentSkillSource::Plugin.discovered()); + + let states = resolve(found.clone(), None, &BTreeMap::new(), &BTreeMap::new(), true); + for provider in ["claude", "copilot", "codex"] { + let farm = farm_dir(&root.join("store"), &format!("plugin-{provider}")); + let _ = stage(&farm, provider, &states, &ws, Some(&home)).unwrap(); + } + assert!( + listed(&farm_dir(&root.join("store"), "plugin-claude").join(".claude/skills")) + .contains(&"release-notes".into()) + ); + assert!( + listed(&farm_dir(&root.join("store"), "plugin-copilot").join("copilot")).contains(&"release-notes".into()) + ); + assert!(listed(&farm_dir(&root.join("store"), "plugin-codex").join("codex")).contains(&"release-notes".into())); + + // Turning a plugin skill off omits it from every CLI's staged farm. + let off_states = resolve( + found, + None, + &BTreeMap::new(), + &BTreeMap::from([("release-notes".to_owned(), policy(AgentSkillMode::Off).unwrap())]), + true, + ); + let farm = farm_dir(&root.join("store"), "plugin-off"); + let _ = stage(&farm, "claude", &off_states, &ws, Some(&home)).unwrap(); + assert!(!farm.join(".claude/skills/release-notes").exists()); + } + + #[test] + fn parses_context_fork_and_paths_frontmatter_and_preserves_file_on_stage() { + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap(); + let ws = root.join("ws"); + let raw_md = "---\n\ + name: verify-ux\n\ + description: Verify UX layouts in an isolated subagent\n\ + context: fork\n\ + paths:\n\ + - \"src/**/*.tsx\"\n\ + - crates/ide-agent/**/*.rs\n\ + ---\n\nRun visual checks.\n"; + write(&ws.join(".openidea/skills/verify-ux/SKILL.md"), raw_md); + write( + &ws.join(".agents/skills/inline-globs/SKILL.md"), + "---\nname: inline-globs\ndescription: Scoped by globs\nglobs: [\"e2e/*.spec.ts\", \"src/ui/*.tsx\"]\n---\n", + ); + + let found = discover_skills(&ws, None); + let verify = found.iter().find(|s| s.name == "verify-ux").unwrap(); + assert!(verify.context_fork); + assert_eq!(verify.paths, ["src/**/*.tsx", "crates/ide-agent/**/*.rs"]); + + let inline = found.iter().find(|s| s.name == "inline-globs").unwrap(); + assert!(!inline.context_fork); + assert_eq!(inline.paths, ["e2e/*.spec.ts", "src/ui/*.tsx"]); + + // Staging passes `SKILL.md` through untouched so native CLIs execute `context: fork` / `paths`. + let states = resolve(found, None, &BTreeMap::new(), &BTreeMap::new(), true); + let farm = farm_dir(&root.join("store"), "fork-passthrough"); + let _ = stage(&farm, "copilot", &states, &ws, None).unwrap(); + let staged_md = std::fs::read_to_string(farm.join("copilot/verify-ux/SKILL.md")).unwrap(); + assert_eq!(staged_md, raw_md); + } } diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index 84b4ee8272..c4ddb3c4d3 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -4459,9 +4459,8 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl let root = root.to_path_buf(); move || SkillsPolicy { user: BTreeMap::from([("tdd".into(), AgentSkillPolicy { mode: AgentSkillMode::Off })]), - workspace: BTreeMap::new(), - workspace_trusted: true, workspace_roots: vec![root.clone()], + ..SkillsPolicy::default() } })); diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index cf773d8834..7b376babe0 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -1206,6 +1206,7 @@ pub struct LanguagesSettings { pub typescript: TypeScriptSettings, pub prettier: ExternalFormatterSettings, pub oxfmt: ExternalFormatterSettings, + pub biome: ExternalFormatterSettings, pub ruff: ExternalFormatterSettings, pub java: JavaSettings, pub ruby: RubySettings, @@ -1226,6 +1227,10 @@ impl Default for LanguagesSettings { typescript: TypeScriptSettings::default(), prettier: ExternalFormatterSettings::default(), oxfmt: ExternalFormatterSettings::default(), + biome: ExternalFormatterSettings { + languages: BIOME_LANGUAGES.iter().map(|&l| l.into()).collect(), + ..ExternalFormatterSettings::default() + }, ruff: ExternalFormatterSettings { languages: vec!["python".into()], ..ExternalFormatterSettings::default() @@ -1297,6 +1302,7 @@ impl LanguagesSettings { match tool { ExternalFormatter::Prettier => &self.prettier, ExternalFormatter::Oxfmt => &self.oxfmt, + ExternalFormatter::Biome => &self.biome, ExternalFormatter::Ruff => &self.ruff, } } @@ -1308,6 +1314,7 @@ impl LanguagesSettings { pub enum ExternalFormatter { Prettier, Oxfmt, + Biome, Ruff, } @@ -1317,16 +1324,21 @@ impl ExternalFormatter { match self { Self::Prettier => "prettier", Self::Oxfmt => "oxfmt", + Self::Biome => "biome", Self::Ruff => "ruff", } } } -/// An external formatter (Prettier, oxfmt, Ruff) and the languages it formats. +/// The languages Biome formats (of those Prettier formats). +pub const BIOME_LANGUAGES: [&str; 8] = + ["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"]; + +/// An external formatter (Prettier, oxfmt, Biome, Ruff) and the languages it formats. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(default, rename_all = "camelCase")] pub struct ExternalFormatterSettings { - /// Empty path: project node_modules (Prettier/oxfmt), managed installation, then PATH. + /// Empty path: project node_modules (Prettier/oxfmt/Biome), managed installation, then PATH. pub path: String, /// Ruff only: directory containing its configuration, or a configuration file. pub configuration_directory: String, diff --git a/crates/ide-extension/src/point.rs b/crates/ide-extension/src/point.rs index 7a74ac0d10..d395783b4d 100644 --- a/crates/ide-extension/src/point.rs +++ b/crates/ide-extension/src/point.rs @@ -122,13 +122,34 @@ pub struct Prepared { pub key: Option, /// User-facing one-liner for the plugin details page ("Insert Date"). pub label: String, + /// When set, this entry is skipped with a plugin load warning instead of failing the plugin. + pub warning: Option, /// Makes it take effect. Must not fail for reasons `prepare` could have checked. pub commit: Commit, } impl Prepared { pub fn new(label: impl Into, commit: impl FnOnce() -> Result + Send + 'static) -> Self { - Self { capabilities: Vec::new(), files: Vec::new(), key: None, label: label.into(), commit: Box::new(commit) } + Self { + capabilities: Vec::new(), + files: Vec::new(), + key: None, + label: label.into(), + warning: None, + commit: Box::new(commit), + } + } + + /// Skips an invalid declaration with a load warning while letting the rest of the plugin load. + pub fn skipped(warning: impl Into) -> Self { + Self { + capabilities: Vec::new(), + files: Vec::new(), + key: None, + label: String::new(), + warning: Some(warning.into()), + commit: Box::new(|| Ok(Disposable::noop())), + } } pub fn key(mut self, key: impl Into) -> Self { diff --git a/crates/ide-extension/src/registry.rs b/crates/ide-extension/src/registry.rs index 51dcfdef2d..2fbec11806 100644 --- a/crates/ide-extension/src/registry.rs +++ b/crates/ide-extension/src/registry.rs @@ -270,6 +270,12 @@ impl ExtensionRegistry { let prepared = point .prepare(pkg, decl) .map_err(|e| format!("contributes.{point_id}[{i}]: {}", strip_prefix(&e, point_id)))?; + if let Some(warning) = prepared.warning { + let msg = format!("contributes.{point_id}[{i}]: {}", strip_prefix(&warning, point_id)); + tracing::warn!(plugin = %pkg.id(), "{msg}"); + set.warnings.push(msg); + continue; + } for cap in &prepared.capabilities { if !set.capabilities.contains(cap) { set.capabilities.push(cap.clone()); diff --git a/crates/ide-host/src/formatter.rs b/crates/ide-host/src/formatter.rs index b3afad4161..921b1dd1a5 100644 --- a/crates/ide-host/src/formatter.rs +++ b/crates/ide-host/src/formatter.rs @@ -2,7 +2,7 @@ use crate::Host; use ide_core::event::NotifyLevel; -use ide_core::settings::{ExternalFormatter, LanguagesSettings, Settings}; +use ide_core::settings::{BIOME_LANGUAGES, ExternalFormatter, LanguagesSettings, Settings}; use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, IpcPath, LanguageId, Pos, Range, TextEdit}; use ide_language::{LanguageConfig, PhpAlignment, Syntax}; use ide_lsp::types::FormatOptions; @@ -10,9 +10,28 @@ use ide_tools::{Tools, formatter}; use std::path::{Path, PathBuf}; const OXFMT_CONFIGS: [&str; 4] = [".oxfmtrc.json", ".oxfmtrc.jsonc", "oxfmt.config.ts", "oxfmt.config.mts"]; +/// A Biome configuration, or Biome installed as a project dependency (it then uses its defaults). +const BIOME_MARKERS: [&str; 3] = ["biome.json", "biome.jsonc", "node_modules/@biomejs/biome/package.json"]; + +/// Reformat Code uses Biome below a Biome configuration or installation, unless the nearest +/// configuration turns its formatter off (Biome lints, another tool formats). +fn biome_formats(file: &Path) -> bool { + let config = ["biome.json", "biome.jsonc"] + .iter() + .filter_map(|name| formatter::find_up(file, Path::new(name))) + .max_by_key(|path| path.components().count()); + match config { + Some(config) => !std::fs::read_to_string(&config) + .ok() + .and_then(|text| serde_json::from_str::(&ide_core::jsonc::strip(&text)).ok()) + .is_some_and(|v| v.pointer("/formatter/enabled") == Some(&serde_json::Value::Bool(false))), + None => BIOME_MARKERS.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some()), + } +} fn supports_external_format(language: &LanguageConfig, tool: ExternalFormatter) -> bool { match language.formatter.as_ref().map(|f| f.tool.as_str()) { + Some("prettier") if tool == ExternalFormatter::Biome => BIOME_LANGUAGES.contains(&language.id.as_str()), Some("prettier") => matches!(tool, ExternalFormatter::Prettier | ExternalFormatter::Oxfmt), Some("ruff") => tool == ExternalFormatter::Ruff, _ => false, @@ -20,9 +39,9 @@ fn supports_external_format(language: &LanguageConfig, tool: ExternalFormatter) } /// The external formatter of a file, for a language with an external formatter. -/// `forced` names the tool (Reformat with Prettier, oxfmt, or Ruff). Ruff is -/// the base formatter for Python; oxfmt can replace Prettier for its languages -/// when configured or selected. A tool that cannot format the language is +/// `forced` names the tool (Reformat with Prettier, oxfmt, Biome, or Ruff). Ruff is +/// the base formatter for Python; Biome, then oxfmt, can replace Prettier for their +/// languages when configured or selected. A tool that cannot format the language is /// rejected even when explicitly requested. fn external_tool( forced: Option, @@ -30,7 +49,7 @@ fn external_tool( file: &Path, settings: &LanguagesSettings, ) -> IdeResult> { - use ExternalFormatter::{Oxfmt, Prettier, Ruff}; + use ExternalFormatter::{Biome, Oxfmt, Prettier, Ruff}; let Some(language) = language.filter(|l| l.formatter.is_some()) else { return match forced { Some(tool) => Err(IdeError::invalid(format!( @@ -56,8 +75,11 @@ fn external_tool( if language.formatter.as_ref().is_some_and(|f| f.tool == "ruff") { return Ok(enabled(Ruff).then_some(Ruff)); } - let oxfmt_config = || OXFMT_CONFIGS.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some()); - Ok(if enabled(Oxfmt) && (settings.oxfmt.prefer || oxfmt_config()) { + let found = |names: &[&str]| names.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some()); + let biome = enabled(Biome) && supports_external_format(language, Biome); + Ok(if biome && (settings.biome.prefer || biome_formats(file)) { + Some(Biome) + } else if enabled(Oxfmt) && (settings.oxfmt.prefer || found(&OXFMT_CONFIGS)) { Some(Oxfmt) } else { enabled(Prettier).then_some(Prettier) @@ -439,7 +461,7 @@ async fn provider_edits( #[cfg(test)] mod tests { use super::*; - use ExternalFormatter::{Oxfmt, Prettier, Ruff}; + use ExternalFormatter::{Biome, Oxfmt, Prettier, Ruff}; use ide_core::LanguageId; use ide_language::LanguageRegistry; @@ -482,6 +504,40 @@ mod tests { assert_eq!(prettier.message, "Prettier cannot format Python files"); let oxfmt = tool(Some(Oxfmt), "python", file, &settings).unwrap_err(); assert_eq!(oxfmt.message, "oxfmt cannot format Python files"); + let biome = tool(Some(Biome), "python", file, &settings).unwrap_err(); + assert_eq!(biome.message, "Biome cannot format Python files"); + } + + #[test] + fn biome_config_or_dependency_selects_biome_for_its_languages() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + std::fs::create_dir_all(root.join("web/src")).unwrap(); + let (web, api, readme) = (root.join("web/src/app.ts"), root.join("api/main.ts"), root.join("web/README.md")); + let mut settings = LanguagesSettings::default(); + for marker in BIOME_MARKERS { + let path = root.join("web").join(marker); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, "{}").unwrap(); + assert_eq!(tool(None, "typescript", &web, &settings).unwrap(), Some(Biome), "{marker}"); + assert_eq!(tool(None, "typescript", &api, &settings).unwrap(), Some(Prettier), "{marker}"); + // Biome doesn't format Markdown: Prettier keeps it. + assert_eq!(tool(None, "markdown", &readme, &settings).unwrap(), Some(Prettier), "{marker}"); + std::fs::remove_file(&path).unwrap(); + } + std::fs::write(root.join("web/biome.json"), "{}").unwrap(); + std::fs::write(root.join("web/.oxfmtrc.json"), "{}").unwrap(); + assert_eq!(tool(None, "css", &web, &settings).unwrap(), Some(Biome)); + settings.biome.languages.retain(|l| l != "css"); + assert_eq!(tool(None, "css", &web, &settings).unwrap(), Some(Oxfmt)); + // Biome only lints here: Prettier keeps formatting. + std::fs::remove_file(root.join("web/.oxfmtrc.json")).unwrap(); + std::fs::write(root.join("web/biome.json"), r#"{ "formatter": { "enabled": false } }"#).unwrap(); + assert_eq!(tool(None, "typescript", &web, &settings).unwrap(), Some(Prettier)); + settings.biome.prefer = true; + assert_eq!(tool(None, "typescript", &api, &settings).unwrap(), Some(Biome)); + let markdown = tool(Some(Biome), "markdown", &readme, &settings).unwrap_err(); + assert_eq!(markdown.message, "Biome cannot format Markdown files"); } #[test] diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index 037c7e29fd..527f19a1ef 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -25,7 +25,7 @@ pub mod rpc; pub mod shell_env; pub mod trust; -pub use project::{Project, apply_git_executable, history_retention}; +pub use project::{Project, history_retention}; use ide_core::{CancellationToken, IdeError, IdeResult, RequestId, SharedSink}; use ide_language::{LanguageRegistry, Syntax}; @@ -34,7 +34,7 @@ use ide_terminal::TerminalManager; use ide_workspace::SettingsStore; use parking_lot::{Mutex, RwLock}; use std::collections::HashMap; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::{Arc, OnceLock}; /// Event sink for one window (by label). @@ -209,6 +209,7 @@ impl Host { }; host.apply_proxy(); host.apply_added_jdks(); + host.apply_git_executable(); // Before any project starts jdtls; the deleting itself can take a while. let unused = ide_sdk::jdtls_workspaces::take_unused(&host.local_data_dir, ide_sdk::jdtls_workspaces::UNUSED_FOR); @@ -600,6 +601,14 @@ impl Host { let homes = self.global_settings.effective().languages.java.added_jdks; ide_sdk::java::set_added_jdks(homes.into_iter().map(PathBuf::from)); } + + /// Global Settings › Version Control › Git › Path to Git executable, for git started outside + /// a project's repositories (clone, init, agents, gh, plugins). A project's own value stays + /// with its repositories ([`Project::repos`]). + pub fn apply_git_executable(&self) { + let exe = self.global_settings.read_effective(|s| s.vcs.git.executable.trim().to_owned()); + ide_vcs::set_default_git_executable((!exe.is_empty()).then(|| Path::new(&exe))); + } } #[cfg(test)] diff --git a/crates/ide-host/src/ops/agent.rs b/crates/ide-host/src/ops/agent.rs index d3f5b13500..c345329301 100644 --- a/crates/ide-host/src/ops/agent.rs +++ b/crates/ide-host/src/ops/agent.rs @@ -8,8 +8,9 @@ use ide_agent::{ AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer, AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask, - CustomAgentInput, ExternalSession, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer, - McpServerInput, McpTransport, NewAgentTask, SkillsPolicy, + CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, McpExternalSource, McpImportSelection, + McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, RemoteSkillBrowseResult, + RemoteSkillPreview, SkillsPolicy, }; use ide_command::command; use ide_core::error::ErrorKind; @@ -1040,15 +1041,20 @@ pub fn agent_set_skill_overrides( host.project(window)?.agents.set_skill_overrides(&task, overrides) } -/// Every skill discovered in the project and the user's folders, with the mode a session -/// of this project runs it with (without any session's own overrides). +/// Every skill discovered in the project, the user's folders and enabled plugins, with +/// the mode a session runs it with (without any session's own overrides). #[command(trust = always)] pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult> { - let project = host.project(window)?; - let (policy, home) = (skills_policy(&project), dirs::home_dir()); + let project = host.project(window).ok().filter(|p| !p.light); + let policy = host_skills_policy(host, project.as_deref()); + let home = dirs::home_dir(); tokio::task::spawn_blocking(move || { Ok(ide_agent::skills::resolve( - ide_agent::skills::discover_skills_in(&policy.workspace_roots, home.as_deref()), + ide_agent::skills::discover_skills_with_plugins( + &policy.workspace_roots, + home.as_deref(), + &policy.plugin_dirs, + ), None, &policy.workspace, &policy.user, @@ -1100,20 +1106,123 @@ pub fn agent_skills_set_mode( } } } - match project { - Some(project) => { - let policy = skills_policy(&project); - let home = dirs::home_dir(); - Ok(ide_agent::skills::resolve( - ide_agent::skills::discover_skills_in(&policy.workspace_roots, home.as_deref()), - None, - &policy.workspace, - &policy.user, - policy.workspace_trusted, - )) - } - None => Ok(Vec::new()), + let policy = host_skills_policy(host, project.as_deref()); + let home = dirs::home_dir(); + Ok(ide_agent::skills::resolve( + ide_agent::skills::discover_skills_with_plugins(&policy.workspace_roots, home.as_deref(), &policy.plugin_dirs), + None, + &policy.workspace, + &policy.user, + policy.workspace_trusted, + )) +} + +/// Resolves a GitHub `owner/repo[/path][@ref]` source and lists the `SKILL.md` skills in it. +#[command(trust = always)] +pub async fn agent_skills_browse( + host: &Host, + source: String, + request: RequestId, +) -> IdeResult { + let cancel = host.begin_request(request); + let search_path = ide_core::tool_path::search_path(); + let res = tokio::task::spawn_blocking(move || { + let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?; + ide_agent::skill_installer::browse_skills(&fetcher, &source, &cancel) + }) + .await + .map_err(join_err); + host.end_request(request); + res? +} + +/// Fetches one skill's `SKILL.md`, file list, and static security scan warnings before installation. +#[command(trust = always)] +pub async fn agent_skills_preview( + host: &Host, + window: &str, + owner: String, + repo: String, + git_ref: String, + subpath: String, + request: RequestId, +) -> IdeResult { + let cancel = host.begin_request(request); + let ws_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone()); + let home = dirs::home_dir(); + let search_path = ide_core::tool_path::search_path(); + let res = tokio::task::spawn_blocking(move || { + let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?; + ide_agent::skill_installer::preview_skill( + &fetcher, + ide_agent::skill_installer::RepoRef { owner: &owner, repo: &repo, git_ref: &git_ref }, + &subpath, + home.as_deref(), + ws_root.as_deref(), + &cancel, + ) + }) + .await + .map_err(join_err); + host.end_request(request); + res? +} + +/// Installs the selected skill subtree into `~/.agents/skills` (User) or `/.agents/skills` (Workspace). +#[command(trust = always)] +pub async fn agent_skills_install( + host: &Host, + window: &str, + input: InstallRemoteSkillRequest, + request: RequestId, +) -> IdeResult> { + let project = host.project(window).ok().filter(|p| !p.light); + if input.scope == McpScope::Workspace { + host.require_trust(window)?; } + let ws_root = project.as_ref().map(|p| p.root.clone()); + let home = dirs::home_dir(); + let cancel = host.begin_request(request); + let search_path = ide_core::tool_path::search_path(); + let install_home = home.clone(); + let install_ws = ws_root.clone(); + let res = tokio::task::spawn_blocking(move || { + let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?; + ide_agent::skill_installer::install_skill( + &fetcher, + &input, + install_home.as_deref(), + install_ws.as_deref(), + &cancel, + ) + }) + .await + .map_err(join_err); + host.end_request(request); + res??; + + let event = IdeEvent::SettingsChanged { key: "agents.skills".into() }; + for p in host.projects() { + p.agents.notify_mcp_servers_changed(); + p.sink.emit(event.clone()); + } + + let policy = host_skills_policy(host, project.as_deref()); + tokio::task::spawn_blocking(move || { + Ok(ide_agent::skills::resolve( + ide_agent::skills::discover_skills_with_plugins( + &policy.workspace_roots, + home.as_deref(), + &policy.plugin_dirs, + ), + None, + &policy.workspace, + &policy.user, + policy.workspace_trusted, + )) + }) + .await + .map_err(join_err)? } /// The user's and the workspace's skill policies (`[agents.skills.]`). @@ -1173,13 +1282,38 @@ pub(crate) fn workspace_skill_roots(root: &std::path::Path) -> Vec SkillsPolicy { - SkillsPolicy { - user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.skills.clone(), - workspace: project.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.skills.clone(), - workspace_trusted: project.trusted.load(std::sync::atomic::Ordering::Acquire), - workspace_roots: workspace_skill_roots(&project.root), +/// The skill policies a session of `project` (or global Settings without a project) resolves against. +fn host_skills_policy(host: &Host, project: Option<&crate::Project>) -> SkillsPolicy { + match project { + Some(project) => { + let workspace_trusted = project.trusted.load(std::sync::atomic::Ordering::Acquire); + let plugin_dirs = host + .plugin_host() + .map(|plugins| plugins.skill_dirs(Some(&project.root), workspace_trusted)) + .unwrap_or_default(); + SkillsPolicy { + user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.skills.clone(), + workspace: project + .settings + .layer(ide_workspace::settings::SettingsScope::Project) + .agents + .skills + .clone(), + workspace_trusted, + workspace_roots: workspace_skill_roots(&project.root), + plugin_dirs, + } + } + None => { + let plugin_dirs = host.plugin_host().map(|plugins| plugins.skill_dirs(None, true)).unwrap_or_default(); + SkillsPolicy { + user: host.global_settings.effective().agents.skills.clone(), + workspace: Default::default(), + workspace_trusted: true, + workspace_roots: Vec::new(), + plugin_dirs, + } + } } } @@ -1339,7 +1473,10 @@ ide_command::domain!( agent_set_env, agent_set_mcp_overrides, agent_set_skill_overrides, + agent_skills_browse, + agent_skills_install, agent_skills_list, + agent_skills_preview, agent_skills_set_mode, agent_stop_background, agent_subscribe, diff --git a/crates/ide-host/src/ops/build.rs b/crates/ide-host/src/ops/build.rs index ee1466247a..36f6f17c65 100644 --- a/crates/ide-host/src/ops/build.rs +++ b/crates/ide-host/src/ops/build.rs @@ -906,6 +906,7 @@ pub async fn build_run( let detected = project.detected_roots.read().clone(); let config_dir = host.config_dir.clone(); let token = host.begin_project_request(window, request); + let launch_project = project.clone(); let result = tokio::task::spawn_blocking(move || { // Fast path (#2476): an unchanged single-project Maven build skips // Maven entirely. Previous diagnostics stay: nothing changed, so they @@ -1003,7 +1004,12 @@ pub async fn build_run( }; let result = compile::run(&root, &plan, &token, &|e| { let _ = on_event.send(e); - })?; + }); + if kind == BuildKind::Rebuild { + // The clean removed outputs that earlier launch snapshots still hold. + launch_project.java_launch_snapshots.lock().forget_reusable_snapshots(); + } + let result = result?; if result.success && single && kind == BuildKind::Build { let model = with_profiles(load(&root, &cache, &settings), &cache); compile::record_menu_build(&cache, &root, &model, file.as_deref(), &token); diff --git a/crates/ide-host/src/ops/dependencies.rs b/crates/ide-host/src/ops/dependencies.rs index 469cc8a907..a97e0344e1 100644 --- a/crates/ide-host/src/ops/dependencies.rs +++ b/crates/ide-host/src/ops/dependencies.rs @@ -2,7 +2,10 @@ use crate::Host; use ide_command::command; use ide_core::{CancellationToken, DocId, IdeError, IdeResult, RequestId}; -use ide_workspace::dependencies::{DependencyVersionSource, DependencyVersions, cargo, go, maven, npm}; +use ide_workspace::dependencies::{ + DependencyVersionSource, DependencyVersions, PythonRequirements, UnsatisfiedRequirement, cargo, go, maven, npm, + python, +}; use std::collections::BTreeMap; use std::hash::{DefaultHasher, Hash, Hasher}; use std::path::{Path, PathBuf}; @@ -254,6 +257,50 @@ pub async fn dependency_versions( result } +/// The requirements of a `requirements*.txt` / `pyproject.toml` the project's interpreter +/// doesn't satisfy; `None` for other files, or with no local interpreter to ask. +#[command(trust = trusted)] +pub async fn python_requirements( + host: &Host, + window: &str, + doc: DocId, + request: RequestId, +) -> IdeResult> { + let project = host.project(window)?; + let config_dir = host.config_dir.clone(); + let cancel = host.begin_project_read_request(window, request); + let result = host + .blocking(move || { + let snap = project.documents.snapshot(doc)?; + let name = snap.path.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + if snap.large || snap.read_only { + return Ok(None); + } + let dependencies = python::requirements(name, &snap.text); + if dependencies.is_empty() { + return Ok(None); + } + // Running the interpreter runs project code (sitecustomize, .pth files). + project.require_trust()?; + let Some(python) = crate::ops::sdk::effective_python(&config_dir, &project, snap.path.parent()) else { + return Ok(None); + }; + let requirements: Vec<&str> = dependencies.iter().map(|d| d.requirement.as_str()).collect(); + let states = ide_sdk::python::unsatisfied_requirements(&python, &requirements, &cancel)?; + let unsatisfied = dependencies + .into_iter() + .zip(states) + .filter_map(|(dependency, state)| { + state.map(|s| UnsatisfiedRequirement { dependency, installed: s.installed }) + }) + .collect(); + Ok(Some(PythonRequirements { python: python.into(), unsatisfied })) + }) + .await; + host.end_request(request); + result +} + #[cfg(test)] mod tests { use super::*; @@ -313,6 +360,56 @@ mod tests { host.close_project("main"); } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn requirements_are_checked_against_the_project_virtualenv() { + let Some(base) = ide_core::tool_path::find_command( + "python3", + &ide_core::tool_path::search_path_in(&std::env::temp_dir()), + &std::env::temp_dir(), + ) else { + return; + }; + let temp = tempfile::tempdir().unwrap(); + let base_dir = dunce::canonicalize(temp.path()).unwrap(); + let root = base_dir.join("project"); + std::fs::create_dir(&root).unwrap(); + let status = std::process::Command::new(base) + .args(["-I", "-m", "venv", "--without-pip"]) + .arg(root.join(".venv")) + .status() + .unwrap(); + assert!(status.success()); + let text = "# 中文\nopenidea-missing-xyz>=1\n-r other.txt\n"; + let path = root.join("requirements.txt"); + std::fs::write(&path, text).unwrap(); + let host = Host::new(HostConfig { + config_dir: base_dir.join("config"), + data_dir: base_dir.join("data"), + local_data_dir: base_dir.join("local"), + languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()), + syntax: Arc::default(), + sink_for: Box::new(|_| Arc::new(|_| {})), + owner: |w| w, + runtime: tokio::runtime::Handle::current(), + project_environment: false, + }); + let project = host.open_project("main", &root).unwrap(); + let info = project.documents.open(&path).unwrap(); + // Restricted Mode never runs the interpreter. + assert!(python_requirements(&host, "main", info.id, RequestId(429)).await.is_err()); + project.trusted.store(true, std::sync::atomic::Ordering::Release); + let found = python_requirements(&host, "main", info.id, RequestId(430)).await.unwrap().unwrap(); + assert!(found.python.0.starts_with(root.join(".venv"))); + assert_eq!(found.unsatisfied.len(), 1); + assert_eq!(found.unsatisfied[0].dependency.package, "openidea-missing-xyz"); + assert_eq!(found.unsatisfied[0].installed, None); + let other = root.join("notes.txt"); + std::fs::write(&other, text).unwrap(); + let info = project.documents.open(&other).unwrap(); + assert!(python_requirements(&host, "main", info.id, RequestId(431)).await.unwrap().is_none()); + host.close_project("main"); + } + struct CachedNpm; impl DependencyVersionSource for CachedNpm { fn id(&self) -> &'static str { @@ -361,4 +458,4 @@ mod tests { } } -ide_command::domain!(dependencies: dependency_versions); +ide_command::domain!(dependencies: dependency_versions, python_requirements); diff --git a/crates/ide-host/src/ops/java/cache.rs b/crates/ide-host/src/ops/java/cache.rs index 38f8bc1fa5..a07e34b7d7 100644 --- a/crates/ide-host/src/ops/java/cache.rs +++ b/crates/ide-host/src/ops/java/cache.rs @@ -135,6 +135,16 @@ impl Session { } } + /// Build › Rebuild replaced the module outputs. The recorded snapshots were copied from + /// the outputs before the clean and may hold classes it removed (a class moved to another + /// package leaves its old file behind when jdtls wrote it), so none of them is reused: + /// the next launch copies the rebuilt outputs. + pub(crate) fn forget_reusable_snapshots(&mut self) { + if let Err(error) = forget_reusable_snapshots(&self.cache) { + tracing::warn!(%error, "Cannot invalidate Java launch snapshots"); + } + } + pub(super) fn build( &mut self, root: &Path, @@ -341,6 +351,32 @@ impl Drop for Session { } } +/// Clears the fingerprint of every launch record under `cache`, so no snapshot matches the +/// sources any more. The records stay: their modules keep delegating to Maven. +fn forget_reusable_snapshots(cache: &Path) -> std::io::Result<()> { + let records = cache.join("java-launch/records"); + if !records.try_exists()? { + return Ok(()); + } + let mut pending = vec![records]; + while let Some(dir) = pending.pop() { + for entry in fs::read_dir(dir)? { + let entry = entry?; + let kind = entry.file_type()?; + if kind.is_dir() { + pending.push(entry.path()); + } else if kind.is_file() && entry.path().extension().is_some_and(|ext| ext == "json") { + let outputs: Option = serde_json::from_slice(&fs::read(entry.path())?).unwrap_or(None); + if let Some(mut outputs) = outputs.filter(|o| o.fingerprint.is_some()) { + outputs.fingerprint = None; + write_record(&entry.path(), &outputs).map_err(|e| std::io::Error::other(e.message))?; + } + } + } + } + Ok(()) +} + fn referenced_snapshots(cache: &Path) -> std::io::Result> { let mut referenced = HashSet::new(); let records = cache.join("java-launch/records"); @@ -610,6 +646,34 @@ mod tests { ); } + #[test] + fn a_menu_rebuild_stops_reusing_snapshots_that_hold_removed_classes() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + let model = fixture(root); + let cancel = CancellationToken::new(); + // A class jdtls wrote for a source since moved to another package; an incremental + // Maven build leaves it in target/classes. + fs::create_dir_all(root.join("target/classes")).unwrap(); + fs::write(root.join("target/classes/Stale.class"), "stale").unwrap(); + let mut session = Session::new(root.join("cache")); + let first = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap(); + assert!(first.snapshot.join("0/Stale.class").is_file()); + let reused = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap(); + assert_eq!(reused.snapshot, first.snapshot); + + // Build › Rebuild cleans the outputs and compiles again. + fs::remove_file(root.join("target/classes/Stale.class")).unwrap(); + session.forget_reusable_snapshots(); + assert!(has_record(root, &root.join("cache"), root)); + let next = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap(); + assert_ne!(next.snapshot, first.snapshot); + assert!(!next.snapshot.join("0/Stale.class").exists()); + assert!(next.snapshot.join("0/Main.class").is_file()); + let again = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap(); + assert_eq!(again.snapshot, next.snapshot); + } + #[test] fn jdt_errors_reuse_an_unchanged_snapshot_and_rebuild_only_on_a_cache_miss() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ide-host/src/ops/lsp.rs b/crates/ide-host/src/ops/lsp.rs index a129421db5..d1c05f6248 100644 --- a/crates/ide-host/src/ops/lsp.rs +++ b/crates/ide-host/src/ops/lsp.rs @@ -1176,6 +1176,22 @@ pub async fn lsp_prepare_rename(host: &Host, window: &str, doc: DocId, pos: Pos) host.project(window)?.lsp.prepare_rename(doc, pos).await } +/// The Throwable class the caret at `pos` names, for the exception breakpoint intention. +#[command(trust = trusted)] +pub async fn lsp_exception_class_at( + host: &Host, + window: &str, + request: RequestId, + doc: DocId, + pos: Pos, +) -> IdeResult> { + let project = host.project(window)?; + let cancel = host.begin_request(request); + let result = project.lsp.exception_class_at(doc, pos, cancel).await; + host.end_request(request); + result +} + /// The class at `pos` and the members Pull Members Up / Push Members Down can move. #[command(trust = trusted)] pub async fn lsp_hierarchy_members( @@ -2842,6 +2858,7 @@ ide_command::domain!( lsp_completion, lsp_document_highlights, lsp_document_links, + lsp_exception_class_at, lsp_execute_code_action, lsp_execute_command, lsp_extract_interface, diff --git a/crates/ide-host/src/ops/project.rs b/crates/ide-host/src/ops/project.rs index e55727bb91..3610920914 100644 --- a/crates/ide-host/src/ops/project.rs +++ b/crates/ide-host/src/ops/project.rs @@ -391,6 +391,9 @@ pub fn set_settings( if key == "languages" || key == "languages.java" || key.starts_with("languages.java.addedJdks") { host.apply_added_jdks(); } + if key == "vcs" || key == "vcs.git" || key == "vcs.git.executable" { + host.apply_git_executable(); + } if is_proxy { host.apply_proxy(); } diff --git a/crates/ide-host/src/ops/sdk.rs b/crates/ide-host/src/ops/sdk.rs index 71845a61c8..54a7f82315 100644 --- a/crates/ide-host/src/ops/sdk.rs +++ b/crates/ide-host/src/ops/sdk.rs @@ -120,6 +120,33 @@ pub async fn sdk_python_interpreter(host: &Host, window: &str, path: PathBuf) -> .map_err(join_err)? } +/// The interpreter of the workspace member `near` belongs to, else the project's. +pub(crate) fn effective_python( + config_dir: &std::path::Path, + project: &crate::Project, + near: Option<&std::path::Path>, +) -> Option { + let project_root = &project.root; + let member = ide_workspace::workspace::Workspace::load(project_root).ok().flatten().and_then(|w| { + let near = near?; + w.projects.into_iter().filter(|root| near.starts_with(root)).max_by_key(|root| root.components().count()) + }); + let (root, settings) = match member { + Some(root) => { + let settings = ide_workspace::SettingsStore::load(config_dir, Some(&root)).effective(); + (root, settings) + } + None => (project_root.clone(), project.settings.effective()), + }; + // A member with no Python of its own falls back to the primary project's + // (the same chain run configurations use), so every answer names one interpreter. + ide_sdk::apply::python_interpreter_near(&root, near, &settings).or_else(|| { + (&root != project_root) + .then(|| ide_sdk::apply::python_interpreter(project_root, &project.settings.effective())) + .flatten() + }) +} + /// The interpreter the project uses: the configured one, else its virtualenv. #[command(trust = trusted)] pub async fn sdk_python_effective( @@ -129,31 +156,11 @@ pub async fn sdk_python_effective( ) -> IdeResult> { host.require_trust(window)?; let project = host.project(window)?; - let (config_dir, project_root) = (host.config_dir.clone(), project.root.clone()); + let config_dir = host.config_dir.clone(); // Loading a member's settings needs more stack than a sync command's main thread has left. - tokio::task::spawn_blocking(move || { - let member = ide_workspace::workspace::Workspace::load(&project_root).ok().flatten().and_then(|w| { - let near = near.as_deref()?; - w.projects.into_iter().filter(|root| near.starts_with(root)).max_by_key(|root| root.components().count()) - }); - let (root, settings) = match member { - Some(root) => { - let settings = ide_workspace::SettingsStore::load(&config_dir, Some(&root)).effective(); - (root, settings) - } - None => (project_root.clone(), project.settings.effective()), - }; - // A member with no Python of its own falls back to the primary project's - // (the same chain run configurations use), so every answer names one interpreter. - let interpreter = ide_sdk::apply::python_interpreter_near(&root, near.as_deref(), &settings).or_else(|| { - (root != project_root) - .then(|| ide_sdk::apply::python_interpreter(&project_root, &project.settings.effective())) - .flatten() - }); - Ok(interpreter.map(Into::into)) - }) - .await - .map_err(join_err)? + tokio::task::spawn_blocking(move || Ok(effective_python(&config_dir, &project, near.as_deref()).map(Into::into))) + .await + .map_err(join_err)? } /// The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`. diff --git a/crates/ide-host/src/ops/vcs.rs b/crates/ide-host/src/ops/vcs.rs index da66600d5a..0f6e6b8278 100644 --- a/crates/ide-host/src/ops/vcs.rs +++ b/crates/ide-host/src/ops/vcs.rs @@ -1,4 +1,4 @@ -use crate::{Host, apply_git_executable}; +use crate::Host; use ide_command::command; use ide_core::IdeResult; use ide_vcs::FileStatus; @@ -9,9 +9,6 @@ pub async fn vcs_status(host: &Host, window: &str) -> IdeResult> let project = host.project(window)?; host.blocking(move || { let settings = project.settings.effective(); - if project.is_trusted() { - apply_git_executable(&settings); - } let repos = project.repos(); if repos.is_empty() { return Err(ide_core::IdeError::unavailable("project is not a git repository")); @@ -30,9 +27,6 @@ pub async fn vcs_ignored_files(host: &Host, window: &str) -> IdeResult, ) -> IdeResult<()> { let settings = host.global_settings.effective(); - apply_git_executable(&settings); let recurse_submodules = settings.vcs.git.clone_submodules; let cancel = host.begin_request(request); let result = tokio::task::spawn_blocking(move || { @@ -1903,11 +1900,12 @@ pub async fn vcs_clone( result } -/// `git init` in `dir` (File › New Project… "Create Git repository"). +/// `git init` in `dir` (VCS › Create Git Repository…): with the git of the window's project when +/// it is trusted, the default one in a window without a project. #[command(trust = always)] -pub async fn vcs_init(host: &Host, dir: PathBuf) -> IdeResult<()> { - apply_git_executable(&host.global_settings.effective()); - blocking(move || ide_vcs::init(&dir)).await +pub async fn vcs_init(host: &Host, window: &str, dir: PathBuf) -> IdeResult<()> { + let git = host.project(window).ok().and_then(|p| p.git_executable()); + blocking(move || ide_vcs::with_git_executable(git.as_deref(), || ide_vcs::init(&dir))).await } /// Settings › Git › Test: runs `git --version` on `path`, or on the auto-detected @@ -2550,14 +2548,8 @@ pub async fn vcs_compare_paths( ) -> IdeResult { let project = host.project(window)?; let cancel = host.begin_request(request); - let result = blocking(move || { - let settings = project.settings.effective(); - if project.is_trusted() { - apply_git_executable(&settings); - } - project.repos().compare_paths(&paths, &revision, repositories.as_deref(), &cancel) - }) - .await; + let result = + blocking(move || project.repos().compare_paths(&paths, &revision, repositories.as_deref(), &cancel)).await; host.end_request(request); result } diff --git a/crates/ide-host/src/plugins/api.rs b/crates/ide-host/src/plugins/api.rs index 04b1ca9d2f..ff2e1a10bd 100644 --- a/crates/ide-host/src/plugins/api.rs +++ b/crates/ide-host/src/plugins/api.rs @@ -136,6 +136,10 @@ pub trait PluginWorkspace: Send + Sync { fn apply_edits(&self, path: &Path, version: u64, edits: &[TextEdit], background: bool) -> Result; /// Code from the project may run (git hooks and config on fetch). fn trusted(&self, root: &Path) -> bool; + /// The git executable of the project at `root` (see [`crate::Project::git_executable`]). + fn git_executable(&self, _root: &Path) -> Option { + None + } /// Root of the project open in `window`. fn project_of(&self, window: &str) -> Option; /// Windows showing the open project at `root`, the most recently focused first. @@ -1457,6 +1461,7 @@ pub(super) fn commit_draft( }; // Both callers have checked that the window's project is trusted. r.set_execution_allowed(true); + r.set_git_executable(workspace.git_executable(&repo.root.0).as_deref()); let backend = &r as &dyn ide_vcs::Backend; let pending = backend .pending_changes(&repo.options, budget, &|path| Ok(workspace.vcs_encoding(path))) @@ -3724,6 +3729,10 @@ impl PluginWorkspace for HostWorkspace { HostWorkspace::project_covering(self, root).is_some_and(|p| p.is_trusted()) } + fn git_executable(&self, root: &Path) -> Option { + HostWorkspace::project_covering(self, root)?.git_executable() + } + fn project_of(&self, window: &str) -> Option { self.0.upgrade()?.project(window).ok().map(|p| p.root.clone()) } @@ -4728,8 +4737,12 @@ impl PluginApi { /// no upstream. The other reads use [`Self::read_repo`] and never execute. fn repo(&self, root: &Path) -> Result, HostError> { let repo = ide_vcs::Repo::discover(root).map_err(failed)?; - if let Some(repo) = &repo { - repo.set_execution_allowed(self.shared.workspace().is_some_and(|w| w.trusted(root))); + if let Some(repo) = &repo + && let Some(workspace) = self.shared.workspace() + && workspace.trusted(root) + { + repo.set_execution_allowed(true); + repo.set_git_executable(workspace.git_executable(root).as_deref()); } Ok(repo) } diff --git a/crates/ide-host/src/plugins/mod.rs b/crates/ide-host/src/plugins/mod.rs index 462128045a..0fff65c32b 100644 --- a/crates/ide-host/src/plugins/mod.rs +++ b/crates/ide-host/src/plugins/mod.rs @@ -53,6 +53,7 @@ mod run_detectors; pub mod run_targets; pub mod search; mod semantic_tokens; +mod skills; mod snippets; mod theme; mod types; @@ -385,6 +386,8 @@ pub struct PluginHost { run_detectors: Arc, /// `[[contributes.javaAgents]]` of enabled plugins. java_agents: Arc, + /// `[[contributes.skills]]` of enabled plugins. + skills: Arc, /// `[[contributes.providers]]` of enabled plugins. providers: Arc, navigation: Mutex, @@ -411,6 +414,8 @@ pub struct PluginHost { announced_theme: Mutex>, /// [`PluginLanguages::revision`] last announced with `LanguagesChanged`. announced_languages: AtomicU64, + /// [`skills::PluginSkills::revision`] last announced to open projects. + announced_skills: AtomicU64, /// `PATH` used to resolve `process:` programs at grant time. path_var: RwLock, /// (plugin id, `process:` capability) → the approved program; read by the @@ -470,7 +475,8 @@ impl PluginHost { let run_detectors: Arc = Arc::default(); let providers: Arc = Arc::default(); let java_agents: Arc = Arc::default(); - register_builtin_points(®istry, &ui, &languages, &run_detectors, &java_agents, &providers) + let skills: Arc = Arc::default(); + register_builtin_points(®istry, &ui, &languages, &run_detectors, &java_agents, &providers, &skills) .map_err(IdeError::internal)?; let pins: Arc>> = Arc::default(); let policy_pins = pins.clone(); @@ -506,6 +512,7 @@ impl PluginHost { languages, run_detectors, java_agents, + skills, providers, navigation: Mutex::default(), endpoints: Mutex::default(), @@ -521,6 +528,7 @@ impl PluginHost { startup_finished: AtomicBool::new(false), announced_theme: Mutex::new(None), announced_languages: AtomicU64::new(0), + announced_skills: AtomicU64::new(0), path_var: RwLock::new(Arc::new(|| std::env::var_os("PATH"))), pins, }; @@ -2915,6 +2923,16 @@ impl PluginHost { if self.announced_languages.swap(languages, Ordering::AcqRel) != languages { self.emit(None, PluginEvent::LanguagesChanged); } + let skills = self.skills.revision(); + if self.announced_skills.swap(skills, Ordering::AcqRel) != skills + && let Some(workspace) = self.shared.workspace.read().clone() + && let Some(host) = workspace.database_host() + { + for p in host.projects() { + p.agents.notify_mcp_servers_changed(); + p.sink.emit(ide_core::IdeEvent::SettingsChanged { key: "agents.skills".into() }); + } + } let active = self.active_theme(); let mut announced = self.announced_theme.lock(); if *announced != active { diff --git a/crates/ide-host/src/plugins/points.rs b/crates/ide-host/src/plugins/points.rs index 58749b7cef..ad00881347 100644 --- a/crates/ide-host/src/plugins/points.rs +++ b/crates/ide-host/src/plugins/points.rs @@ -66,6 +66,7 @@ pub fn register_builtin_points( run_detectors: &Arc, java_agents: &Arc, providers: &Arc, + skills: &Arc, ) -> Result<(), String> { registry.register(Arc::new(UiPoint::new(COMMANDS, ui.clone(), command)))?; registry.register(Arc::new(super::theme::ThemesPoint::new(ui.clone())))?; @@ -73,6 +74,7 @@ pub fn register_builtin_points( registry.register(Arc::new(UiPoint::new(super::icons::POINT_ID, ui.clone(), super::icons::icon_theme)))?; registry.register(Arc::new(super::run_detectors::RunDetectorsPoint::new(run_detectors.clone())))?; registry.register(Arc::new(super::java_agents::JavaAgentsPoint::new(java_agents.clone())))?; + registry.register(Arc::new(super::skills::SkillsPoint::new(skills.clone())))?; registry.register(Arc::new(super::navigation::IndexersPoint))?; registry.register(Arc::new(super::providers::ProvidersPoint::new(providers.clone())))?; registry.register(Arc::new(UiPoint::new(super::providers::SECRETS_POINT, ui.clone(), super::providers::secret)))?; diff --git a/crates/ide-host/src/plugins/skills.rs b/crates/ide-host/src/plugins/skills.rs new file mode 100644 index 0000000000..fe97d9927d --- /dev/null +++ b/crates/ide-host/src/plugins/skills.rs @@ -0,0 +1,250 @@ +//! The `skills` extension point (API 1.15): declarative `SKILL.md` folders inside a +//! plugin package (`[[contributes.skills]]`), discovered directly from live plugins' +//! package directories and staged into agent sessions through [`ide_agent::skills`]. +//! +//! ```toml +//! [[contributes.skills]] +//! path = "skills/release-notes/SKILL.md" +//! ``` +//! +//! Invalid entries emit a plugin load warning (`Prepared::skipped`) rather than failing +//! the whole plugin; `engines.openidea` compatibility (`^1.15`) remains a manifest check. + +use super::PluginHost; +use ide_extension::{Disposable, ExtensionPoint, Package, Placement, Prepared, decode}; +use parking_lot::RwLock; +use serde::Deserialize; +use std::collections::HashSet; +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +pub const POINT_ID: &str = "skills"; +/// Maximum total size of all files inside one contributed skill folder (2 MiB). +pub const MAX_SKILL_DIR_BYTES: u64 = 2 << 20; +const MAX_SKILL_FILES: usize = 256; +const MAX_SKILL_DEPTH: usize = 16; + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct Decl { + path: PathBuf, +} + +#[derive(Clone, Debug)] +struct ContributedSkill { + plugin_id: String, + name: String, + /// Package-relative directory holding `SKILL.md` (e.g. `skills/release-notes`). + rel_dir: PathBuf, +} + +/// Contributed skills of loaded plugins. +#[derive(Default)] +pub struct PluginSkills { + items: RwLock>, + seq: AtomicU64, + revision: AtomicU64, +} + +impl PluginSkills { + pub fn revision(&self) -> u64 { + self.revision.load(Ordering::Acquire) + } + + fn add(self: &Arc, item: ContributedSkill) -> Disposable { + let seq = self.seq.fetch_add(1, Ordering::Relaxed); + self.items.write().push((seq, item)); + self.revision.fetch_add(1, Ordering::AcqRel); + let weak = Arc::downgrade(self); + Disposable::new(move || { + if let Some(this) = weak.upgrade() { + this.items.write().retain(|(s, _)| *s != seq); + this.revision.fetch_add(1, Ordering::AcqRel); + } + }) + } +} + +pub struct SkillsPoint { + store: Arc, +} + +impl SkillsPoint { + pub fn new(store: Arc) -> Self { + Self { store } + } +} + +impl ExtensionPoint for SkillsPoint { + fn id(&self) -> &'static str { + POINT_ID + } + + fn placement(&self) -> Placement { + Placement::Workspace + } + + fn prepare(&self, pkg: &Package, decl: toml::Value) -> Result { + pkg.manifest.needs_api("contributes.skills", 15)?; + match self.prepare_entry(pkg, decl) { + Ok(prepared) => Ok(prepared), + Err(warning) => Ok(Prepared::skipped(warning)), + } + } +} + +impl SkillsPoint { + fn prepare_entry(&self, pkg: &Package, decl: toml::Value) -> Result { + let d: Decl = decode(POINT_ID, decl)?; + if d.path.as_os_str().is_empty() || !d.path.components().all(|c| matches!(c, Component::Normal(_))) { + return Err(format!("{}: `path` must be a relative path inside the plugin", d.path.display())); + } + if d.path.file_name().and_then(|n| n.to_str()) != Some("SKILL.md") { + return Err(format!("{}: must point to `/SKILL.md`", d.path.display())); + } + let Some(rel_dir) = d.path.parent().filter(|p| !p.as_os_str().is_empty()) else { + return Err(format!("{}: must live inside a `/SKILL.md` folder", d.path.display())); + }; + let Some(folder) = rel_dir.file_name().and_then(|n| n.to_str()) else { + return Err(format!("{}: invalid skill folder name", d.path.display())); + }; + + // Reject duplicate skill folder names across distinct paths in the same plugin. + for other in pkg.manifest.declarations(POINT_ID) { + let Some(other_path) = other.get("path").and_then(|v| v.as_str()).map(Path::new) else { continue }; + if other_path == d.path { + break; + } + if other_path.file_name().and_then(|n| n.to_str()) == Some("SKILL.md") + && other_path.parent().and_then(|p| p.file_name()).and_then(|n| n.to_str()) == Some(folder) + { + return Err(format!("duplicate skill `{folder}` in plugin")); + } + } + + let pkg_root = pkg.dir.canonicalize().map_err(|e| format!("plugin directory: {e}"))?; + let abs_dir = pkg.resolve(rel_dir)?; + if !abs_dir.is_dir() { + return Err(format!("{}: not a directory", rel_dir.display())); + } + let _ = pkg.resolve(&d.path)?; + + let mut files = Vec::new(); + let mut total_bytes = 0u64; + let mut visited_dirs = HashSet::new(); + visited_dirs.insert(abs_dir.clone()); + collect_skill_files( + &pkg_root, + &pkg.dir.join(rel_dir), + rel_dir, + 0, + &mut visited_dirs, + &mut files, + &mut total_bytes, + folder, + )?; + files.sort(); + + let text = pkg.read_text(&d.path)?; + ide_agent::skills::validate_plugin_skill(&abs_dir, folder, &text) + .map_err(|e| format!("{}: {e}", d.path.display()))?; + + let label = format!("/{folder}"); + let key = folder.to_owned(); + let item = ContributedSkill { + plugin_id: pkg.id().to_owned(), + name: folder.to_owned(), + rel_dir: rel_dir.to_path_buf(), + }; + let store = self.store.clone(); + let mut prepared = Prepared::new(label, move || Ok(store.add(item))).key(key); + prepared.files = files; + Ok(prepared) + } +} + +#[allow(clippy::too_many_arguments)] +fn collect_skill_files( + pkg_root: &Path, + abs_dir: &Path, + rel_dir: &Path, + depth: usize, + visited_dirs: &mut HashSet, + files: &mut Vec, + total_bytes: &mut u64, + skill_name: &str, +) -> Result<(), String> { + if depth > MAX_SKILL_DEPTH { + return Err(format!("{}: directory nesting exceeds {MAX_SKILL_DEPTH} levels", rel_dir.display())); + } + let entries = std::fs::read_dir(abs_dir).map_err(|e| format!("{}: {e}", rel_dir.display()))?; + for entry in entries { + let entry = entry.map_err(|e| format!("{}: {e}", rel_dir.display()))?; + let name = entry.file_name(); + let entry_abs = entry.path(); + let entry_rel = rel_dir.join(&name); + let sym_meta = std::fs::symlink_metadata(&entry_abs).map_err(|e| format!("{}: {e}", entry_rel.display()))?; + let canon = entry_abs + .canonicalize() + .map_err(|_| format!("{}: broken symlink or unreadable entry", entry_rel.display()))?; + if !canon.starts_with(pkg_root) { + return Err(format!("{}: points outside the plugin", entry_rel.display())); + } + let meta = if sym_meta.file_type().is_symlink() { + std::fs::metadata(&entry_abs).map_err(|e| format!("{}: {e}", entry_rel.display()))? + } else { + sym_meta + }; + if meta.is_dir() { + if !visited_dirs.insert(canon.clone()) { + return Err(format!("{}: cyclic directory link", entry_rel.display())); + } + collect_skill_files( + pkg_root, + &entry_abs, + &entry_rel, + depth + 1, + visited_dirs, + files, + total_bytes, + skill_name, + )?; + visited_dirs.remove(&canon); + } else if meta.is_file() { + if files.len() >= MAX_SKILL_FILES { + return Err(format!("skill `{skill_name}` exceeds {MAX_SKILL_FILES} files")); + } + *total_bytes = total_bytes.saturating_add(meta.len()); + if *total_bytes > MAX_SKILL_DIR_BYTES { + return Err(format!("skill `{skill_name}` exceeds {} MiB", MAX_SKILL_DIR_BYTES >> 20)); + } + files.push(entry_rel); + } else { + return Err(format!("{}: unsupported file type in skill folder", entry_rel.display())); + } + } + Ok(()) +} + +impl PluginHost { + /// Skill directories (`/`) contributed by live plugins for `root`. + /// Project-local `.openidea/plugins/` packages only apply to their own trusted project. + pub fn skill_dirs(&self, root: Option<&Path>, workspace_trusted: bool) -> Vec { + let mut entries: Vec<(String, String, PathBuf)> = Vec::new(); + for (_, item) in self.skills.items.read().iter() { + let Ok(plugin) = self.get(&item.plugin_id) else { continue }; + if !plugin.status().is_live() { + continue; + } + if let Some(dev_root) = plugin.dev_root.as_deref() + && (!workspace_trusted || root != Some(dev_root)) + { + continue; + } + entries.push((item.plugin_id.clone(), item.name.clone(), plugin.dir().join(&item.rel_dir))); + } + entries.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))); + entries.into_iter().map(|(_, _, path)| path).collect() + } +} diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index 2ed2851553..944d098329 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -286,6 +286,10 @@ impl Host { lombok.jar(), ); ide_sdk::apply::configure_gradle_runtime(cfg, root, server_root, &effective); + let gradle_dirs: Vec<_> = std::iter::once(data_dir.join("gradle")) + .chain(dirs::cache_dir().map(|dir| dir.join("openidea").join("gradle"))) + .collect(); + ide_sdk::apply::configure_gradle_classpath(cfg, &gradle_dirs); ide_sdk::apply::configure_maven_sources(cfg, &effective); ide_sdk::jdtls::launch_directly(cfg); } @@ -692,6 +696,10 @@ impl Host { roots })); } + { + let weak = Arc::downgrade(&project); + project.agents.set_git_executable_hook(Arc::new(move || weak.upgrade()?.git_executable())); + } self.insert_project(window, project.clone()); for (key, text, dirty) in &carried { let _ = project.documents.restore_untitled_buffer(key, text, *dirty); @@ -765,13 +773,20 @@ impl Host { let skill_settings = settings.clone(); let skill_root = root.clone(); let trust = self.trust.clone(); + let plugin_host = self.plugin_host.read().clone(); agents.set_skills_policy_hook(Box::new(move || { let layer = |scope| skill_settings.layer(scope).agents.skills.clone(); + let workspace_trusted = trust.window_trusted(&skill_root).unwrap_or(false); + let plugin_dirs = plugin_host + .upgrade() + .map(|plugins| plugins.skill_dirs(Some(&skill_root), workspace_trusted)) + .unwrap_or_default(); ide_agent::SkillsPolicy { user: layer(ide_workspace::settings::SettingsScope::Global), workspace: layer(ide_workspace::settings::SettingsScope::Project), - workspace_trusted: trust.window_trusted(&skill_root).unwrap_or(false), + workspace_trusted, workspace_roots: crate::ops::agent::workspace_skill_roots(&skill_root), + plugin_dirs, } })); agents.set_mcp_servers_hook(Box::new(move || { @@ -1062,11 +1077,24 @@ impl Project { ); } + /// Settings › Version Control › Git › Path to Git executable, this project's value (its own + /// layer over the global one); `None` when it is empty or the project is not trusted. + /// Every git started for the project runs it: the project's repositories carry it, and work + /// that opens repositories of its own (agent worktrees, gh, plugins) passes it to + /// [`ide_vcs::with_git_executable`]. + pub fn git_executable(&self) -> Option { + let git = self.settings.read_effective(|s| s.vcs.git.executable.trim().to_owned()); + (self.is_trusted() && !git.is_empty()).then(|| PathBuf::from(git)) + } + /// The project's git repositories. pub fn repos(&self) -> Repos { let repos = self.repos.read().clone(); + let trusted = self.is_trusted(); + let git = self.git_executable(); for repo in repos.all() { - repo.set_execution_allowed(self.is_trusted()); + repo.set_execution_allowed(trusted); + repo.set_git_executable(git.as_deref()); } repos } @@ -1150,9 +1178,6 @@ impl Project { fn run_in(&self, repo: &Repo, f: impl FnOnce(&Repo) -> IdeResult) -> IdeResult { let settings = self.settings.effective(); - if self.is_trusted() { - apply_git_executable(&settings); - } repo.set_ignored_names(settings.ignored_names()); repo.set_cli_status(settings.vcs.git.cli_status); repo.set_automatic_shelf( @@ -2183,12 +2208,6 @@ fn notify_transfer(sink: &SharedSink, what: &str, path: &Path, result: IdeResult }); } -/// Settings › Version Control › Git › Path to Git executable (empty = auto-detect). -pub fn apply_git_executable(settings: &ide_core::settings::Settings) { - let exe = settings.vcs.git.executable.trim(); - ide_vcs::set_git_executable((!exe.is_empty()).then(|| Path::new(exe))); -} - #[cfg(test)] mod maven_linkage_tests { #[test] diff --git a/crates/ide-host/tests/plugins.rs b/crates/ide-host/tests/plugins.rs index 1e84271824..a8a4523c49 100644 --- a/crates/ide-host/tests/plugins.rs +++ b/crates/ide-host/tests/plugins.rs @@ -7313,3 +7313,112 @@ fn a_freshly_installed_plugin_gets_the_post_install_settings_event() { "freshly installed plugin got no post-install event: {received}" ); } + +#[test] +fn contributes_skills_installs_discovers_and_tracks_plugin_lifecycle() { + let f = fixture(Limits::default()); + let info = f.install(&sample("agent-skills")); + assert_eq!(info.status, PluginStatus::Static); + assert!(info.warnings.is_empty(), "{:?}", info.warnings); + assert!(info.contributions.iter().any(|c| c.point == "skills" && c.label == "/release-notes")); + + let dirs = f.host.skill_dirs(Some(&f.project), true); + assert_eq!(dirs.len(), 1); + assert!(dirs[0].join("SKILL.md").is_file(), "SKILL.md copied to install dir"); + assert!( + dirs[0].join("references/template.md").is_file(), + "bundled supporting files in the skill folder copied to install dir" + ); + + let discovered = ide_agent::skills::discover_skills_with_plugins(std::slice::from_ref(&f.project), None, &dirs); + assert_eq!(discovered.len(), 1); + assert_eq!(discovered[0].name, "release-notes"); + assert_eq!(discovered[0].source, ide_agent::AgentSkillSource::Plugin); + assert_eq!(discovered[0].hint.as_deref(), Some("[tag]")); + + // Workspace skill with the same name wins; the plugin skill is never silently renamed. + let ws_skill = f.project.join(".agents/skills/release-notes"); + std::fs::create_dir_all(&ws_skill).unwrap(); + std::fs::write(ws_skill.join("SKILL.md"), "---\nname: release-notes\ndescription: workspace override\n---\n") + .unwrap(); + let clashed = ide_agent::skills::discover_skills_with_plugins(std::slice::from_ref(&f.project), None, &dirs); + assert_eq!(clashed.len(), 1); + assert_eq!(clashed[0].source, ide_agent::AgentSkillSource::Workspace); + assert_eq!(clashed[0].description, "workspace override"); + + // Disabling or uninstalling removes the plugin's skill directories immediately. + f.host.set_enabled("test.agent-skills", false).unwrap(); + assert!(f.host.skill_dirs(Some(&f.project), true).is_empty()); + f.host.set_enabled("test.agent-skills", true).unwrap(); + assert_eq!(f.host.skill_dirs(Some(&f.project), true).len(), 1); + f.host.uninstall("test.agent-skills").unwrap(); + assert!(f.host.skill_dirs(Some(&f.project), true).is_empty()); +} + +#[test] +fn contributes_skills_needs_api_1_15_and_warns_without_failing_plugin_on_bad_entries() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + + // Older `engines.openidea` is refused at the manifest check. + let old_api = tmp.path().join("old-api"); + copy_dir(&sample("agent-skills"), &old_api); + let manifest = std::fs::read_to_string(old_api.join("plugin.toml")).unwrap(); + std::fs::write(old_api.join("plugin.toml"), manifest.replace("\"^1.15\"", "\"^1.14\"")).unwrap(); + let err = f.host.install_from_dir(&old_api, &Consent::all()).unwrap_err(); + assert!(err.message.contains("new in plugin API 1.15"), "{err:?}"); + + // Invalid skill entries emit load warnings while valid skills and the plugin itself still load. + let pkg = tmp.path().join("mixed-skills"); + std::fs::create_dir_all(pkg.join("skills/good-skill")).unwrap(); + std::fs::write(pkg.join("skills/good-skill/SKILL.md"), "---\nname: good-skill\ndescription: valid skill\n---\n") + .unwrap(); + std::fs::create_dir_all(pkg.join("skills/wrong-name")).unwrap(); + std::fs::write( + pkg.join("skills/wrong-name/SKILL.md"), + "---\nname: mismatched\ndescription: bad frontmatter name\n---\n", + ) + .unwrap(); + std::fs::create_dir_all(pkg.join("skills/not-skill-md")).unwrap(); + std::fs::write(pkg.join("skills/not-skill-md/README.md"), "nope\n").unwrap(); + std::fs::create_dir_all(pkg.join("skills/oversize")).unwrap(); + std::fs::write(pkg.join("skills/oversize/SKILL.md"), "---\nname: oversize\ndescription: too big\n---\n").unwrap(); + std::fs::write(pkg.join("skills/oversize/blob.bin"), vec![b'x'; (2 << 20) + 16]).unwrap(); + + #[allow(unused_mut)] + let mut manifest = String::from( + "id = \"acme.mixed-skills\"\n\ + name = \"Mixed Skills\"\n\ + version = \"1.0.0\"\n\ + engines.openidea = \"^1.15\"\n\n\ + [[contributes.skills]]\npath = \"skills/good-skill/SKILL.md\"\n\ + [[contributes.skills]]\npath = \"../outside/SKILL.md\"\n\ + [[contributes.skills]]\npath = \"skills/not-skill-md/README.md\"\n\ + [[contributes.skills]]\npath = \"skills/wrong-name/SKILL.md\"\n\ + [[contributes.skills]]\npath = \"skills/oversize/SKILL.md\"\n", + ); + #[cfg(unix)] + { + let outside = tmp.path().join("outside.txt"); + std::fs::write(&outside, "secret\n").unwrap(); + std::fs::create_dir_all(pkg.join("skills/escape-link")).unwrap(); + std::fs::write( + pkg.join("skills/escape-link/SKILL.md"), + "---\nname: escape-link\ndescription: has escaping symlink\n---\n", + ) + .unwrap(); + std::os::unix::fs::symlink(&outside, pkg.join("skills/escape-link/leak.txt")).unwrap(); + manifest.push_str("[[contributes.skills]]\npath = \"skills/escape-link/SKILL.md\"\n"); + } + std::fs::write(pkg.join("plugin.toml"), manifest).unwrap(); + + let info = f.install(&pkg); + assert_eq!(info.status, PluginStatus::Static, "bad skill entries must not fail the plugin"); + let expected_warnings = if cfg!(unix) { 5 } else { 4 }; + assert_eq!(info.warnings.len(), expected_warnings, "{:?}", info.warnings); + assert!(info.warnings.iter().all(|w| w.starts_with("contributes.skills[")), "{:?}", info.warnings); + + let dirs = f.host.skill_dirs(Some(&f.project), true); + assert_eq!(dirs.len(), 1); + assert!(dirs[0].ends_with("skills/good-skill"), "{dirs:?}"); +} diff --git a/crates/ide-host/tests/trust.rs b/crates/ide-host/tests/trust.rs index b791ed2f4d..9c2700370c 100644 --- a/crates/ide-host/tests/trust.rs +++ b/crates/ide-host/tests/trust.rs @@ -352,7 +352,6 @@ async fn restricted_git_views_ignore_project_executables_and_mutations_cannot_ru project.with_repo(|repo| repo.commit("trusted", false, false)).unwrap(); assert!(root.join("git-executable.marker").exists()); assert!(root.join("git-hook.marker").exists()); - ide_vcs::set_git_executable(None); host.shutdown().await; } diff --git a/crates/ide-host/tests/trust_git_binary.rs b/crates/ide-host/tests/trust_git_binary.rs index 0defc4cc57..24cbe5cc17 100644 --- a/crates/ide-host/tests/trust_git_binary.rs +++ b/crates/ide-host/tests/trust_git_binary.rs @@ -1,15 +1,14 @@ -//! The configured Git binary is process-wide, so it has its own test binary. +//! Which git executable each window's repositories run. Its own test binary: the default +//! executable (global settings) is process-wide. #![cfg(unix)] use ide_core::NullSink; use ide_host::{Host, HostConfig, ops}; use std::os::unix::fs::PermissionsExt; +use std::path::Path; use std::sync::Arc; -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn restricted_status_does_not_select_the_project_git_for_other_windows() { - let tmp = tempfile::tempdir().unwrap(); - let base = dunce::canonicalize(tmp.path()).unwrap(); - let host = Arc::new(Host::new(HostConfig { +fn host(base: &Path) -> Arc { + Arc::new(Host::new(HostConfig { config_dir: base.join("config"), data_dir: base.join("data"), local_data_dir: base.join("data"), @@ -19,7 +18,126 @@ async fn restricted_status_does_not_select_the_project_git_for_other_windows() { owner: |w| w, runtime: tokio::runtime::Handle::current(), project_environment: false, - })); + })) +} + +/// A repository with `tools/git`: it appends a line to `marker`, waits while `gate` exists, +/// then runs the real git. +fn repo_with_wrapper(root: &Path, marker: &Path, gate: &Path) { + std::fs::create_dir_all(root.join(".openidea")).unwrap(); + std::fs::create_dir_all(root.join("tools")).unwrap(); + let real = ide_vcs::detected_git_executable().expect("git is installed"); + let wrapper = root.join("tools/git"); + let script = format!( + "#!/bin/sh\necho run >> '{}'\ni=0\nwhile [ -e '{}' ] && [ $i -lt 400 ]; do sleep 0.05; i=$((i+1)); done\nexec '{}' \"$@\"\n", + marker.display(), + gate.display(), + real.display() + ); + std::fs::write(&wrapper, script).unwrap(); + std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap(); + let init = std::process::Command::new(&real).arg("init").arg("-q").arg(root).output().unwrap(); + assert!(init.status.success(), "{}", String::from_utf8_lossy(&init.stderr)); +} + +fn runs(marker: &Path) -> usize { + std::fs::read_to_string(marker).map_or(0, |s| s.lines().count()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_project_git_executable_stays_with_its_project_while_another_window_runs_git() { + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let host = host(&base); + let (a, c) = (base.join("a"), base.join("c")); + let (a_marker, c_marker, gate) = (base.join("a.marker"), base.join("c.marker"), base.join("gate")); + repo_with_wrapper(&a, &a_marker, &gate); + repo_with_wrapper(&c, &c_marker, &gate); + // Relative: resolved against the repository that runs it, so C has a `tools/git` of its own. + std::fs::write(a.join(".openidea/settings.toml"), "[vcs.git]\nexecutable = \"tools/git\"\n").unwrap(); + let project_a = host.open_project("a", &a).unwrap(); + host.open_project("c", &c).unwrap(); + for root in [&a, &c] { + host.set_project_trust(root, true, false).await.unwrap(); + } + + // Project A runs two git commands in one go, as `compare_paths` does; window C runs its own + // git between them. + std::fs::write(&gate, "").unwrap(); + let two_commands = tokio::task::spawn_blocking(move || { + project_a.with_repo(|repo| { + repo.remotes()?; + repo.remotes() + }) + }); + for _ in 0..200 { + if runs(&a_marker) > 0 { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + assert_eq!(runs(&a_marker), 1, "control: project A's first command runs A's git"); + ops::vcs::vcs_status(&host, "c").await.unwrap(); + ops::vcs::vcs_remotes(&host, "c", None).await.unwrap(); + std::fs::remove_file(&gate).unwrap(); + two_commands.await.unwrap().unwrap(); + + assert_eq!(runs(&a_marker), 2, "project A's second command lost A's git once window C ran git"); + assert_eq!(runs(&c_marker), 0, "project C has no git setting but ran A's relative tools/git"); + host.shutdown().await; +} + +/// An agent task opens repositories of its own (the project's, then its worktree): their git is +/// the project's too. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_agent_task_worktree_runs_the_project_git() { + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let host = host(&base); + let root = base.join("a"); + let marker = base.join("a.marker"); + repo_with_wrapper(&root, &marker, &base.join("no-gate")); + let real = ide_vcs::detected_git_executable().unwrap(); + let commit = std::process::Command::new(&real) + .arg("-C") + .arg(&root) + .args(["-c", "user.name=t", "-c", "user.email=t@example.test", "-c", "commit.gpgsign=false"]) + .args(["commit", "-q", "--allow-empty", "-m", "init"]) + .output() + .unwrap(); + assert!(commit.status.success(), "{}", String::from_utf8_lossy(&commit.stderr)); + let wrapper = root.join("tools/git"); + std::fs::write(root.join(".openidea/settings.toml"), format!("[vcs.git]\nexecutable = {wrapper:?}\n")).unwrap(); + host.open_project("a", &root).unwrap(); + host.set_project_trust(&root, true, false).await.unwrap(); + + let task = ops::agent::agent_create( + &host, + "a", + ide_agent::NewAgentTask { + prompt: ide_agent::AgentPrompt { text: "Say hi".into(), ..Default::default() }, + provider: "codex".into(), + isolation: ide_agent::Isolation::Worktree, + idle: true, + ..Default::default() + }, + ) + .await + .unwrap(); + assert!(task.cwd.0.join(".git").exists(), "the task has its worktree"); + let created = runs(&marker); + assert!(created > 0, "creating the task's worktree ran another git than the project's"); + + ops::agent::agent_delete(&host, "a", task.id, true).await.unwrap(); + assert!(runs(&marker) > created, "removing the task's worktree ran another git than the project's"); + host.shutdown().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn restricted_status_does_not_select_the_project_git_for_other_windows() { + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let host = host(&base); let root = base.join("malicious"); std::fs::create_dir_all(root.join(".openidea")).unwrap(); let marker = base.join("git.marker"); diff --git a/crates/ide-host/tests/trust_vcs_sweep.rs b/crates/ide-host/tests/trust_vcs_sweep.rs index 68c40c5fed..36f1bcf344 100644 --- a/crates/ide-host/tests/trust_vcs_sweep.rs +++ b/crates/ide-host/tests/trust_vcs_sweep.rs @@ -326,7 +326,7 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() { }), ), // Last: it rewrites nothing of an existing repository, but it does touch it. - call!("vcs_init", "", vcs::vcs_init(host, project.root.clone())), + call!("vcs_init", "", vcs::vcs_init(host, w, project.root.clone())), ]; // The sweep covers every `vcs_*` command declared `trust = always`: a newly allowed one fails diff --git a/crates/ide-language/src/lib.rs b/crates/ide-language/src/lib.rs index 4cf4af1f7d..1d41b6a6f0 100644 --- a/crates/ide-language/src/lib.rs +++ b/crates/ide-language/src/lib.rs @@ -156,7 +156,8 @@ pub struct LanguageServerConfig { pub requires_env: Vec, /// Files whose presence marks a workspace root, e.g. `Cargo.toml`; /// `file#table` requires the TOML file to contain that dotted table, e.g. - /// `pyproject.toml#tool.ruff`. + /// `pyproject.toml#tool.ruff`, or the JSON file that dotted key, e.g. + /// `package.json#devDependencies.tailwindcss`. #[serde(default)] pub root_markers: Vec, /// Serve only files below a root marker, not the whole project: a framework's diff --git a/crates/ide-language/src/markers.rs b/crates/ide-language/src/markers.rs index d78ae08ece..752f941a70 100644 --- a/crates/ide-language/src/markers.rs +++ b/crates/ide-language/src/markers.rs @@ -58,11 +58,12 @@ pub fn arduino_sketch_root(project: &Path, path: &Path) -> Option { /// `dir` contains `marker`: a relative path, a file name pattern with one /// `*` (`*.csproj`), or a TOML or JSON file name (no pattern) and a dotted table -/// it must contain (`pyproject.toml#tool.ruff`, `package.json#eslintConfig`). +/// or JSON key it must contain (`pyproject.toml#tool.ruff`, `package.json#eslintConfig`, +/// `package.json#devDependencies.tailwindcss`). fn has_marker(dir: &Path, marker: &str) -> bool { if let Some((file, table)) = marker.split_once('#') { return if file.ends_with(".json") { - has_json_object(&dir.join(file), table) + has_json_key(&dir.join(file), table) } else { has_toml_table(&dir.join(file), table) }; @@ -88,11 +89,12 @@ fn has_toml_table(file: &Path, table: &str) -> bool { table.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(toml::Value::is_table) } -/// `file` parses as JSON and has the dotted object `key` (`eslintConfig`). -fn has_json_object(file: &Path, key: &str) -> bool { +/// `file` parses as JSON and has the dotted `key` with a value other than `null`: +/// an object (`eslintConfig`) or a dependency's version (`dependencies.tailwindcss`). +fn has_json_key(file: &Path, key: &str) -> bool { let Ok(text) = std::fs::read_to_string(file) else { return false }; let Ok(value) = serde_json::from_str::(&text) else { return false }; - key.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(serde_json::Value::is_object) + key.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(|v| !v.is_null()) } /// `path` is (or, after its creation or removal, was) a root marker of the @@ -177,6 +179,20 @@ mod tests { assert!(!is_marker_path(&root.join("svc/setup.cfg"), "pyproject.toml#tool.ruff")); } + #[test] + fn json_markers_need_their_key() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); + let marker = "package.json#devDependencies.tailwindcss"; + std::fs::write(dir.join("package.json"), r#"{"devDependencies": {"vite": "^7.0.0"}}"#).unwrap(); + assert!(!has_marker(dir, marker)); + std::fs::write(dir.join("package.json"), r#"{"devDependencies": {"tailwindcss": "^4.1.0"}}"#).unwrap(); + assert!(has_marker(dir, marker) && !has_marker(dir, "package.json#dependencies.tailwindcss")); + std::fs::write(dir.join("package.json"), r#"{"eslintConfig": null}"#).unwrap(); + assert!(!has_marker(dir, "package.json#eslintConfig")); + assert!(is_marker_path(&dir.join("package.json"), marker)); + } + #[test] fn patterns_match_file_names() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-language/src/registry.rs b/crates/ide-language/src/registry.rs index 1ed493dd4e..6bb321416f 100644 --- a/crates/ide-language/src/registry.rs +++ b/crates/ide-language/src/registry.rs @@ -715,9 +715,20 @@ mod tests { // it); before the HTML server (hover, rename and symbols take the first). assert_eq!( names("typescript"), - ["vtsls", "typescript-language-server", "angular-language-server", "oxlint", "eslint"] + [ + "vtsls", + "typescript-language-server", + "angular-language-server", + "oxlint", + "eslint", + "biome", + "tailwindcss-language-server" + ] + ); + assert_eq!( + names("html"), + ["angular-language-server", "vscode-html-language-server", "tailwindcss-language-server"] ); - assert_eq!(names("html"), ["angular-language-server", "vscode-html-language-server"]); for lang in ["typescript", "html"] { let cfg = reg.get(&LanguageId::new(lang)).unwrap(); let angular = cfg.language_servers.iter().find(|s| s.name == "angular-language-server").unwrap(); @@ -744,6 +755,34 @@ mod tests { } } + #[test] + fn biome_lints_files_below_its_config_or_installation() { + let reg = reg(); + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + for dir in ["apps/web/src", "apps/admin/node_modules/@biomejs/biome", "apps/api"] { + std::fs::create_dir_all(root.join(dir)).unwrap(); + } + std::fs::write(root.join("apps/web/biome.jsonc"), "{}").unwrap(); + for lang in + ["javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc", "css", "graphql"] + { + let cfg = reg.get(&LanguageId::new(lang)).unwrap(); + let biome = cfg.language_servers.iter().find(|s| s.name == "biome").unwrap(); + assert_eq!( + (biome.command.as_str(), biome.args.as_slice()), + ("biome", ["lsp-proxy".to_string()].as_slice()) + ); + assert!(biome.require_root_marker && !biome.fallback, "{lang}"); + // Reformat Code runs `biome format`: the server's formatting would race the language's own. + assert_eq!(biome.features, ["code-action", "diagnostics"], "{lang}"); + let served = |file: &str| crate::marked_root(Some(root), &root.join(file), &biome.root_markers); + assert_eq!(served("apps/web/src/main.ts"), Some(root.join("apps/web")), "{lang}"); + assert_eq!(served("apps/admin/main.ts"), Some(root.join("apps/admin")), "{lang}"); + assert_eq!(served("apps/api/main.ts"), None, "{lang}"); + } + } + #[test] fn eslint_serves_js_files_only_below_its_config() { let reg = reg(); @@ -771,6 +810,60 @@ mod tests { } } + #[test] + fn tailwind_serves_web_files_only_in_tailwind_projects() { + let reg = reg(); + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + for dir in ["v3/src", "v4/src", "plain/src"] { + std::fs::create_dir_all(root.join(dir)).unwrap(); + } + std::fs::write(root.join("v3/tailwind.config.js"), "module.exports = {};").unwrap(); + std::fs::write(root.join("v4/package.json"), r#"{"devDependencies": {"tailwindcss": "^4.1.0"}}"#).unwrap(); + std::fs::write(root.join("plain/package.json"), r#"{"devDependencies": {"vite": "^7.0.0"}}"#).unwrap(); + for lang in + ["html", "css", "javascript", "javascriptreact", "typescript", "typescriptreact", "vue", "svelte", "astro"] + { + let cfg = reg.get(&LanguageId::new(lang)).unwrap(); + // Last: the language's own servers answer hover first. + let tailwind = cfg.language_servers.last().unwrap(); + assert_eq!(tailwind.name, "tailwindcss-language-server", "{lang}"); + assert_eq!(tailwind.args, ["--stdio"], "{lang}"); + assert!(tailwind.require_root_marker && !tailwind.fallback, "{lang}"); + let served = |file: &str| crate::marked_root(Some(root), &root.join(file), &tailwind.root_markers); + assert_eq!(served("v3/src/app.css"), Some(root.join("v3")), "{lang}"); + assert_eq!(served("v4/src/app.css"), Some(root.join("v4")), "{lang}"); + assert_eq!(served("plain/src/app.css"), None, "{lang}: package.json without tailwindcss"); + } + } + + #[test] + fn stylelint_serves_style_sheets_only_below_its_config() { + let reg = reg(); + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + for dir in ["apps/web/src", "apps/admin/src", "apps/api"] { + std::fs::create_dir_all(root.join(dir)).unwrap(); + } + std::fs::write(root.join("apps/web/stylelint.config.mjs"), "export default {};").unwrap(); + std::fs::write(root.join("apps/admin/package.json"), r#"{"stylelint": {"extends": []}}"#).unwrap(); + std::fs::write(root.join("apps/api/package.json"), r#"{"name": "api"}"#).unwrap(); + for lang in ["css", "scss", "less"] { + let cfg = reg.get(&LanguageId::new(lang)).unwrap(); + let stylelint = cfg.language_servers.iter().find(|s| s.name == "stylelint").unwrap(); + assert_eq!(stylelint.command, "stylelint-language-server", "{lang}"); + assert!(stylelint.require_root_marker && !stylelint.fallback, "{lang}"); + assert_eq!(stylelint.features, ["code-action", "diagnostics"], "{lang}"); + // The server lints only the languages in `validate` (CSS alone by default). + let validate = stylelint.settings.as_ref().unwrap().get("validate").unwrap(); + assert_eq!(validate, &serde_json::json!(["css", "scss", "less"]), "{lang}"); + let served = |file: &str| crate::marked_root(Some(root), &root.join(file), &stylelint.root_markers); + assert_eq!(served("apps/web/src/app.css"), Some(root.join("apps/web")), "{lang}"); + assert_eq!(served("apps/admin/src/app.css"), Some(root.join("apps/admin")), "{lang}"); + assert_eq!(served("apps/api/app.css"), None, "{lang}: package.json without stylelint"); + } + } + #[test] fn laravel_lsp_serves_php_files_only_below_artisan() { let reg = reg(); diff --git a/crates/ide-lsp/src/jdtls.rs b/crates/ide-lsp/src/jdtls.rs index 689abd96d7..c29bf2baaf 100644 --- a/crates/ide-lsp/src/jdtls.rs +++ b/crates/ide-lsp/src/jdtls.rs @@ -21,6 +21,7 @@ const GENERATED_SOURCES: &str = "openidea.java.generatedSources"; pub(crate) mod configuration; pub(crate) mod exception_breakpoints; +mod exception_type; mod extract_interface; mod formatter; mod generated; diff --git a/crates/ide-lsp/src/jdtls/exception_type.rs b/crates/ide-lsp/src/jdtls/exception_type.rs new file mode 100644 index 0000000000..675ed1da94 --- /dev/null +++ b/crates/ide-lsp/src/jdtls/exception_type.rs @@ -0,0 +1,38 @@ +//! The exception class at a caret, for the exception breakpoint intention, through the +//! app-owned JDT extension (`java/java-usages`). +use super::COMMAND_TIMEOUT; +use crate::LspManager; +use crate::types::ExceptionClassRef; +use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Pos}; +use serde_json::json; + +const EXCEPTION_TYPE: &str = "openidea.java.exceptionType"; + +impl LspManager { + /// The Throwable class the caret at `pos` names; `None` when there is none, or when no + /// server of the document has the command. + pub async fn exception_class_at( + &self, + doc: DocId, + pos: Pos, + cancel: CancellationToken, + ) -> IdeResult> { + let snap = self.snapshot(doc)?; + let mut targets = self.ready_targets(&snap.servers, |c| c.commands().iter().any(|c| c == EXCEPTION_TYPE)).await; + if targets.is_empty() { + return Ok(None); + } + let t = targets.swap_remove(0); + let at = snap.position(&t, pos); + let params = json!({ + "command": EXCEPTION_TYPE, + "arguments": [snap.uri, at.line, at.character], + }); + let found: Option = + self.call(&t, "workspace/executeCommand", params, Some(&cancel), COMMAND_TIMEOUT).await?; + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + Ok(found) + } +} diff --git a/crates/ide-lsp/src/types.rs b/crates/ide-lsp/src/types.rs index 3d433e3af9..ddb83ffa1a 100644 --- a/crates/ide-lsp/src/types.rs +++ b/crates/ide-lsp/src/types.rs @@ -467,6 +467,16 @@ pub struct HierarchyMember { pub abstractable: bool, } +/// The exception class a caret names: a reference to it, its declaration, or a throw of it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ExceptionClassRef { + /// The binary name (`app.Outer$Failure`), as exception breakpoints take it. + pub qualified_name: String, + /// The simple name (`Failure`). + pub display_name: String, +} + /// The class at a position and what can move: pull-up destinations, or the subclasses /// members are pushed into. #[derive(Clone, Debug, Serialize, Deserialize, Type)] diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index b545f691f0..ae4e48ffe6 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -3770,6 +3770,36 @@ async fn exception_breakpoints_send_the_whole_list_and_decode_states() { ); } +#[tokio::test(flavor = "multi_thread")] +async fn exception_class_at_asks_the_extension_and_is_none_without_it() { + let mut caps = incremental_caps(); + caps["executeCommandProvider"] = json!({"commands": ["openidea.java.exceptionType"]}); + let h = harness_for("java", "java", &[("jdtls", caps)], &[]); + let (doc, path) = h.open("Main.java", "class Main {\n void f() { throw new Failure(); }\n}"); + h.wait_status("jdtls", ServerStatus::Ready).await; + let s = h.launcher.state("jdtls"); + s.respond("workspace/executeCommand", json!({"qualifiedName": "app.Main$Failure", "displayName": "Failure"})); + let found = h.mgr.exception_class_at(doc, Pos::new(1, 23), Default::default()).await.unwrap(); + assert_eq!( + found, + Some(ide_lsp::types::ExceptionClassRef { + qualified_name: "app.Main$Failure".into(), + display_name: "Failure".into() + }) + ); + let asked = s.requested("workspace/executeCommand"); + assert_eq!(asked[0]["command"], "openidea.java.exceptionType"); + assert_eq!(asked[0]["arguments"], json!([uri_of(&path), 1, 23])); + s.respond("workspace/executeCommand", json!(null)); + assert_eq!(h.mgr.exception_class_at(doc, Pos::new(0, 1), Default::default()).await.unwrap(), None); + + let plain = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]); + let (doc, _) = plain.open("Main.java", "class Main {}"); + plain.wait_status("jdtls", ServerStatus::Ready).await; + assert_eq!(plain.mgr.exception_class_at(doc, Pos::new(0, 7), Default::default()).await.unwrap(), None); + assert!(plain.launcher.state("jdtls").requested("workspace/executeCommand").is_empty()); +} + #[tokio::test(flavor = "multi_thread")] async fn debug_server_port_maps_to_module() { let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]); diff --git a/crates/ide-lsp/tests/real_servers.rs b/crates/ide-lsp/tests/real_servers.rs index c12e476fbe..0a52a5d160 100644 --- a/crates/ide-lsp/tests/real_servers.rs +++ b/crates/ide-lsp/tests/real_servers.rs @@ -947,6 +947,73 @@ async fn angular_language_server_end_to_end() { tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap(); } +/// The Tailwind CSS server on `fixtures/tailwind-app` (Tailwind 4, `@theme` colours), with +/// the built-in definitions: class completion in JSX and `@apply`, hover with the generated +/// CSS, and the class conflict warning. Set `OPENIDEA_TEST_NPM_TOOLS` to a dir with +/// `npm i @tailwindcss/language-server`; the fixture's own `tailwindcss` isn't needed. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "requires @tailwindcss/language-server (OPENIDEA_TEST_NPM_TOOLS)"] +async fn tailwindcss_language_server_end_to_end() { + let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS")); + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().canonicalize().unwrap(); + let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/tailwind-app"); + for file in ["package.json", "index.html", "src/app.css", "src/App.tsx"] { + std::fs::create_dir_all(root.join(file).parent().unwrap()).unwrap(); + std::fs::copy(fixture.join(file), root.join(file)).unwrap(); + } + let builtin = LanguageRegistry::load(None).unwrap(); + let languages = ["typescriptreact", "css"].map(|id| { + let mut cfg = builtin.get(&LanguageId::new(id)).unwrap(); + cfg.language_servers.retain(|s| s.name == "tailwindcss-language-server"); + let bin = tools.join("node_modules/.bin/tailwindcss-language-server"); + cfg.language_servers[0].command = bin.to_string_lossy().into_owned(); + cfg + }); + let (mgr, events) = manager(&root, LanguageRegistry::from_configs(languages.to_vec())); + let (tsx, css) = (DocId::next(), DocId::next()); + let tsx_path = root.join("src/App.tsx"); + let css_path = root.join("src/app.css"); + let tsx_text = std::fs::read_to_string(&tsx_path).unwrap(); + let css_text = std::fs::read_to_string(&css_path).unwrap(); + mgr.did_open(tsx, &tsx_path, &LanguageId::new("typescriptreact"), 1, &tsx_text); + mgr.did_open(css, &css_path, &LanguageId::new("css"), 1, &css_text); + let at = |text: &str, needle: &str, offset: usize| { + let (line, l) = text.lines().enumerate().find(|(_, l)| l.contains(needle)).unwrap(); + Pos::new(line as u32, (l.find(needle).unwrap() + offset) as u32) + }; + + // The project's own `@theme` colour, in `className` and after `@apply`. + let in_class = at(&tsx_text, "className=\"flex flex-col", "className=\"".len()); + let in_apply = at(&css_text, "@apply rounded-md", "@apply ".len()); + for (doc, pos) in [(tsx, in_class), (css, in_apply)] { + retry("class completion", Duration::from_secs(60), || { + let mgr = mgr.clone(); + async move { + let list = mgr.completion(doc, pos, None, Default::default()).await.ok()?; + list.items.iter().any(|i| i.label == "bg-brand-500").then_some(()) + } + }) + .await; + } + let hover = mgr.hover(tsx, at(&tsx_text, "bg-white", 1), Default::default()).await.unwrap().unwrap(); + assert!(hover.contents.value.contains("background-color"), "{}", hover.contents.value); + let hover = mgr.hover(tsx, at(&tsx_text, "text-brand-700", 1), Default::default()).await.unwrap().unwrap(); + assert!(hover.contents.value.contains("--color-brand-700"), "{}", hover.contents.value); + + // `flex block`: both set `display`. + retry("class conflict", Duration::from_secs(30), || { + let found = events.lock().iter().any(|e| { + matches!(e, IdeEvent::Diagnostics { path, items, .. } + if path.ends_with("src/App.tsx") + && items.iter().any(|d| d.message.contains("applies the same CSS properties"))) + }); + async move { found.then_some(()) } + }) + .await; + tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap(); +} + /// A notebook's code cells on basedpyright and Ruff (LSP 3.17 notebook sync): names flow from /// earlier cells, IPython magics parse, and locations and diagnostics name the cells. #[tokio::test(flavor = "multi_thread")] diff --git a/crates/ide-plugin/tests/fixtures/agent-skills/plugin.toml b/crates/ide-plugin/tests/fixtures/agent-skills/plugin.toml new file mode 100644 index 0000000000..f0cff44450 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/agent-skills/plugin.toml @@ -0,0 +1,9 @@ +id = "test.agent-skills" +name = "Agent Skills Fixture" +version = "1.0.0" +description = "Declarative plugin contributing an agent skill." +authors = ["OpenIDEA contributors"] +engines.openidea = "^1.15" + +[[contributes.skills]] +path = "skills/release-notes/SKILL.md" diff --git a/crates/ide-plugin/tests/fixtures/agent-skills/skills/release-notes/SKILL.md b/crates/ide-plugin/tests/fixtures/agent-skills/skills/release-notes/SKILL.md new file mode 100644 index 0000000000..59d9f64526 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/agent-skills/skills/release-notes/SKILL.md @@ -0,0 +1,7 @@ +--- +name: release-notes +description: Draft concise release notes from merged commits and pull requests. +argument-hint: "[tag]" +--- + +Summarize user-visible changes since the given release tag using `references/template.md`. diff --git a/crates/ide-plugin/tests/fixtures/agent-skills/skills/release-notes/references/template.md b/crates/ide-plugin/tests/fixtures/agent-skills/skills/release-notes/references/template.md new file mode 100644 index 0000000000..ffffc6ebe0 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/agent-skills/skills/release-notes/references/template.md @@ -0,0 +1,7 @@ +## Added + +- Summary of user-facing features. + +## Fixed + +- Summary of resolved bugs. diff --git a/crates/ide-run/src/config.rs b/crates/ide-run/src/config.rs index cf40ffc931..8a306f0b28 100644 --- a/crates/ide-run/src/config.rs +++ b/crates/ide-run/src/config.rs @@ -118,6 +118,8 @@ struct FileConfig { #[serde(alias = "stopCommand")] stop_command: Option, target: Option, + #[serde(alias = "testRunner")] + test_runner: Option, } pub(crate) fn slug(s: &str) -> String { @@ -183,6 +185,7 @@ fn convert(configs: Vec, local: bool) -> Vec { emulate_terminal: c.emulate_terminal, stop_command: non_empty(c.stop_command), target: non_empty(c.target), + test_runner: non_empty(c.test_runner), }, }); } @@ -298,6 +301,9 @@ fn to_table(c: &RunConfig) -> Table { if let Some(target) = &x.target { t.insert("target", value(target)); } + if let Some(runner) = &x.test_runner { + t.insert("test-runner", value(runner)); + } t } diff --git a/crates/ide-run/src/detect.rs b/crates/ide-run/src/detect.rs index f53738bc12..e319222fc3 100644 --- a/crates/ide-run/src/detect.rs +++ b/crates/ide-run/src/detect.rs @@ -243,8 +243,53 @@ pub(crate) fn is_test_script(name: &str) -> bool { matches!(name, "test" | "vitest" | "jest") || name.starts_with("test:") } -fn push_scripts(pkg: &Json, pm: &str, prefix: Option<&str>, cwd: Option, out: &mut Vec) { - let Some(scripts) = pkg.get("scripts").and_then(Json::as_object) else { return }; +/// The test runner a `package.json` script starts, when its output and test selection differ +/// from Jest / Vitest's: `playwright test`, `mocha`, or `node --test` (`tsx --test`) with Node's own +/// reporters (the IDE adds its reporter next to them, which a reporter chosen here would clash with). +fn script_test_runner(script: &str) -> Option<&'static str> { + let tokens: Vec<&str> = script.split(|c: char| c.is_whitespace() || matches!(c, '&' | '|' | ';')).collect(); + if tokens.windows(2).any(|w| w[0] == "playwright" && w[1] == "test") { + return Some("playwright"); + } + if tokens.iter().any(|t| matches!(t.rsplit('/').next(), Some("mocha" | "_mocha"))) { + return Some("mocha"); + } + let node = tokens.iter().position(|t| matches!(*t, "node" | "tsx"))?; + // Node's own options: up to the script (`node server.js --test` passes `--test` to the program). + let mut options = Vec::new(); + for t in &tokens[node + 1..] { + let value = options.last().is_some_and(|o| NODE_VALUE_OPTIONS.contains(o)); + if !value && !t.starts_with('-') { + break; + } + options.push(*t); + } + (options.contains(&"--test") && !options.iter().any(|t| t.starts_with("--test-reporter"))).then_some("node-test") +} + +/// Node options whose value is the next argument. +const NODE_VALUE_OPTIONS: &[&str] = + &["-r", "--require", "--import", "--loader", "--experimental-loader", "-C", "--conditions", "--env-file"]; + +const PLAYWRIGHT_CONFIGS: &[&str] = &[ + "playwright.config.ts", + "playwright.config.js", + "playwright.config.mts", + "playwright.config.mjs", + "playwright.config.cts", + "playwright.config.cjs", +]; + +/// Pushes the package's scripts; returns the test runners they start. +fn push_scripts( + pkg: &Json, + pm: &str, + prefix: Option<&str>, + cwd: Option, + out: &mut Vec, +) -> HashSet<&'static str> { + let mut runners = HashSet::new(); + let Some(scripts) = pkg.get("scripts").and_then(Json::as_object) else { return runners }; let mut names: Vec<&String> = scripts.keys().collect(); names.sort(); for script in names { @@ -254,11 +299,39 @@ fn push_scripts(pkg: &Json, pm: &str, prefix: Option<&str>, cwd: Option }; let mut c = config(id, name, "npm", pm, &["run", script]).in_dir(cwd.clone()).debug("js-debug"); c.extras.module = cwd.as_deref().map(ide_core::ipc_path::to_ipc); - if is_test_script(script) { + let runner = scripts[script].as_str().and_then(script_test_runner); + if is_test_script(script) || runner.is_some() { c = c.test(); } + if let Some(runner) = runner { + c.extras.test_runner = Some(runner.to_owned()); + runners.insert(runner); + } out.push(c); } + runners +} + +/// `npx playwright test` for a package with a Playwright configuration that no script runs +/// (`npm init playwright` adds none). +fn push_playwright( + dir: &Path, + runners: &HashSet<&str>, + prefix: Option<&str>, + cwd: Option, + out: &mut Vec, +) { + if runners.contains("playwright") || first_existing(dir, PLAYWRIGHT_CONFIGS).is_none() { + return; + } + let (id, name) = match prefix { + Some(p) => (format!("playwright:{p}"), format!("{p}: playwright test")), + None => ("playwright".to_owned(), "playwright test".to_owned()), + }; + let mut c = config(id, name, "node", "npx", &["playwright", "test"]).in_dir(cwd.clone()).debug("js-debug").test(); + c.extras.module = cwd.as_deref().map(ide_core::ipc_path::to_ipc); + c.extras.test_runner = Some("playwright".to_owned()); + out.push(c); } fn detect_node(root: &Path, out: &mut Vec) { @@ -275,7 +348,10 @@ fn detect_node(root: &Path, out: &mut Vec) { let pm = package_manager(&dir, &pkg); let rel = relative(root, &dir); let label = ide_core::ipc_path::to_ipc(&rel); - push_scripts(&pkg, pm, (dir != root).then_some(label.as_str()), (dir != root).then_some(rel), out); + let prefix = (dir != root).then_some(label.as_str()); + let cwd = (dir != root).then_some(rel); + let runners = push_scripts(&pkg, pm, prefix, cwd.clone(), out); + push_playwright(&dir, &runners, prefix, cwd, out); for member_dir in ide_core::project_roots::node_workspace_members(&dir) { if !covered.insert(member_dir.clone()) { continue; @@ -288,7 +364,8 @@ fn detect_node(root: &Path, out: &mut Vec) { .map(str::to_owned) .unwrap_or_else(|| ide_core::ipc_path::to_ipc(&rel)); let name = if dir == root { name } else { format!("{label}:{name}") }; - push_scripts(&member, pm, Some(&name), Some(rel), out); + let runners = push_scripts(&member, pm, Some(&name), Some(rel.clone()), out); + push_playwright(&member_dir, &runners, Some(&name), Some(rel), out); } } } diff --git a/crates/ide-run/src/lib.rs b/crates/ide-run/src/lib.rs index e1a0807c03..3278f7dbbc 100644 --- a/crates/ide-run/src/lib.rs +++ b/crates/ide-run/src/lib.rs @@ -182,6 +182,12 @@ pub struct RunExtras { #[serde(default, skip_serializing_if = "Option::is_none")] #[specta(optional)] pub target: Option, + /// The test framework a test configuration runs when detection recognised one that the + /// command line doesn't name (a `package.json` script running `playwright test`): picks the + /// test output parser and how a single test is selected. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub test_runner: Option, } impl Default for RunExtras { @@ -205,6 +211,7 @@ impl Default for RunExtras { emulate_terminal: false, stop_command: None, target: None, + test_runner: None, } } } diff --git a/crates/ide-run/tests/detect.rs b/crates/ide-run/tests/detect.rs index 86ecaaf278..a80269dde4 100644 --- a/crates/ide-run/tests/detect.rs +++ b/crates/ide-run/tests/detect.rs @@ -51,6 +51,61 @@ fn npm_scripts_with_lockfile_package_manager() { assert!(find(&c, "npm:test:e2e").is_test); } +#[test] +fn playwright_scripts_and_configs() { + let dir = project(&[ + ("package.json", r#"{"scripts":{"e2e":"cross-env CI=1 playwright test --project=chromium","test":"vitest"}}"#), + ("playwright.config.ts", ""), + ("site/package.json", r#"{"devDependencies":{"@playwright/test":"^1.56.0"}}"#), + ("site/playwright.config.ts", ""), + ]); + let c = detect(dir.path()); + let e2e = find(&c, "npm:e2e"); + assert!(e2e.is_test); + assert_eq!(e2e.extras.test_runner.as_deref(), Some("playwright")); + assert_eq!(find(&c, "npm:test").extras.test_runner, None); + // The root's script runs Playwright already; the nested package has none. + assert!(!ids(&c).contains(&"playwright")); + let site = find(&c, "playwright:site"); + assert_eq!(cmdline(site), "npx playwright test"); + assert_eq!(site.name, "site: playwright test"); + assert!(site.is_test && site.detected); + assert_eq!(site.kind, "node"); + assert_eq!(site.cwd.as_deref(), Some(Path::new("site"))); + assert_eq!(site.extras.test_runner.as_deref(), Some("playwright")); + assert_eq!(site.debug_adapter.as_deref(), Some("js-debug")); +} + +#[test] +fn node_test_scripts() { + let dir = project(&[( + "package.json", + r#"{"scripts":{"test":"node --import tsx --test","check":"tsx --test src/","tap":"node --test --test-reporter=tap","start":"node server.js --test"}}"#, + )]); + let c = detect(dir.path()); + assert_eq!(find(&c, "npm:test").extras.test_runner.as_deref(), Some("node-test")); + let check = find(&c, "npm:check"); + assert!(check.is_test); + assert_eq!(check.extras.test_runner.as_deref(), Some("node-test")); + // A reporter of its own: run as written, without the IDE's. + assert_eq!(find(&c, "npm:tap").extras.test_runner, None); + assert_eq!(find(&c, "npm:start").extras.test_runner, None); +} + +#[test] +fn mocha_scripts() { + let dir = project(&[( + "package.json", + r#"{"scripts":{"spec":"mocha --recursive","test":"nyc ./node_modules/.bin/mocha","lint":"eslint mocha.config.js"}}"#, + )]); + let c = detect(dir.path()); + let spec = find(&c, "npm:spec"); + assert!(spec.is_test); + assert_eq!(spec.extras.test_runner.as_deref(), Some("mocha")); + assert_eq!(find(&c, "npm:test").extras.test_runner.as_deref(), Some("mocha")); + assert!(!find(&c, "npm:lint").is_test); +} + #[test] fn package_manager_selection() { for (lock, pm) in [("yarn.lock", "yarn"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("package-lock.json", "npm")] { diff --git a/crates/ide-sdk/Cargo.toml b/crates/ide-sdk/Cargo.toml index 6ccbc17d4a..745db57d30 100644 --- a/crates/ide-sdk/Cargo.toml +++ b/crates/ide-sdk/Cargo.toml @@ -6,6 +6,7 @@ edition.workspace = true license.workspace = true [dependencies] +dirs.workspace = true dunce.workspace = true ignore.workspace = true ide-core.workspace = true diff --git a/crates/ide-sdk/src/apply.rs b/crates/ide-sdk/src/apply.rs index f044f8c1fe..ecb6d1b138 100644 --- a/crates/ide-sdk/src/apply.rs +++ b/crates/ide-sdk/src/apply.rs @@ -537,6 +537,42 @@ pub fn configure_gradle_runtime(cfg: &mut LanguageServerConfig, root: &Path, bui merge(cfg.settings.get_or_insert_with(|| json!({})), json!({"java": {"import": {"gradle": gradle}}})); } +/// Gradle's Eclipse model, which jdtls imports the build through, leaves out project dependencies +/// a source set only compiles against (`compileOnly(project(":a"))`) and marks some as test-only, +/// so their classes don't resolve in the editor although Gradle compiles. jdtls's Gradle import +/// runs an init script that adds them, written to the first of `dirs` whose path has no +/// whitespace: Buildship stores the import's arguments joined by spaces and splits them again, +/// so `Application Support` would break the path. The name carries the script's hash, so +/// releases running side by side never overwrite each other's script. +pub fn configure_gradle_classpath(cfg: &mut LanguageServerConfig, dirs: &[PathBuf]) { + const SCRIPT: &str = include_str!("gradle-classpath.init.gradle"); + if cfg.name != "jdtls" { + return; + } + let mut hash = 0xcbf29ce484222325u64; + for byte in SCRIPT.bytes() { + hash = (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3); + } + let name = format!("openidea-classpath-{hash:016x}.init.gradle"); + let Some(script) = dirs + .iter() + .map(|dir| dir.join(&name)) + .filter(|script| !script.to_string_lossy().contains(char::is_whitespace)) + .find(|script| { + std::fs::read(script).ok().as_deref() == Some(SCRIPT.as_bytes()) + || script.parent().is_some_and(|dir| std::fs::create_dir_all(dir).is_ok()) + && std::fs::write(script, SCRIPT).is_ok() + }) + else { + tracing::warn!("no directory without spaces for the Gradle classpath init script: {dirs:?}"); + return; + }; + merge( + cfg.settings.get_or_insert_with(|| json!({})), + json!({"java": {"import": {"gradle": {"arguments": ["--init-script", script.to_string_lossy()]}}}}), + ); +} + /// Settings › Build Tools › Maven › Automatically download sources and Always update /// snapshots → jdtls `java.maven.downloadSources` / `java.maven.updateSnapshots`. pub fn configure_maven_sources(cfg: &mut LanguageServerConfig, s: &Settings) { @@ -1424,6 +1460,14 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root if name == astro::SERVER { astro::configure(cfg, root, server_root, s); } + // Biome lints with the project's own version (its configuration follows that version's + // schema); an explicit executable setting still wins. + if name == "biome" + && cfg.command == "biome" + && let Some(bin) = crate::npm::project_bin("biome", root, server_root) + { + cfg.command = bin.to_string_lossy().into_owned(); + } if name == crate::arduino::SERVER { crate::arduino::configure(cfg, root, server_root, s); } @@ -2521,6 +2565,33 @@ mod maven_linkage_tests { assert_eq!(gradle["user"]["home"], resolved("/caches/gradle")); } + #[test] + fn gradle_import_adds_the_projects_a_source_set_compiles_against() { + let temp = tempfile::tempdir().unwrap(); + let spaced = temp.path().join("Application Support").join("gradle"); + let plain = temp.path().join("cache").join("gradle"); + let mut cfg = custom_server("jdtls", &LanguageServerSettings::default()); + cfg.settings = Some(json!({"java": {"import": {"gradle": {"enabled": true}}}})); + configure_gradle_classpath(&mut cfg, &[spaced.clone(), plain.clone()]); + let gradle = &cfg.settings.as_ref().unwrap()["java"]["import"]["gradle"]; + assert_eq!(gradle["enabled"], json!(true), "merged, not replaced"); + let args = gradle["arguments"].as_array().unwrap(); + assert_eq!(args[0], json!("--init-script")); + let script = PathBuf::from(args[1].as_str().unwrap()); + assert_eq!(script.parent(), Some(plain.as_path()), "Buildship splits arguments at spaces"); + assert!(!spaced.exists()); + let text = std::fs::read_to_string(&script).unwrap(); + assert!(text.contains("compileClasspath") && text.contains("whenMerged")); + + let mut other = custom_server("pyright", &LanguageServerSettings::default()); + configure_gradle_classpath(&mut other, &[plain]); + assert!(other.settings.is_none(), "only jdtls imports Gradle builds"); + + let mut nowhere = custom_server("jdtls", &LanguageServerSettings::default()); + configure_gradle_classpath(&mut nowhere, &[spaced]); + assert!(nowhere.settings.is_none(), "no usable directory: the import runs without it"); + } + #[test] fn gradle_import_of_a_gradle_build_runs_on_the_project_jdk_like_the_ides_builds() { let temp = tempfile::tempdir().unwrap(); @@ -2743,3 +2814,42 @@ mod conda_activation_tests { assert_eq!(conda_activation(&plain.join("bin").join("python"), "bash", Some(conda), None), None); } } + +#[cfg(test)] +mod biome_tests { + use super::*; + + fn binary(dir: &Path) -> PathBuf { + let bin = dir.join(if cfg!(windows) { "biome.cmd" } else { "biome" }); + std::fs::create_dir_all(dir).unwrap(); + std::fs::write(&bin, "").unwrap(); + #[cfg(unix)] + std::fs::set_permissions(&bin, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap(); + bin + } + + #[test] + fn biome_runs_the_projects_own_biome_unless_an_executable_is_set() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("project"); + let web = root.join("apps/web"); + let configured = |s: &Settings, server_root: &Path| { + let mut cfg = custom_server("biome", &LanguageServerSettings::default()); + cfg.command = "biome".into(); + configure_server(&mut cfg, &root, server_root, s); + PathBuf::from(cfg.command) + }; + let workspace = binary(&root.join("node_modules/.bin")); + assert_eq!(configured(&Settings::default(), &web), workspace); + let member = binary(&web.join("node_modules/.bin")); + assert_eq!(configured(&Settings::default(), &web), member); + // Outside the project: not the project's installation. + binary(&tmp.path().join("node_modules/.bin")); + assert_eq!(configured(&Settings::default(), &tmp.path().join("other")), PathBuf::from("biome")); + let custom = binary(&tmp.path().join("custom")); + let mut s = Settings::default(); + s.tools + .insert("biome".into(), ide_core::settings::ToolSettings { path: custom.to_string_lossy().into_owned() }); + assert_eq!(configured(&s, &web), custom); + } +} diff --git a/crates/ide-sdk/src/astro.rs b/crates/ide-sdk/src/astro.rs index ecd06e7a0c..03acea2632 100644 --- a/crates/ide-sdk/src/astro.rs +++ b/crates/ide-sdk/src/astro.rs @@ -1,7 +1,7 @@ //! Astro (Volar) requires a TypeScript language-service library at initialize. use crate::apply::{merge_init_options, setting_path, tsdk}; -use crate::npm::{has_ts_api, own_typescript, package_dir}; +use crate::npm::{has_ts_api, own_typescript, package_dir, project_bin}; use ide_core::settings::Settings; use ide_core::tool_path::{find_command, search_path}; use ide_language::LanguageServerConfig; @@ -20,10 +20,7 @@ pub(crate) fn configure(cfg: &mut LanguageServerConfig, root: &Path, server_root // A project's installation wins over managed / global tools. Explicit // executable settings still win, as they do for other language servers. if cfg.command == SERVER - && let Some(bin) = server_root - .ancestors() - .take_while(|dir| dir.starts_with(root)) - .find_map(|dir| find_command(SERVER, dir.join("node_modules/.bin").as_os_str(), server_root)) + && let Some(bin) = project_bin(SERVER, root, server_root) { cfg.command = bin.to_string_lossy().into_owned(); } diff --git a/crates/ide-sdk/src/gradle-classpath.init.gradle b/crates/ide-sdk/src/gradle-classpath.init.gradle new file mode 100644 index 0000000000..68c89d4a37 --- /dev/null +++ b/crates/ide-sdk/src/gradle-classpath.init.gradle @@ -0,0 +1,37 @@ +// Gradle's Eclipse model leaves out project dependencies a source set only compiles against +// (compileOnly, compileOnlyApi), and marks some as test-only. Add each project the main or test +// compile classpath names, so Java code sees the classes it compiles against. +allprojects { + plugins.withId('java') { + apply plugin: 'eclipse' + eclipse.classpath.file.whenMerged { classpath -> + def projectOf = { dep -> + def path + try { path = dep.path } catch (MissingPropertyException ignored) { path = dep.dependencyProject.path } + rootProject.findProject(path) + } + def wanted = [:] + ['testCompileClasspath', 'compileClasspath'].each { name -> + def configuration = configurations.findByName(name) + if (configuration == null) return + configuration.allDependencies.withType(ProjectDependency).each { dep -> + def target = projectOf(dep) + if (target == null || target == project) return + def eclipseName = target.extensions.findByName('eclipse')?.project?.name ?: target.name + wanted['/' + eclipseName] = name == 'compileClasspath' + } + } + def existing = classpath.entries.findAll { it instanceof org.gradle.plugins.ide.eclipse.model.ProjectDependency } + wanted.each { path, main -> + def entry = existing.find { it.path == path } + if (entry == null) { + entry = new org.gradle.plugins.ide.eclipse.model.ProjectDependency(path) + entry.entryAttributes['without_test_code'] = 'true' + classpath.entries.add(entry) + } + if (main) entry.entryAttributes.remove('test') + else if (!entry.entryAttributes.containsKey('test')) entry.entryAttributes['test'] = 'true' + } + } + } +} diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rs index aba77507c9..26392675f2 100644 --- a/crates/ide-sdk/src/java.rs +++ b/crates/ide-sdk/src/java.rs @@ -1629,7 +1629,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option { install_bundle( data_dir, "java-usages", - "1.16.0", + "1.17.0", include_bytes!("../../../java/java-usages/openidea-java-usages.jar"), ) } diff --git a/crates/ide-sdk/src/jdtls.rs b/crates/ide-sdk/src/jdtls.rs index a8426aa033..021fcde814 100644 --- a/crates/ide-sdk/src/jdtls.rs +++ b/crates/ide-sdk/src/jdtls.rs @@ -287,8 +287,8 @@ pub fn launch_directly(cfg: &mut LanguageServerConfig) { return; } let Some(script) = script_for(cfg) else { return }; - let Some(install) = - jdtls_home(&script).and_then(|h| find_install(&h, std::env::consts::OS, std::env::consts::ARCH)) + let home = jdtls_home(&script); + let Some(install) = home.as_deref().and_then(|h| find_install(h, std::env::consts::OS, std::env::consts::ARCH)) else { return; }; @@ -307,14 +307,60 @@ pub fn launch_directly(cfg: &mut LanguageServerConfig) { cfg.launch_error = Some(error); return; } + let area = home.as_deref().and_then(|home| configuration_area(home, &cfg.args, dirs::cache_dir())); cfg.args = java_args(&install, jdk.major, &cfg.args); + if let Some(area) = area + && let Some(jar) = cfg.args.iter().position(|a| a == "-jar") + { + cfg.args.insert(jar, format!("-Dosgi.configuration.area={}", area.to_string_lossy())); + } cfg.command = java.to_string_lossy().into_owned(); } +/// Equinox extracts bundle files, jdtls's Gradle init scripts among them, into its writable +/// configuration area, `/configuration` unless the launch names one. jdtls passes those +/// scripts to every Gradle import as `--init-script` arguments, and Buildship stores a build's +/// arguments joined by spaces and splits them again. Under a home with spaces (macOS's +/// `Application Support`) each import that sets a Gradle JDK, user home or argument then fails +/// with "The specified initialization script '…/Application' does not exist". Such a home +/// gets an area without spaces in the user's cache directory, one per install. +fn configuration_area(home: &Path, args: &[String], cache: Option) -> Option { + let parsed = split_script_args(args); + let named = parsed.jvm.iter().any(|a| a.starts_with("-Dosgi.configuration.area=")) + || parsed.rest.iter().any(|a| a == "-configuration"); + if named || !home.join("configuration").to_string_lossy().contains(char::is_whitespace) { + return None; + } + let mut hash = 0xcbf29ce484222325u64; + for byte in home.to_string_lossy().bytes() { + hash = (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3); + } + Some(cache?.join("openidea").join("jdtls-configuration").join(format!("{hash:016x}"))) + .filter(|area| !area.to_string_lossy().contains(char::is_whitespace)) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn a_home_with_spaces_gets_a_configuration_area_without_them() { + let cache = Some(PathBuf::from("/cache")); + let spaced = Path::new("/Users/me/Library/Application Support/openidea/tools/jdtls"); + let area = configuration_area(spaced, &[], cache.clone()).unwrap(); + assert!(area.starts_with("/cache/openidea/jdtls-configuration")); + assert_eq!(configuration_area(spaced, &[], cache.clone()), Some(area), "one per install"); + assert_ne!( + configuration_area(Path::new("/opt/My Tools/jdtls"), &[], cache.clone()), + configuration_area(spaced, &[], cache.clone()) + ); + assert_eq!(configuration_area(Path::new("/opt/jdtls"), &[], cache.clone()), None, "the default is fine"); + let own = strings(&["--jvm-arg=-Dosgi.configuration.area=/mine"]); + assert_eq!(configuration_area(spaced, &own, cache.clone()), None, "the user's area stays"); + assert_eq!(configuration_area(spaced, &strings(&["-configuration", "/mine"]), cache), None); + assert_eq!(configuration_area(spaced, &[], Some(PathBuf::from("/My Cache"))), None); + } + fn strings(args: &[&str]) -> Vec { args.iter().map(|s| s.to_string()).collect() } diff --git a/crates/ide-sdk/src/npm.rs b/crates/ide-sdk/src/npm.rs index edd087f9f3..61a27209c4 100644 --- a/crates/ide-sdk/src/npm.rs +++ b/crates/ide-sdk/src/npm.rs @@ -10,6 +10,13 @@ pub(crate) fn has_ts_api(lib: &Path) -> bool { lib.join("typescript.js").is_file() } +/// `command` installed in the project: the nearest `node_modules/.bin` from `server_root` up to `root`. +pub(crate) fn project_bin(command: &str, root: &Path, server_root: &Path) -> Option { + server_root.ancestors().take_while(|dir| dir.starts_with(root)).find_map(|dir| { + ide_core::tool_path::find_command(command, dir.join("node_modules/.bin").as_os_str(), server_root) + }) +} + /// The native executable of TypeScript 7 (`typescript` 7+, whose `tsc` is native, or /// `@typescript/native-preview`'s `tsgo`), from its package directory or its `lib`. /// These packages have no JavaScript API (`lib/typescript.js`); their platform package diff --git a/crates/ide-sdk/src/python.rs b/crates/ide-sdk/src/python.rs index 98466971bb..66a55048af 100644 --- a/crates/ide-sdk/src/python.rs +++ b/crates/ide-sdk/src/python.rs @@ -1,7 +1,7 @@ //! Python environments: creating virtualenvs and managing packages with pip //! (or `uv pip` for environments created by uv, which ship without pip). -use crate::exec::{query_in, stream, which}; +use crate::exec::{query_in, query_in_cancellable, stream, which}; use crate::{Sdk, bin_dir, exe, venv_of}; use ide_core::{CancellationToken, IdeError, IdeResult}; use serde::{Deserialize, Serialize}; @@ -320,6 +320,82 @@ pub fn install_package( stream(&program, &args, dir.as_ref().map(|d| d.path()), &pip_env(python), cancel, on_line).map(|_| ()) } +/// Run by the interpreter itself, so markers and PEP 440 specifiers are judged as pip would: +/// prints, per requirement of `argv[1]` (a JSON list), `null` when satisfied or not applicable +/// there, else `{"installed": }`. +const CHECK_REQUIREMENTS: &str = r#" +import json, re, sys +try: + from packaging.requirements import Requirement +except Exception: + try: + from pip._vendor.packaging.requirements import Requirement + except Exception: + Requirement = None +from importlib import metadata +norm = lambda n: re.sub(r"[-_.]+", "-", n).lower() +installed = {} +for d in metadata.distributions(): + name = d.metadata["Name"] + if name: + installed.setdefault(norm(name), d.version) +out = [] +for line in json.loads(sys.argv[1]): + try: + if Requirement: + r = Requirement(line) + name, spec, applies = r.name, r.specifier, r.marker is None or r.marker.evaluate({"extra": ""}) + else: + # Without packaging only names are compared; a marker can't be judged. + name, spec, applies = re.match(r"[A-Za-z0-9._-]+", line).group(0), None, ";" not in line + version = installed.get(norm(name)) + if not applies or (version is not None and (spec is None or spec.contains(version, prereleases=True))): + out.append(None) + else: + out.append({"installed": version}) + except Exception: + out.append(None) +print(json.dumps(out)) +"#; + +#[derive(Debug, Deserialize, PartialEq)] +pub struct Unsatisfied { + /// The version installed that misses the specifier; `None` when not installed. + pub installed: Option, +} + +/// Which of `requirements` (PEP 508 strings) `python` doesn't satisfy, in order; +/// `None` for satisfied ones, for ones whose marker excludes this interpreter, and +/// for ones it can't parse. +pub fn unsatisfied_requirements( + python: &Path, + requirements: &[&str], + cancel: &CancellationToken, +) -> IdeResult>> { + let list = serde_json::to_string(requirements).map_err(|e| IdeError::internal(e.to_string()))?; + let dir = neutral_dir().ok_or_else(|| IdeError::internal("no temporary directory"))?; + let out = query_in_cancellable( + python, + &["-c", CHECK_REQUIREMENTS, &list], + dir.path(), + &[], + Duration::from_secs(20), + cancel, + ); + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let out = + out.ok_or_else(|| IdeError::unavailable(format!("cannot check requirements with {}", python.display())))?; + let json = out.lines().rev().find(|l| l.starts_with('[')).unwrap_or(""); + let result: Vec> = + serde_json::from_str(json).map_err(|e| IdeError::internal(format!("unexpected output: {e}")))?; + if result.len() != requirements.len() { + return Err(IdeError::internal("unexpected output: wrong number of results")); + } + Ok(result) +} + pub fn uninstall_package( python: &Path, name: &str, diff --git a/crates/ide-sdk/src/tests.rs b/crates/ide-sdk/src/tests.rs index 28786cc04d..6c061a69a8 100644 --- a/crates/ide-sdk/src/tests.rs +++ b/crates/ide-sdk/src/tests.rs @@ -6,6 +6,7 @@ use crate::apply::{ }; use crate::python::parse_pip_list; use crate::{bin_dir, exe, venv_of}; +use ide_core::CancellationToken; use ide_core::settings::Settings; use ide_language::LanguageServerConfig; use ide_run::RunConfig; @@ -3184,3 +3185,46 @@ fn server_command_paths_report_executables_set_for_built_in_servers() { ] ); } + +#[test] +fn unsatisfied_requirements_are_judged_by_the_interpreter() { + let Some(base) = crate::exec::which("python3").or_else(|| crate::exec::which("python")) else { return }; + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("env"); + // System site packages: pip's vendored `packaging` when the base has pip. + let status = std::process::Command::new(base) + .args(["-I", "-m", "venv", "--without-pip", "--system-site-packages"]) + .arg(&home) + .status() + .unwrap(); + assert!(status.success()); + let python = home.join(bin_dir()).join(exe("python")); + let site = std::process::Command::new(&python) + .args(["-c", "import sysconfig; print(sysconfig.get_paths()['purelib'])"]) + .output() + .unwrap(); + let site = std::path::PathBuf::from(String::from_utf8(site.stdout).unwrap().trim()); + let info = site.join("Fake.Dist_Pkg-1.0.dist-info"); + std::fs::create_dir_all(&info).unwrap(); + std::fs::write(info.join("METADATA"), "Metadata-Version: 2.1\nName: Fake.Dist_Pkg\nVersion: 1.0\n").unwrap(); + let packaging = std::process::Command::new(&python) + .args(["-c", "import pip._vendor.packaging.requirements"]) + .status() + .is_ok_and(|s| s.success()); + let cancel = CancellationToken::new(); + let found = crate::python::unsatisfied_requirements( + &python, + &[ + "fake-dist-pkg", + "FAKE_dist.pkg>=0.5", + "fake-dist-pkg>=2", + "openidea-not-installed-xyz[extra]==1", + "openidea-not-installed-xyz; sys_platform == 'nowhere'", + ], + &cancel, + ) + .unwrap(); + let missing = || Some(crate::python::Unsatisfied { installed: None }); + let old = packaging.then(|| crate::python::Unsatisfied { installed: Some("1.0".into()) }); + assert_eq!(found, [None, None, old, missing(), None]); +} diff --git a/crates/ide-tools/src/formatter.rs b/crates/ide-tools/src/formatter.rs index 538d48331f..944c794594 100644 --- a/crates/ide-tools/src/formatter.rs +++ b/crates/ide-tools/src/formatter.rs @@ -62,13 +62,22 @@ fn package_bin(package: &Path, tool: &str) -> IdeResult { Ok(path) } -/// Prettier and Ruff format ranges for some languages (`config.range`); oxfmt formats whole files only. +/// Prettier and Ruff format ranges for some languages (`config.range`); oxfmt and Biome format whole files only. pub fn supports_range(tool: &str, config: &FormatterConfig) -> bool { matches!(tool, "prettier" | "ruff") && config.range } fn is_formatter(tool: &str) -> bool { - crate::registry::find(tool).is_some_and(|t| t.kind == crate::ToolKind::Formatter || t.name == "ruff") + crate::registry::find(tool) + .is_some_and(|t| t.kind == crate::ToolKind::Formatter || matches!(t.name, "ruff" | "biome")) +} + +/// The npm package that provides `tool`'s CLI. +fn npm_package(tool: &str) -> &str { + match tool { + "biome" => "@biomejs/biome", + _ => tool, + } } impl Tools { @@ -81,7 +90,7 @@ impl Tools { if !is_formatter(tool) { return Err(IdeError::unavailable(format!("Unknown external formatter: {tool}"))); } - let package = Path::new("node_modules").join(tool); + let package = Path::new("node_modules").join(npm_package(tool)); let manifest = package.join("package.json"); let (path, node) = if let Some(custom) = custom.filter(|p| p.is_dir()) { (package_bin(custom, tool)?, true) @@ -108,7 +117,7 @@ impl Tools { } /// Every tool resolves its configuration itself. Prettier's project configuration -/// overrides the editor indentation passed here; oxfmt and Ruff read their own +/// overrides the editor indentation passed here; oxfmt, Biome and Ruff read their own /// configuration files. Ruff also discovers the nearest `pyproject.toml`, /// `ruff.toml`, or `.ruff.toml` from the stdin filename. pub fn arguments( @@ -137,6 +146,12 @@ pub fn arguments( } return args; } + if tool == "biome" { + // Biome finds its `biome.json` and ignore files from the file's path itself. + let mut path = OsString::from("--stdin-file-path="); + path.push(file); + return vec!["format".into(), path]; + } if tool == "prettier" { let parser = if config.parser == "markdown" && file.extension().is_some_and(|s| s == "mdx") { "mdx" @@ -323,6 +338,38 @@ mod tests { assert!(unknown.message.contains("Unknown external formatter"), "{}", unknown.message); } + #[test] + fn biome_runs_the_nearest_biomejs_package_with_the_file_path() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + let package = root.join("node_modules/@biomejs/biome"); + std::fs::create_dir_all(package.join("bin")).unwrap(); + std::fs::write(package.join("package.json"), r#"{"bin":{"biome":"bin/biome"}}"#).unwrap(); + std::fs::write(package.join("bin/biome"), "").unwrap(); + std::fs::write(root.join(".prettierignore"), "dist").unwrap(); + let file = root.join("packages/web/src/app.ts"); + let path = std::env::var_os("PATH").unwrap_or_default(); + let tools = Tools::with_paths(root.join("tools"), path, crate::platform::Platform::current()); + + let command = tools.formatter_command("biome", &file, None).unwrap(); + let program = Path::new(command.get_program()).file_stem().unwrap().to_string_lossy().into_owned(); + assert_eq!(program, "node"); + let script: Vec<_> = command.get_args().collect(); + assert_eq!( + Path::new(&script[0]).components().collect::>(), + package.join("bin/biome").components().collect::>() + ); + + let config = FormatterConfig { tool: "prettier".into(), parser: "typescript".into(), range: true }; + let range = + Some(FormatRange { start_offset: 3, end_offset: 9, start_line: 1, start_col: 1, end_line: 1, end_col: 7 }); + let mut stdin_path = OsString::from("--stdin-file-path="); + stdin_path.push(&file); + // No Prettier ignore files or indentation: Biome reads its own configuration. + assert_eq!(arguments("biome", &config, &file, 4, false, range, None), ["format".into(), stdin_path]); + assert!(!supports_range("biome", &config)); + } + #[test] fn ruff_formats_stdin_and_uses_its_config_and_range_flags() { let config = FormatterConfig { tool: "ruff".into(), parser: "python".into(), range: true }; diff --git a/crates/ide-tools/src/process.rs b/crates/ide-tools/src/process.rs index 3d6844c795..279fb01c06 100644 --- a/crates/ide-tools/src/process.rs +++ b/crates/ide-tools/src/process.rs @@ -405,6 +405,13 @@ impl Http { self } + /// Skips `GITHUB_TOKEN` / `GH_TOKEN` / `gh auth token` (e.g. retrying a public GitHub endpoint after HTTP 401). + pub fn without_github_auth(mut self) -> Self { + self.gh = None; + self.explicit_github_token = None; + self + } + fn base(&self, url: &str, cancel: &CancellationToken) -> IdeResult<(Command, Option)> { if cancel.is_cancelled() { return Err(IdeError::cancelled()); diff --git a/crates/ide-tools/src/registry.rs b/crates/ide-tools/src/registry.rs index e4c1deb29f..f9164af39c 100644 --- a/crates/ide-tools/src/registry.rs +++ b/crates/ide-tools/src/registry.rs @@ -201,6 +201,18 @@ pub static TOOLS: &[ToolSpec] = &[ needs: NODE, homepage: "https://oxc.rs/docs/guide/usage/linter", }, + // Linter and formatter: `biome lsp-proxy` lints, and Reformat Code runs `biome format`. + ToolSpec { + name: "biome", + display: "Biome", + kind: LanguageServer, + commands: &["biome"], + method: Method::Npm { packages: &["@biomejs/biome"] }, + fallback: None, + version: ver("biome"), + needs: NODE, + homepage: "https://biomejs.dev", + }, ToolSpec { name: "eslint", display: "ESLint Language Server", @@ -212,6 +224,17 @@ pub static TOOLS: &[ToolSpec] = &[ homepage: "https://github.com/hrsh7th/vscode-langservers-extracted", needs: NODE, }, + ToolSpec { + name: "stylelint", + display: "Stylelint Language Server", + kind: LanguageServer, + commands: &["stylelint-language-server"], + method: Method::Npm { packages: &["@stylelint/language-server"] }, + fallback: None, + version: V, + homepage: "https://github.com/stylelint/vscode-stylelint", + needs: NODE, + }, ToolSpec { name: "rust-analyzer", display: "rust-analyzer", @@ -444,6 +467,18 @@ pub static TOOLS: &[ToolSpec] = &[ homepage: "https://angular.dev/tools/language-service", needs: &[], }, + ToolSpec { + name: "tailwindcss-language-server", + display: "Tailwind CSS Language Server", + kind: LanguageServer, + commands: &["tailwindcss-language-server"], + // Brings Tailwind CSS 3 and 4 for projects whose own `tailwindcss` isn't installed yet. + method: Method::Npm { packages: &["@tailwindcss/language-server"] }, + fallback: None, + version: V, + homepage: "https://github.com/tailwindlabs/tailwindcss-intellisense", + needs: NODE, + }, ToolSpec { name: "graphql-lsp", display: "GraphQL Language Server", @@ -1286,7 +1321,7 @@ mod tests { known.insert((d.adapter.clone(), d.command.clone())); } } - // The host selects the formatter of each file (Prettier or oxfmt) and runs its own CLIs. + // The host selects the formatter of each file (Prettier, oxfmt or Biome) and runs its own CLIs. for t in TOOLS.iter().filter(|t| !matches!(t.kind, Plugin | Formatter | Cli)) { assert!( known.contains(&(t.name.to_string(), t.commands[0].to_string())), diff --git a/crates/ide-vcs/src/cli.rs b/crates/ide-vcs/src/cli.rs index 901fef6a55..d14fe2d7e6 100644 --- a/crates/ide-vcs/src/cli.rs +++ b/crates/ide-vcs/src/cli.rs @@ -40,15 +40,15 @@ impl Drop for TempIndex { } } -/// Explicit git executable from Settings › Version Control › Git (`None` = auto-detect). -static CONFIGURED: std::sync::RwLock> = std::sync::RwLock::new(None); +/// Git executable of the user's global settings (`None` = auto-detect). Never a project's: a +/// project's repositories carry their own ([`crate::Repo::set_git_executable`]). +static DEFAULT: std::sync::RwLock> = std::sync::RwLock::new(None); -/// Sets (or clears, with `None` / an empty path) the git executable to use. -pub fn set_git_executable(path: Option<&Path>) { +/// Sets (or clears, with `None` / an empty path) the git executable of repositories that have +/// none of their own, from the global settings only. +pub fn set_default_git_executable(path: Option<&Path>) { let path = path.filter(|p| !p.as_os_str().is_empty()).map(Path::to_path_buf); - if *CONFIGURED.read().unwrap_or_else(|e| e.into_inner()) != path { - *CONFIGURED.write().unwrap_or_else(|e| e.into_inner()) = path; - } + *DEFAULT.write().unwrap_or_else(|e| e.into_inner()) = path; } /// Environment that routes credential prompts (`ssh` passphrases and host keys, @@ -129,16 +129,20 @@ pub fn detected_git_executable() -> Option { detected_git().map(Path::to_path_buf) } +/// The executable of the repository this thread works in, else the default, else the detected one. pub(crate) fn git_binary() -> IdeResult { - if let Some(configured) = CONFIGURED.read().unwrap_or_else(|e| e.into_inner()).clone() { - return Ok(configured); + if let Some(own) = crate::scoped_git_executable() { + return Ok(own.to_path_buf()); + } + if let Some(default) = DEFAULT.read().unwrap_or_else(|e| e.into_inner()).clone() { + return Ok(default); } detected_git() .map(Path::to_path_buf) .ok_or_else(|| IdeError::unavailable("git executable not found; install git and make sure it is on PATH")) } -/// `git --version` of `executable` (or the configured / detected one), e.g. `git version 2.44.0`. +/// `git --version` of `executable` (or the default / detected one), e.g. `git version 2.44.0`. pub fn git_version(executable: Option<&Path>) -> IdeResult { let exe = match executable.filter(|p| !p.as_os_str().is_empty()) { Some(p) => p.to_path_buf(), diff --git a/crates/ide-vcs/src/commit_message.rs b/crates/ide-vcs/src/commit_message.rs index 0306701cd8..44db15e491 100644 --- a/crates/ide-vcs/src/commit_message.rs +++ b/crates/ide-vcs/src/commit_message.rs @@ -1,4 +1,4 @@ -use crate::{ExecutionScope, Repo, cherry_pick_plan, cli, ops}; +use crate::{Repo, cherry_pick_plan, cli, ops}; use ide_core::workflow_settings::EmptyCherryPickAction; use ide_core::{CancellationToken, IdeError, IdeResult, IpcPath}; use notify::event::{MetadataKind, ModifyKind}; @@ -9,7 +9,6 @@ use std::collections::BTreeSet; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; -use std::sync::atomic::Ordering; use std::sync::{Arc, Mutex}; const MESSAGE_LIMIT: usize = 1 << 20; @@ -211,7 +210,7 @@ impl Repo { cancel: &CancellationToken, changed: impl Fn() + Send + 'static, ) -> IdeResult { - let _scope = ExecutionScope::enter(self.execution_allowed.load(Ordering::Acquire)); + let _scope = self.execution_scope(); let [git_dir, common_dir] = self.metadata_dirs()?; let mut files = BTreeSet::from([git_dir.join("HEAD"), git_dir.join("config.worktree"), common_dir.join("config")]); @@ -248,7 +247,7 @@ impl Repo { } fn pending_apply(&self, cancel: &CancellationToken) -> Option { - let _scope = ExecutionScope::enter(self.execution_allowed.load(Ordering::Acquire)); + let _scope = self.execution_scope(); let (kind, marker, revision) = self.apply_head()?; let commit = gix::ObjectId::from_hex(revision.as_bytes()).ok()?.to_string(); let (_, base) = self.head().ok()?; @@ -297,7 +296,7 @@ impl Repo { /// The staged changes Git would commit after a cherry-pick or revert stopped. pub fn review_apply_commit(&self, cancel: &CancellationToken) -> IdeResult> { - let _scope = ExecutionScope::enter(self.execution_allowed.load(Ordering::Acquire)); + let _scope = self.execution_scope(); self.review_apply_index(cancel, &[]) } @@ -371,7 +370,7 @@ impl Repo { cancel: &CancellationToken, out: &dyn Fn(String), ) -> IdeResult { - let _scope = ExecutionScope::enter(self.execution_allowed.load(Ordering::Acquire)); + let _scope = self.execution_scope(); if message.trim().is_empty() || message.contains('\0') || message.len() > MESSAGE_LIMIT { return Err(IdeError::invalid("Invalid commit message")); } @@ -421,7 +420,7 @@ impl Repo { } fn commit_message_config(&self, cancel: &CancellationToken) -> IdeResult<(MessageConfig, Option)> { - let _scope = ExecutionScope::enter(self.execution_allowed.load(Ordering::Acquire)); + let _scope = self.execution_scope(); let raw = cli::run_bounded( self.root(), &["config", "--includes", "--show-origin", "--null", "--list"], diff --git a/crates/ide-vcs/src/compare.rs b/crates/ide-vcs/src/compare.rs index 1825ae710e..1d8af53703 100644 --- a/crates/ide-vcs/src/compare.rs +++ b/crates/ide-vcs/src/compare.rs @@ -129,8 +129,7 @@ impl Repos { continue; } let repo = self.at_root(&root.0).expect("scope comes from registry"); - let _scope = - crate::ExecutionScope::enter(repo.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = repo.execution_scope(); let mut missing_revision = false; let mut compare = || -> IdeResult<(String, Vec)> { // Worktree comparisons must not run repository-defined clean/process filters diff --git a/crates/ide-vcs/src/incoming.rs b/crates/ide-vcs/src/incoming.rs index 43e01c777b..09facdac23 100644 --- a/crates/ide-vcs/src/incoming.rs +++ b/crates/ide-vcs/src/incoming.rs @@ -7,7 +7,6 @@ use ide_core::{CancellationToken, IdeError, IdeResult}; use serde::{Deserialize, Serialize}; use specta::Type; use std::collections::{BTreeMap, HashMap}; -use std::sync::atomic::Ordering; #[derive(Clone, Debug, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] @@ -39,7 +38,7 @@ pub(crate) struct IncomingObservations { impl Repo { pub fn check_incoming_refs(&self, cancel: &CancellationToken) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(Ordering::Acquire)); + let _scope = self.execution_scope(); let generation = { let mut observations = self.incoming_observations.lock().unwrap_or_else(|p| p.into_inner()); observations.generation += 1; diff --git a/crates/ide-vcs/src/lib.rs b/crates/ide-vcs/src/lib.rs index 8647cfb8d6..a32d6255b1 100644 --- a/crates/ide-vcs/src/lib.rs +++ b/crates/ide-vcs/src/lib.rs @@ -962,7 +962,7 @@ pub use backend::Backend; pub use cherry_pick_plan::CherryPickOptions; pub use cli::{ GitCommandObserver, detected_git_executable, filter_overrides_from, git_version, restrict, set_askpass_env, - set_git_command_observer, set_git_executable, + set_default_git_executable, set_git_command_observer, }; pub use diff::build_partial_patch; pub use external_diff::{ExternalDiffSide, launch_external_diff}; @@ -1055,7 +1055,7 @@ mod clone_tests { /// Creates an empty repository in `dir` (`git init`). pub fn init(dir: &Path) -> IdeResult<()> { // `git init` runs nothing a repository config names, so the configured git runs as it is. - let _scope = ExecutionScope::enter(true); + let _scope = ExecutionScope::enter_with(true, opening_git_executable()); cli::run(dir, &["init", "-q"], None).map(|_| ()) } @@ -1069,6 +1069,7 @@ pub fn diff_hunks(old_text: &str, new_text: &str) -> Vec { /// on-disk state, so it never needs to be reopened after external changes. pub struct Repo { execution_allowed: std::sync::atomic::AtomicBool, + git_executable: std::sync::RwLock>>, root: PathBuf, git_dir: PathBuf, inner: std::sync::Mutex, @@ -1092,7 +1093,7 @@ impl Repo { /// Restores this batch's pending Shelf after its repository commands have returned. pub fn finish_shelf_batch(&self, batch: &str) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); preserve::finish_batch(self, batch) } @@ -1103,18 +1104,18 @@ impl Repo { } /// The worktree root. pub fn root(&self) -> &Path { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); &self.root } /// git's own folders for this worktree: its git dir and the common one (they differ for a /// linked worktree, whose `.git` file points into the main repository). pub fn metadata_dirs(&self) -> IdeResult<[PathBuf; 2]> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); Ok([self.git_dir.clone(), repo::absolute(self.gix()?.common_dir())?]) } /// Untracked files with one of these names (or under such a folder) are not reported. pub fn set_ignored_names(&self, names: IgnoredNames) { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); *self.ignored.write().unwrap_or_else(|p| p.into_inner()) = names; } /// Read the working-tree status with `git status` rather than in process: for file systems @@ -1125,17 +1126,17 @@ impl Repo { /// Staged (HEAD↔index) and unstaged (index↔worktree, incl. untracked) changes, /// sorted by path. Conflicted files report `unstaged: Conflicted` and no staged kind. pub fn status(&self) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); status::status(self) } pub fn ignored_files(&self) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); status::ignored_files(self) } /// Status of `paths` only (absolute; those outside the repository are ignored), for the /// dirty-scope refresh after a watcher batch. An empty list is the full status. pub fn status_paths(&self, paths: &[PathBuf]) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); // Restricted Mode starts no program of the repository, and the scoped read is `git status` // with a pathspec: answer with the full gitoxide status instead. if !self.execution_allowed.load(std::sync::atomic::Ordering::Acquire) { @@ -1151,18 +1152,18 @@ impl Repo { status::status_paths(self, &rel) } pub fn branch_info(&self) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); refs::branch_info(self) } /// Current branch (short name; `None` when detached) and HEAD commit, without /// upstream tracking (cheap enough to call for every repository on each refresh). pub fn head(&self) -> IdeResult<(Option, Option)> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); refs::head(&self.gix()?) } /// Merge / rebase / cherry-pick… in progress (cheap: no ref walking). pub fn operation(&self) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); Ok(refs::operation(&self.gix()?)) } /// Whether Git is running an interactive rebase in this worktree. @@ -1178,13 +1179,13 @@ impl Repo { encoding: impl Into, ) -> IdeResult> { let encoding = encoding.into(); - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); Ok(self.blob_of(path, rev.unwrap_or("HEAD"))?.map(|b| text_encoding::decode(&b, encoding).into_owned())) } /// The file's git mode at `rev` as printed by git (`100644`, `100755`, `120000`…), /// `None` when absent there. `rev` follows `file_at`'s rules, `WT` reads the worktree. pub fn file_mode_at(&self, path: &Path, rev: Option<&str>) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); if rev == Some("WT") { return repo::worktree_mode(self.root(), &self.rel_path(path)?); } @@ -1194,7 +1195,7 @@ impl Repo { } /// Raw revision bytes, for encoding detection when the working file is absent. pub fn file_bytes_at(&self, path: &Path, rev: Option<&str>) -> IdeResult>> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); self.blob_of(path, rev.unwrap_or("HEAD")) } /// Stage selected decoded hunks, retaining the index encoding, BOM and line endings. @@ -1206,7 +1207,7 @@ impl Repo { encoding: impl Into, ) -> IdeResult<()> { let encoding = encoding.into(); - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::stage_hunks(self, path, current, selected, encoding) } /// Hunks of `current_text` against HEAD (or the index when `against_index`). @@ -1223,7 +1224,7 @@ impl Repo { encoding: impl Into, ) -> IdeResult> { let encoding = encoding.into(); - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let Ok(rel) = self.rel_path(path) else { return Ok(Vec::new()) }; if rel.is_empty() || rel == ".git" || rel.starts_with(".git/") { return Ok(Vec::new()); @@ -1269,13 +1270,13 @@ impl Repo { encoding: TextEncoding, options: GitAnnotateSettings, ) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::blame(self, path, current_text, revision, encoding, options) } /// Adds `commit` to the list `blame.ignoreRevsFile` names, so annotate skips it; with none /// configured, to `.git-blame-ignore-revs` at the worktree root, which the local config then names. pub fn ignore_blame_revision(&self, commit: &str) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::ignore_blame_revision(self, commit) } /// History for Selection: commits that changed `lines` (0-based, inclusive, of the @@ -1289,7 +1290,7 @@ impl Repo { cancel: &CancellationToken, ) -> IdeResult { let encoding = encoding.into(); - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); block_history::block_history(self, path, current_text, lines, encoding, cancel) } /// Commits newest-first in topological order (children before parents). @@ -1300,11 +1301,11 @@ impl Repo { /// `skip`/`limit` paginate over the filtered result; `limit == 0` means no limit. /// `refs` decorations are `HEAD`, branch names (`main`, `origin/main`) and `tag: `. pub fn log(&self, query: &LogQuery) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); history::log(self, query, &CancellationToken::new()) } pub fn log_cancellable(&self, query: &LogQuery, cancel: &CancellationToken) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); history::log(self, query, cancel) } /// Commits unique to `source` that have no equivalent on `target`; `None` if a ref is absent. @@ -1314,7 +1315,7 @@ impl Repo { target: &str, cancel: &CancellationToken, ) -> IdeResult>> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); history::not_cherry_picked(self, source, target, cancel) } /// Enables the disposable, content-addressed log cache outside the worktree. @@ -1331,7 +1332,7 @@ impl Repo { .collect()) } pub fn log_users(&self) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let out = cli::run(self.root(), &["log", "--all", "--format=%an <%ae>"], None)?; Ok(out .stdout_str() @@ -1361,8 +1362,7 @@ impl Repo { revisions: &[String], cancel: &CancellationToken, ) -> IdeResult> { - let allowed = self.execution_allowed.load(std::sync::atomic::Ordering::Acquire); - let _scope = crate::ExecutionScope::enter(allowed); + let _scope = self.execution_scope(); let allowed = crate::execution_allowed(); let repo = self.gix()?; let shallow: std::collections::HashSet = @@ -1429,7 +1429,7 @@ impl Repo { /// Lists one immutable revision directory. Directory names end in `/`. pub fn revision_children(&self, revision: &str, directory: &str) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let repo = self.gix()?; let id = repo::resolve(&repo, revision)?.to_string(); let directory = self.rel_path(std::path::Path::new(directory))?; @@ -1452,7 +1452,7 @@ impl Repo { } pub fn revision_files(&self, revision: &str) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let repo = self.gix()?; let id = repo::resolve(&repo, revision)?.to_string(); let out = cli::run(self.root(), &["ls-tree", "-r", "-z", "--name-only", "--", &id], None)?; @@ -1465,13 +1465,13 @@ impl Repo { } /// Files changed by `commit` relative to its first parent (renames detected). pub fn commit_files(&self, commit: &str) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); history::commit_files(self, commit) } /// Combined changes of several commits (oldest first): per file, before the first commit /// that touched it ↔ after the last one (IDEA's multi-commit Git Log selection). pub fn commits_changes(&self, commits: &[String]) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); history::commits_changes(self, commits) } /// The combined changes of a selection whose display order can differ from history. @@ -1480,17 +1480,17 @@ impl Repo { commits: &[String], cancel: &CancellationToken, ) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); history::commit_selection_changes(self, commits, cancel) } /// Local and remote branches; the current branch first, then most recent first. pub fn branches(&self) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); refs::branches(self) } /// Stash entries, newest (`stash@{0}`) first. pub fn stashes(&self) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); refs::stashes(self) } /// Working tree against a revision, optionally restricted to a file. Bounded and cancellable. @@ -1501,7 +1501,7 @@ impl Repo { max_bytes: usize, cancel: &CancellationToken, ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let rev = against.unwrap_or("HEAD"); if rev.is_empty() || rev.starts_with('-') || rev.contains('\0') { return Err(ide_core::IdeError::invalid("invalid revision")); @@ -1523,20 +1523,20 @@ impl Repo { /// against /dev/null) or HEAD↔index (`staged == true`). Empty when unchanged. pub fn diff_text(&self, path: &Path, staged: bool, encoding: impl Into) -> IdeResult { let encoding = encoding.into(); - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::diff_text(self, path, staged, encoding) } /// `git config --get ` (all scopes); `None` when unset. pub fn config_get(&self, key: &str) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let out = cli::run_raw(&self.root, &["config", "--get", key], None)?; Ok((out.code == Some(0)).then(|| out.stdout_str().trim().to_string())) } /// Reads a boolean in Git's own config syntax, including implicit true. pub fn config_get_bool(&self, key: &str) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let args = ["config", "--type=bool", "--get", "--", key]; let out = cli::run_raw(&self.root, &args, None)?; match (out.code, out.stdout_str().trim()) { @@ -1550,7 +1550,7 @@ impl Repo { /// Sets `user.name` and `user.email` for commits: in this repository's config, or in the /// user's global one (`global`). pub fn set_user_identity(&self, name: &str, email: &str, global: bool) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let scope = if global { "--global" } else { "--local" }; for (key, value) in [("user.name", name.trim()), ("user.email", email.trim())] { if value.is_empty() { @@ -1563,20 +1563,20 @@ impl Repo { // ---- writes (git CLI) ---- pub fn stage(&self, paths: &[PathBuf]) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::stage(self, paths) } pub fn stage_without_content(&self, paths: &[PathBuf]) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::stage_without_content(self, paths) } pub fn unstage(&self, paths: &[PathBuf]) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::unstage(self, paths) } /// Restores the selected worktree files from the index. pub fn restore_unstaged(&self, paths: &[PathBuf]) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::restore_unstaged(self, paths) } /// Applies a unified-diff patch to the index (partial staging of hunks/lines). @@ -1586,7 +1586,7 @@ impl Repo { patch: &str, encoding: &dyn Fn(&Path) -> IdeResult, ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::stage_patch(self, patch, &|path| encoding(path).map(Into::into)) } /// Stages a formatter's edits against the index text it started from. @@ -1598,7 +1598,7 @@ impl Repo { encoding: impl Into, ) -> IdeResult<()> { let encoding = encoding.into(); - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let rel = self.rel_path(path)?; let staged = self .blob_of(path, ":0")? @@ -1617,13 +1617,13 @@ impl Repo { /// changes are kept), untracked files and directories are deleted. A submodule goes back /// to the commit the index records, with its tracked files restored. pub fn discard(&self, paths: &[PathBuf]) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::discard(self, paths) } /// Commits the index; returns the new HEAD commit id. An empty message with /// `amend` keeps the previous message. pub fn commit(&self, message: &str, amend: bool, sign_off: bool) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let options = CommitOptions { amend, sign_off, author: None, run_hooks: true, ..Default::default() }; write::commit(self, message, &options, &|_| Ok(encoding_rs::UTF_8.into())) } @@ -1634,12 +1634,12 @@ impl Repo { options: &CommitOptions, encoding: &dyn Fn(&Path) -> IdeResult, ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::commit(self, message, options, &|path| encoding(path).map(Into::into)) } /// Appends the commit prepared during a failed earlier Amend. pub fn keep_amend_commit(&self, commit: &str) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); commit_rewrite::keep_amend(self, commit) } /// The text a partial commit would put in the index, without changing it. @@ -1660,7 +1660,7 @@ impl Repo { encoding: &dyn Fn(&Path) -> IdeResult, cancel: &CancellationToken, ) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::commit_crlf_paths(self, paths, options, &|path| encoding(path).map(Into::into), cancel) } /// Check the selected sources for large files, respecting this repo's Git LFS configuration. @@ -1672,7 +1672,7 @@ impl Repo { encoding: &dyn Fn(&Path) -> IdeResult, cancel: &CancellationToken, ) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::commit_large_files(self, paths, options, limit, &|path| encoding(path).map(Into::into), cancel) } /// What [`Repo::commit_with`] would commit with `options`, file by file, without @@ -1683,14 +1683,14 @@ impl Repo { max_bytes: usize, encoding: &dyn Fn(&Path) -> IdeResult, ) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::pending_changes(self, options, max_bytes, &|path| encoding(path).map(Into::into)) } /// Switches to `branch`. With `create`, creates it at HEAD. Without, a remote branch /// (`origin/x`) gets a local tracking branch and any other revision is checked out /// detached. pub fn checkout(&self, branch: &str, create: bool) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::checkout(self, branch, create) } /// [`Repo::checkout`] as IDEA does it: local changes in the way are reported (or @@ -1698,13 +1698,13 @@ impl Repo { /// is behind fast-forwards that branch, while one that is ahead is reported (or /// rebased / reset per `options.diverged`). pub fn checkout_with(&self, branch: &str, create: bool, options: &CheckoutOptions) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::checkout_with(self, branch, create, options) } /// Finds tracked local changes that may block a switch to `branch` without changing HEAD, /// the index, or the worktree. pub fn checkout_affected_files(&self, branch: &str) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::checkout_affected_files(self, branch) } /// Creates branch `name` at `start` (default HEAD), optionally switching to it. A @@ -1751,7 +1751,7 @@ impl Repo { overwrite: bool, expected_tip: Option<&str>, ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::create_branch(self, name, start, checkout, overwrite, expected_tip) } @@ -1761,20 +1761,20 @@ impl Repo { created: &BranchCreation, previous_head: Option<&HistoryTip>, ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::undo_branch_creation(self, name, created, previous_head) } /// Undo Commit: resets the current branch to the parent of `commit` (which must be /// HEAD and not a merge) keeping its changes staged; undoing the initial commit /// leaves an unborn branch. Returns the undone commit's message. pub fn undo_commit(&self, commit: &str) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::undo_commit(self, commit) } /// Edit Commit Message without touching the index or the working tree; returns HEAD /// before and after. pub fn reword(&self, commit: &str, message: &str) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); commit_rewrite::reword(self, commit, message) } @@ -1786,7 +1786,7 @@ impl Repo { paths: &[PathBuf], message: &str, ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); commit_rewrite::extract(self, commit, expected_head, paths, message) } @@ -1799,7 +1799,7 @@ impl Repo { cancel: &CancellationToken, out: &dyn Fn(String), ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); commit_rewrite::drop_changes(self, commit, expected_head, paths, cancel, out) } @@ -1809,7 +1809,7 @@ impl Repo { } pub fn restore_head_on_branch(&self, before: &str, after: &str, branch: Option<&str>) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::restore_head(self, before, after, branch) } @@ -1820,53 +1820,53 @@ impl Repo { branch: &str, checkout: &HistoryTip, ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::restore_rebase_checkout(self, before, after, branch, checkout) } /// Deletes a local branch (`git branch -d`, `-D` when `force`). pub fn delete_branch(&self, branch: &str, force: bool) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::delete_branch(self, branch, force) } /// Deletes a local branch as IDEA does: without asking, force-deleting one that is not /// fully merged (reported as `unmerged`), and returning what [`Repo::restore_branch`] /// needs to undo it. pub fn delete_branch_restorable(&self, branch: &str) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::delete_branch_restorable(self, branch, None) } /// Deletes a local branch selected for cleanup with its remote branch. pub fn delete_tracking_branch(&self, branch: &str, tip: &str, upstream: &str) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::delete_branch_restorable(self, branch, Some((tip, upstream))) } /// Deletes a branch offered for cleanup after a merge, with a tip and HEAD ancestry check. pub fn delete_merged_branch(&self, branch: &str, expected_tip: &str) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::delete_merged_branch(self, branch, expected_tip) } /// Recreates a deleted branch at its old tip, with its upstream. pub fn restore_branch(&self, deleted: &DeletedBranch) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::restore_branch(self, deleted) } /// Renames a local branch (`git branch -m`); its upstream configuration moves with it, /// unless `unset_upstream` drops the tracking instead. pub fn rename_branch(&self, from: &str, to: &str, unset_upstream: bool) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::rename_branch(self, from, to, unset_upstream) } /// Merges `branch` into HEAD; local changes are stashed and restored around it. On /// conflicts an error is returned and the repository is left mid-merge /// (`branch_info().operation == Some("merge")`). pub fn merge(&self, branch: &str) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::merge(self, branch) } /// Rebases the current branch onto `onto`; local changes are stashed and restored. pub fn rebase(&self, onto: &str) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::rebase(self, onto) } @@ -1876,7 +1876,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::rebase_branch(self, plan, cancel, on_output) } /// Rebases the selected branch onto the original HEAD and leaves it checked out. @@ -1886,7 +1886,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::checkout_rebase(self, plan, cancel, on_output) } /// `paths` (absolute) stashes only those files; empty stashes the whole working tree. @@ -1898,20 +1898,20 @@ impl Repo { keep_index: bool, paths: &[PathBuf], ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let _stash_lock = write::lock_stashes(self)?; write::stash_push(self, message, include_untracked, keep_index, paths) } /// `reinstate_index`: also restore what was staged when the stash was made. pub fn stash_apply(&self, index: u32, pop: bool, reinstate_index: bool) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let _stash_lock = write::lock_stashes(self)?; write::stash_apply(self, &format!("stash@{{{index}}}"), pop, reinstate_index) } /// Creates and checks out `branch` at the commit the stash was made on, applies the /// stash there (index included) and drops it. pub fn stash_branch(&self, index: u32, branch: &str) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let _stash_lock = write::lock_stashes(self)?; write::stash_branch(self, &format!("stash@{{{index}}}"), branch) } @@ -1923,23 +1923,23 @@ impl Repo { reinstate_index: bool, branch: Option<&str>, ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::unstash_selected(self, stash, pop, reinstate_index, branch) } /// Removes `stash@{index}` without applying it. pub fn stash_drop(&self, index: u32) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let _stash_lock = write::lock_stashes(self)?; write::stash_drop(self, index) } /// Removes the selected stash, returning the position from which it was removed. pub fn drop_selected_stash(&self, stash: &Stash) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::drop_selected_stash(self, stash) } /// Removes the repository's stash reflog without changing the index or working files. pub fn stash_clear(&self) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let _stash_lock = write::lock_stashes(self)?; cli::run(self.root(), &["stash", "clear"], None).map(|_| ()) } @@ -1951,7 +1951,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::delete_remote_branch(self, branch, cancel, on_output) } /// Network operations stream progress lines through `on_output`. @@ -1973,7 +1973,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); if !self.is_shallow()? { return Ok(()); } @@ -2031,7 +2031,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let tag_config = remotes::pull_tag_config(self, tags)?; let mut args: Vec<&str> = tag_config.iter().flat_map(|entry| ["-c", entry.as_str()]).collect(); let mode: &[&str] = if rebase { &["--rebase"] } else { &["--no-rebase", "--ff"] }; @@ -2090,7 +2090,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::push(self, options, cancel, on_output) } /// Pushes the exact source and destination chosen in the Push dialog. @@ -2102,7 +2102,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::push_selected(self, selection, inspected, options, cancel, on_output) } /// Repeats a rejected push with the exact lease reviewed in the dialog. @@ -2114,13 +2114,13 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::force_push_rejected(self, divergence, tags, no_verify, cancel, on_output) } /// Whether the repository has an executable hook `name` (e.g. `pre-push`), wherever /// `core.hooksPath` puts it: the Push dialog then offers to skip it. pub fn has_hook(&self, name: &str) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::has_hook(self, name) } /// Pushes a local branch, or its history up to `revision`, to its upstream (Git Log @@ -2133,7 +2133,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::push_branch( self, branch, @@ -2153,7 +2153,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::push_branch(self, branch, options, cancel, on_output) } /// Update Project › Reset to the Remote Branch: the current branch is moved to its @@ -2168,7 +2168,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::reset_to_upstream(self, tags, cancel, on_output) } /// Fast-forwards the requested branches to their upstreams, including branches @@ -2189,7 +2189,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); write::update_branches(self, branches, tags, cancel, on_output) } // ---- in-progress operations, history rewriting, tags ---- @@ -2211,7 +2211,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::continue_op(self, stage, |args| { cherry_pick_plan::resume(self, args, None, empty_action, cancel, on_output) }) @@ -2225,7 +2225,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::finish_merge(self, branch, head, target, cancel, on_output) } pub fn abort_operation(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> { @@ -2238,7 +2238,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::abort_op(self, expected, cancel, on_output) } /// Skips the current commit of a rebase / cherry-pick / revert. @@ -2252,7 +2252,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::skip_op(self, |args| cherry_pick_plan::resume(self, args, None, empty_action, cancel, on_output)) } /// Cherry-picks `commits` in order (oldest first). Stops mid-way on conflicts. @@ -2294,12 +2294,12 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); cherry_pick_plan::start(self, commits, options, cancel, on_output) } /// Reverts `commits` in order (newest first) with git's default messages. pub fn revert(&self, commits: &[String], cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::revert(self, commits, cancel, on_output) } /// Interactive rebase of `base..HEAD` (`None`: from the root) following `entries`, @@ -2312,7 +2312,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::interactive_rebase(self, base, entries, cancel, on_output) } /// Moves the current branch to `commit` (`git reset --`). @@ -2323,22 +2323,22 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::reset(self, commit, mode, cancel, on_output) } /// Creates tag `name` on `commit` (annotated when `message` is given). pub fn create_tag(&self, name: &str, commit: &str, message: Option<&str>, force: bool) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::create_tag(self, name, commit, message, force) } /// Deletes a local tag, returning what [`Repo::restore_tag`] needs to undo it. pub fn delete_tag(&self, name: &str) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::delete_tag(self, name) } /// Recreates a deleted tag (annotated ones with their message). pub fn restore_tag(&self, deleted: &DeletedTag) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::restore_tag(self, deleted) } /// Pushes one tag to `remote` (Push Tag › Push to …). @@ -2349,7 +2349,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::push_tag(self, tag, remote, false, cancel, on_output) } /// Deletes a tag on `remote` (Delete on Remote, after deleting it locally). @@ -2360,7 +2360,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::push_tag(self, tag, remote, true, cancel, on_output).map(drop) } /// Deletes a locally removed tag on the configured remotes only at its original tip. @@ -2370,33 +2370,33 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::delete_tag_on_remotes(self, deleted, cancel, on_output) } pub fn tags(&self) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::tags(self) } /// Files that differ between revisions `from` and `to`. pub fn diff_revisions(&self, from: &str, to: &str) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::diff_revisions(self, from, to) } /// Added and deleted lines between `from` and `to`. `paths` limits the diff to those /// repository-relative paths (both names of a rename); empty diffs every file. pub fn diff_numstat(&self, from: &str, to: &str, paths: &[String]) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::diff_numstat(self, from, to, paths) } /// Tracked files whose working-tree content differs from `rev`. pub fn diff_with_worktree(&self, rev: &str) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::diff_with_worktree(self, rev) } /// `(repo-relative path, added lines, deleted lines)` of the tracked files whose /// working-tree content differs from `rev`. pub fn numstat_with_worktree(&self, rev: &str) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::numstat_with_worktree(self, rev) } @@ -2404,7 +2404,7 @@ impl Repo { /// Patch of the local changes of `paths` against HEAD (untracked files included). pub fn create_patch(&self, paths: &[PathBuf], reverse: bool) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let rel = self.rel_paths(paths)?; Ok(patch::working_patch(self, &rel, reverse, true)?.0) } @@ -2415,21 +2415,21 @@ impl Repo { reverse: bool, prefix: &str, ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); patch::staging_patch(self, entries, reverse, prefix) } /// Patch of the changes made by `commits` (oldest first). pub fn create_commits_patch(&self, commits: &[String], reverse: bool) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); patch::commits_patch(self, commits, reverse) } /// A binary-safe patch of the selected files between two revisions. pub fn create_revisions_patch(&self, before: &str, after: &str, paths: &[PathBuf]) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); patch::revisions_patch(self, before, after, paths) } pub fn patch_preview(&self, patch: &str) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); patch::preview(self, patch) } pub fn patch_file_diff( @@ -2438,57 +2438,57 @@ impl Repo { path: &str, encoding: &dyn Fn(&Path, &[u8]) -> TextEncoding, ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); patch::file_diff::generate(self, patch, path, "", encoding) } /// Applies a patch to the working tree, 3-way merging when it does not apply cleanly. pub fn apply_patch(&self, patch: &str) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); patch::apply_for_review(self, patch, "") } /// Applies the file sections with the selected destination paths. pub fn apply_selected_patch(&self, patch: &str, paths: &[String]) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); patch::apply_selected(self, patch, paths) } /// Saves the changes of `paths` under `shelf_dir` and reverts them. pub fn shelve(&self, shelf_dir: &Path, name: &str, paths: &[PathBuf]) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let rel = self.rel_paths(paths)?; shelf::shelve(self, shelf_dir, name, &rel) } pub fn unshelve(&self, shelf_dir: &Path, id: &str, remove: bool) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); shelf::unshelve(self, shelf_dir, id, remove) } /// Who is on each side of the conflicts of the operation in progress. pub fn merge_sides(&self) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); ops::merge_sides(self) } /// Files with saved resolutions from an ongoing Git operation. pub fn resolved_conflicts(&self) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); conflict_resolution::resolved_paths(self) } /// Restores the original conflict stages and worktree contents for resolved files. pub fn revert_resolved_conflicts(&self, paths: &[PathBuf]) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); conflict_resolution::revert_resolved(self, paths) } /// Resolves each selected path using the chosen index stage, including its mode or deletion. pub fn accept_conflict_side(&self, paths: &[PathBuf], side: ConflictSide) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); conflict_resolution::accept_side(self, paths, side) } /// The versions of a conflicted file with the user's work as `ours`, as IDEA's merge /// dialog shows them (sides swapped during a rebase). pub fn merge_versions(&self, path: &Path, encoding: impl Into) -> IdeResult { let encoding = encoding.into(); - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let sides = self.merge_sides()?; let blobs = self.conflict_blobs(path)?; if blobs.iter().flatten().any(|bytes| text_encoding::is_binary(bytes, encoding)) { @@ -2508,7 +2508,7 @@ impl Repo { path: &Path, encoding: impl Into, ) -> IdeResult<(Option, Option, Option)> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let [base, ours, theirs] = decode_conflict_blobs(self.conflict_blobs(path)?, encoding.into()); Ok((base, ours, theirs)) } @@ -2525,33 +2525,83 @@ fn decode_conflict_blobs(blobs: [Option>; 3], encoding: TextEncoding) -> blobs.map(|blob| blob.map(|bytes| text_encoding::decode(&bytes, encoding).into_owned())) } +/// What git started on this thread may do, and which executable it is. +#[derive(Clone)] +struct Grant { + allowed: bool, + git: Option>, +} + // `None`: nobody has decided yet. Git started now is restricted, and the first scope entered -// decides. The flag governs the git CLI only: gitoxide follows the repository's own flag. -thread_local! { static EXECUTION_ALLOWED: std::cell::Cell> = const { std::cell::Cell::new(None) }; } -struct ExecutionScope(Option); +// decides. The grant governs the git CLI only: gitoxide follows the repository's own flag. +thread_local! { static EXECUTION: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } +struct ExecutionScope(Option); impl ExecutionScope { - /// The outermost scope decides; a scope inside it can only restrict. fn enter(allowed: bool) -> Self { - Self( - EXECUTION_ALLOWED - .with(|current| current.replace(Some(current.get().map_or(allowed, |outer| outer && allowed)))), - ) + Self::enter_with(allowed, None) + } + /// The outermost scope decides; a scope inside it can only restrict. + fn enter_with(allowed: bool, git: Option>) -> Self { + EXECUTION.with(|current| { + let mut current = current.borrow_mut(); + let grant = match current.as_ref() { + Some(outer) => Grant { allowed: outer.allowed && allowed, git: outer.git.clone() }, + None => Grant { allowed, git }, + }; + Self(current.replace(grant)) + }) } } impl Drop for ExecutionScope { fn drop(&mut self) { - EXECUTION_ALLOWED.with(|current| current.set(self.0)); + EXECUTION.with(|current| *current.borrow_mut() = self.0.take()); } } pub(crate) fn execution_allowed() -> bool { - EXECUTION_ALLOWED.with(|current| current.get().unwrap_or(false)) + EXECUTION.with(|current| current.borrow().as_ref().is_some_and(|grant| grant.allowed)) +} +/// The git executable of the repository whose scope this thread is in, when it may execute. +pub(crate) fn scoped_git_executable() -> Option> { + EXECUTION + .with(|current| current.borrow().as_ref().filter(|grant| grant.allowed).and_then(|grant| grant.git.clone())) +} + +thread_local! { static OPENING_GIT: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; } + +/// Runs `f` with `git` (a project's Path to Git executable; `None` for the default) as the git +/// executable of every [`Repo`] opened in it on this thread, and of [`init`]: for work on behalf +/// of a project that opens its own repositories. It grants no execution. +pub fn with_git_executable(git: Option<&Path>, f: impl FnOnce() -> T) -> T { + struct Restore(Option>); + impl Drop for Restore { + fn drop(&mut self) { + OPENING_GIT.with(|opening| *opening.borrow_mut() = self.0.take()); + } + } + let git = git.filter(|p| !p.as_os_str().is_empty()).map(std::sync::Arc::from); + let _restore = Restore(OPENING_GIT.with(|opening| opening.replace(git))); + f() +} +pub(crate) fn opening_git_executable() -> Option> { + OPENING_GIT.with(|opening| opening.borrow().clone()) } impl Repo { /// Whether git may run what the repository's config names (hooks, filters, the fsmonitor, /// signature verifiers, a promisor) and use the configured git executable. A repository /// starts without it: only a caller that knows the project is trusted grants it. pub fn set_execution_allowed(&self, allowed: bool) { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); self.execution_allowed.store(allowed, std::sync::atomic::Ordering::Release); } + /// The git executable from this repository's project settings (`None` or empty: the default, + /// see [`set_default_git_executable`]). A relative path resolves against the worktree root. + /// Used only while execution is allowed. + pub fn set_git_executable(&self, path: Option<&Path>) { + let path = path.filter(|p| !p.as_os_str().is_empty()).map(std::sync::Arc::from); + *self.git_executable.write().unwrap_or_else(|p| p.into_inner()) = path; + } + fn execution_scope(&self) -> ExecutionScope { + let git = self.git_executable.read().unwrap_or_else(|p| p.into_inner()).clone(); + ExecutionScope::enter_with(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire), git) + } } diff --git a/crates/ide-vcs/src/manage.rs b/crates/ide-vcs/src/manage.rs index 1f9ca12611..142ec93d1f 100644 --- a/crates/ide-vcs/src/manage.rs +++ b/crates/ide-vcs/src/manage.rs @@ -278,7 +278,7 @@ impl Repo { /// Merges `branches` into the current branch (Git › Merge…). pub fn merge_with(&self, branches: &[String], options: &MergeOptions) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let args = merge_args(branches, options)?; let args: Vec<&str> = args.iter().map(String::as_str).collect(); crate::preserve::around(self, "Local changes saved before merge", || run(self.root(), &args, None).map(|_| ())) @@ -286,7 +286,7 @@ impl Repo { /// Tries the merge as requested. Smart Merge preserves local changes after user confirmation. pub fn merge_attempt(&self, branches: &[String], options: &MergeOptions, smart: bool) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let branches = branches .iter() .map(|branch| crate::write::unambiguous_branch_name(self, branch.trim()).to_owned()) @@ -298,13 +298,13 @@ impl Repo { /// Predicts which tracked local changes a branch merge may have to save. pub fn merge_affected_files(&self, branch: &str) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); crate::write::merge_affected_files(self, branch) } /// Rebases the chosen branch or HEAD. Without an upstream, rebases from the root. pub fn rebase_with(&self, upstream: Option<&str>, options: &RebaseOptions) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let args = rebase_args(upstream, options)?; self.validate_rebase(options)?; let args: Vec<&str> = args.iter().map(String::as_str).collect(); @@ -334,7 +334,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let args = pull_args(remote, branches, rebase, options)?; let args: Vec<&str> = args.iter().map(String::as_str).collect(); crate::preserve::around(self, "Local changes saved before update", || { @@ -344,7 +344,7 @@ impl Repo { /// Manage Remotes: adds, removes or edits a remote. pub fn edit_remote(&self, edit: &RemoteEdit) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); match edit { RemoteEdit::Add { name, url } => { let (name, url) = (arg(name, "remote name")?, arg(url, "URL")?); @@ -368,7 +368,7 @@ impl Repo { /// Working trees of the repository, the main one first. pub fn worktrees(&self) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let out = run(self.root(), &["worktree", "list", "--porcelain"], None)?; let mut trees = parse_worktrees(&out.stdout_str()); if let Some(main) = trees.first_mut().filter(|main| main.head.is_some()) { @@ -390,7 +390,7 @@ impl Repo { /// Checks out a local branch, a new branch, or a detached revision in a new worktree. pub fn add_worktree(&self, path: &Path, commitish: &str, new_branch: Option<&str>) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let path = path.to_string_lossy().into_owned(); let commitish = arg(commitish, "revision")?; let mut args: Vec = vec!["worktree".into(), "add".into()]; @@ -410,7 +410,7 @@ impl Repo { /// Move Worktree…: moves a linked worktree's folder to exactly `to`. An empty folder there /// is replaced (Git would move the worktree inside it); any other existing `to` is refused. pub fn move_worktree(&self, path: &Path, to: &Path) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); if std::fs::symlink_metadata(to).is_ok() { let empty_dir = to.is_dir() && std::fs::read_dir(to).is_ok_and(|mut d| d.next().is_none()); if !empty_dir { @@ -423,7 +423,7 @@ impl Repo { } pub fn remove_worktree(&self, path: &Path, force: bool) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let path = path.to_string_lossy().into_owned(); let mut args = vec!["worktree", "remove"]; if force { @@ -434,13 +434,13 @@ impl Repo { } pub fn set_worktree_locked(&self, path: &Path, locked: bool) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let operation = if locked { "lock" } else { "unlock" }; run(self.root(), &["worktree", operation, "--", &path.to_string_lossy()], None).map(|_| ()) } pub fn prune_worktrees(&self) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); run(self.root(), &["worktree", "prune", "--expire", "now"], None).map(|_| ()) } } diff --git a/crates/ide-vcs/src/patch.rs b/crates/ide-vcs/src/patch.rs index e880844de1..df19466ac3 100644 --- a/crates/ide-vcs/src/patch.rs +++ b/crates/ide-vcs/src/patch.rs @@ -503,12 +503,12 @@ pub struct ProjectPatchGroup { impl ProjectPatchGroup { pub fn preview(&self, r: &Repo) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(r.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = r.execution_scope(); preview_with_prefix(r, &self.patch, &self.prefix) } pub fn apply(&self, r: &Repo) -> IdeResult { - let _scope = crate::ExecutionScope::enter(r.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = r.execution_scope(); let outcome = apply_for_review(r, &self.patch, &self.prefix)?; let based = |paths: Vec| paths.into_iter().map(|path| format!("{}{path}", self.prefix)).collect(); Ok(ApplyOutcome { applied: based(outcome.applied), conflicts: based(outcome.conflicts) }) @@ -520,7 +520,7 @@ impl ProjectPatchGroup { path: &str, encoding: &dyn Fn(&Path, &[u8]) -> crate::TextEncoding, ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(r.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = r.execution_scope(); file_diff::generate(r, &self.patch, path, &self.prefix, encoding) } } diff --git a/crates/ide-vcs/src/push_preview.rs b/crates/ide-vcs/src/push_preview.rs index 6d22c45cdc..80f72daa31 100644 --- a/crates/ide-vcs/src/push_preview.rs +++ b/crates/ide-vcs/src/push_preview.rs @@ -311,7 +311,7 @@ impl Repo { live: bool, cancel: &CancellationToken, ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let (source, target, local_tip) = selection.refs(self, cancel)?; let urls = remote_push_urls(self, &selection.remote, cancel)?; let mut result = PushInspection { @@ -406,7 +406,7 @@ impl Repo { cancel: &CancellationToken, out: &dyn Fn(String), ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let target = selection.target_ref(self, cancel)?; let urls = remote_push_urls(self, &selection.remote, cancel)?; let [url] = urls.as_slice() else { diff --git a/crates/ide-vcs/src/rebase_editor.rs b/crates/ide-vcs/src/rebase_editor.rs index 6a038bb1b7..7c4b392f57 100644 --- a/crates/ide-vcs/src/rebase_editor.rs +++ b/crates/ide-vcs/src/rebase_editor.rs @@ -7,7 +7,6 @@ use std::cell::{Cell, RefCell}; use std::collections::{BTreeMap, HashSet}; use std::ffi::OsStr; use std::fs; -use std::sync::atomic::Ordering; #[derive(Deserialize, Serialize, Type)] #[serde(tag = "kind", rename_all = "camelCase")] @@ -110,7 +109,7 @@ impl Repo { if cancel.is_cancelled() { return Err(IdeError::cancelled()); } - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(Ordering::Acquire)); + let _scope = self.execution_scope(); if self.operation()?.as_deref() != Some("rebase") { return Err(IdeError::invalid("No rebase in progress")); } @@ -140,7 +139,7 @@ impl Repo { if cancel.is_cancelled() { return Err(IdeError::cancelled()); } - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(Ordering::Acquire)); + let _scope = self.execution_scope(); let mut args = rebase_args(upstream, options)?; self.validate_rebase(options)?; args.insert(1, "--interactive".into()); diff --git a/crates/ide-vcs/src/remotes.rs b/crates/ide-vcs/src/remotes.rs index 978005a335..f3038157cc 100644 --- a/crates/ide-vcs/src/remotes.rs +++ b/crates/ide-vcs/src/remotes.rs @@ -105,7 +105,7 @@ impl Repo { /// Configured remotes with their fetch URLs. pub fn remotes(&self) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let out = cli::run(self.root(), &["remote", "-v"], None)?; Ok(parse_remotes(&out.stdout_str())) } @@ -123,7 +123,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let mut args = vec!["fetch", "--progress"]; args.extend(fetch_tag_args(mode, true)); if let Some(remote) = remote { @@ -167,7 +167,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); if cancel.is_cancelled() { return Err(IdeError::cancelled()); } @@ -266,7 +266,7 @@ impl Repo { /// Whether `rev` names a commit present in the object database. pub fn has_commit(&self, rev: &str) -> bool { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); check_rev(rev).is_ok() && cli::run_raw(self.root(), &["cat-file", "-e", &format!("{rev}^{{commit}}")], None) .is_ok_and(|o| o.code == Some(0)) @@ -281,7 +281,7 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); check_rev(remote)?; for r in refspecs { check_rev(r)?; @@ -293,7 +293,7 @@ impl Repo { /// The best common ancestor of two revisions, if any. pub fn merge_base(&self, a: &str, b: &str) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); check_rev(a)?; check_rev(b)?; let out = cli::run_raw(self.root(), &["merge-base", a, b], None)?; @@ -302,7 +302,7 @@ impl Repo { /// Files changed between two revisions (renames detected). pub fn diff_files(&self, from: &str, to: &str) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); check_rev(from)?; check_rev(to)?; let out = cli::run( diff --git a/crates/ide-vcs/src/repo.rs b/crates/ide-vcs/src/repo.rs index e41f028abe..3f21f82454 100644 --- a/crates/ide-vcs/src/repo.rs +++ b/crates/ide-vcs/src/repo.rs @@ -80,6 +80,7 @@ pub(crate) fn discover(path: &Path) -> IdeResult> { let cache = Cache { stamp: stamp(&files), files, repo: ts, pack_stamp: pack_stamp(&pack_dir), pack_dir }; Ok(Some(Repo { execution_allowed: std::sync::atomic::AtomicBool::new(false), + git_executable: std::sync::RwLock::new(crate::opening_git_executable()), root, git_dir, inner: std::sync::Mutex::new(cache), @@ -114,7 +115,7 @@ impl Repo { /// A thread-local gitoxide handle; reopened when configuration or packed refs change. /// gitoxide's packed-ref snapshot only reloads for a newer mtime, which a replacement may preserve. pub(crate) fn gix(&self) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); if !self.execution_allowed.load(std::sync::atomic::Ordering::Acquire) { return gix::open_opts(&self.git_dir, gix::open::Options::default().filter_config_section(|_| false)) .map_err(gx); @@ -140,7 +141,7 @@ impl Repo { /// Repository-relative path with `/` separators. Accepts absolute paths inside the /// worktree or paths already relative to it. pub(crate) fn rel_path(&self, path: &Path) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); Ok(self.index_spelling(self.given_rel_path(path)?)) } @@ -161,7 +162,7 @@ impl Repo { } pub fn diff_entry_at(&self, path: &Path, rev: &str) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let repo = self.gix()?; let given = self.given_rel_path(path)?; let indexed = self.index_spelling(given.clone()); @@ -264,7 +265,7 @@ impl Repo { /// Absolute path for a repository-relative path. pub(crate) fn abs_path(&self, rel: &str) -> PathBuf { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let mut p = self.root.clone(); for part in rel.split('/').filter(|s| !s.is_empty()) { p.push(part); diff --git a/crates/ide-vcs/src/shelf.rs b/crates/ide-vcs/src/shelf.rs index ff838b26e4..c1cd08f1fe 100644 --- a/crates/ide-vcs/src/shelf.rs +++ b/crates/ide-vcs/src/shelf.rs @@ -147,7 +147,7 @@ pub struct ShelfCapture { impl ShelfCapture { pub fn capture(r: &Repo, base: &Path, paths: &[PathBuf]) -> IdeResult { - let _scope = crate::ExecutionScope::enter(r.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = r.execution_scope(); let repo = r.root().to_path_buf(); let prefix = repository_prefix(&repo, base)?; let (patch, files) = @@ -160,7 +160,7 @@ impl ShelfCapture { } pub fn revert(&self, r: &Repo) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(r.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = r.execution_scope(); if r.root() != self.repo { return Err(IdeError::invalid("The shelf repository has changed")); } @@ -230,7 +230,7 @@ pub struct ShelfSelection { impl ShelfSelection { pub fn apply(&self, r: &Repo) -> IdeResult { - let _scope = crate::ExecutionScope::enter(r.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = r.execution_scope(); let mut outcome = crate::patch::apply_with_prefix(r, &self.patch, &self.prefix)?; for path in outcome.applied.iter_mut().chain(outcome.conflicts.iter_mut()) { *path = format!("{}{path}", self.prefix); @@ -722,7 +722,7 @@ pub(crate) fn unshelve(r: &Repo, shelf: &Path, id: &str, remove: bool) -> IdeRes } pub fn unshelve_path(r: &Repo, shelf: &Path, id: &str, remove: bool, path: Option<&str>) -> IdeResult { - let _scope = crate::ExecutionScope::enter(r.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = r.execution_scope(); let patch = selected_patch(shelf, id, path)?; let outcome = crate::patch::apply(r, &patch)?; if remove && outcome.conflicts.is_empty() { @@ -800,7 +800,7 @@ pub fn diff_files(r: &Repo, shelf: &Path, id: &str) -> IdeResult IdeResult> { - let _scope = crate::ExecutionScope::enter(r.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = r.execution_scope(); let strip = crate::patch::strip_option(prefix); let mut apply = vec!["apply"]; apply.extend(strip.as_deref()); diff --git a/crates/ide-vcs/src/signing.rs b/crates/ide-vcs/src/signing.rs index 8af1962342..b2e7a03283 100644 --- a/crates/ide-vcs/src/signing.rs +++ b/crates/ide-vcs/src/signing.rs @@ -1,4 +1,4 @@ -use crate::{ExecutionScope, Repo, cli, execution_allowed}; +use crate::{Repo, cli, execution_allowed}; use gix::lock::{self, acquire::Fail}; use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind}; use serde::{Deserialize, Serialize}; @@ -6,7 +6,6 @@ use specta::Type; use std::io; use std::path::{Path, PathBuf}; use std::process::Command; -use std::sync::atomic::Ordering; #[derive(Debug, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] @@ -40,7 +39,7 @@ impl Repo { } pub fn gpg_signing_keys(&self, cancel: &CancellationToken) -> IdeResult> { - let _scope = ExecutionScope::enter(self.execution_allowed.load(Ordering::Acquire)); + let _scope = self.execution_scope(); self.require_openpgp()?; let program = gpg_program(self.root(), cancel)?; let mut cmd = Command::new(&program); @@ -58,7 +57,7 @@ impl Repo { } pub fn edit_signing(&self, edit: GitSigningEdit) -> IdeResult<()> { - let _scope = ExecutionScope::enter(self.execution_allowed.load(Ordering::Acquire)); + let _scope = self.execution_scope(); self.require_openpgp()?; if edit.enabled.is_none() && edit.key.is_none() { return Ok(()); @@ -199,6 +198,7 @@ fn decode_user_id(value: &str) -> String { #[cfg(test)] mod tests { use super::*; + use crate::ExecutionScope; const FINGERPRINT: &str = "1234567890123456789012345678901234567890"; const SUBKEY: &str = "ABCDEFABCDEFABCDEFABCDEFABCDEFABCDEFABCD"; diff --git a/crates/ide-vcs/src/staged_text.rs b/crates/ide-vcs/src/staged_text.rs index 098244a815..571a5ee97c 100644 --- a/crates/ide-vcs/src/staged_text.rs +++ b/crates/ide-vcs/src/staged_text.rs @@ -13,7 +13,7 @@ use crate::cli::TempIndex; use crate::diff::{normalize_eol, replace_text}; use crate::repo::{blob_data, gx}; use crate::text_encoding::{TextEncoding, decode, encode, has_bom, is_binary}; -use crate::{ApplyCommitReview, ExecutionScope, HunkKind, Repo, write}; +use crate::{ApplyCommitReview, HunkKind, Repo, write}; #[derive(Debug, Serialize, Deserialize, Type)] pub struct StagedText { @@ -146,7 +146,7 @@ impl Repo { max_bytes: usize, encoding: impl FnOnce(&[u8]) -> TextEncoding, ) -> IdeResult> { - let _scope = ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let repo = self.gix()?; let rel = self.rel_path(path)?; let Some(entry) = staged_entry(&repo, &rel)? else { @@ -174,7 +174,7 @@ impl Repo { text: &str, encoding: impl FnOnce(&[u8]) -> TextEncoding, ) -> IdeResult { - let _scope = ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let repo = self.gix()?; let path_to_index = repo.index_path(); let lock = @@ -211,7 +211,7 @@ impl Repo { cancel: &CancellationToken, encoding: impl Fn(&Path, &[u8]) -> TextEncoding, ) -> IdeResult { - let _scope = ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let repo = self.gix()?; let index_path = repo.index_path(); let lock = diff --git a/crates/ide-vcs/src/submodules.rs b/crates/ide-vcs/src/submodules.rs index 7713acd13c..833097058e 100644 --- a/crates/ide-vcs/src/submodules.rs +++ b/crates/ide-vcs/src/submodules.rs @@ -55,7 +55,7 @@ impl Repo { source: SubmoduleRollbackSource, restore_checkout: bool, ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); if !crate::execution_allowed() { return Err(IdeError::invalid("Submodule rollback requires a trusted project")); } @@ -133,10 +133,9 @@ impl Repo { cancel: &CancellationToken, on_output: &dyn Fn(String), ) -> IdeResult<()> { - let _scope = crate::ExecutionScope::enter( - self.execution_allowed.load(std::sync::atomic::Ordering::Acquire) - && parent.execution_allowed.load(std::sync::atomic::Ordering::Acquire), - ); + // The superproject's git runs it; the submodule can only restrict what it may do. + let _parent = parent.execution_scope(); + let _scope = self.execution_scope(); if !crate::execution_allowed() { return Err(IdeError::invalid("Submodule update requires a trusted project")); } diff --git a/crates/ide-vcs/src/worktree_config.rs b/crates/ide-vcs/src/worktree_config.rs index 183d46b713..e47052bf63 100644 --- a/crates/ide-vcs/src/worktree_config.rs +++ b/crates/ide-vcs/src/worktree_config.rs @@ -28,7 +28,7 @@ impl Repo { return Ok(()); } let root = self.root(); - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let matches = run( root, &["ls-files", "-z", "--cached", "--others", "--ignored", "--exclude-from=.worktreeinclude"], diff --git a/crates/ide-vcs/src/write.rs b/crates/ide-vcs/src/write.rs index d1b745ec2f..a0150160a9 100644 --- a/crates/ide-vcs/src/write.rs +++ b/crates/ide-vcs/src/write.rs @@ -22,7 +22,7 @@ const UNCOMMITTED_AUTHOR: &str = "Not Committed Yet"; impl Repo { pub(crate) fn rel_paths(&self, paths: &[PathBuf]) -> IdeResult> { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); paths .iter() .map(|p| { @@ -33,7 +33,7 @@ impl Repo { } pub(crate) fn has_head(&self) -> IdeResult { - let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let _scope = self.execution_scope(); let repo = self.gix()?; Ok(!repo.head().map_err(gx)?.is_unborn()) } diff --git a/crates/ide-workspace/src/dependencies/mod.rs b/crates/ide-workspace/src/dependencies/mod.rs index 9560c408cc..f5449a85a4 100644 --- a/crates/ide-workspace/src/dependencies/mod.rs +++ b/crates/ide-workspace/src/dependencies/mod.rs @@ -4,6 +4,7 @@ pub mod cargo; pub mod go; pub mod maven; pub mod npm; +pub mod python; pub use cache::VersionCache; use ide_core::{CancellationToken, IdeResult}; @@ -48,3 +49,20 @@ pub struct DependencyVersions { pub versions: Vec, pub update: Option, } + +/// A requirement the project's interpreter does not satisfy. +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct UnsatisfiedRequirement { + pub dependency: ManifestDependency, + /// The installed version that misses the specifier; `None` when not installed. + pub installed: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PythonRequirements { + /// The interpreter checked, which installs go to. + pub python: ide_core::IpcPath, + pub unsatisfied: Vec, +} diff --git a/crates/ide-workspace/src/dependencies/python.rs b/crates/ide-workspace/src/dependencies/python.rs new file mode 100644 index 0000000000..5a725d69e8 --- /dev/null +++ b/crates/ide-workspace/src/dependencies/python.rs @@ -0,0 +1,193 @@ +//! Python requirements in `requirements*.txt` and `pyproject.toml`. Whether one is +//! satisfied is up to the interpreter (`ide-sdk`): markers and PEP 440 depend on it. +use super::ManifestDependency; +use toml_edit::{Document, Item}; + +/// `requirements.txt`, `requirements-dev.txt`, `requirements/base.txt`'s siblings named alike. +pub fn is_requirements_file(name: &str) -> bool { + name.starts_with("requirements") && name.ends_with(".txt") +} + +/// The requirements of a manifest, by file name; `requirement` is the PEP 508 string +/// and `from..to` its UTF-16 span. +pub fn requirements(file_name: &str, text: &str) -> Vec { + if file_name == "pyproject.toml" { + pyproject(text) + } else if is_requirements_file(file_name) { + requirements_txt(text) + } else { + Vec::new() + } +} + +/// The distribution name a requirement starts with, if it names one (not a URL, path or archive). +fn named(requirement: &str) -> Option { + let end = requirement + .find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))) + .unwrap_or(requirement.len()); + let name = requirement[..end].trim_end_matches(['.', '-', '_']); + let rest = requirement[end..].trim_start(); + if name.is_empty() + || !name.as_bytes()[0].is_ascii_alphanumeric() + || rest.starts_with([':', '/', '\\']) + || !rest.starts_with('@') && [".whl", ".zip", ".tar.gz", ".tgz"].iter().any(|ext| requirement.ends_with(ext)) + || requirement.contains("://") && !rest.starts_with(['@', '[']) + { + return None; + } + Some(ManifestDependency { package: name.to_owned(), requirement: requirement.to_owned(), from: 0, to: 0 }) +} + +fn utf16(text: &str, byte: usize) -> u32 { + text[..byte].encode_utf16().count() as u32 +} + +fn requirements_txt(text: &str) -> Vec { + let mut out = Vec::new(); + let mut start = 0; + for line in text.split_inclusive('\n') { + let line_start = start; + start += line.len(); + let body = line.trim_end_matches(['\n', '\r']); + // A comment starts the line or follows whitespace; per-requirement options (`--hash`) follow ` -`. + let cut = [" #", "\t#", " --", "\t--", " \\"].iter().filter_map(|m| body.find(m)).min().unwrap_or(body.len()); + let content = body[..cut].trim_end(); + let lead = content.len() - content.trim_start().len(); + let requirement = content.trim_start(); + if requirement.is_empty() || requirement.starts_with(['#', '-']) || is_continuation(text, line_start) { + continue; + } + if let Some(mut dep) = named(requirement) { + dep.from = utf16(text, line_start + lead); + dep.to = utf16(text, line_start + lead + requirement.len()); + out.push(dep); + } + } + out +} + +/// The previous physical line ends with `\`: this one continues it (its options). +fn is_continuation(text: &str, line_start: usize) -> bool { + text[..line_start].trim_end_matches(['\n', '\r']).ends_with('\\') +} + +fn pyproject(text: &str) -> Vec { + let Ok(doc) = text.parse::>() else { return Vec::new() }; + let mut arrays = Vec::new(); + if let Some(project) = doc.get("project").and_then(Item::as_table_like) { + arrays.extend(project.get("dependencies")); + if let Some(extras) = project.get("optional-dependencies").and_then(Item::as_table_like) { + arrays.extend(extras.iter().map(|(_, item)| item)); + } + } + // PEP 735 groups; `{ include-group = "…" }` entries aren't strings and are skipped. + if let Some(groups) = doc.get("dependency-groups").and_then(Item::as_table_like) { + arrays.extend(groups.iter().map(|(_, item)| item)); + } + let mut out = Vec::new(); + for value in arrays.into_iter().filter_map(Item::as_array).flat_map(|a| a.iter()) { + let (Some(requirement), Some(span)) = (value.as_str(), value.span()) else { continue }; + let Some(raw) = text.get(span.clone()) else { continue }; + let delimiter = if raw.starts_with("\"\"\"") || raw.starts_with("'''") { 3 } else { 1 }; + if let Some(mut dep) = named(requirement.trim()) { + dep.from = utf16(text, span.start + delimiter); + dep.to = utf16(text, span.end - delimiter); + out.push(dep); + } + } + out.sort_unstable_by_key(|d| d.from); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn names(deps: &[ManifestDependency], text: &str) -> Vec<(String, String)> { + let units: Vec = text.encode_utf16().collect(); + deps.iter() + .map(|d| { + let span = String::from_utf16(&units[d.from as usize..d.to as usize]).unwrap(); + assert_eq!(span, d.requirement, "span matches the requirement"); + (d.package.clone(), d.requirement.clone()) + }) + .collect() + } + + #[test] + fn requirements_txt_keeps_named_requirements_only() { + let text = "# 中文 😀 comment\n\ + Django>=4.2,<5 # web\n\ + typing_extensions\n\ + requests[socks]==2.31.0 ; python_version >= \"3.8\"\n\ + -r base.txt\n\ + --index-url https://pypi.org/simple\n\ + -e ./local\n\ + ./pkg\n\ + /abs/path\n\ + https://example.com/x.tar.gz\n\ + foo-1.0-py3-none-any.whl\n\ + pkg @ https://example.com/pkg.zip\n\ + numpy==1.26.4 \\\n --hash=sha256:abc \\\n --hash=sha256:def\n\ + \n \n\ + black --config-settings=x=y\n"; + let deps = requirements("requirements.txt", text); + assert_eq!( + names(&deps, text), + [ + ("Django", "Django>=4.2,<5"), + ("typing_extensions", "typing_extensions"), + ("requests", "requests[socks]==2.31.0 ; python_version >= \"3.8\""), + ("pkg", "pkg @ https://example.com/pkg.zip"), + ("numpy", "numpy==1.26.4"), + ("black", "black"), + ] + .map(|(a, b)| (a.to_owned(), b.to_owned())) + ); + } + + #[test] + fn requirements_files_by_name() { + assert!(is_requirements_file("requirements.txt")); + assert!(is_requirements_file("requirements-dev.txt")); + assert!(!is_requirements_file("constraints.txt")); + assert!(requirements("notes.txt", "django\n").is_empty()); + } + + #[test] + fn pyproject_project_extras_and_groups() { + let text = r#"[build-system] +requires = ["setuptools"] + +[project] +name = "demo" +dependencies = [ + "flask>=3", # 注释 + 'PyYAML', + "local @ file:///tmp/x", +] + +[project.optional-dependencies] +test = ["pytest>=8; python_version>='3.9'"] + +[dependency-groups] +dev = ["ruff", { include-group = "test" }] + +[tool.poetry.dependencies] +ignored = "^1" +"#; + let deps = requirements("pyproject.toml", text); + assert_eq!( + names(&deps, text), + [ + ("flask", "flask>=3"), + ("PyYAML", "PyYAML"), + ("local", "local @ file:///tmp/x"), + ("pytest", "pytest>=8; python_version>='3.9'"), + ("ruff", "ruff"), + ] + .map(|(a, b)| (a.to_owned(), b.to_owned())) + ); + assert!(requirements("pyproject.toml", "[project\n").is_empty()); + } +} diff --git a/crates/ide-workspace/src/settings.rs b/crates/ide-workspace/src/settings.rs index c4c136607e..7f125782cf 100644 --- a/crates/ide-workspace/src/settings.rs +++ b/crates/ide-workspace/src/settings.rs @@ -355,6 +355,11 @@ impl SettingsStore { self.effective.read().clone() } + /// Reads part of the effective settings without copying all of them. + pub fn read_effective(&self, read: impl FnOnce(&Settings) -> T) -> T { + read(&self.effective.read()) + } + /// Settings defined in `scope`'s file alone (without merging the other layer). pub fn layer(&self, scope: SettingsScope) -> Settings { let mut merged = defaults_json(); diff --git a/docs/en/contribute/setup.mdx b/docs/en/contribute/setup.mdx index 899349675b..af1a0cd65e 100644 --- a/docs/en/contribute/setup.mdx +++ b/docs/en/contribute/setup.mdx @@ -67,7 +67,7 @@ mise run dev `setup` runs `pnpm install` in this worktree. `dev` and `dev:app` use the same worktree-aware launchers as the direct commands. No shell activation is needed for `mise run`. -Run `mise tasks` to list all tasks. `mise run build` builds the frontend (not a desktop installer); `mise run dogfood:build` and `mise run dogfood:install` build and locally install a grey-icon dogfood desktop app that shares settings and data with the release app. Only one of the two apps runs at a time, since they share one instance; settings written by the newer dogfood build can make an older release ignore the settings file. The dogfood app never updates itself: run `dogfood:install` again to pick up new changes. `mise run test` runs Vitest and `cargo test --workspace`; `mise run check` runs the format, lint, type and unused-code checks, then both test suites. Neither requires nextest or the plugin WASM target. +Run `mise tasks` to list all tasks. `mise run build` builds the frontend (not a desktop installer); `mise run dogfood:build` and `mise run dogfood:install` build and locally install a grey-icon dogfood desktop app that shares settings and data with the release app. Only one of the two apps runs at a time, since they share one instance; settings written by the newer dogfood build can make an older release ignore the settings file. The dogfood app never updates itself: run `dogfood:install` again to pick up new changes. `mise run dogfood:remote ` builds and stages `openidea-server` on an SSH host configured in **Tools › SSH Configurations** (`--clean` removes the override). `mise run test` runs Vitest and `cargo test --workspace`; `mise run check` runs the format, lint, type and unused-code checks, then both test suites. Neither requires nextest or the plugin WASM target. ## Worktrees diff --git a/docs/en/guide/editor.mdx b/docs/en/guide/editor.mdx index cd6221c0a9..58003313a6 100644 --- a/docs/en/guide/editor.mdx +++ b/docs/en/guide/editor.mdx @@ -88,7 +88,7 @@ All folding commands are also in **Code › Folding**. Fold regions come from th | **Auto-Indent Lines** | `⌃⌥I` | `Ctrl+Alt+I` | | **Optimize Imports** | `⌃⌥O` | `Ctrl+Alt+O` | -**Reformat Code** formats the selection, or the whole file when nothing is selected, as one undo step. The formatting comes from the file's language server or from the formatter the language is configured with (for example Ruff for Python, Prettier or oxfmt for web languages; find their commands as **Reformat with …** in Find Action). **Reformat File…** also lets you choose the scope and optimize imports. +**Reformat Code** formats the selection, or the whole file when nothing is selected, as one undo step. The formatting comes from the file's language server or from the formatter the language is configured with (for example Ruff for Python, Prettier, oxfmt or Biome for web languages; find their commands as **Reformat with …** in Find Action). **Reformat File…** also lets you choose the scope and optimize imports. Indentation and other style options are under **Settings › Editor › Code Style**, with a page per language. `.editorconfig` files in the project are read too. diff --git a/docs/en/guide/run.mdx b/docs/en/guide/run.mdx index fa64aca9b6..63436ce87f 100644 --- a/docs/en/guide/run.mdx +++ b/docs/en/guide/run.mdx @@ -19,6 +19,7 @@ When a project opens, OpenIDEA scans its build files (also in nested projects of | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `package.json` | One per `scripts` entry, run with the package manager of the lock file (npm, pnpm, yarn or bun). `test`, `test:*`, `jest` and `vitest` scripts are marked as tests. | | `deno.json` / `deno.jsonc` | Deno tasks | +| `playwright.config.*` | Scripts that run `playwright test` are tests; without one, `npx playwright test` | | `Cargo.toml` | `cargo run` for each binary, `cargo test`, `cargo build`; workspace members are included | | `build.gradle(.kts)` / `pom.xml` | Gradle and Maven run configurations | | `go.mod` / `go.work` | Go programs and tests | diff --git a/docs/en/guide/testing.mdx b/docs/en/guide/testing.mdx index 2972a79bf5..65af9ef708 100644 --- a/docs/en/guide/testing.mdx +++ b/docs/en/guide/testing.mdx @@ -32,7 +32,7 @@ Running a single test creates a temporary run configuration based on the project | Language | Gutter icons on | Runs with | | --------------------------- | --------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | | Rust | `#[test]` functions, `mod tests` | `cargo test`, `cargo nextest` | -| JavaScript / TypeScript | `test`, `it`, `describe`, `suite`, `context` (also `.each`, `.only`, `.skip`) | Jest or Vitest through the project's test script; Deno and Bun | +| JavaScript / TypeScript | `test`, `it`, `describe`, `suite`, `context` (also `.each`, `.only`, `.skip`) | Jest or Vitest via the test script; Playwright Test; Deno, Bun | | Python | pytest `def test_*` and `class Test*`, unittest `TestCase` subclasses | pytest, Django `manage.py test` | | Go | `func TestX(t *testing.T)`, benchmarks | `go test` | | Java, Kotlin, Scala, Groovy | JUnit `@Test`, `@ParameterizedTest`, `@RepeatedTest`, `@TestFactory`, `@TestTemplate`; TestNG | Maven Surefire (`-Dtest=`) or Gradle (`--tests`) | @@ -66,7 +66,7 @@ Detected test configurations show results in the tree automatically. For your ow | **Rerun** (in the Run tool window) | `⌘R` | `Ctrl+F5` | | **Rerun Failed Tests** | — | — | -**Rerun Failed Tests** (in the Run tool window toolbar and Find Action) runs only the tests that failed in the last run, using each tool's filter syntax. It works for Cargo, Jest / Vitest, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks. +**Rerun Failed Tests** (in the Run tool window toolbar and Find Action) runs only the tests that failed in the last run, using each tool's filter syntax. It works for Cargo, Jest / Vitest, Playwright, `node --test`, Mocha, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks. ## Navigate between code and tests diff --git a/docs/en/languages/index.mdx b/docs/en/languages/index.mdx index 92b88990e8..c0c1f61bf0 100644 --- a/docs/en/languages/index.mdx +++ b/docs/en/languages/index.mdx @@ -34,7 +34,7 @@ For a recognized file, support comes in layers: A language can list more than one server: - **Alternatives** (shown as `a → b` in the table below): only the first one that is installed runs. Python, for example, uses basedpyright, and falls back to pyright, ty or pyrefly only when basedpyright is missing. In **Settings › Languages & Frameworks › Language Servers** you can pick one of them or set the choice to **Automatic** (the first one available). -- **Additions** (shown as `+ b`): run next to the main server, usually only in projects that use them. Ruff joins basedpyright in projects with a Ruff configuration; oxlint joins vtsls in projects with an oxlint configuration; the Angular and Laravel servers join in Angular and Laravel projects. +- **Additions** (shown as `+ b`): run next to the main server, usually only in projects that use them. Ruff joins basedpyright in projects with a Ruff configuration; oxlint joins vtsls in projects with an oxlint configuration; Stylelint joins the CSS, SCSS and Less server in projects with a Stylelint configuration (`.stylelintrc*`, `stylelint.config.*` or `stylelint` in `package.json`), running the project's own `stylelint` (**Fix Stylelint Problems** in the editor's context menu applies its fixes); Biome joins the JavaScript, TypeScript, JSON, CSS and GraphQL servers in projects with a Biome configuration or installation; the Angular, Laravel and Tailwind CSS servers join in Angular, Laravel and Tailwind CSS projects. ## Installing language servers and debuggers @@ -91,92 +91,92 @@ Selecting a language server on the Language Servers page shows its settings, whi The table lists every built-in language definition. Server and debugger names in **bold** can be installed from the IDE; the others you install yourself (the install hint in the IDE says how). "Highlighting" and "Tree-sitter" mark instant highlighting and the bundled grammar for outline and folding. -| Language | ID | Files | Highlighting | Tree-sitter | Language servers | Debugger | -| ------------------- | ------------------ | ----------------------------------------------------------- | ------------ | ----------- | ------------------------------------------------------------------------------------- | ------------------------ | -| .env | `dotenv` | `.env` | Yes | — | — | — | -| Arduino | `arduino` | `.ino` | Yes | Yes | arduino-language-server | — | -| AsciiDoc | `asciidoc` | `.adoc`, `.asciidoc` | Yes | — | — | — | -| Astro | `astro` | `.astro` | Yes | — | **astro-ls** + **oxlint** | — | -| Batch | `bat` | `.bat`, `.cmd` | Yes | — | — | — | -| C | `c` | `.c`, `.h` | Yes | Yes | **clangd** | lldb-dap | -| C# | `csharp` | `.cs`, `.csx` | Yes | Yes | **csharp-ls** | **netcoredbg** | -| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | Yes | Yes | **clangd** | lldb-dap | -| Clojure | `clojure` | `.clj`, `.cljs`, `.cljc`, `.cljd`, `.edn`, … | Yes | — | **clojure-lsp** | — | -| CMake | `cmake` | `.cmake` | Yes | Yes | **neocmakelsp** → cmake-language-server | — | -| CSS | `css` | `.css`, `.pcss`, `.postcss` | Yes | Yes | **vscode-css-language-server** | — | -| D | `d` | `.d`, `.di` | Yes | — | serve-d | — | -| Dart | `dart` | `.dart` | Yes | Yes | dart | dart | -| Diff | `diff` | `.diff`, `.patch`, `.rej` | Yes | — | — | — | -| Django Template | `django-html` | `.djhtml`, `templates/*.html`, `*.txt` | Yes | Yes | **vscode-html-language-server**, **djlsp** | — | -| Dockerfile | `dockerfile` | `.dockerfile`, `.containerfile` | Yes | — | **dockerfile-language-server** | — | -| Elixir | `elixir` | `.ex`, `.exs` | Yes | Yes | **elixir-ls** | **elixir-ls-debugger** | -| ERB | `erb` | `.erb`, `.html.erb`, `.rhtml`, `.js.erb`, `.text.erb`, … | Yes | — | — | — | -| Erlang | `erlang` | `.erl`, `.hrl`, `.escript`, `.app.src` | Yes | — | elp | — | -| F# | `fsharp` | `.fs`, `.fsi`, `.fsx` | Yes | — | **fsautocomplete** | **netcoredbg** | -| GDScript | `gdscript` | `.gd` | Yes | Yes | godot | godot | -| Git Attributes | `gitattributes` | `.gitattributes` | — | — | — | — | -| Go | `go` | `.go` | Yes | Yes | **gopls** | **delve** | -| Go Module | `go.mod` | `go.mod` | Yes | — | **gopls** | — | -| Go Workspace | `go.work` | `go.work` | Yes | — | **gopls** | — | -| Godot Resource | `godot-resource` | `.tscn`, `.tres`, `.godot`, `.import` | Yes | — | — | — | -| Godot Shader | `gdshader` | `.gdshader`, `.gdshaderinc` | Yes | — | — | — | -| GraphQL | `graphql` | `.graphql`, `.graphqls`, `.gql` | Yes | Yes | **graphql-lsp** | — | -| Groovy | `groovy` | `.groovy`, `.gradle`, `.gvy`, `.gy`, `.gsh` | Yes | — | groovy-language-server | — | -| Haskell | `haskell` | `.hs`, `.hs-boot`, `.hsig` | Yes | Yes | haskell-language-server | — | -| HCL | `hcl` | `.hcl`, `.nomad`, `.pkr.hcl` | Yes | Yes | — | — | -| HTML | `html` | `.html`, `.htm`, `.xhtml`, `.shtml`, `.html.tmpl` | Yes | Yes | **vscode-html-language-server** + **angular-language-server** | — | -| HTTP Request | `http` | `.http`, `.rest` | Yes | — | — | — | -| Ignore File | `ignore` | `.gitignore`, `.dockerignore` | — | — | — | — | -| INI | `ini` | `.ini`, `.cfg`, `.conf`, `.cnf`, `.inf`, … | Yes | — | — | — | -| Java | `java` | `.java` | Yes | Yes | **jdtls** → **java-analyzer** → **kmp-lsp** | **java-debug** | -| JavaScript | `javascript` | `.js`, `.mjs`, `.cjs` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** | -| JavaScript JSX | `javascriptreact` | `.jsx` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** | -| JSON | `json` | `.json`, `.geojson`, `.topojson`, `.webmanifest`, `.har`, … | Yes | Yes | **vscode-json-language-server** | — | -| JSON with Comments | `jsonc` | `.jsonc`, `.code-workspace`, `.code-snippets` | Yes | Yes | **vscode-json-language-server** | — | -| JSP | `jsp` | `.jsp`, `.jspx`, `.jspf`, `.jsph`, `.tag`, … | Yes | — | — | — | -| Julia | `julia` | `.jl` | Yes | — | julia-languageserver | — | -| Kotlin | `kotlin` | `.kt`, `.kts` | Yes | Yes | **kotlin-lsp** → **kotlin-language-server** → **kmp-lsp** | **kotlin-debug-adapter** | -| LaTeX | `latex` | `.tex`, `.ltx`, `.sty`, `.cls`, `.dtx`, … | Yes | — | **texlab** | — | -| Less | `less` | `.less` | Yes | — | **vscode-css-language-server** | — | -| Log | `log` | `.log` | Yes | — | — | — | -| Lua | `lua` | `.lua`, `.luau`, `.rockspec` | Yes | Yes | **lua-language-server** | — | -| Makefile | `makefile` | `.mk`, `.mak`, `.make` | Yes | Yes | — | — | -| Markdown | `markdown` | `.md`, `.markdown`, `.mdown`, `.mkd`, `.mkdn`, … | Yes | Yes | **marksman** | — | -| Nix | `nix` | `.nix` | Yes | Yes | nil → nixd | — | -| Objective-C | `objective-c` | `.m` | Yes | — | **clangd** | lldb-dap | -| Objective-C++ | `objective-cpp` | `.mm` | Yes | — | **clangd** | lldb-dap | -| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | Yes | Yes | ocamllsp | ocamlearlybird | -| OCaml Interface | `ocaml.interface` | `.mli` | Yes | Yes | ocamllsp | — | -| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | Yes | — | **perlnavigator** | — | -| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | Yes | Yes | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** | -| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — | -| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | Yes | — | powershell-editor-services | — | -| Prisma | `prisma` | `.prisma` | Yes | Yes | **prisma-language-server** | — | -| Properties | `properties` | `.properties`, `.prefs` | Yes | — | — | — | -| Protocol Buffers | `proto` | `.proto` | Yes | Yes | **buf** | — | -| Python | `python` | `.py`, `.pyi`, `.pyw` | Yes | Yes | **basedpyright** → **pyright** → **ty** → **pyrefly** + **ruff** | **debugpy** | -| R | `r` | `.r`, `.rprofile` | Yes | — | r-languageserver | — | -| reStructuredText | `restructuredtext` | `.rst` | Yes | — | — | — | -| Ruby | `ruby` | `.rb`, `.rake`, `.gemspec`, `.ru`, `.rbi`, … | Yes | Yes | **ruby-lsp** → **solargraph** | rdbg | -| Rust | `rust` | `.rs` | Yes | Yes | **rust-analyzer** | **codelldb** | -| Sass | `sass` | `.sass` | Yes | — | — | — | -| Scala | `scala` | `.scala`, `.sc`, `.sbt`, `.mill` | Yes | Yes | metals | — | -| SCSS | `scss` | `.scss` | Yes | — | **vscode-css-language-server** | — | -| Shell Script | `shellscript` | `.sh`, `.bash`, `.zsh`, `.ksh`, `.ash`, … | Yes | Yes | **bash-language-server** | **bash-debug** | -| Slint | `slint` | `.slint` | Yes | — | **slint-lsp** | — | -| SQL | `sql` | `.sql`, `.ddl`, `.dml`, `.psql`, `.pgsql`, … | Yes | — | **sqls** | — | -| Svelte | `svelte` | `.svelte` | Yes | — | **svelte-language-server** + **oxlint** | — | -| Swift | `swift` | `.swift`, `.swiftinterface` | Yes | Yes | sourcekit-lsp | lldb-dap | -| Terraform | `terraform` | `.tf`, `.tofu`, `.tftest.hcl` | Yes | Yes | **terraform-ls** | — | -| Terraform Variables | `terraform-vars` | `.tfvars` | Yes | Yes | **terraform-ls** | — | -| TOML | `toml` | `.toml` | Yes | Yes | **taplo** | — | -| TypeScript | `typescript` | `.ts`, `.mts`, `.cts` | Yes | Yes | **vtsls** → **typescript-language-server** + **angular-language-server** + **oxlint** | **js-debug** | -| TypeScript JSX | `typescriptreact` | `.tsx` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** | -| Typst | `typst` | `.typ` | — | — | **tinymist** | — | -| Vue | `vue` | `.vue` | Yes | — | **vue-language-server**, **vtsls** + **oxlint** | — | -| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | Yes | Yes | **lemminx** | — | -| YAML | `yaml` | `.yaml`, `.yml` | Yes | Yes | **yaml-language-server** | — | -| Zig | `zig` | `.zig`, `.zon` | Yes | Yes | **zls** | **codelldb** | +| Language | ID | Files | Highlighting | Tree-sitter | Language servers | Debugger | +| ------------------- | ------------------ | ----------------------------------------------------------- | ------------ | ----------- | ------------------------------------------------------------------------------------------------- | ------------------------ | +| .env | `dotenv` | `.env` | Yes | — | — | — | +| Arduino | `arduino` | `.ino` | Yes | Yes | arduino-language-server | — | +| AsciiDoc | `asciidoc` | `.adoc`, `.asciidoc` | Yes | — | — | — | +| Astro | `astro` | `.astro` | Yes | — | **astro-ls** + **oxlint** | — | +| Batch | `bat` | `.bat`, `.cmd` | Yes | — | — | — | +| C | `c` | `.c`, `.h` | Yes | Yes | **clangd** | lldb-dap | +| C# | `csharp` | `.cs`, `.csx` | Yes | Yes | **csharp-ls** | **netcoredbg** | +| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | Yes | Yes | **clangd** | lldb-dap | +| Clojure | `clojure` | `.clj`, `.cljs`, `.cljc`, `.cljd`, `.edn`, … | Yes | — | **clojure-lsp** | — | +| CMake | `cmake` | `.cmake` | Yes | Yes | **neocmakelsp** → cmake-language-server | — | +| CSS | `css` | `.css`, `.pcss`, `.postcss` | Yes | Yes | **vscode-css-language-server** + **biome** + **stylelint** | — | +| D | `d` | `.d`, `.di` | Yes | — | serve-d | — | +| Dart | `dart` | `.dart` | Yes | Yes | dart | dart | +| Diff | `diff` | `.diff`, `.patch`, `.rej` | Yes | — | — | — | +| Django Template | `django-html` | `.djhtml`, `templates/*.html`, `*.txt` | Yes | Yes | **vscode-html-language-server**, **djlsp** | — | +| Dockerfile | `dockerfile` | `.dockerfile`, `.containerfile` | Yes | — | **dockerfile-language-server** | — | +| Elixir | `elixir` | `.ex`, `.exs` | Yes | Yes | **elixir-ls** | **elixir-ls-debugger** | +| ERB | `erb` | `.erb`, `.html.erb`, `.rhtml`, `.js.erb`, `.text.erb`, … | Yes | — | — | — | +| Erlang | `erlang` | `.erl`, `.hrl`, `.escript`, `.app.src` | Yes | — | elp | — | +| F# | `fsharp` | `.fs`, `.fsi`, `.fsx` | Yes | — | **fsautocomplete** | **netcoredbg** | +| GDScript | `gdscript` | `.gd` | Yes | Yes | godot | godot | +| Git Attributes | `gitattributes` | `.gitattributes` | — | — | — | — | +| Go | `go` | `.go` | Yes | Yes | **gopls** | **delve** | +| Go Module | `go.mod` | `go.mod` | Yes | — | **gopls** | — | +| Go Workspace | `go.work` | `go.work` | Yes | — | **gopls** | — | +| Godot Resource | `godot-resource` | `.tscn`, `.tres`, `.godot`, `.import` | Yes | — | — | — | +| Godot Shader | `gdshader` | `.gdshader`, `.gdshaderinc` | Yes | — | — | — | +| GraphQL | `graphql` | `.graphql`, `.graphqls`, `.gql` | Yes | Yes | **graphql-lsp** + **biome** | — | +| Groovy | `groovy` | `.groovy`, `.gradle`, `.gvy`, `.gy`, `.gsh` | Yes | — | groovy-language-server | — | +| Haskell | `haskell` | `.hs`, `.hs-boot`, `.hsig` | Yes | Yes | haskell-language-server | — | +| HCL | `hcl` | `.hcl`, `.nomad`, `.pkr.hcl` | Yes | Yes | — | — | +| HTML | `html` | `.html`, `.htm`, `.xhtml`, `.shtml`, `.html.tmpl` | Yes | Yes | **vscode-html-language-server** + **angular-language-server** | — | +| HTTP Request | `http` | `.http`, `.rest` | Yes | — | — | — | +| Ignore File | `ignore` | `.gitignore`, `.dockerignore` | — | — | — | — | +| INI | `ini` | `.ini`, `.cfg`, `.conf`, `.cnf`, `.inf`, … | Yes | — | — | — | +| Java | `java` | `.java` | Yes | Yes | **jdtls** → **java-analyzer** → **kmp-lsp** | **java-debug** | +| JavaScript | `javascript` | `.js`, `.mjs`, `.cjs` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** | +| JavaScript JSX | `javascriptreact` | `.jsx` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** | +| JSON | `json` | `.json`, `.geojson`, `.topojson`, `.webmanifest`, `.har`, … | Yes | Yes | **vscode-json-language-server** + **biome** | — | +| JSON with Comments | `jsonc` | `.jsonc`, `.code-workspace`, `.code-snippets` | Yes | Yes | **vscode-json-language-server** + **biome** | — | +| JSP | `jsp` | `.jsp`, `.jspx`, `.jspf`, `.jsph`, `.tag`, … | Yes | — | — | — | +| Julia | `julia` | `.jl` | Yes | — | julia-languageserver | — | +| Kotlin | `kotlin` | `.kt`, `.kts` | Yes | Yes | **kotlin-lsp** → **kotlin-language-server** → **kmp-lsp** | **kotlin-debug-adapter** | +| LaTeX | `latex` | `.tex`, `.ltx`, `.sty`, `.cls`, `.dtx`, … | Yes | — | **texlab** | — | +| Less | `less` | `.less` | Yes | — | **vscode-css-language-server** + **stylelint** | — | +| Log | `log` | `.log` | Yes | — | — | — | +| Lua | `lua` | `.lua`, `.luau`, `.rockspec` | Yes | Yes | **lua-language-server** | — | +| Makefile | `makefile` | `.mk`, `.mak`, `.make` | Yes | Yes | — | — | +| Markdown | `markdown` | `.md`, `.markdown`, `.mdown`, `.mkd`, `.mkdn`, … | Yes | Yes | **marksman** | — | +| Nix | `nix` | `.nix` | Yes | Yes | nil → nixd | — | +| Objective-C | `objective-c` | `.m` | Yes | — | **clangd** | lldb-dap | +| Objective-C++ | `objective-cpp` | `.mm` | Yes | — | **clangd** | lldb-dap | +| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | Yes | Yes | ocamllsp | ocamlearlybird | +| OCaml Interface | `ocaml.interface` | `.mli` | Yes | Yes | ocamllsp | — | +| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | Yes | — | **perlnavigator** | — | +| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | Yes | Yes | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** | +| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — | +| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | Yes | — | powershell-editor-services | — | +| Prisma | `prisma` | `.prisma` | Yes | Yes | **prisma-language-server** | — | +| Properties | `properties` | `.properties`, `.prefs` | Yes | — | — | — | +| Protocol Buffers | `proto` | `.proto` | Yes | Yes | **buf** | — | +| Python | `python` | `.py`, `.pyi`, `.pyw` | Yes | Yes | **basedpyright** → **pyright** → **ty** → **pyrefly** + **ruff** | **debugpy** | +| R | `r` | `.r`, `.rprofile` | Yes | — | r-languageserver | — | +| reStructuredText | `restructuredtext` | `.rst` | Yes | — | — | — | +| Ruby | `ruby` | `.rb`, `.rake`, `.gemspec`, `.ru`, `.rbi`, … | Yes | Yes | **ruby-lsp** → **solargraph** | rdbg | +| Rust | `rust` | `.rs` | Yes | Yes | **rust-analyzer** | **codelldb** | +| Sass | `sass` | `.sass` | Yes | — | — | — | +| Scala | `scala` | `.scala`, `.sc`, `.sbt`, `.mill` | Yes | Yes | metals | — | +| SCSS | `scss` | `.scss` | Yes | — | **vscode-css-language-server** + **stylelint** | — | +| Shell Script | `shellscript` | `.sh`, `.bash`, `.zsh`, `.ksh`, `.ash`, … | Yes | Yes | **bash-language-server** | **bash-debug** | +| Slint | `slint` | `.slint` | Yes | — | **slint-lsp** | — | +| SQL | `sql` | `.sql`, `.ddl`, `.dml`, `.psql`, `.pgsql`, … | Yes | — | **sqls** | — | +| Svelte | `svelte` | `.svelte` | Yes | — | **svelte-language-server** + **oxlint** | — | +| Swift | `swift` | `.swift`, `.swiftinterface` | Yes | Yes | sourcekit-lsp | lldb-dap | +| Terraform | `terraform` | `.tf`, `.tofu`, `.tftest.hcl` | Yes | Yes | **terraform-ls** | — | +| Terraform Variables | `terraform-vars` | `.tfvars` | Yes | Yes | **terraform-ls** | — | +| TOML | `toml` | `.toml` | Yes | Yes | **taplo** | — | +| TypeScript | `typescript` | `.ts`, `.mts`, `.cts` | Yes | Yes | **vtsls** → **typescript-language-server** + **angular-language-server** + **oxlint** + **biome** | **js-debug** | +| TypeScript JSX | `typescriptreact` | `.tsx` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** | +| Typst | `typst` | `.typ` | — | — | **tinymist** | — | +| Vue | `vue` | `.vue` | Yes | — | **vue-language-server**, **vtsls** + **oxlint** | — | +| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | Yes | Yes | **lemminx** | — | +| YAML | `yaml` | `.yaml`, `.yml` | Yes | Yes | **yaml-language-server** | — | +| Zig | `zig` | `.zig`, `.zon` | Yes | Yes | **zls** | **codelldb** | Notes: diff --git a/docs/en/languages/javascript.mdx b/docs/en/languages/javascript.mdx index 087f68aaac..4947c1744c 100644 --- a/docs/en/languages/javascript.mdx +++ b/docs/en/languages/javascript.mdx @@ -7,16 +7,18 @@ OpenIDEA edits JavaScript (`.js`, `.mjs`, `.cjs`, `.jsx`) and TypeScript (`.ts`, ## Language servers -| Files | Server | Notes | -| ------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | -| JS, JSX, TS, TSX | `vtsls` | Default TypeScript server. | -| JS, JSX, TS, TSX | `typescript-language-server` | Fallback: used only while `vtsls` is not installed. | -| `.vue` | `vue-language-server` + `vtsls` | Vue's hybrid mode: TypeScript inside `.vue` files comes from `vtsls` with `@vue/typescript-plugin`. | -| `.svelte` | `svelte-language-server` | | -| `.astro` | `astro-ls` | Needs Node.js and a TypeScript library. | -| TS and HTML in Angular projects | `angular-language-server` (`ngserver`) | Only below `angular.json` or `node_modules/@angular/core`. | -| All of the above | `oxlint` | Only below an `.oxlintrc.json`, `.oxlintrc.jsonc`, `oxlint.config.ts` or `oxlint.config.mts`. | -| All of the above | `vscode-eslint-language-server` (ESLint) | Only below an ESLint configuration (`eslint.config.*`, `.eslintrc*` or `eslintConfig` in `package.json`); runs the project's own `eslint`. | +| Files | Server | Notes | +| ------------------------------- | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | +| JS, JSX, TS, TSX | `vtsls` | Default TypeScript server. | +| JS, JSX, TS, TSX | `typescript-language-server` | Fallback: used only while `vtsls` is not installed. | +| `.vue` | `vue-language-server` + `vtsls` | Vue's hybrid mode: TypeScript inside `.vue` files comes from `vtsls` with `@vue/typescript-plugin`. | +| `.svelte` | `svelte-language-server` | | +| `.astro` | `astro-ls` | Needs Node.js and a TypeScript library. | +| TS and HTML in Angular projects | `angular-language-server` (`ngserver`) | Only below `angular.json` or `node_modules/@angular/core`. | +| All of the above | `oxlint` | Only below an `.oxlintrc.json`, `.oxlintrc.jsonc`, `oxlint.config.ts` or `oxlint.config.mts`. | +| All of the above | `vscode-eslint-language-server` (ESLint) | Only below an ESLint configuration (`eslint.config.*`, `.eslintrc*` or `eslintConfig` in `package.json`); runs the project's own `eslint`. | +| JS, JSX, TS, TSX, JSON, CSS | `biome lsp-proxy` (Biome) | Only below a `biome.json` / `biome.jsonc` or an installed `@biomejs/biome`; runs the project's own `biome`. | +| All of the above, HTML and CSS | `tailwindcss-language-server` (Tailwind CSS) | Only below a `tailwind.config.*` or a `package.json` that depends on `tailwindcss`: class completion, hover with the generated CSS, and class diagnostics. | The TypeScript servers start for a workspace marked by `tsconfig.json`, `jsconfig.json` or `package.json`. Files outside any `tsconfig.json` / `jsconfig.json` are still registered with tsserver, so loose scripts get code insight too. @@ -47,7 +49,8 @@ All servers, debuggers and formatters are listed in **Settings › Languages & F | `vtsls`, `typescript-language-server` | npm (`@vtsls/language-server`; `typescript-language-server` + `typescript@6`) | | `vue-language-server`, `svelte-language-server`, `astro-ls`, `angular-language-server` | npm | | `oxlint` | npm | -| Prettier, oxfmt | npm | +| `tailwindcss-language-server` | npm (`@tailwindcss/language-server`) | +| Prettier, oxfmt, Biome | npm | | JavaScript Debugger (vscode-js-debug) | GitHub release (`microsoft/vscode-js-debug`) | The Astro and Angular servers also run from the project's own `node_modules/.bin` when it has them. @@ -67,14 +70,20 @@ The Astro and Angular servers also run from the project's own `node_modules/.bin - **Prettier** (**Settings › Languages & Frameworks › Prettier**) formats JavaScript, JSX, TypeScript, TSX, JSON, Vue, HTML, CSS, SCSS, Less, GraphQL, YAML and Markdown by default. The executable is found in the project's `node_modules`, then the managed installation, then `PATH`, unless you set **Prettier path**. - **oxfmt** (**Settings › Languages & Frameworks › oxfmt**) replaces Prettier for an enabled language in files below an oxfmt configuration (`.oxfmtrc.json`, `oxfmt.config.ts`), or when it is the selected provider. +- **Biome** (**Settings › Languages & Frameworks › Biome**) replaces Prettier and oxfmt for JavaScript, JSX, TypeScript, TSX, JSON, CSS and GraphQL in files below a `biome.json` / `biome.jsonc` or an installed `@biomejs/biome` (unless the configuration sets `formatter.enabled` to `false`), or when it is the selected provider. It formats whole files and reads its own configuration. -On both pages, **Formatting provider** chooses between **Automatic (language server first)** and the tool itself, **Run on save** formats on save, and **Enabled languages** limits which languages the tool handles. +On these pages, **Formatting provider** chooses between **Automatic (language server first)** and the tool itself, **Run on save** formats on save, and **Enabled languages** limits which languages the tool handles. + +### Biome lint + +In a Biome project, Biome's diagnostics show in the editor and the Problems tool window, and `⌥⏎` / `Alt+Enter` offers its quick fixes and suppressions. Biome's safe fixes (`source.fixAll.biome`) run with **Code › Code Cleanup** and, when **Settings › Tools › Actions on Save › Run code cleanup** is on, on save. When Biome's formatter is enabled, its fix-all formats the file too. ## Run and test OpenIDEA detects run configurations when the project opens: -- One configuration per `package.json` script (`npm run build`, `pnpm run dev`, …), for the root package, nested packages and workspace members. Scripts named `test`, `jest`, `vitest` or `test:*` are test configurations. +- One configuration per `package.json` script (`npm run build`, `pnpm run dev`, …), for the root package, nested packages and workspace members. Scripts named `test`, `jest`, `vitest` or `test:*`, and scripts that run `playwright test`, `node --test` or `mocha`, are test configurations. +- `playwright test` (through `npx`) for a package with a `playwright.config.*` that no script runs. - One per task in `deno.json` / `deno.jsonc` (`deno task `). In `package.json`, the gutter shows run icons on each `scripts` entry to run or debug it. @@ -85,7 +94,7 @@ In `package.json`, the gutter shows run icons on each `scripts` entry to run or - Any other `.js` file runs with `node` (with `deno run` or `bun run` in a project with `deno.json` or `bun.lock`). - A `.ts` file runs with Node.js directly on 22.18+ / 23.6+, with `--experimental-strip-types` on 22.6–22.17 and 23.0–23.5, else through `tsx` or `ts-node`. -Jest and Vitest output is turned into the test tree, with **Rerun Failed Tests**. **Run with Coverage** works for scripts that run `vitest` or `jest` (Vitest needs a coverage provider such as `@vitest/coverage-v8`; the IDE offers to add it) and for `node` / `tsx` / `ts-node` runs through `c8`. See [Testing](/en/guide/testing) and [Coverage](/en/guide/coverage). +Jest, Vitest, Playwright Test, `node --test` and Mocha output is turned into the test tree, with **Rerun Failed Tests**. Playwright runs report through its `list` reporter unless the configuration names another; a test in the gutter runs by its line (`file:line`), and runs with several projects show each project under its file. `node --test` runs report through the IDE's reporter next to `spec`, added to `NODE_OPTIONS` (a script that chooses its own `--test-reporter` runs without the tree); single tests and reruns are selected by full name (`--test-name-pattern`). Mocha runs keep their reporter and load an IDE hook through `NODE_OPTIONS` that reports each test with its line; single tests and reruns use `--grep`, and in projects that test with Mocha or `node --test`, tests in `test/` get gutter icons whatever their file name. **Run with Coverage** works for scripts that run `vitest` or `jest` (Vitest needs a coverage provider such as `@vitest/coverage-v8`; the IDE offers to add it) and for `node` / `tsx` / `ts-node` runs through `c8`. See [Testing](/en/guide/testing) and [Coverage](/en/guide/coverage). ## Debugging diff --git a/docs/en/plugins/guides/run-targets.mdx b/docs/en/plugins/guides/run-targets.mdx index 8a07b6c9fe..15ef996904 100644 --- a/docs/en/plugins/guides/run-targets.mdx +++ b/docs/en/plugins/guides/run-targets.mdx @@ -297,14 +297,14 @@ launching as before. ## Running programs -| Function | What it does | -| ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | -| `Project::run_process(program, &args, stdin)` | Runs the pinned program in the project root and waits: `{ status, stdout, stderr }`, 4 MiB each. | -| `host::run_command(&Command, Some(&project), stdin)` | API 1.3: the same, with environment variables added by `Command::env`. | -| `host::run_captured(&Command, Some(&project), stdin, options)` | API 1.15: configurable output limit (up to 128 MiB per stream); errors explicitly if either stdout or stderr overflows. | -| `host::start(&Command, Some(&project))` | API 1.3: a `Child` left running: `poll`, `write`, `close_stdin`, `wait`, `kill`. At most 8. | -| `host::start_stream(&Command, Some(&project), options)` | API 1.15: lossless streaming with backpressure and bounded buffer, terminating with an explicit error on total overflow.| -| `host::open_terminal(title, program, &args)` | A Terminal tab running the program (see [Views](/en/plugins/guides/views)). | +| Function | What it does | +| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | +| `Project::run_process(program, &args, stdin)` | Runs the pinned program in the project root and waits: `{ status, stdout, stderr }`, 4 MiB each. | +| `host::run_command(&Command, Some(&project), stdin)` | API 1.3: the same, with environment variables added by `Command::env`. | +| `host::run_captured(&Command, Some(&project), stdin, options)` | API 1.15: configurable output limit (up to 128 MiB per stream); errors explicitly if either stdout or stderr overflows. | +| `host::start(&Command, Some(&project))` | API 1.3: a `Child` left running: `poll`, `write`, `close_stdin`, `wait`, `kill`. At most 8. | +| `host::start_stream(&Command, Some(&project), options)` | API 1.15: lossless streaming with backpressure and bounded buffer, terminating with an explicit error on total overflow. | +| `host::open_terminal(title, program, &args)` | A Terminal tab running the program (see [Views](/en/plugins/guides/views)). | ```rust use openidea_plugin::host::{self, Command}; diff --git a/docs/en/plugins/manifest.mdx b/docs/en/plugins/manifest.mdx index a9800e0c96..35529408df 100644 --- a/docs/en/plugins/manifest.mdx +++ b/docs/en/plugins/manifest.mdx @@ -124,6 +124,7 @@ Each contribution point is a table (`[contributes.settings]`) or an array of tab | `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?` | no | [Run targets](/en/plugins/guides/run-targets) | | `runConfigurations` | `files` (API 1.4) | yes | [Run targets](/en/plugins/guides/run-targets) | | `javaAgents` | `path`, `args?` (API 1.10); `vmOptions?`, `jdk?` (API 1.14) | no | [README: Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) | +| `skills` | `path` (`skills//SKILL.md`, API 1.15) | no | [README: API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) | | `mcpTools` | `name`, `description`, `inputSchema`, `readOnly`, `destructive` (API 1.4) | yes | [MCP tools](/en/plugins/guides/mcp) | | `themes` | `path`, `editor-scheme?` | no | [Themes](/en/plugins/guides/themes) | | `iconThemes` | `id`, `label`, `path` | no | [Icon themes](/en/plugins/guides/icon-themes) | diff --git a/docs/en/plugins/versioning.mdx b/docs/en/plugins/versioning.mdx index cf2ac247f2..e1c102fd8f 100644 --- a/docs/en/plugins/versioning.mdx +++ b/docs/en/plugins/versioning.mdx @@ -29,6 +29,7 @@ The plugin API has one version number: the version of the WIT package in [`wit/` | 1.12.0 | In development on `main` | `ui.set-console-rules`: highlight rules (regex, palette colours, styles) for Run and Debug console output | | 1.13.0 | OpenIDEA 0.1.49 | Optional `search-provider` export and `searchCategories`: custom Search Everywhere tabs with cancellable queries | | 1.14.0 | In development on `main` | Optional `hover-actions` export: left-edge line actions revealed by line-edge hover, with an anchor line and inclusive trigger range; `[[contributes.javaAgents]]` `vmOptions` / `jdk`: JVM flags (optionally JetBrains Runtime–only) before `-javaagent:`; `ui.set-status-item-menu` / `set-window-status-item-menu`: a menu on a status bar item | +| 1.15.0 | In development on `main` | `caret-moved` event; declarative `[[contributes.skills]]` (`path = "skills//SKILL.md"`) for bundling agent skills in plugins | The full list of what each version added is in [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md). diff --git a/docs/en/reference/settings.mdx b/docs/en/reference/settings.mdx index 0bdee582e2..2b78d2f6d8 100644 --- a/docs/en/reference/settings.mdx +++ b/docs/en/reference/settings.mdx @@ -55,7 +55,7 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"] | Plugins | Plugins | | Version Control | Commit; Confirmation; Directory Mappings; Issue Navigation; Log; Shelf; Git; GitHub | | Build, Execution, Deployment | CMake; Gradle; Maven; Console; Debugger (Data Views, Stepping); Python Debugger; Run/Debug; Run Targets; Deployment (Options) | -| Languages & Frameworks | Language Servers; Go (Build Tags, Go Modules); Java; Markdown; Node.js; PHP; Python Interpreter; Prettier; oxfmt; Ruff; Ruby; Rust; TypeScript | +| Languages & Frameworks | Language Servers; Go (Build Tags, Go Modules); Java; Markdown; Node.js; PHP; Python Interpreter; Prettier; oxfmt; Biome; Ruff; Ruby; Rust; TypeScript | | Tools | Agents (Chat); Terminal; Actions on Save; External Tools; SSH Configurations; MCP Server | | Security | Project Trust | diff --git a/docs/zh/contribute/setup.mdx b/docs/zh/contribute/setup.mdx index 87950897db..2cc1acb0fd 100644 --- a/docs/zh/contribute/setup.mdx +++ b/docs/zh/contribute/setup.mdx @@ -67,7 +67,7 @@ mise run dev `setup` 在当前 worktree 中执行 `pnpm install`。`dev` 和 `dev:app` 都沿用原来的启动脚本,保留 worktree 隔离。使用 `mise run` 不需要在 shell 中激活 mise。 -运行 `mise tasks` 可以查看全部任务。`mise run build` 构建前端,不生成桌面安装包;`mise run dogfood:build` 和 `mise run dogfood:install` 用于构建并在本地安装灰色图标的 dogfood 桌面版(与正式版共享设置和数据)。两者共用同一个实例,同一时间只能运行一个;较新的 dogfood 版写入的设置可能让较旧的正式版忽略整个设置文件。dogfood 版不会自动更新,需要更新时重新运行 `dogfood:install`。`mise run test` 运行 Vitest 和 `cargo test --workspace`;`mise run check` 先检查格式、代码规范、类型和未使用的代码,再运行这两套测试。两者都不需要 nextest 或插件的 WASM 目标。 +运行 `mise tasks` 可以查看全部任务。`mise run build` 构建前端,不生成桌面安装包;`mise run dogfood:build` 和 `mise run dogfood:install` 用于构建并在本地安装灰色图标的 dogfood 桌面版(与正式版共享设置和数据)。两者共用同一个实例,同一时间只能运行一个;较新的 dogfood 版写入的设置可能让较旧的正式版忽略整个设置文件。dogfood 版不会自动更新,需要更新时重新运行 `dogfood:install`。`mise run dogfood:remote ` 在 **工具 › SSH 配置** 中指定的远程主机上构建并部署 `openidea-server`(`--clean` 可移除覆盖)。`mise run test` 运行 Vitest 和 `cargo test --workspace`;`mise run check` 先检查格式、代码规范、类型和未使用的代码,再运行这两套测试。两者都不需要 nextest 或插件的 WASM 目标。 ## Worktree diff --git a/docs/zh/guide/editor.mdx b/docs/zh/guide/editor.mdx index 4dbdd3c281..12e5e0466f 100644 --- a/docs/zh/guide/editor.mdx +++ b/docs/zh/guide/editor.mdx @@ -88,7 +88,7 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、 | **自动缩进行** | `⌃⌥I` | `Ctrl+Alt+I` | | **优化导入** | `⌃⌥O` | `Ctrl+Alt+O` | -**重新格式化代码** 格式化选区,没有选区时格式化整个文件,整体算一步撤销。格式化由文件的语言服务器或该语言配置的格式化工具完成(例如 Python 用 Ruff,Web 语言用 Prettier 或 oxfmt;在查找操作里搜 **使用 … 重新格式化** 可以指定工具)。**重新格式化文件…** 还能选择范围并顺便优化导入。 +**重新格式化代码** 格式化选区,没有选区时格式化整个文件,整体算一步撤销。格式化由文件的语言服务器或该语言配置的格式化工具完成(例如 Python 用 Ruff,Web 语言用 Prettier、oxfmt 或 Biome;在查找操作里搜 **使用 … 重新格式化** 可以指定工具)。**重新格式化文件…** 还能选择范围并顺便优化导入。 缩进等代码风格选项在 **设置 › 编辑器 › 代码样式** 中,每种语言一个页面。项目里的 `.editorconfig` 也会生效。 diff --git a/docs/zh/guide/run.mdx b/docs/zh/guide/run.mdx index 08673a5118..38b36fa52a 100644 --- a/docs/zh/guide/run.mdx +++ b/docs/zh/guide/run.mdx @@ -19,6 +19,7 @@ description: "创建、编辑和启动运行配置,从装订区运行代码, | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `package.json` | 每个 `scripts` 条目一个,使用锁文件对应的包管理器(npm、pnpm、yarn 或 bun)。`test`、`test:*`、`jest`、`vitest` 脚本会标记为测试。 | | `deno.json` / `deno.jsonc` | Deno task | +| `playwright.config.*` | 运行 `playwright test` 的脚本是测试配置;没有这样的脚本时为 `npx playwright test` | | `Cargo.toml` | 每个二进制一个 `cargo run`,以及 `cargo test`、`cargo build`;包含 workspace 成员 | | `build.gradle(.kts)` / `pom.xml` | Gradle、Maven 运行配置 | | `go.mod` / `go.work` | Go 程序和测试 | diff --git a/docs/zh/guide/testing.mdx b/docs/zh/guide/testing.mdx index 200a7af954..5fec744ff5 100644 --- a/docs/zh/guide/testing.mdx +++ b/docs/zh/guide/testing.mdx @@ -28,7 +28,7 @@ OpenIDEA 直接使用项目自己的测试工具(Cargo、Jest、pytest、Maven | 语言 | 装订区图标位置 | 运行方式 | | --------------------------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | Rust | `#[test]` 函数、`mod tests` | `cargo test`、`cargo nextest` | -| JavaScript / TypeScript | `test`、`it`、`describe`、`suite`、`context`(含 `.each`、`.only`、`.skip`) | 通过项目的测试脚本运行 Jest 或 Vitest;Deno、Bun | +| JavaScript / TypeScript | `test`、`it`、`describe`、`suite`、`context`(含 `.each`、`.only`、`.skip`) | 用测试脚本运行 Jest 或 Vitest;Playwright;Deno、Bun | | Python | pytest 的 `def test_*`、`class Test*`,unittest 的 `TestCase` 子类 | pytest、Django `manage.py test` | | Go | `func TestX(t *testing.T)`、基准测试 | `go test` | | Java、Kotlin、Scala、Groovy | JUnit `@Test`、`@ParameterizedTest`、`@RepeatedTest`、`@TestFactory`、`@TestTemplate`;TestNG | Maven Surefire(`-Dtest=`)或 Gradle(`--tests`) | @@ -62,7 +62,7 @@ RSpec 有自己的配置类型(**RSpec 测试**)和检测到的 `rspec` 配 | **重新运行**(在“运行”工具窗口中) | `⌘R` | `Ctrl+F5` | | **重新运行失败的测试** | — | — | -**重新运行失败的测试**(在“运行”工具窗口工具栏和“查找操作”中)只运行上一次失败的测试,会按各个工具自己的过滤语法生成命令。支持 Cargo、Jest / Vitest、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。 +**重新运行失败的测试**(在“运行”工具窗口工具栏和“查找操作”中)只运行上一次失败的测试,会按各个工具自己的过滤语法生成命令。支持 Cargo、Jest / Vitest、Playwright、`node --test`、Mocha、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。 ## 在代码和测试之间跳转 diff --git a/docs/zh/languages/index.mdx b/docs/zh/languages/index.mdx index 5aff7d56c5..2574424436 100644 --- a/docs/zh/languages/index.mdx +++ b/docs/zh/languages/index.mdx @@ -32,7 +32,7 @@ OpenIDEA 用一个小的定义文件 `languages/.toml` 描述每种语言: 一种语言可以配置多个服务器: - **备选**(下表中写作 `a → b`):只运行第一个已安装的。例如 Python 默认用 basedpyright,只有它缺失时才退回 pyright、ty 或 pyrefly。在 **设置 › 语言和框架 › 语言服务器** 中可以指定其中一个,或选 **自动**(使用第一个可用的)。 -- **附加**(写作 `+ b`):和主服务器同时运行,通常只在用到它的项目中启用。带 Ruff 配置的项目里 Ruff 与 basedpyright 一起运行;带 oxlint 配置的项目里 oxlint 与 vtsls 一起运行;Angular 和 Laravel 项目里分别加上 Angular 和 Laravel 的服务器。 +- **附加**(写作 `+ b`):和主服务器同时运行,通常只在用到它的项目中启用。带 Ruff 配置的项目里 Ruff 与 basedpyright 一起运行;带 oxlint 配置的项目里 oxlint 与 vtsls 一起运行;带 Stylelint 配置(`.stylelintrc*`、`stylelint.config.*` 或 `package.json` 中的 `stylelint`)的项目里 Stylelint 与 CSS、SCSS、Less 的服务器一起运行,使用项目自己的 `stylelint`(编辑器右键菜单中的 **修复 Stylelint 问题** 应用它的修复);带 Biome 配置或安装了 Biome 的项目里 Biome 与 JavaScript、TypeScript、JSON、CSS 和 GraphQL 的服务器一起运行;Angular、Laravel 和 Tailwind CSS 项目里分别加上 Angular、Laravel 和 Tailwind CSS 的服务器。 ## 安装语言服务器和调试器 @@ -86,92 +86,92 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自 下表列出全部内置语言定义。**加粗** 的服务器和调试器可以在 IDE 中一键安装,其余需要自行安装(IDE 中的安装提示会说明方法)。"高亮"和"Tree-sitter"两列分别表示是否有即时高亮,以及是否有用于大纲和折叠的内置语法。 -| 语言 | ID | 文件 | 高亮 | Tree-sitter | 语言服务器 | 调试器 | -| ------------------- | ------------------ | ----------------------------------------------------------- | ---- | ----------- | ------------------------------------------------------------------------------------- | ------------------------ | -| .env | `dotenv` | `.env` | 是 | — | — | — | -| Arduino | `arduino` | `.ino` | 是 | 是 | arduino-language-server | — | -| AsciiDoc | `asciidoc` | `.adoc`, `.asciidoc` | 是 | — | — | — | -| Astro | `astro` | `.astro` | 是 | — | **astro-ls** + **oxlint** | — | -| Batch | `bat` | `.bat`, `.cmd` | 是 | — | — | — | -| C | `c` | `.c`, `.h` | 是 | 是 | **clangd** | lldb-dap | -| C# | `csharp` | `.cs`, `.csx` | 是 | 是 | **csharp-ls** | **netcoredbg** | -| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | 是 | 是 | **clangd** | lldb-dap | -| Clojure | `clojure` | `.clj`, `.cljs`, `.cljc`, `.cljd`, `.edn`, … | 是 | — | **clojure-lsp** | — | -| CMake | `cmake` | `.cmake` | 是 | 是 | **neocmakelsp** → cmake-language-server | — | -| CSS | `css` | `.css`, `.pcss`, `.postcss` | 是 | 是 | **vscode-css-language-server** | — | -| D | `d` | `.d`, `.di` | 是 | — | serve-d | — | -| Dart | `dart` | `.dart` | 是 | 是 | dart | dart | -| Diff | `diff` | `.diff`, `.patch`, `.rej` | 是 | — | — | — | -| Django Template | `django-html` | `.djhtml`, `templates/*.html`, `*.txt` | 是 | 是 | **vscode-html-language-server**, **djlsp** | — | -| Dockerfile | `dockerfile` | `.dockerfile`, `.containerfile` | 是 | — | **dockerfile-language-server** | — | -| Elixir | `elixir` | `.ex`, `.exs` | 是 | 是 | **elixir-ls** | **elixir-ls-debugger** | -| ERB | `erb` | `.erb`, `.html.erb`, `.rhtml`, `.js.erb`, `.text.erb`, … | 是 | — | — | — | -| Erlang | `erlang` | `.erl`, `.hrl`, `.escript`, `.app.src` | 是 | — | elp | — | -| F# | `fsharp` | `.fs`, `.fsi`, `.fsx` | 是 | — | **fsautocomplete** | **netcoredbg** | -| GDScript | `gdscript` | `.gd` | 是 | 是 | godot | godot | -| Git Attributes | `gitattributes` | `.gitattributes` | — | — | — | — | -| Go | `go` | `.go` | 是 | 是 | **gopls** | **delve** | -| Go Module | `go.mod` | `go.mod` | 是 | — | **gopls** | — | -| Go Workspace | `go.work` | `go.work` | 是 | — | **gopls** | — | -| Godot Resource | `godot-resource` | `.tscn`, `.tres`, `.godot`, `.import` | 是 | — | — | — | -| Godot Shader | `gdshader` | `.gdshader`, `.gdshaderinc` | 是 | — | — | — | -| GraphQL | `graphql` | `.graphql`, `.graphqls`, `.gql` | 是 | 是 | **graphql-lsp** | — | -| Groovy | `groovy` | `.groovy`, `.gradle`, `.gvy`, `.gy`, `.gsh` | 是 | — | groovy-language-server | — | -| Haskell | `haskell` | `.hs`, `.hs-boot`, `.hsig` | 是 | 是 | haskell-language-server | — | -| HCL | `hcl` | `.hcl`, `.nomad`, `.pkr.hcl` | 是 | 是 | — | — | -| HTML | `html` | `.html`, `.htm`, `.xhtml`, `.shtml`, `.html.tmpl` | 是 | 是 | **vscode-html-language-server** + **angular-language-server** | — | -| HTTP Request | `http` | `.http`, `.rest` | 是 | — | — | — | -| Ignore File | `ignore` | `.gitignore`, `.dockerignore` | — | — | — | — | -| INI | `ini` | `.ini`, `.cfg`, `.conf`, `.cnf`, `.inf`, … | 是 | — | — | — | -| Java | `java` | `.java` | 是 | 是 | **jdtls** → **java-analyzer** → **kmp-lsp** | **java-debug** | -| JavaScript | `javascript` | `.js`, `.mjs`, `.cjs` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** | -| JavaScript JSX | `javascriptreact` | `.jsx` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** | -| JSON | `json` | `.json`, `.geojson`, `.topojson`, `.webmanifest`, `.har`, … | 是 | 是 | **vscode-json-language-server** | — | -| JSON with Comments | `jsonc` | `.jsonc`, `.code-workspace`, `.code-snippets` | 是 | 是 | **vscode-json-language-server** | — | -| JSP | `jsp` | `.jsp`, `.jspx`, `.jspf`, `.jsph`, `.tag`, … | 是 | — | — | — | -| Julia | `julia` | `.jl` | 是 | — | julia-languageserver | — | -| Kotlin | `kotlin` | `.kt`, `.kts` | 是 | 是 | **kotlin-lsp** → **kotlin-language-server** → **kmp-lsp** | **kotlin-debug-adapter** | -| LaTeX | `latex` | `.tex`, `.ltx`, `.sty`, `.cls`, `.dtx`, … | 是 | — | **texlab** | — | -| Less | `less` | `.less` | 是 | — | **vscode-css-language-server** | — | -| Log | `log` | `.log` | 是 | — | — | — | -| Lua | `lua` | `.lua`, `.luau`, `.rockspec` | 是 | 是 | **lua-language-server** | — | -| Makefile | `makefile` | `.mk`, `.mak`, `.make` | 是 | 是 | — | — | -| Markdown | `markdown` | `.md`, `.markdown`, `.mdown`, `.mkd`, `.mkdn`, … | 是 | 是 | **marksman** | — | -| Nix | `nix` | `.nix` | 是 | 是 | nil → nixd | — | -| Objective-C | `objective-c` | `.m` | 是 | — | **clangd** | lldb-dap | -| Objective-C++ | `objective-cpp` | `.mm` | 是 | — | **clangd** | lldb-dap | -| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | 是 | 是 | ocamllsp | ocamlearlybird | -| OCaml Interface | `ocaml.interface` | `.mli` | 是 | 是 | ocamllsp | — | -| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | 是 | — | **perlnavigator** | — | -| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | 是 | 是 | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** | -| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — | -| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | 是 | — | powershell-editor-services | — | -| Prisma | `prisma` | `.prisma` | 是 | 是 | **prisma-language-server** | — | -| Properties | `properties` | `.properties`, `.prefs` | 是 | — | — | — | -| Protocol Buffers | `proto` | `.proto` | 是 | 是 | **buf** | — | -| Python | `python` | `.py`, `.pyi`, `.pyw` | 是 | 是 | **basedpyright** → **pyright** → **ty** → **pyrefly** + **ruff** | **debugpy** | -| R | `r` | `.r`, `.rprofile` | 是 | — | r-languageserver | — | -| reStructuredText | `restructuredtext` | `.rst` | 是 | — | — | — | -| Ruby | `ruby` | `.rb`, `.rake`, `.gemspec`, `.ru`, `.rbi`, … | 是 | 是 | **ruby-lsp** → **solargraph** | rdbg | -| Rust | `rust` | `.rs` | 是 | 是 | **rust-analyzer** | **codelldb** | -| Sass | `sass` | `.sass` | 是 | — | — | — | -| Scala | `scala` | `.scala`, `.sc`, `.sbt`, `.mill` | 是 | 是 | metals | — | -| SCSS | `scss` | `.scss` | 是 | — | **vscode-css-language-server** | — | -| Shell Script | `shellscript` | `.sh`, `.bash`, `.zsh`, `.ksh`, `.ash`, … | 是 | 是 | **bash-language-server** | **bash-debug** | -| Slint | `slint` | `.slint` | 是 | — | **slint-lsp** | — | -| SQL | `sql` | `.sql`, `.ddl`, `.dml`, `.psql`, `.pgsql`, … | 是 | — | **sqls** | — | -| Svelte | `svelte` | `.svelte` | 是 | — | **svelte-language-server** + **oxlint** | — | -| Swift | `swift` | `.swift`, `.swiftinterface` | 是 | 是 | sourcekit-lsp | lldb-dap | -| Terraform | `terraform` | `.tf`, `.tofu`, `.tftest.hcl` | 是 | 是 | **terraform-ls** | — | -| Terraform Variables | `terraform-vars` | `.tfvars` | 是 | 是 | **terraform-ls** | — | -| TOML | `toml` | `.toml` | 是 | 是 | **taplo** | — | -| TypeScript | `typescript` | `.ts`, `.mts`, `.cts` | 是 | 是 | **vtsls** → **typescript-language-server** + **angular-language-server** + **oxlint** | **js-debug** | -| TypeScript JSX | `typescriptreact` | `.tsx` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** | -| Typst | `typst` | `.typ` | — | — | **tinymist** | — | -| Vue | `vue` | `.vue` | 是 | — | **vue-language-server**, **vtsls** + **oxlint** | — | -| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | 是 | 是 | **lemminx** | — | -| YAML | `yaml` | `.yaml`, `.yml` | 是 | 是 | **yaml-language-server** | — | -| Zig | `zig` | `.zig`, `.zon` | 是 | 是 | **zls** | **codelldb** | +| 语言 | ID | 文件 | 高亮 | Tree-sitter | 语言服务器 | 调试器 | +| ------------------- | ------------------ | ----------------------------------------------------------- | ---- | ----------- | ------------------------------------------------------------------------------------------------- | ------------------------ | +| .env | `dotenv` | `.env` | 是 | — | — | — | +| Arduino | `arduino` | `.ino` | 是 | 是 | arduino-language-server | — | +| AsciiDoc | `asciidoc` | `.adoc`, `.asciidoc` | 是 | — | — | — | +| Astro | `astro` | `.astro` | 是 | — | **astro-ls** + **oxlint** | — | +| Batch | `bat` | `.bat`, `.cmd` | 是 | — | — | — | +| C | `c` | `.c`, `.h` | 是 | 是 | **clangd** | lldb-dap | +| C# | `csharp` | `.cs`, `.csx` | 是 | 是 | **csharp-ls** | **netcoredbg** | +| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | 是 | 是 | **clangd** | lldb-dap | +| Clojure | `clojure` | `.clj`, `.cljs`, `.cljc`, `.cljd`, `.edn`, … | 是 | — | **clojure-lsp** | — | +| CMake | `cmake` | `.cmake` | 是 | 是 | **neocmakelsp** → cmake-language-server | — | +| CSS | `css` | `.css`, `.pcss`, `.postcss` | 是 | 是 | **vscode-css-language-server** + **biome** + **stylelint** | — | +| D | `d` | `.d`, `.di` | 是 | — | serve-d | — | +| Dart | `dart` | `.dart` | 是 | 是 | dart | dart | +| Diff | `diff` | `.diff`, `.patch`, `.rej` | 是 | — | — | — | +| Django Template | `django-html` | `.djhtml`, `templates/*.html`, `*.txt` | 是 | 是 | **vscode-html-language-server**, **djlsp** | — | +| Dockerfile | `dockerfile` | `.dockerfile`, `.containerfile` | 是 | — | **dockerfile-language-server** | — | +| Elixir | `elixir` | `.ex`, `.exs` | 是 | 是 | **elixir-ls** | **elixir-ls-debugger** | +| ERB | `erb` | `.erb`, `.html.erb`, `.rhtml`, `.js.erb`, `.text.erb`, … | 是 | — | — | — | +| Erlang | `erlang` | `.erl`, `.hrl`, `.escript`, `.app.src` | 是 | — | elp | — | +| F# | `fsharp` | `.fs`, `.fsi`, `.fsx` | 是 | — | **fsautocomplete** | **netcoredbg** | +| GDScript | `gdscript` | `.gd` | 是 | 是 | godot | godot | +| Git Attributes | `gitattributes` | `.gitattributes` | — | — | — | — | +| Go | `go` | `.go` | 是 | 是 | **gopls** | **delve** | +| Go Module | `go.mod` | `go.mod` | 是 | — | **gopls** | — | +| Go Workspace | `go.work` | `go.work` | 是 | — | **gopls** | — | +| Godot Resource | `godot-resource` | `.tscn`, `.tres`, `.godot`, `.import` | 是 | — | — | — | +| Godot Shader | `gdshader` | `.gdshader`, `.gdshaderinc` | 是 | — | — | — | +| GraphQL | `graphql` | `.graphql`, `.graphqls`, `.gql` | 是 | 是 | **graphql-lsp** + **biome** | — | +| Groovy | `groovy` | `.groovy`, `.gradle`, `.gvy`, `.gy`, `.gsh` | 是 | — | groovy-language-server | — | +| Haskell | `haskell` | `.hs`, `.hs-boot`, `.hsig` | 是 | 是 | haskell-language-server | — | +| HCL | `hcl` | `.hcl`, `.nomad`, `.pkr.hcl` | 是 | 是 | — | — | +| HTML | `html` | `.html`, `.htm`, `.xhtml`, `.shtml`, `.html.tmpl` | 是 | 是 | **vscode-html-language-server** + **angular-language-server** | — | +| HTTP Request | `http` | `.http`, `.rest` | 是 | — | — | — | +| Ignore File | `ignore` | `.gitignore`, `.dockerignore` | — | — | — | — | +| INI | `ini` | `.ini`, `.cfg`, `.conf`, `.cnf`, `.inf`, … | 是 | — | — | — | +| Java | `java` | `.java` | 是 | 是 | **jdtls** → **java-analyzer** → **kmp-lsp** | **java-debug** | +| JavaScript | `javascript` | `.js`, `.mjs`, `.cjs` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** | +| JavaScript JSX | `javascriptreact` | `.jsx` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** | +| JSON | `json` | `.json`, `.geojson`, `.topojson`, `.webmanifest`, `.har`, … | 是 | 是 | **vscode-json-language-server** + **biome** | — | +| JSON with Comments | `jsonc` | `.jsonc`, `.code-workspace`, `.code-snippets` | 是 | 是 | **vscode-json-language-server** + **biome** | — | +| JSP | `jsp` | `.jsp`, `.jspx`, `.jspf`, `.jsph`, `.tag`, … | 是 | — | — | — | +| Julia | `julia` | `.jl` | 是 | — | julia-languageserver | — | +| Kotlin | `kotlin` | `.kt`, `.kts` | 是 | 是 | **kotlin-lsp** → **kotlin-language-server** → **kmp-lsp** | **kotlin-debug-adapter** | +| LaTeX | `latex` | `.tex`, `.ltx`, `.sty`, `.cls`, `.dtx`, … | 是 | — | **texlab** | — | +| Less | `less` | `.less` | 是 | — | **vscode-css-language-server** + **stylelint** | — | +| Log | `log` | `.log` | 是 | — | — | — | +| Lua | `lua` | `.lua`, `.luau`, `.rockspec` | 是 | 是 | **lua-language-server** | — | +| Makefile | `makefile` | `.mk`, `.mak`, `.make` | 是 | 是 | — | — | +| Markdown | `markdown` | `.md`, `.markdown`, `.mdown`, `.mkd`, `.mkdn`, … | 是 | 是 | **marksman** | — | +| Nix | `nix` | `.nix` | 是 | 是 | nil → nixd | — | +| Objective-C | `objective-c` | `.m` | 是 | — | **clangd** | lldb-dap | +| Objective-C++ | `objective-cpp` | `.mm` | 是 | — | **clangd** | lldb-dap | +| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | 是 | 是 | ocamllsp | ocamlearlybird | +| OCaml Interface | `ocaml.interface` | `.mli` | 是 | 是 | ocamllsp | — | +| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | 是 | — | **perlnavigator** | — | +| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | 是 | 是 | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** | +| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — | +| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | 是 | — | powershell-editor-services | — | +| Prisma | `prisma` | `.prisma` | 是 | 是 | **prisma-language-server** | — | +| Properties | `properties` | `.properties`, `.prefs` | 是 | — | — | — | +| Protocol Buffers | `proto` | `.proto` | 是 | 是 | **buf** | — | +| Python | `python` | `.py`, `.pyi`, `.pyw` | 是 | 是 | **basedpyright** → **pyright** → **ty** → **pyrefly** + **ruff** | **debugpy** | +| R | `r` | `.r`, `.rprofile` | 是 | — | r-languageserver | — | +| reStructuredText | `restructuredtext` | `.rst` | 是 | — | — | — | +| Ruby | `ruby` | `.rb`, `.rake`, `.gemspec`, `.ru`, `.rbi`, … | 是 | 是 | **ruby-lsp** → **solargraph** | rdbg | +| Rust | `rust` | `.rs` | 是 | 是 | **rust-analyzer** | **codelldb** | +| Sass | `sass` | `.sass` | 是 | — | — | — | +| Scala | `scala` | `.scala`, `.sc`, `.sbt`, `.mill` | 是 | 是 | metals | — | +| SCSS | `scss` | `.scss` | 是 | — | **vscode-css-language-server** + **stylelint** | — | +| Shell Script | `shellscript` | `.sh`, `.bash`, `.zsh`, `.ksh`, `.ash`, … | 是 | 是 | **bash-language-server** | **bash-debug** | +| Slint | `slint` | `.slint` | 是 | — | **slint-lsp** | — | +| SQL | `sql` | `.sql`, `.ddl`, `.dml`, `.psql`, `.pgsql`, … | 是 | — | **sqls** | — | +| Svelte | `svelte` | `.svelte` | 是 | — | **svelte-language-server** + **oxlint** | — | +| Swift | `swift` | `.swift`, `.swiftinterface` | 是 | 是 | sourcekit-lsp | lldb-dap | +| Terraform | `terraform` | `.tf`, `.tofu`, `.tftest.hcl` | 是 | 是 | **terraform-ls** | — | +| Terraform Variables | `terraform-vars` | `.tfvars` | 是 | 是 | **terraform-ls** | — | +| TOML | `toml` | `.toml` | 是 | 是 | **taplo** | — | +| TypeScript | `typescript` | `.ts`, `.mts`, `.cts` | 是 | 是 | **vtsls** → **typescript-language-server** + **angular-language-server** + **oxlint** + **biome** | **js-debug** | +| TypeScript JSX | `typescriptreact` | `.tsx` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** | +| Typst | `typst` | `.typ` | — | — | **tinymist** | — | +| Vue | `vue` | `.vue` | 是 | — | **vue-language-server**, **vtsls** + **oxlint** | — | +| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | 是 | 是 | **lemminx** | — | +| YAML | `yaml` | `.yaml`, `.yml` | 是 | 是 | **yaml-language-server** | — | +| Zig | `zig` | `.zig`, `.zon` | 是 | 是 | **zls** | **codelldb** | 说明: diff --git a/docs/zh/languages/javascript.mdx b/docs/zh/languages/javascript.mdx index 912cbaa6fb..c99b3f53c1 100644 --- a/docs/zh/languages/javascript.mdx +++ b/docs/zh/languages/javascript.mdx @@ -7,16 +7,18 @@ OpenIDEA 打开 JavaScript(`.js`、`.mjs`、`.cjs`、`.jsx`)和 TypeScript ## 语言服务器 -| 文件 | 服务器 | 说明 | -| --------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | -| JS、JSX、TS、TSX | `vtsls` | 默认的 TypeScript 服务器。 | -| JS、JSX、TS、TSX | `typescript-language-server` | 备选:仅在未安装 `vtsls` 时使用。 | -| `.vue` | `vue-language-server` + `vtsls` | Vue 的 hybrid 模式:`.vue` 中的 TypeScript 由加载了 `@vue/typescript-plugin` 的 `vtsls` 处理。 | -| `.svelte` | `svelte-language-server` | | -| `.astro` | `astro-ls` | 需要 Node.js 和 TypeScript 库。 | -| Angular 项目中的 TS 和 HTML | `angular-language-server`(`ngserver`) | 只在 `angular.json` 或 `node_modules/@angular/core` 所在目录之下启用。 | -| 以上全部 | `oxlint` | 只在存在 `.oxlintrc.json`、`.oxlintrc.jsonc`、`oxlint.config.ts` 或 `oxlint.config.mts` 的目录之下启用。 | -| 以上全部 | `vscode-eslint-language-server`(ESLint) | 只在 ESLint 配置(`eslint.config.*`、`.eslintrc*` 或 `package.json` 中的 `eslintConfig`)所在目录之下启用,运行项目自己的 `eslint`。 | +| 文件 | 服务器 | 说明 | +| --------------------------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| JS、JSX、TS、TSX | `vtsls` | 默认的 TypeScript 服务器。 | +| JS、JSX、TS、TSX | `typescript-language-server` | 备选:仅在未安装 `vtsls` 时使用。 | +| `.vue` | `vue-language-server` + `vtsls` | Vue 的 hybrid 模式:`.vue` 中的 TypeScript 由加载了 `@vue/typescript-plugin` 的 `vtsls` 处理。 | +| `.svelte` | `svelte-language-server` | | +| `.astro` | `astro-ls` | 需要 Node.js 和 TypeScript 库。 | +| Angular 项目中的 TS 和 HTML | `angular-language-server`(`ngserver`) | 只在 `angular.json` 或 `node_modules/@angular/core` 所在目录之下启用。 | +| 以上全部 | `oxlint` | 只在存在 `.oxlintrc.json`、`.oxlintrc.jsonc`、`oxlint.config.ts` 或 `oxlint.config.mts` 的目录之下启用。 | +| 以上全部 | `vscode-eslint-language-server`(ESLint) | 只在 ESLint 配置(`eslint.config.*`、`.eslintrc*` 或 `package.json` 中的 `eslintConfig`)所在目录之下启用,运行项目自己的 `eslint`。 | +| JS、JSX、TS、TSX、JSON、CSS | `biome lsp-proxy`(Biome) | 只在 `biome.json` / `biome.jsonc` 所在目录或安装了 `@biomejs/biome` 的项目之下启用,运行项目自己的 `biome`。 | +| 以上全部及 HTML、CSS | `tailwindcss-language-server`(Tailwind CSS) | 只在 `tailwind.config.*` 或依赖了 `tailwindcss` 的 `package.json` 所在目录之下启用:类名补全、悬停显示生成的 CSS、类名诊断。 | TypeScript 服务器以 `tsconfig.json`、`jsconfig.json` 或 `package.json` 所在目录为工作区根。不属于任何 `tsconfig.json` / `jsconfig.json` 的文件也会注册给 tsserver,零散脚本同样有代码智能。 @@ -47,7 +49,9 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript | `vtsls`、`typescript-language-server` | npm(`@vtsls/language-server`;`typescript-language-server` + `typescript@6`) | | `vue-language-server`、`svelte-language-server`、`astro-ls`、`angular-language-server` | npm | | `oxlint` | npm | +| `tailwindcss-language-server` | npm(`@tailwindcss/language-server`) | | Prettier、oxfmt | npm | +| Prettier、oxfmt、Biome | npm | | JavaScript 调试器(vscode-js-debug) | GitHub release(`microsoft/vscode-js-debug`) | 如果项目自己的 `node_modules/.bin` 里有 Astro 或 Angular 服务器,会优先使用项目里的。 @@ -67,14 +71,20 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript - **Prettier**(**设置 › 语言和框架 › Prettier**)默认处理 JavaScript、JSX、TypeScript、TSX、JSON、Vue、HTML、CSS、SCSS、Less、GraphQL、YAML 和 Markdown。未设置 **Prettier 路径** 时,依次查找项目 `node_modules`、IDE 管理的安装、`PATH`。 - **oxfmt**(**设置 › 语言和框架 › oxfmt**)在 oxfmt 配置文件(`.oxfmtrc.json`、`oxfmt.config.ts`)所在目录之下,或被选为格式化工具时,替代 Prettier 处理已启用的语言。 +- **Biome**(**设置 › 语言和框架 › Biome**)在 `biome.json` / `biome.jsonc` 所在目录或安装了 `@biomejs/biome` 的项目之下(配置里 `formatter.enabled` 为 `false` 时除外),或被选为格式化工具时,替代 Prettier 和 oxfmt 处理 JavaScript、JSX、TypeScript、TSX、JSON、CSS 和 GraphQL。它总是格式化整个文件,并读取自己的配置。 -两个页面上,**格式化工具** 可选 **自动(优先语言服务器)** 或工具本身,**保存时运行** 控制保存时格式化,**启用的语言** 限定工具处理哪些语言。 +这些页面上,**格式化工具** 可选 **自动(优先语言服务器)** 或工具本身,**保存时运行** 控制保存时格式化,**启用的语言** 限定工具处理哪些语言。 + +### Biome 检查 + +在 Biome 项目中,Biome 的诊断显示在编辑器和“问题”工具窗口里,`⌥⏎` / `Alt+Enter` 提供它的快速修复和抑制。Biome 的安全修复(`source.fixAll.biome`)随 **代码 › 代码清理** 运行;开启 **设置 › 工具 › 保存时操作 › 运行代码清理** 后,保存时也会运行。Biome 的格式化器开启时,它的全部修复也会格式化文件。 ## 运行与测试 打开项目时,OpenIDEA 会自动检测运行配置: -- 每个 `package.json` 脚本一个配置(`npm run build`、`pnpm run dev` 等),覆盖根包、嵌套包和 workspace 成员。名为 `test`、`jest`、`vitest` 或 `test:*` 的脚本是测试配置。 +- 每个 `package.json` 脚本一个配置(`npm run build`、`pnpm run dev` 等),覆盖根包、嵌套包和 workspace 成员。名为 `test`、`jest`、`vitest` 或 `test:*` 的脚本,以及运行 `playwright test`、`node --test` 或 `mocha` 的脚本,是测试配置。 +- 有 `playwright.config.*` 但没有脚本运行它的包:通过 `npx` 运行的 `playwright test`。 - `deno.json` / `deno.jsonc` 中每个 task 一个配置(`deno task `)。 在 `package.json` 中,每个 `scripts` 条目旁的边栏图标可以直接运行或调试该脚本。 @@ -85,7 +95,7 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript - 其他 `.js` 文件用 `node` 运行(项目含 `deno.json` 或 `bun.lock` 时改用 `deno run` 或 `bun run`)。 - `.ts` 文件在 Node.js 22.18+ / 23.6+ 上直接运行,在 22.6–22.17 和 23.0–23.5 上加 `--experimental-strip-types`,更早的版本则通过 `tsx` 或 `ts-node` 运行。 -Jest 和 Vitest 的输出会解析成测试树,支持 **重新运行失败的测试**。**使用覆盖率运行** 支持调用 `vitest` 或 `jest` 的脚本(Vitest 需要 `@vitest/coverage-v8` 之类的覆盖率 provider,缺失时 IDE 会提示添加),以及通过 `c8` 运行的 `node` / `tsx` / `ts-node`。详见[测试](/zh/guide/testing)和[覆盖率](/zh/guide/coverage)。 +Jest、Vitest、Playwright Test、`node --test` 和 Mocha 的输出会解析成测试树,支持 **重新运行失败的测试**。Playwright 运行时使用它的 `list` 报告器(配置里指定了其他报告器时除外);从行号栏运行单个测试时按行号选择(`file:line`),有多个 project 的运行会在文件下按 project 分组。`node --test` 运行时,IDE 通过 `NODE_OPTIONS` 在 `spec` 旁加上自己的报告器(脚本自己指定了 `--test-reporter` 时不显示测试树);单个测试和重新运行按完整名称选择(`--test-name-pattern`)。Mocha 运行保留它自己的报告器,并通过 `NODE_OPTIONS` 加载 IDE 的钩子,逐个报告测试及其所在行;单个测试和重新运行使用 `--grep`,在用 Mocha 或 `node --test` 测试的项目里,`test/` 目录下的测试不论文件名都有行号栏图标。**使用覆盖率运行** 支持调用 `vitest` 或 `jest` 的脚本(Vitest 需要 `@vitest/coverage-v8` 之类的覆盖率 provider,缺失时 IDE 会提示添加),以及通过 `c8` 运行的 `node` / `tsx` / `ts-node`。详见[测试](/zh/guide/testing)和[覆盖率](/zh/guide/coverage)。 ## 调试 diff --git a/docs/zh/plugins/guides/run-targets.mdx b/docs/zh/plugins/guides/run-targets.mdx index 0053e53e98..d58f2db9b0 100644 --- a/docs/zh/plugins/guides/run-targets.mdx +++ b/docs/zh/plugins/guides/run-targets.mdx @@ -254,14 +254,14 @@ register_plugin!(MyPlugin, run_target_validation); ## 运行程序 -| 函数 | 作用 | -| ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- | -| `Project::run_process(program, &args, stdin)` | 在项目根目录运行已固定的程序并等待结束:`{ status, stdout, stderr }`,各 4 MiB。 | -| `host::run_command(&Command, Some(&project), stdin)` | API 1.3:同上,可用 `Command::env` 追加环境变量。 | -| `host::run_captured(&Command, Some(&project), stdin, options)` | API 1.15:可配置输出上限(每个流最高 128 MiB),stdout 或 stderr 溢出时明确报错。 | -| `host::start(&Command, Some(&project))` | API 1.3:保持运行的 `Child`:`poll`、`write`、`close_stdin`、`wait`、`kill`。最多 8 个。 | -| `host::start_stream(&Command, Some(&project), options)` | API 1.15:基于管道背压的有界无损流式传输,超出总预算时明确报错并终止进程。 | -| `host::open_terminal(title, program, &args)` | 运行该程序的终端标签页(见 [视图](/zh/plugins/guides/views))。 | +| 函数 | 作用 | +| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `Project::run_process(program, &args, stdin)` | 在项目根目录运行已固定的程序并等待结束:`{ status, stdout, stderr }`,各 4 MiB。 | +| `host::run_command(&Command, Some(&project), stdin)` | API 1.3:同上,可用 `Command::env` 追加环境变量。 | +| `host::run_captured(&Command, Some(&project), stdin, options)` | API 1.15:可配置输出上限(每个流最高 128 MiB),stdout 或 stderr 溢出时明确报错。 | +| `host::start(&Command, Some(&project))` | API 1.3:保持运行的 `Child`:`poll`、`write`、`close_stdin`、`wait`、`kill`。最多 8 个。 | +| `host::start_stream(&Command, Some(&project), options)` | API 1.15:基于管道背压的有界无损流式传输,超出总预算时明确报错并终止进程。 | +| `host::open_terminal(title, program, &args)` | 运行该程序的终端标签页(见 [视图](/zh/plugins/guides/views))。 | ```rust use openidea_plugin::host::{self, Command}; diff --git a/docs/zh/plugins/manifest.mdx b/docs/zh/plugins/manifest.mdx index 503f01c042..4f07100768 100644 --- a/docs/zh/plugins/manifest.mdx +++ b/docs/zh/plugins/manifest.mdx @@ -124,6 +124,7 @@ optional = ["net:api.openai.com", "secrets"] | `runDetectors` | `id`、`name`、`files`、`command`、`args?`、`test?`、`framework?` | 否 | [运行目标](/zh/plugins/guides/run-targets) | | `runConfigurations` | `files`(API 1.4) | 是 | [运行目标](/zh/plugins/guides/run-targets) | | `javaAgents` | `path`、`args?`(API 1.10);`vmOptions?`、`jdk?`(API 1.14) | 否 | [README:Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) | +| `skills` | `path`(`skills//SKILL.md`,API 1.15) | 否 | [README:API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) | | `mcpTools` | `name`、`description`、`inputSchema`、`readOnly`、`destructive`(API 1.4) | 是 | [MCP 工具](/zh/plugins/guides/mcp) | | `themes` | `path`、`editor-scheme?` | 否 | [主题](/zh/plugins/guides/themes) | | `iconThemes` | `id`、`label`、`path` | 否 | [图标主题](/zh/plugins/guides/icon-themes) | diff --git a/docs/zh/plugins/versioning.mdx b/docs/zh/plugins/versioning.mdx index a796316761..2685f0931b 100644 --- a/docs/zh/plugins/versioning.mdx +++ b/docs/zh/plugins/versioning.mdx @@ -26,6 +26,7 @@ description: "engines.openidea、插件 API 从 1.0 到 1.13 的各个版本, | 1.12.0 | `main` 上开发中 | `ui.set-console-rules`:Run/Debug 控制台输出的高亮规则(正则、调色板颜色、文本样式) | | 1.13.0 | OpenIDEA 0.1.49 | 新增 `search-provider` 导出和 `searchCategories` 贡献点:可取消查询的全局搜索自定义分类 | | 1.14.0 | `main` 上开发中 | 可选 `hover-actions` 导出:行内侧 hover 显示的左侧操作,带锚定行和包含式触发行范围; `[[contributes.javaAgents]]` 的 `vmOptions` / `jdk`:在 `-javaagent:` 之前注入 JVM 参数(可选仅 JetBrains Runtime);`ui.set-status-item-menu` / `set-window-status-item-menu`:状态栏项菜单 | +| 1.15.0 | `main` 上开发中 | `caret-moved` 事件;声明式 `[[contributes.skills]]`(`path = "skills//SKILL.md"`),在插件包中打包代理技能 | 每个版本新增内容的完整列表见 [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md)。 diff --git a/docs/zh/reference/settings.mdx b/docs/zh/reference/settings.mdx index 513ae03015..c544cb0b73 100644 --- a/docs/zh/reference/settings.mdx +++ b/docs/zh/reference/settings.mdx @@ -55,7 +55,7 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"] | 插件 | 插件 | | 版本控制 | 提交;确认;目录映射;问题导航;日志;搁置;Git;GitHub | | 构建、执行、部署 | CMake;Gradle;Maven;控制台;调试器(数据视图、单步执行);Python 调试器;运行/调试;运行目标;部署(选项) | -| 语言和框架 | 语言服务器;Go(构建标签、Go 模块);Java;Markdown;Node.js;PHP;Python 解释器;Prettier;oxfmt;Ruff;Ruby;Rust;TypeScript | +| 语言和框架 | 语言服务器;Go(构建标签、Go 模块);Java;Markdown;Node.js;PHP;Python 解释器;Prettier;oxfmt;Biome;Ruff;Ruby;Rust;TypeScript | | 工具 | 智能体(聊天);终端;保存时操作;外部工具;SSH 配置;MCP 服务器 | | 安全 | 项目信任 | diff --git a/e2e/agentSkills.spec.ts b/e2e/agentSkills.spec.ts index ecc450214d..cea1150a31 100644 --- a/e2e/agentSkills.spec.ts +++ b/e2e/agentSkills.spec.ts @@ -73,6 +73,8 @@ const initialSkills: AgentSkillState[] = [ alsoIn: ["claudeWorkspace"], userInvocable: true, disableModelInvocation: false, + contextFork: true, + paths: ["src/**/*.tsx", "e2e/*.spec.ts"], valid: true, warnings: [], }, @@ -111,6 +113,22 @@ const initialSkills: AgentSkillState[] = [ mode: "off", origin: "user", }, + { + skill: { + name: "release-notes", + description: "Draft concise release notes from merged commits and pull requests", + hint: "[tag]", + path: "/Users/dev/Library/Application Support/ai.l0ng.openidea/plugins/acme.release-tools/1.0.0/skills/release-notes", + source: "plugin", + alsoIn: [], + userInvocable: true, + disableModelInvocation: false, + valid: true, + warnings: [], + }, + mode: "auto", + origin: "none", + }, { skill: { name: "pg-tune", @@ -190,6 +208,90 @@ test("manages multi-level skills in Settings and per-session overrides via Compo ); return skills; }; + handlers.agent_skills_browse = () => ({ + owner: "vercel-labs", + repo: "agent-skills", + gitRef: "main", + treeSha: "9f8e7d6c", + truncated: false, + skills: [ + { folderName: "find-skills", subpath: "skills/find-skills", fileCount: 2, totalBytes: 1420 }, + { folderName: "web-design-audit", subpath: "skills/web-design-audit", fileCount: 1, totalBytes: 860 }, + ], + }); + handlers.agent_skills_preview = ({ subpath }) => + subpath === "skills/web-design-audit" + ? { + owner: "vercel-labs", + repo: "agent-skills", + gitRef: "main", + treeSha: "9f8e7d6c", + subpath: "skills/web-design-audit", + skillName: "web-design-audit", + description: "Audit responsive layout and contrast tokens", + skillMarkdown: + "---\nname: web-design-audit\ndescription: Audit responsive layout and contrast tokens\n---\n\nCheck spacing and contrast tokens.\n", + files: [{ path: "SKILL.md", size: 860, executable: false, symlink: false }], + scanWarnings: [], + alreadyInstalledUser: false, + alreadyInstalledWorkspace: false, + } + : { + owner: "vercel-labs", + repo: "agent-skills", + gitRef: "main", + treeSha: "9f8e7d6c", + subpath: "skills/find-skills", + skillName: "find-skills", + description: "Discover reusable SKILL.md workflows and inspect bundled scripts", + skillMarkdown: + "---\nname: find-skills\ndescription: Discover reusable SKILL.md workflows and inspect bundled scripts\nallowed-tools:\n - Bash(gh:*)\n---\n\nInspect candidate SKILL.md files before installing.\n", + files: [ + { path: "SKILL.md", size: 980, executable: false, symlink: false }, + { path: "scripts/inspect.sh", size: 440, executable: true, symlink: false }, + ], + scanWarnings: [ + { + kind: "executableScript", + file: "scripts/inspect.sh", + message: "Contains executable file mode (100755)", + }, + { + kind: "allowedToolsShell", + file: "SKILL.md", + message: "`allowed-tools` grants shell/command execution (`Bash(gh:*)`)", + }, + ], + alreadyInstalledUser: false, + alreadyInstalledWorkspace: false, + }; + handlers.agent_skills_install = ({ input }) => { + const req = input as { subpath: string; scope: "user" | "workspace" }; + const installedName = req.subpath.endsWith("web-design-audit") ? "web-design-audit" : "find-skills"; + skills = [ + ...skills, + { + skill: { + name: installedName, + description: "Discover reusable SKILL.md workflows and inspect bundled scripts", + hint: null, + path: + req.scope === "workspace" + ? `/dev/openidea/.agents/skills/${installedName}` + : `/Users/dev/.agents/skills/${installedName}`, + source: req.scope === "workspace" ? "workspace" : "user", + alsoIn: [], + userInvocable: true, + disableModelInvocation: false, + valid: true, + warnings: [], + }, + mode: "auto", + origin: "none", + }, + ]; + return skills; + }; handlers.agent_set_skill_overrides = ({ overrides }) => { currentTask = { ...currentTask, skillOverrides: overrides as Record }; return currentTask; @@ -226,7 +328,11 @@ test("manages multi-level skills in Settings and per-session overrides via Compo const sessionPopup = page.getByRole("dialog", { name: "Session Skills" }); await expect(sessionPopup).toBeVisible(); await expect(sessionPopup).toContainText("verify"); + await expect(sessionPopup).toContainText("fork"); + await expect(sessionPopup).toContainText("paths"); await expect(sessionPopup).toContainText("impeccable"); + await expect(sessionPopup).toContainText("Plugins"); + await expect(sessionPopup).toContainText("release-notes"); await expect(sessionPopup).toContainText("Untrusted workspace"); // Enable default-off `impeccable` for this session and turn `pg-tune` off for this session. @@ -250,12 +356,48 @@ test("manages multi-level skills in Settings and per-session overrides via Compo await expect(settingsDialog).toBeVisible(); await expect(settingsDialog.getByRole("heading", { name: "Skills" })).toBeVisible(); await expect(settingsDialog.getByTitle(".claude/skills").first()).toHaveText("Claude Code"); + await expect(settingsDialog.getByText("context: fork")).toBeVisible(); + await expect(settingsDialog.getByText("paths (2)")).toBeVisible(); await settingsDialog.getByRole("button", { name: /^verify/ }).click(); await expect(settingsDialog.getByText("Claude Code (.claude/skills)")).toBeVisible(); + await expect(settingsDialog.getByText("src/**/*.tsx, e2e/*.spec.ts")).toBeVisible(); await expect(settingsDialog.getByText("SKILL.md is valid")).toBeVisible(); + await settingsDialog.getByRole("tab", { name: /Plugins/ }).click(); + await expect(settingsDialog.getByText("release-notes")).toBeVisible(); + await expect(settingsDialog.getByText("[[contributes.skills]]")).toBeVisible(); + if (screenshotDir) { + await settingsDialog.screenshot({ path: `${screenshotDir}/after-settings-skills-plugins.png` }); + await settingsDialog.getByRole("tab", { name: /All Sources/ }).click(); await settingsDialog.screenshot({ path: `${screenshotDir}/after-settings-skills.png` }); } + + // Open Install Skill… dialog, fetch repository, verify static scan warning gate, confirm, and install. + await settingsDialog.getByRole("button", { name: "Install Skill…" }).click(); + const installDialog = page.getByRole("dialog", { name: "Install Agent Skill" }); + await expect(installDialog).toBeVisible(); + await installDialog.getByLabel("Skill repository").fill("vercel-labs/agent-skills"); + await installDialog.getByRole("button", { name: "Fetch" }).click(); + + await expect(installDialog.getByText("Static security scan found 2 warnings")).toBeVisible(); + const installBtn = installDialog.getByRole("button", { name: "Install", exact: true }); + await expect(installBtn).toBeDisabled(); + + if (screenshotDir) { + await installDialog.screenshot({ path: `${screenshotDir}/after-install-skill-dialog.png` }); + } + + await installDialog.getByLabel("I reviewed these warnings and want to install this skill").click(); + await expect(installBtn).toBeEnabled(); + await installBtn.click(); + + await expect(installDialog).toHaveCount(0); + await settingsDialog.getByRole("tab", { name: /^User/ }).click(); + await expect(settingsDialog.getByText("find-skills")).toBeVisible(); + + if (screenshotDir) { + await settingsDialog.screenshot({ path: `${screenshotDir}/after-settings-skills-installed.png` }); + } }); diff --git a/e2e/breakpointDialogLayout.spec.ts b/e2e/breakpointDialogLayout.spec.ts index 9d894dfbaf..c8b51b8fd1 100644 --- a/e2e/breakpointDialogLayout.spec.ts +++ b/e2e/breakpointDialogLayout.spec.ts @@ -18,18 +18,27 @@ test("keeps breakpoint details editable when the dialog gets narrow", async ({ w const list = dialog.getByRole("listbox", { name: "All breakpoints" }); const condition = dialog.locator('input[aria-label="Condition"]'); await expect(condition).toHaveValue("amount > 100"); + const actions = dialog.getByRole("group", { name: "Actions", exact: true }); + await expect(actions).toBeVisible(); + await expect(dialog.getByText("Condition", { exact: true })).toHaveCSS("font-size", "13px"); + await expect(dialog.getByText("Hit count", { exact: true })).toHaveCSS("font-size", "13px"); await expect.poll(async () => (await condition.boundingBox())?.width ?? 0).toBeGreaterThanOrEqual(240); await expect(dialog.getByRole("button", { name: "Done", exact: true })).toBeInViewport({ ratio: 1 }); await condition.fill("amount > 250"); - await dialog.getByRole("checkbox", { name: "Evaluate and log", exact: true }).check(); - await dialog.getByRole("textbox", { name: "Evaluate and log", exact: true }).fill("total: {amount}"); + await actions.getByRole("checkbox", { name: '"Breakpoint hit" message', exact: true }).check(); + await actions.getByRole("checkbox", { name: "Evaluate and log", exact: true }).check(); + const log = actions.getByRole("textbox", { name: "Evaluate and log", exact: true }); + await log.fill("total: {amount}"); + const temporary = actions.getByRole("checkbox", { name: "Remove once hit", exact: true }); + await temporary.check(); const first = list.getByRole("option", { name: /CheckInternationalSettlementBeforeDispatch\.java:8/ }); await expect(first.getByText(":8", { exact: true })).toBeInViewport({ ratio: 1 }); await list.getByRole("option", { name: /Receipt\.java:5/ }).click(); await expect(condition).toHaveValue(""); await first.click(); await expect(condition).toHaveValue("amount > 250"); - await expect(dialog.getByRole("textbox", { name: "Evaluate and log", exact: true })).toHaveValue("total: {amount}"); + await expect(log).toHaveValue("total: {amount}"); + await expect(temporary).toBeChecked(); await page.setViewportSize({ width: 1080, height: 760 }); const divider = dialog.locator('[data-separator][aria-orientation="vertical"]'); diff --git a/e2e/codeInsight.spec.ts b/e2e/codeInsight.spec.ts index 26824d47a8..f27f1c1f9d 100644 --- a/e2e/codeInsight.spec.ts +++ b/e2e/codeInsight.spec.ts @@ -715,6 +715,58 @@ test("rename keeps the typed name, uses the editor font and shows long preview n await expect.poll(() => ipcCalls(page, "apply_workspace_edit")).toHaveLength(1); }); +test("intentions separate quick fixes from other actions and navigate across the divider", async ({ + workbench: page, +}) => { + const editor = await openSample(page); + const fix = "Correct the Order type"; + const refactor = "Extract the order value"; + await page.evaluate( + ({ file, edit, fix, refactor }) => { + const action = (title: string, kind: string, newText: string) => ({ + title, + kind, + isPreferred: false, + disabledReason: null, + edit: { files: [{ kind: "edit", path: file, edits: [{ range: edit, new_text: newText }] }] }, + command: null, + data: null, + server: 1, + }); + window.__ipc.handlers.lsp_code_actions = () => [ + action(refactor, "refactor.extract", "ExtractedOrder"), + action(fix, "quickfix", "CorrectOrder"), + ]; + window.__ipc.handlers.lsp_execute_code_action = () => []; + }, + { file: FILE, edit: range(20, 19, 24), fix, refactor }, + ); + await caretAt(editor, page, "val order: Order", "Order "); + await page.keyboard.press("Alt+Enter"); + + const popup = page.getByRole("dialog", { name: "Intentions", exact: true }); + const list = popup.getByRole("listbox", { name: "Intentions" }); + const divider = list.locator("[class*=listDivider]"); + const preview = popup.locator('[aria-label="Preview"] pre'); + await expect(list.getByRole("option", { name: fix })).toBeVisible(); + await page.keyboard.type("order"); + await expect(list.getByRole("option")).toHaveText([fix, refactor]); + await expect(divider).toHaveCount(1); + await expect(list.getByRole("option", { name: fix })).toHaveAttribute("aria-selected", "true"); + await expect(preview).toContainText("CorrectOrder"); + await list.press("ArrowDown"); + await expect(list.getByRole("option", { name: refactor })).toHaveAttribute("aria-selected", "true"); + await expect(preview).toContainText("ExtractedOrder"); + + for (const _character of "order") await list.press("Backspace"); + await page.keyboard.type("extract"); + await expect(list.getByRole("option")).toHaveText([refactor]); + await expect(divider).toHaveCount(0); + await list.press("Enter"); + await expect(popup).toBeHidden(); + await expect.poll(() => ipcCalls(page, "lsp_execute_code_action")).toHaveLength(1); +}); + test("intention previews fit narrow windows and wrap long code lines", async ({ workbench: page }) => { await page.setViewportSize({ width: 1600, height: 900 }); const editor = await openSample(page); diff --git a/e2e/debugVariablesLayout.spec.ts b/e2e/debugVariablesLayout.spec.ts index 90b6ad4ad4..b78512415e 100644 --- a/e2e/debugVariablesLayout.spec.ts +++ b/e2e/debugVariablesLayout.spec.ts @@ -4,61 +4,178 @@ const amountName = "regionalSettlementAmountFromExternalProcessorBeforeRounding" const routingName = "settlementRoutingReferenceForCrossBorderReconciliation"; const routingText = "APR-2026 / eu-west / batch-701 / settlement complete"; const routingValue = "'" + routingText + "'"; +const invalidValueMessage = "The settlement amount must be a valid decimal expression."; -test("keeps values and their full-value action readable in a narrow debugger", async ({ workbench: page }) => { - await page.setViewportSize({ width: 1220, height: 760 }); +test.describe("a paused session with editable values", () => { + test.beforeEach(async ({ workbench: page }) => { + await page.setViewportSize({ width: 1220, height: 760 }); + await stubDesktop(page); + await page.evaluate( + async ({ amountName, routingName, routingValue, invalidValueMessage }) => { + const debugModule = "/src/features/debugger/state.ts"; + const layoutModule = "/src/workbench/toolwindows/store.ts"; + const servicesModule = "/src/workbench/contributions.ts"; + const { adoptSession } = await import(/* @vite-ignore */ debugModule); + const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule); + const { toolWindowService } = await import(/* @vite-ignore */ servicesModule); + const h = window.__ipc.handlers; + let amountValue = "47.74"; + const amount = () => ({ + name: amountName, + value: amountValue, + typeName: "float", + variablesReference: 0, + evaluateName: amountName, + }); + h.debug_scopes = () => [{ name: "Locals", variablesReference: 100, expensive: false }]; + h.debug_variables = () => [ + amount(), + { name: routingName, value: routingValue, typeName: "str", variablesReference: 0, evaluateName: routingName }, + ]; + h.debug_set_variable = ({ value }) => { + if (value === "invalid") throw { kind: "invalid", message: invalidValueMessage, detail: null }; + amountValue = String(value); + return amount(); + }; + adoptSession(91, { + name: "Checkout", + adapter: "debugpy", + status: "paused", + selectedFrame: 11, + frames: [{ id: 11, name: "checkout", path: null, line: 0, column: 0, presentationHint: null }], + }); + moveToolWindow("debug", "right"); + setToolWindowSize("right", 390); + toolWindowService().show("debug", true); + }, + { amountName, routingName, routingValue, invalidValueMessage }, + ); + + const debug = page.getByRole("region", { name: "Debug", exact: true }); + await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click(); + }); + + test("keeps values and their full-value action readable in a narrow debugger", async ({ workbench: page }) => { + const debug = page.getByRole("region", { name: "Debug", exact: true }); + const amount = debug.getByText("47.74", { exact: true }); + await expect + .poll(() => amount.evaluate((el) => el.clientWidth > 0 && el.scrollWidth <= el.clientWidth + 1)) + .toBe(true); + const routing = debug.getByRole("treeitem").filter({ hasText: routingName }); + const show = routing.getByTitle("Show", { exact: true }); + await expect(show).toBeInViewport({ ratio: 1 }); + await show.click(); + const dialog = page.getByRole("dialog", { name: `Value of ${routingName}` }); + await expect(dialog.getByText(routingText, { exact: true })).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + + await page.setViewportSize({ width: 1640, height: 760 }); + await page.evaluate(async () => { + const layoutModule = "/src/workbench/toolwindows/store.ts"; + const { moveToolWindow } = await import(/* @vite-ignore */ layoutModule); + moveToolWindow("debug", "bottom"); + }); + await expect(show).toBeHidden(); + await expect + .poll(() => + routing.getByText(routingValue, { exact: true }).evaluate((el) => el.scrollWidth <= el.clientWidth + 1), + ) + .toBe(true); + }); + + test("keeps the variable label and input in place when editing a value", async ({ workbench: page }) => { + const debug = page.getByRole("region", { name: "Debug", exact: true }); + const row = debug.getByRole("treeitem").filter({ hasText: amountName }); + const name = row.getByText(amountName, { exact: true }); + await row.click(); + const nameBefore = (await name.boundingBox())!; + const equal = row.getByText("=", { exact: true }); + const equalBefore = (await equal.boundingBox())!; + const color = await name.evaluate((el) => getComputedStyle(el).color); + + await page.keyboard.press("F2"); + const input = row.getByRole("textbox", { name: `New value of ${amountName}` }); + await expect(input).toBeFocused(); + await expect(input).toHaveValue("47.74"); + await expect(name).toHaveCSS("color", color); + expect((await name.boundingBox())!.x).toBeCloseTo(nameBefore.x, 0); + expect((await equal.boundingBox())!.x).toBeCloseTo(equalBefore.x, 0); + await expect(row.locator("svg")).toHaveCount(1); + + await input.fill("invalid"); + await input.press("Enter"); + await expect(input).toHaveAttribute("aria-invalid", "true"); + await expect(input).toHaveAttribute("title", invalidValueMessage); + await expect(input).toBeInViewport({ ratio: 1 }); + expect((await input.boundingBox())!.width).toBeGreaterThan(60); + expect((await equal.boundingBox())!.x).toBeCloseTo(equalBefore.x, 0); + + await input.press("Escape"); + await expect(input).toBeHidden(); + await expect(row).toContainText("47.74"); + + await page.keyboard.press("F2"); + await expect(input).toHaveValue("47.74"); + await input.fill("48.25"); + await input.press("Enter"); + await expect(input).toBeHidden(); + await expect(row).toContainText("48.25"); + }); +}); + +test("keeps a decimal value legible beside a long runtime type", async ({ workbench: page }) => { + const name = "dailySettlementTotal"; + const type = "ExactSettlementAmountForCrossBorderReconciliation"; + const value = "12486245.8067"; + const countName = "pendingInvoices"; + await page.setViewportSize({ width: 1100, height: 720 }); await stubDesktop(page); await page.evaluate( - async ({ amountName, routingName, routingValue }) => { + async ({ name, type, value, countName }) => { const debugModule = "/src/features/debugger/state.ts"; const layoutModule = "/src/workbench/toolwindows/store.ts"; - const servicesModule = "/src/workbench/contributions.ts"; + const serviceModule = "/src/workbench/contributions.ts"; const { adoptSession } = await import(/* @vite-ignore */ debugModule); const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule); - const { toolWindowService } = await import(/* @vite-ignore */ servicesModule); - const h = window.__ipc.handlers; - h.debug_scopes = () => [{ name: "Locals", variablesReference: 100, expensive: false }]; - h.debug_variables = () => [ - { name: amountName, value: "47.74", typeName: "float", variablesReference: 0, evaluateName: amountName }, - { name: routingName, value: routingValue, typeName: "str", variablesReference: 0, evaluateName: routingName }, + const { toolWindowService } = await import(/* @vite-ignore */ serviceModule); + window.__ipc.handlers.debug_scopes = () => [{ name: "Locals", variablesReference: 100, expensive: false }]; + window.__ipc.handlers.debug_variables = () => [ + { name, value, typeName: type, variablesReference: 0, evaluateName: name }, + { name: countName, value: "327", typeName: "int", variablesReference: 0, evaluateName: countName }, ]; - adoptSession(91, { - name: "Checkout", + adoptSession(92, { + name: "Settlement", adapter: "debugpy", status: "paused", selectedFrame: 11, - frames: [{ id: 11, name: "checkout", path: null, line: 0, column: 0, presentationHint: null }], + frames: [{ id: 11, name: "settle", path: null, line: 0, column: 0, presentationHint: null }], }); moveToolWindow("debug", "right"); - setToolWindowSize("right", 390); + setToolWindowSize("right", 280); toolWindowService().show("debug", true); }, - { amountName, routingName, routingValue }, + { name, type, value, countName }, ); - const debug = page.getByRole("region", { name: "Debug", exact: true }); await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click(); - const amount = debug.getByText("47.74", { exact: true }); - await expect - .poll(() => amount.evaluate((el) => el.clientWidth > 0 && el.scrollWidth <= el.clientWidth + 1)) - .toBe(true); - const routing = debug.getByRole("treeitem").filter({ hasText: routingName }); - const show = routing.getByTitle("Show", { exact: true }); - await expect(show).toBeInViewport({ ratio: 1 }); - await show.click(); - const dialog = page.getByRole("dialog", { name: `Value of ${routingName}` }); - await expect(dialog.getByText(routingText, { exact: true })).toBeVisible(); - await page.keyboard.press("Escape"); - await expect(dialog).toBeHidden(); + const variable = debug.getByRole("treeitem").filter({ hasText: name }); + const amount = variable.getByText(value, { exact: true }); + const annotation = variable.getByTitle(`{${type}}`, { exact: true }); + await expect(amount).toBeVisible(); + await expect.poll(() => amount.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); + await expect(variable.getByTitle("Show", { exact: true })).toBeHidden(); + await expect(annotation).toBeVisible(); - await page.setViewportSize({ width: 1640, height: 760 }); + const shortValueName = debug.getByText(countName, { exact: true }); + await expect.poll(() => shortValueName.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); + + await page.setViewportSize({ width: 1440, height: 760 }); await page.evaluate(async () => { const layoutModule = "/src/workbench/toolwindows/store.ts"; - const { moveToolWindow } = await import(/* @vite-ignore */ layoutModule); + const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule); moveToolWindow("debug", "bottom"); + setToolWindowSize("bottom", 310); }); - await expect(show).toBeHidden(); - await expect - .poll(() => routing.getByText(routingValue, { exact: true }).evaluate((el) => el.scrollWidth <= el.clientWidth + 1)) - .toBe(true); + await expect.poll(() => annotation.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); }); diff --git a/e2e/diff-navigation.spec.ts b/e2e/diff-navigation.spec.ts index 5a2a04a86f..5d723f16dd 100644 --- a/e2e/diff-navigation.spec.ts +++ b/e2e/diff-navigation.spec.ts @@ -111,6 +111,70 @@ test("a narrow diff keeps navigation, settings and the difference count visible" await expect(toolbar).toContainText("1 of 1 differences"); }); +test("revision titles keep both filenames in view when the diff divider moves", async ({ workbench: page }) => { + const leftName = "OrderRoutes.ts"; + const rightName = "OrdersRoutes.ts"; + const directory = "services/customer-orders/fulfillment/warehouse-routing/primary"; + await page.setViewportSize({ width: 800, height: 650 }); + await stubDesktop(page); + await page.evaluate( + async ({ directory, leftName, rightName }) => { + const inputPath = "/src/features/vcs/diffInput.ts"; + const layoutPath = "/src/workbench/toolwindows/store.ts"; + const { openDiff } = await import(inputPath); + const { hideAllToolWindows } = await import(layoutPath); + const leftPath = `/dev/acme-api/${directory}/${leftName}`; + const rightPath = `/dev/acme-api/${directory}/${rightName}`; + window.__ipc.handlers.vcs_file_at = (args) => + args.rev === "7b70e02c" ? "export const region = 'east';\r\n" : "export const region = 'west';\n"; + window.__ipc.handlers.vcs_file_mode = () => "100644"; + hideAllToolWindows(); + localStorage.setItem("openidea.vcs.diffOptions", JSON.stringify({ mode: "split", alignChanges: false })); + await openDiff({ + path: rightPath, + left: { type: "rev", rev: "7b70e02c", path: leftPath }, + right: { type: "rev", rev: "a8c5f31d", path: rightPath }, + }); + }, + { directory, leftName, rightName }, + ); + const left = page.getByTitle(/^7b70e02c .*OrderRoutes\.ts$/); + const right = page.getByTitle(/^a8c5f31d .*OrdersRoutes\.ts$/); + const filenamesFit = async () => { + for (const [title, filename] of [ + [left, leftName], + [right, rightName], + ] as const) { + await expect(title).toBeVisible(); + expect(await title.getAttribute("title")).toContain(`${directory}/${filename}`); + const text = title.locator("span").filter({ hasText: filename }).last(); + expect( + await text.evaluate((el, filename) => { + const node = el.firstChild!; + const range = document.createRange(); + range.setStart(node, (node.textContent ?? "").length - filename.length); + range.setEnd(node, (node.textContent ?? "").length); + const bounds = range.getBoundingClientRect(); + const clip = el.getBoundingClientRect(); + return bounds.left >= clip.left - 1 && bounds.right <= clip.right + 1; + }, filename), + `${filename} is visible within its revision label`, + ).toBe(true); + } + }; + await filenamesFit(); + + const divider = page.getByRole("separator", { name: "Resize diff panes" }); + const { x, y, width, height } = (await divider.boundingBox())!; + const leftWidth = (await left.boundingBox())!.width; + await page.mouse.move(x + width / 2, y + height / 2); + await page.mouse.down(); + await page.mouse.move(x + width / 2 - 96, y + height / 2, { steps: 4 }); + await page.mouse.up(); + await expect.poll(async () => (await left.boundingBox())!.width).toBeLessThan(leftWidth - 60); + await filenamesFit(); +}); + test("a medium-width diff keeps its full status beside the viewer tools", async ({ workbench: page }) => { await page.setViewportSize({ width: 490, height: 650 }); await page.evaluate(async () => { diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index 750158d484..56fbab85c5 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -526,7 +526,7 @@ test("Markdown preview keeps following find and edits after scrolling the source await content.focus(); await page.keyboard.press("Meta+a"); await page.keyboard.insertText("- **$`v_0`$ Flat wings.**"); - await expect(preview.locator("strong .katex annotation")).toHaveText("v_0"); + await expect(preview.locator("strong [data-math-svg] > svg")).toHaveAttribute("aria-label", "v_0"); }); test("Markdown preview aligns Mermaid diagrams to their container align attribute", async ({ workbench: page }) => { diff --git a/e2e/editorSingleRowTabsLayout.spec.ts b/e2e/editorSingleRowTabsLayout.spec.ts index f900982604..ae973835ca 100644 --- a/e2e/editorSingleRowTabsLayout.spec.ts +++ b/e2e/editorSingleRowTabsLayout.spec.ts @@ -69,3 +69,49 @@ test("the bottom single row keeps a long selected tab visible alongside the hidd await pane.getByRole("tab", { name: shortFile, exact: true }).press("End"); await expectCloseToFit(tab); }); + +test("same-name tabs keep the filename beside a shortened directory", async ({ workbench: page }) => { + const filename = "AllocationRule.ts"; + const first = "qa"; + const second = "backoffice-reconciliation"; + await openSplit(page, [`${first}/${filename}`, `${second}/${filename}`], "top"); + await page.setViewportSize({ width: 900, height: 760 }); + + const pane = page.locator("section[data-pane-id]").filter({ + has: page.getByRole("tab").filter({ hasText: second }), + }); + const selected = pane.getByRole("tab").filter({ hasText: second }); + await expect(selected).toHaveText(`${second}/${filename}`); + await expectCloseToFit(selected); + const directory = selected.getByText(`${second}/`, { exact: true }); + const name = selected.getByText(filename, { exact: true }); + await expect.poll(() => directory.evaluate((el) => el.clientWidth > 0 && el.scrollWidth > el.clientWidth)).toBe(true); + await expect + .poll(() => + name.evaluate((el) => { + const text = document.createRange(); + text.selectNodeContents(el); + return el.getBoundingClientRect().width >= text.getBoundingClientRect().width; + }), + ) + .toBe(true); + + await pane.getByRole("button", { name: "Show Hidden Tabs" }).click(); + const picker = page.getByRole("grid", { name: "Hidden Editor Tabs" }); + await expect(picker.getByRole("gridcell").filter({ hasText: `${first}/${filename}` })).toBeVisible(); + await page.keyboard.press("Enter"); + const firstTab = pane.getByRole("tab").filter({ hasText: first }); + await expectCloseToFit(firstTab); + await expect + .poll(() => + firstTab.getByText(`${first}/`, { exact: true }).evaluate((el) => { + const text = document.createRange(); + text.selectNodeContents(el); + return Math.abs(el.clientWidth - text.getBoundingClientRect().width); + }), + ) + .toBeLessThanOrEqual(1); + + await firstTab.locator("..").getByRole("button", { name: "Close Tab", exact: true }).click(); + await expect(page.getByRole("tab", { name: filename, exact: true })).toHaveAttribute("aria-selected", "true"); +}); diff --git a/e2e/gitLogScrollbar.spec.ts b/e2e/gitLogScrollbar.spec.ts index 4a8b6da115..e70fca87bf 100644 --- a/e2e/gitLogScrollbar.spec.ts +++ b/e2e/gitLogScrollbar.spec.ts @@ -117,7 +117,7 @@ test("fits a wide graph and saved columns without horizontal scrolling", async ( expect(await list.evaluate((element) => element.scrollLeft)).toBe(0); }); -test("keeps ref names visible when a long commit subject competes for space", async ({ workbench: page }) => { +test("keeps expanded ref names visible when a long commit subject competes for space", async ({ workbench: page }) => { const branch = "origin/feature/workspace-settings"; const tag = "v2.1"; const summary = "Keep workspace settings and commit references visible ".repeat(4).trim(); @@ -127,7 +127,7 @@ test("keeps ref names visible when a long commit subject competes for space", as const options = "/src/features/vcs/logOptions.ts"; const { useGitLog } = await import(/* @vite-ignore */ log); const { useLogOptions } = await import(/* @vite-ignore */ options); - useLogOptions.setState({ tagNames: true }); + useLogOptions.setState({ tagNames: true, compactRefs: false }); const [first, ...rest] = useGitLog.getState().commits; useGitLog.setState({ commits: [{ ...first, summary, refs: [branch, `tag: ${tag}`] }, ...rest] }); }, diff --git a/e2e/gitLogToolbarMenus.spec.ts b/e2e/gitLogToolbarMenus.spec.ts index fac6341476..fdef939250 100644 --- a/e2e/gitLogToolbarMenus.spec.ts +++ b/e2e/gitLogToolbarMenus.spec.ts @@ -112,6 +112,57 @@ test("Git Log separates commit message typography from compact metadata", async await expect(author).toHaveCSS("font-size", "12px"); }); +test("compact Git Log refs give the subject room on either side", async ({ workbench: page }) => { + await page.setViewportSize({ width: 630, height: 720 }); + const refSubject = "Reconcile shipping credits"; + const longReference = "release-quarterly-settlement-and-backoffice-invoice-reconciliation"; + await page.evaluate( + async ({ refSubject, longReference }) => { + const optionsModule = "/src/features/vcs/logOptions.ts"; + const logModule = "/src/features/vcs/logStore.ts"; + const { setLogOptions } = await import(/* @vite-ignore */ optionsModule); + const { useGitLog } = await import(/* @vite-ignore */ logModule); + setLogOptions({ showBranches: false, showDetails: false }); + const [first, ...rest] = useGitLog.getState().commits; + useGitLog.setState({ + commits: [{ ...first, summary: refSubject, message: refSubject, refs: [longReference] }, ...rest], + }); + }, + { refSubject, longReference }, + ); + const row = page.getByRole("listbox", { name: "Commits" }).getByRole("option").filter({ hasText: refSubject }); + const subject = row.getByText(refSubject, { exact: true }); + const ref = row.getByTitle(longReference, { exact: true }); + const expectLayout = async () => { + await expect + .poll(() => + subject.evaluate((el) => { + const text = document.createRange(); + text.selectNodeContents(el); + return el.getBoundingClientRect().width + 0.02 >= text.getBoundingClientRect().width; + }), + ) + .toBe(true); + await expect + .poll(() => + ref.evaluate((el) => { + const refs = el.parentElement!; + return refs.clientWidth / refs.parentElement!.clientWidth; + }), + ) + .toBeLessThanOrEqual(0.34); + await expect(ref).toHaveCSS("font-size", "12px"); + await expect(subject).toHaveCSS("font-size", "13px"); + }; + await expectLayout(); + await expect.poll(async () => (await subject.boundingBox())!.x < (await ref.boundingBox())!.x).toBe(true); + + await page.getByRole("toolbar", { name: "Log filters" }).getByRole("button", { name: "View Options" }).click(); + await page.getByRole("menuitemcheckbox", { name: "References on the Left" }).click(); + await expectLayout(); + await expect.poll(async () => (await subject.boundingBox())!.x > (await ref.boundingBox())!.x).toBe(true); +}); + test("a second click on a Git Log toolbar button closes its popup", async ({ workbench: page }) => { const toolbar = page.getByRole("toolbar", { name: "Log filters" }); const branchPopup = page.getByRole("dialog", { name: "Filter by Branch" }); @@ -174,6 +225,50 @@ test("Git Log keeps filters and actions inside the commit pane at the minimum wi await expect(page.getByRole("menuitem", { name: "Paths" })).toBeVisible(); }); +test("long Git Log filter values shorten inside their buttons", async ({ workbench: page }) => { + const branchName = "feature/quarterly-settlement-and-backoffice-invoice-reconciliation"; + await page.setViewportSize({ width: 1120, height: 720 }); + await page.evaluate(async (branch) => { + const logModule = "/src/features/vcs/logStore.ts"; + const optionsModule = "/src/features/vcs/logOptions.ts"; + const { setLogBranches } = await import(/* @vite-ignore */ logModule); + const { setLogOptions } = await import(/* @vite-ignore */ optionsModule); + setLogOptions({ showBranches: false, showDetails: false }); + setLogBranches([branch]); + }, branchName); + + const toolbar = page.getByRole("toolbar", { name: "Log filters" }); + const branch = toolbar.getByRole("button", { name: `Branch: ${branchName}`, exact: true }); + const value = branch.getByText(branchName, { exact: true }); + const clear = toolbar.getByRole("button", { name: "Clear Branch filter", exact: true }); + for (const width of [1120, 620]) { + await page.setViewportSize({ width, height: 720 }); + await expect(branch).toBeVisible(); + await expect(value).toHaveCSS("text-overflow", "ellipsis"); + expect( + await value.evaluate((label) => { + const bounds = label.getBoundingClientRect(); + const button = label.closest("button")!.getBoundingClientRect(); + return label.scrollWidth > label.clientWidth && bounds.width > 0 && bounds.right <= button.right; + }), + ).toBe(true); + await expect(branch).toHaveAttribute("title", branchName); + await clear.click({ trial: true }); + } + + await page.setViewportSize({ width: 400, height: 560 }); + // The overflow is measured after the resize: open the menu once the filter has moved into it. + await expect(branch).toBeHidden(); + await toolbar.getByRole("button", { name: "More Filters" }).click(); + await expect(page.getByRole("menuitem", { name: `Branch: ${branchName}`, exact: true })).toBeVisible(); + await page.keyboard.press("Escape"); + + await page.setViewportSize({ width: 620, height: 720 }); + await clear.click(); + await expect(toolbar.getByRole("button", { name: "Branch", exact: true })).toBeVisible(); + await expect(clear).toBeHidden(); +}); + test("Git Log puts affected changes on the changed-files toolbar and groups preview options", async ({ workbench: page, }) => { diff --git a/e2e/pushTargetBranch.spec.ts b/e2e/pushTargetBranch.spec.ts index 37802644e1..baa171aa5d 100644 --- a/e2e/pushTargetBranch.spec.ts +++ b/e2e/pushTargetBranch.spec.ts @@ -177,7 +177,29 @@ test("Push keeps commit subjects and changed files readable in a narrow window", await expect(input).toHaveValue("main"); await expect(dialog.getByRole("button", { name: "Push", exact: true })).toBeInViewport(); const details = dialog.getByRole("region", { name: "Commit details" }); - await expect(details).toContainText("Keep the new totals consistent with receipts."); + await page.evaluate(async () => { + const project = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ project); + const { settings } = useProject.getState(); + useProject.setState({ + settings: { + ...settings, + editor: { ...settings?.editor, fontFamily: "Consolas", fontSize: 18, fontWeight: 400, boldFontWeight: 700 }, + }, + }); + }); + const messageSubject = details.getByText(OUTGOING, { exact: true }); + const messageBody = details.getByText("Keep the new totals consistent with receipts.", { exact: true }); + await expect(messageSubject).toHaveCSS("font-weight", "700"); + await expect(messageBody).toHaveCSS("font-weight", "400"); + await expect(messageSubject).toHaveCSS("font-size", "18px"); + await expect(messageBody).toHaveCSS("font-size", "18px"); + await expect(messageBody).toHaveCSS("font-family", /Consolas/); + const metadata = details.getByText(/Sam Rivera /); + await expect(metadata).toHaveCSS("font-size", "12px"); + await metadata.scrollIntoViewIfNeeded(); + await expect(metadata).toBeInViewport(); + expect(await details.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); await expect .poll(async () => { const [tree, message] = await Promise.all([files.boundingBox(), details.boundingBox()]); diff --git a/e2e/recentNavigationLayout.spec.ts b/e2e/recentNavigationLayout.spec.ts index 57889c4d23..428c2be6fb 100644 --- a/e2e/recentNavigationLayout.spec.ts +++ b/e2e/recentNavigationLayout.spec.ts @@ -93,3 +93,42 @@ test("Recent Locations keeps all snippet lines visible when the editor font grow await expect(row.getByText("changed", { exact: true })).toBeInViewport({ ratio: 1 }); await expect(filter).toBeFocused(); }); + +test("Recent Locations shows each file name once with its parent directory", async ({ workbench: page }) => { + await stubDesktop(page); + await page.evaluate(async () => { + const tracking = "/src/features/search/common/tracking.ts"; + const { useTracking } = await import(/* @vite-ignore */ tracking); + const now = Date.now(); + useTracking.setState({ + locations: [ + ["README.md", "# Shop API"], + ["packages/billing/Routes.ts", "registerBillingRoutes();"], + ["packages/checkout/Routes.ts", "registerCheckoutRoutes();"], + ].map(([path, snippet], index) => ({ + path: `/dev/acme-api/${path}`, + line: 0, + col: 0, + changed: false, + time: now - index * 60000, + snippet: [snippet], + snippetStart: 0, + })), + }); + }); + await openRecent(page, "recentLocations"); + const dialog = page.getByRole("dialog", { name: "Recent Locations", exact: true }); + const rows = dialog.getByRole("option"); + await expect(rows).toHaveCount(3); + await expect(rows.filter({ hasText: "# Shop API" }).getByText("README.md", { exact: true })).toHaveCount(1); + + const billing = rows.filter({ hasText: "registerBillingRoutes();" }); + const checkout = rows.filter({ hasText: "registerCheckoutRoutes();" }); + await expect(billing.getByText("packages/billing", { exact: true })).toBeVisible(); + await expect(checkout.getByText("packages/checkout", { exact: true })).toBeVisible(); + await expect(checkout.getByTitle("packages/checkout/Routes.ts", { exact: true })).toBeVisible(); + + await dialog.getByRole("textbox", { name: "Filter recent locations" }).fill("packages/checkout"); + await expect(rows).toHaveCount(1); + await expect(rows.first()).toContainText("registerCheckoutRoutes();"); +}); diff --git a/e2e/refactorPreviewLayout.spec.ts b/e2e/refactorPreviewLayout.spec.ts new file mode 100644 index 0000000000..e78dbc1ec0 --- /dev/null +++ b/e2e/refactorPreviewLayout.spec.ts @@ -0,0 +1,63 @@ +import { expect, test } from "./fixtures"; + +test("the workspace refactoring preview separates filenames from directories and keeps outcomes readable", async ({ + workbench: page, +}) => { + await page.setViewportSize({ width: 420, height: 620 }); + await page.evaluate(async () => { + const popupPath = "/src/editor/lsp/popupStore.ts"; + const editPath = "/src/editor/lsp/workspaceEdit.ts"; + const { openPopup } = await import(/* @vite-ignore */ popupPath); + const { summarizeWorkspaceEdit } = await import(/* @vite-ignore */ editPath); + const root = "/dev/acme-api"; + const edit = { + range: { start: { line: 0, col: 0 }, end: { line: 0, col: 9 } }, + new_text: "postInvoice", + }; + openPopup({ + kind: "preview", + title: "Rename 'saveOrder' to 'postInvoice'", + summary: summarizeWorkspaceEdit({ + files: [ + { kind: "edit", path: `${root}/README.md`, edits: [edit] }, + { kind: "edit", path: `${root}/packages/billing/src/Routes.ts`, edits: [edit, edit] }, + { kind: "edit", path: `${root}/packages/checkout/src/Routes.ts`, edits: [edit] }, + { + kind: "rename", + from: `${root}/packages/checkout/src/Invoice.ts`, + to: `${root}/packages/checkout/src/InvoiceReconciliationForInternationalOrders.ts`, + }, + ], + }), + renameThemeClasses: "", + confirmLabel: "Do Refactor", + onConfirm: () => { + document.body.dataset.refactorConfirmed = "true"; + }, + }); + }); + + const dialog = page.getByRole("dialog", { name: "Rename 'saveOrder' to 'postInvoice'" }); + const rows = dialog.getByRole("list", { name: "Changes" }).getByRole("listitem"); + await expect(rows).toHaveCount(4); + await expect(dialog.getByText("4 occurrences in 4 files")).toBeVisible(); + const root = rows.filter({ hasText: "README.md" }); + await expect(root.getByText("README.md", { exact: true })).toHaveCount(1); + + const billing = rows.filter({ hasText: "2 occurrences" }); + await expect(billing.getByText("Routes.ts", { exact: true })).toBeVisible(); + await expect(billing.getByText("packages/billing/src", { exact: true })).toBeVisible(); + await expect(billing.getByTitle("packages/billing/src/Routes.ts", { exact: true })).toBeVisible(); + const checkout = rows.filter({ hasText: "packages/checkout/src" }).filter({ hasText: "Routes.ts" }); + await expect(checkout.getByText("packages/checkout/src", { exact: true })).toBeVisible(); + + const rename = rows.filter({ hasText: "Invoice.ts" }); + const target = rename.getByText("→ InvoiceReconciliationForInternationalOrders.ts", { exact: true }); + await expect(target).toBeVisible(); + await expect(target).toHaveAttribute("title", "packages/checkout/src/InvoiceReconciliationForInternationalOrders.ts"); + expect((await target.boundingBox())!.width).toBeGreaterThan(35); + await expect(dialog.getByRole("button", { name: "Do Refactor", exact: true })).toBeInViewport(); + await dialog.getByRole("button", { name: "Do Refactor", exact: true }).click(); + await expect(dialog).toBeHidden(); + await expect(page.locator("body")).toHaveAttribute("data-refactor-confirmed", "true"); +}); diff --git a/e2e/run.spec.ts b/e2e/run.spec.ts index 4a1cb62881..0861c7b957 100644 --- a/e2e/run.spec.ts +++ b/e2e/run.spec.ts @@ -76,6 +76,73 @@ test("⌃R runs the selected configuration and shows its output and exit", async expect(started).toMatchObject({ config: { id: "npm:dev", command: "npm", args: ["run", "dev"] } }); }); +test("expanded console folds stay reachable at the start of their rows", async ({ workbench: page }) => { + const heading = "Reconciling orders for the overnight settlement and inventory reporting pipeline"; + await stubRun( + page, + [ + { + kind: "stdout", + text: [ + "TRACE Reused inventory connection", + "TRACE Loaded warehouse configuration", + heading, + "TRACE Checked warehouse audit result", + "TRACE Updated inventory snapshot", + "Processed 24 orders", + "", + ].join("\n"), + }, + ], + null, + ); + await page.evaluate(async () => { + const projectModule = "/src/platform/project.ts"; + const layoutModule = "/src/workbench/toolwindows/store.ts"; + const { useProject } = await import(/* @vite-ignore */ projectModule); + const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule); + const { settings } = useProject.getState(); + useProject.setState({ + settings: { ...settings, console: { ...settings?.console, foldPatterns: ["TRACE "] } }, + }); + moveToolWindow("run", "right"); + setToolWindowSize("right", 320); + }); + await page.keyboard.press("Control+r"); + const log = page.getByRole("region", { name: "Run", exact: true }).getByRole("log"); + const expand = log.getByTitle("Expand folded lines", { exact: true }); + const collapse = log.getByRole("button", { name: "Collapse folded lines", exact: true }); + await expect(expand).toHaveCount(2); + + await expand.first().click(); + await expect(log.getByText("TRACE Reused inventory connection", { exact: true })).toBeVisible(); + await expect(collapse).toHaveCount(1); + await collapse.press("Space"); + await expect(expand).toHaveCount(2); + + await expand.first().press("Enter"); + await expect(collapse).toBeFocused(); + await expand.last().click(); + await expect(collapse).toHaveCount(2); + for (const scrollLeft of [0, 120]) { + await log.evaluate((element, x) => (element.scrollLeft = x), scrollLeft); + expect(await log.evaluate((element) => element.scrollLeft)).toBe(scrollLeft); + for (const control of await collapse.all()) { + const aligned = await control.evaluate((button) => { + const log = button.closest('[role="log"]')!.getBoundingClientRect(); + const row = button.closest("[data-index]")!.getBoundingClientRect(); + const box = button.getBoundingClientRect(); + return Math.abs(box.left - log.left) <= 1 && box.top >= row.top && box.bottom <= row.bottom + 1; + }); + expect(aligned).toBe(true); + } + } + await collapse.first().click(); + await collapse.first().click(); + await expect(expand).toHaveCount(2); + expect(await ipcCalls(page, "run_stdin")).toEqual([]); +}); + test("⌘F2 stops a running process", async ({ workbench: page }) => { await stubRun(page, [{ kind: "stdout", text: "Watching for changes…\n" }], null); await page.keyboard.press("Control+r"); @@ -122,6 +189,45 @@ test("a long Run tab fits its side panel with room for the pin and close buttons await expect(run).toBeHidden(); }); +test("the Run toolbar keeps primary actions in one row in a side dock", async ({ workbench: page }) => { + const output = "Waiting for orders. ".repeat(8).trim(); + await stubRun(page, [{ kind: "stdout", text: `${output}\n` }], null); + const dock = async (width: number) => { + await page.evaluate(async (width) => { + const path = "/src/workbench/toolwindows/store.ts"; + const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ path); + moveToolWindow("run", "right"); + setToolWindowSize("right", width); + }, width); + }; + await dock(200); + await page.keyboard.press("Control+r"); + const run = page.getByRole("region", { name: "Run", exact: true }); + const toolbar = run.getByRole("toolbar", { name: "Run actions" }); + const console = run.getByRole("log"); + await expect(console).toContainText(output); + await expect + .poll(() => toolbar.evaluate((el) => new Set([...el.querySelectorAll("button")].map((b) => b.offsetTop)).size)) + .toBe(1); + const more = toolbar.getByRole("button", { name: "More Actions" }); + const menu = page.getByRole("menu", { name: "More Actions" }); + await more.press("Enter"); + const wrap = menu.getByRole("menuitemcheckbox", { name: "Soft-Wrap" }); + await expect(wrap).toHaveAttribute("aria-checked", "false"); + await expect(menu.getByRole("menuitemcheckbox", { name: "Scroll to End" })).toHaveAttribute("aria-checked", "true"); + await wrap.click(); + await expect(menu).toBeHidden(); + await expect.poll(() => console.evaluate((el) => el.scrollWidth <= el.clientWidth + 1)).toBe(true); + + await dock(340); + await expect(toolbar.getByRole("button", { name: "Soft-Wrap" })).toHaveAttribute("aria-pressed", "true"); + await expect(toolbar.getByRole("button", { name: "Scroll to End" })).toBeVisible(); + await more.click(); + await expect(menu.getByRole("menuitemcheckbox")).toHaveCount(0); + await menu.getByRole("menuitem", { name: "Edit Configurations…" }).click(); + await expect(page.getByRole("dialog", { name: "Run/Debug Configurations" })).toBeVisible(); +}); + test("a short Run pane has room for the full toolbar above the output", async ({ workbench: page }) => { await page.setViewportSize({ width: 400, height: 500 }); const output = "Watching for changes…"; @@ -284,6 +390,64 @@ test("test results keep counts, actions and selected output visible as the pane await expect(output).toContainText(message); }); +test("test results keep elapsed time beside the counts", async ({ workbench: page }) => { + await page.setViewportSize({ width: 1060, height: 740 }); + const lines = [ + "test_tax (test_ledger.CheckoutTests.test_tax) ... ok", + "test_refund (test_ledger.CheckoutTests.test_refund) ... FAIL", + "test_callback (test_ledger.CheckoutTests.test_callback) ... skipped 'Requires a callback'", + "Ran 3 tests in 0.170s", + "FAILED (failures=1, skipped=1)", + ]; + await stubRun(page, [{ kind: "stderr", text: lines.join("\n") + "\n" }], 1, { + id: "django:checkout-tests", + name: "Checkout tests", + kind: "django-test", + command: "python", + args: ["manage.py", "test", "-v", "2"], + isTest: true, + }); + await page.keyboard.press("Control+r"); + const run = page.getByRole("region", { name: "Run", exact: true }); + const summary = run.getByRole("status").filter({ hasText: "1 failing" }); + const ignored = summary.getByText("1 ignored", { exact: true }); + const elapsed = summary.getByText("170 ms", { exact: true }); + await expect(elapsed).toBeVisible(); + for (const width of [1060, 540]) { + await page.setViewportSize({ width, height: 740 }); + await expect + .poll(async () => { + const [count, duration] = await Promise.all([ignored.boundingBox(), elapsed.boundingBox()]); + return count && duration && Math.abs(count.y - duration.y) <= 1 ? duration.x - count.x - count.width : Infinity; + }) + .toBeLessThanOrEqual(12); + } + await expect(summary).toHaveCSS("border-bottom-width", "2px"); +}); + +test("test results retain a running label after the first test starts", async ({ workbench: page }) => { + const name = "TestCheckoutTotals"; + await stubRun( + page, + [{ kind: "stdout", text: JSON.stringify({ Package: "example.com/checkout", Action: "run", Test: name }) + "\n" }], + null, + { + id: "go:checkout-tests", + name: "Checkout tests", + kind: "go", + command: "go", + args: ["test", "-json"], + isTest: true, + }, + ); + await page.keyboard.press("Control+r"); + const run = page.getByRole("region", { name: "Run", exact: true }); + await expect(run.getByRole("treeitem", { name: new RegExp(name) })).toBeVisible(); + const summary = run.getByRole("status").filter({ hasText: "Running…" }); + await expect(summary).toBeVisible(); + await expect(summary).toHaveCSS("border-bottom-width", "2px"); +}); + test("test results group failure navigation and let users hide row durations", async ({ workbench: page }) => { await page.setViewportSize({ width: 540, height: 740 }); const first = "TestCheckoutTotalsWithTaxRoundingAndPendingRefunds"; diff --git a/e2e/runConfigDialogScroll.spec.ts b/e2e/runConfigDialogScroll.spec.ts index 7b15417b4e..20aabe883b 100644 --- a/e2e/runConfigDialogScroll.spec.ts +++ b/e2e/runConfigDialogScroll.spec.ts @@ -2,7 +2,7 @@ import type { Locator, Page } from "@playwright/test"; import { expect, test } from "./fixtures"; for (const height of [990, 700, 560]) { - test(`run configurations dialog keeps its toolbar and scrolls only inside the panes at ${height}px`, async ({ + test(`run configurations dialog keeps its toolbar and name visible while scrolling at ${height}px`, async ({ workbench: page, }) => { await page.setViewportSize({ width: 900, height }); @@ -62,9 +62,13 @@ async function resize(page: Page, dialog: Locator, dy: number) { async function checkScrolling(page: Page, dialog: Locator) { const body = dialog.locator("[data-dialog-body]"); const list = dialog.getByRole("tree", { name: "Run configurations", exact: true }); - const form = dialog.locator('[class*="_editForm_"]'); + const form = dialog.locator('[class*="_formSettings_"]'); + const nameField = dialog.getByRole("textbox", { name: "Name", exact: true }); await list.evaluate((el) => (el.scrollTop = 0)); await form.evaluate((el) => (el.scrollTop = 0)); + // Measure once the dialog's opening animation has settled. + await dialog.evaluate((el) => Promise.all(el.getAnimations().map((animation) => animation.finished))); + const nameTop = (await nameField.boundingBox())!.y; await list.hover(); await page.mouse.wheel(0, 200); await expect.poll(() => list.evaluate((el) => el.scrollTop)).toBeGreaterThan(0); @@ -74,6 +78,8 @@ async function checkScrolling(page: Page, dialog: Locator) { await page.mouse.wheel(0, 200); await expect.poll(() => form.evaluate((el) => el.scrollTop)).toBeGreaterThan(0); expect(await list.evaluate((el) => el.scrollTop)).toBe(listTop); + expect((await nameField.boundingBox())!.y).toBeCloseTo(nameTop, 0); + await expect(dialog.getByRole("checkbox", { name: /Store as project file/ })).toBeInViewport({ ratio: 1 }); const overflow = await body.evaluate((el) => ({ scroll: el.scrollHeight, client: el.clientHeight, diff --git a/e2e/runConfigLayout.spec.ts b/e2e/runConfigLayout.spec.ts index fe6af50c8d..9afb50c807 100644 --- a/e2e/runConfigLayout.spec.ts +++ b/e2e/runConfigLayout.spec.ts @@ -112,7 +112,7 @@ test("resizing the configuration dialog grows its panes and keeps the footer vis await expect(dialog.getByRole("tree", { name: "Run configurations", exact: true })).toBeVisible(); await expect.poll(async () => (await content.boundingBox())!.height).toBeLessThan(initial); await expect - .poll(() => dialog.locator("[class*='editForm_']").evaluate((el) => el.scrollHeight - el.clientHeight)) + .poll(() => dialog.locator("[class*='_formSettings_']").evaluate((el) => el.scrollHeight - el.clientHeight)) .toBeGreaterThan(0); }); @@ -144,7 +144,7 @@ test("Java, npm and Python forms fit narrow and zoomed content panes", async ({ for (const width of [1024, 640, 520]) { await page.setViewportSize({ width, height: 820 }); await expect - .poll(() => dialog.locator("[class*='editForm_']").evaluate((el) => el.scrollWidth - el.clientWidth), { + .poll(() => dialog.locator("[class*='_formSettings_']").evaluate((el) => el.scrollWidth - el.clientWidth), { message: `${kind}, ${width}px, ${zoom * 100}%`, }) .toBeLessThanOrEqual(1); @@ -204,7 +204,7 @@ for (const locale of ["en", "zh"]) { ) .toMatchObject({ overflow: expect.any(Number), footerFits: true, footerVisible: true }); await expect - .poll(() => dialog.locator("[class*='editForm_']").evaluate((el) => el.scrollWidth - el.clientWidth)) + .poll(() => dialog.locator("[class*='_formSettings_']").evaluate((el) => el.scrollWidth - el.clientWidth)) .toBeLessThanOrEqual(1); const tasks = dialog.getByRole("list"); await tasks.scrollIntoViewIfNeeded(); diff --git a/e2e/searchEverywhereLayout.spec.ts b/e2e/searchEverywhereLayout.spec.ts index 3f33ae714b..abc760a18c 100644 --- a/e2e/searchEverywhereLayout.spec.ts +++ b/e2e/searchEverywhereLayout.spec.ts @@ -1,6 +1,60 @@ import { doubleShift, expect, stubDesktop, test } from "./fixtures"; import type { Page } from "@playwright/test"; +test("action names stay readable beside shortcuts and categories", async ({ workbench: page }) => { + const titles = ["Reconcile warehouse totals", "Reconcile settlement exports"]; + const shortcuts = await page.evaluate(async (titles) => { + const actionsModule = "/src/platform/actions.ts"; + const keymapModule = "/src/platform/keymap.ts"; + const { registerActions, executeAction } = await import(/* @vite-ignore */ actionsModule); + const platformModule = "/src/platform/platformInfo.ts"; + const { registerExtensionBindings, shortcutLabel } = await import(/* @vite-ignore */ keymapModule); + const { usePlatform } = await import(/* @vite-ignore */ platformModule); + usePlatform.setState({ os: "windows" }); + const ids = ["review.reconcileWarehouse", "review.reconcileSettlement"]; + const bindings = ["Ctrl+K Ctrl+R", "Ctrl+Alt+Shift+PageDown Ctrl+Alt+Shift+PageUp"]; + registerActions( + titles.map((title, index) => ({ + id: ids[index]!, + title, + category: "Warehouse reconciliation and settlement reports", + icon: "check", + run: () => document.body.setAttribute("data-review-action", title), + })), + ); + ids.forEach((id, index) => registerExtensionBindings(id, [bindings[index]!])); + await executeAction("navigate.findAction"); + return ids.map((id) => shortcutLabel(id) as string); + }, titles); + const dialog = page.locator('[role="dialog"]:has(#se-query)'); + await dialog.getByRole("combobox", { name: "Search query" }).fill("Reconcile"); + + for (const width of [400, 1120]) { + await page.setViewportSize({ width, height: 630 }); + for (const [index, title] of titles.entries()) { + const row = dialog.getByRole("option").filter({ hasText: title }); + const keys = row.getByText(shortcuts[index]!, { exact: true }); + await expect(keys).toBeAttached(); + const geometry = await keys.evaluate((el) => { + const name = el.previousElementSibling!.getBoundingClientRect(); + const main = el.parentElement!.getBoundingClientRect(); + const key = el.getBoundingClientRect(); + return { name: name.width, inside: key.left >= name.right && key.right <= main.right + 1 }; + }); + expect(geometry.name).toBeGreaterThanOrEqual(80); + expect(geometry.inside).toBe(true); + await expect(keys).toHaveCSS("font-size", "12px"); + await expect(keys).toHaveCSS("font-weight", "600"); + await expect(keys).toHaveAttribute("title", shortcuts[index]!); + if (index === 0) expect(await keys.evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true); + } + } + + await dialog.getByRole("option").filter({ hasText: titles[1]! }).click(); + await expect(dialog).toBeHidden(); + await expect(page.locator("body")).toHaveAttribute("data-review-action", titles[1]!); +}); + async function searchFiles(page: Page) { await stubDesktop(page); await page.evaluate(() => { diff --git a/e2e/searchPopupsNarrow.spec.ts b/e2e/searchPopupsNarrow.spec.ts index 3ca17f20c5..e869ecbad2 100644 --- a/e2e/searchPopupsNarrow.spec.ts +++ b/e2e/searchPopupsNarrow.spec.ts @@ -3,7 +3,9 @@ * header on screen: titles stay on one line and every header control lies inside the popup. */ import type { Page } from "@playwright/test"; -import { expect, stubDesktop, test } from "./fixtures"; +import { expect, openFromTree, stubDesktop, test } from "./fixtures"; + +const LONG_RESULT_PATH = "config/RegionalOrderReconciliationEndpointsForSandboxEnvironments.txt"; async function run(page: Page, id: string) { await page.evaluate(async (id) => { @@ -15,15 +17,16 @@ async function run(page: Page, id: string) { async function stubFindMatches(page: Page) { await stubDesktop(page); - await page.evaluate(() => { + await page.evaluate((longPath) => { window.__ipc.handlers.search_validate = () => null; window.__ipc.handlers.search_start = (args) => { const send = (event: unknown) => window.__ipc.send(args.onEvent, event); const text = "base=http://localhost:8080"; setTimeout(() => { for (let i = 0; i < 12; i++) { - const relPath = `config/endpoint-${i}.txt`; - const matches = [{ line: 0, text, ranges: [[5, text.length]], textOffset: 0 }]; + const relPath = i === 0 ? longPath : `config/endpoint-${i}.txt`; + const lines = i === 0 ? [12344, 12345] : [0]; + const matches = lines.map((line) => ({ line, text, ranges: [[5, text.length]], textOffset: 0 })); send({ type: "file", file: { path: `/dev/acme-api/${relPath}`, relPath, matches }, @@ -31,12 +34,12 @@ async function stubFindMatches(page: Page) { } send({ type: "done", - summary: { files: 12, matches: 12, limitHit: false, cancelled: false, elapsedMs: 4 }, + summary: { files: 12, matches: 13, limitHit: false, cancelled: false, elapsedMs: 4 }, }); }, 20); return null; }; - }); + }, LONG_RESULT_PATH); } async function expectControlsFit(page: Page) { @@ -74,7 +77,8 @@ test.describe("search popups at the minimum window width", () => { await expect(page.getByRole("dialog").locator("header [aria-live]")).toContainText(/match/); const dialog = page.getByRole("dialog"); const title = dialog.getByText(id === "find.inPath" ? "Find in Files" : "Replace in Files", { exact: true }); - const count = dialog.getByText("12 matches in 12 files", { exact: true }); + const count = dialog.getByText("13 matches in 12 files", { exact: true }); + const line = dialog.getByText("12345", { exact: true }); for (const [width, height] of [ [400, 500], [600, 700], @@ -87,6 +91,14 @@ test.describe("search popups at the minimum window width", () => { expect( await text.evaluate((el) => el.getClientRects().length === 1 && el.scrollWidth <= el.clientWidth), ).toBe(true); + await expect(line).toBeVisible(); + expect( + await line.evaluate( + (el) => el.getBoundingClientRect().right <= el.parentElement!.getBoundingClientRect().right + 0.5, + ), + "the line number fits even when the long filename is elided", + ).toBe(true); + await expect(line.locator("..").getByTitle(LONG_RESULT_PATH)).toBeVisible(); for (const name of ["Search Context", "Pin Window"]) await dialog.getByRole("button", { name, exact: true }).click({ trial: true }); } @@ -106,6 +118,49 @@ test.describe("search popups at the minimum window width", () => { await dialog.getByRole("button", { name: /Browse/ }).click({ trial: true }); }); + test("Replace in Files keeps its footer actions together as the window narrows", async ({ workbench: page }) => { + await page.setViewportSize({ width: 1120, height: 750 }); + await openFromTree(page, "settings.gradle.kts"); + await stubFindMatches(page); + await run(page, "find.replaceInPath"); + const dialog = page.getByRole("dialog", { name: "Replace in Files" }); + const search = dialog.getByRole("textbox", { name: "Text to find" }); + await search.fill("http://localhost:8080"); + await expect(dialog.locator("header [aria-live]")).toContainText("13 matches in 12 files"); + await search.press("Shift+ArrowDown"); + await search.press("Shift+ArrowDown"); + + const footer = dialog.locator("footer"); + const open = footer.getByRole("button", { name: "Open in Find Window", exact: true }); + const shortcut = footer.getByText(/^(Ctrl\+Enter|⌘↵)$/); + const replaceAll = footer.getByRole("button", { name: "Replace All", exact: true }); + const replaceSelected = footer.getByRole("button", { name: "Replace 3 Occurrences", exact: true }); + await expect(replaceSelected).toBeEnabled(); + for (const [width, height] of [ + [400, 500], + [1120, 750], + ] as const) { + await page.setViewportSize({ width, height }); + const [key, find, all, selected] = await Promise.all([ + shortcut.boundingBox(), + open.boundingBox(), + replaceAll.boundingBox(), + replaceSelected.boundingBox(), + ]); + if (!key || !find || !all || !selected) throw new Error("Expected all footer actions to be visible"); + expect(Math.abs(key.y + key.height / 2 - find.y - find.height / 2)).toBeLessThanOrEqual(1); + expect(Math.abs(all.y - selected.y)).toBeLessThanOrEqual(1); + await expectControlsFit(page); + await expect(footer).toBeInViewport({ ratio: 1 }); + await expect(shortcut).toHaveCSS("font-size", "12px"); + await open.click({ trial: true }); + await replaceSelected.click({ trial: true }); + } + await search.press("Meta+Enter"); + await expect(dialog).toBeHidden(); + await expect(page.getByRole("region", { name: "Find", exact: true })).toContainText("http://localhost:8080"); + }); + for (const id of [ "navigate.searchEverywhere", "navigate.searchText", diff --git a/e2e/settingsHeaderLayout.spec.ts b/e2e/settingsHeaderLayout.spec.ts index 49d678cb6c..c0e82bfa73 100644 --- a/e2e/settingsHeaderLayout.spec.ts +++ b/e2e/settingsHeaderLayout.spec.ts @@ -1,5 +1,38 @@ import { expect, test } from "./fixtures"; +test("keeps the current settings page name readable when the path is wider than the pane", async ({ + workbench: page, +}) => { + await page.keyboard.press("Meta+,"); + const settings = page.getByRole("dialog", { name: "Settings", exact: true }); + const search = settings.getByRole("textbox", { name: "Search settings" }); + await search.fill("Maven"); + const path = settings.getByLabel("Breadcrumb", { exact: true }); + const parent = path.getByText("Build, Execution, Deployment", { exact: true }); + const current = path.getByText("Maven", { exact: true }); + await expect(current).toBeVisible(); + await search.clear(); + + for (const width of [400, 560, 1120]) { + await page.setViewportSize({ width, height: 720 }); + await expect + .poll(() => + current.evaluate((label) => { + const box = label.getBoundingClientRect(); + const trail = label.closest("[aria-label=Breadcrumb]")!.getBoundingClientRect(); + return label.clientWidth >= label.scrollWidth && box.width > 0 && box.right <= trail.right + 1; + }), + ) + .toBe(true); + } + await expect(parent).toBeInViewport({ ratio: 1 }); + expect(await parent.evaluate((label) => label.scrollWidth <= label.clientWidth)).toBe(true); + await settings.getByRole("button", { name: "Back", exact: true }).click(); + await expect(current).toBeHidden(); + await settings.getByRole("button", { name: "Forward", exact: true }).click(); + await expect(current).toBeVisible(); +}); + test("dirty settings keep scope labels and navigation inside the page header", async ({ workbench: page }) => { await page.keyboard.press("Meta+,"); await expect(page.getByRole("dialog", { name: "Settings", exact: true })).toBeVisible(); diff --git a/e2e/usagesPopupLayout.spec.ts b/e2e/usagesPopupLayout.spec.ts new file mode 100644 index 0000000000..8227878489 --- /dev/null +++ b/e2e/usagesPopupLayout.spec.ts @@ -0,0 +1,45 @@ +import { expect, test } from "./fixtures"; + +test("Show Usages distinguishes same-named files without losing the line or snippet", async ({ workbench: page }) => { + await page.setViewportSize({ width: 480, height: 620 }); + await page.evaluate(async () => { + const usages = "/src/features/code-insight/usages.ts"; + const { useUsagesPopup } = await import(/* @vite-ignore */ usages); + const symbol = "submitOrder"; + useUsagesPopup.setState({ + open: true, + anchor: { x: 30, y: 90 }, + symbol, + groups: ( + [ + ["/dev/acme-api/packages/billing/src/Routes.ts", "return submitOrder(invoice);"], + ["/dev/acme-api/packages/checkout/src/Routes.ts", "return submitOrder(cart);"], + ["/dev/acme-api/src/Worker.ts", "await submitOrder(job);"], + ] as const + ).map(([path, text]) => { + const col = text.indexOf(symbol); + return { path, usages: [{ path, line: 6, col, endCol: col + symbol.length, text }] }; + }), + }); + }); + + const popup = page.getByRole("dialog", { name: "Usages", exact: true }); + const rows = popup.getByRole("option"); + const billing = rows.filter({ hasText: "invoice" }); + const checkout = rows.filter({ hasText: "cart" }); + await expect(rows).toHaveCount(3); + for (const [row, directory] of [ + [billing, "billing"], + [checkout, "checkout"], + ] as const) { + await expect(row.getByText("Routes.ts", { exact: true })).toBeVisible(); + const caption = row.getByText(directory, { exact: true }); + await expect(caption).toBeVisible(); + expect(await caption.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); + await expect(row.getByText("7", { exact: true })).toBeVisible(); + await expect(row.locator("mark")).toHaveText("submitOrder"); + } + + await expect(checkout.getByTitle("/dev/acme-api/packages/checkout/src/Routes.ts", { exact: true })).toBeVisible(); + await expect(rows.filter({ hasText: "Worker.ts" }).getByText("src", { exact: true })).toHaveCount(0); +}); diff --git a/fixtures/README.md b/fixtures/README.md index b15ecc6a4d..afe2b0c32e 100644 --- a/fixtures/README.md +++ b/fixtures/README.md @@ -9,6 +9,9 @@ something to show. | ---------------- | --------------------------------------------------------------- | ----------------------------------- | -------------------- | ------------------------------------- | -------------------------------------------------------- | | `rust-app/` | cargo | `cargo run` | `cargo test` | `cargo test --features failing-tests` | unused variable in `src/parser.rs` | | `ts-app/` | Node 22+, pnpm/npm | `pnpm start` | `pnpm test` (vitest) | `OPENIDEA_FAIL=1 pnpm test` | unused function in `src/index.ts` | +| `playwright-app/` | Node 22+, npm (Playwright Test, no browser needed) | — | `npm test` | `OPENIDEA_FAIL=1 npm test` | unused function in `src/checkout.ts` | +| `node-test-app/` | Node 22+, npm (no dependencies) | — | `npm test` (node:test) | `OPENIDEA_FAIL=1 npm test` | unused constant in `src/inventory.js` | +| `mocha-app/` | Node 22+, npm | — | `npm test` (Mocha) | `OPENIDEA_FAIL=1 npm test` | unused constant in `src/pricing.js` | | `python-app/` | Python 3.10+, pytest | `python -m tasks.cli` (from `src/`) | `pytest` | `OPENIDEA_FAIL=1 pytest` | unused imports in `models.py` | | `go-app/` | Go 1.22+ | `go run ./cmd/server` | `go test ./...` | `OPENIDEA_FAIL=1 go test ./...` | unused `fmt.Sprintf` result in `internal/store/store.go` | | `kotlin-gradle/` | JDK 21, Gradle 8 (no wrapper) | `gradle run` | `gradle test` | `gradle test -PopenideaFail` | unused variable in `App.kt` | @@ -16,7 +19,10 @@ something to show. | `c-app/` | gcc / g++ 12+, make, GDB 14+ | `make all` | — | — | — | | `php-app/` | PHP 8.5, Composer | `composer quote` | `vendor/bin/pest` | `OPENIDEA_FAIL=1 vendor/bin/pest` | unused variable in `ThresholdCustoms.php` | | `django-app/` | Python 3.10+, Django 5.2+ | `python manage.py runserver` | `python manage.py test` | `OPENIDEA_FAIL=1 python manage.py test` | unused import in `shop/views.py` | +| `tailwind-app/` | Node 22+, pnpm/npm, Tailwind CSS 4, React | `pnpm dev` | — | — | `flex` conflicting with `block` in `src/App.tsx` | | `zig-app/` | Zig 0.17 | `zig build run` | `zig build test` | — | — | +| `biome-app/` | Node 22+, `@biomejs/biome` (`npm install`) | `npm start` | — | — | `let` never reassigned, `==` and a duplicate CSS `color` (Biome) | +| `stylelint-app/` | Node 22+, `stylelint` (`npm install`) | — | — | — | long hex colour, unknown property, empty block, duplicate selector (Stylelint) | | `polyglot/` | Go, TS, Python, C, shell, SQL, TOML/YAML/JSON, proto, Terraform | `make` | `make test` | — | unused variable in `native/hash.c` | The fixtures are standalone: `rust-app` declares its own `[workspace]` and @@ -39,7 +45,7 @@ git init -q && git add -A && git commit -qm "initial" # for the VCS checks ``` Then open the folder with **File › Open…** (`⌘⇧⌥O`) or from the Welcome screen. -For `ts-app` / `polyglot/web` run `pnpm install` first; for `python-app` create a +For `ts-app` / `playwright-app` / `mocha-app` / `polyglot/web` run `pnpm install` first (`npm install` for `biome-app` and `stylelint-app`); for `python-app` create a venv (`python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'`); for `php-app` run `composer install` (debugging it needs Xdebug in the PHP on `PATH`). diff --git a/fixtures/biome-app/biome.json b/fixtures/biome-app/biome.json new file mode 100644 index 0000000000..9b1e4aa568 --- /dev/null +++ b/fixtures/biome-app/biome.json @@ -0,0 +1,27 @@ +{ + "$schema": "https://biomejs.dev/schemas/2.6.8/schema.json", + "files": { + "includes": ["**", "!node_modules"] + }, + "formatter": { + "enabled": true, + "indentStyle": "space", + "indentWidth": 2, + "lineWidth": 100 + }, + "javascript": { + "formatter": { + "quoteStyle": "single" + } + }, + "linter": { + "enabled": true, + "rules": { + "preset": "recommended", + "style": { + "useConst": "error", + "useTemplate": "warn" + } + } + } +} diff --git a/fixtures/biome-app/package.json b/fixtures/biome-app/package.json new file mode 100644 index 0000000000..265711ee13 --- /dev/null +++ b/fixtures/biome-app/package.json @@ -0,0 +1,16 @@ +{ + "name": "openidea-fixture-biome", + "version": "0.1.0", + "private": true, + "description": "OpenIDEA QA fixture: Biome lint diagnostics, fixes and formatting", + "type": "module", + "scripts": { + "start": "node --experimental-strip-types src/index.ts", + "lint": "biome lint", + "format": "biome format --write", + "check": "biome check" + }, + "devDependencies": { + "@biomejs/biome": "2.6.8" + } +} diff --git a/fixtures/biome-app/src/cart.ts b/fixtures/biome-app/src/cart.ts new file mode 100644 index 0000000000..9468889724 --- /dev/null +++ b/fixtures/biome-app/src/cart.ts @@ -0,0 +1,21 @@ +export interface Item { + name: string + price: number + quantity: number +} + +export function total(items: Item[]): number { + let sum = 0 + for (const item of items) sum += item.price * item.quantity + return sum +} + +// Intentional Biome problems: `let` never reassigned (useConst, safe fix), +// string concatenation (useTemplate) and `==` (noDoubleEquals). +export function describe(items: Item[]): string { + let label = "Cart: " + items.length + " items" + if (items.length == 0) { + return "Cart is empty" + } + return label +} diff --git a/fixtures/biome-app/src/data.json b/fixtures/biome-app/src/data.json new file mode 100644 index 0000000000..16c995841f --- /dev/null +++ b/fixtures/biome-app/src/data.json @@ -0,0 +1,2 @@ +{ "currency": "EUR", + "discounts": [ 5, 10,15 ] } diff --git a/fixtures/biome-app/src/index.ts b/fixtures/biome-app/src/index.ts new file mode 100644 index 0000000000..d802a35c5d --- /dev/null +++ b/fixtures/biome-app/src/index.ts @@ -0,0 +1,9 @@ +import { describe, total, type Item } from "./cart.ts" + +const items: Item[] = [ + { name: "Notebook", price: 4.5, quantity: 2 }, + { name: "Pen", price: 1.25, quantity: 4 }, +] + +// Set a breakpoint here +console.log(describe(items), "-", total(items).toFixed(2)) diff --git a/fixtures/biome-app/src/theme.css b/fixtures/biome-app/src/theme.css new file mode 100644 index 0000000000..03478b772e --- /dev/null +++ b/fixtures/biome-app/src/theme.css @@ -0,0 +1,6 @@ +/* Intentional Biome problem: `color` is declared twice (noDuplicateProperties). */ +.cart { + color: #333; + padding:4px 8px; + color: #444; +} diff --git a/fixtures/mocha-app/.gitignore b/fixtures/mocha-app/.gitignore new file mode 100644 index 0000000000..3c3629e647 --- /dev/null +++ b/fixtures/mocha-app/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/fixtures/mocha-app/package.json b/fixtures/mocha-app/package.json new file mode 100644 index 0000000000..bf94a3fca6 --- /dev/null +++ b/fixtures/mocha-app/package.json @@ -0,0 +1,13 @@ +{ + "name": "openidea-fixture-pricing", + "version": "0.1.0", + "private": true, + "description": "OpenIDEA QA fixture: Mocha specs for a small pricing module", + "type": "module", + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "mocha": "^10.8.0" + } +} diff --git a/fixtures/mocha-app/src/pricing.js b/fixtures/mocha-app/src/pricing.js new file mode 100644 index 0000000000..c2b12cd262 --- /dev/null +++ b/fixtures/mocha-app/src/pricing.js @@ -0,0 +1,14 @@ +export function withTax(net, rate) { + if (rate < 0) throw new RangeError("tax rate must not be negative"); + return Math.round(net * (1 + rate) * 100) / 100; +} + +export function bulkDiscount(quantity) { + // TODO: read the tiers from the catalog instead of hard-coding them + if (quantity >= 100) return 0.15; + if (quantity >= 10) return 0.05; + return 0; +} + +// An intentional warning: never used. +const CURRENCY = "EUR"; diff --git a/fixtures/mocha-app/test/pricing.spec.js b/fixtures/mocha-app/test/pricing.spec.js new file mode 100644 index 0000000000..6ed7a7ea2a --- /dev/null +++ b/fixtures/mocha-app/test/pricing.spec.js @@ -0,0 +1,29 @@ +import assert from "node:assert/strict"; +import { bulkDiscount, withTax } from "../src/pricing.js"; + +describe("pricing", function () { + describe("withTax", function () { + it("adds the rate", function () { + assert.equal(withTax(100, 0.2), 120); + }); + + it("rejects a negative rate", function () { + assert.throws(() => withTax(100, -0.1), RangeError); + }); + }); + + describe("bulkDiscount", function () { + it("has no discount for a few items", function () { + assert.equal(bulkDiscount(3), 0); + }); + + it("discounts large orders", function () { + assert.equal(bulkDiscount(250), 0.15); + }); + }); + + it("intentionally fails (set OPENIDEA_FAIL=1)", function () { + if (!process.env.OPENIDEA_FAIL) this.skip(); + assert.equal(withTax(10, 0.1), 11.5); + }); +}); diff --git a/fixtures/node-test-app/.gitignore b/fixtures/node-test-app/.gitignore new file mode 100644 index 0000000000..3c3629e647 --- /dev/null +++ b/fixtures/node-test-app/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/fixtures/node-test-app/package.json b/fixtures/node-test-app/package.json new file mode 100644 index 0000000000..ccc488690a --- /dev/null +++ b/fixtures/node-test-app/package.json @@ -0,0 +1,10 @@ +{ + "name": "openidea-fixture-inventory", + "version": "0.1.0", + "private": true, + "description": "OpenIDEA QA fixture: node:test tests for a small inventory module (no dependencies)", + "type": "module", + "scripts": { + "test": "node --test" + } +} diff --git a/fixtures/node-test-app/src/inventory.js b/fixtures/node-test-app/src/inventory.js new file mode 100644 index 0000000000..a251a2f311 --- /dev/null +++ b/fixtures/node-test-app/src/inventory.js @@ -0,0 +1,23 @@ +export class Inventory { + #stock = new Map(); + + receive(sku, quantity) { + if (!Number.isInteger(quantity) || quantity <= 0) throw new RangeError("quantity must be a positive integer"); + this.#stock.set(sku, this.count(sku) + quantity); + return this; + } + + ship(sku, quantity) { + // TODO: reserve stock for open orders before shipping + if (quantity > this.count(sku)) throw new Error(`not enough ${sku} in stock`); + this.#stock.set(sku, this.count(sku) - quantity); + return this; + } + + count(sku) { + return this.#stock.get(sku) ?? 0; + } +} + +// An intentional warning: never used. +const RESTOCK_LEVEL = 5; diff --git a/fixtures/node-test-app/test/inventory.test.js b/fixtures/node-test-app/test/inventory.test.js new file mode 100644 index 0000000000..8b5b3b65f6 --- /dev/null +++ b/fixtures/node-test-app/test/inventory.test.js @@ -0,0 +1,27 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { Inventory } from "../src/inventory.js"; + +describe("inventory", () => { + it("counts received stock", () => { + assert.equal(new Inventory().receive("mug", 3).receive("mug", 2).count("mug"), 5); + }); + + describe("shipping", () => { + it("takes items out of stock", () => { + assert.equal(new Inventory().receive("mug", 3).ship("mug", 2).count("mug"), 1); + }); + + it("refuses more than is in stock", () => { + assert.throws(() => new Inventory().ship("mug", 1), /not enough mug/); + }); + }); + + it("intentionally fails (set OPENIDEA_FAIL=1)", { skip: !process.env.OPENIDEA_FAIL }, () => { + assert.equal(new Inventory().receive("mug", 1).count("mug"), 2); + }); +}); + +it("rejects non-positive quantities", () => { + assert.throws(() => new Inventory().receive("mug", 0), RangeError); +}); diff --git a/fixtures/playwright-app/.gitignore b/fixtures/playwright-app/.gitignore new file mode 100644 index 0000000000..4569578274 --- /dev/null +++ b/fixtures/playwright-app/.gitignore @@ -0,0 +1,3 @@ +node_modules +test-results +playwright-report diff --git a/fixtures/playwright-app/package.json b/fixtures/playwright-app/package.json new file mode 100644 index 0000000000..35d1d4a699 --- /dev/null +++ b/fixtures/playwright-app/package.json @@ -0,0 +1,15 @@ +{ + "name": "openidea-fixture-checkout", + "version": "0.1.0", + "private": true, + "description": "OpenIDEA QA fixture: Playwright Test specs for a checkout module (no browser needed)", + "type": "module", + "scripts": { + "test": "playwright test", + "lint": "tsc -p . --noEmit" + }, + "devDependencies": { + "@playwright/test": "^1.56.0", + "typescript": "^5.6.0" + } +} diff --git a/fixtures/playwright-app/playwright.config.ts b/fixtures/playwright-app/playwright.config.ts new file mode 100644 index 0000000000..99313f18cd --- /dev/null +++ b/fixtures/playwright-app/playwright.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from "@playwright/test"; + +// The IDE replaces the reporter with `list` for its test tree; `dot` is what a terminal shows. +export default defineConfig({ + testDir: "tests", + reporter: "dot", +}); diff --git a/fixtures/playwright-app/src/checkout.ts b/fixtures/playwright-app/src/checkout.ts new file mode 100644 index 0000000000..a213a6593e --- /dev/null +++ b/fixtures/playwright-app/src/checkout.ts @@ -0,0 +1,27 @@ +export interface Line { + sku: string; + price: number; + quantity: number; +} + +const FREE_SHIPPING_FROM = 50; + +export function subtotal(lines: Line[]): number { + return lines.reduce((sum, l) => sum + l.price * l.quantity, 0); +} + +export function shipping(lines: Line[]): number { + // TODO: shipping by weight instead of a flat rate + return subtotal(lines) >= FREE_SHIPPING_FROM ? 0 : 4.99; +} + +export function applyCoupon(total: number, code: string): number { + if (code === "HALF") return Math.round(total * 50) / 100; + if (code === "TENOFF") return Math.max(0, total - 10); + throw new Error(`unknown coupon: ${code}`); +} + +// An intentional warning: never used. +function roundUp(value: number): number { + return Math.ceil(value); +} diff --git a/fixtures/playwright-app/tests/checkout.spec.ts b/fixtures/playwright-app/tests/checkout.spec.ts new file mode 100644 index 0000000000..315ce0703c --- /dev/null +++ b/fixtures/playwright-app/tests/checkout.spec.ts @@ -0,0 +1,36 @@ +import { expect, test } from "@playwright/test"; +import { applyCoupon, shipping, subtotal, type Line } from "../src/checkout.ts"; + +const mug: Line = { sku: "mug", price: 12, quantity: 2 }; +const lamp: Line = { sku: "lamp", price: 40, quantity: 1 }; + +test.describe("checkout", () => { + test("adds up the lines", () => { + expect(subtotal([mug, lamp])).toBe(64); + }); + + test.describe("shipping", () => { + test("is free from 50", () => { + expect(shipping([mug, lamp])).toBe(0); + }); + + test("is a flat rate below 50", () => { + expect(shipping([mug])).toBe(4.99); + }); + }); + + test("intentionally fails (set OPENIDEA_FAIL=1)", () => { + test.skip(!process.env.OPENIDEA_FAIL, "set OPENIDEA_FAIL=1"); + expect(shipping([lamp])).toBe(0); + }); +}); + +test.describe("coupons", () => { + test("halves the total", () => { + expect(applyCoupon(64, "HALF")).toBe(32); + }); + + test("rejects unknown codes", () => { + expect(() => applyCoupon(64, "NOPE")).toThrow("unknown coupon"); + }); +}); diff --git a/fixtures/playwright-app/tsconfig.json b/fixtures/playwright-app/tsconfig.json new file mode 100644 index 0000000000..9e626e1e5f --- /dev/null +++ b/fixtures/playwright-app/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "noUnusedLocals": true, + "allowImportingTsExtensions": true, + "noEmit": true, + "skipLibCheck": true + }, + "include": ["src", "tests", "playwright.config.ts"] +} diff --git a/fixtures/stylelint-app/package.json b/fixtures/stylelint-app/package.json new file mode 100644 index 0000000000..517b7c2348 --- /dev/null +++ b/fixtures/stylelint-app/package.json @@ -0,0 +1,17 @@ +{ + "name": "openidea-fixture-stylelint", + "version": "0.1.0", + "private": true, + "description": "OpenIDEA QA fixture: Stylelint diagnostics and fixes for CSS, SCSS and Less", + "type": "module", + "scripts": { + "lint": "stylelint \"src/**/*.{css,scss,less}\"", + "fix": "stylelint \"src/**/*.{css,scss,less}\" --fix" + }, + "devDependencies": { + "postcss-less": "6.0.0", + "stylelint": "18.1.0", + "stylelint-config-standard": "41.1.0", + "stylelint-config-standard-scss": "18.0.0" + } +} diff --git a/fixtures/stylelint-app/src/app.css b/fixtures/stylelint-app/src/app.css new file mode 100644 index 0000000000..de7e67f961 --- /dev/null +++ b/fixtures/stylelint-app/src/app.css @@ -0,0 +1,7 @@ +/* Intentional Stylelint problems: a long hex colour (color-hex-length, fixable) + and a misspelt property (property-no-unknown). */ +.card { + color: #ffffff; + colour: red; + padding: 4px 8px; +} diff --git a/fixtures/stylelint-app/src/layout.less b/fixtures/stylelint-app/src/layout.less new file mode 100644 index 0000000000..57b614cfcb --- /dev/null +++ b/fixtures/stylelint-app/src/layout.less @@ -0,0 +1,10 @@ +@gutter: 16px; + +// Intentional Stylelint problem: the same selector twice (no-duplicate-selectors). +.layout { + margin: @gutter; +} + +.layout { + padding: @gutter; +} diff --git a/fixtures/stylelint-app/src/theme.scss b/fixtures/stylelint-app/src/theme.scss new file mode 100644 index 0000000000..675ce4a6d7 --- /dev/null +++ b/fixtures/stylelint-app/src/theme.scss @@ -0,0 +1,9 @@ +$accent: #336699; + +// Intentional Stylelint problem: an empty block (block-no-empty). +.button { + color: $accent; + + &:hover { + } +} diff --git a/fixtures/stylelint-app/stylelint.config.mjs b/fixtures/stylelint-app/stylelint.config.mjs new file mode 100644 index 0000000000..c776b569f8 --- /dev/null +++ b/fixtures/stylelint-app/stylelint.config.mjs @@ -0,0 +1,8 @@ +/** @type {import("stylelint").Config} */ +export default { + extends: ["stylelint-config-standard"], + overrides: [ + { files: ["**/*.scss"], extends: ["stylelint-config-standard-scss"] }, + { files: ["**/*.less"], customSyntax: "postcss-less" }, + ], +}; diff --git a/fixtures/tailwind-app/.gitignore b/fixtures/tailwind-app/.gitignore new file mode 100644 index 0000000000..f06235c460 --- /dev/null +++ b/fixtures/tailwind-app/.gitignore @@ -0,0 +1,2 @@ +node_modules +dist diff --git a/fixtures/tailwind-app/index.html b/fixtures/tailwind-app/index.html new file mode 100644 index 0000000000..111c5054d6 --- /dev/null +++ b/fixtures/tailwind-app/index.html @@ -0,0 +1,13 @@ + + + + + + Tailwind fixture + + + +
+ + + diff --git a/fixtures/tailwind-app/package.json b/fixtures/tailwind-app/package.json new file mode 100644 index 0000000000..c25b26109b --- /dev/null +++ b/fixtures/tailwind-app/package.json @@ -0,0 +1,24 @@ +{ + "name": "openidea-fixture-tailwind", + "version": "0.1.0", + "private": true, + "description": "OpenIDEA QA fixture: a Tailwind CSS 4 page with React", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -p . && vite build" + }, + "dependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@tailwindcss/vite": "^4.1.0", + "@types/react": "^19.0.0", + "@types/react-dom": "^19.0.0", + "@vitejs/plugin-react": "^5.0.0", + "tailwindcss": "^4.1.0", + "typescript": "^5.6.0", + "vite": "^7.0.0" + } +} diff --git a/fixtures/tailwind-app/src/App.tsx b/fixtures/tailwind-app/src/App.tsx new file mode 100644 index 0000000000..e79262b6d1 --- /dev/null +++ b/fixtures/tailwind-app/src/App.tsx @@ -0,0 +1,15 @@ +import { useState } from "react"; + +export function App() { + const [count, setCount] = useState(0); + return ( +
+

Tailwind CSS fixture

+ {/* Intentional warning: `flex` and `block` both set `display`. */} +

Clicked {count} times.

+ +
+ ); +} diff --git a/fixtures/tailwind-app/src/app.css b/fixtures/tailwind-app/src/app.css new file mode 100644 index 0000000000..f514672385 --- /dev/null +++ b/fixtures/tailwind-app/src/app.css @@ -0,0 +1,10 @@ +@import "tailwindcss"; + +@theme { + --color-brand-500: oklch(0.62 0.19 259); + --color-brand-700: oklch(0.49 0.17 262); +} + +.btn { + @apply rounded-md bg-brand-500 px-4 py-2 font-medium text-white hover:bg-brand-700; +} diff --git a/fixtures/tailwind-app/src/main.tsx b/fixtures/tailwind-app/src/main.tsx new file mode 100644 index 0000000000..1c711a7b40 --- /dev/null +++ b/fixtures/tailwind-app/src/main.tsx @@ -0,0 +1,9 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { App } from "./App"; + +createRoot(document.getElementById("root")!).render( + + + , +); diff --git a/fixtures/tailwind-app/tsconfig.json b/fixtures/tailwind-app/tsconfig.json new file mode 100644 index 0000000000..f7216161df --- /dev/null +++ b/fixtures/tailwind-app/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "jsx": "react-jsx", + "strict": true, + "noEmit": true, + "skipLibCheck": true + }, + "include": ["src", "vite.config.ts"] +} diff --git a/fixtures/tailwind-app/vite.config.ts b/fixtures/tailwind-app/vite.config.ts new file mode 100644 index 0000000000..fcdeea2375 --- /dev/null +++ b/fixtures/tailwind-app/vite.config.ts @@ -0,0 +1,7 @@ +import tailwindcss from "@tailwindcss/vite"; +import react from "@vitejs/plugin-react"; +import { defineConfig } from "vite"; + +export default defineConfig({ + plugins: [react(), tailwindcss()], +}); diff --git a/java/java-usages/MANIFEST.MF b/java/java-usages/MANIFEST.MF index 8380d7f7b3..ca787adafd 100644 --- a/java/java-usages/MANIFEST.MF +++ b/java/java-usages/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: OpenIDEA Java usages Bundle-SymbolicName: ai.openidea.usages;singleton:=true -Bundle-Version: 1.16.0 +Bundle-Version: 1.17.0 Bundle-RequiredExecutionEnvironment: JavaSE-21 Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core, org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime, diff --git a/java/java-usages/README.md b/java/java-usages/README.md index f0d724a2d7..5506ce55e3 100644 --- a/java/java-usages/README.md +++ b/java/java-usages/README.md @@ -88,7 +88,7 @@ is not a claim of full IntelliJ feature parity. ## Rebuild and delivery The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as -`java-usages-1.16.0.jar`, and added alongside existing initialization bundles. +`java-usages-1.17.0.jar`, and added alongside existing initialization bundles. Users need no compiler, Maven or Python. Manifest/install version must change when replacing the bundle because OSGi caches bundles. @@ -139,6 +139,9 @@ reproducible SHA-256 is `c29e5455c02c245523b2e7a5861e00ae670cefc66cda33ec19fdce2 Version 1.16.0 adds `openidea.java.generatedSources`, which puts Maven plugin output such as protobuf and gRPC stubs on the project classpath; its reproducible SHA-256 is `a5feda1cae11bdea1044fb311404840b048601af037f65685973721f1eefff8b`. +Version 1.17.0 adds `openidea.java.exceptionType`, the exception class at a caret for the exception +breakpoint intention; its reproducible SHA-256 is +`d1c596b37dcb6bd402ad48b214fd2a7651dbd4472eeea49e2ce992ea2f1363e9`. ```sh export PATH=/path/to/jdk25/bin:$PATH @@ -169,6 +172,7 @@ python3 java/java-usages/tests/read-write.py /path/to/jdtls /path/to/lombok.jar OPENIDEA_USAGES_INDEX_STRESS=1 python3 java/java-usages/tests/read-write.py /path/to/jdtls /path/to/lombok.jar > /tmp/read-write-indexed.json python3 java/java-usages/tests/hierarchy.py /path/to/jdtls python3 java/java-usages/tests/implementations.py /path/to/jdtls +python3 java/java-usages/tests/exception-type.py /path/to/jdtls ``` The harnesses select the JDT LS configuration for the current platform. The first @@ -185,6 +189,21 @@ listing, moving, declaring abstract, pulling up to an interface, conflicts repor before any change, and a class without supertypes. Each edit is applied to a copy of the fixture and compiled with javac. +`exception-type.py` puts the caret on throws, catches (multi-catch too), qualified names, a +thrown variable or call, a nested, local, unresolved or non-Throwable class, an import and a +class declaration, and compares each answer with IntelliJ's. + +## Exception class at a caret + +`openidea.java.exceptionType(uri, line, column)` answers `{qualifiedName, displayName}` (the +binary name, `app.Outer$Failure`, and the simple name) or `null`, as IntelliJ's +`ControlExceptionBreakpointJVMSupport` decides: from the token right of the caret, else the one +left of it, the nearest enclosing reference, class or throw statement. A reference gives the class +it resolves to (a constructor's class; a variable, a method or a package gives nothing, and so does +a call with a qualifier, which UAST sees as a reference to its method), a class gives itself only on +its name, a throw statement the class of what it throws. The class must be a `Throwable` with a +qualified name: not unresolved, local, anonymous or a type variable. + ## Class-hierarchy refactorings `openidea.java.hierarchy.members(uri, line, column, kind)` describes the class at the diff --git a/java/java-usages/openidea-java-usages.jar b/java/java-usages/openidea-java-usages.jar index a5dff7a48e..053d57c1aa 100644 Binary files a/java/java-usages/openidea-java-usages.jar and b/java/java-usages/openidea-java-usages.jar differ diff --git a/java/java-usages/plugin.xml b/java/java-usages/plugin.xml index b12450e051..fbab8c136f 100644 --- a/java/java-usages/plugin.xml +++ b/java/java-usages/plugin.xml @@ -30,5 +30,8 @@ + + + diff --git a/java/java-usages/src/ai/openidea/breakpoints/ExceptionTypeCommand.java b/java/java-usages/src/ai/openidea/breakpoints/ExceptionTypeCommand.java new file mode 100644 index 0000000000..8b56ddcb5a --- /dev/null +++ b/java/java-usages/src/ai/openidea/breakpoints/ExceptionTypeCommand.java @@ -0,0 +1,113 @@ +package ai.openidea.breakpoints; + +import ai.openidea.Documents; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jdt.core.ITypeRoot; +import org.eclipse.jdt.core.dom.*; +import org.eclipse.jdt.core.manipulation.CoreASTProvider; +import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler; +import org.eclipse.jdt.ls.core.internal.JDTUtils; +import org.eclipse.jdt.ls.core.internal.handlers.JsonRpcHelpers; + +/** + * The exception class a caret names, for the Create / Enable / Disable exception breakpoint intention. + * + *

{@code openidea.java.exceptionType(uri, line, column)} answers {@code {qualifiedName, displayName}} + * ({@code qualifiedName} is the binary name, {@code app.Outer$Failure}) or {@code null}. It follows + * IntelliJ's {@code ControlExceptionBreakpointJVMSupport}: from the token right of the caret, else the + * one left of it, the nearest enclosing reference, class or throw statement decides. A reference gives + * the class it resolves to (a constructor's class; a variable, a method or a package gives nothing), a + * class gives itself only on its name, and a throw statement the class of the thrown expression. The + * class must be a {@link Throwable} with a qualified name: not unresolved, local, anonymous or a type + * variable. + */ +public final class ExceptionTypeCommand implements IDelegateCommandHandler { + @Override + public Object executeCommand(String command, List arguments, IProgressMonitor monitor) throws Exception { + Documents.awaitChanges(monitor); + String uri = (String) arguments.get(0); + int line = ((Number) arguments.get(1)).intValue(); + int column = ((Number) arguments.get(2)).intValue(); + ITypeRoot root = JDTUtils.resolveTypeRoot(uri); + if (root == null || !root.exists()) return null; + CompilationUnit ast = CoreASTProvider.getInstance().getAST(root, CoreASTProvider.WAIT_YES, monitor); + if (ast == null) return null; + int offset = JsonRpcHelpers.toOffset(root, line, column); + if (offset < 0) return null; + ITypeBinding found = classAt(ast, offset); + if (found == null && offset > 0) found = classAt(ast, offset - 1); + return found == null ? null : describe(found); + } + + /** The exception class for the token holding the character at {@code offset}. */ + static ITypeBinding classAt(CompilationUnit ast, int offset) { + if (offset >= ast.getStartPosition() + ast.getLength()) return null; + ASTNode leaf = new NodeFinder(ast, offset, 1).getCoveringNode(); + ITypeBinding type = classReference(leaf); + return isException(type) ? type : null; + } + + private static ITypeBinding classReference(ASTNode leaf) { + for (ASTNode n = leaf; n != null; n = n.getParent()) { + if (n instanceof AbstractTypeDeclaration declaration) { + return leaf == declaration.getName() ? declaration.resolveBinding() : null; + } + if (n instanceof AnonymousClassDeclaration) return null; + if (n instanceof ThrowStatement thrown) return thrown.getExpression().resolveTypeBinding(); + if (isReference(n)) return referencedClass(n); + } + return null; + } + + /** + * What UAST converts to a reference expression: a name that is not a declaration or a label, a + * field access, a call or instance creation with a qualifier, a method or constructor reference. + */ + private static boolean isReference(ASTNode n) { + if (n instanceof SimpleName name) { + if (name.isDeclaration()) return false; + StructuralPropertyDescriptor at = name.getLocationInParent(); + return at != LabeledStatement.LABEL_PROPERTY && at != BreakStatement.LABEL_PROPERTY + && at != ContinueStatement.LABEL_PROPERTY && at != MemberValuePair.NAME_PROPERTY; + } + return n instanceof QualifiedName || n instanceof FieldAccess || n instanceof SuperFieldAccess + || n instanceof SuperMethodInvocation || n instanceof MethodReference || n instanceof MemberRef + || n instanceof MethodRef || (n instanceof MethodInvocation call && call.getExpression() != null) + || (n instanceof ClassInstanceCreation creation && creation.getExpression() != null); + } + + private static ITypeBinding referencedClass(ASTNode reference) { + IBinding binding = switch (reference) { + case Name name -> name.resolveBinding(); + case ClassInstanceCreation creation -> creation.resolveConstructorBinding(); + case MethodReference method -> method.resolveMethodBinding(); + case MethodInvocation call -> call.resolveMethodBinding(); + case SuperMethodInvocation call -> call.resolveMethodBinding(); + default -> null; + }; + if (binding instanceof ITypeBinding type) return type; + if (binding instanceof IMethodBinding method && method.isConstructor()) return method.getDeclaringClass(); + return null; + } + + private static boolean isException(ITypeBinding type) { + if (type == null || type.isRecovered() || !type.isClass() || type.isLocal() || type.isAnonymous()) return false; + for (ITypeBinding t = type.getErasure(); t != null; t = t.getSuperclass()) { + if ("java.lang.Throwable".equals(t.getQualifiedName())) return true; + } + return false; + } + + private static Map describe(ITypeBinding type) { + ITypeBinding erased = type.getErasure(); + String binary = erased.getBinaryName(); + if (binary == null) return null; + Map out = new LinkedHashMap<>(); + out.put("qualifiedName", binary); + out.put("displayName", erased.getName()); + return out; + } +} diff --git a/java/java-usages/tests/exception-type.py b/java/java-usages/tests/exception-type.py new file mode 100644 index 0000000000..b30da6e424 --- /dev/null +++ b/java/java-usages/tests/exception-type.py @@ -0,0 +1,242 @@ +"""The exception class at a caret, against a real JDT LS. Arguments: jdtls home, optional bundle jar. + +Each case puts the caret at an offset inside a unique piece of text and compares the answer of +`openidea.java.exceptionType` with IntelliJ's ControlExceptionBreakpointJVMSupport: the class a +reference resolves to (a constructor's class), a class declaration's name, or the type a throw +statement throws, when that class is a Throwable with a qualified name. +""" +import json +import pathlib +import platform +import queue +import subprocess +import sys +import tempfile +import threading +import time + +home = pathlib.Path(sys.argv[1]).resolve() +bundle = pathlib.Path(sys.argv[2]).resolve() if len(sys.argv) > 2 else pathlib.Path(__file__).resolve().parents[1] / 'openidea-java-usages.jar' +work = pathlib.Path(tempfile.mkdtemp(prefix='openidea-exception-type-')) +config = work / 'config' +config.mkdir() +system, machine = platform.system(), platform.machine().lower() +config_name = {'Windows': 'config_win', 'Darwin': 'config_mac'}.get(system, 'config_linux') +config_names = ([config_name + '_arm'] if machine in ('arm64', 'aarch64') else []) + [config_name] +config_source = next(home / name / 'config.ini' for name in config_names if (home / name / 'config.ini').is_file()) +(config / 'config.ini').write_bytes(config_source.read_bytes()) +project = work / 'project' +(project / 'src/app/errors').mkdir(parents=True) +(project / '.project').write_text('apporg.eclipse.jdt.core.javabuilderorg.eclipse.jdt.core.javanature') +(project / '.classpath').write_text('') +sources = { + 'errors/OrderException.java': '''package app.errors; + +public class OrderException extends Exception { + public OrderException(String message) { + super(message); + } +} +''', + 'Main.java': '''package app; + +import app.errors.OrderException; +import java.io.IOException; + +public class Main { + static class Failure extends RuntimeException { + } + + static class NotAnException { + } + + void place(Exception given, String msg) throws Exception { + try { + throw new OrderException("order " + msg); + } catch (OrderException | IllegalArgumentException e) { + throw given; + } + } + + void qualified() { + throw new java.lang.IllegalStateException("qualified"); + } + + void nested() { + throw new Failure(); + } + + void missing() { + throw new Missing(); + } + + Object plain() { + return new NotAnException(); + } + + static Exception build(String why) { + return new IOException(why); + } + + void call() throws Exception { + throw build("call"); + } + + void qualifiedCall() throws Exception { + throw Main.build("qualifiedCall"); + } + + void typeVariable(T t) throws T { + throw t; + } + + void local() { + class Local extends RuntimeException { + } + throw new Local(); + } +} +''', +} +for name, text in sources.items(): + (project / 'src/app' / name).write_text(text) +uri = lambda name: (project / 'src/app' / name).as_uri() + +log = (work / 'stderr.log').open('w') +proc = subprocess.Popen(['java', '-Declipse.application=org.eclipse.jdt.ls.core.id1', '-Dosgi.bundles.defaultStartLevel=4', '-Declipse.product=org.eclipse.jdt.ls.core.product', '-Xmx1G', '--add-modules=ALL-SYSTEM', '--add-opens', 'java.base/java.util=ALL-UNNAMED', '--add-opens', 'java.base/java.lang=ALL-UNNAMED', '-jar', str(next((home / 'plugins').glob('org.eclipse.equinox.launcher_*.jar'))), '-configuration', str(config), '-data', str(work / 'metadata')], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log) +messages = queue.Queue() +lock = threading.Lock() + + +def send(message): + data = json.dumps(message).encode() + with lock: + proc.stdin.write(f'Content-Length: {len(data)}\r\n\r\n'.encode() + data) + proc.stdin.flush() + + +def read(): + while True: + headers = {} + while True: + line = proc.stdout.readline() + if not line: + return + if line == b'\r\n': + break + k, v = line.decode().split(':', 1) + headers[k.lower()] = v.strip() + message = json.loads(proc.stdout.read(int(headers['content-length']))) + if 'method' in message and 'id' in message: + send({'jsonrpc': '2.0', 'id': message['id'], 'result': [] if message['method'] == 'workspace/configuration' else None}) + else: + messages.put(message) + + +threading.Thread(target=read, daemon=True).start() +seq = 0 + + +def request(method, params): + global seq + seq += 1 + send({'jsonrpc': '2.0', 'id': seq, 'method': method, 'params': params}) + deadline = time.monotonic() + 180 + while time.monotonic() < deadline: + msg = messages.get(timeout=max(1, deadline - time.monotonic())) + if msg.get('id') == seq: + if 'error' in msg: + raise RuntimeError(msg['error']) + return msg.get('result') + raise TimeoutError(method) + + +def exception_type(file, needle, at=0): + """The answer with the caret `at` characters into the only line holding `needle`.""" + lines = sources[file].splitlines() + found = [i for i, t in enumerate(lines) if needle in t] + assert len(found) == 1, (needle, found) + line = found[0] + column = lines[line].index(needle) + at + return request('workspace/executeCommand', {'command': 'openidea.java.exceptionType', 'arguments': [uri(file), line, column]}) + + +ORDER = {'qualifiedName': 'app.errors.OrderException', 'displayName': 'OrderException'} +EXCEPTION = {'qualifiedName': 'java.lang.Exception', 'displayName': 'Exception'} +CASES = [ + # throw new X(…): on the class, on `throw`, on `new`, inside a literal argument; a variable is not a class. + ('throw new OrderException', 'OrderException', 10, ORDER), + ('throw new OrderException', 'throw', 0, ORDER), + ('throw new OrderException', 'new', 1, ORDER), + ('throw new OrderException', '"order "', 2, ORDER), + ('throw new OrderException', 'msg', 1, None), + # Multi-catch: each alternative; the caret right after a name takes the name to its left. + ('catch (OrderException', 'OrderException', 3, ORDER), + ('catch (OrderException', 'IllegalArgumentException', 0, {'qualifiedName': 'java.lang.IllegalArgumentException', 'displayName': 'IllegalArgumentException'}), + ('catch (OrderException', 'OrderException', len('OrderException'), ORDER), + ('catch (OrderException', 'catch', 1, None), + ('catch (OrderException', '|', 0, None), + ('catch (OrderException', ' e)', 1, None), + # A thrown variable: its declared type on `throw`, nothing on the variable. + ('throw given', 'throw', 2, EXCEPTION), + ('throw given', 'given', 2, None), + # A qualified name: the class, not its packages. + ('java.lang.IllegalStateException', 'IllegalStateException', 4, {'qualifiedName': 'java.lang.IllegalStateException', 'displayName': 'IllegalStateException'}), + ('java.lang.IllegalStateException', 'java', 1, None), + ('java.lang.IllegalStateException', 'lang', 1, None), + # A nested class: its binary name, its simple name; also on its declaration and its superclass. + ('throw new Failure', 'Failure', 2, {'qualifiedName': 'app.Main$Failure', 'displayName': 'Failure'}), + ('static class Failure', 'Failure', 0, {'qualifiedName': 'app.Main$Failure', 'displayName': 'Failure'}), + ('static class Failure', 'RuntimeException', 3, {'qualifiedName': 'java.lang.RuntimeException', 'displayName': 'RuntimeException'}), + ('static class Failure', 'static', 1, None), + # A type that does not resolve, and a class that is not a Throwable. + ('throw new Missing', 'Missing', 2, None), + ('throw new Missing', 'throw', 1, None), + ('static class NotAnException', 'NotAnException', 2, None), + ('return new NotAnException', 'NotAnException', 2, None), + # A call: its return type on `throw`; the method name is not a class. + ('throw build', 'throw', 0, EXCEPTION), + ('throw build', 'build', 1, None), + ('throw build', '"call"', 1, EXCEPTION), + # A qualified call is a reference to its method (UAST): nothing inside it, the qualifier's class aside. + ('throw Main.build', '"qualifiedCall"', 1, None), + ('throw Main.build', 'throw', 0, EXCEPTION), + # A type variable and a local class have no qualified name. + ('throw t;', 'throw', 0, None), + ('throw new Local', 'Local', 1, None), + # An import names the class too. + ('import app.errors.OrderException', 'OrderException', 1, ORDER), + # Outside a throw, a reference or a class name: nothing. + ('void nested()', 'nested', 1, None), + ('public class Main', 'Main', 1, None), +] + +try: + init = request('initialize', {'processId': None, 'rootUri': project.as_uri(), 'workspaceFolders': [{'uri': project.as_uri(), 'name': 'app'}], 'capabilities': {}, 'initializationOptions': {'bundles': [str(bundle)], 'settings': {'java': {'import': {'gradle': {'enabled': False}, 'maven': {'enabled': False}}}}}}) + commands = init['capabilities']['executeCommandProvider']['commands'] + assert 'openidea.java.exceptionType' in commands, commands + send({'jsonrpc': '2.0', 'method': 'initialized', 'params': {}}) + for name, text in sources.items(): + send({'jsonrpc': '2.0', 'method': 'textDocument/didOpen', 'params': {'textDocument': {'uri': uri(name), 'languageId': 'java', 'version': 1, 'text': text}}}) + request('java/buildWorkspace', True) + failed = [] + for line_needle, needle, at, expected in CASES: + lines = sources['Main.java'].splitlines() + line = next(i for i, t in enumerate(lines) if line_needle in t) + column = lines[line].index(needle, lines[line].index(line_needle) if needle in line_needle else 0) + at + got = request('workspace/executeCommand', {'command': 'openidea.java.exceptionType', 'arguments': [uri('Main.java'), line, column]}) + status = 'OK' if got == expected else 'FAIL' + if got != expected: + failed.append((line_needle, needle, at)) + print(f'{status} {line_needle!r} at {needle!r}+{at}: {got}') + # A class declared in another file, read through the position in that file. + got = exception_type('errors/OrderException.java', 'class OrderException', 6) + print(('OK' if got == ORDER else 'FAIL'), 'declaration in its own file:', got) + if got != ORDER: + failed.append('declaration in its own file') + assert not failed, failed + print('exception-type: all cases passed') +finally: + proc.terminate() + proc.wait(timeout=20) + print('Evidence:', work, file=sys.stderr) diff --git a/languages/astro.toml b/languages/astro.toml index 5f74115444..546b166c0f 100644 --- a/languages/astro.toml +++ b/languages/astro.toml @@ -45,6 +45,17 @@ codeAction = { disableRuleComment = { enable = true, location = "separateLine" } # No `rules`: an empty list there means no rule gets fixed. codeActionOnSave = { mode = "all" } +# Tailwind CSS: class completion, hover and diagnostics, only in a project that uses Tailwind +# (`tailwind.config.*` or `tailwindcss` in package.json). After the language's own servers, +# which answer hover first. +[[language-servers]] +name = "tailwindcss-language-server" +command = "tailwindcss-language-server" +args = ["--stdio"] +root-markers = ["tailwind.config.*", "package.json#dependencies.tailwindcss", "package.json#devDependencies.tailwindcss"] +require-root-marker = true +install-hint = "npm i -g @tailwindcss/language-server" + # Components run in the browser: breakpoints in them are hit by a JavaScript Debug configuration. [debugger] adapter = "js-debug" diff --git a/languages/css.toml b/languages/css.toml index 4f8ba1e111..a7ef0224b7 100644 --- a/languages/css.toml +++ b/languages/css.toml @@ -13,3 +13,42 @@ command = "vscode-css-language-server" args = ["--stdio"] initialization-options = { provideFormatter = true, css = {}, scss = {}, less = {} } install-hint = "npm i -g vscode-langservers-extracted" + +# Biome: lint diagnostics, quick fixes and fix-all below a Biome configuration or installation, +# from the project's own biome. Formatting is Reformat Code's (Settings › Biome). +[[language-servers]] +name = "biome" +command = "biome" +args = ["lsp-proxy"] +root-markers = ["biome.json", "biome.jsonc", "node_modules/@biomejs/biome"] +require-root-marker = true +features = ["code-action", "diagnostics"] +install-hint = "npm i -D @biomejs/biome" + +# Stylelint: only below a project's Stylelint configuration; the server runs the project's own +# stylelint. Diagnostics, quick fixes and fix-all (Code Cleanup, Actions on Save) only: the +# server's formatting applies the same fixes, and Reformat Code stays the formatter's. +[[language-servers]] +name = "stylelint" +command = "stylelint-language-server" +args = ["--stdio"] +root-markers = [".stylelintrc", ".stylelintrc.json", ".stylelintrc.yaml", ".stylelintrc.yml", ".stylelintrc.js", ".stylelintrc.cjs", ".stylelintrc.mjs", ".stylelintrc.ts", ".stylelintrc.cts", ".stylelintrc.mts", "stylelint.config.js", "stylelint.config.cjs", "stylelint.config.mjs", "stylelint.config.ts", "stylelint.config.cts", "stylelint.config.mts", "package.json#stylelint"] +require-root-marker = true +features = ["code-action", "diagnostics"] +install-hint = "npm i -g @stylelint/language-server" + +# Read as section `stylelint`: the languages it lints (its default is CSS only). +[language-servers.settings] +validate = ["css", "scss", "less"] +snippet = ["css", "scss", "less"] + +# Tailwind CSS: class completion, hover and diagnostics, only in a project that uses Tailwind +# (`tailwind.config.*` or `tailwindcss` in package.json). After the language's own servers, +# which answer hover first. +[[language-servers]] +name = "tailwindcss-language-server" +command = "tailwindcss-language-server" +args = ["--stdio"] +root-markers = ["tailwind.config.*", "package.json#dependencies.tailwindcss", "package.json#devDependencies.tailwindcss"] +require-root-marker = true +install-hint = "npm i -g @tailwindcss/language-server" diff --git a/languages/graphql.toml b/languages/graphql.toml index 7e1c1f43fc..c4e9db1a0d 100644 --- a/languages/graphql.toml +++ b/languages/graphql.toml @@ -12,3 +12,14 @@ command = "graphql-lsp" args = ["server", "-m", "stream"] root-markers = [".graphqlrc", ".graphqlrc.yml", ".graphqlrc.yaml", ".graphqlrc.json", "graphql.config.js", "graphql.config.ts", "graphql.config.yml", "graphql.config.yaml", "graphql.config.json"] install-hint = "npm i -g graphql-language-service-cli" + +# Biome: lint diagnostics, quick fixes and fix-all below a Biome configuration or installation, +# from the project's own biome. Formatting is Reformat Code's (Settings › Biome). +[[language-servers]] +name = "biome" +command = "biome" +args = ["lsp-proxy"] +root-markers = ["biome.json", "biome.jsonc", "node_modules/@biomejs/biome"] +require-root-marker = true +features = ["code-action", "diagnostics"] +install-hint = "npm i -D @biomejs/biome" diff --git a/languages/html.toml b/languages/html.toml index 1b62c42388..7d94927540 100644 --- a/languages/html.toml +++ b/languages/html.toml @@ -41,6 +41,17 @@ args = ["--stdio"] initialization-options = { provideFormatter = true, embeddedLanguages = { css = true, javascript = true } } install-hint = "npm i -g vscode-langservers-extracted" +# Tailwind CSS: class completion, hover and diagnostics, only in a project that uses Tailwind +# (`tailwind.config.*` or `tailwindcss` in package.json). After the language's own servers, +# which answer hover first. +[[language-servers]] +name = "tailwindcss-language-server" +command = "tailwindcss-language-server" +args = ["--stdio"] +root-markers = ["tailwind.config.*", "package.json#dependencies.tailwindcss", "package.json#devDependencies.tailwindcss"] +require-root-marker = true +install-hint = "npm i -g @tailwindcss/language-server" + # Scripts in a page run in the browser: breakpoints in them are hit by a JavaScript Debug configuration. [debugger] adapter = "js-debug" diff --git a/languages/javascript.toml b/languages/javascript.toml index e4b14ce0f8..d41e965703 100644 --- a/languages/javascript.toml +++ b/languages/javascript.toml @@ -106,6 +106,28 @@ codeAction = { disableRuleComment = { enable = true, location = "separateLine" } # No `rules`: an empty list there means no rule gets fixed. codeActionOnSave = { mode = "all" } +# Biome: lint diagnostics, quick fixes and fix-all below a Biome configuration or installation, +# from the project's own biome. Formatting is Reformat Code's (Settings › Biome). +[[language-servers]] +name = "biome" +command = "biome" +args = ["lsp-proxy"] +root-markers = ["biome.json", "biome.jsonc", "node_modules/@biomejs/biome"] +require-root-marker = true +features = ["code-action", "diagnostics"] +install-hint = "npm i -D @biomejs/biome" + +# Tailwind CSS: class completion, hover and diagnostics, only in a project that uses Tailwind +# (`tailwind.config.*` or `tailwindcss` in package.json). After the language's own servers, +# which answer hover first. +[[language-servers]] +name = "tailwindcss-language-server" +command = "tailwindcss-language-server" +args = ["--stdio"] +root-markers = ["tailwind.config.*", "package.json#dependencies.tailwindcss", "package.json#devDependencies.tailwindcss"] +require-root-marker = true +install-hint = "npm i -g @tailwindcss/language-server" + [debugger] adapter = "js-debug" command = "js-debug-adapter" diff --git a/languages/javascriptreact.toml b/languages/javascriptreact.toml index 79dc303236..9dc7cc15e6 100644 --- a/languages/javascriptreact.toml +++ b/languages/javascriptreact.toml @@ -109,6 +109,28 @@ codeAction = { disableRuleComment = { enable = true, location = "separateLine" } # No `rules`: an empty list there means no rule gets fixed. codeActionOnSave = { mode = "all" } +# Biome: lint diagnostics, quick fixes and fix-all below a Biome configuration or installation, +# from the project's own biome. Formatting is Reformat Code's (Settings › Biome). +[[language-servers]] +name = "biome" +command = "biome" +args = ["lsp-proxy"] +root-markers = ["biome.json", "biome.jsonc", "node_modules/@biomejs/biome"] +require-root-marker = true +features = ["code-action", "diagnostics"] +install-hint = "npm i -D @biomejs/biome" + +# Tailwind CSS: class completion, hover and diagnostics, only in a project that uses Tailwind +# (`tailwind.config.*` or `tailwindcss` in package.json). After the language's own servers, +# which answer hover first. +[[language-servers]] +name = "tailwindcss-language-server" +command = "tailwindcss-language-server" +args = ["--stdio"] +root-markers = ["tailwind.config.*", "package.json#dependencies.tailwindcss", "package.json#devDependencies.tailwindcss"] +require-root-marker = true +install-hint = "npm i -g @tailwindcss/language-server" + [debugger] adapter = "js-debug" command = "js-debug-adapter" diff --git a/languages/json.toml b/languages/json.toml index 34403bc0ad..94f29d3502 100644 --- a/languages/json.toml +++ b/languages/json.toml @@ -58,3 +58,14 @@ url = "https://swc.rs/schema.json" [[language-servers.settings.json.schemas]] fileMatch = ["composer.json"] url = "https://getcomposer.org/schema.json" + +# Biome: lint diagnostics, quick fixes and fix-all below a Biome configuration or installation, +# from the project's own biome. Formatting is Reformat Code's (Settings › Biome). +[[language-servers]] +name = "biome" +command = "biome" +args = ["lsp-proxy"] +root-markers = ["biome.json", "biome.jsonc", "node_modules/@biomejs/biome"] +require-root-marker = true +features = ["code-action", "diagnostics"] +install-hint = "npm i -D @biomejs/biome" diff --git a/languages/jsonc.toml b/languages/jsonc.toml index c32b4a2352..bb76a0a379 100644 --- a/languages/jsonc.toml +++ b/languages/jsonc.toml @@ -60,3 +60,14 @@ url = "https://swc.rs/schema.json" [[language-servers.settings.json.schemas]] fileMatch = ["composer.json"] url = "https://getcomposer.org/schema.json" + +# Biome: lint diagnostics, quick fixes and fix-all below a Biome configuration or installation, +# from the project's own biome. Formatting is Reformat Code's (Settings › Biome). +[[language-servers]] +name = "biome" +command = "biome" +args = ["lsp-proxy"] +root-markers = ["biome.json", "biome.jsonc", "node_modules/@biomejs/biome"] +require-root-marker = true +features = ["code-action", "diagnostics"] +install-hint = "npm i -D @biomejs/biome" diff --git a/languages/less.toml b/languages/less.toml index cfc834ee80..05f7541352 100644 --- a/languages/less.toml +++ b/languages/less.toml @@ -13,3 +13,20 @@ command = "vscode-css-language-server" args = ["--stdio"] initialization-options = { provideFormatter = true, css = {}, scss = {}, less = {} } install-hint = "npm i -g vscode-langservers-extracted" + +# Stylelint: only below a project's Stylelint configuration; the server runs the project's own +# stylelint. Diagnostics, quick fixes and fix-all (Code Cleanup, Actions on Save) only: the +# server's formatting applies the same fixes, and Reformat Code stays the formatter's. +[[language-servers]] +name = "stylelint" +command = "stylelint-language-server" +args = ["--stdio"] +root-markers = [".stylelintrc", ".stylelintrc.json", ".stylelintrc.yaml", ".stylelintrc.yml", ".stylelintrc.js", ".stylelintrc.cjs", ".stylelintrc.mjs", ".stylelintrc.ts", ".stylelintrc.cts", ".stylelintrc.mts", "stylelint.config.js", "stylelint.config.cjs", "stylelint.config.mjs", "stylelint.config.ts", "stylelint.config.cts", "stylelint.config.mts", "package.json#stylelint"] +require-root-marker = true +features = ["code-action", "diagnostics"] +install-hint = "npm i -g @stylelint/language-server" + +# Read as section `stylelint`: the languages it lints (its default is CSS only). +[language-servers.settings] +validate = ["css", "scss", "less"] +snippet = ["css", "scss", "less"] diff --git a/languages/scss.toml b/languages/scss.toml index dcdaadd4c0..11ec9ddffa 100644 --- a/languages/scss.toml +++ b/languages/scss.toml @@ -13,3 +13,20 @@ command = "vscode-css-language-server" args = ["--stdio"] initialization-options = { provideFormatter = true, css = {}, scss = {}, less = {} } install-hint = "npm i -g vscode-langservers-extracted" + +# Stylelint: only below a project's Stylelint configuration; the server runs the project's own +# stylelint. Diagnostics, quick fixes and fix-all (Code Cleanup, Actions on Save) only: the +# server's formatting applies the same fixes, and Reformat Code stays the formatter's. +[[language-servers]] +name = "stylelint" +command = "stylelint-language-server" +args = ["--stdio"] +root-markers = [".stylelintrc", ".stylelintrc.json", ".stylelintrc.yaml", ".stylelintrc.yml", ".stylelintrc.js", ".stylelintrc.cjs", ".stylelintrc.mjs", ".stylelintrc.ts", ".stylelintrc.cts", ".stylelintrc.mts", "stylelint.config.js", "stylelint.config.cjs", "stylelint.config.mjs", "stylelint.config.ts", "stylelint.config.cts", "stylelint.config.mts", "package.json#stylelint"] +require-root-marker = true +features = ["code-action", "diagnostics"] +install-hint = "npm i -g @stylelint/language-server" + +# Read as section `stylelint`: the languages it lints (its default is CSS only). +[language-servers.settings] +validate = ["css", "scss", "less"] +snippet = ["css", "scss", "less"] diff --git a/languages/svelte.toml b/languages/svelte.toml index 7e57414481..d402a9d7fa 100644 --- a/languages/svelte.toml +++ b/languages/svelte.toml @@ -51,6 +51,17 @@ codeAction = { disableRuleComment = { enable = true, location = "separateLine" } # No `rules`: an empty list there means no rule gets fixed. codeActionOnSave = { mode = "all" } +# Tailwind CSS: class completion, hover and diagnostics, only in a project that uses Tailwind +# (`tailwind.config.*` or `tailwindcss` in package.json). After the language's own servers, +# which answer hover first. +[[language-servers]] +name = "tailwindcss-language-server" +command = "tailwindcss-language-server" +args = ["--stdio"] +root-markers = ["tailwind.config.*", "package.json#dependencies.tailwindcss", "package.json#devDependencies.tailwindcss"] +require-root-marker = true +install-hint = "npm i -g @tailwindcss/language-server" + # Components run in the browser: breakpoints in them are hit by a JavaScript Debug configuration. [debugger] adapter = "js-debug" diff --git a/languages/typescript.toml b/languages/typescript.toml index 95d93a7b86..0d1031bc78 100644 --- a/languages/typescript.toml +++ b/languages/typescript.toml @@ -124,6 +124,28 @@ codeAction = { disableRuleComment = { enable = true, location = "separateLine" } # No `rules`: an empty list there means no rule gets fixed. codeActionOnSave = { mode = "all" } +# Biome: lint diagnostics, quick fixes and fix-all below a Biome configuration or installation, +# from the project's own biome. Formatting is Reformat Code's (Settings › Biome). +[[language-servers]] +name = "biome" +command = "biome" +args = ["lsp-proxy"] +root-markers = ["biome.json", "biome.jsonc", "node_modules/@biomejs/biome"] +require-root-marker = true +features = ["code-action", "diagnostics"] +install-hint = "npm i -D @biomejs/biome" + +# Tailwind CSS: class completion, hover and diagnostics, only in a project that uses Tailwind +# (`tailwind.config.*` or `tailwindcss` in package.json). After the language's own servers, +# which answer hover first. +[[language-servers]] +name = "tailwindcss-language-server" +command = "tailwindcss-language-server" +args = ["--stdio"] +root-markers = ["tailwind.config.*", "package.json#dependencies.tailwindcss", "package.json#devDependencies.tailwindcss"] +require-root-marker = true +install-hint = "npm i -g @tailwindcss/language-server" + [debugger] adapter = "js-debug" command = "js-debug-adapter" diff --git a/languages/typescriptreact.toml b/languages/typescriptreact.toml index 66dd643304..b829399f55 100644 --- a/languages/typescriptreact.toml +++ b/languages/typescriptreact.toml @@ -110,6 +110,28 @@ codeAction = { disableRuleComment = { enable = true, location = "separateLine" } # No `rules`: an empty list there means no rule gets fixed. codeActionOnSave = { mode = "all" } +# Biome: lint diagnostics, quick fixes and fix-all below a Biome configuration or installation, +# from the project's own biome. Formatting is Reformat Code's (Settings › Biome). +[[language-servers]] +name = "biome" +command = "biome" +args = ["lsp-proxy"] +root-markers = ["biome.json", "biome.jsonc", "node_modules/@biomejs/biome"] +require-root-marker = true +features = ["code-action", "diagnostics"] +install-hint = "npm i -D @biomejs/biome" + +# Tailwind CSS: class completion, hover and diagnostics, only in a project that uses Tailwind +# (`tailwind.config.*` or `tailwindcss` in package.json). After the language's own servers, +# which answer hover first. +[[language-servers]] +name = "tailwindcss-language-server" +command = "tailwindcss-language-server" +args = ["--stdio"] +root-markers = ["tailwind.config.*", "package.json#dependencies.tailwindcss", "package.json#devDependencies.tailwindcss"] +require-root-marker = true +install-hint = "npm i -g @tailwindcss/language-server" + [debugger] adapter = "js-debug" command = "js-debug-adapter" diff --git a/languages/vue.toml b/languages/vue.toml index 7d54c43659..77b9e58a25 100644 --- a/languages/vue.toml +++ b/languages/vue.toml @@ -88,6 +88,17 @@ codeAction = { disableRuleComment = { enable = true, location = "separateLine" } # No `rules`: an empty list there means no rule gets fixed. codeActionOnSave = { mode = "all" } +# Tailwind CSS: class completion, hover and diagnostics, only in a project that uses Tailwind +# (`tailwind.config.*` or `tailwindcss` in package.json). After the language's own servers, +# which answer hover first. +[[language-servers]] +name = "tailwindcss-language-server" +command = "tailwindcss-language-server" +args = ["--stdio"] +root-markers = ["tailwind.config.*", "package.json#dependencies.tailwindcss", "package.json#devDependencies.tailwindcss"] +require-root-marker = true +install-hint = "npm i -g @tailwindcss/language-server" + # Components run in the browser: breakpoints in them are hit by a JavaScript Debug configuration. [debugger] adapter = "js-debug" diff --git a/mise.toml b/mise.toml index 93b95b73fc..298c31dcf3 100644 --- a/mise.toml +++ b/mise.toml @@ -29,6 +29,10 @@ description = "Build and install the local dogfood desktop app" depends = ["dogfood:build"] run = "pnpm dogfood:install --no-build" +[tasks."dogfood:remote"] +description = "Build and install a local dogfood openidea-server on a configured SSH remote" +run = "pnpm dogfood:remote" + [tasks.test] description = "Run the frontend and Rust workspace tests" run = ["pnpm test", "cargo test --workspace"] diff --git a/package.json b/package.json index a018510f84..271a50b18c 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,8 @@ "eval": "node evals/run.ts", "release:prepare": "node scripts/release-prepare.ts", "dogfood:build": "node scripts/dogfood.ts build", - "dogfood:install": "node scripts/dogfood.ts install" + "dogfood:install": "node scripts/dogfood.ts install", + "dogfood:remote": "node scripts/dogfood-remote.ts" }, "simple-git-hooks": { "pre-commit": "pnpm lint-staged" @@ -69,6 +70,8 @@ "@lezer/common": "^1.5.3", "@lezer/highlight": "^1.2.5", "@lezer/lr": "^1.4.11", + "@mathjax/mathjax-tex-font": "4.1.3", + "@mathjax/src": "4.1.3", "@plutojl/lang-julia": "^1.2.0", "@replit/codemirror-vim": "6.4.0", "@tanstack/react-virtual": "^3.14.21", @@ -94,6 +97,7 @@ }, "devDependencies": { "@lezer/generator": "^1.8.1", + "@noble/hashes": "^2.4.0", "@playwright/test": "^1.64.1", "@tauri-apps/cli": "^2", "@testing-library/jest-dom": "^7.0.1", diff --git a/plugins/README.md b/plugins/README.md index 4c83494015..909761daf7 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -145,6 +145,7 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK. | `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?` (API 1.4; §6.2) | no | | `runConfigurations` | `files`: marker files for the optional `run-configurations` export (API 1.4) | yes | | `javaAgents` | `path` (a jar in the package), `args?`, `vmOptions?`, `jdk?` — a Java agent for Java run configurations, behind `java.agent` (API 1.10; `vmOptions`/`jdk` in 1.14; _Java agents_) | no | +| `skills` | `path` (`skills//SKILL.md` in the package) — agent skill folder staged into coding-agent sessions (API 1.15) | no | | `mcpTools` | `name`, `description`, `inputSchema` (package JSON Schema path), `readOnly`, `destructive` (API 1.4; see _Plugin MCP tools_) | yes | | `snippets` | `language`, `path` (named JSON snippets; API 1.4) | no | | `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes | @@ -437,6 +438,13 @@ matching SDK. Plugins for 1.14 and earlier keep working. New in 1.15: position once the caret rests: defer costly work (loading data behind a hover) until then. Subscribe at run time or declare `on-event:caret-moved`; requires `events`. +- **Agent skills (`[[contributes.skills]]`).** Declarative `path = + "skills//SKILL.md"` entries expose bundled `SKILL.md` folders (up to + 2 MiB per skill, no symlinks leaving the package) under the **Plugins** group + in Settings › Agents › Skills and the Composer picker, staged into agent + sessions while the plugin is enabled; workspace and user skills take + precedence on a name clash, and invalid entries report a plugin load warning + rather than failing the plugin. ### API 1.14 diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8ead3ffc87..55d4b1b09a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -84,6 +84,12 @@ importers: '@lezer/lr': specifier: ^1.4.11 version: 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8) + '@mathjax/mathjax-tex-font': + specifier: 4.1.3 + version: 4.1.3 + '@mathjax/src': + specifier: 4.1.3 + version: 4.1.3 '@plutojl/lang-julia': specifier: ^1.2.0 version: 1.2.0 @@ -154,6 +160,9 @@ importers: '@lezer/generator': specifier: ^1.8.1 version: 1.8.1 + '@noble/hashes': + specifier: ^2.4.0 + version: 2.4.0 '@playwright/test': specifier: ^1.64.1 version: 1.64.1 @@ -162,7 +171,7 @@ importers: version: 2.12.3 '@testing-library/jest-dom': specifier: ^7.0.1 - version: 7.0.1(@testing-library/dom@10.4.2)(vitest@5.0.5(@types/node@26.6.5)(jsdom@30.1.3)(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(yaml@2.9.1))) + version: 7.0.1(@testing-library/dom@10.4.2)(vitest@5.0.5(@types/node@26.6.5)(jsdom@30.1.3(@noble/hashes@2.4.0))(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(yaml@2.9.1))) '@testing-library/react': specifier: ^16.3.3 version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) @@ -183,7 +192,7 @@ importers: version: 6.1.2(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(yaml@2.9.1)) jsdom: specifier: ^30.1.3 - version: 30.1.3 + version: 30.1.3(@noble/hashes@2.4.0) knip: specifier: ^6.43.0 version: 6.43.0 @@ -210,7 +219,7 @@ importers: version: 8.3.4(@types/node@26.6.5)(jiti@2.7.0)(yaml@2.9.1) vitest: specifier: ^5.0.5 - version: 5.0.5(@types/node@26.6.5)(jsdom@30.1.3)(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(yaml@2.9.1)) + version: 5.0.5(@types/node@26.6.5)(jsdom@30.1.3(@noble/hashes@2.4.0))(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(yaml@2.9.1)) yaml: specifier: ^2.9.1 version: 2.9.1 @@ -451,6 +460,9 @@ packages: '@iconify/utils@3.1.7': resolution: {integrity: sha512-JZHlwdID+dy+lTgbYC8NEC4zeugqeYsc6jewvzb4c58kHauJn+X7rNwQjxz5p2qSjqaEeQoLkCIQ9v/H4PK0/w==} + '@isaacs/nonrecursive-glob-match@1.1.0': + resolution: {integrity: sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==} + '@jridgewell/resolve-uri@3.1.2': resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} engines: {node: '>=6.0.0'} @@ -519,6 +531,15 @@ packages: '@marijn/find-cluster-break@1.0.4': resolution: {integrity: sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==} + '@mathjax/mathjax-newcm-font@4.1.3': + resolution: {integrity: sha512-gzAB3dFHilHX1l5x2xUqRL+1jDQt3Fyza1DkEMVXWC4E8SvsGdlgEza47HYi2WhVcgfkvf4zgUGzuhbq3Pjlew==} + + '@mathjax/mathjax-tex-font@4.1.3': + resolution: {integrity: sha512-9B78brBEmmAwyumaREIyM1gF2HgDamDIXA36UyeXWxX7XrpLdmoSB5NLIf/c6tEA4L6xNrIdMxfgY6YX/kcSNw==} + + '@mathjax/src@4.1.3': + resolution: {integrity: sha512-rIrWquuBSoJuoMBdC/1qD+AUHTorlccPicoVy6P2xbUgnuDBpCcpbHtOAsB8L3hdCHtNBg92lF8e3Fz+pkcQbw==} + '@mermaid-js/parser@2.0.1': resolution: {integrity: sha512-j37dj/h6p6pots1L7pLPPNuABEEu9WP4OYg9pW1g+nYG331j0+3canE9OagtYdytYvdSAMG+2fKU5cxep6LgjA==} engines: {node: '>=22.12.0'} @@ -530,6 +551,10 @@ packages: '@emnapi/core': ^1.7.1 || 2.0.0-beta.2 '@emnapi/runtime': ^1.7.1 || 2.0.0-beta.2 + '@noble/hashes@2.4.0': + resolution: {integrity: sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==} + engines: {node: '>= 20.19.0'} + '@oxc-parser/binding-android-arm-eabi@0.155.0': resolution: {integrity: sha512-A6xv7hDtnTm+xlZ7utn6rRQpRMJHRhVr3gjRGqlx0RUX84mNk0pAsy6YN/wWhuOTkaZhRrrzaLxf0NfbH77j2w==} engines: {node: ^20.19.0 || >=22.12.0} @@ -598,6 +623,7 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} cpu: [riscv64] os: [linux] + libc: [glibc] '@oxc-parser/binding-linux-riscv64-musl@0.155.0': resolution: {integrity: sha512-JSlhgoK+/g1TGJI5NuADx2+6syhxnQNLCWLXyO5QLFyetomcr/vIxSdiNlmyAv963YXUzCuwAwRG6npZ5xyJ1A==} @@ -1075,6 +1101,7 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] + libc: [musl] '@rolldown/binding-linux-ppc64-gnu@1.2.14': resolution: {integrity: sha512-4+Kl8daPV8NDHaD7mfCcc1pRM+Qg7ab8DyMm5FG5WoZgv4h2i3KFN1CybYBNbQqmuYm7ftJLvmMI1eHYJ22S/Q==} @@ -1088,12 +1115,14 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] + libc: [glibc] '@rolldown/binding-linux-x64-gnu@1.2.14': resolution: {integrity: sha512-WxalXzgrLVpKC93xfpaJ3gCXUWzeCr+FRCbDVD2mUAy4L6Vo3lNVz0epUEUpxPWJkLNYUwM4OSIikv36OJ9mLg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] + libc: [glibc] '@rolldown/binding-linux-x64-musl@1.2.14': resolution: {integrity: sha512-3G3tnAmTpdk9jO3GQtyHXqeFD2SlecfTws/Y3M2mmj9nMBwwuLT4kur8sZKeu7ENUHSpVO3cIsm5A52LEWWwlg==} @@ -1456,6 +1485,10 @@ packages: '@vitest/spy@5.0.5': resolution: {integrity: sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==} + '@xmldom/xmldom@0.9.12': + resolution: {integrity: sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A==} + engines: {node: '>=14.6'} + '@xterm/addon-fit@0.12.0-beta.334': resolution: {integrity: sha512-fIFQHJ15PER9KhAG24IhA5vF4ysHEKrJgImt/ZqRcahvNUGF1T3WnpJ6bLvlvnsft7bVT0ofBWySx6nxFNAXkA==} peerDependencies: @@ -1491,9 +1524,17 @@ packages: resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} engines: {node: '>=12'} + balanced-match@4.0.4: + resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} + engines: {node: 18 || 20 || >=22} + bidi-js@1.1.0: resolution: {integrity: sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==} + brace-expansion@5.0.13: + resolution: {integrity: sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==} + engines: {node: 20 || >=22} + chai@6.3.0: resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} engines: {node: '>=18'} @@ -1506,6 +1547,10 @@ packages: resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} engines: {node: '>=6'} + commander@14.0.3: + resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==} + engines: {node: '>=20'} + commander@15.1.0: resolution: {integrity: sha512-cgnQ88TRrWcC7pVq46RzJVRMktu3W2RcbnoidnfBsl1bmDCBwJS/udcIZpKoCrbAYYaCqsz1yZCVIgbIaU3ddQ==} engines: {node: '>=22.12.0'} @@ -1767,6 +1812,10 @@ packages: get-tsconfig@4.14.3: resolution: {integrity: sha512-++QEw4DIY7WGoukz+/+A/8dGYPT9l9yIadnmSgZ8Rjr3YVSVDipQSO9CdnJo9ePqFqUUqh+wk9uIaoiAwsiPkA==} + glob@14.0.6: + resolution: {integrity: sha512-OwXjVP2svY5EyLY75Vek96C8qK43gqrt4xsZ+qSILdnaEiJPXkd62mcfUSNx/TQErQRdu5uM5kF67sfONragKw==} + engines: {node: 18 || 20 || >=22} + hachure-fill@0.5.2: resolution: {integrity: sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==} @@ -1871,6 +1920,7 @@ packages: engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] + libc: [glibc] lightningcss-linux-arm64-musl@1.33.0: resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} @@ -1884,12 +1934,14 @@ packages: engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] + libc: [glibc] lightningcss-linux-x64-musl@1.33.0: resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] + libc: [musl] lightningcss-win32-arm64-msvc@1.33.0: resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} @@ -1943,10 +1995,24 @@ packages: resolution: {integrity: sha512-wlVCp+8eTupfCeeFvoZNNiTuHrvag0P2jz/ILgb/f/6jkVokUefOcujefi8qUe/j2asHiSePncVsz/xzzA80LQ==} engines: {node: '>=22.12.0'} + mhchemparser@4.2.1: + resolution: {integrity: sha512-kYmyrCirqJf3zZ9t/0wGgRZ4/ZJw//VwaRVGA75C4nhE60vtnIzhl9J9ndkX/h6hxSN7pjg/cE0VxbnNM+bnDQ==} + min-indent@1.0.1: resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==} engines: {node: '>=4'} + minimatch@11.0.9: + resolution: {integrity: sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==} + engines: {node: 20 || >=22} + + minipass@7.1.3: + resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} + engines: {node: '>=16 || 14 >=14.17'} + + mj-context-menu@1.0.0: + resolution: {integrity: sha512-OSgBFQRCVhrZwRa9lhqnKcJU92dd/YXgBjup0uyeuj9bOaVsf4myOyrjU4PfhYkdDk6AqVUTov7v5uFMvIbduA==} + nanoid@3.3.20: resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -1992,6 +2058,9 @@ packages: vite-plus: optional: true + package-json-from-dist@1.0.1: + resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==} + package-manager-detector@1.9.0: resolution: {integrity: sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA==} @@ -2001,6 +2070,10 @@ packages: path-data-parser@0.1.0: resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==} + path-scurry@3.0.0: + resolution: {integrity: sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==} + engines: {node: 18 || 20 || >=22} + picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} @@ -2071,6 +2144,11 @@ packages: resolve-pkg-maps@1.0.0: resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} + rimraf@6.1.4: + resolution: {integrity: sha512-Fk3reQDVPZUMbEm7Zwxz03BWQMW3V5buSk9aU8OckTrO8A1nQtbqvYsAantGNermwsIsXcuOBqcoJ3HuMELctw==} + engines: {node: 20 || >=22} + hasBin: true + robust-predicates@3.0.3: resolution: {integrity: sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==} @@ -2107,6 +2185,10 @@ packages: resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} engines: {node: '>=0.10.0'} + speech-rule-engine@5.0.0-rc.4: + resolution: {integrity: sha512-3dFcH2QtQNhtvUUc09TxoaEK4WG03B9Z57krFG9jocrKykKGu35BhIkWr0vgEAxZZomEWkeluff69y/EbYzP4Q==} + hasBin: true + std-env@4.3.0: resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} @@ -2303,6 +2385,9 @@ packages: engines: {node: '>=20.11'} hasBin: true + wicked-good-xpath@1.3.0: + resolution: {integrity: sha512-Gd9+TUn5nXdwj/hFsPVx5cuHHiF5Bwuc30jZ4+ronF1qHK5O7HD0sgmXWSEgwKquT3ClLoKPVbO6qGwVwLzvAw==} + xml-name-validator@5.0.0: resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==} engines: {node: '>=18'} @@ -2703,7 +2788,9 @@ snapshots: tslib: 2.8.1 optional: true - '@exodus/bytes@1.16.0': {} + '@exodus/bytes@1.16.0(@noble/hashes@2.4.0)': + optionalDependencies: + '@noble/hashes': 2.4.0 '@floating-ui/core@1.8.0': dependencies: @@ -2734,6 +2821,8 @@ snapshots: '@iconify/types': 2.0.0 import-meta-resolve: 4.2.0 + '@isaacs/nonrecursive-glob-match@1.1.0': {} + '@jridgewell/resolve-uri@3.1.2': {} '@jridgewell/sourcemap-codec@1.6.0': {} @@ -2843,6 +2932,17 @@ snapshots: '@marijn/find-cluster-break@1.0.4': {} + '@mathjax/mathjax-newcm-font@4.1.3': {} + + '@mathjax/mathjax-tex-font@4.1.3': {} + + '@mathjax/src@4.1.3': + dependencies: + '@mathjax/mathjax-newcm-font': 4.1.3 + mhchemparser: 4.2.1 + mj-context-menu: 1.0.0 + speech-rule-engine: 5.0.0-rc.4 + '@mermaid-js/parser@2.0.1': dependencies: '@chevrotain/types': 13.2.0 @@ -2854,6 +2954,8 @@ snapshots: '@tybys/wasm-util': 0.10.4 optional: true + '@noble/hashes@2.4.0': {} + '@oxc-parser/binding-android-arm-eabi@0.155.0': optional: true @@ -3241,7 +3343,7 @@ snapshots: picocolors: 1.1.1 pretty-format: 27.5.1 - '@testing-library/jest-dom@7.0.1(@testing-library/dom@10.4.2)(vitest@5.0.5(@types/node@26.6.5)(jsdom@30.1.3)(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(yaml@2.9.1)))': + '@testing-library/jest-dom@7.0.1(@testing-library/dom@10.4.2)(vitest@5.0.5(@types/node@26.6.5)(jsdom@30.1.3(@noble/hashes@2.4.0))(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(yaml@2.9.1)))': dependencies: '@adobe/css-tools': 4.5.0 '@testing-library/dom': 10.4.2 @@ -3251,7 +3353,7 @@ snapshots: picocolors: 1.1.1 redent: 3.0.0 optionalDependencies: - vitest: 5.0.5(@types/node@26.6.5)(jsdom@30.1.3)(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(yaml@2.9.1)) + vitest: 5.0.5(@types/node@26.6.5)(jsdom@30.1.3(@noble/hashes@2.4.0))(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(yaml@2.9.1)) '@testing-library/react@16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': dependencies: @@ -3459,6 +3561,8 @@ snapshots: '@vitest/spy@5.0.5': {} + '@xmldom/xmldom@0.9.12': {} + '@xterm/addon-fit@0.12.0-beta.334(@xterm/xterm@6.1.0-beta.338)': dependencies: '@xterm/xterm': 6.1.0-beta.338 @@ -3483,10 +3587,16 @@ snapshots: assertion-error@2.0.1: {} + balanced-match@4.0.4: {} + bidi-js@1.1.0: dependencies: require-from-string: 2.0.2 + brace-expansion@5.0.13: + dependencies: + balanced-match: 4.0.4 + chai@6.3.0: {} chevrotain@13.2.0: @@ -3499,6 +3609,8 @@ snapshots: clsx@2.1.1: {} + commander@14.0.3: {} + commander@15.1.0: {} commander@7.2.0: {} @@ -3706,10 +3818,10 @@ snapshots: d3: 7.9.0 lodash-es: 4.18.1 - data-urls@8.0.0: + data-urls@8.0.0(@noble/hashes@2.4.0): dependencies: whatwg-mimetype: 5.0.0 - whatwg-url: 17.3.0 + whatwg-url: 17.3.0(@noble/hashes@2.4.0) transitivePeerDependencies: - '@noble/hashes' @@ -3772,11 +3884,17 @@ snapshots: dependencies: resolve-pkg-maps: 1.0.0 + glob@14.0.6: + dependencies: + minimatch: 11.0.9 + minipass: 7.1.3 + path-scurry: 3.0.0 + hachure-fill@0.5.2: {} - html-encoding-sniffer@7.0.0: + html-encoding-sniffer@7.0.0(@noble/hashes@2.4.0): dependencies: - '@exodus/bytes': 1.16.0 + '@exodus/bytes': 1.16.0(@noble/hashes@2.4.0) transitivePeerDependencies: - '@noble/hashes' @@ -3800,17 +3918,17 @@ snapshots: js-tokens@4.0.0: {} - jsdom@30.1.3: + jsdom@30.1.3(@noble/hashes@2.4.0): dependencies: '@asamuzakjp/css-color': 7.1.7 '@asamuzakjp/dom-selector': 10.0.4 '@bramus/specificity': 2.4.3 '@csstools/css-syntax-patches-for-csstree': 1.1.15(css-tree@3.2.1) - '@exodus/bytes': 1.16.0 + '@exodus/bytes': 1.16.0(@noble/hashes@2.4.0) css-tree: 3.2.1 - data-urls: 8.0.0 + data-urls: 8.0.0(@noble/hashes@2.4.0) decimal.js: 10.6.0 - html-encoding-sniffer: 7.0.0 + html-encoding-sniffer: 7.0.0(@noble/hashes@2.4.0) is-potential-custom-element-name: 1.0.1 lru-cache: 11.5.3 parse5: 8.0.1 @@ -3820,7 +3938,7 @@ snapshots: w3c-xmlserializer: 6.0.0 webidl-conversions: 8.0.1 whatwg-mimetype: 5.0.0 - whatwg-url: 17.3.0 + whatwg-url: 17.3.0(@noble/hashes@2.4.0) xml-name-validator: 5.0.0 transitivePeerDependencies: - '@noble/hashes' @@ -3953,8 +4071,21 @@ snapshots: ts-dedent: 2.3.0 uuid: 14.0.3 + mhchemparser@4.2.1: {} + min-indent@1.0.1: {} + minimatch@11.0.9: + dependencies: + '@isaacs/nonrecursive-glob-match': 1.1.0 + brace-expansion: 5.0.13 + + minipass@7.1.3: {} + + mj-context-menu@1.0.0: + dependencies: + rimraf: 6.1.4 + nanoid@3.3.20: {} obug@3.0.0: {} @@ -4051,6 +4182,8 @@ snapshots: '@oxlint/binding-win32-ia32-msvc': 1.89.0 '@oxlint/binding-win32-x64-msvc': 1.89.0 + package-json-from-dist@1.0.1: {} + package-manager-detector@1.9.0: {} parse5@8.0.1: @@ -4059,6 +4192,11 @@ snapshots: path-data-parser@0.1.0: {} + path-scurry@3.0.0: + dependencies: + lru-cache: 11.5.3 + minipass: 7.1.3 + picocolors@1.1.1: {} picomatch@4.0.7: {} @@ -4118,6 +4256,11 @@ snapshots: resolve-pkg-maps@1.0.0: {} + rimraf@6.1.4: + dependencies: + glob: 14.0.6 + package-json-from-dist: 1.0.1 + robust-predicates@3.0.3: {} rolldown@1.2.14: @@ -4164,6 +4307,12 @@ snapshots: source-map-js@1.2.2: {} + speech-rule-engine@5.0.0-rc.4: + dependencies: + '@xmldom/xmldom': 0.9.12 + commander: 14.0.3 + wicked-good-xpath: 1.3.0 + std-env@4.3.0: {} string-argv@0.3.2: {} @@ -4241,7 +4390,7 @@ snapshots: jiti: 2.7.0 yaml: 2.9.1 - vitest@5.0.5(@types/node@26.6.5)(jsdom@30.1.3)(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(yaml@2.9.1)): + vitest@5.0.5(@types/node@26.6.5)(jsdom@30.1.3(@noble/hashes@2.4.0))(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(yaml@2.9.1)): dependencies: '@types/chai': 5.2.3 '@vitest/mocker': 5.0.5(vite@8.3.4(@types/node@26.6.5)(jiti@2.7.0)(yaml@2.9.1)) @@ -4259,7 +4408,7 @@ snapshots: why-is-node-running: 3.2.1 optionalDependencies: '@types/node': 26.6.5 - jsdom: 30.1.3 + jsdom: 30.1.3(@noble/hashes@2.4.0) transitivePeerDependencies: - msw @@ -4275,9 +4424,9 @@ snapshots: whatwg-mimetype@5.0.0: {} - whatwg-url@17.3.0: + whatwg-url@17.3.0(@noble/hashes@2.4.0): dependencies: - '@exodus/bytes': 1.16.0 + '@exodus/bytes': 1.16.0(@noble/hashes@2.4.0) tr46: 7.0.0 webidl-conversions: 8.0.1 transitivePeerDependencies: @@ -4285,6 +4434,8 @@ snapshots: why-is-node-running@3.2.1: {} + wicked-good-xpath@1.3.0: {} + xml-name-validator@5.0.0: {} xmlchars@2.2.0: {} diff --git a/scripts/dogfood-remote.test.ts b/scripts/dogfood-remote.test.ts new file mode 100644 index 0000000000..93db678e93 --- /dev/null +++ b/scripts/dogfood-remote.test.ts @@ -0,0 +1,225 @@ +// @vitest-environment node +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { + BIN_MARK, + blake3Hex16, + buildSshArgs, + cleanLocalDogfoodServers, + extractFramedBinary, + formatSshConnectionError, + isRustVersionAtLeast, + loadSshConfigs, + normalizeRemotePlatform, + parseDogfoodRemoteArgs, + parseRunningServerPids, + parseToml, + readWorkspaceMetadata, + resolveAppDirs, + resolveSshConfig, + stageLocalDogfoodServer, + workspaceTarArgs, +} from "./dogfood-remote.ts"; + +function blake3TestInput(length: number): Uint8Array { + const buf = new Uint8Array(length); + for (let i = 0; i < length; i++) { + buf[i] = i % 251; + } + return buf; +} + +describe("dogfood:remote", () => { + it("computes the 16-character BLAKE3 build_id expected by remote_dev::ensure_server", () => { + // Reference vector (input[i] = i % 251, 2049 bytes -> multi-chunk tree) matching `blake3::hash(bytes).to_hex()[..16]`. + expect(blake3Hex16(blake3TestInput(2049))).toBe("5f4d72f40d7a5f82"); + }); + + it("parses both UI inline-table and [[ssh.configs]] TOML settings formats", () => { + const temp = mkdtempSync(join(tmpdir(), "openidea-dogfood-remote-")); + try { + const configDir = join(temp, "config"); + mkdirSync(configDir, { recursive: true }); + writeFileSync( + join(configDir, "settings.toml"), + [ + "# Global settings written by Settings › Tools › SSH Configurations", + "[appearance]", + 'locale = "en"', + "", + "[ssh]", + 'configs = [{ id = "cfg-1", name = "my-remote", host = "remote-host.example.com", port = 2222, user = "alice", auth = "keyPair", keyFile = "~/.ssh/id_ed25519", saveSecret = false }]', + "", + ].join("\n"), + ); + + const loaded = loadSshConfigs(configDir); + expect(loaded).toEqual([ + { + id: "cfg-1", + name: "my-remote", + host: "remote-host.example.com", + port: 2222, + user: "alice", + auth: "keyPair", + keyFile: "~/.ssh/id_ed25519", + }, + ]); + + const resolved = resolveSshConfig(loaded, "my-remote"); + expect(buildSshArgs(resolved, ["StrictHostKeyChecking=no"], "/Users/alice")).toEqual([ + "-p", + "2222", + "-l", + "alice", + "-i", + join("/Users/alice", ".ssh", "id_ed25519"), + "-o", + "ConnectTimeout=10", + "-o", + "StrictHostKeyChecking=no", + "--", + "remote-host.example.com", + ]); + + expect(() => resolveSshConfig(loaded, "missing-box")).toThrow(/Available SSH configurations: my-remote/); + + const tableDoc = parseToml( + ["[[ssh.configs]]", 'name = "alt-remote"', 'host = "alt.example.com"', 'user = "bob"', 'auth = "openSsh"'].join( + "\n", + ), + ); + expect(tableDoc).toEqual({ + ssh: { + configs: [{ name: "alt-remote", host: "alt.example.com", user: "bob", auth: "openSsh" }], + }, + }); + } finally { + rmSync(temp, { recursive: true, force: true }); + } + }); + + it("resolves config and custom local-data directories like ide_host::data_dirs", () => { + const temp = mkdtempSync(join(tmpdir(), "openidea-dirs-")); + try { + const cfgRoot = join(temp, "cfg"); + const customLocalRoot = join(temp, "custom-caches"); + mkdirSync(join(cfgRoot, "ai.l0ng.openidea"), { recursive: true }); + writeFileSync(join(cfgRoot, "ai.l0ng.openidea", "local-data-dir.txt"), `${customLocalRoot}\n`); + + expect( + resolveAppDirs({ + platform: "darwin", + env: { OPENIDEA_CONFIG_DIR: cfgRoot }, + home: "/Users/alice", + }), + ).toEqual({ + configDir: join(cfgRoot, "ai.l0ng.openidea"), + localDataDir: join(customLocalRoot, "ai.l0ng.openidea"), + }); + } finally { + rmSync(temp, { recursive: true, force: true }); + } + }); + + it("parses CLI flags and normalizes remote uname platforms", () => { + expect( + parseDogfoodRemoteArgs(["--", "my-remote", "--install-rust", "--restart", "--ssh-opt", "Port=2222"]), + ).toEqual({ + remoteName: "my-remote", + clean: false, + installRust: true, + restart: "always", + sshOpts: ["Port=2222"], + }); + expect(parseDogfoodRemoteArgs(["--clean"])).toEqual({ + remoteName: undefined, + clean: true, + installRust: false, + restart: "prompt", + sshOpts: [], + }); + expect(() => parseDogfoodRemoteArgs(["my-remote", "--restart", "--no-restart"])).toThrow(/Cannot pass both/); + expect(() => parseDogfoodRemoteArgs([])).toThrow(/Usage:/); + expect(normalizeRemotePlatform("Linux x86_64\n")).toEqual({ os: "linux", arch: "x86_64" }); + expect(normalizeRemotePlatform("Linux aarch64")).toEqual({ os: "linux", arch: "aarch64" }); + expect(normalizeRemotePlatform("Darwin arm64")).toEqual({ os: "macos", arch: "aarch64" }); + }); + + it("handles connection errors, Rust version checks, and running openidea-server PID detection", () => { + const repoRoot = join(import.meta.dirname, ".."); + const meta = readWorkspaceMetadata(repoRoot); + expect(meta.version).toMatch(/^\d+\.\d+\.\d+/); + expect(meta.rustVersion).toMatch(/^\d+\.\d+/); + + expect(isRustVersionAtLeast("rustc 1.96.0 (0000000 2026-06-01)", "1.96")).toBe(true); + expect(isRustVersionAtLeast("rustc 1.100.0-nightly (abcdef0 2026-11-01)", "1.96")).toBe(true); + expect(isRustVersionAtLeast("rustc 1.75.0 (82e1608df 2023-12-21)", "1.96")).toBe(false); + expect(isRustVersionAtLeast("no-rustc", "1.96")).toBe(false); + + const errMsg = formatSshConnectionError( + "my-remote", + "alice@remote-host.example.com:22", + "Warning: Permanently added 'remote-host.example.com' (ED25519) to the list of known hosts.\nssh: connect to host remote-host.example.com port 22: Connection refused\n", + 255, + ); + expect(errMsg).toContain("Cannot connect to SSH remote 'my-remote' (alice@remote-host.example.com:22)"); + expect(errMsg).toContain("Connection refused"); + expect(errMsg).not.toContain("Permanently added"); + + const psText = [ + " 101 /bin/bash", + " 4321 /home/alice/.openidea/server/0.1.50/42bd8ae098588d22/openidea-server --stdio", + " 4399 openidea-server --stdio", + " 4500 grep openidea-server", + ].join("\n"); + expect(parseRunningServerPids(psText)).toEqual([4321, 4399]); + }); + + it("backs up an existing cached release server on stage and restores it on --clean", () => { + const temp = mkdtempSync(join(tmpdir(), "openidea-stage-")); + try { + const serverDir = join(temp, "server", "0.1.50", "linux-aarch64"); + mkdirSync(serverDir, { recursive: true }); + const binPath = join(serverDir, "openidea-server"); + writeFileSync(binPath, "official-release-binary"); + + const dogfoodBytes = Buffer.from("dogfood-server-binary-v1"); + const id1 = blake3Hex16(dogfoodBytes); + stageLocalDogfoodServer(temp, "0.1.50", "linux", "aarch64", dogfoodBytes, id1); + expect(readFileSync(binPath, "utf8")).toBe("dogfood-server-binary-v1"); + + // A second dogfood build must keep the original release backup intact. + const dogfoodBytes2 = Buffer.from("dogfood-server-binary-v2"); + const id2 = blake3Hex16(dogfoodBytes2); + stageLocalDogfoodServer(temp, "0.1.50", "linux", "aarch64", dogfoodBytes2, id2); + expect(readFileSync(binPath, "utf8")).toBe("dogfood-server-binary-v2"); + + const cleaned = cleanLocalDogfoodServers(temp, "0.1.50", "linux-aarch64"); + expect(cleaned).toEqual([{ platformKey: "linux-aarch64", buildId: id2, restoredRelease: true }]); + expect(existsSync(binPath)).toBe(true); + expect(readFileSync(binPath, "utf8")).toBe("official-release-binary"); + } finally { + rmSync(temp, { recursive: true, force: true }); + } + }); + + it("strips login shell banners before the framed binary stream and verifies SHA-256", () => { + const payload = Buffer.from([0x7f, 0x45, 0x4c, 0x46, 1, 2, 3, 4]); + const sha = createHash("sha256").update(payload).digest("hex"); + const framed = Buffer.concat([Buffer.from(`Welcome to Ubuntu!\n${BIN_MARK}${sha}\n`, "utf8"), payload]); + expect(extractFramedBinary(framed)).toEqual(payload); + expect(() => extractFramedBinary(Buffer.from(`${BIN_MARK}${"0".repeat(64)}\ncorrupt`))).toThrow(/SHA-256 mismatch/); + }); + + it("anchors tar Cargo target exclusions so nested source folders like crates/ide-ssh/src/target stay included", () => { + const args = workspaceTarArgs(); + expect(args).not.toContain("--exclude=target"); + expect(args).toContain("--exclude=plugins/target"); + expect(args).toContain("crates"); + expect(args).toContain("generators"); + }); +}); diff --git a/scripts/dogfood-remote.ts b/scripts/dogfood-remote.ts new file mode 100644 index 0000000000..59b6c8d799 --- /dev/null +++ b/scripts/dogfood-remote.ts @@ -0,0 +1,1160 @@ +import { blake3 } from "@noble/hashes/blake3.js"; +import { spawn, spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { + chmodSync, + existsSync, + mkdirSync, + readdirSync, + readFileSync, + realpathSync, + renameSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { homedir } from "node:os"; +import { isAbsolute, join } from "node:path"; +import { createInterface } from "node:readline/promises"; +import { fileURLToPath } from "node:url"; + +export const APP_IDENTIFIER = "ai.l0ng.openidea"; +export const PROBE_MARK = "__OPENIDEA_DOGFOOD_PROBE__"; +export const BIN_MARK = "__OPENIDEA_DOGFOOD_BIN__:"; +export const DOGFOOD_MARKER_FILE = ".dogfood-build-id"; +export const RELEASE_BACKUP_FILE = "openidea-server.release.bak"; + +const SUPPORTED_PLATFORMS = new Set(["linux-x86_64", "linux-aarch64", "macos-aarch64", "macos-x86_64"]); + +const WORKSPACE_SYNC_PATHS = [ + "Cargo.toml", + "Cargo.lock", + "crates", + "src-tauri", + "generators", + "languages", + "java", + "plugins", + "sdk", + "wit", + "src", +] as const; + +export type SshAuthKind = "openSsh" | "keyPair" | "password"; + +export interface SshRemoteConfig { + id: string; + name: string; + host: string; + port?: number; + user: string; + auth: SshAuthKind; + keyFile: string; +} + +export type RestartPolicy = "prompt" | "always" | "never"; + +export interface DogfoodRemoteArgs { + remoteName?: string; + clean: boolean; + installRust: boolean; + restart: RestartPolicy; + sshOpts: string[]; +} + +export interface WorkspaceMetadata { + version: string; + rustVersion: string; +} + +export interface AppDirs { + configDir: string; + localDataDir: string; +} + +export function blake3Hex16(data: Uint8Array): string { + return Buffer.from(blake3(data)).toString("hex").slice(0, 16); +} + +// --- Minimal TOML reader for `settings.toml` and `Cargo.toml` --- + +type TomlTable = Record; + +class TomlCursor { + readonly text: string; + pos = 0; + + constructor(text: string) { + this.text = text; + } + + eof(): boolean { + return this.pos >= this.text.length; + } + + peek(offset = 0): string { + return this.text[this.pos + offset] ?? ""; + } + + skipInlineSpace() { + while (this.peek() === " " || this.peek() === "\t") { + this.pos++; + } + } + + skipBlankAndComments() { + while (!this.eof()) { + const ch = this.peek(); + if (ch === " " || ch === "\t" || ch === "\r" || ch === "\n") { + this.pos++; + } else if (ch === "#") { + while (!this.eof() && this.peek() !== "\n") this.pos++; + } else { + break; + } + } + } + + skipLineTail() { + this.skipInlineSpace(); + if (this.peek() === "#") { + while (!this.eof() && this.peek() !== "\n") this.pos++; + } + if (this.peek() === "\r") this.pos++; + if (this.peek() === "\n") this.pos++; + } + + readBasicString(multiline: boolean): string { + let out = ""; + if (multiline && this.peek() === "\r" && this.peek(1) === "\n") this.pos += 2; + else if (multiline && this.peek() === "\n") this.pos += 1; + + while (!this.eof()) { + if (multiline && this.text.startsWith('"""', this.pos)) { + this.pos += 3; + while (this.peek() === '"') { + out += '"'; + this.pos++; + } + return out; + } + if (!multiline && this.peek() === '"') { + this.pos++; + return out; + } + const ch = this.peek(); + this.pos++; + if (ch === "\\") { + const esc = this.peek(); + this.pos++; + if (multiline && (esc === "\n" || esc === "\r" || esc === " " || esc === "\t")) { + while (this.peek() === " " || this.peek() === "\t" || this.peek() === "\r" || this.peek() === "\n") { + this.pos++; + } + continue; + } + switch (esc) { + case "b": + out += "\b"; + break; + case "t": + out += "\t"; + break; + case "n": + out += "\n"; + break; + case "f": + out += "\f"; + break; + case "r": + out += "\r"; + break; + case '"': + out += '"'; + break; + case "\\": + out += "\\"; + break; + case "u": { + const hex = this.text.slice(this.pos, this.pos + 4); + this.pos += 4; + out += String.fromCodePoint(Number.parseInt(hex, 16)); + break; + } + case "U": { + const hex = this.text.slice(this.pos, this.pos + 8); + this.pos += 8; + out += String.fromCodePoint(Number.parseInt(hex, 16)); + break; + } + default: + out += esc; + } + } else { + out += ch; + } + } + throw new Error("Unterminated TOML basic string"); + } + + readLiteralString(multiline: boolean): string { + if (multiline && this.peek() === "\r" && this.peek(1) === "\n") this.pos += 2; + else if (multiline && this.peek() === "\n") this.pos += 1; + let out = ""; + while (!this.eof()) { + if (multiline && this.text.startsWith("'''", this.pos)) { + this.pos += 3; + return out; + } + if (!multiline && this.peek() === "'") { + this.pos++; + return out; + } + out += this.peek(); + this.pos++; + } + throw new Error("Unterminated TOML literal string"); + } + + readKeySegment(): string { + this.skipInlineSpace(); + if (this.peek() === '"') { + this.pos++; + return this.readBasicString(false); + } + if (this.peek() === "'") { + this.pos++; + return this.readLiteralString(false); + } + const start = this.pos; + while (!this.eof() && /[A-Za-z0-9_-]/.test(this.peek())) { + this.pos++; + } + const key = this.text.slice(start, this.pos); + if (!key) throw new Error(`Expected TOML key at offset ${this.pos}`); + return key; + } + + readDottedKey(): string[] { + const parts = [this.readKeySegment()]; + while (true) { + this.skipInlineSpace(); + if (this.peek() !== ".") break; + this.pos++; + parts.push(this.readKeySegment()); + } + return parts; + } + + readValue(): unknown { + this.skipInlineSpace(); + if (this.text.startsWith('"""', this.pos)) { + this.pos += 3; + return this.readBasicString(true); + } + if (this.text.startsWith("'''", this.pos)) { + this.pos += 3; + return this.readLiteralString(true); + } + if (this.peek() === '"') { + this.pos++; + return this.readBasicString(false); + } + if (this.peek() === "'") { + this.pos++; + return this.readLiteralString(false); + } + if (this.peek() === "[") { + this.pos++; + const items: unknown[] = []; + while (true) { + this.skipBlankAndComments(); + if (this.peek() === "]") { + this.pos++; + return items; + } + items.push(this.readValue()); + this.skipBlankAndComments(); + if (this.peek() === ",") { + this.pos++; + continue; + } + if (this.peek() === "]") { + this.pos++; + return items; + } + throw new Error(`Expected ',' or ']' in TOML array at offset ${this.pos}`); + } + } + if (this.peek() === "{") { + this.pos++; + const table: TomlTable = {}; + while (true) { + this.skipBlankAndComments(); + if (this.peek() === "}") { + this.pos++; + return table; + } + const key = this.readDottedKey(); + this.skipInlineSpace(); + if (this.peek() !== "=") throw new Error(`Expected '=' in inline table at offset ${this.pos}`); + this.pos++; + setDotted(table, key, this.readValue()); + this.skipBlankAndComments(); + if (this.peek() === ",") { + this.pos++; + continue; + } + if (this.peek() === "}") { + this.pos++; + return table; + } + throw new Error(`Expected ',' or '}' in inline table at offset ${this.pos}`); + } + } + + const start = this.pos; + while (!this.eof() && !/[\s,\]}#]/.test(this.peek())) { + this.pos++; + } + const raw = this.text.slice(start, this.pos); + if (raw === "true") return true; + if (raw === "false") return false; + const cleaned = raw.replaceAll("_", ""); + if (/^[+-]?(0x[0-9a-fA-F]+|0o[0-7]+|0b[01]+|\d+(\.\d+)?([eE][+-]?\d+)?)$/.test(cleaned)) { + return Number(cleaned); + } + return raw; + } +} + +function isRecord(value: unknown): value is TomlTable { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function ensureTable(root: TomlTable, path: readonly string[]): TomlTable { + let cursor = root; + for (const segment of path) { + const existing = cursor[segment]; + if (Array.isArray(existing)) { + const last = existing[existing.length - 1]; + if (!isRecord(last)) throw new Error(`TOML path '${path.join(".")}' conflicts with non-table array`); + cursor = last; + } else if (isRecord(existing)) { + cursor = existing; + } else if (existing === undefined) { + const next: TomlTable = {}; + cursor[segment] = next; + cursor = next; + } else { + throw new Error(`TOML path '${path.join(".")}' conflicts with scalar value`); + } + } + return cursor; +} + +function setDotted(target: TomlTable, path: readonly string[], value: unknown) { + const parent = ensureTable(target, path.slice(0, -1)); + const last = path[path.length - 1]!; + parent[last] = value; +} + +export function parseToml(text: string): TomlTable { + const root: TomlTable = {}; + let current: TomlTable = root; + const cursor = new TomlCursor(text); + + while (!cursor.eof()) { + cursor.skipBlankAndComments(); + if (cursor.eof()) break; + + if (cursor.text.startsWith("[[", cursor.pos)) { + cursor.pos += 2; + const path = cursor.readDottedKey(); + cursor.skipInlineSpace(); + if (!cursor.text.startsWith("]]", cursor.pos)) { + throw new Error(`Expected ']]' at offset ${cursor.pos}`); + } + cursor.pos += 2; + cursor.skipLineTail(); + const parent = ensureTable(root, path.slice(0, -1)); + const last = path[path.length - 1]!; + const existing = parent[last]; + const entry: TomlTable = {}; + if (existing === undefined) { + parent[last] = [entry]; + } else if (Array.isArray(existing)) { + existing.push(entry); + } else { + throw new Error(`TOML array table '${path.join(".")}' conflicts with existing key`); + } + current = entry; + continue; + } + + if (cursor.peek() === "[") { + cursor.pos += 1; + const path = cursor.readDottedKey(); + cursor.skipInlineSpace(); + if (cursor.peek() !== "]") { + throw new Error(`Expected ']' at offset ${cursor.pos}`); + } + cursor.pos += 1; + cursor.skipLineTail(); + current = ensureTable(root, path); + continue; + } + + const key = cursor.readDottedKey(); + cursor.skipInlineSpace(); + if (cursor.peek() !== "=") { + throw new Error(`Expected '=' after '${key.join(".")}' at offset ${cursor.pos}`); + } + cursor.pos += 1; + const value = cursor.readValue(); + setDotted(current, key, value); + cursor.skipLineTail(); + } + + return root; +} + +// --- Configuration, paths, and SSH command building --- + +function resolveEnvDir(envName: string, envValue: string | undefined, osDefault: string, identifier: string): string { + const trimmed = envValue?.trim(); + if (!trimmed) return join(osDefault, identifier); + if (!isAbsolute(trimmed)) { + throw new Error(`${envName} must be an absolute path: ${trimmed}`); + } + return join(trimmed, identifier); +} + +export function resolveAppDirs(options?: { + platform?: NodeJS.Platform; + env?: NodeJS.ProcessEnv; + home?: string; + identifier?: string; +}): AppDirs { + const platform = options?.platform ?? process.platform; + const env = options?.env ?? process.env; + const home = options?.home ?? homedir(); + const identifier = options?.identifier ?? APP_IDENTIFIER; + + let osConfig: string; + let osLocalData: string; + if (platform === "darwin") { + osConfig = join(home, "Library", "Application Support"); + osLocalData = osConfig; + } else if (platform === "win32") { + osConfig = env.APPDATA?.trim() || join(home, "AppData", "Roaming"); + osLocalData = env.LOCALAPPDATA?.trim() || join(home, "AppData", "Local"); + } else { + osConfig = env.XDG_CONFIG_HOME?.trim() || join(home, ".config"); + osLocalData = env.XDG_DATA_HOME?.trim() || join(home, ".local", "share"); + } + + const configDir = resolveEnvDir("OPENIDEA_CONFIG_DIR", env.OPENIDEA_CONFIG_DIR, osConfig, identifier); + + const localEnv = env.OPENIDEA_LOCAL_DATA_DIR?.trim(); + if (localEnv) { + return { + configDir, + localDataDir: resolveEnvDir("OPENIDEA_LOCAL_DATA_DIR", localEnv, osLocalData, identifier), + }; + } + + const overrideFile = join(configDir, "local-data-dir.txt"); + if (existsSync(overrideFile)) { + const stored = readFileSync(overrideFile, "utf8").trim(); + if (stored) { + if (!isAbsolute(stored)) { + throw new Error(`custom local data directory must be an absolute path: ${stored}`); + } + return { configDir, localDataDir: join(stored, identifier) }; + } + } + + return { configDir, localDataDir: join(osLocalData, identifier) }; +} + +function parseSshConfigEntry(raw: unknown): SshRemoteConfig | undefined { + if (!isRecord(raw)) return undefined; + const name = typeof raw.name === "string" ? raw.name.trim() : ""; + const id = typeof raw.id === "string" ? raw.id.trim() : ""; + const host = typeof raw.host === "string" ? raw.host.trim() : ""; + if (!name && !id) return undefined; + const port = typeof raw.port === "number" && Number.isInteger(raw.port) && raw.port > 0 ? raw.port : undefined; + const user = typeof raw.user === "string" ? raw.user.trim() : ""; + const auth: SshAuthKind = + raw.auth === "keyPair" || raw.auth === "password" || raw.auth === "openSsh" ? raw.auth : "openSsh"; + const keyFile = typeof raw.keyFile === "string" ? raw.keyFile.trim() : ""; + return { id, name: name || id, host, port, user, auth, keyFile }; +} + +function readSshConfigsFromFile(settingsFile: string): SshRemoteConfig[] | undefined { + if (!existsSync(settingsFile)) return undefined; + const doc = parseToml(readFileSync(settingsFile, "utf8")); + const ssh = doc.ssh; + if (!isRecord(ssh) || !Array.isArray(ssh.configs)) return undefined; + return ssh.configs.map(parseSshConfigEntry).filter((entry): entry is SshRemoteConfig => entry !== undefined); +} + +export function loadSshConfigs(configDir: string, projectRoot?: string): SshRemoteConfig[] { + const globalConfigs = readSshConfigsFromFile(join(configDir, "settings.toml")); + const projectConfigs = projectRoot + ? readSshConfigsFromFile(join(projectRoot, ".openidea", "settings.toml")) + : undefined; + return projectConfigs ?? globalConfigs ?? []; +} + +export function resolveSshConfig(configs: readonly SshRemoteConfig[], remoteName: string): SshRemoteConfig { + const target = remoteName.trim(); + const match = configs.find((c) => c.name === target) ?? configs.find((c) => c.id === target); + if (!match) { + const available = configs.map((c) => c.name).filter(Boolean); + const listHint = + available.length > 0 + ? `Available SSH configurations: ${available.join(", ")}` + : "No SSH configurations found in Settings › Tools › SSH Configurations (settings.toml)."; + throw new Error(`SSH configuration '${target}' not found. ${listHint}`); + } + if (!match.host) { + throw new Error(`SSH configuration '${match.name}' has an empty host`); + } + return match; +} + +export function expandTilde(filePath: string, home = homedir()): string { + if (filePath === "~") return home; + if (filePath.startsWith("~/") || filePath.startsWith("~\\")) { + return join(home, filePath.slice(2)); + } + return filePath; +} + +export function formatRemoteEndpoint(config: SshRemoteConfig): string { + const userPrefix = config.user ? `${config.user}@` : ""; + const portSuffix = config.port !== undefined ? `:${config.port}` : ""; + return `${userPrefix}${config.host}${portSuffix}`; +} + +export function buildSshArgs( + config: SshRemoteConfig, + extraSshOpts: readonly string[] = [], + home = homedir(), +): string[] { + const args: string[] = []; + if (config.port !== undefined) { + args.push("-p", String(config.port)); + } + if (config.user) { + args.push("-l", config.user); + } + if (config.auth === "keyPair" && config.keyFile) { + args.push("-i", expandTilde(config.keyFile, home)); + } + const hasConnectTimeout = extraSshOpts.some((opt) => /^ConnectTimeout\s*=/i.test(opt)); + if (!hasConnectTimeout) { + args.push("-o", "ConnectTimeout=10"); + } + for (const opt of extraSshOpts) { + args.push("-o", opt); + } + args.push("--", config.host); + return args; +} + +export function parseRustVersion(versionOutput: string): [number, number, number] | undefined { + const match = /(?:^|\b)rustc\s+(\d+)\.(\d+)(?:\.(\d+))?|^(\d+)\.(\d+)(?:\.(\d+))?/.exec(versionOutput.trim()); + if (!match) return undefined; + const major = Number(match[1] ?? match[4]); + const minor = Number(match[2] ?? match[5]); + const patch = Number(match[3] ?? match[6] ?? "0"); + if (!Number.isInteger(major) || !Number.isInteger(minor) || !Number.isInteger(patch)) return undefined; + return [major, minor, patch]; +} + +export function isRustVersionAtLeast(actualOutput: string, minimumRequired: string): boolean { + const actual = parseRustVersion(actualOutput); + const minimum = parseRustVersion(minimumRequired); + if (!actual || !minimum) return false; + for (let i = 0; i < 3; i++) { + if (actual[i]! > minimum[i]!) return true; + if (actual[i]! < minimum[i]!) return false; + } + return true; +} + +export function parseRunningServerPids(psOutput: string): number[] { + const pids = new Set(); + for (const rawLine of psOutput.split(/\r?\n/)) { + const line = rawLine.trim(); + if (!line) continue; + const match = /^(\d+)\s+(\S+)(?:\s+(.*))?$/.exec(line); + if (!match) continue; + const pid = Number(match[1]); + const exe = match[2] ?? ""; + if (!Number.isInteger(pid) || pid <= 0) continue; + if (exe === "openidea-server" || exe.endsWith("/openidea-server")) { + pids.add(pid); + } + } + return [...pids].sort((a, b) => a - b); +} + +export function formatSshConnectionError( + remoteName: string, + endpoint: string, + stderrText: string, + status: number | null, +): string { + const detail = stderrText + .split(/\r?\n/) + .map((line) => line.trim()) + .filter((line) => line.length > 0 && !line.startsWith("Warning: Permanently added ")) + .join("; "); + const reason = detail || `ssh exited with status ${status ?? "unknown"}`; + return `Cannot connect to SSH remote '${remoteName}' (${endpoint}): ${reason}. Verify the host is reachable and check Settings › Tools › SSH Configurations.`; +} + +export function normalizeRemotePlatform(uname: string): { os: string; arch: string } { + const parts = uname.trim().split(/\s+/); + const rawOs = (parts[0] ?? "").toLowerCase(); + const rawArch = parts[1] ?? ""; + const os = rawOs === "darwin" ? "macos" : rawOs; + const arch = rawArch === "arm64" ? "aarch64" : rawArch === "amd64" ? "x86_64" : rawArch; + const key = `${os}-${arch}`; + if (!SUPPORTED_PLATFORMS.has(key)) { + throw new Error(`Unsupported remote platform '${key}' (from uname '${uname.trim()}')`); + } + return { os, arch }; +} + +export function parseDogfoodRemoteArgs(args: readonly string[]): DogfoodRemoteArgs { + const filtered = args.filter((arg) => arg !== "--"); + let remoteName: string | undefined; + let clean = false; + let installRust = false; + let sawRestart = false; + let sawNoRestart = false; + const sshOpts: string[] = []; + + for (let i = 0; i < filtered.length; i++) { + const arg = filtered[i]!; + if (arg === "--clean") { + clean = true; + } else if (arg === "--install-rust") { + installRust = true; + } else if (arg === "--restart") { + sawRestart = true; + } else if (arg === "--no-restart") { + sawNoRestart = true; + } else if (arg === "--ssh-opt") { + const value = filtered[i + 1]; + if (!value) throw new Error("--ssh-opt requires a key=value argument"); + sshOpts.push(value); + i += 1; + } else if (arg.startsWith("--ssh-opt=")) { + sshOpts.push(arg.slice("--ssh-opt=".length)); + } else if (arg.startsWith("-")) { + throw new Error(`Unexpected option '${arg}'`); + } else if (remoteName === undefined) { + remoteName = arg; + } else { + throw new Error(`Unexpected extra argument '${arg}'`); + } + } + + if (sawRestart && sawNoRestart) { + throw new Error("Cannot pass both '--restart' and '--no-restart'"); + } + + if (!remoteName && !clean) { + throw new Error( + "Usage: dogfood:remote [--clean] [--install-rust] [--restart | --no-restart] [--ssh-opt key=value]", + ); + } + + const restart: RestartPolicy = sawRestart ? "always" : sawNoRestart ? "never" : "prompt"; + return { remoteName, clean, installRust, restart, sshOpts }; +} + +export function readWorkspaceMetadata(root: string): WorkspaceMetadata { + const cargoToml = parseToml(readFileSync(join(root, "Cargo.toml"), "utf8")); + const workspace = cargoToml.workspace; + if (isRecord(workspace) && isRecord(workspace.package)) { + const version = workspace.package.version; + const rustVersion = workspace.package["rust-version"]; + if (typeof version === "string" && typeof rustVersion === "string") { + return { version, rustVersion }; + } + } + throw new Error("Could not read [workspace.package].version and rust-version from Cargo.toml"); +} + +// --- Local server cache staging & clean restoration --- + +export function stageLocalDogfoodServer( + localDataDir: string, + version: string, + os: string, + arch: string, + binary: Uint8Array, + buildId: string, +): string { + const dir = join(localDataDir, "server", version, `${os}-${arch}`); + mkdirSync(dir, { recursive: true }); + const binPath = join(dir, "openidea-server"); + const backupPath = join(dir, RELEASE_BACKUP_FILE); + const markerPath = join(dir, DOGFOOD_MARKER_FILE); + + if (existsSync(binPath) && !existsSync(markerPath) && !existsSync(backupPath)) { + renameSync(binPath, backupPath); + } + + const tmpPath = join(dir, `.openidea-server.${process.pid}.tmp`); + writeFileSync(tmpPath, binary); + chmodSync(tmpPath, 0o755); + renameSync(tmpPath, binPath); + writeFileSync(markerPath, `${buildId}\n`); + return binPath; +} + +export interface CleanedOverride { + platformKey: string; + buildId: string; + restoredRelease: boolean; +} + +export function cleanLocalDogfoodServers( + localDataDir: string, + version: string, + platformKeyFilter?: string, +): CleanedOverride[] { + const versionDir = join(localDataDir, "server", version); + if (!existsSync(versionDir)) return []; + const cleaned: CleanedOverride[] = []; + + for (const entry of readdirSync(versionDir, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + if (platformKeyFilter && entry.name !== platformKeyFilter) continue; + const dir = join(versionDir, entry.name); + const markerPath = join(dir, DOGFOOD_MARKER_FILE); + if (!existsSync(markerPath)) continue; + + const buildId = readFileSync(markerPath, "utf8").trim(); + const binPath = join(dir, "openidea-server"); + const backupPath = join(dir, RELEASE_BACKUP_FILE); + + rmSync(binPath, { force: true }); + rmSync(markerPath, { force: true }); + let restoredRelease = false; + if (existsSync(backupPath)) { + renameSync(backupPath, binPath); + restoredRelease = true; + } + cleaned.push({ platformKey: entry.name, buildId, restoredRelease }); + } + return cleaned; +} + +export function extractFramedBinary(stdout: Buffer): Buffer { + const markerBytes = Buffer.from(BIN_MARK, "utf8"); + const idx = stdout.indexOf(markerBytes); + if (idx === -1) { + throw new Error("Remote stream did not contain openidea-server binary header"); + } + const headerStart = idx + markerBytes.length; + const newline = stdout.indexOf(0x0a, headerStart); + if (newline === -1) { + throw new Error("Malformed openidea-server binary header"); + } + const expectedSha256 = stdout.subarray(headerStart, newline).toString("utf8").trim(); + const payload = stdout.subarray(newline + 1); + const actualSha256 = createHash("sha256").update(payload).digest("hex"); + if (actualSha256 !== expectedSha256) { + throw new Error(`Downloaded openidea-server SHA-256 mismatch: expected ${expectedSha256}, got ${actualSha256}`); + } + return payload; +} + +// --- Remote execution helpers --- + +function shellQuote(value: string): string { + return `'${value.replaceAll("'", "'\\''")}'`; +} + +interface RemoteContext { + name: string; + endpoint: string; +} + +const REMOTE_PATH_SETUP = `export PATH="$HOME/.cargo/bin:$HOME/.local/share/mise/shims:$PATH"; . "$HOME/.cargo/env" 2>/dev/null || true`; + +function runSshCapture(sshArgs: readonly string[], remoteScript: string, remote?: RemoteContext): Buffer { + const result = spawnSync("ssh", [...sshArgs, remoteScript], { + stdio: ["ignore", "pipe", "pipe"], + maxBuffer: 512 * 1024 * 1024, + }); + if (result.error) { + if (remote) { + throw new Error(formatSshConnectionError(remote.name, remote.endpoint, result.error.message, null)); + } + throw result.error; + } + if (result.status !== 0) { + const stderrText = result.stderr?.toString("utf8") ?? ""; + if (remote && result.status === 255) { + throw new Error(formatSshConnectionError(remote.name, remote.endpoint, stderrText, result.status)); + } + const detail = stderrText.trim(); + throw new Error( + `Remote command${remote ? ` on '${remote.name}'` : ""} exited with status ${result.status}${detail ? `: ${detail}` : ""}`, + ); + } + return result.stdout; +} + +function runSshInteractive(sshArgs: readonly string[], remoteScript: string, remote?: RemoteContext) { + const result = spawnSync("ssh", [...sshArgs, remoteScript], { + stdio: "inherit", + }); + if (result.error) { + if (remote) { + throw new Error(formatSshConnectionError(remote.name, remote.endpoint, result.error.message, null)); + } + throw result.error; + } + if (result.status !== 0) { + if (remote && result.status === 255) { + throw new Error(formatSshConnectionError(remote.name, remote.endpoint, "", result.status)); + } + throw new Error(`Remote command${remote ? ` on '${remote.name}'` : ""} exited with status ${result.status}`); + } +} + +export function workspaceTarArgs(): string[] { + // Never pass bare `--exclude=target`: BSD/GNU tar matches nested source folders like `crates/ide-ssh/src/target`. + return [ + "--exclude=plugins/target", + "--exclude=sdk/target", + "--exclude=src-tauri/target", + "--exclude=plugins/official/*/web-src/node_modules", + "--exclude=.DS_Store", + "--exclude=*.tsbuildinfo", + "-czf", + "-", + ...WORKSPACE_SYNC_PATHS, + ]; +} + +async function syncWorkspaceOverSsh(root: string, sshArgs: readonly string[], remoteCacheRoot: string) { + const cleanSubdirs = WORKSPACE_SYNC_PATHS.filter((p) => p !== "Cargo.toml" && p !== "Cargo.lock").join(" "); + // Extract into a staging folder and sync by checksum via `rsync -rc` when available so unchanged + // crates and asset directories keep their mtimes and Cargo only recompiles touched crates. + const remoteScript = [ + `set -eu`, + `stage=${remoteCacheRoot}/staging.$$`, + `ws=${remoteCacheRoot}/workspace`, + `rm -rf "$stage"`, + `mkdir -p "$stage" "$ws"`, + `tar xzf - -C "$stage"`, + `if command -v rsync >/dev/null 2>&1; then`, + ` rsync -rc --delete --exclude='/target' "$stage/" "$ws/"`, + `else`, + ` (cd "$ws" && rm -rf ${cleanSubdirs})`, + ` cp -RPp "$stage/." "$ws/"`, + `fi`, + `rm -rf "$stage"`, + ].join("\n"); + const tarArgs = workspaceTarArgs(); + + await new Promise((resolve, reject) => { + const tar = spawn("tar", tarArgs, { + cwd: root, + env: { ...process.env, COPYFILE_DISABLE: "1" }, + stdio: ["ignore", "pipe", "inherit"], + }); + const ssh = spawn("ssh", [...sshArgs, remoteScript], { + stdio: ["pipe", "inherit", "inherit"], + }); + + ssh.stdin.on("error", () => {}); + tar.stdout.pipe(ssh.stdin); + let tarCode: number | null = null; + let sshCode: number | null = null; + let settled = false; + + const fail = (err: Error) => { + if (settled) return; + settled = true; + tar.kill(); + ssh.kill(); + reject(err); + }; + const maybeDone = () => { + if (settled || tarCode === null || sshCode === null) return; + settled = true; + if (tarCode !== 0) reject(new Error(`tar exited with status ${tarCode}`)); + else if (sshCode !== 0) reject(new Error(`ssh tar extract exited with status ${sshCode}`)); + else resolve(); + }; + + tar.once("error", fail); + ssh.once("error", fail); + tar.once("close", (code) => { + tarCode = code ?? 1; + if (tarCode !== 0) fail(new Error(`tar exited with status ${tarCode}`)); + else maybeDone(); + }); + ssh.once("close", (code) => { + sshCode = code ?? 1; + if (sshCode !== 0) fail(new Error(`ssh tar extract exited with status ${sshCode}`)); + else maybeDone(); + }); + }); +} + +interface RemoteProbe { + os: string; + arch: string; + hasCargo: boolean; + rustcVersion?: string; + hasRustup: boolean; +} + +function extractMarkedLines(raw: string): string[] { + const after = raw.includes(PROBE_MARK) ? raw.slice(raw.indexOf(PROBE_MARK) + PROBE_MARK.length) : raw; + return after + .split(/\r?\n/) + .map((l) => l.trim()) + .filter(Boolean); +} + +function probeRemote(sshArgs: readonly string[], remote: RemoteContext): RemoteProbe { + const script = [ + REMOTE_PATH_SETUP, + `printf '${PROBE_MARK}\\n'`, + `uname -sm`, + `if command -v cargo >/dev/null 2>&1; then echo has-cargo; else echo no-cargo; fi`, + `rustc --version 2>/dev/null || echo no-rustc`, + `if command -v rustup >/dev/null 2>&1; then echo has-rustup; else echo no-rustup; fi`, + ].join("; "); + const lines = extractMarkedLines(runSshCapture(sshArgs, script, remote).toString("utf8")); + const { os, arch } = normalizeRemotePlatform(lines[0] ?? ""); + const hasCargo = lines[1] === "has-cargo"; + const rustcRaw = lines[2] ?? "no-rustc"; + const rustcVersion = rustcRaw === "no-rustc" ? undefined : rustcRaw; + const hasRustup = lines[3] === "has-rustup"; + return { os, arch, hasCargo, rustcVersion, hasRustup }; +} + +function ensureRemoteRustToolchain( + sshArgs: readonly string[], + remote: RemoteContext, + probe: RemoteProbe, + requiredRustVersion: string, + installRust: boolean, +) { + if (probe.hasCargo && probe.rustcVersion && isRustVersionAtLeast(probe.rustcVersion, requiredRustVersion)) { + return; + } + + if (!probe.hasCargo || !probe.rustcVersion) { + if (!installRust) { + throw new Error( + `Rust toolchain ('cargo'/'rustc' >= ${requiredRustVersion}) is not installed on '${remote.name}'. Install Rust on the remote host or re-run with '--install-rust'.`, + ); + } + console.log(`Installing minimal Rust toolchain on '${remote.name}'...`); + runSshInteractive( + sshArgs, + `curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal`, + remote, + ); + } else { + if (!installRust) { + const hint = probe.hasRustup + ? `Run 'rustup update stable' on '${remote.name}' or re-run with '--install-rust'.` + : `Update Rust on '${remote.name}' or re-run with '--install-rust' to install a current toolchain in ~/.cargo.`; + throw new Error( + `Rust on '${remote.name}' is too old (${probe.rustcVersion}; Cargo.toml requires rust-version >= ${requiredRustVersion}). ${hint}`, + ); + } + if (probe.hasRustup) { + console.log(`Updating Rust stable toolchain on '${remote.name}' (found ${probe.rustcVersion})...`); + runSshInteractive( + sshArgs, + `${REMOTE_PATH_SETUP}; rustup toolchain install stable --profile minimal && rustup default stable`, + remote, + ); + } else { + console.log( + `Installing current Rust toolchain into ~/.cargo on '${remote.name}' (found ${probe.rustcVersion})...`, + ); + runSshInteractive( + sshArgs, + `curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal`, + remote, + ); + } + } + + const updated = probeRemote(sshArgs, remote); + if (!updated.hasCargo || !updated.rustcVersion || !isRustVersionAtLeast(updated.rustcVersion, requiredRustVersion)) { + throw new Error( + `Rust on '${remote.name}' still does not meet rust-version >= ${requiredRustVersion} (active: ${updated.rustcVersion ?? "none"}). Check remote PATH precedence.`, + ); + } +} + +function listRunningRemoteServers(sshArgs: readonly string[], remote: RemoteContext): number[] { + const script = `printf '${PROBE_MARK}\\n'; ps -u "$(id -u)" -o pid=,args= 2>/dev/null || true`; + const raw = runSshCapture(sshArgs, script, remote).toString("utf8"); + const after = raw.includes(PROBE_MARK) ? raw.slice(raw.indexOf(PROBE_MARK) + PROBE_MARK.length) : raw; + return parseRunningServerPids(after); +} + +async function askYesNo(promptText: string): Promise { + const rl = createInterface({ input: process.stdin, output: process.stdout }); + try { + const answer = await rl.question(promptText); + return /^y(es)?$/i.test(answer.trim()); + } finally { + rl.close(); + } +} + +async function handleRunningRemoteServers( + sshArgs: readonly string[], + remote: RemoteContext, + buildId: string, + policy: RestartPolicy, +) { + const runningPids = listRunningRemoteServers(sshArgs, remote); + if (runningPids.length === 0) return; + + const pidList = runningPids.join(", "); + let shouldRestart = false; + if (policy === "always") { + shouldRestart = true; + } else if (policy === "never") { + shouldRestart = false; + } else if (process.stdin.isTTY && process.stdout.isTTY) { + shouldRestart = await askYesNo( + `Found ${runningPids.length} running openidea-server instance(s) on '${remote.name}' (PID ${pidList}). Stop them now so connected OpenIDEA windows reconnect to build ${buildId}? [y/N] `, + ); + } + + if (shouldRestart) { + runSshInteractive(sshArgs, `kill ${runningPids.join(" ")} 2>/dev/null || true`, remote); + console.log( + `Stopped running openidea-server instance(s) (PID ${pidList}) on '${remote.name}'; connected OpenIDEA windows will reconnect to build ${buildId}.`, + ); + } else { + console.log( + `Note: ${runningPids.length} openidea-server instance(s) still running on '${remote.name}' (PID ${pidList}). Reconnect in OpenIDEA (or re-run with '--restart') to switch active windows to build ${buildId}.`, + ); + } +} + +export async function runDogfoodRemote(root: string, cliArgs: readonly string[]) { + const parsed = parseDogfoodRemoteArgs(cliArgs); + const { version, rustVersion } = readWorkspaceMetadata(root); + const { configDir, localDataDir } = resolveAppDirs(); + + const envOpts = (process.env.DOGFOOD_SSH_OPTS ?? "") + .split(",") + .map((s) => s.trim()) + .filter(Boolean); + const extraSshOpts = [...envOpts, ...parsed.sshOpts]; + + if (parsed.clean && !parsed.remoteName) { + const cleaned = cleanLocalDogfoodServers(localDataDir, version); + if (cleaned.length === 0) { + console.log(`No local dogfood openidea-server overrides found for v${version}`); + } else { + for (const item of cleaned) { + console.log( + `Removed local dogfood override for ${item.platformKey} (${item.buildId})${item.restoredRelease ? " and restored cached release binary" : ""}`, + ); + } + } + return; + } + + const configs = loadSshConfigs(configDir, root); + const remoteConfig = resolveSshConfig(configs, parsed.remoteName!); + const remoteContext: RemoteContext = { + name: remoteConfig.name, + endpoint: formatRemoteEndpoint(remoteConfig), + }; + const sshArgs = buildSshArgs(remoteConfig, extraSshOpts); + const probe = probeRemote(sshArgs, remoteContext); + const { os, arch } = probe; + const platformKey = `${os}-${arch}`; + + if (parsed.clean) { + const cleaned = cleanLocalDogfoodServers(localDataDir, version, platformKey); + for (const item of cleaned) { + if (/^[0-9a-f]{16}$/.test(item.buildId)) { + runSshInteractive(sshArgs, `rm -rf "$HOME/.openidea/server/${version}/${item.buildId}"`, remoteContext); + } + console.log( + `Cleaned dogfood openidea-server (${item.buildId}) for ${remoteConfig.name} (${platformKey})${item.restoredRelease ? " and restored cached release binary" : ""}`, + ); + } + if (cleaned.length === 0) { + console.log(`No dogfood openidea-server override found for ${remoteConfig.name} (${platformKey}, v${version})`); + } + return; + } + + ensureRemoteRustToolchain(sshArgs, remoteContext, probe, rustVersion, parsed.installRust); + + const remoteCacheRoot = '"$HOME/.cache/openidea-dogfood"'; + console.log(`Syncing backend workspace to '${remoteConfig.name}' (${platformKey})...`); + await syncWorkspaceOverSsh(root, sshArgs, remoteCacheRoot); + + const lto = process.env.CARGO_PROFILE_RELEASE_LTO ?? "off"; + const codegenUnits = process.env.CARGO_PROFILE_RELEASE_CODEGEN_UNITS ?? "16"; + console.log(`Building openidea-server v${version} on '${remoteConfig.name}'...`); + runSshInteractive( + sshArgs, + `${REMOTE_PATH_SETUP}; cd "$HOME/.cache/openidea-dogfood/workspace" && CARGO_PROFILE_RELEASE_LTO=${shellQuote(lto)} CARGO_PROFILE_RELEASE_CODEGEN_UNITS=${shellQuote(codegenUnits)} cargo build --release --locked -p ide-host --bin openidea-server`, + remoteContext, + ); + + console.log(`Fetching built openidea-server from '${remoteConfig.name}'...`); + const rawStream = runSshCapture( + sshArgs, + `bin="$HOME/.cache/openidea-dogfood/workspace/target/release/openidea-server"; sum="$( (sha256sum "$bin" 2>/dev/null || shasum -a 256 "$bin") | awk '{print $1}' )"; printf '${BIN_MARK}%s\\n' "$sum"; cat "$bin"`, + remoteContext, + ); + const binary = extractFramedBinary(rawStream); + const buildId = blake3Hex16(binary); + + console.log(`Installing openidea-server (${buildId}) on '${remoteConfig.name}'...`); + runSshInteractive( + sshArgs, + `set -eu; dir="$HOME/.openidea/server/${version}"; dest="$dir/${buildId}"; mkdir -p "$dest"; tmp="$dest/openidea-server.$$.part"; cp "$HOME/.cache/openidea-dogfood/workspace/target/release/openidea-server" "$tmp"; chmod 755 "$tmp"; mv -f "$tmp" "$dest/openidea-server"; find "$dir" -mindepth 1 -maxdepth 1 ! -name ${shellQuote(buildId)} -exec rm -rf {} +`, + remoteContext, + ); + + const stagedPath = stageLocalDogfoodServer(localDataDir, version, os, arch, binary, buildId); + console.log( + `Installed dogfood openidea-server v${version} (${buildId}) on '${remoteConfig.name}' (~/.openidea/server/${version}/${buildId}/openidea-server) and staged ${stagedPath}`, + ); + + await handleRunningRemoteServers(sshArgs, remoteContext, buildId, parsed.restart); +} + +if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) { + try { + const root = realpathSync(fileURLToPath(new URL("..", import.meta.url))); + await runDogfoodRemote(root, process.argv.slice(2)); + } catch (error) { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; + } +} diff --git a/smoke/run.test.ts b/smoke/run.test.ts index 6be950dca6..3b16844be5 100644 --- a/smoke/run.test.ts +++ b/smoke/run.test.ts @@ -1,5 +1,5 @@ /** - * Running and testing each language's `fixtures/` project the way the Run tool window does: + * Running and testing each language's `fixtures/` projects the way the Run tool window does: * the backend detects the configurations, the run store starts them (with its test * reporting), parses the output into the test tree, and reruns the failed tests. */ @@ -50,19 +50,57 @@ const env = (config: RunConfig, vars: Record): RunConfig => ({ }); const args = (config: RunConfig, extra: string[]): RunConfig => ({ ...config, args: [...config.args, ...extra] }); -const CASES: Record = { - typescript: { - fixture: "ts-app", - setup: (root) => execFileSync("npm", ["install", "--no-audit", "--no-fund"], { cwd: root, stdio: "ignore" }), - run: { config: "npm:start", prints: "Total: $134.97" }, - tests: { - config: "npm:test", - failing: (c) => env(c, { OPENIDEA_FAIL: "1" }), - passed: 4, - failed: "intentionally fails (set OPENIDEA_FAIL=1)", - file: "tests/cart.test.ts", +const npmInstall = (root: string) => + execFileSync("npm", ["install", "--no-audit", "--no-fund"], { cwd: root, stdio: "ignore" }); + +/** Each language's fixtures, run one after the other (the JavaScript test runners' in the TypeScript job). */ +const CASES: Record = { + typescript: [ + { + fixture: "ts-app", + setup: npmInstall, + run: { config: "npm:start", prints: "Total: $134.97" }, + tests: { + config: "npm:test", + failing: (c) => env(c, { OPENIDEA_FAIL: "1" }), + passed: 4, + failed: "intentionally fails (set OPENIDEA_FAIL=1)", + file: "tests/cart.test.ts", + }, }, - }, + { + fixture: "playwright-app", + setup: npmInstall, + tests: { + config: "npm:test", + failing: (c) => env(c, { OPENIDEA_FAIL: "1" }), + passed: 5, + failed: "intentionally fails (set OPENIDEA_FAIL=1)", + file: "tests/checkout.spec.ts", + }, + }, + { + fixture: "node-test-app", + tests: { + config: "npm:test", + failing: (c) => env(c, { OPENIDEA_FAIL: "1" }), + passed: 4, + failed: "intentionally fails (set OPENIDEA_FAIL=1)", + file: "test/inventory.test.js", + }, + }, + { + fixture: "mocha-app", + setup: npmInstall, + tests: { + config: "npm:test", + failing: (c) => env(c, { OPENIDEA_FAIL: "1" }), + passed: 4, + failed: "intentionally fails (set OPENIDEA_FAIL=1)", + file: "test/pricing.spec.js", + }, + }, + ], python: { fixture: "python-app", // A project venv with pytest, as the fixture's README sets it up. @@ -154,15 +192,20 @@ let server: Server | null = null; let disconnect: (() => void) | null = null; let base = ""; -afterEach(async () => { +async function close() { // As switching projects does: run ids restart with each server. resetRuns(); disconnect?.(); + disconnect = null; await server?.close(); + server = null; // A language server's own process (jdtls's JVM) can outlive the server's for a moment: // deleting its data directory has to wait for it. if (base) rmSync(base, { recursive: true, force: true, maxRetries: 10, retryDelay: 1000 }); -}); + base = ""; +} + +afterEach(close); async function open(c: Case): Promise { base = realpathSync(mkdtempSync(join(tmpdir(), "openidea-smoke-"))); @@ -208,8 +251,7 @@ async function runToEnd(config: RunConfig, timeoutMs = 8 * 60_000): Promise<{ id return { id: session.id, output }; } -async function smoke(language: string) { - const c = CASES[language]!; +async function smoke(c: Case) { await open(c); if (c.run) { @@ -258,6 +300,11 @@ async function smoke(language: string) { expect(again.firstFailure()?.name).toBe(c.tests.failed); } -for (const language of Object.keys(CASES)) { - test(language, () => smoke(language)); +for (const [language, cases] of Object.entries(CASES)) { + test(language, async () => { + for (const [i, c] of [cases].flat().entries()) { + if (i > 0) await close(); + await smoke(c); + } + }); } diff --git a/src-tauri/src/commands/app.rs b/src-tauri/src/commands/app.rs index c1334211bd..a2007e7d41 100644 --- a/src-tauri/src/commands/app.rs +++ b/src-tauri/src/commands/app.rs @@ -313,6 +313,7 @@ pub async fn settings_import(window: Window, state: State<'_, AppState>, path: P crate::commands::ssh::apply_ssh_settings(&state); state.host.mcp.apply(&state.host); state.host.apply_proxy(); + state.host.apply_git_executable(); state.updates.wake.notify_one(); state.sink.emit(ide_core::IdeEvent::SettingsChanged { key: String::new() }); let settings = ide_host::ops::project::settings_get(&state.host, window.label()); diff --git a/src-tauri/src/commands/github.rs b/src-tauri/src/commands/github.rs index 0ca223be88..86bfe8b984 100644 --- a/src-tauri/src/commands/github.rs +++ b/src-tauri/src/commands/github.rs @@ -133,11 +133,14 @@ pub async fn gh_pr_create( on_output: Channel, ) -> IdeResult { let root = root(&window, &state, repo)?; + let git = state.project(window.label())?.git_executable(); let cancel = state.begin_request(request); let dir = root.clone(); let result = blocking(move || { - ide_github::create(&dir, &pr, &cancel, &|line| { - let _ = on_output.send(line); + ide_vcs::with_git_executable(git.as_deref(), || { + ide_github::create(&dir, &pr, &cancel, &|line| { + let _ = on_output.send(line); + }) }) }) .await; @@ -207,10 +210,14 @@ pub async fn gh_pr_prepare_diff( on_output: Channel, ) -> IdeResult { let root = root(&window, &state, repo)?; + let git = state.project(window.label())?.git_executable(); let cancel = state.begin_request(request); let result = blocking(move || { - ide_github::prepare_diff(&root, number, &head_oid, &base_oid, &base_ref, &name_with_owner, &cancel, &|line| { + let output = |line: String| { let _ = on_output.send(line); + }; + ide_vcs::with_git_executable(git.as_deref(), || { + ide_github::prepare_diff(&root, number, &head_oid, &base_oid, &base_ref, &name_with_owner, &cancel, &output) }) }) .await; diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index e18a4d009b..93829ce06c 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -48,7 +48,10 @@ agent_set_env trusted project_host bin agent_set_mcp_overrides always project_host bindings sync agent_set_skill_overrides always project_host bindings sync agent_shell trusted project_host bindings async +agent_skills_browse always project_host bindings async +agent_skills_install always project_host bindings async agent_skills_list always project_host bindings async +agent_skills_preview always project_host bindings async agent_skills_set_mode always project_host bindings sync agent_stop_background always project_host bindings async agent_subscribe always project_host bindings sync @@ -346,6 +349,7 @@ lsp_code_lens trusted project_host bin lsp_completion trusted project_host bindings async lsp_document_highlights trusted project_host bindings async lsp_document_links trusted project_host bindings async +lsp_exception_class_at trusted project_host bindings async lsp_execute_code_action trusted project_host bindings async lsp_execute_command trusted project_host bindings async lsp_extract_interface trusted project_host bindings async @@ -513,6 +517,7 @@ project_trust_status always project_host bin project_workspace_member_set always project_host bindings sync project_workspace_members always project_host bindings sync proxy_check_connection always desktop bindings async +python_requirements trusted project_host bindings async recent_files always project_host bindings sync recent_project_groups always desktop bindings sync recent_projects always desktop bindings async diff --git a/src/bindings.ts b/src/bindings.ts index da3c51b4a9..4e213b7fff 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -150,11 +150,17 @@ export const commands = { * starting a turn; its output goes to the agent with the next message. */ agentShell: (task: string, command: string, request: RequestId) => typedError(__TAURI_INVOKE("agent_shell", { task, command, request })), + /** Resolves a GitHub `owner/repo[/path][@ref]` source and lists the `SKILL.md` skills in it. */ + agentSkillsBrowse: (source: string, request: RequestId) => typedError(__TAURI_INVOKE("agent_skills_browse", { source, request })), + /** Installs the selected skill subtree into `~/.agents/skills` (User) or `/.agents/skills` (Workspace). */ + agentSkillsInstall: (input: InstallRemoteSkillRequest, request: RequestId) => typedError(__TAURI_INVOKE("agent_skills_install", { input, request })), /** - * Every skill discovered in the project and the user's folders, with the mode a session - * of this project runs it with (without any session's own overrides). + * Every skill discovered in the project, the user's folders and enabled plugins, with + * the mode a session runs it with (without any session's own overrides). */ agentSkillsList: () => typedError(__TAURI_INVOKE("agent_skills_list")), + /** Fetches one skill's `SKILL.md`, file list, and static security scan warnings before installation. */ + agentSkillsPreview: (owner: string, repo: string, gitRef: string, subpath: string, request: RequestId) => typedError(__TAURI_INVOKE("agent_skills_preview", { owner, repo, gitRef, subpath, request })), /** * Sets how `name` may run in `scope`, in the settings file of that scope, and returns the * updated list. `SKILL.md` files are never touched; the default `auto` removes the entry. @@ -840,6 +846,13 @@ export const commands = { lspDocumentHighlights: (doc: DocId, pos: Pos) => typedError(__TAURI_INVOKE("lsp_document_highlights", { doc, pos })), /** Links in a document (`href`s, Markdown links, `#include`s…) from its language servers. */ lspDocumentLinks: (doc: DocId) => typedError(__TAURI_INVOKE("lsp_document_links", { doc })), + /** The Throwable class the caret at `pos` names, for the exception breakpoint intention. */ + lspExceptionClassAt: (request: RequestId, doc: DocId, pos: Pos) => typedError<{ + /** The binary name (`app.Outer$Failure`), as exception breakpoints take it. */ + qualifiedName: string, + /** The simple name (`Failure`). */ + displayName: string, +} | null, IdeError>(__TAURI_INVOKE("lsp_exception_class_at", { request, doc, pos })), lspExecuteCodeAction: (request: RequestId, doc: DocId, action: CodeAction, answers: FormAnswer[]) => typedError(__TAURI_INVOKE("lsp_execute_code_action", { request, doc, action, answers })), /** * Runs a server command (`workspace/executeCommand`), e.g. a completion item's @@ -1351,6 +1364,15 @@ export const commands = { * edited (not yet applied); the response status, or why there was none. */ proxyCheckConnection: (proxy: ProxySettings, url: string) => typedError(__TAURI_INVOKE("proxy_check_connection", { proxy, url })), + /** + * The requirements of a `requirements*.txt` / `pyproject.toml` the project's interpreter + * doesn't satisfy; `None` for other files, or with no local interpreter to ask. + */ + pythonRequirements: (doc: DocId, request: RequestId) => typedError<{ + /** The interpreter checked, which installs go to. */ + python: IpcPath, + unsatisfied: UnsatisfiedRequirement[], +} | null, IdeError>(__TAURI_INVOKE("python_requirements", { doc, request })), /** Recently opened files, most recent first (⌘E). */ recentFiles: () => typedError(__TAURI_INVOKE("recent_files")), /** The welcome screen's project groups. */ @@ -1909,7 +1931,10 @@ export const commands = { vcsHasHook: (repo: string | null, name: string) => typedError(__TAURI_INVOKE("vcs_has_hook", { repo, name })), vcsIgnoreBlameRevision: (path: string, commit: string) => typedError(__TAURI_INVOKE("vcs_ignore_blame_revision", { path, commit })), vcsIgnoredFiles: () => typedError(__TAURI_INVOKE("vcs_ignored_files")), - /** `git init` in `dir` (File › New Project… "Create Git repository"). */ + /** + * `git init` in `dir` (VCS › Create Git Repository…): with the git of the window's project when + * it is trusted, the default one in a window without a project. + */ vcsInit: (dir: string) => typedError(__TAURI_INVOKE("vcs_init", { dir })), /** Reads the selected push target without prompting for remote credentials. */ vcsInspectPush: (repo: string | null, request: RequestId, selection: PushSelection, live: boolean) => typedError(__TAURI_INVOKE("vcs_inspect_push", { repo, request, selection, live })), @@ -2928,6 +2953,8 @@ export type AgentSkillSource = "workspace" | /** The user's `~/.agents/skills` (what `npx skills add` fills). */ "user" | +/** Contributed by an enabled OpenIDEA plugin (`[[contributes.skills]]`). */ +"plugin" | /** The project's `.claude/skills`. */ "claudeWorkspace" | /** `~/.claude/skills`. */ @@ -2995,6 +3022,10 @@ export type AgentSkill_Deserialize = { userInvocable?: boolean, /** True when frontmatter sets `disable-model-invocation: true` (defaults to `slashOnly`). */ disableModelInvocation?: boolean, + /** True when frontmatter sets `context: fork` (passed through natively to supporting CLIs). */ + contextFork?: boolean, + /** Optional `paths` / `globs` patterns from frontmatter (passed through natively to supporting CLIs). */ + paths?: string[], /** The `SKILL.md` passes validation (`name` matches its folder, `description` present). */ valid: boolean, /** What validation found (`name` mismatch, missing or over-long description…). */ @@ -3017,6 +3048,10 @@ export type AgentSkill_Serialize = { userInvocable: boolean, /** True when frontmatter sets `disable-model-invocation: true` (defaults to `slashOnly`). */ disableModelInvocation: boolean, + /** True when frontmatter sets `context: fork` (passed through natively to supporting CLIs). */ + contextFork: boolean, + /** Optional `paths` / `globs` patterns from frontmatter (passed through natively to supporting CLIs). */ + paths?: string[], /** The `SKILL.md` passes validation (`name` matches its folder, `description` present). */ valid: boolean, /** What validation found (`name` mismatch, missing or over-long description…). */ @@ -6524,6 +6559,14 @@ export type ExceptionClassBreakpoint = { classExclusionFilters: string[], }; +/** The exception class a caret names: a reference to it, its declaration, or a throw of it. */ +export type ExceptionClassRef = { + /** The binary name (`app.Outer$Failure`), as exception breakpoints take it. */ + qualifiedName: string, + /** The simple name (`Failure`). */ + displayName: string, +}; + /** What a session's exception class breakpoints can do. */ export type ExceptionClassSupport = { /** Whose class names the session takes: `java`. */ @@ -6611,11 +6654,11 @@ export type ExternalDiffSide = { }; /** A formatter that runs outside the language servers, with its own settings group. */ -export type ExternalFormatter = "prettier" | "oxfmt" | "ruff"; +export type ExternalFormatter = "prettier" | "oxfmt" | "biome" | "ruff"; -/** An external formatter (Prettier, oxfmt, Ruff) and the languages it formats. */ +/** An external formatter (Prettier, oxfmt, Biome, Ruff) and the languages it formats. */ export type ExternalFormatterSettings = { - /** Empty path: project node_modules (Prettier/oxfmt), managed installation, then PATH. */ + /** Empty path: project node_modules (Prettier/oxfmt/Biome), managed installation, then PATH. */ path?: string, /** Ruff only: directory containing its configuration, or a configuration file. */ configurationDirectory?: string, @@ -8230,6 +8273,18 @@ export type InstallPreview = { needsConsent: boolean, }; +export type InstallRemoteSkillRequest = { + owner: string, + repo: string, + gitRef: string, + subpath: string, + scope: McpScope, + /** Must be `true` when the static security scan produces any warnings. */ + confirmWarnings?: boolean, + /** Must be `true` to replace an existing folder of the same name in `scope`. */ + overwrite?: boolean, +}; + /** The settings folder of a JetBrains IDE (or Android Studio) of this user. */ export type InstalledIdeSettings = { /** The IDE and its version: `IntelliJ IDEA 2025.2`. */ @@ -8762,6 +8817,7 @@ export type LanguagesSettings = { typescript?: TypeScriptSettings, prettier?: ExternalFormatterSettings, oxfmt?: ExternalFormatterSettings, + biome?: ExternalFormatterSettings, ruff?: ExternalFormatterSettings, java?: JavaSettings, ruby?: RubySettings, @@ -11271,6 +11327,12 @@ export type PythonPackage = { version: string, }; +export type PythonRequirements = { + /** The interpreter checked, which installs go to. */ + python: IpcPath, + unsatisfied: UnsatisfiedRequirement[], +}; + export type PythonSettings = { /** * Project interpreter executable; empty = auto-detect (project venv, else `python3`); @@ -11612,6 +11674,47 @@ export type RemoteSession = { commands: string[], }; +export type RemoteSkillBrowseResult = { + owner: string, + repo: string, + gitRef: string, + treeSha: string, + truncated: boolean, + skills: RemoteSkillCandidate[], +}; + +export type RemoteSkillCandidate = { + /** Target folder name (`` under `.agents/skills/`). */ + folderName: string, + /** Repository-relative directory holding `SKILL.md` (`""` when at repository root). */ + subpath: string, + fileCount: number, + totalBytes: number, +}; + +export type RemoteSkillFile = { + /** Path relative to the skill folder (e.g. `"SKILL.md"`, `"scripts/check.sh"`). */ + path: string, + size: number, + executable: boolean, + symlink: boolean, +}; + +export type RemoteSkillPreview = { + owner: string, + repo: string, + gitRef: string, + treeSha: string, + subpath: string, + skillName: string, + description: string, + skillMarkdown: string, + files: RemoteSkillFile[], + scanWarnings: SkillScanWarning[], + alreadyInstalledUser: boolean, + alreadyInstalledWorkspace: boolean, +}; + /** Where [`remote_connect`] is (`fraction`: 0..1 of a download / upload). */ export type RemoteStage = "connecting" | /** `devcontainer up`: building or starting the container. */ @@ -11841,6 +11944,12 @@ export type RunExtras_Deserialize = { stopCommand?: string | null, /** Settings › Run Targets id the process runs on (over SSH); `None` = this machine. */ target?: string | null, + /** + * The test framework a test configuration runs when detection recognised one that the + * command line doesn't name (a `package.json` script running `playwright test`): picks the + * test output parser and how a single test is selected. + */ + testRunner?: string | null, }; export type RunExtras_Serialize = { @@ -11885,6 +11994,12 @@ export type RunExtras_Serialize = { stopCommand?: string | null, /** Settings › Run Targets id the process runs on (over SSH); `None` = this machine. */ target?: string | null, + /** + * The test framework a test configuration runs when detection recognised one that the + * command line doesn't name (a `package.json` script running `playwright test`): picks the + * test output parser and how a single test is selected. + */ + testRunner?: string | null, }; /** A process started from a run configuration. */ @@ -12485,6 +12600,14 @@ export type SizeSource = */ "addressGaps" | "layout"; +export type SkillScanWarning = { + kind: SkillScanWarningKind, + file: string, + message: string, +}; + +export type SkillScanWarningKind = "hiddenUnicode" | "outOfRootSymlink" | "executableScript" | "allowedToolsShell"; + export type SkipReason = /** A configuration with this name already exists. */ { kind: "nameTaken" } | @@ -13475,6 +13598,13 @@ export type UnityProjectInfo = { projects: string[], }; +/** A requirement the project's interpreter does not satisfy. */ +export type UnsatisfiedRequirement = { + dependency: ManifestDependency, + /** The installed version that misses the specifier; `None` when not installed. */ + installed: string | null, +}; + export type UpdateCheck = { enabled: boolean, update: UpdateInfo | null, diff --git a/src/editor/api.ts b/src/editor/api.ts index 4d542ae4f9..b69dbc9807 100644 --- a/src/editor/api.ts +++ b/src/editor/api.ts @@ -41,6 +41,7 @@ import { rootOfPath } from "@/platform/projectRoots"; import { isVirtualUri } from "@/platform/virtualDocs"; import { cornerInset } from "@/editor/core/cm/cornerInset"; export { iconAreaSource, mapLineStart, type IconAreaSource } from "@/editor/core/cm/iconArea"; +export { disambiguateTitles } from "@/editor/core/model/tabTitles"; export { invalidateNavigationProviders, navigationEpoch, @@ -573,6 +574,31 @@ export function contributedIntentions(view: EditorView): ContributedIntention[] }); } +/** + * Providers of context actions that need an answer from the language server first. ⌥↵ waits for + * them along with the server's code actions; the light bulb does too. `signal` aborts when the + * answer is no longer wanted (the caret moved on). + */ +export const asyncIntentionProviders = + Facet.define<(view: EditorView, signal: AbortSignal) => Promise>(); + +export async function contributedIntentionsAsync( + view: EditorView, + signal: AbortSignal, +): Promise { + const found = await Promise.all( + view.state.facet(asyncIntentionProviders).map((p) => + Promise.resolve() + .then(() => p(view, signal)) + .catch((e: unknown) => { + if (!signal.aborted) console.error("intention provider failed", e); + return []; + }), + ), + ); + return found.flat(); +} + // --- navigation history ------------------------------------------------------ /** One entry of the Back/Forward (⌘[ / ⌘]) history. 0-based line, UTF-16 col. */ diff --git a/src/editor/core/model/tabTitles.test.ts b/src/editor/core/model/tabTitles.test.ts index 229ad00f5c..0f421f23bc 100644 --- a/src/editor/core/model/tabTitles.test.ts +++ b/src/editor/core/model/tabTitles.test.ts @@ -26,6 +26,12 @@ describe("disambiguateTitles", () => { expect(m.get("/r/a/d/f.ts")).toBe("d"); }); + it("distinguishes directory names that occur at different depths", () => { + const paths = ["/r/prod/shared/f.ts", "/r/shared/prod/f.ts", "/r/test/shared/f.ts"]; + const labels = disambiguateTitles(paths); + expect(paths.map((path) => labels.get(path))).toEqual(["prod/shared", "shared/prod", "test"]); + }); + it("ignores duplicates of the same path", () => { expect(disambiguateTitles(["/p/a/x.ts", "/p/a/x.ts"]).size).toBe(0); }); diff --git a/src/editor/core/model/tabTitles.ts b/src/editor/core/model/tabTitles.ts index 0f2458afea..99ab7197ab 100644 --- a/src/editor/core/model/tabTitles.ts +++ b/src/editor/core/model/tabTitles.ts @@ -1,6 +1,6 @@ /** - * IDEA-style editor tab titles for files that share a name: the nearest parent - * directory that tells them apart is shown after the name (`lib.rs — ide-lsp` + * Directory hints for files that share a name: a distinguishing parent + * directory is shown after the name (`lib.rs — ide-lsp` * for `crates/ide-lsp/src/lib.rs` next to `crates/ide-vcs/src/lib.rs`). */ @@ -27,25 +27,24 @@ export function disambiguateTitles(paths: readonly string[], titleOf = baseName) for (const group of groups.values()) { if (group.length < 2) continue; const dirs = group.map(parents); + const nameCounts = new Map(); + const suffixCounts = new Map(); + const suffixes = dirs.map((names) => { + for (const name of new Set(names)) { + nameCounts.set(name, (nameCounts.get(name) ?? 0) + 1); + } + let suffix = ""; + return names.map((name) => { + suffix = suffix ? `${name}/${suffix}` : name; + suffixCounts.set(suffix, (suffixCounts.get(suffix) ?? 0) + 1); + return suffix; + }); + }); group.forEach((path, i) => { - const own = dirs[i]!; - let hint: string | null = null; - for (let depth = 0; depth < own.length; depth++) { - const seg = own[depth]!; - if (dirs.every((other, j) => j === i || other[depth] !== seg)) { - hint = seg; - break; - } - } - if (hint === null) { - // No single directory is unique: the shortest distinguishing parent path. - const suffix = (d: string[], k: number) => d.slice(0, k).reverse().join("/"); - for (let k = 2; k <= own.length && hint === null; k++) { - const mine = suffix(own, k); - if (dirs.every((other, j) => j === i || suffix(other, k) !== mine)) hint = mine; - } - } - out.set(path, hint ?? (own.length ? own.slice().reverse().join("/") : "/")); + const name = dirs[i]!.find((segment) => nameCounts.get(segment) === 1); + const paths = suffixes[i]!; + const hint = name ?? paths.find((suffix, depth) => depth > 0 && suffixCounts.get(suffix) === 1); + out.set(path, hint ?? paths.at(-1) ?? "/"); }); } return out; diff --git a/src/editor/core/view/EditorArea.module.css b/src/editor/core/view/EditorArea.module.css index cad566bfe2..0a1118cf17 100644 --- a/src/editor/core/view/EditorArea.module.css +++ b/src/editor/core/view/EditorArea.module.css @@ -150,6 +150,28 @@ .deprecated { text-decoration-line: line-through; } +.tabPath { + --tab-directory-min: min(5ch, 25%); + display: flex; +} +.tabDirectory > span, +.tabFilename { + overflow: hidden; + text-overflow: ellipsis; +} +.tabDirectory { + flex: 0 1000 max-content; + /* Leave space for a short prefix without stretching one that already fits. */ + width: var(--tab-directory-min); + color: var(--fg-subtle); +} +.tabDirectory > span { + display: block; +} +.tabFilename { + flex: none; + max-width: calc(100% - var(--tab-directory-min)); +} .dupe { color: var(--fg-faint); margin-left: 4px; diff --git a/src/editor/core/view/EditorArea.tsx b/src/editor/core/view/EditorArea.tsx index 5a339d897e..337d75a6a5 100644 --- a/src/editor/core/view/EditorArea.tsx +++ b/src/editor/core/view/EditorArea.tsx @@ -219,15 +219,23 @@ function PaneView({ paneId }: { paneId: string }) { const pin = t.pinned ? : null; const file = t.input.kind === "file" && t.input.path ? files.get(t.input.path) : undefined; const title = markModified && dirty[i] ? `*${name}` : name; + const prefix = t.input.kind === "file" && dupe ? (dupe.endsWith("/") ? dupe : `${dupe}/`) : null; return { id: t.id, - label: ( + label: prefix ? ( + + + {prefix} + + {title} + + ) : ( <> {file?.deprecated ? {title} : title} {dupe && {dupe}} ), - text: dupe ? `${name} — ${dupe}` : name, + text: prefix ? `${prefix}${name}` : dupe ? `${name} — ${dupe}` : name, icon: showFileIcon ? t.input.kind === "file" && t.input.path ? (tabIcons[i] ?? file?.icon) diff --git a/src/editor/lsp/Popups.module.css b/src/editor/lsp/Popups.module.css index 4a23f3c04f..41248010c1 100644 --- a/src/editor/lsp/Popups.module.css +++ b/src/editor/lsp/Popups.module.css @@ -532,20 +532,6 @@ .renamePreview .previewList { overflow: visible; } -.renamePreview .previewName { - min-width: 0; - max-width: 55%; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} -.renamePreview .previewOp { - flex: 0 1 auto; - min-width: 0; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} .renamePreview .previewWarning { overflow-wrap: anywhere; } @@ -571,23 +557,46 @@ padding: 0 14px; font-size: var(--fs-ui); } -.previewName { - color: var(--fg-emphasis); +.previewFile { + flex: 1 1 auto; + display: flex; + align-items: baseline; + gap: var(--space-2); + min-width: 0; } -.previewPath { +.previewName, +.previewDirectory, +.previewOp { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; +} +.previewName { + flex: none; + max-inline-size: 100%; + color: var(--fg-emphasis); +} +.previewFile:has(.previewDirectory) .previewName { + max-inline-size: 70%; +} +.previewDirectory { color: var(--fg-subtle); font-size: var(--fs-small); + direction: rtl; } .previewOp, .previewCount { - flex: none; font-size: var(--fs-small); color: var(--fg-muted); } +.previewOp { + max-inline-size: 55%; +} +.previewCount { + flex: none; + font-variant-numeric: tabular-nums; +} .previewWarning { flex: none; diff --git a/src/editor/lsp/Popups.test.tsx b/src/editor/lsp/Popups.test.tsx index 530cf3dde0..68a38ae0cc 100644 --- a/src/editor/lsp/Popups.test.tsx +++ b/src/editor/lsp/Popups.test.tsx @@ -15,7 +15,7 @@ vi.mock("@/workbench/contributions", async (orig) => { }); const { LspPopups, DocumentationWindow } = await import("./Popups"); -const { closePopup, openPopup, useLspPopup } = await import("./popupStore"); +const { closePopup, openPopup, updatePopup, useLspPopup } = await import("./popupStore"); const { useDocWindow, hoverDoc, pushHistory, stepHistory, hoverCandidates } = await import("./docs"); const { mountHoverDoc } = await import("./DocView"); const { hoverSource } = await import("./hover"); @@ -139,6 +139,31 @@ describe("list popup", () => { expect(onClose).toHaveBeenCalledOnce(); }); + it("keeps the chosen intention when a quick-fix section arrives ahead of it", () => { + const local = ["Extract variable", "Inline value"].map((label) => ({ + id: label, + label, + section: { id: "intentions" }, + run: vi.fn(), + })); + openPopup({ kind: "list", title: "Intentions", anchor: { x: 0, y: 0 }, items: local, busy: true }); + render(); + fireEvent.keyDown(screen.getByRole("listbox"), { key: "ArrowDown" }); + expect(screen.getByRole("option", { name: "Inline value", selected: true })).toBeVisible(); + + const runFix = vi.fn(); + act(() => + updatePopup("list", { + busy: false, + items: [{ id: "fix", label: "Correct type", section: { id: "quick-fixes" }, run: runFix }, ...local], + }), + ); + expect(screen.getByRole("option", { name: "Inline value", selected: true })).toBeVisible(); + fireEvent.keyDown(screen.getByRole("listbox"), { key: "Enter" }); + expect(local[1]!.run).toHaveBeenCalledOnce(); + expect(runFix).not.toHaveBeenCalled(); + }); + it("focuses the rows, not the header's pin button, when it opens", () => { openPopup({ kind: "list", diff --git a/src/editor/lsp/Popups.tsx b/src/editor/lsp/Popups.tsx index a70942476b..00623fa8c0 100644 --- a/src/editor/lsp/Popups.tsx +++ b/src/editor/lsp/Popups.tsx @@ -22,7 +22,7 @@ import { selectableText, T, } from "@/ui"; -import { basename, relativePath, useProject } from "@/platform/project"; +import { basename, relativeDir, relativePath, useProject } from "@/platform/project"; import { closePopup, updatePopup, @@ -112,14 +112,10 @@ function ListPopup({ popup }: { popup: Extract }) { const [query, setQuery] = useState(""); const rows = useMemo(() => listPopupRows(popup.items, query), [popup.items, query]); const firstEnabled = rows.findIndex((row) => row.kind === "action" && !row.item.disabled); - const [active, setActive] = useState(firstEnabled); - const clamped = Math.min(active, rows.length - 1); + const [activeId, setActiveId] = useState(null); + const selected = rows.findIndex((row) => row.kind === "action" && row.item.id === activeId); const activeIndex = - rows[clamped]?.kind === "action" - ? clamped - : firstEnabled >= 0 - ? firstEnabled - : firstSelectable(rows, isListSection); + selected >= 0 ? selected : firstEnabled >= 0 ? firstEnabled : firstSelectable(rows, isListSection); const activeRow = rows[activeIndex]; const activeItem = activeRow?.kind === "action" ? activeRow.item : undefined; const showIcons = !popup.compact || popup.items.some((item) => item.icon || item.symbol); @@ -183,11 +179,11 @@ function ListPopup({ popup }: { popup: Extract }) { if (item) activate(item); } else if (e.key === "Backspace" && query) { setQuery(query.slice(0, -1)); - setActive(-1); + setActiveId(null); e.preventDefault(); } else if (e.key.length === 1 && !(e.key === " " && !query)) { setQuery(query + e.key); - setActive(-1); + setActiveId(null); e.preventDefault(); } }; @@ -297,7 +293,10 @@ function ListPopup({ popup }: { popup: Extract }) { row.kind === "section" && row.label ? {row.label} : } activeIndex={activeIndex} - onActiveChange={setActive} + onActiveChange={(index) => { + const row = rows[index]; + setActiveId(row?.kind === "action" ? row.item.id : null); + }} hoverSelects autoFocus aria-label={popup.title} @@ -762,25 +761,34 @@ function PreviewDialog({ popup }: { popup: Extract ) : (
    - {summary.entries.map((e) => ( -
  • - - - {basename(e.path)} - - - {relativePath(root, e.path)} - - - {e.operation === "rename" && e.to && → {basename(e.to)}} - {e.operation && e.operation !== "rename" && {e.operation}} - {e.edits > 0 && ( - - {e.edits} {e.edits === 1 ? "occurrence" : "occurrences"} + {summary.entries.map((e) => { + const name = basename(e.path); + const directory = relativeDir(root, e.path); + return ( +
  • + + + {name} + {directory && ( + + {directory} + + )} - )} -
  • - ))} + {e.operation === "rename" && e.to && ( + + → {basename(e.to)} + + )} + {e.operation && e.operation !== "rename" && {e.operation}} + {e.edits > 0 && ( + + {e.edits} {e.edits === 1 ? "occurrence" : "occurrences"} + + )} + + ); + })}
)} diff --git a/src/editor/lsp/actions.ts b/src/editor/lsp/actions.ts index 7644849a2b..2a20b0404e 100644 --- a/src/editor/lsp/actions.ts +++ b/src/editor/lsp/actions.ts @@ -104,6 +104,13 @@ const fixEslintProblems = (v: EditorView) => none: "No ESLint problems to fix", label: "Fix ESLint Problems", }); +/** WebStorm's Fix Stylelint Problems: vscode-stylelint's fix-all for the whole file. */ +const fixStylelintProblems = (v: EditorView) => + runKindAction(v, "source.fixAll.stylelint", { + whole: true, + none: "No Stylelint problems to fix", + label: "Fix Stylelint Problems", + }); /** * typescript-language-server's organize imports only sorts and merges them; removing the unused * ones is its own action, so Optimize Imports runs that first in these languages. @@ -195,10 +202,10 @@ function editorAction( /** Whether saving a `language` file formats it: Format on save, or Run on save of an external formatter. */ export function formatsOnSave(settings: Settings | null, language: string): boolean { - const { prettier, oxfmt, ruff } = validateLanguages(settings?.languages); + const { prettier, oxfmt, biome, ruff } = validateLanguages(settings?.languages); return ( !!settings?.editor?.formatOnSave || - [prettier, oxfmt, ruff].some((formatter) => formatter.runOnSave && formatter.languages.includes(language)) + [prettier, oxfmt, biome, ruff].some((formatter) => formatter.runOnSave && formatter.languages.includes(language)) ); } @@ -275,6 +282,13 @@ export function registerLspActions(): () => void { (v) => formatDocument(v, { explicit: true, tool: "oxfmt" }), { keywords: ["format", "oxfmt", "oxc"] }, ), + editorAction( + "code.reformatWithBiome", + "Reformat with Biome", + "Code", + (v) => formatDocument(v, { explicit: true, tool: "biome" }), + { keywords: ["format", "biome"] }, + ), editorAction( "code.reformatWithRuff", "Reformat with Ruff", @@ -288,6 +302,9 @@ export function registerLspActions(): () => void { editorAction("code.fixEslintProblems", "Fix ESLint Problems", "Code", fixEslintProblems, { keywords: ["eslint", "lint", "fix all"], }), + editorAction("code.fixStylelintProblems", "Fix Stylelint Problems", "Code", fixStylelintProblems, { + keywords: ["stylelint", "lint", "css", "fix all"], + }), editorAction("code.optimizeImports", "Optimize Imports", "Code", optimizeImports, { keywords: ["organize imports"], }), diff --git a/src/editor/lsp/format.test.ts b/src/editor/lsp/format.test.ts index d108b53035..c8a4af7820 100644 --- a/src/editor/lsp/format.test.ts +++ b/src/editor/lsp/format.test.ts @@ -173,13 +173,15 @@ describe("format on save provider isolation", () => { } }); - it("formats on save for the languages whose Prettier or oxfmt Run on save is on", () => { + it("formats on save for the languages whose Prettier, oxfmt or Biome Run on save is on", () => { const settings = (languages: Settings["languages"], formatOnSave = false) => ({ editor: { formatOnSave }, languages }) as Settings; const oxfmt = settings({ oxfmt: { runOnSave: true, languages: ["typescript"] } }); expect(formatsOnSave(oxfmt, "typescript")).toBe(true); expect(formatsOnSave(oxfmt, "markdown")).toBe(false); expect(formatsOnSave(settings({ prettier: { runOnSave: true } }), "markdown")).toBe(true); + expect(formatsOnSave(settings({ biome: { runOnSave: true } }), "json")).toBe(true); + expect(formatsOnSave(settings({ biome: { runOnSave: true } }), "markdown")).toBe(false); expect(formatsOnSave(settings({ ruff: { runOnSave: true } }), "python")).toBe(true); expect(formatsOnSave(settings({ ruff: { runOnSave: true } }), "typescript")).toBe(false); expect(formatsOnSave(settings({}), "typescript")).toBe(false); diff --git a/src/editor/lsp/format.ts b/src/editor/lsp/format.ts index bb91d16e5c..9f4b0cc417 100644 --- a/src/editor/lsp/format.ts +++ b/src/editor/lsp/format.ts @@ -96,7 +96,7 @@ interface FormatDocumentOptions { explicit: boolean; selectionOnly?: boolean; onSave?: boolean; - /** Runs this external formatter whatever the settings select (Reformat with Prettier/oxfmt). */ + /** Runs this external formatter whatever the settings select (Reformat with Prettier/oxfmt/Biome). */ tool?: ExternalFormatter; /** Formats only these ranges, e.g. the text changed since the last commit; an empty list formats nothing. */ ranges?: readonly OffsetRange[]; @@ -176,6 +176,7 @@ async function format(view: EditorView, opts: FormatDocumentOptions): Promise { _resetI18nForTests(); }); -describe.each(["prettier", "oxfmt", "ruff"])("%s formatter errors", (name) => { +describe.each(["prettier", "oxfmt", "biome", "ruff"])("%s formatter errors", (name) => { const tool = { type: "tool", tool: name, missing: false } as const; - const display = name === "prettier" ? "Prettier" : name === "ruff" ? "Ruff" : name; + const display = ({ prettier: "Prettier", biome: "Biome", ruff: "Ruff" } as Record)[name] ?? name; it("uses structured missing-tool information to request the shared install prompt", async () => { const prompt = vi.fn(); const dispose = registerAction({ @@ -130,6 +130,7 @@ describe("Reformat with an external formatter", () => { it.each([ ["code.reformatWithPrettier", "prettier"], ["code.reformatWithOxfmt", "oxfmt"], + ["code.reformatWithBiome", "biome"], ["code.reformatWithRuff", "ruff"], ])("%s asks the backend for %s whatever the settings select", async (id, tool) => { vi.spyOn(lsp, "lspRequest").mockImplementation(async (request) => { diff --git a/src/editor/lsp/inlay.ts b/src/editor/lsp/inlay.ts index ec39e86285..65fd60f0c8 100644 --- a/src/editor/lsp/inlay.ts +++ b/src/editor/lsp/inlay.ts @@ -17,7 +17,7 @@ import { debounce, docOf, isUnavailable, lspRequest } from "./lsp"; import { offsetsToRange, posToOffset } from "./positions"; import { featureBackoff, onLspRefresh, onServerSettled, anyServerBusy } from "./availability"; import { gotoTargets } from "./navigation"; -import { tx } from "@/platform/i18n"; +import { tx, txPart } from "@/platform/i18n"; const KIND_LABEL: Record = { type: "Type hints", @@ -42,7 +42,7 @@ function typeHintOffset(view: EditorView, at: number): number | null { /** Right-click on a hint: turn its kind off (IDEA's "Disable '…' hints"), or open the settings. */ export function inlayMenuItems(kind: InlayHint["kind"]): MenuItem[] { return [ - { label: tx`Disable ${KIND_LABEL[kind]}`, run: () => void setEditorSetting(`inlay.${kind}`, false) }, + { label: tx`Disable ${txPart(KIND_LABEL[kind])}`, run: () => void setEditorSetting(`inlay.${kind}`, false) }, { kind: "separator" }, { label: "Inlay Hints Settings…", run: () => void executeAction("file.settings", "editor.inlayHints") }, ]; diff --git a/src/editor/lsp/intentions.test.ts b/src/editor/lsp/intentions.test.ts index 9940327319..dd48782799 100644 --- a/src/editor/lsp/intentions.test.ts +++ b/src/editor/lsp/intentions.test.ts @@ -54,6 +54,7 @@ const { withInspectionControls, } = await import("./intentions"); const { useLspPopup, closePopup } = await import("./popupStore"); +const { asyncIntentionProviders } = await import("@/editor/api"); const { setFileDiagnostics, toLintDiagnostics } = await import("./diagnostics"); const { lspDoc } = await import("./lsp"); @@ -195,6 +196,58 @@ describe("⌥↵ popup timing", () => { }); }); +describe("context actions a feature finds through the language server", () => { + const editor = (...providers: Parameters[0][]) => { + const view = new EditorView({ + state: EditorState.create({ + doc: "f(1);\n", + extensions: [ + lspDoc.of({ doc: 1, path: "/p/A.java", language: "java", uiMode: null, readOnly: false }), + ...providers.map((p) => asyncIntentionProviders.of(p)), + ], + }), + }); + views.push(view); + return view; + }; + const labels = () => (useLspPopup.getState().popup as { items: { label: string }[] }).items.map((i) => i.label); + const intention = (label: string) => ({ id: label, label, run: () => {} }); + + it("waits for them and lists them with the server's actions", async () => { + let answer!: (v: ReturnType[]) => void; + const view = editor(() => new Promise((r) => (answer = r))); + lspCodeActions.mockResolvedValue({ status: "ok", data: [{ ...resolved, edit: null }] }); + const shown = showIntentions(view); + await Promise.resolve(); + answer([intention("Create exception breakpoint on Failure")]); + await shown; + expect(labels()).toEqual( + expect.arrayContaining(["Create exception breakpoint on Failure", "Introduce local variable"]), + ); + }); + + it("lists them alone when the server has nothing", async () => { + const view = editor(async () => [intention("Disable exception breakpoint on Failure")]); + lspCodeActions.mockResolvedValue({ status: "ok", data: [] }); + await showIntentions(view); + expect(labels()).toEqual(["Disable exception breakpoint on Failure"]); + }); + + it("keeps the other rows when one provider fails", async () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + const view = editor( + async () => { + throw new Error("boom"); + }, + async () => [intention("Enable exception breakpoint on Failure")], + ); + lspCodeActions.mockResolvedValue({ status: "ok", data: [] }); + await showIntentions(view); + expect(labels()).toEqual(["Enable exception breakpoint on Failure"]); + error.mockRestore(); + }); +}); + describe("inspection controls in ⌥↵ (issue #42)", () => { const editorAt = (path: string) => { const view = new EditorView({ diff --git a/src/editor/lsp/intentions.ts b/src/editor/lsp/intentions.ts index bc1313c50c..50fd2c7fbd 100644 --- a/src/editor/lsp/intentions.ts +++ b/src/editor/lsp/intentions.ts @@ -11,6 +11,7 @@ import { diff } from "@codemirror/merge"; import { commands, isCancelled, type CodeAction, type Diagnostic } from "@/platform/ipc"; import { contributedIntentions, + contributedIntentionsAsync, contributedQuickFixes, intentionProviders, intentionsChanged, @@ -41,7 +42,7 @@ import { inspectionsAt, type EditorDiagnostic } from "./diagnostics"; import { SPELLING_INSPECTION } from "@/platform/inspections"; import { editInspectionSettings, intentionControls } from "@/platform/inspectionControls"; import { runInteractiveCodeAction } from "./interactiveCommand"; -import { tx } from "@/platform/i18n"; +import { tx, txPart } from "@/platform/i18n"; const codeActionBackoff = featureBackoff(); @@ -60,11 +61,18 @@ export function quickFixIcon(view: EditorView): "bulb" | "bulb-fix" { const isFixItem = (item: ListPopupItem) => item.quickFix ?? item.icon === "bulb-fix"; -/** Local and language-server fixes share icons and the same stable ordering. */ +/** Local and language-server fixes share icons and are grouped separately from other actions. */ export function listedIntentions(view: EditorView, items: ListPopupItem[]): ListPopupItem[] { const rank = (item: ListPopupItem) => (item.disabled ? 4 : 0) + (isFixItem(item) ? 0 : 2) + (item.emphasis ? 0 : 1); return items - .map((item) => (isFixItem(item) ? { ...item, quickFix: true, icon: quickFixIcon(view) } : item)) + .map((item) => { + const fix = isFixItem(item); + return { + ...item, + ...(fix && { quickFix: true, icon: quickFixIcon(view) }), + section: item.section ?? { id: item.disabled ? "unavailable" : fix ? "quick-fixes" : "intentions" }, + }; + }) .sort((a, b) => rank(a) - rank(b)); } @@ -496,7 +504,8 @@ export function withInspectionControls(view: EditorView, items: ListPopupItem[]) ...items, ...inspections.map((inspection) => ({ id: `inspection:${inspection.id}`, - label: tx`Inspection '${inspection.name}' options`, + label: tx`Inspection '${txPart(inspection.name)}' options`, + section: { id: "inspection-options" }, icon: "settings", run: () => editInspectionSettings(inspection.id), submenu: intentionControls(inspection), @@ -566,13 +575,18 @@ export async function showIntentions(view: EditorView) { display(itemsFor([]), true); }, INTENTIONS_POPUP_DELAY_MS); + const asked = new AbortController(); try { let failure: unknown = null; // Like IDEA, only applicable intentions are listed (servers also report disabled refactorings). - const actions = await fetchIntentions(view).catch((e: unknown) => { - failure = e; - return null; - }); + const [actions, found] = await Promise.all([ + fetchIntentions(view).catch((e: unknown) => { + failure = e; + return null; + }), + contributedIntentionsAsync(view, asked.signal), + ]); + local.push(...found); clearTimeout(timer); const items = actions ? itemsFor(actions) : withInspectionControls(view, listedIntentions(view, local)); if (!items.length) { @@ -591,6 +605,8 @@ export async function showIntentions(view: EditorView) { clearTimeout(timer); if (ours()) closePopup(); reportLspError(view, e, true); + } finally { + asked.abort(); } } @@ -696,6 +712,7 @@ const bulbField = StateField.define({ const bulbPlugin = ViewPlugin.fromClass( class { private lookup = debounce(() => void this.run(), 500); + private asked: AbortController | null = null; constructor(private view: EditorView) { this.lookup(); } @@ -724,7 +741,9 @@ const bulbPlugin = ViewPlugin.fromClass( const typoFix = spellingIntentions(this.view).length > 0; const selection = state.selection.main; const ownFix = contributedQuickFixes(this.view, selection.from, selection.to).length > 0; - const local = typoFix || ownFix || contributedIntentions(this.view).length > 0; + this.asked?.abort(); + const asked = (this.asked = new AbortController()); + const found = contributedIntentionsAsync(this.view, asked.signal); const backoff = codeActionBackoff.active(doc.doc); let actions: CodeAction[] = []; if (!backoff) { @@ -734,6 +753,7 @@ const bulbPlugin = ViewPlugin.fromClass( if (isUnavailable(e)) codeActionBackoff.mark(doc.doc); } } + const local = typoFix || ownFix || contributedIntentions(this.view).length > 0 || (await found).length > 0; if (this.view.state.doc !== state.doc || !this.view.state.selection.eq(state.selection) || !this.view.hasFocus) return; const line = state.doc.lineAt(state.selection.main.head).number; @@ -751,6 +771,7 @@ const bulbPlugin = ViewPlugin.fromClass( } destroy() { this.lookup.cancel(); + this.asked?.abort(); } }, ); diff --git a/src/editor/refactor/safeDelete.ts b/src/editor/refactor/safeDelete.ts index 00ff875826..e5a4082c4f 100644 --- a/src/editor/refactor/safeDelete.ts +++ b/src/editor/refactor/safeDelete.ts @@ -26,7 +26,7 @@ import { confirmChecked } from "@/workbench/messages"; import { openPopup, type PreviewOccurrence } from "@/editor/lsp/popupStore"; import { cannotPerform } from "./catalog"; import { cancelled, languageName } from "./query"; -import { tx } from "@/platform/i18n"; +import { tx, txPart } from "@/platform/i18n"; import { askUsagesDetected } from "./SafeDeleteUsages"; // --------------------------------------------------------------------------- @@ -364,7 +364,7 @@ function previewTextOccurrences( }); openPopup({ kind: "preview", - title: tx`Safe Delete ${target.kind} '${target.name}'`, + title: tx`Safe Delete ${txPart(target.kind)} '${target.name}'`, summary: { files: 1, occurrences: occurrences.length, @@ -409,7 +409,7 @@ export async function safeDelete(view: EditorView): Promise { // IDEA always confirms first; usages are searched after OK. const confirmed = await confirmChecked({ title: "Safe Delete", - message: tx`Delete ${target.kind} '${target.name}'?`, + message: tx`Delete ${txPart(target.kind)} '${target.name}'?`, presentation: "form", ok: "OK", checkbox: "Search in comments and strings", @@ -427,7 +427,7 @@ export async function safeDelete(view: EditorView): Promise { ]); if (view.state.doc !== docBefore) return; if (usages.length) { - const answer = await askUsagesDetected(tx`${target.kind} '${target.name}'`, usages); + const answer = await askUsagesDetected(tx`${txPart(target.kind)} '${target.name}'`, usages); if (answer === "view") viewUsages(target.name, usages); else if (answer === "delete") applyDeletion(view, docBefore, target, comments); else view.focus(); diff --git a/src/features/agents/InstallSkillDialog.tsx b/src/features/agents/InstallSkillDialog.tsx new file mode 100644 index 0000000000..e1a3e26e95 --- /dev/null +++ b/src/features/agents/InstallSkillDialog.tsx @@ -0,0 +1,392 @@ +import clsx from "clsx"; +import { useCallback, useEffect, useRef, useState } from "react"; +import type { + AgentSkillState, + McpScope, + RemoteSkillBrowseResult, + RemoteSkillCandidate, + RemoteSkillPreview, + RequestId, + SkillScanWarningKind, +} from "@/bindings"; +import { formatMessage, useTx } from "@/platform/i18n"; +import { commands, isCancelled, nextRequestId } from "@/platform/ipc"; +import { Button, Checkbox, Dialog, Icon, Input, Select, Tabs, T, selectableText } from "@/ui"; +import type { SkillsBackend } from "./skillsModel"; +import page from "./SettingsPage.module.css"; +import styles from "./SkillsPage.module.css"; + +type PreviewTab = "markdown" | "files"; + +function formatBytes(bytes: number): string { + if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`; + if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KiB`; + return `${bytes} B`; +} + +const WARNING_KIND_LABELS: Record = { + hiddenUnicode: "Hidden Unicode", + outOfRootSymlink: "Out-of-root symlink", + executableScript: "Executable script", + allowedToolsShell: "Shell tool grant", +}; + +export function InstallSkillDialog({ + backend, + hasTrustedProject, + onInstalled, + onClose, +}: { + backend: SkillsBackend; + hasTrustedProject: boolean; + onInstalled: (next: AgentSkillState[]) => void; + onClose: () => void; +}) { + const tx = useTx(); + const [source, setSource] = useState(""); + const [scope, setScope] = useState("user"); + const [browseResult, setBrowseResult] = useState(null); + const [selectedSubpath, setSelectedSubpath] = useState(null); + const [preview, setPreview] = useState(null); + const [previewTab, setPreviewTab] = useState("markdown"); + const [confirmedWarnings, setConfirmedWarnings] = useState(false); + const [overwrite, setOverwrite] = useState(false); + const [loading, setLoading] = useState(false); + const [installing, setInstalling] = useState(false); + const [error, setError] = useState(null); + const activeReq = useRef(null); + + const cancelInFlight = useCallback(() => { + if (activeReq.current != null) { + void commands.cancelRequest?.(activeReq.current); + activeReq.current = null; + } + }, []); + + useEffect(() => () => cancelInFlight(), [cancelInFlight]); + + const loadPreview = useCallback( + async (res: RemoteSkillBrowseResult, candidate: RemoteSkillCandidate) => { + if (!backend.preview) return; + cancelInFlight(); + const req = nextRequestId(); + activeReq.current = req; + setSelectedSubpath(candidate.subpath); + setPreview(null); + setConfirmedWarnings(false); + setOverwrite(false); + setError(null); + setLoading(true); + try { + const loaded = await backend.preview(res.owner, res.repo, res.gitRef, candidate.subpath, req); + if (activeReq.current === req) { + setPreview(loaded); + activeReq.current = null; + } + } catch (e: unknown) { + if (!isCancelled(e)) { + setError(e instanceof Error ? e.message : String(e)); + } + } finally { + if (activeReq.current === req || activeReq.current == null) { + setLoading(false); + } + } + }, + [backend, cancelInFlight], + ); + + const fetchRepository = useCallback(async () => { + const trimmed = source.trim(); + if (!trimmed || !backend.browse) return; + cancelInFlight(); + const req = nextRequestId(); + activeReq.current = req; + setLoading(true); + setError(null); + setBrowseResult(null); + setPreview(null); + setSelectedSubpath(null); + setConfirmedWarnings(false); + setOverwrite(false); + try { + const res = await backend.browse(trimmed, req); + if (activeReq.current !== req) return; + activeReq.current = null; + setBrowseResult(res); + const first = res.skills[0]; + if (first) { + await loadPreview(res, first); + } else { + setLoading(false); + } + } catch (e: unknown) { + if (!isCancelled(e)) { + setError(e instanceof Error ? e.message : String(e)); + } + setLoading(false); + } + }, [backend, cancelInFlight, loadPreview, source]); + + const alreadyExists = + preview != null && (scope === "workspace" ? preview.alreadyInstalledWorkspace : preview.alreadyInstalledUser); + const needsWarningConfirm = (preview?.scanWarnings.length ?? 0) > 0; + const canInstall = + !!preview && + !loading && + !installing && + (!needsWarningConfirm || confirmedWarnings) && + (!alreadyExists || overwrite); + + const handleInstall = async () => { + if (!preview || !backend.install || !canInstall) return; + cancelInFlight(); + const req = nextRequestId(); + activeReq.current = req; + setInstalling(true); + setError(null); + try { + const next = await backend.install( + { + owner: preview.owner, + repo: preview.repo, + gitRef: preview.gitRef, + subpath: preview.subpath, + scope, + confirmWarnings: confirmedWarnings, + overwrite, + }, + req, + ); + activeReq.current = null; + onInstalled(next); + } catch (e: unknown) { + if (!isCancelled(e)) { + setError(e instanceof Error ? e.message : String(e)); + } + } finally { + setInstalling(false); + } + }; + + const handleClose = () => { + cancelInFlight(); + onClose(); + }; + + return ( + void handleInstall(), + }, + { label: "Cancel", role: "cancel", onClick: handleClose }, + ]} + > +
+

+ + Enter a GitHub repository (owner/repo, owner/repo@skill, owner/repo/path@ref, or a GitHub URL). Only the + chosen skill folder is downloaded after preview and static scan. + +

+ +
+ setSource(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter") { + e.preventDefault(); + e.stopPropagation(); + void fetchRepository(); + } + }} + placeholder={tx("owner/repo, owner/repo@skill, or GitHub URL")} + aria-label={tx("Skill repository")} + autoFocus + /> + +
+ +
+ + Install location + + { - const next = event.currentTarget.value; - setDraft(next); - if (isValid(next)) onValid(next); - }} - onBlur={() => setDraft(null)} - onFocus={(event) => event.currentTarget.select()} - /> - - ); -} - -function Picker({ id, request }: { id: number; request: PickerRequest }) { - const [value, setValue] = useState(request.value); - const [recent] = useState(readRecent); - const [sampling, setSampling] = useState(false); - const t = useTx(); - const eyeDropper = (window as EyeDropperWindow).EyeDropper; +function EditorPicker({ id, request }: { id: number; request: PickerRequest }) { useEffect(() => { const close = () => { if (sequence === id) closeColorPicker(); @@ -156,154 +72,18 @@ function Picker({ id, request }: { id: number; request: PickerRequest }) { return () => request.view.scrollDOM.removeEventListener("scroll", close); }, [id, request.view]); - const update = (next: Rgba) => { - if (sequence !== id || !active) return; - setValue(next); - active = { ...active, value: next }; - request.onChange?.(next); - }; - const channel = (index: 0 | 1 | 2, text: string) => { - const number = Number(text); - const next: Rgba = [...value]; - next[index] = number; - update(next); - }; - const alpha = (text: string) => { - const number = Number(text); - update([value[0], value[1], value[2], number / 100]); - }; - const hex = (text: string) => { - const next = fromHex(text); - if (next) update(next); - }; - const numeric = (max: number) => (text: string) => /^\d{1,3}$/.test(text) && Number(text) <= max; - const sampleScreen = async () => { - if (!eyeDropper || sampling) return; - setSampling(true); - try { - const result = await new eyeDropper().open(); - const next = fromHex(result.sRGBHex); - if (next && sequence === id && active) update(next); - } catch (error) { - if (!(error instanceof DOMException && error.name === "AbortError")) console.warn(error); - } finally { - if (sequence === id && active) setSampling(false); - } - }; - return ( - closeColorPicker(reason !== "escape")} - aria-label={t("Color picker")} - className={styles.popup} - trapFocus - closeOnDeactivate={false} - > -
{ - event.preventDefault(); - if (!event.currentTarget.querySelector('[aria-invalid="true"]')) closeColorPicker(true); - }} - > -
- update([r, g, b, a])} - /> -
- void sampleScreen()} - /> -
- -
-
-
-
- channel(0, v)} - /> - channel(1, v)} - /> - channel(2, v)} - /> - - fromHex(v) !== null} - onValid={hex} - /> -
- {recent.length > 0 && ( -
- {recent.map((hex) => ( - - ))} -
- )} -
- - -
-
-
+ initial={request.value} + onChange={(value) => { + if (sequence !== id || !active) return; + active = { ...active, value }; + request.onChange?.(value); + }} + onFinish={(commit) => { + if (sequence === id) closeColorPicker(commit); + }} + /> ); } diff --git a/src/features/color-preview/colors.ts b/src/features/color-preview/colors.ts index 84dbb7bbbb..82b2093e28 100644 --- a/src/features/color-preview/colors.ts +++ b/src/features/color-preview/colors.ts @@ -1,3 +1,6 @@ +import { hex2, toHex6, type Rgba } from "@/ui/colorPickerValues"; +export { fromHex, toHex6, toHex8, type Rgba } from "@/ui/colorPickerValues"; + /** * Color literals of a line for the gutter's color preview: `#rgb` / `#rrggbb` (with alpha), * `rgb()` / `rgba()` / `hsl()` / `hsla()`, and CSS named colors in style sheets. Pure; the @@ -14,9 +17,6 @@ export interface ColorMatch { format: ColorFormat; } -/** Red, green, blue 0–255 and alpha 0–1. */ -export type Rgba = [number, number, number, number]; - /** Style sheet languages: named colors and unquoted hex values are colors there. */ const STYLE_SHEETS = new Set(["css", "scss", "sass", "less", "stylus", "postcss"]); /** Markup that embeds style sheets (`