Compare commits

...
Author SHA1 Message Date
l0ng-ai 9b59961127 fix(debugger): keep values readable beside long type labels 2026-11-22 15:45:28 +08:00
LU XIANGRUIandwildcatDownstairs 8e541d5b45 feat(run): run node:test tests with a test tree and Rerun Failed Tests (#5172)
`node --test` runs showed no test tree, and single tests ran with Jest's `-t`.

- Detection: a `package.json` script whose Node options include `--test` (also `tsx --test`) is a test configuration with `testRunner: "node-test"`; a script that picks its own `--test-reporter` runs as written.
- Test tree: test runs add the IDE's reporter (`nodeTestReporter.js`, passed as a `data:` URL) next to `spec` through `NODE_OPTIONS`, which works through `npm run`, Node's per-file child processes and remote run targets. It prints a record per test (file, describe chain, status, duration, declaration line, error); the records become the tree and are hidden from the console, which keeps `spec`'s output.
- Gutter, Rerun Failed Tests, run selected tests: select by full name with `--test-name-pattern` in `NODE_OPTIONS`, plus the files.

New fixture `fixtures/node-test-app`, run by `smoke/run.test.ts` in the TypeScript job.

Closes #5152

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 15:19:57 +08:00
LU XIANGRUIandwildcatDownstairs 87c4659547 fix(i18n): insert tx template values as written (#5177)
In the Chinese UI, Rename on a folder named `tasks` read 将目录“任务”及其用法重命名为:. The `tx` template tag translated every interpolated string that had a catalog entry of its own, so a file, branch, script or container name that matched a UI word (`tasks`, `Retry`) was shown translated. Values are now inserted as written. Call sites that interpolate the app's own UI words (kind labels, option titles, "Source"/"Target") mark them with the new `txPart(...)`, which is also translated again after a language change; the text catalog guard checks `txPart` literals too. `txTemplate` still translates captured parts.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 15:14:54 +08:00
l0ng-ai 3475dbd688 fix: restore frontend tests after the skill installer and Python Console (#5182)
Three frontend tests failed on main after #5157 and #5164: SkillsPage.module.css read an undeclared --r-sm (now --radius-small); the SKILL.md catalog entry is a file name kept as written in Chinese, so it joins the same-as-English list; and the VS Code presets lacked python.console.executeSelection, which stays unbound there because Shift+Enter would shadow typing in Python files.
2026-11-22 15:14:02 +08:00
Deng Liuanddengliu 0800e8445f feat(agents): native GitHub skill browser, preview, static scan, and installer (#5157)
Settings › Agents › Skills gets Install Skill…: enter a GitHub source in the forms `npx skills add` accepts (`owner/repo`, `owner/repo@skill`, `owner/repo#ref`, `owner/repo/path[@ref]`, GitHub tree URLs, pasted skills.sh links), pick one of the skills found, preview its `SKILL.md` and file list, and install it into `~/.agents/skills` (default) or the workspace `.agents/skills` (trusted projects only). Sources resolve through GitHub's Git Trees and Blobs APIs over the existing `ide-tools` HTTP client, with no curated repository list and no Node or git dependency, retrying unauthenticated when an ambient GitHub token gets HTTP 401 on a public repository. Only the selected skill's subtree is downloaded (capped at 2 MiB / 256 files) and installed atomically through a staging folder. A static scan flags hidden or bidirectional Unicode, out-of-root symlinks (omitted on disk), executable scripts and `allowed-tools` shell grants; the user must confirm the warnings, and the backend checks that confirmation again before writing.

Part of #5115

Co-authored-by: dengliu <[email protected]>
2026-11-22 15:09:01 +08:00
Deng Liuanddengliu b7ac5f1bbb feat(plugins): declarative [[contributes.skills]] in plugin.toml (API 1.15) (#5144)
Plugins can now bundle `SKILL.md` folders with a manifest-only `[[contributes.skills]]` extension point (API 1.15, no WIT change). They appear under Plugins in Settings › Agents › Skills and the Composer Skills picker while the plugin is enabled, and are staged into each CLI's per-session skill folder from the plugin's package directory; disabling or uninstalling the plugin removes them right away. Load-time validation keeps `path` inside the package (no `..` or escaping symlinks), requires `<dir>/SKILL.md` with the usual folder-name and frontmatter rules, and caps a skill folder at 2 MiB / 256 files; an invalid entry becomes a plugin load warning without failing the rest of the plugin. Every file of a valid skill folder is part of the package files, so versioned installs and remote sync copy supporting scripts and references. Workspace and user skills win on a name clash. Includes a declarative fixture plugin and docs.

Closes #5114

Co-authored-by: dengliu <[email protected]>
2026-11-22 15:02:11 +08:00
l0ng-ai f473cd9927 fix(agents): give Codex skill paths one separator on Windows (#5158)
Skill roots are joined as `.agents/skills`, so a SKILL.md path that could not be canonicalized kept a forward slash on Windows and failed hub_staging_hands_each_cli_its_own_tree. Rebuild the path from its components before handing it to Codex.
2026-11-22 14:44:44 +08:00
LU XIANGRUIandwildcatDownstairs 9a3b97a5fa feat(python): flag requirements the interpreter does not satisfy and offer to install them (#5168)
`requirements*.txt` and `pyproject.toml` (`[project]` dependencies, optional dependencies, `[dependency-groups]`) now mark each requirement the project's interpreter doesn't have installed, or whose installed version misses the specifier. A banner offers Install requirements, and the quick fixes are Install requirement and Install all missing requirements; installs use the same pip/uv path as the interpreter settings page, run as a background task, report failures in one notification and re-check the file. The interpreter judges the requirements itself (with `packaging` or pip's vendored copy), so PEP 440 specifiers, PEP 503 names and markers behave as pip does; Rust only parses the files for spans, skipping `-r`, `-e`, options, URLs and paths. Nothing is checked without a local interpreter, for a container interpreter, or in Restricted Mode. It is a new inspection, "Unsatisfied package requirements", and the Cargo version check now shares the same editor plugin (`manifestCheck.ts`).

Closes #5147

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 14:43:09 +08:00
LU XIANGRUIandwildcatDownstairs c632dfa01c feat(python): add a Python Console tool window (#5164)
Adds a Python Console tool window: an interactive interpreter of the project's Python (the one Settings and the status bar show; in a workspace, the member the active file is in), started in the project root with the source roots on `PYTHONPATH`. It uses IPython when the interpreter has it and plain Python otherwise, in its own `__main__`. Enter runs the input, Shift+Enter adds a line, Up/Down recall earlier inputs, and while code runs a typed line answers its `input()`. A Variables pane lists the console's globals after each run. Execute Selection in Python Console (`python.console.executeSelection`, Alt+Shift+E, also in the editor context menu of Python files) sends the selection or the current line, starting the console if needed; a selection inside an indented block is dedented. The console is a small driver script run on the existing Run process host, so there are no backend changes.

Closes #5148

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 14:34:50 +08:00
LU XIANGRUIandwildcatDownstairs 88f494ca50 feat(debugger): view pandas and numpy values as a table (#5166)
In a Python debug session, a DataFrame, Series or ndarray variable or watch only showed a one-line repr. It now has View as Table in its context menu: a resizable window with column headers (with dtypes for a DataFrame), the index, the shape, and pagers for rows (100 per page) and columns (30 per page). Each page is one `evaluate` in the paused frame: a small helper slices the object in the debuggee and returns only that page as JSON, so the whole object never goes over DAP. The expression can be edited (e.g. `a[0]` for a 3-D array), and the window stays open across steps, refreshing after each step or frame change.

Closes #5165

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 14:31:17 +08:00
LU XIANGRUIandwildcatDownstairs 9b4ee2a6ff feat(run): run Playwright tests with a test tree and Rerun Failed Tests (#5169)
A Playwright project had no test tree and no Rerun Failed Tests: its output went through the Jest / Vitest parser, single tests ran with Jest's `-t`, and projects without a `test` script weren't detected at all.

- Detection: a `package.json` script that runs `playwright test` is a test configuration and records `testRunner: "playwright"` (new optional `RunExtras.test_runner`, `test-runner` in `run.toml`); a package with a `playwright.config.*` that no script runs gets `npx playwright test`.
- Test tree: test runs add `--reporter=list` unless a reporter is named, parsed into file › [project] › describe chain › test with status, duration, location and failure details.
- Gutter: `test.describe` blocks and `fixme` / `fail` / `serial` tests get run / debug icons and run by declaration line (`file:line`); in a project with Playwright and another runner, specs run on Playwright's configuration and other tests on the other runner's.
- Rerun Failed Tests / run selected tests: the files plus `--grep` on the describe chain and title, with `--project` when the run named projects.

New fixture `fixtures/playwright-app`; `smoke/run.test.ts` runs it after `ts-app`.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 14:30:06 +08:00
LU XIANGRUIandwildcatDownstairs e75d438f70 feat(python): update imports when a module or package is renamed or moved (#5171)
Renaming or moving a Python module or package left every import of it broken: basedpyright has no `workspace/willRenameFiles`, so no reference updates reached the move preview. `refactor_file_move_edits` now maps the moved paths to dotted module names from the project's Python roots (`src/` layout or the project root, `tests/`), and `Syntax::python_import_edits` rewrites the import statements of each project `.py`/`.pyi` file from its tree-sitter tree. It covers `import a.b` (with qualified uses `a.b.X`), `import a.b as c`, `from a.b import X`, `from a import b`, relative imports (kept relative, also in the moved files themselves) and package moves; when a rename changes the name an import binds, the import keeps it with an alias. The edits join the existing move preview and undo. A Python server that answers `willRenameFiles` still wins. The Python language smoke now checks file moves.

Closes #5146

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 14:26:50 +08:00
LU XIANGRUIandwildcatDownstairs a67b27c33a feat(editor): highlight CSS, GraphQL, SQL and HTML in template literals (#5160)
In JavaScript and TypeScript files, embedded code in template literals showed as one string. The body of a tagged template literal is now parsed in the language its tag names: CSS for styled-components / emotion / Lit (`styled.div`, `styled(Comp)`, `.attrs(…)`, `css`, `createGlobalStyle`, `keyframes`, `injectGlobal`, parsed as declarations plus nested rules), GraphQL for `gql` / `graphql` (also the `graphql(`…`)` call form), SQL for `sql` and HTML for `html`; a `/* GraphQL */`-style comment before a plain literal works too. Substitutions stay JavaScript. CSS, SQL and HTML use the same modes as files in those languages; GraphQL gets a small stream mode used only inside literals (`.graphql` files keep tree-sitter highlighting). The embedded mode loads lazily, comment toggling and bracket matching follow it, and Angular TypeScript files and Markdown `ts` fences get the same injection.

Closes #5150

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 14:24:24 +08:00
Akbar Husain 62028362d6 feat(remote): forward ports of a WSL project (#5140)
The Ports tool window existed only for SSH hosts and dev containers; a WSL project refused to forward. A WSL distribution shares this machine's loopback (as `forward_web_url` already assumes), so a port it listens on is reachable here on the same port without a tunnel. The route decision is now a pure `forward_route(target, host)` (SSH channel tunnel, container exec tunnel, or WSL's shared loopback; another host stays reachable from a dev container only), and `Forward::Wsl` reports the port unchanged and owns no resource. The Ports tool window registers for WSL sessions, remembered ports are scoped per distribution and folder (`wsl:<distro>:<root>`), the refusal and its string are gone, and the remote docs describe it.

Co-authored-by: akbar1214 <[email protected]>
2026-11-22 14:23:05 +08:00
173 changed files with 8504 additions and 406 deletions

No files matched your search

Generated
+1
View File
@@ -4146,6 +4146,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
name = "ide-agent"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"blake3",
"dunce",
"encoding_rs",
+1
View File
@@ -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
+17 -3
View File
@@ -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};
@@ -145,11 +150,19 @@ pub struct SkillsPolicy {
pub workspace_trusted: bool,
/// All workspace folders (the project root plus any multi-repo workspace members).
pub workspace_roots: Vec<PathBuf>,
/// Validated `<dir>` folders contributed by live OpenIDEA plugins (`[[contributes.skills]]`).
pub plugin_dirs: Vec<PathBuf>,
}
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(),
}
}
}
@@ -818,10 +831,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,
@@ -2142,7 +2156,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,
+3 -1
View File
@@ -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)
}
}
File diff suppressed because it is too large. Load diff
+123 -18
View File
@@ -247,6 +247,17 @@ pub fn discover_skills(workspace: &Path, home: Option<&Path>) -> Vec<AgentSkill>
/// 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<AgentSkill> {
discover_skills_with_plugins(workspaces, home, &[])
}
/// [`discover_skills_in`] plus the `<dir>` 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<AgentSkill> {
let mut out: Vec<AgentSkill> = Vec::new();
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
let mut seen_names: HashSet<String> = HashSet::new();
@@ -273,29 +284,59 @@ pub fn discover_skills_in(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Ag
}
if let Some(home) = home {
roots.extend(HOME_ROOTS.iter().map(|(rel, source)| (home.join(rel), *source)));
roots.extend(copilot_installed_plugin_roots(&home.join(".copilot")));
}
let mut push_skill = |skill: AgentSkill| {
let path = dunce::canonicalize(&skill.path.0).unwrap_or_else(|_| skill.path.0.clone());
if !seen_paths.insert(path.clone()) {
if let Some(existing) = out.iter_mut().find(|s| s.path.0 == path)
&& existing.source != skill.source
&& !existing.also_in.contains(&skill.source)
{
existing.also_in.push(skill.source);
}
return;
}
if !seen_names.insert(skill.name.to_ascii_lowercase()) {
return;
}
out.push(AgentSkill { path: path.into(), ..skill });
};
for (root, source) in roots {
for skill in skills_of(&root, source) {
let path = dunce::canonicalize(&skill.path.0).unwrap_or_else(|_| skill.path.0.clone());
if !seen_paths.insert(path.clone()) {
if let Some(existing) = out.iter_mut().find(|s| s.path.0 == path)
&& existing.source != source
&& !existing.also_in.contains(&source)
{
existing.also_in.push(source);
}
continue;
push_skill(skill);
}
}
for dir in plugin_skill_dirs {
let Some(folder) = file_name(dir) else { continue };
if !dir.is_dir() {
continue;
}
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
push_skill(parse_skill_file(dir, &folder, &text, AgentSkillSource::Plugin));
}
if let Some(home) = home {
for (root, source) in copilot_installed_plugin_roots(&home.join(".copilot")) {
for skill in skills_of(&root, source) {
push_skill(skill);
}
if !seen_names.insert(skill.name.to_ascii_lowercase()) {
continue;
}
out.push(AgentSkill { path: path.into(), ..skill });
}
}
out
}
/// Validates a plugin-contributed `<folder>/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<AgentSkill, String> {
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"];
@@ -662,11 +703,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::<PathBuf>().to_string_lossy().into_owned()
}
fn direct_link_matches(root: &Path, name: &str, target: &Path) -> bool {
@@ -1330,4 +1372,67 @@ 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());
}
}
+1 -2
View File
@@ -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()
}
}));
+22 -1
View File
@@ -122,13 +122,34 @@ pub struct Prepared {
pub key: Option<String>,
/// 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<String>,
/// Makes it take effect. Must not fail for reasons `prepare` could have checked.
pub commit: Commit,
}
impl Prepared {
pub fn new(label: impl Into<String>, commit: impl FnOnce() -> Result<Disposable, String> + 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<String>) -> 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<String>) -> Self {
+6
View File
@@ -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());
+164 -27
View File
@@ -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<Vec<AgentSkillState>> {
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<RemoteSkillBrowseResult> {
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<RemoteSkillPreview> {
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 `<workspace>/.agents/skills` (Workspace).
#[command(trust = always)]
pub async fn agent_skills_install(
host: &Host,
window: &str,
input: InstallRemoteSkillRequest,
request: RequestId,
) -> IdeResult<Vec<AgentSkillState>> {
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.<name>]`).
@@ -1173,13 +1282,38 @@ pub(crate) fn workspace_skill_roots(root: &std::path::Path) -> Vec<std::path::Pa
roots
}
/// The skill policies a session of `project` resolves against.
fn skills_policy(project: &crate::Project) -> 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,
+99 -2
View File
@@ -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<Option<PythonRequirements>> {
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);
+127 -3
View File
@@ -3,10 +3,14 @@
use crate::Host;
use ide_command::command;
use ide_core::{IdeResult, RequestId, WorkspaceEdit};
use ide_core::{FileEdit, IdeResult, RequestId, WorkspaceEdit};
use ide_language::Syntax;
use ide_lsp::types::FileRenameEdits;
use ide_workspace::file_moves::moved_path;
use ide_workspace::roots::{ProjectRoots, RootKind};
use ide_workspace::{FileMove, UndoOutcome};
use std::path::PathBuf;
use parking_lot::Mutex;
use std::path::{Path, PathBuf};
use super::doc::blocking;
@@ -24,16 +28,110 @@ pub async fn refactor_file_move_edits(
) -> IdeResult<FileRenameEdits> {
let project = host.project(window)?;
let token = host.begin_request(request);
let result = project.lsp.will_rename_files(&pairs(&moves), token).await;
let result = project.lsp.will_rename_files(&pairs(&moves), token.clone()).await;
host.end_request(request);
let mut result = result?;
let syntax = host.syntax();
blocking(move || {
// basedpyright has no `workspace/willRenameFiles`; a Python server that answered wins.
if !result.edit.files.iter().any(|f| matches!(f, FileEdit::Edit { path, .. } if is_python(path))) {
let python = python_import_edits(&project, &syntax, &moves, &|| token.is_cancelled());
result.edit.files.extend(python.files);
}
project.documents.prepare_workspace_edit(&mut result.edit)?;
Ok(result)
})
.await
}
fn is_python(path: &Path) -> bool {
path.extension().is_some_and(|e| e == "py" || e == "pyi")
}
/// The dotted name of a Python module file or package folder, from its project's Python roots
/// (`src/a/b.py` → `a.b` in a `src` layout).
fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -> Option<String> {
let rel = path.strip_prefix(root).ok()?.to_string_lossy().replace('\\', "/");
let base = roots
.root_for(&rel)
.filter(|r| matches!(r.kind, RootKind::Source | RootKind::Test))
.map_or("", |r| r.path.as_str());
let inner = if base.is_empty() { rel.as_str() } else { rel.strip_prefix(base)?.trim_start_matches('/') };
let inner = if is_dir { inner } else { inner.strip_suffix(".py").or_else(|| inner.strip_suffix(".pyi"))? };
let inner = inner.strip_suffix("/__init__").unwrap_or(inner);
let valid = |s: &str| {
s.chars().next().is_some_and(|c| !c.is_ascii_digit()) && s.chars().all(|c| c == '_' || c.is_alphanumeric())
};
(!inner.is_empty() && inner.split('/').all(valid)).then(|| inner.replace('/', "."))
}
/// The package relative imports in `file` start from.
fn python_package(root: &Path, roots: &ProjectRoots, file: &Path) -> String {
let Some(module) = python_module(root, roots, file, false) else { return String::new() };
if file.file_stem().is_some_and(|s| s == "__init__") {
module
} else {
module.rsplit_once('.').map_or(String::new(), |(p, _)| p.to_owned())
}
}
/// Import updates in the project's Python files for `moves` (paths before the move).
fn python_import_edits(
project: &crate::project::Project,
syntax: &Syntax,
moves: &[FileMove],
cancelled: &(dyn Fn() -> bool + Sync),
) -> WorkspaceEdit {
let root = &project.root;
let roots = project.roots();
let renames: Vec<(String, String)> = moves
.iter()
.filter_map(|m| {
let is_dir = m.from.is_dir();
if !is_dir && (!is_python(&m.from) || m.from.file_stem().is_some_and(|s| s == "__init__")) {
return None;
}
let old = python_module(root, &roots, &m.from, is_dir)?;
let new = python_module(root, &roots, &m.to, is_dir)?;
(old != new).then_some((old, new))
})
.collect();
if renames.is_empty() {
return WorkspaceEdit::default();
}
let names: Vec<&str> = renames.iter().map(|(old, _)| old.rsplit('.').next().unwrap_or(old)).collect();
let found: Mutex<Vec<(PathBuf, Vec<ide_core::TextEdit>)>> = Mutex::new(Vec::new());
ide_vfs::walk_files(root, &project.exclude_globs(), |path| {
if cancelled() || !is_python(path) {
return;
}
let moved = moved_path(path, moves);
let text = match project.documents.text_of(path) {
Some(t) => t,
None => match std::fs::read_to_string(path) {
Ok(t) => t,
Err(_) => return,
},
};
if moved == path && !names.iter().any(|n| text.contains(n)) {
return;
}
let edits = syntax.python_import_edits(
&text,
&python_package(root, &roots, path),
&python_package(root, &roots, &moved),
&renames,
);
if !edits.is_empty() {
found.lock().push((path.to_path_buf(), edits));
}
});
let mut files = found.into_inner();
files.sort_by(|a, b| a.0.cmp(&b.0));
let files = files.into_iter().map(|(path, edits)| FileEdit::Edit { path: path.into(), edits, version: None });
WorkspaceEdit { files: files.collect(), ..Default::default() }
}
/// Applies `edit` (from [`refactor_file_move_edits`], possibly empty), moves the
/// files and notifies the servers. Returns the id for [`refactor_undo_file_move`].
#[command(trust = always)]
@@ -111,3 +209,29 @@ ide_command::domain!(
refactor_move_files,
refactor_undo_file_move,
);
#[cfg(test)]
mod tests {
use super::*;
use ide_workspace::roots::SourceFolder;
#[test]
fn python_module_names_follow_the_roots() {
let root = Path::new("/p");
let folder = |path: &str, kind| SourceFolder { path: path.into(), kind, detected_from: None };
let roots = ProjectRoots::compute(
vec![folder("src", RootKind::Source), folder("tests", RootKind::Test)],
&Default::default(),
);
let name = |p: &str, dir| python_module(root, &roots, &root.join(p), dir);
assert_eq!(name("src/tasks/models.py", false).as_deref(), Some("tasks.models"));
assert_eq!(name("src/tasks/__init__.py", false).as_deref(), Some("tasks"));
assert_eq!(name("src/tasks", true).as_deref(), Some("tasks"));
assert_eq!(name("tests/test_models.py", false).as_deref(), Some("test_models"));
assert_eq!(name("scripts/run.pyi", false).as_deref(), Some("scripts.run"));
assert_eq!(name("my-scripts/run.py", false), None);
assert_eq!(name("src/tasks/notes.txt", false), None);
assert_eq!(python_package(root, &roots, &root.join("src/tasks/cli.py")), "tasks");
assert_eq!(python_package(root, &roots, &root.join("src/tasks/__init__.py")), "tasks");
}
}
+31 -24
View File
@@ -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<PathBuf> {
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<Option<ide_core::IpcPath>> {
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`.
+19 -1
View File
@@ -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<run_detectors::RunDetectors>,
/// `[[contributes.javaAgents]]` of enabled plugins.
java_agents: Arc<java_agents::JavaAgents>,
/// `[[contributes.skills]]` of enabled plugins.
skills: Arc<skills::PluginSkills>,
/// `[[contributes.providers]]` of enabled plugins.
providers: Arc<providers::Providers>,
navigation: Mutex<navigation::NavigationIndex>,
@@ -411,6 +414,8 @@ pub struct PluginHost {
announced_theme: Mutex<Option<ActiveTheme>>,
/// [`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<PathVar>,
/// (plugin id, `process:` capability) → the approved program; read by the
@@ -470,7 +475,8 @@ impl PluginHost {
let run_detectors: Arc<run_detectors::RunDetectors> = Arc::default();
let providers: Arc<providers::Providers> = Arc::default();
let java_agents: Arc<java_agents::JavaAgents> = Arc::default();
register_builtin_points(&registry, &ui, &languages, &run_detectors, &java_agents, &providers)
let skills: Arc<skills::PluginSkills> = Arc::default();
register_builtin_points(&registry, &ui, &languages, &run_detectors, &java_agents, &providers, &skills)
.map_err(IdeError::internal)?;
let pins: Arc<RwLock<HashMap<(String, String), ProgramPin>>> = 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 {
+2
View File
@@ -66,6 +66,7 @@ pub fn register_builtin_points(
run_detectors: &Arc<super::run_detectors::RunDetectors>,
java_agents: &Arc<super::java_agents::JavaAgents>,
providers: &Arc<super::providers::Providers>,
skills: &Arc<super::skills::PluginSkills>,
) -> 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)))?;
+250
View File
@@ -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<Vec<(u64, ContributedSkill)>>,
seq: AtomicU64,
revision: AtomicU64,
}
impl PluginSkills {
pub fn revision(&self) -> u64 {
self.revision.load(Ordering::Acquire)
}
fn add(self: &Arc<Self>, 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<PluginSkills>,
}
impl SkillsPoint {
pub fn new(store: Arc<PluginSkills>) -> 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<Prepared, String> {
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<Prepared, String> {
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 `<dir>/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 `<name>/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<PathBuf>,
files: &mut Vec<PathBuf>,
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 (`<plugin_dir>/<rel_dir>`) 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<PathBuf> {
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()
}
}
+8 -1
View File
@@ -765,13 +765,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 || {
+2 -2
View File
@@ -742,8 +742,8 @@ const PYTHON: Checks = Checks {
typed("src/tasks/models.py", "from enum import IntEnum", "import abc"),
Imports::Before("import os"),
)),
// basedpyright has no `workspace/willRenameFiles`.
file_move: None,
// basedpyright has no `workspace/willRenameFiles`: the IDE rewrites the imports.
file_move: Some(("src/tasks/models.py", "src/tasks/domain.py", "src/tasks/cli.py", "from .domain import")),
};
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+109
View File
@@ -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:?}");
}
+1
View File
@@ -12,6 +12,7 @@ mod literals;
mod outline;
mod php_align;
mod python_facts;
mod python_imports;
mod rst;
mod selection;
mod sfc;
@@ -0,0 +1,404 @@
//! Import updates for moved Python modules and packages, which basedpyright leaves to the
//! client (no `workspace/willRenameFiles`). Works on dotted module names; the caller maps
//! files to them from the project's roots.
use super::lines::LineIndex;
use crate::{LanguageId, Syntax};
use ide_core::TextEdit;
use tree_sitter::{Node, Tree};
impl Syntax {
/// Edits that keep the imports of a Python `text` resolving after `moves` (old → new
/// dotted names; a package covers its submodules). `package` is the package relative
/// imports start from (`a.b` for `a/b/c.py` and `a/b/__init__.py`), `new_package` the
/// same after the move.
pub fn python_import_edits(
&self,
text: &str,
package: &str,
new_package: &str,
moves: &[(String, String)],
) -> Vec<TextEdit> {
self.analyze(&LanguageId::new("python"), text, |_, tree, text| {
Some(Rewrite { text, idx: LineIndex::new(text), package, new_package, moves, edits: Vec::new() }.run(tree))
})
.unwrap_or_default()
}
}
struct Rewrite<'a> {
text: &'a str,
idx: LineIndex<'a>,
package: &'a str,
new_package: &'a str,
moves: &'a [(String, String)],
edits: Vec<TextEdit>,
}
impl Rewrite<'_> {
fn run(mut self, tree: &Tree) -> Vec<TextEdit> {
let mut imports = Vec::new();
let mut chains = Vec::new();
collect(tree.root_node(), &mut |n| match n.kind() {
"import_statement" | "import_from_statement" => imports.push(n),
"attribute" if !inside_import(n) => chains.push(n),
_ => {}
});
let mut renamed: Vec<(String, String)> = Vec::new();
for node in imports {
if node.kind() == "import_statement" {
self.import(node, &mut renamed);
} else {
self.import_from(node);
}
}
// `import a.b` is used as `a.b.x`: those chains follow the import.
for node in chains {
let t = self.src(node);
if let Some((_, new)) = renamed.iter().find(|(old, _)| *old == t) {
self.edit(node, new.clone());
}
}
self.edits.sort_by_key(|e| (e.range.start.line, e.range.start.col));
self.edits
}
fn src(&self, n: Node) -> &str {
self.text.get(n.byte_range()).unwrap_or_default()
}
fn edit(&mut self, n: Node, new_text: String) {
self.edits.push(TextEdit { range: self.idx.range(n.start_byte(), n.end_byte()), new_text });
}
/// `import a.b`, `import a.b as c`.
fn import(&mut self, node: Node, renamed: &mut Vec<(String, String)>) {
let mut cursor = node.walk();
for item in node.children_by_field_name("name", &mut cursor) {
let (name, aliased) = match item.kind() {
"aliased_import" => match item.child_by_field_name("name") {
Some(n) => (n, true),
None => continue,
},
_ => (item, false),
};
let old = self.src(name).to_owned();
let Some(new) = map_module(&old, self.moves) else { continue };
if aliased {
self.edit(name, new);
} else if old.contains('.') {
renamed.push((old, new.clone()));
self.edit(name, new);
} else {
// The bound name stays, so the rest of the file needs no change.
self.edit(name, format!("{new} as {old}"));
}
}
}
/// `from m import x`, `from .m import x as y`, `from . import m`.
fn import_from(&mut self, node: Node) {
let Some(module) = node.child_by_field_name("module_name") else { return };
let relative = (module.kind() == "relative_import").then(|| {
let mut cursor = module.walk();
let dots = module
.children(&mut cursor)
.find(|c| c.kind() == "import_prefix")
.map_or(0, |p| self.src(p).matches('.').count());
let rest = module.child(1).filter(|c| c.kind() == "dotted_name").map_or("", |c| self.src(c));
(dots, rest.to_owned())
});
let source = match &relative {
Some((dots, rest)) => match resolve(*dots, rest, self.package) {
Some(s) => s,
None => return,
},
None => self.src(module).to_owned(),
};
let target = map_module(&source, self.moves).unwrap_or_else(|| source.clone());
// Imported submodules that moved on their own (`from pkg import models`).
let mut cursor = node.walk();
let names: Vec<Node> = node.children_by_field_name("name", &mut cursor).collect();
let mut moved: Vec<(Node, String, String, String)> = Vec::new(); // (item, parent, name, bound)
for &item in &names {
let (name, alias) = match item.kind() {
"aliased_import" => (item.child_by_field_name("name"), item.child_by_field_name("alias")),
_ => (Some(item), None),
};
let Some(name) = name else { continue };
let n = self.src(name).to_owned();
let full = join(&source, &n);
let Some(new) = map_module(&full, self.moves) else { continue };
if new == join(&target, &n) {
continue;
}
let (parent, last) =
new.rsplit_once('.').map_or((String::new(), new.clone()), |(p, l)| (p.into(), l.into()));
let bound = alias.map_or(n, |a| self.src(a).to_owned());
moved.push((item, parent, last, bound));
}
let as_name =
|last: &str, bound: &str| if last == bound { last.to_owned() } else { format!("{last} as {bound}") };
// Renamed inside the same package: only the name changes.
let in_place: Vec<(Node, String)> =
moved.iter().filter(|m| m.1 == target).map(|m| (m.0, as_name(&m.2, &m.3))).collect();
moved.retain(|m| m.1 != target);
let render = |module: &str, rw: &Self| match &relative {
Some((dots, rest)) if resolve(*dots, rest, rw.new_package).as_deref() == Some(module) => None,
Some(_) => Some(relative_to(module, rw.new_package).unwrap_or_else(|| module.to_owned())),
None => Some(module.to_owned()),
};
let all_one_parent = !moved.is_empty()
&& moved.len() == names.len()
&& moved.iter().all(|m| m.1 == moved[0].1 && !m.1.is_empty());
if all_one_parent {
let parent = moved[0].1.clone();
if let Some(m) = render(&parent, self).filter(|m| m != self.src(module)) {
self.edit(module, m);
}
for (item, _, last, bound) in moved {
let new = as_name(&last, &bound);
if new != self.src(item) {
self.edit(item, new);
}
}
return;
}
if moved.is_empty() {
if let Some(m) = render(&target, self).filter(|m| m != self.src(module)) {
self.edit(module, m);
}
for (item, text) in in_place {
self.edit(item, text);
}
return;
}
// ponytail: a split statement loses a multi-line names list's layout; fine for the rare
// "some names of one `from` moved elsewhere" case.
let indent = line_indent(self.text, node.start_byte());
let mut parents: Vec<&str> = Vec::new();
for m in &moved {
if !parents.contains(&m.1.as_str()) {
parents.push(&m.1);
}
}
let mut added: Vec<String> = Vec::new();
for parent in parents {
let items: Vec<String> = moved.iter().filter(|m| m.1 == parent).map(|m| as_name(&m.2, &m.3)).collect();
added.push(if parent.is_empty() {
format!("import {}", items.join(", "))
} else {
let from = render(parent, self).unwrap_or_else(|| self.src(module).to_owned());
format!("from {from} import {}", items.join(", "))
});
}
let kept: Vec<String> = names
.iter()
.filter(|n| !moved.iter().any(|m| m.0 == **n))
.map(|n| in_place.iter().find(|(i, _)| i == n).map_or_else(|| self.src(*n).to_owned(), |(_, t)| t.clone()))
.collect();
let sep = format!("\n{indent}");
if kept.is_empty() {
self.edit(node, added.join(&sep));
return;
}
if let Some(m) = render(&target, self).filter(|m| m != self.src(module)) {
self.edit(module, m);
}
let (first, last) = (names[0], names[names.len() - 1]);
let range = self.idx.range(first.start_byte(), last.end_byte());
self.edits.push(TextEdit { range, new_text: kept.join(", ") });
let end = self.idx.pos(node.end_byte());
self.edits.push(TextEdit {
range: ide_core::Range { start: end, end },
new_text: format!("{sep}{}", added.join(&sep)),
});
}
}
fn collect<'t>(node: Node<'t>, f: &mut impl FnMut(Node<'t>)) {
f(node);
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
collect(child, f);
}
}
fn inside_import(mut n: Node) -> bool {
while let Some(p) = n.parent() {
if matches!(p.kind(), "import_statement" | "import_from_statement" | "future_import_statement") {
return true;
}
n = p;
}
false
}
fn line_indent(text: &str, byte: usize) -> &str {
let start = text[..byte].rfind('\n').map_or(0, |i| i + 1);
&text[start..byte]
}
fn join(a: &str, b: &str) -> String {
match (a.is_empty(), b.is_empty()) {
(true, _) => b.to_owned(),
(_, true) => a.to_owned(),
_ => format!("{a}.{b}"),
}
}
/// `name` after `moves` (the longest moved prefix wins), if it changed.
fn map_module(name: &str, moves: &[(String, String)]) -> Option<String> {
moves
.iter()
.filter(|(from, _)| name == from || name.strip_prefix(from.as_str()).is_some_and(|r| r.starts_with('.')))
.max_by_key(|(from, _)| from.len())
.map(|(from, to)| format!("{to}{}", &name[from.len()..]))
.filter(|new| new != name)
}
/// The absolute module `from <dots><rest> import` names inside `package`.
fn resolve(dots: usize, rest: &str, package: &str) -> Option<String> {
let segs: Vec<&str> = package.split('.').filter(|s| !s.is_empty()).collect();
let keep = segs.len().checked_sub(dots.checked_sub(1)?)?;
if keep == 0 {
return None;
}
Some(join(&segs[..keep].join("."), rest))
}
/// The shortest relative form of `module` from `package`, if they share a top-level package.
fn relative_to(module: &str, package: &str) -> Option<String> {
let segs: Vec<&str> = package.split('.').filter(|s| !s.is_empty()).collect();
(1..=segs.len()).find_map(|dots| {
let base = segs[..segs.len() + 1 - dots].join(".");
let rest = if module == base { "" } else { module.strip_prefix(&base)?.strip_prefix('.')? };
Some(format!("{}{rest}", ".".repeat(dots)))
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::syntax::lines::byte_at;
fn apply(text: &str, package: &str, new_package: &str, moves: &[(&str, &str)]) -> String {
let moves: Vec<(String, String)> = moves.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect();
let mut edits = Syntax::new().python_import_edits(text, package, new_package, &moves);
edits.sort_by_key(|e| std::cmp::Reverse((e.range.start.line, e.range.start.col)));
let mut out = text.to_owned();
for e in edits {
let (s, t) = (byte_at(&out, e.range.start).unwrap(), byte_at(&out, e.range.end).unwrap());
out.replace_range(s..t, &e.new_text);
}
out
}
const RENAME: &[(&str, &str)] = &[("pkg.models", "pkg.domain")];
#[test]
fn absolute_imports() {
let src = "import pkg.models\nimport pkg.models as m\nfrom pkg.models import Task, Priority\nimport pkg.modelsx\n\nx = pkg.models.Task()\ny = m.Task\n";
assert_eq!(
apply(src, "app", "app", RENAME),
"import pkg.domain\nimport pkg.domain as m\nfrom pkg.domain import Task, Priority\nimport pkg.modelsx\n\nx = pkg.domain.Task()\ny = m.Task\n"
);
}
#[test]
fn bound_names_keep_their_alias() {
let src = "from pkg import models\nfrom pkg import models as mo, cli\nimport models\n";
let moves = &[("pkg.models", "pkg.domain"), ("models", "domain")];
assert_eq!(
apply(src, "app", "app", moves),
"from pkg import domain as models\nfrom pkg import domain as mo, cli\nimport domain as models\n"
);
}
#[test]
fn relative_imports() {
let src = "from .models import Task\nfrom . import models\nfrom . import cli\n";
assert_eq!(
apply(src, "pkg", "pkg", RENAME),
"from .domain import Task\nfrom . import domain as models\nfrom . import cli\n"
);
let src = "from ..models import Task\nfrom .. import models, cli\n";
assert_eq!(
apply(src, "pkg.sub", "pkg.sub", RENAME),
"from ..domain import Task\nfrom .. import domain as models, cli\n"
);
}
#[test]
fn module_moved_to_another_package() {
let moves = &[("pkg.models", "core.models")];
assert_eq!(apply("from .models import Task\n", "pkg", "pkg", moves), "from core.models import Task\n");
assert_eq!(apply("from pkg import models\n", "app", "app", moves), "from core import models\n");
assert_eq!(
apply("def f():\n from pkg import cli, models\n", "app", "app", moves),
"def f():\n from pkg import cli\n from core import models\n"
);
let moves = &[("pkg.models", "core.models"), ("pkg.cli", "pkg.main"), ("pkg.util", "util")];
assert_eq!(
apply("from pkg import cli, models, util, other\n", "app", "app", moves),
"from pkg import main as cli, other\nfrom core import models\nimport util\n"
);
assert_eq!(
apply("from . import models\n", "pkg.sub", "pkg.sub", &[("pkg.sub.models", "pkg.models")]),
"from .. import models\n"
);
}
#[test]
fn the_moved_file_keeps_its_relative_imports_resolving() {
// pkg/cli.py → other/cli.py: `.models` (pkg.models) did not move.
let moves = &[("pkg.cli", "other.cli")];
assert_eq!(apply("from .models import Task\n", "pkg", "other", moves), "from pkg.models import Task\n");
// pkg/sub/cli.py → pkg/cli.py
let moves = &[("pkg.sub.cli", "pkg.cli")];
assert_eq!(apply("from ..models import Task\n", "pkg.sub", "pkg", moves), "from .models import Task\n");
}
#[test]
fn package_moves() {
let moves = &[("pkg", "lib.pkg")];
let src =
"import pkg\nimport pkg.models\nfrom pkg.models import Task\nfrom pkg import models\n\npkg.models.Task()\n";
assert_eq!(
apply(src, "", "", moves),
"import lib.pkg as pkg\nimport lib.pkg.models\nfrom lib.pkg.models import Task\nfrom lib.pkg import models\n\nlib.pkg.models.Task()\n"
);
// Inside the moved package, relative imports still resolve.
assert_eq!(
apply("from .models import Task\nfrom . import cli\n", "pkg", "lib.pkg", moves),
"from .models import Task\nfrom . import cli\n"
);
// Absolute self-imports follow it.
assert_eq!(
apply("from pkg.models import Task\n", "pkg", "lib.pkg", moves),
"from lib.pkg.models import Task\n"
);
}
#[test]
fn unrelated_imports_are_untouched() {
let src = "from __future__ import annotations\nimport os\nfrom datetime import date\nfrom pkgx import models\nfrom . import *\n";
assert_eq!(apply(src, "pkg", "pkg", RENAME), src);
}
#[test]
fn helpers() {
assert_eq!(resolve(1, "m", "a.b").as_deref(), Some("a.b.m"));
assert_eq!(resolve(2, "", "a.b").as_deref(), Some("a"));
assert_eq!(resolve(3, "m", "a.b"), None);
assert_eq!(relative_to("a.b.m", "a.b").as_deref(), Some(".m"));
assert_eq!(relative_to("a.c", "a.b").as_deref(), Some("..c"));
assert_eq!(relative_to("x.c", "a.b"), None);
assert_eq!(map_module("pkg.models.sub", RENAME_OWNED.as_slice()).as_deref(), Some("pkg.domain.sub"));
}
static RENAME_OWNED: std::sync::LazyLock<Vec<(String, String)>> =
std::sync::LazyLock::new(|| vec![("pkg.models".into(), "pkg.domain".into())]);
}
@@ -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"
@@ -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`.
@@ -0,0 +1,7 @@
## Added
- Summary of user-facing features.
## Fixed
- Summary of resolved bugs.
+6
View File
@@ -118,6 +118,8 @@ struct FileConfig {
#[serde(alias = "stopCommand")]
stop_command: Option<String>,
target: Option<String>,
#[serde(alias = "testRunner")]
test_runner: Option<String>,
}
pub(crate) fn slug(s: &str) -> String {
@@ -183,6 +185,7 @@ fn convert(configs: Vec<FileConfig>, local: bool) -> Vec<RunConfig> {
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
}
+79 -5
View File
@@ -243,8 +243,50 @@ 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<PathBuf>, out: &mut Vec<RunConfig>) {
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`, 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");
}
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<PathBuf>,
out: &mut Vec<RunConfig>,
) -> 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 +296,39 @@ fn push_scripts(pkg: &Json, pm: &str, prefix: Option<&str>, cwd: Option<PathBuf>
};
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<PathBuf>,
out: &mut Vec<RunConfig>,
) {
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<RunConfig>) {
@@ -275,7 +345,10 @@ fn detect_node(root: &Path, out: &mut Vec<RunConfig>) {
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 +361,8 @@ fn detect_node(root: &Path, out: &mut Vec<RunConfig>) {
.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);
}
}
}
+7
View File
@@ -182,6 +182,12 @@ pub struct RunExtras {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub target: Option<String>,
/// 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<String>,
}
impl Default for RunExtras {
@@ -205,6 +211,7 @@ impl Default for RunExtras {
emulate_terminal: false,
stop_command: None,
target: None,
test_runner: None,
}
}
}
+41
View File
@@ -51,6 +51,47 @@ 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 package_manager_selection() {
for (lock, pm) in [("yarn.lock", "yarn"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("package-lock.json", "npm")] {
+77 -1
View File
@@ -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": <version or null>}`.
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<String>,
}
/// 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<Vec<Option<Unsatisfied>>> {
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<Option<Unsatisfied>> =
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,
+44
View File
@@ -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]);
}
+7
View File
@@ -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<String>)> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
@@ -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<String>,
pub update: Option<DependencyUpdate>,
}
/// 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<String>,
}
#[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<UnsatisfiedRequirement>,
}
@@ -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<ManifestDependency> {
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<ManifestDependency> {
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<ManifestDependency> {
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<ManifestDependency> {
let Ok(doc) = text.parse::<Document<String>>() 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<u16> = 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());
}
}
+1 -1
View File
@@ -62,7 +62,7 @@ When the language server cannot help, Introduce Variable and Introduce Constant
## Move, copy and rename files
In the Project view, **Rename…** (`⇧F6` / `Shift+F6`), **Move…** (`F6`, drag and drop, or cut and paste) and **Copy…** (`F5`, copy and paste, or `⌥`-drag / `Alt`-drag) open a dialog. With **Search for references** on, references to the file are updated through the language servers that support it (for example imports in TypeScript); **Search in comments and strings** also looks there. The changes are shown in a preview first.
In the Project view, **Rename…** (`⇧F6` / `Shift+F6`), **Move…** (`F6`, drag and drop, or cut and paste) and **Copy…** (`F5`, copy and paste, or `⌥`-drag / `Alt`-drag) open a dialog. With **Search for references** on, references to the file are updated through the language servers that support it (for example imports in TypeScript); Python imports are updated by the IDE itself; **Search in comments and strings** also looks there. The changes are shown in a preview first.
In the editor, **Move…** on a symbol runs the server's move refactoring, where the language has one. In Java it asks where to: a top-level class goes to another package (its package declaration, imports and every reference follow), a static member or nested class to another class, an instance method to the class of one of its fields or parameters; warnings are confirmed in **Problems Detected** first.
+4
View File
@@ -134,6 +134,10 @@ needed. The status bar then shows **WSL: `<distribution>`**.
Opening a folder under `\\wsl.localhost\<distribution>\` also opens it through the distribution.
**Browse** is not available for WSL.
The **Ports** tool window is available in a WSL window too. Because the distribution shares this machine's
`localhost`, a forwarded port is reachable here on the same port; the window lists, opens and remembers ports as it
does for SSH.
## Other uses of SSH configurations
- **Run targets** (**Settings › Build, Execution, Deployment › Run Targets**) run a configuration on an SSH host. See
+1
View File
@@ -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 |
+2 -2
View File
@@ -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`, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks.
## Navigate between code and tests
+3 -2
View File
@@ -74,7 +74,8 @@ On both pages, **Formatting provider** chooses between **Automatic (language ser
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` or `node --test`, 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 <name>`).
In `package.json`, the gutter shows run icons on each `scripts` entry to run or debug it.
@@ -85,7 +86,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 and `node --test` 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`). **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
+2
View File
@@ -21,6 +21,8 @@ basedpyright starts in its `standard` type-checking mode instead of its own stri
Ruff starts only for files below a Ruff configuration: a `ruff.toml`, a `.ruff.toml`, or a `pyproject.toml` that contains a `[tool.ruff]` table. basedpyright has no formatter, so formatting comes from Ruff.
Moving or renaming a module or package in the Project view with **Search for references** on updates the `import` and `from … import` statements that refer to it, relative imports included, in the same preview as the move. basedpyright has no file-move support, so the IDE finds these imports itself from the syntax tree. When a rename changes the name an import binds, the import keeps it as an alias: `from pkg import models` becomes `from pkg import domain as models`.
To pick the type checker yourself, open **Settings › Languages & Frameworks › Language Servers**, select any of the four servers and change **Language server for Python**. **Automatic** uses the first installed one in the order above; you can also choose one server or **None**.
## Setup
+1
View File
@@ -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/<name>/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) |
+1
View File
@@ -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/<name>/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).
+1 -1
View File
@@ -57,7 +57,7 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
## 移动、复制和重命名文件
在项目视图中,**重命名…**(`⇧F6` / `Shift+F6`)、**移动…**(`F6`、拖放或剪切后粘贴)和 **复制…**(`F5`、复制后粘贴,或按住 `⌥` / `Alt` 拖动)会打开对话框。勾选 **搜索引用** 后,支持此功能的语言服务器会更新对该文件的引用(例如 TypeScript 的 import);**在注释和字符串中搜索** 会把注释和字符串也算进去。改动会先显示预览。
在项目视图中,**重命名…**(`⇧F6` / `Shift+F6`)、**移动…**(`F6`、拖放或剪切后粘贴)和 **复制…**(`F5`、复制后粘贴,或按住 `⌥` / `Alt` 拖动)会打开对话框。勾选 **搜索引用** 后,支持此功能的语言服务器会更新对该文件的引用(例如 TypeScript 的 import),Python 的 import 由 IDE 自己更新;**在注释和字符串中搜索** 会把注释和字符串也算进去。改动会先显示预览。
在编辑器中对符号执行 **移动…**,会调用该语言服务器的移动重构(如果有的话)。在 Java 中会先询问目标:顶层类移动到其他包(包声明、import 和所有引用随之更新),静态成员或嵌套类移动到其他类,实例方法移动到其某个字段或形参的类;有警告时先在 **检测到问题** 中确认。
+2
View File
@@ -106,6 +106,8 @@ Shell。IDE 内置的 SSH 客户端会使用配置里保存的密码、密钥或
打开 `\\wsl.localhost\<distribution>\` 下的文件夹时,也会自动通过该发行版打开。WSL 方式不支持**浏览**。
WSL 窗口中也可以使用**端口**工具窗口。由于发行版与本机的 `localhost` 相通,转发的端口在本机可用同一端口访问;端口的列表、在浏览器中打开和记忆方式与 SSH 相同。
## SSH 配置的其他用途
- **运行目标**(**设置 › 构建、执行、部署 › 运行目标**)可以在 SSH 主机上执行运行配置,见[运行配置](/zh/guide/run)。
+1
View File
@@ -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 程序和测试 |
+2 -2
View File
@@ -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`、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。
## 在代码和测试之间跳转
+3 -2
View File
@@ -74,7 +74,8 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript
打开项目时,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` 的脚本,是测试配置。
- 有 `playwright.config.*` 但没有脚本运行它的包:通过 `npx` 运行的 `playwright test`。
- `deno.json` / `deno.jsonc` 中每个 task 一个配置(`deno task <name>`)。
在 `package.json` 中,每个 `scripts` 条目旁的边栏图标可以直接运行或调试该脚本。
@@ -85,7 +86,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` 的输出会解析成测试树,支持 **重新运行失败的测试**。Playwright 运行时使用它的 `list` 报告器(配置里指定了其他报告器时除外);从行号栏运行单个测试时按行号选择(`file:line`),有多个 project 的运行会在文件下按 project 分组。`node --test` 运行时,IDE 通过 `NODE_OPTIONS` 在 `spec` 旁加上自己的报告器(脚本自己指定了 `--test-reporter` 时不显示测试树);单个测试和重新运行按完整名称选择(`--test-name-pattern`)。**使用覆盖率运行** 支持调用 `vitest` 或 `jest` 的脚本(Vitest 需要 `@vitest/coverage-v8` 之类的覆盖率 provider,缺失时 IDE 会提示添加),以及通过 `c8` 运行的 `node` / `tsx` / `ts-node`。详见[测试](/zh/guide/testing)和[覆盖率](/zh/guide/coverage)。
## 调试
+2
View File
@@ -21,6 +21,8 @@ basedpyright 以 `standard` 类型检查模式启动,而不是它自带的更
Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`,或包含 `[tool.ruff]` 表的 `pyproject.toml`。basedpyright 本身不提供格式化,格式化由 Ruff 负责。
移动或重命名模块、包时(项目视图中,勾选 **搜索引用**),引用它的 `import` 和 `from … import` 语句(包括相对导入)会一起更新,和移动操作显示在同一个预览里。basedpyright 不支持文件移动,所以这些导入由 IDE 根据语法树自己查找。如果重命名改变了导入绑定的名字,导入会用别名保留原名:`from pkg import models` 变成 `from pkg import domain as models`。
想手动指定类型检查器,打开 **设置 › 语言和框架 › 语言服务器**,选中这四个服务器中的任意一个,修改 **Python 语言服务器**。**自动** 会按上表顺序使用第一个已安装的服务器;也可以固定选一个,或选 **无**。
## 环境配置
+1
View File
@@ -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/<name>/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) |
+1
View File
@@ -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/<name>/SKILL.md"`),在插件包中打包代理技能 |
每个版本新增内容的完整列表见 [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md)。
+135
View File
@@ -111,6 +111,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 +206,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<string, AgentSkillMode> };
return currentTask;
@@ -227,6 +327,8 @@ test("manages multi-level skills in Settings and per-session overrides via Compo
await expect(sessionPopup).toBeVisible();
await expect(sessionPopup).toContainText("verify");
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.
@@ -255,7 +357,40 @@ test("manages multi-level skills in Settings and per-session overrides via Compo
await expect(settingsDialog.getByText("Claude Code (.claude/skills)")).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` });
}
});
+56
View File
@@ -62,3 +62,59 @@ test("keeps values and their full-value action readable in a narrow debugger", a
.poll(() => routing.getByText(routingValue, { exact: true }).evaluate((el) => el.scrollWidth <= el.clientWidth + 1))
.toBe(true);
});
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 ({ name, type, value, countName }) => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.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 */ 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(92, {
name: "Settlement",
adapter: "debugpy",
status: "paused",
selectedFrame: 11,
frames: [{ id: 11, name: "settle", path: null, line: 0, column: 0, presentationHint: null }],
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 280);
toolWindowService().show("debug", true);
},
{ name, type, value, countName },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
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();
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, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
moveToolWindow("debug", "bottom");
setToolWindowSize("bottom", 310);
});
await expect.poll(() => annotation.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
});
+29
View File
@@ -0,0 +1,29 @@
import { expect, test } from "./fixtures";
test("template literals highlight and comment in their embedded language", async ({ workbench: page }) => {
await page.evaluate(async () => {
const backendPath = "/src/editor/core/backend.ts";
const contributionsPath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(contributionsPath);
docBackend().files.set(
"/dev/acme-api/styles.ts",
"const Button = styled.button`\n padding: 4px;\n`;\nconst QUERY = gql`\n query Cart { total }\n`;\nconst plain = `margin: 0`;\n",
);
await editorService().openFile("/dev/acme-api/styles.ts");
});
const content = page.locator('.cm-editor[data-language="TypeScript"] .cm-content');
await expect(content).toBeVisible();
// Each word of an embedded language is a token of its own; a plain literal stays one string.
await expect(content.locator("span").filter({ hasText: /^padding$/ })).toBeVisible();
await expect(content.locator("span").filter({ hasText: /^query$/ })).toBeVisible();
await expect(content.locator("span").filter({ hasText: /^`margin: 0`$/ })).toBeVisible();
await content.evaluate((element) => {
const view = (element as HTMLElement & { cmTile: { view: import("@codemirror/view").EditorView } }).cmTile.view;
view.dispatch({ selection: { anchor: view.state.doc.toString().indexOf("query") } });
view.focus();
});
await page.keyboard.press("Meta+/");
await expect(content).toContainText("# query Cart { total }");
});
+3 -1
View File
@@ -9,6 +9,8 @@ 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` |
| `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` |
@@ -39,7 +41,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` / `polyglot/web` run `pnpm install` first; 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`).
+1
View File
@@ -0,0 +1 @@
node_modules
+10
View File
@@ -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"
}
}
+23
View File
@@ -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;
@@ -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);
});
+3
View File
@@ -0,0 +1,3 @@
node_modules
test-results
playwright-report
+15
View File
@@ -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"
}
}
@@ -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",
});
+27
View File
@@ -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);
}
@@ -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");
});
});
+13
View File
@@ -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"]
}
+70
View File
@@ -0,0 +1,70 @@
// Embedded languages in template literals: CSS, GraphQL, SQL and HTML are highlighted inside them.
// The tags are local stand-ins for styled-components, graphql-tag, a SQL client and Lit.
type Tag = (strings: TemplateStringsArray, ...values: unknown[]) => string;
const tag: Tag = (strings, ...values) => String.raw({ raw: strings }, ...values);
const css = tag;
const keyframes = tag;
const gql = tag;
const sql = tag;
const html = tag;
const styled = Object.assign((_component: unknown) => tag, { button: tag, div: tag });
export const fadeIn = keyframes`
from { opacity: 0; }
to { opacity: 1; }
`;
export const Button = styled.button`
padding: 4px 12px;
color: ${() => "white"};
background: #3574f0;
animation: ${fadeIn} 120ms ease-out;
&:hover {
background: #4682fa;
}
`;
export const Card = styled(Button)`
border-radius: 8px;
`;
export const centered = css`
display: flex;
align-items: center;
`;
export const CART_QUERY = gql`
query Cart($id: ID!, $first: Int = 10) {
cart(id: $id) {
total
items(first: $first) {
...CartItem
}
}
}
fragment CartItem on Item {
name
price
}
`;
export function cartRows(cartId: string): string {
return sql`
SELECT name, price
FROM cart_items
WHERE cart_id = ${cartId}
ORDER BY price DESC
`;
}
export function cartView(total: string): string {
return html`<section class="cart"><h2>Total</h2><p>${total}</p></section>`;
}
export const ITEM_FIELDS = /* GraphQL */ `
fragment ItemFields on Item { name price }
`;
+8
View File
@@ -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/<name>/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/<name>/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
+55 -19
View File
@@ -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,46 @@ const env = (config: RunConfig, vars: Record<string, string>): RunConfig => ({
});
const args = (config: RunConfig, extra: string[]): RunConfig => ({ ...config, args: [...config.args, ...extra] });
const CASES: Record<string, Case> = {
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<string, Case | Case[]> = {
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",
},
},
],
python: {
fixture: "python-app",
// A project venv with pytest, as the fixture's README sets it up.
@@ -154,15 +181,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<string> {
base = realpathSync(mkdtempSync(join(tmpdir(), "openidea-smoke-")));
@@ -208,8 +240,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 +289,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);
}
});
}
+57 -12
View File
@@ -88,10 +88,13 @@ pub struct Connection {
/// A forwarded port's host (`None`: the remote host itself) and remote port.
type ForwardKey = (Option<String>, u16);
/// A forwarded port: through the SSH connection, or `docker exec` in a dev container.
/// A forwarded port: through the SSH connection, `docker exec` in a dev container, or — for
/// WSL — nothing, the distribution's `localhost` already being this machine's.
enum Forward {
Ssh(ide_ssh::Tunnel),
Container(ide_remote::container_tunnel::Tunnel),
/// The remote port, reachable here on the same port without a tunnel.
Wsl(u16),
}
impl Forward {
@@ -99,6 +102,7 @@ impl Forward {
match self {
Self::Ssh(t) => t.port(),
Self::Container(t) => t.port(),
Self::Wsl(port) => *port,
}
}
}
@@ -954,20 +958,48 @@ pub async fn remote_forward_port(
Ok(port)
}
/// How a remote port reaches this machine: through the SSH connection, an exec-based
/// container tunnel, or — for WSL — nothing, the distribution's `localhost` being this
/// machine's. `None`: not reachable (another host only from a dev container).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ForwardRoute {
Ssh,
Container,
Wsl,
}
fn forward_route(target: &RemoteTarget, host: Option<&str>) -> Option<ForwardRoute> {
match (target, host) {
(RemoteTarget::Ssh { .. }, None) => Some(ForwardRoute::Ssh),
(RemoteTarget::Ssh { .. }, Some(_)) => None,
(RemoteTarget::DevContainer { .. }, _) => Some(ForwardRoute::Container),
(RemoteTarget::Wsl { .. }, None) => Some(ForwardRoute::Wsl),
(RemoteTarget::Wsl { .. }, Some(_)) => None,
}
}
/// Forwards `remote_port` of `host` (`None`: the remote host itself) to the same local port
/// when it is free, else to a free one. Another host is reached from a dev container only.
/// when it is free, else to a free one. A WSL distribution shares this machine's loopback, so
/// its port is already reachable on the same port here. Another host is reached from a dev
/// container only.
async fn open_forward(c: &Connection, host: Option<&str>, remote_port: u16) -> IdeResult<Forward> {
if let (Some(session), None) = (c.session.clone(), host) {
let tunnel = ide_ssh::Tunnel::listen_on(session, Some(remote_port), "localhost", remote_port).await?;
return Ok(Forward::Ssh(tunnel));
let unsupported = || IdeError::unavailable("Forwarding ports is not supported here yet");
match forward_route(&c.target, host) {
Some(ForwardRoute::Ssh) => {
let session = c.session.clone().ok_or_else(unsupported)?;
let tunnel = ide_ssh::Tunnel::listen_on(session, Some(remote_port), "localhost", remote_port).await?;
Ok(Forward::Ssh(tunnel))
}
Some(ForwardRoute::Container) => {
let exec = c.exec.clone().ok_or_else(unsupported)?;
let host = host.unwrap_or("localhost");
Ok(Forward::Container(
ide_remote::container_tunnel::Tunnel::listen(exec, remote_port, host, remote_port).await?,
))
}
Some(ForwardRoute::Wsl) => Ok(Forward::Wsl(remote_port)),
None => Err(unsupported()),
}
if let Some(exec) = c.exec.clone() {
let host = host.unwrap_or("localhost");
return Ok(Forward::Container(
ide_remote::container_tunnel::Tunnel::listen(exec, remote_port, host, remote_port).await?,
));
}
Err(IdeError::unavailable("Forwarding ports is not supported in a WSL project yet"))
}
/// `web_url` answers with the remote host's built-in web server, on its loopback: the URL's
@@ -1284,6 +1316,19 @@ mod tests {
assert!(parse_remote_location(r"\\wsl.localhost\Ubuntu\home\me\app").is_none());
}
#[test]
fn a_port_is_routed_by_the_target_and_its_host() {
let ssh = RemoteTarget::Ssh { config: "box".into() };
let wsl = RemoteTarget::Wsl { distro: "Ubuntu".into() };
let container = RemoteTarget::DevContainer { folder: "/work/app".into(), config: String::new() };
assert_eq!(forward_route(&ssh, None), Some(ForwardRoute::Ssh));
assert_eq!(forward_route(&ssh, Some("selenium")), None);
assert_eq!(forward_route(&container, None), Some(ForwardRoute::Container));
assert_eq!(forward_route(&container, Some("selenium")), Some(ForwardRoute::Container));
assert_eq!(forward_route(&wsl, None), Some(ForwardRoute::Wsl));
assert_eq!(forward_route(&wsl, Some("selenium")), None);
}
#[test]
fn a_command_missing_on_a_server_of_another_version_says_which_versions() {
let missing = || IdeError::unavailable("-32601: command web_url is not available remotely");
+4
View File
@@ -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
@@ -510,6 +513,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
+105 -2
View File
@@ -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<null, IdeError>(__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<RemoteSkillBrowseResult, IdeError>(__TAURI_INVOKE("agent_skills_browse", { source, request })),
/** Installs the selected skill subtree into `~/.agents/skills` (User) or `<workspace>/.agents/skills` (Workspace). */
agentSkillsInstall: (input: InstallRemoteSkillRequest, request: RequestId) => typedError<AgentSkillState_Serialize[], IdeError>(__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<AgentSkillState_Serialize[], IdeError>(__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<RemoteSkillPreview, IdeError>(__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.
@@ -1348,6 +1354,15 @@ export const commands = {
* edited (not yet applied); the response status, or why there was none.
*/
proxyCheckConnection: (proxy: ProxySettings, url: string) => typedError<string, IdeError>(__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<IpcPath[], IdeError>(__TAURI_INVOKE("recent_files")),
/** The welcome screen's project groups. */
@@ -2820,6 +2835,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`. */
@@ -7780,6 +7797,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`. */
@@ -10639,6 +10668,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`);
@@ -10922,6 +10957,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 (`<name>` under `.agents/skills/<name>`). */
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. */
@@ -11146,6 +11222,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 = {
@@ -11190,6 +11272,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. */
@@ -11790,6 +11878,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" } |
@@ -12701,6 +12797,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,
+4 -2
View File
@@ -2,6 +2,7 @@ import { LanguageSupport, LRLanguage } from "@codemirror/language";
import { javascript } from "@codemirror/lang-javascript";
import { parseMixed, type Input, type NestedParse, type SyntaxNode, type SyntaxNodeRef } from "@lezer/common";
import { angular, angularLanguage } from "./index";
import { templateInjection, type TemplateLanguageResolver } from "../templateLanguages";
function nextCode(node: SyntaxNode): SyntaxNode | null {
let next = node.nextSibling;
@@ -37,10 +38,11 @@ function mixTemplate(node: SyntaxNodeRef, input: Input): NestedParse | null {
const typescript = javascript({ typescript: true });
export function angularTypescript(): LanguageSupport {
export function angularTypescript(resolve: TemplateLanguageResolver): LanguageSupport {
const literals = templateInjection(resolve);
// Mount on the decorator so changing its name or metadata invalidates the template too.
const language = (typescript.language as LRLanguage).configure(
{ wrap: parseMixed(mixTemplate) },
{ wrap: parseMixed((node, input) => mixTemplate(node, input) ?? literals(node, input)) },
"angular-typescript",
);
return new LanguageSupport(language, [typescript.support, angular().support]);
+195
View File
@@ -0,0 +1,195 @@
/**
* GraphQL for template literals (`gql`, `graphql`), coloured as `.graphql` files' tree-sitter
* highlighting colours them: operation and fragment names as functions, fields as properties,
* argument names and `$variables` as variables, named types as types, enum values as
* constants and directives as annotations.
*/
import type { StreamParser, StringStream } from "@codemirror/language";
/** What a bracket opened: a selection set, a type's fields, an enum's values, arguments, … */
type Scope = "selection" | "fields" | "values" | "arguments" | "variables" | "inputs" | "object" | "list";
interface Frame {
scope: Scope;
/** After `:` (or `=`) in this scope: a type or a value comes next. */
colon: boolean;
/** After `=`: a default value, not a type. */
value?: boolean;
/** For `list`: its items are types, not values. */
types?: boolean;
}
export interface GraphQLState {
stack: Frame[];
/** The top-level definition being read: `type`, `enum`, `union`, `directive`, `schema` or an operation. */
definition: string | null;
/** What the next name is, whatever the scope. */
next: "definition" | "type" | "spread" | "location" | null;
inBlockString: boolean;
}
const OPERATIONS = new Set(["query", "mutation", "subscription", "fragment"]);
const TYPE_DEFINITIONS = new Set(["type", "interface", "input", "scalar", "union", "enum"]);
const KEYWORDS = new Set([...OPERATIONS, ...TYPE_DEFINITIONS, "schema", "extend", "implements", "directive", "on"]);
const VALUE_KEYWORDS = new Set(["true", "false", "null"]);
const NAME = /^[_A-Za-z][_0-9A-Za-z]*/;
function blockString(stream: StringStream, state: GraphQLState): string {
while (!stream.eol()) {
if (stream.match('\\"""') || stream.next() !== '"') continue;
if (stream.match('""')) {
state.inBlockString = false;
break;
}
}
return "string";
}
function open(state: GraphQLState, bracket: string) {
const top = state.stack[state.stack.length - 1];
const definition = state.definition;
let frame: Frame;
if (bracket === "[") frame = { scope: "list", colon: false, types: isTypePosition(state) };
else if (bracket === "{") {
const scope: Scope = !top
? definition === "enum"
? "values"
: definition && definition !== "operation"
? "fields"
: "selection"
: top.colon || top.scope === "list" || top.scope === "object" || top.scope === "arguments"
? "object"
: "selection";
frame = { scope, colon: false };
} else {
const typeSystem = !!definition && definition !== "operation";
const scope: Scope = typeSystem ? "inputs" : top ? "arguments" : "variables";
frame = { scope, colon: false };
}
state.stack.push(frame);
state.next = null;
}
/** Whether a name here is a type (`$id: ID`, `name: String`, `[Episode!]`). */
function isTypePosition(state: GraphQLState): boolean {
const top = state.stack[state.stack.length - 1];
if (!top) return false;
if (top.scope === "list") return !!top.types;
return top.colon && !top.value && (top.scope === "fields" || top.scope === "variables" || top.scope === "inputs");
}
/** A name, string or number was read: what follows is no longer after `:`. */
function consumed(top: Frame | undefined) {
if (top && top.scope !== "list") top.colon = top.value = false;
}
function name(word: string, state: GraphQLState): string | null {
const top = state.stack[state.stack.length - 1];
const next = state.next;
if (next === "definition") {
state.next = null;
return state.definition === "operation" ? "variableName.function" : "typeName";
}
if (next === "spread") {
if (word === "on") {
state.next = "type";
return "keyword";
}
state.next = null;
return "variableName.function";
}
if (next === "type") {
state.next = null;
return "typeName";
}
if (next === "location") {
if (/^[A-Z_]+$/.test(word)) return "variableName.constant";
state.next = null;
}
if (!top) {
if (!KEYWORDS.has(word)) return null;
if (OPERATIONS.has(word)) {
state.definition = "operation";
state.next = "definition";
} else if (TYPE_DEFINITIONS.has(word)) {
state.definition = word;
state.next = "definition";
} else if (word === "schema" || word === "directive") state.definition = word;
else if (word === "implements") state.next = "type";
else if (word === "on") state.next = state.definition === "directive" ? "location" : "type";
return "keyword";
}
if (isTypePosition(state)) {
consumed(top);
return "typeName";
}
if (top.colon || top.scope === "list") {
consumed(top);
return VALUE_KEYWORDS.has(word) ? "keyword" : "variableName.constant";
}
switch (top.scope) {
case "values":
return "variableName.constant";
case "arguments":
case "inputs":
return "variableName";
default:
return "propertyName";
}
}
export const graphqlParser: StreamParser<GraphQLState> = {
name: "graphql",
startState: () => ({ stack: [], definition: null, next: null, inBlockString: false }),
copyState: (s) => ({ ...s, stack: s.stack.map((f) => ({ ...f })) }),
token(stream, state) {
if (state.inBlockString) return blockString(stream, state);
if (stream.eatSpace() || stream.eat(",")) return null;
if (stream.match("#")) {
stream.skipToEnd();
return "comment";
}
if (stream.match('"""')) {
state.inBlockString = true;
return blockString(stream, state);
}
const top = state.stack[state.stack.length - 1];
if (stream.match(/^"(?:[^"\\]|\\.)*"?/)) {
consumed(top);
return "string";
}
if (stream.match(/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/)) {
consumed(top);
return "number";
}
if (stream.match(/^\$[_A-Za-z][_0-9A-Za-z]*/)) {
if (top?.scope !== "variables") consumed(top);
return "variableName";
}
if (stream.match(/^@[_A-Za-z][_0-9A-Za-z]*/)) return "annotation";
if (stream.match("...")) {
state.next = "spread";
return "punctuation";
}
const word = stream.match(NAME);
if (word) return name((word as RegExpMatchArray)[0], state);
const ch = stream.next()!;
if ("{([".includes(ch)) {
open(state, ch);
return "bracket";
}
if ("})]".includes(ch)) {
state.stack.pop();
consumed(state.stack[state.stack.length - 1]);
if (!state.stack.length && ch === "}") state.definition = null;
return "bracket";
}
// In a selection set, `alias: field` names a field after the colon too.
if (ch === ":" && top && top.scope !== "selection") top.colon = true;
else if (ch === "=" && top) top.colon = top.value = true;
else if (ch === "=" && state.definition === "union") state.next = "type";
else if ((ch === "|" || ch === "&") && !top && state.next !== "location") state.next = "type";
return "punctuation";
},
languageData: { commentTokens: { line: "#" }, closeBrackets: { brackets: ["(", "[", "{", '"'] } },
};
+32 -2
View File
@@ -12,6 +12,7 @@ import {
LanguageSupport,
StreamLanguage,
delimitedIndent,
type Language,
indentNodeProp,
indentService,
language as languageFacet,
@@ -169,9 +170,28 @@ const OWN_MODES = [
},
}),
),
// CSS, GraphQL, SQL and HTML in tagged template literals (`styled.div`, `gql`, `sql`, `html`).
...(
[
["JavaScript", {}],
["TypeScript", { typescript: true }],
["JSX", { jsx: true }],
["TSX", { jsx: true, typescript: true }],
] as const
).map(([name, config]) =>
LanguageDescription.of({
name,
load: () => import("./templateLanguages").then((m) => m.javascriptWithTemplates(config, templateLanguage)),
}),
),
// Only for template literals: `.graphql` files keep the backend's tree-sitter highlighting.
LanguageDescription.of({
name: "GraphQL",
load: async () => new LanguageSupport(StreamLanguage.define((await import("./graphql")).graphqlParser)),
}),
LanguageDescription.of({
name: "Angular TypeScript",
load: () => import("./angular/inline").then((m) => m.angularTypescript()),
load: () => import("./angular/inline").then((m) => m.angularTypescript(templateLanguage)),
}),
LanguageDescription.of({ name: "Angular Template", load: () => import("./angular").then((m) => m.angular()) }),
LanguageDescription.of({ name: "Thymeleaf", load: () => import("./thymeleaf").then((m) => m.thymeleafSupport()) }),
@@ -368,7 +388,17 @@ export function fencedCodeMode(info: string): FencedCodeMode | null {
const uiMode = infos?.has(name) ? infos.get(name)!.uiMode : uiModeForPath(`.${name}`);
desc = uiMode ? findLanguageDescription(uiMode, "") : null;
}
if (!desc) return null;
return desc ? patchedMode(desc) : null;
}
/** The mode named `name` (`CSS`, `GraphQL`) for a template literal, with the tag patches of a file in it. */
function templateLanguage(name: string): Language | LanguageDescription | null {
const desc = findLanguageDescription(name, "");
return desc ? patchedMode(desc).language : null;
}
/** `desc` with the same tag patches as a file of that language, loaded on first use. */
function patchedMode(desc: LanguageDescription): FencedCodeMode {
const ready = patched.get(desc);
if (ready) return { name: desc.name, language: ready.language };
// Markdown parses the block once the proxy has loaded the patched support.
@@ -0,0 +1,196 @@
import { beforeAll, describe, expect, it } from "vitest";
import { ensureSyntaxTree, type LanguageSupport } from "@codemirror/language";
import { EditorState } from "@codemirror/state";
import { highlightTree, tags as t, type Tag } from "@lezer/highlight";
import { toggleComment } from "@codemirror/commands";
import { findLanguageDescription, loadSupport } from "./languages";
import { openideaHighlightStyle } from "./highlight";
const supports: Record<string, LanguageSupport> = {};
beforeAll(async () => {
// Embedded modes load lazily; load them up front so one parse covers the literals.
for (const name of ["CSS", "GraphQL", "SQL", "HTML", "JavaScript", "TypeScript", "TSX", "Angular TypeScript"])
supports[name] = (await loadSupport(findLanguageDescription(name, "")!))!;
});
function tokens(mode: string, doc: string): { text: string; cls: string }[] {
const out: { text: string; cls: string }[] = [];
highlightTree(supports[mode]!.language.parser.parse(doc), openideaHighlightStyle, (from, to, cls) => {
out.push({ text: doc.slice(from, to), cls });
});
return out;
}
function expectTokens(mode: string, doc: string, expected: readonly (readonly [string, Tag])[]) {
const got = tokens(mode, doc);
for (const [text, tag] of expected) {
const cls = openideaHighlightStyle.style([tag]);
expect(cls, String(tag)).toBeTruthy();
expect(got, text).toContainEqual({ text, cls });
}
}
/** No string-coloured token contains `text`: the literal's body is not one string. */
function expectNotString(mode: string, doc: string, text: string) {
const string = openideaHighlightStyle.style([t.string]);
expect(tokens(mode, doc).filter((tok) => tok.cls === string && tok.text.includes(text))).toEqual([]);
}
describe("template literal languages", () => {
it("highlights CSS in styled-components and emotion templates", () => {
const doc = [
"const Button = styled.button`",
" color: ${(p) => p.color};",
" padding: 4px 8px;",
" &:hover { background: #fff; }",
"`;",
"const Link = styled(Anchor).attrs({ role: 'link' })`margin: 0;`;",
"const Global = createGlobalStyle`body { margin: 0 }`;",
"const spin = keyframes`from { opacity: 0 } to { opacity: 1 }`;",
"const mixin = css`display: flex;`;",
].join("\n");
expectTokens("JavaScript", doc, [
["color", t.attributeName],
["padding", t.attributeName],
["4", t.number],
["px", t.attributeValue],
["background", t.attributeName],
["#fff", t.tagName],
["margin", t.attributeName],
["body", t.tagName],
["opacity", t.attributeName],
["display", t.attributeName],
["flex", t.attributeValue],
// The substitution stays JavaScript.
["=>", t.punctuation],
]);
expectNotString("JavaScript", doc, "padding");
});
it("follows TypeScript type arguments on the tag", () => {
expectTokens("TypeScript", "const Box = styled.div<{ gap: number }>`gap: ${(p) => p.gap}px;`;", [
["gap", t.attributeName],
["number", t.typeName],
]);
});
it("highlights GraphQL in gql and graphql templates and calls", () => {
const doc = [
"const HERO = gql`",
" query Hero($id: ID!, $first: Int = 10) @cached {",
" hero(id: $id, episode: JEDI) { name friends(first: $first) { ...Friend } }",
" }",
" fragment Friend on Character { name }",
"`;",
"const Me = graphql(`query Me { me { id } }`, [Friend]);",
].join("\n");
expectTokens("TypeScript", doc, [
["query", t.keyword],
["Hero", t.function(t.variableName)],
["$id", t.variableName],
["ID", t.typeName],
["Int", t.typeName],
["10", t.number],
["@cached", t.annotation],
["hero", t.propertyName],
["episode", t.variableName],
["JEDI", t.constant(t.variableName)],
["Friend", t.function(t.variableName)],
["fragment", t.keyword],
["Character", t.typeName],
["Me", t.function(t.variableName)],
["me", t.propertyName],
]);
});
it("highlights GraphQL schema definitions", () => {
const doc = [
"const typeDefs = gql`",
" type Query implements Node { hero(episode: Episode = JEDI): [Character!]! }",
" enum Episode { NEWHOPE JEDI }",
" union Result = Human | Droid",
"`;",
].join("\n");
expectTokens("JavaScript", doc, [
["type", t.keyword],
["Query", t.typeName],
["Node", t.typeName],
["hero", t.propertyName],
["episode", t.variableName],
["Episode", t.typeName],
["Character", t.typeName],
["NEWHOPE", t.constant(t.variableName)],
["Human", t.typeName],
["Droid", t.typeName],
]);
});
it("highlights SQL and HTML templates", () => {
const doc = [
"const rows = await sql`SELECT id, name FROM users WHERE id = ${id}`;",
'const view = html`<button class="primary" @click=${go}>Go</button>`;',
].join("\n");
expectTokens("JavaScript", doc, [
["SELECT", t.keyword],
["FROM", t.keyword],
["WHERE", t.keyword],
["button", t.tagName],
["class", t.attributeName],
['"primary"', t.attributeValue],
]);
expectNotString("JavaScript", doc, "SELECT");
});
it("highlights a literal a /* language */ comment names", () => {
expectTokens("TSX", "const q = /* GraphQL */ `query Q { a }`;\nconst s = /* sql */ `SELECT 1`;", [
["query", t.keyword],
["Q", t.function(t.variableName)],
["SELECT", t.keyword],
]);
});
it("leaves other template literals strings", () => {
const doc = "const a = `color: red;`;\nconst b = tag`query Q { a }`;\nconst c = /* note */ `SELECT 1`;";
const string = openideaHighlightStyle.style([t.string]);
for (const text of ["`color: red;`", "`query Q { a }`", "`SELECT 1`"])
expect(tokens("JavaScript", doc)).toContainEqual({ text, cls: string });
});
it("injects into Angular TypeScript files too", () => {
expectTokens(
"Angular TypeScript",
"@Component({ template: '<p>{{ name }}</p>' })\nclass A {}\nconst q = gql`query Q { a }`;",
[
["p", t.tagName],
["query", t.keyword],
],
);
});
it.each([
["css", "tag", "const a = css`color: red;`;", "`color: red;`"],
["GraphQL", "note", "const a = /* GraphQL */ `query Q { a }`;", "`query Q { a }`"],
])("re-parses the literal when its %s tag changes", (from, to, doc, literal) => {
let state = EditorState.create({ doc, extensions: [supports.JavaScript!] });
ensureSyntaxTree(state, state.doc.length, 5000);
const at = doc.indexOf(from);
state = state.update({ changes: { from: at, to: at + from.length, insert: to } }).state;
const tree = ensureSyntaxTree(state, state.doc.length, 5000)!;
const parsed: string[] = [];
highlightTree(tree, openideaHighlightStyle, (from, to) => parsed.push(state.sliceDoc(from, to)));
expect(parsed).toContain(literal);
});
it("comments lines with the embedded language's comment syntax", () => {
const doc = "const q = gql`\n query Q { a }\n`;";
let state = EditorState.create({
doc,
selection: { anchor: doc.indexOf("query") },
extensions: [supports.JavaScript!],
});
ensureSyntaxTree(state, state.doc.length, 5000);
toggleComment({ state, dispatch: (tr) => (state = tr.state) });
expect(state.doc.line(2).text).toBe(" # query Q { a }");
});
});
+146
View File
@@ -0,0 +1,146 @@
/**
* Embedded languages in JavaScript and TypeScript template literals, as WebStorm injects them:
* CSS in styled-components / emotion / Lit (`styled.div`, `styled(Button).attrs(…)`, `css`,
* `createGlobalStyle`, `keyframes`, `injectGlobal`), GraphQL (`gql`, `graphql`, also called as
* `graphql(`…`)`), SQL (`sql`) and HTML (`html`). A `/* GraphQL *\/`-style comment right before
* a plain template literal names its language too.
*
* The literal's text between `${…}` substitutions is parsed as one document of the embedded
* language; the substitutions stay JavaScript.
*/
import { LanguageDescription, LanguageSupport, LRLanguage, ParseContext, type Language } from "@codemirror/language";
import { javascript } from "@codemirror/lang-javascript";
import type { LRParser } from "@lezer/lr";
import {
parseMixed,
type Input,
type NestedParse,
type Parser,
type SyntaxNode,
type SyntaxNodeRef,
} from "@lezer/common";
/** A mode by `LanguageDescription` name, with the tag patches of a file in that language. */
export type TemplateLanguageResolver = (name: string) => Language | LanguageDescription | null;
const CSS_TAGS = new Set(["css", "createGlobalStyle", "keyframes", "injectGlobal"]);
/** The embedded language a tag names, by mode name. */
function tagLanguage(tag: SyntaxNode, input: Input): string | null {
if (rootName(tag, input) === "styled") return "CSS";
const name = lastName(tag, input);
if (!name) return null;
if (CSS_TAGS.has(name)) return "CSS";
if (name === "gql" || name === "graphql") return "GraphQL";
if (name === "sql" || name === "SQL") return "SQL";
if (name === "html") return "HTML";
return null;
}
const COMMENT_LANGUAGES: Record<string, string> = {
css: "CSS",
graphql: "GraphQL",
gql: "GraphQL",
sql: "SQL",
html: "HTML",
};
/** The language a `/* name *\/` comment names. */
function commentLanguage(comment: SyntaxNode, input: Input): string | null {
const name = /^\/\*\s*([A-Za-z]+)\s*\*\/$/.exec(input.read(comment.from, comment.to))?.[1];
return (name && COMMENT_LANGUAGES[name.toLowerCase()]) ?? null;
}
/** The identifier a tag expression starts from: `styled` in `styled(Button).attrs({})`. */
function rootName(node: SyntaxNode, input: Input): string | null {
for (let n: SyntaxNode | null = node; n; n = n.firstChild) {
if (n.name === "VariableName") return input.read(n.from, n.to);
if (!["MemberExpression", "CallExpression", "InstantiationExpression"].includes(n.name)) return null;
}
return null;
}
/** The name a tag expression ends with: `sql` in `sql` and `Prisma.sql`, `css` in `css<Props>`. */
function lastName(node: SyntaxNode, input: Input): string | null {
let n: SyntaxNode | null = node;
if (n.name === "InstantiationExpression") n = n.firstChild;
if (n?.name === "MemberExpression") n = n.lastChild;
return n && (n.name === "VariableName" || n.name === "PropertyName") ? input.read(n.from, n.to) : null;
}
/** The literal's text between the backticks, without its `${…}` substitutions. */
function contentRanges(template: SyntaxNode, input: Input): { from: number; to: number }[] {
const ranges: { from: number; to: number }[] = [];
let from = template.from + 1;
for (const sub of template.getChildren("Interpolation")) {
if (sub.from > from) ranges.push({ from, to: sub.from });
from = sub.to;
}
const closed = template.to - template.from > 1 && input.read(template.to - 1, template.to) === "`";
const to = closed ? template.to - 1 : template.to;
if (to > from) ranges.push({ from, to });
return ranges;
}
/** Styled-components and emotion bodies are declarations and nested rules, as in a `style` attribute. */
const declarationParsers = new WeakMap<Parser, Parser>();
function parserFor(name: string, resolve: TemplateLanguageResolver): Parser | null {
const mode = resolve(name);
if (!mode) return null;
let language: Language;
if (mode instanceof LanguageDescription) {
if (!mode.support) return ParseContext.getSkippingParser(mode.load());
language = mode.support.language;
} else language = mode;
if (name !== "CSS" || !(language instanceof LRLanguage)) return language.parser;
let parser = declarationParsers.get(language.parser);
if (!parser)
declarationParsers.set(language.parser, (parser = (language.parser as LRParser).configure({ top: "Styles" })));
return parser;
}
/** The nested parse for `node`, mounted on the tagged template or call so editing the tag re-parses it. */
export function templateInjection(resolve: TemplateLanguageResolver) {
return (ref: SyntaxNodeRef, input: Input): NestedParse | null => {
// Called for every node on each parse: rule out the rest before materializing the node.
if (ref.name !== "TaggedTemplateExpression" && ref.name !== "CallExpression" && ref.name !== "TemplateString")
return null;
const node = ref.node;
let template: SyntaxNode | null = null;
let language: string | null = null;
if (node.name === "TaggedTemplateExpression") {
template = node.lastChild;
const tag = node.firstChild;
language = tag && template !== tag ? tagLanguage(tag, input) : null;
} else if (node.name === "CallExpression") {
// `graphql(`…`)` (gql.tada, GraphQL Code Generator's client preset).
const callee = node.firstChild;
const first = node.getChild("ArgList")?.firstChild?.nextSibling;
if (callee && first?.name === "TemplateString" && tagLanguage(callee, input) === "GraphQL") {
template = first;
language = "GraphQL";
}
} else if (node.name === "TemplateString" && node.parent?.name !== "TaggedTemplateExpression") {
const before = node.prevSibling;
if (before?.name === "BlockComment") {
template = node;
language = commentLanguage(before, input);
}
}
if (!template || template.name !== "TemplateString" || !language) return null;
const overlay = contentRanges(template, input);
if (!overlay.length) return null;
const parser = parserFor(language, resolve);
return parser ? { parser, overlay } : null;
};
}
type JavaScriptConfig = NonNullable<Parameters<typeof javascript>[0]>;
/** `javascript(config)` that also parses embedded languages in template literals. */
export function javascriptWithTemplates(config: JavaScriptConfig, resolve: TemplateLanguageResolver): LanguageSupport {
const base = javascript(config);
const language = (base.language as LRLanguage).configure({ wrap: parseMixed(templateInjection(resolve)) });
return new LanguageSupport(language, base.support);
}
+2 -2
View File
@@ -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<InlayHint["kind"], string> = {
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") },
];
+2 -2
View File
@@ -41,7 +41,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();
@@ -496,7 +496,7 @@ 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`,
icon: "settings",
run: () => editInspectionSettings(inspection.id),
submenu: intentionControls(inspection),
+4 -4
View File
@@ -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<void> {
// 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<void> {
]);
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();
+392
View File
@@ -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<SkillScanWarningKind, string> = {
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<McpScope>("user");
const [browseResult, setBrowseResult] = useState<RemoteSkillBrowseResult | null>(null);
const [selectedSubpath, setSelectedSubpath] = useState<string | null>(null);
const [preview, setPreview] = useState<RemoteSkillPreview | null>(null);
const [previewTab, setPreviewTab] = useState<PreviewTab>("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<string | null>(null);
const activeReq = useRef<RequestId | null>(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 (
<Dialog
open
onClose={handleClose}
title={tx("Install Agent Skill")}
width={680}
buttons={[
{
label: installing ? "Installing…" : "Install",
role: "default",
disabled: !canInstall,
onClick: () => void handleInstall(),
},
{ label: "Cancel", role: "cancel", onClick: handleClose },
]}
>
<div className={styles.installBody}>
<p className={styles.hint}>
<T>
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.
</T>
</p>
<div className={styles.installSourceRow}>
<Input
className={styles.installSourceInput}
value={source}
onChange={(e) => 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
/>
<Button
variant="secondary"
disabled={!source.trim() || loading || installing}
onClick={() => void fetchRepository()}
>
{loading && !browseResult ? <T>Fetching…</T> : <T>Fetch</T>}
</Button>
</div>
<div className={styles.installScopeRow}>
<span>
<T>Install location</T>
</span>
<Select
className={styles.installScopeSelect}
variant="framed"
aria-label={tx("Install location")}
value={scope}
disabled={installing}
options={[
{ value: "user" as McpScope, label: tx("User (~/.agents/skills)") },
...(hasTrustedProject
? [{ value: "workspace" as McpScope, label: tx("Workspace (.agents/skills)") }]
: []),
]}
onChange={setScope}
/>
</div>
{error && (
<div className={page.error} role="alert">
<Icon name="error" size={14} />
<span>{error}</span>
</div>
)}
{browseResult && (
<div className={styles.candidateSection}>
<div className={styles.candidateHeader}>
<span>
{browseResult.owner}/{browseResult.repo}@{browseResult.gitRef}
</span>
<span>{formatMessage(tx("{count} skills found"), { count: browseResult.skills.length })}</span>
</div>
{browseResult.skills.length > 1 && (
<div className={styles.candidateList} role="listbox" aria-label={tx("Available skills")}>
{browseResult.skills.map((candidate) => {
const active = selectedSubpath === candidate.subpath;
return (
<button
key={candidate.subpath || candidate.folderName}
type="button"
role="option"
aria-selected={active}
className={clsx(styles.candidateBtn, active && styles.candidateBtnActive)}
onClick={() => void loadPreview(browseResult, candidate)}
>
<span>{candidate.folderName}</span>
<span className={styles.candidateMeta}>{formatBytes(candidate.totalBytes)}</span>
</button>
);
})}
</div>
)}
</div>
)}
{loading && browseResult && !preview && (
<div className={styles.hint}>
<T>Scanning SKILL.md and bundled files…</T>
</div>
)}
{preview && (
<>
{preview.scanWarnings.length === 0 ? (
<div className={styles.scanClean} role="status">
<Icon name="check" size={14} className={styles.scanCleanIcon} />
<span>
<T>
Static scan passed: no hidden Unicode, out-of-root symlinks, shell tool grants, or executable
scripts detected.
</T>
</span>
</div>
) : (
<div className={styles.scanWarnBox} role="region" aria-label={tx("Static security scan warnings")}>
<div className={styles.scanWarnTitle}>
<Icon name="warning" size={14} />
<span>
{formatMessage(tx("Static security scan found {count} warnings"), {
count: preview.scanWarnings.length,
})}
</span>
</div>
<ul className={styles.scanWarnList}>
{preview.scanWarnings.map((w, idx) => (
<li key={`${w.kind}:${w.file}:${idx}`}>
<strong>{tx(WARNING_KIND_LABELS[w.kind])}:</strong>{" "}
<span className={styles.scanWarnCode}>{w.file}</span> — {w.message}
</li>
))}
</ul>
<Checkbox
checked={confirmedWarnings}
onChange={setConfirmedWarnings}
label={tx("I reviewed these warnings and want to install this skill")}
/>
</div>
)}
{alreadyExists && (
<Checkbox
checked={overwrite}
onChange={setOverwrite}
label={formatMessage(tx("Replace existing {name} folder in the selected location"), {
name: preview.skillName,
})}
/>
)}
<div className={clsx(styles.previewBox, selectableText)}>
<div className={styles.previewMeta}>
<div className={page.cardTitleRow}>
<span className={styles.skillName}>{preview.skillName}</span>
{preview.subpath && <span className={page.tag}>{preview.subpath}</span>}
</div>
{preview.description && <span className={styles.subtitle}>{preview.description}</span>}
</div>
<Tabs
variant="compact"
aria-label={tx("Skill preview")}
activeId={previewTab}
onSelect={(id) => setPreviewTab(id as PreviewTab)}
items={[
{ id: "markdown", label: "SKILL.md", text: "SKILL.md" },
{
id: "files",
label: formatMessage(tx("Files ({count})"), { count: preview.files.length }),
text: tx("Files"),
},
]}
/>
{previewTab === "markdown" ? (
<pre className={styles.previewMarkdown}>{preview.skillMarkdown}</pre>
) : (
<div className={styles.fileList} role="list">
{preview.files.map((f) => (
<div key={f.path} role="listitem" className={styles.fileRow}>
<span className={styles.filePath}>{f.path}</span>
<span className={styles.fileRight}>
{f.executable && (
<span className={clsx(page.tag, page.tagWarning)}>
<T>Executable</T>
</span>
)}
{f.symlink && (
<span className={page.tag}>
<T>Symlink</T>
</span>
)}
<span>{formatBytes(f.size)}</span>
</span>
</div>
))}
</div>
)}
</div>
</>
)}
</div>
</Dialog>
);
}
+197
View File
@@ -33,3 +33,200 @@
font-size: var(--fs-small);
line-height: 1.4;
}
.installBody {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: var(--space-3) var(--space-4) 0;
}
.installSourceRow {
display: flex;
align-items: center;
gap: var(--space-2);
}
.installSourceInput {
flex: 1;
min-width: 0;
}
.installScopeRow {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
font-size: var(--fs-small);
color: var(--fg-secondary);
}
.installScopeSelect {
min-width: 240px;
}
.candidateSection {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
}
.candidateHeader {
display: flex;
align-items: center;
justify-content: space-between;
font-size: var(--fs-small);
color: var(--fg-muted);
}
.candidateList {
display: flex;
flex-wrap: wrap;
gap: var(--space-1-5);
max-height: 112px;
overflow-y: auto;
}
.candidateBtn {
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
padding: 4px 10px;
border-radius: var(--radius-small);
border: 1px solid var(--border-popup);
background: var(--bg-elev);
color: var(--fg);
font-size: var(--fs-small);
cursor: pointer;
}
.candidateBtn:hover {
background: var(--bg-hover);
}
.candidateBtnActive {
border-color: var(--accent);
background: var(--bg-selected);
color: var(--fg-strong);
}
.candidateMeta {
color: var(--fg-muted);
font-size: var(--fs-tiny);
}
.scanClean {
display: flex;
align-items: center;
gap: var(--space-2);
padding: 8px 10px;
border-radius: var(--radius-small);
border: 1px solid var(--border-popup);
background: var(--bg-elev);
color: var(--fg-secondary);
font-size: var(--fs-small);
}
.scanCleanIcon {
color: var(--success);
flex-shrink: 0;
}
.scanWarnBox {
display: flex;
flex-direction: column;
gap: var(--space-2);
padding: 10px 12px;
border-radius: var(--radius-small);
border: 1px solid var(--warning);
background: var(--bg-elev);
font-size: var(--fs-small);
}
.scanWarnTitle {
display: flex;
align-items: center;
gap: var(--space-1-5);
font-weight: 600;
color: var(--warning);
}
.scanWarnList {
margin: 0;
padding-left: 18px;
display: flex;
flex-direction: column;
gap: var(--space-1);
color: var(--fg);
max-height: 120px;
overflow-y: auto;
}
.scanWarnCode {
font-family: var(--font-mono);
font-size: var(--fs-tiny);
color: var(--fg-secondary);
}
.previewBox {
display: flex;
flex-direction: column;
gap: var(--space-2);
border: 1px solid var(--border-popup);
border-radius: var(--radius-small);
padding: 10px;
background: var(--bg-app);
}
.previewMeta {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
}
.previewMarkdown {
margin: 0;
max-height: 210px;
overflow: auto;
white-space: pre-wrap;
word-break: break-word;
font-family: var(--font-mono);
font-size: var(--fs-small);
line-height: 1.45;
color: var(--fg);
}
.fileList {
display: flex;
flex-direction: column;
gap: var(--space-1);
max-height: 210px;
overflow-y: auto;
}
.fileRow {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding: 3px 6px;
border-radius: var(--radius-small);
font-size: var(--fs-small);
}
.filePath {
font-family: var(--font-mono);
color: var(--fg);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.fileRight {
display: flex;
align-items: center;
gap: var(--space-1-5);
color: var(--fg-muted);
font-size: var(--fs-tiny);
flex-shrink: 0;
}
+140 -2
View File
@@ -1,6 +1,14 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import type { AgentSkillMode, AgentSkillSource, AgentSkillState, McpScope, ProjectInfo } from "@/bindings";
import type {
AgentSkillMode,
AgentSkillSource,
AgentSkillState,
InstallRemoteSkillRequest,
McpScope,
ProjectInfo,
RemoteSkillPreview,
} from "@/bindings";
import { useProject } from "@/platform/project";
import { SkillsPage, type SkillsBackend } from "./SkillsPage";
@@ -26,6 +34,7 @@ const state = (
const SKILLS: AgentSkillState[] = [
state("tdd", "workspace"),
state("impeccable", "user", "off"),
state("release-notes", "plugin"),
state("ux-flow", "claudeWorkspace", "slashOnly"),
state("playwright", "copilotUser"),
];
@@ -45,7 +54,7 @@ function backend(): SkillsBackend & { setModeCalls: Array<{ name: string; scope:
/** Opens one row's select and picks an option by text. */
function pick(triggerLabel: string, option: string) {
fireEvent.click(screen.getByRole("button", { name: triggerLabel }));
fireEvent.click(within(screen.getByRole("listbox")).getByText(option));
fireEvent.click(within(screen.getByRole("listbox", { name: triggerLabel })).getByText(option));
}
afterEach(() => useProject.setState({ project: null }));
@@ -58,6 +67,9 @@ describe("SkillsPage", () => {
const workspace = screen.getByRole("region", { name: "Workspace" });
expect(within(workspace).getByText("tdd")).toBeInTheDocument();
expect(screen.getByRole("region", { name: "User" })).toBeInTheDocument();
const plugins = screen.getByRole("region", { name: "Plugins" });
expect(within(plugins).getByText("release-notes")).toBeInTheDocument();
expect(within(plugins).queryByText("CLI-discovered")).not.toBeInTheDocument();
expect(screen.getByRole("region", { name: "Claude Code" })).toBeInTheDocument();
expect(screen.getByRole("region", { name: "GitHub Copilot" })).toBeInTheDocument();
expect(screen.getAllByText("Slash only").length).toBeGreaterThan(0);
@@ -80,10 +92,16 @@ describe("SkillsPage", () => {
render(<SkillsPage backend={backend()} />);
await waitFor(() => expect(screen.getByText("tdd")).toBeInTheDocument());
fireEvent.click(screen.getByRole("tab", { name: /Plugins/ }));
expect(screen.getByText("release-notes")).toBeInTheDocument();
expect(screen.queryByText("tdd")).not.toBeInTheDocument();
expect(screen.queryByText("playwright")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("tab", { name: /Agent Folders/ }));
expect(screen.getByText("playwright")).toBeInTheDocument();
expect(screen.queryByText("tdd")).not.toBeInTheDocument();
expect(screen.queryByText("impeccable")).not.toBeInTheDocument();
expect(screen.queryByText("release-notes")).not.toBeInTheDocument();
});
it("sets a skill's mode in Global from its row", async () => {
@@ -139,4 +157,124 @@ describe("SkillsPage", () => {
expect(await screen.findByText(/does not match the folder/)).toBeInTheDocument();
expect(screen.queryByText("SKILL.md is valid")).not.toBeInTheDocument();
});
it("browses a GitHub repo, previews SKILL.md & files, gates on static scan warnings, and installs", async () => {
const project = { root: "/proj", name: "Proj", trusted: true, isGit: true } as ProjectInfo;
useProject.setState({ project });
const installCalls: InstallRemoteSkillRequest[] = [];
const previews: Record<string, RemoteSkillPreview> = {
"skills/clean-doc": {
owner: "acme",
repo: "skills",
gitRef: "main",
treeSha: "abc123",
subpath: "skills/clean-doc",
skillName: "clean-doc",
description: "Clean documentation helper",
skillMarkdown: "---\nname: clean-doc\ndescription: Clean documentation helper\n---\nWrite clear docs.\n",
files: [{ path: "SKILL.md", size: 92, executable: false, symlink: false }],
scanWarnings: [],
alreadyInstalledUser: false,
alreadyInstalledWorkspace: false,
},
"skills/deploy-script": {
owner: "acme",
repo: "skills",
gitRef: "main",
treeSha: "abc123",
subpath: "skills/deploy-script",
skillName: "deploy-script",
description: "Deploys staging builds",
skillMarkdown:
"---\nname: deploy-script\ndescription: Deploys staging builds\nallowed-tools: Bash(git:*)\n---\nRun deploy.\n",
files: [
{ path: "SKILL.md", size: 112, executable: false, symlink: false },
{ path: "scripts/deploy.sh", size: 48, executable: true, symlink: false },
],
scanWarnings: [
{
kind: "executableScript",
file: "scripts/deploy.sh",
message: "Contains executable file mode (100755)",
},
{
kind: "allowedToolsShell",
file: "SKILL.md",
message: "`allowed-tools` grants shell/command execution (`Bash(git:*)`)",
},
],
alreadyInstalledUser: false,
alreadyInstalledWorkspace: false,
},
};
const installerBackend: SkillsBackend = {
...backend(),
browse: vi.fn(async () => ({
owner: "acme",
repo: "skills",
gitRef: "main",
treeSha: "abc123",
truncated: false,
skills: [
{ folderName: "clean-doc", subpath: "skills/clean-doc", fileCount: 1, totalBytes: 92 },
{ folderName: "deploy-script", subpath: "skills/deploy-script", fileCount: 2, totalBytes: 160 },
],
})),
preview: vi.fn(async (_owner, _repo, _ref, subpath) => {
const found = previews[subpath];
if (!found) throw new Error(`missing preview for ${subpath}`);
return found;
}),
install: vi.fn(async (input) => {
installCalls.push(input);
return [...SKILLS, state("deploy-script", input.scope === "workspace" ? "workspace" : "user")];
}),
};
render(<SkillsPage backend={installerBackend} />);
await waitFor(() => expect(screen.getByText("tdd")).toBeInTheDocument());
fireEvent.click(screen.getByRole("button", { name: "Install Skill…" }));
const dialog = await screen.findByRole("dialog", { name: "Install Agent Skill" });
fireEvent.change(within(dialog).getByLabelText("Skill repository"), { target: { value: "acme/skills" } });
fireEvent.click(within(dialog).getByRole("button", { name: "Fetch" }));
// First candidate (`clean-doc`) has 0 warnings -> Install is immediately enabled.
expect(await within(dialog).findByText(/Static scan passed/)).toBeInTheDocument();
expect(within(dialog).getByRole("button", { name: "Install" })).toBeEnabled();
// Switch to `deploy-script` -> warnings require confirmation checkbox before Install enables.
fireEvent.click(within(dialog).getByRole("option", { name: /deploy-script/ }));
expect(await within(dialog).findByText(/Static security scan found 2 warnings/)).toBeInTheDocument();
const installBtn = within(dialog).getByRole("button", { name: "Install" });
expect(installBtn).toBeDisabled();
// Inspect bundled file list tab.
fireEvent.click(within(dialog).getByRole("tab", { name: /Files \(2\)/ }));
expect(within(dialog).getAllByText("scripts/deploy.sh")).toHaveLength(2);
expect(within(dialog).getByText("Executable")).toBeInTheDocument();
// Confirm warnings and install into Workspace (.agents/skills).
pick("Install location", "Workspace (.agents/skills)");
fireEvent.click(within(dialog).getByLabelText("I reviewed these warnings and want to install this skill"));
expect(installBtn).toBeEnabled();
fireEvent.click(installBtn);
await waitFor(() =>
expect(installCalls).toEqual([
{
owner: "acme",
repo: "skills",
gitRef: "main",
subpath: "skills/deploy-script",
scope: "workspace",
confirmWarnings: true,
overwrite: false,
},
]),
);
await waitFor(() => expect(screen.getByText("deploy-script")).toBeInTheDocument());
});
});
+36 -2
View File
@@ -9,9 +9,11 @@ import { useCallback, useEffect, useMemo, useState } from "react";
import type { AgentSkillMode, AgentSkillState, McpScope } from "@/bindings";
import { revealInFileManager, revealInFileManagerLabel } from "@/platform/fileManager";
import { formatMessage, useTx } from "@/platform/i18n";
import { isTauri, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { Button, Icon, IconButton, SearchField, Select, Tabs, T } from "@/ui";
import { editorService } from "@/workbench/contributions";
import { InstallSkillDialog } from "./InstallSkillDialog";
import { providerIcon } from "./model";
import {
SKILL_SOURCE_GROUPS,
@@ -25,7 +27,7 @@ import styles from "./SkillsPage.module.css";
export { defaultSkillsBackend, type SkillsBackend };
type SourceTab = "all" | "workspace" | "user" | "cli";
type SourceTab = "all" | "workspace" | "user" | "plugin" | "cli";
/** A key of the source-group table (and so, a skill source). */
type SkillSource = keyof typeof SKILL_SOURCE_GROUPS;
@@ -42,17 +44,20 @@ function groupsForTab(tab: SourceTab): readonly SkillSource[] {
if (tab === "all") return order;
if (tab === "workspace") return order.filter((s) => s === "workspace" || s.endsWith("Workspace"));
if (tab === "user") return order.filter((s) => s === "user" || s.endsWith("User"));
if (tab === "plugin") return ["plugin"];
return order.filter(isDiscoveredSource);
}
export function SkillsPage({ backend = defaultSkillsBackend }: { backend?: SkillsBackend }) {
const tx = useTx();
const hasProject = useProject((s) => !!s.project?.root);
const hasTrustedProject = useProject((s) => !!s.project?.root && !!s.project?.trusted);
const [tab, setTab] = useState<SourceTab>("all");
const [skills, setSkills] = useState<AgentSkillState[]>([]);
const [query, setQuery] = useState("");
const [error, setError] = useState<string | null>(null);
const [busyName, setBusyName] = useState<string | null>(null);
const [installOpen, setInstallOpen] = useState(false);
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});
// The scope the row's mode selector writes to; defaults follow where the mode came from.
@@ -80,7 +85,13 @@ export function SkillsPage({ backend = defaultSkillsBackend }: { backend?: Skill
useEffect(() => {
load();
}, [load]);
if (backend !== defaultSkillsBackend || !isTauri() || typeof onIdeEvent !== "function") return;
return onIdeEvent("settingsChanged", (e) => {
if (!e.key || e.key.startsWith("agents.skills")) {
load();
}
});
}, [load, backend]);
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
@@ -133,6 +144,11 @@ export function SkillsPage({ backend = defaultSkillsBackend }: { backend?: Skill
<T>Skills</T>
</h2>
<div className={page.headerActions}>
{backend.browse && backend.preview && backend.install && (
<Button variant="primary" onClick={() => setInstallOpen(true)}>
<Icon name="plus" size={14} /> <T>Install Skill…</T>
</Button>
)}
<Button variant="secondary" onClick={load}>
<Icon name="refresh" size={14} /> <T>Rescan</T>
</Button>
@@ -173,6 +189,12 @@ export function SkillsPage({ backend = defaultSkillsBackend }: { backend?: Skill
text: tx("User"),
trailing: <span className={page.badge}>{tabCount("user")}</span>,
},
{
id: "plugin",
label: tx("Plugins"),
text: tx("Plugins"),
trailing: <span className={page.badge}>{tabCount("plugin")}</span>,
},
{
id: "cli",
label: tx("Agent Folders"),
@@ -255,6 +277,18 @@ export function SkillsPage({ backend = defaultSkillsBackend }: { backend?: Skill
</div>
)}
</div>
{installOpen && (
<InstallSkillDialog
backend={backend}
hasTrustedProject={hasTrustedProject}
onInstalled={(next) => {
syncCatalog(next);
setInstallOpen(false);
}}
onClose={() => setInstallOpen(false)}
/>
)}
</div>
);
}
+12
View File
@@ -153,6 +153,18 @@ describe("SkillsPicker", () => {
).not.toBeInTheDocument();
});
it("groups plugin-contributed skills under Plugins and lets the session toggle them", async () => {
const withPlugin = [...SKILLS, state("release-notes", "plugin", "auto")];
render(<Harness skills={withPlugin} />);
fireEvent.click(screen.getByRole("button", { name: "Skills" }));
expect(await screen.findByText("Plugins")).toBeInTheDocument();
const toggle = screen.getByRole("switch", { name: "Enable release-notes for this session" });
expect(toggle).toHaveAttribute("aria-checked", "true");
fireEvent.click(toggle);
await waitFor(() => expect(screen.getByRole("button", { name: "Skills" })).toHaveTextContent("Skills3/5"));
});
it("shows an empty state without skills", async () => {
render(<Harness skills={[]} />);
+2 -2
View File
@@ -11,7 +11,7 @@ import type {
AgentTokens,
AgentUsage,
} from "@/bindings";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
export interface FileRef {
/** Absolute path (in the task's directory). */
@@ -562,7 +562,7 @@ const LIMIT_WINDOWS: Record<string, { short: string; name: string }> = {
export function limitLabel(l: AgentLimit, now: number): { short: string; percent: number; detail: string } {
const known = LIMIT_WINDOWS[l.window];
const percent = Math.min(100, Math.round(l.usedPercent ?? 0));
const name = known ? tx(known.name) : l.window;
const name = known ? txPart(known.name) : l.window;
const used = tx`${name}: ${percent}% used`;
if (l.resetsMs == null)
return {
+25 -2
View File
@@ -5,24 +5,47 @@
*/
import { useEffect } from "react";
import { create } from "zustand";
import type { AgentSkillMode, AgentSkillSource, AgentSkillState, McpScope } from "@/bindings";
import type {
AgentSkillMode,
AgentSkillSource,
AgentSkillState,
InstallRemoteSkillRequest,
McpScope,
RemoteSkillBrowseResult,
RemoteSkillPreview,
RequestId,
} from "@/bindings";
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
export interface SkillsBackend {
list(): Promise<AgentSkillState[]>;
setMode(name: string, scope: McpScope, mode: AgentSkillMode): Promise<AgentSkillState[]>;
browse?(source: string, request: RequestId): Promise<RemoteSkillBrowseResult>;
preview?(
owner: string,
repo: string,
gitRef: string,
subpath: string,
request: RequestId,
): Promise<RemoteSkillPreview>;
install?(input: InstallRemoteSkillRequest, request: RequestId): Promise<AgentSkillState[]>;
}
export const defaultSkillsBackend: SkillsBackend = {
list: () => (typeof commands.agentSkillsList === "function" ? call(commands.agentSkillsList()) : Promise.resolve([])),
setMode: (name, scope, mode) => call(commands.agentSkillsSetMode(name, scope, mode)),
browse: (source, request) => call(commands.agentSkillsBrowse(source, request)),
preview: (owner, repo, gitRef, subpath, request) =>
call(commands.agentSkillsPreview(owner, repo, gitRef, subpath, request)),
install: (input, request) => call(commands.agentSkillsInstall(input, request)),
};
/** Which folder family a skill came from, with the paths it is discovered in. */
export const SKILL_SOURCE_GROUPS: Record<AgentSkillSource, { label: string; paths: string; agent: string | null }> = {
workspace: { label: "Workspace", paths: ".agents/skills · .openidea/skills", agent: null },
user: { label: "User", paths: "~/.agents/skills", agent: null },
plugin: { label: "Plugins", paths: "[[contributes.skills]]", agent: null },
claudeWorkspace: { label: "Claude Code", paths: ".claude/skills", agent: "claude" },
claudeUser: { label: "Claude Code", paths: "~/.claude/skills", agent: "claude" },
githubWorkspace: { label: "GitHub Copilot", paths: ".github/skills", agent: "copilot" },
@@ -35,7 +58,7 @@ export const SKILL_SOURCE_GROUPS: Record<AgentSkillSource, { label: string; path
/** Skill folders the CLI discovers itself: OpenIDEA only reads them, and its "off" holds only where the CLI supports it. */
export function isDiscoveredSource(source: AgentSkillSource): boolean {
return source !== "workspace" && source !== "user";
return source !== "workspace" && source !== "user" && source !== "plugin";
}
export interface SessionSkillItem {
+2 -2
View File
@@ -36,7 +36,7 @@ import {
} from "./jsonValue";
import { JsonValueEditor, JsonValueWindow, type JsonEditorApi } from "./JsonValueEditor";
import styles from "./Database.module.css";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
export type DataPanel = "record" | "value" | "aggregates";
@@ -46,7 +46,7 @@ export function exportMenu(data: ExportData, source: string, format?: ExportForm
{ label: "Export Data…", icon: "export", run: () => openDialog({ kind: "export", data, source, format }) },
{ kind: "separator" },
...EXPORT_FORMATS.map((f): MenuItem => ({
label: tx`Copy as ${f.label}`,
label: tx`Copy as ${txPart(f.label)}`,
icon: "copy",
run: () => void writeClipboardText(exportData(f.id, data)),
})),
+3 -3
View File
@@ -46,7 +46,7 @@ import {
} from "./store";
import { openTableData } from "./treeActions";
import styles from "./Database.module.css";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
/** Read-only SQL with the editor's syntax colours (IDEA's dialog Preview pane). */
function SqlPreview({ sql, label = "Preview" }: { sql: string; label?: string }) {
@@ -130,7 +130,7 @@ function RenameDialog({ id, object }: { id: string; object: DbObjectRef | null }
>
<div className={styles.dialogBody}>
<label className={styles.formLabelLeft} htmlFor="db-rename">
{tx`Rename ${what} '${initial}' to:`}
{tx`Rename ${txPart(what)} '${initial}' to:`}
</label>
<Input
id="db-rename"
@@ -166,7 +166,7 @@ function DropDialog({ id, object }: { id: string; object: DbObjectRef }) {
>
<div className={styles.dialogBody}>
<div className={styles.dialogLead}>
{tx`Drop ${KIND_LABEL[object.kind]}`} <strong>{reference(driver, object)}</strong>
{tx`Drop ${txPart(KIND_LABEL[object.kind])}`} <strong>{reference(driver, object)}</strong>
{tx`? This cannot be undone.`}
</div>
<Checkbox
@@ -6,7 +6,7 @@
*/
import { useEffect, useMemo, useRef, useState } from "react";
import clsx from "clsx";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import { Button, Checkbox, Dialog, EmptyState, Icon, Select, Spinner, T, Tree, type SelectOption } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { CodePreview } from "./CodePreview";
@@ -72,14 +72,14 @@ function SidePicker({ label, side, onChange }: { label: string; side: Side; onCh
<T>{label}</T>
</span>
<Select
aria-label={tx`${tx(label)} data source`}
aria-label={tx`${txPart(label)} data source`}
value={side.id || null}
placeholder="<data source>"
options={sourceOptions}
onChange={(id) => onChange({ id, schema: sourceById(id)?.driver === "sqlite" ? "main" : "" })}
/>
<Select
aria-label={tx`${tx(label)} schema`}
aria-label={tx`${txPart(label)} schema`}
value={side.schema || null}
placeholder="<schema>"
options={schemaOptions}
@@ -129,7 +129,7 @@ function migrates(source: Side, target: Side): string {
}
function includeLabel(r: Row): string {
const name = r.kind === "group" ? tx(r.label) : r.diff.name;
const name = r.kind === "group" ? txPart(r.label) : r.diff.name;
return tx`Include ${name}`;
}
+2 -2
View File
@@ -21,7 +21,7 @@ import {
type DbTxMode,
} from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { tx, useTx, useTxTemplate } from "@/platform/i18n";
import { tx, txPart, useTx, useTxTemplate } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { sshLabel as configLabel } from "@/platform/remoteSettings";
import { useWorkflowSettings } from "@/platform/workflowSettings";
@@ -333,7 +333,7 @@ function SecondsOption({
<Input
className={styles.secondsInput}
inputMode="numeric"
aria-label={tx`${label} (seconds)`}
aria-label={tx`${txPart(label)} (seconds)`}
disabled={!on}
value={draft}
onChange={(e) => {
@@ -0,0 +1,245 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
const ipc = vi.hoisted(() => ({ debugEvaluateIn: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return { ...real, commands: { ...real.commands, ...ipc } };
});
import type { DebugSessionId, Variable } from "@/platform/ipc";
import { adoptSession, useDebug } from "../state";
import { clampWindow, isTableType, parseTableResult, tableExpression } from "../tableView";
import { TableViewDialog } from "../ui/TableViewDialog";
import { VariablesView } from "../ui/VariablesView";
import { useOverlays } from "../ui/popoverStore";
import { hideContextMenu, useContextMenuStore } from "@/ui/Menu";
/** How debugpy shows the helper's JSON reply: Python's repr of a str. */
const pyRepr = (o: unknown) => `'${JSON.stringify(o).replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
const reply = (o: unknown) =>
Promise.resolve({
status: "ok" as const,
data: { name: "", value: pyRepr(o), typeName: "str", variablesReference: 0, evaluateName: null },
});
const PAGE = {
kind: "frame" as const,
shape: [250, 2],
rows: 250,
columns: 2,
dtypes: ["object", "float64"],
headers: ["name", "score"],
index: ["0", "1"],
cells: [
['it\'s "x"', "1.5"],
["日本", "nan"],
],
};
function session(adapter = "debugpy") {
useDebug.setState({ sessions: {}, active: null });
adoptSession(7, { adapter });
useDebug.setState((s) => ({
sessions: { 7: { ...s.sessions[7]!, status: "paused", selectedFrame: 10 } },
active: 7,
}));
}
/** A `stopped` event as `state.ts` records it: the frame is unknown until the stack trace arrives. */
function stop(frame: number | null) {
act(() =>
useDebug.setState((s) => ({
sessions: {
7: { ...s.sessions[7]!, stops: s.sessions[7]!.stops + (frame == null ? 1 : 0), selectedFrame: frame },
},
})),
);
}
beforeEach(() => session());
afterEach(() => {
cleanup();
vi.clearAllMocks();
useDebug.setState({ sessions: {}, active: null });
useOverlays.setState({ tableView: null });
});
describe("table view model", () => {
it("knows the types debugpy reports for DataFrame, Series and ndarray", () => {
expect(["DataFrame", "Series", "ndarray"].every(isTableType)).toBe(true);
expect(isTableType("list")).toBe(false);
expect(isTableType(null)).toBe(false);
});
it("reads the helper's reply through Python's string quoting", () => {
expect(parseTableResult(pyRepr(PAGE))).toEqual({ page: PAGE });
expect(parseTableResult(pyRepr({ error: "ndim", ndim: 3 }))).toEqual({ error: "ndim", ndim: 3 });
expect(parseTableResult("NameError: name 'df' is not defined")).toEqual({
error: "NameError: name 'df' is not defined",
});
});
it("moves a window the object no longer reaches back to its last page", () => {
const w = { row: 100, column: 30 };
expect(clampWindow(w, { rows: 250, columns: 45 })).toBe(w);
expect(clampWindow({ row: 200, column: 30 }, { rows: 50, columns: 45 })).toEqual({ row: 0, column: 30 });
expect(clampWindow({ row: 200, column: 30 }, { rows: 150, columns: 12 })).toEqual({ row: 100, column: 0 });
expect(clampWindow({ row: 100, column: 0 }, { rows: 0, columns: 0 })).toEqual({ row: 0, column: 0 });
});
it("passes the expression outside the helper's lambda, with the page window", () => {
const e = tableExpression("frames['a']", { row: 100, column: 30 });
expect(e).toMatch(
/^\(lambda g, o: \(exec\(".*", g\), g\['f'\]\(o, 100, 100, 30, 30\)\)\[1\]\)\(\{\}, \(frames\['a'\]\)\)$/s,
);
});
});
describe("View as Table", () => {
it("shows a page with headers, dtypes and index, and fetches the next rows on demand", async () => {
ipc.debugEvaluateIn.mockImplementation(() => reply(PAGE));
render(<TableViewDialog expression="df" session={7 as DebugSessionId} onClose={() => {}} />);
const table = await screen.findByRole("table");
expect(
within(table)
.getAllByRole("columnheader")
.map((h) => h.textContent),
).toEqual(["", "nameobject", "scorefloat64"]);
expect(within(table).getAllByRole("row")[1]!.textContent).toBe('0it\'s "x"1.5');
expect(screen.getByText("Shape (250, 2)")).toBeInTheDocument();
expect(screen.getByText("Rows 1–100 of 250")).toBeInTheDocument();
expect(ipc.debugEvaluateIn).toHaveBeenCalledWith(7, 10, tableExpression("df", { row: 0, column: 0 }), "clipboard");
fireEvent.click(screen.getByRole("button", { name: "Next Rows" }));
await waitFor(() =>
expect(ipc.debugEvaluateIn).toHaveBeenLastCalledWith(
7,
10,
tableExpression("df", { row: 100, column: 0 }),
"clipboard",
),
);
expect(await screen.findByText("Rows 101–200 of 250")).toBeInTheDocument();
});
it("asks for a 2-D slice of an array with more dimensions", async () => {
ipc.debugEvaluateIn.mockImplementation(() => reply({ error: "ndim", ndim: 3 }));
render(<TableViewDialog expression="a" session={7 as DebugSessionId} onClose={() => {}} />);
expect(await screen.findByRole("alert")).toHaveTextContent("A 3-dimensional array can't be shown as a table");
});
it("shows the exception of an expression that fails in the frame", async () => {
// With the `clipboard` context debugpy answers with the exception's repr as the value.
ipc.debugEvaluateIn.mockImplementation(() =>
Promise.resolve({
status: "ok" as const,
data: {
name: "",
value: `NameError("name 'df' is not defined")`,
typeName: "NameError",
variablesReference: 3,
evaluateName: null,
},
}),
);
render(<TableViewDialog expression="df" session={7 as DebugSessionId} onClose={() => {}} />);
expect(await screen.findByRole("alert")).toHaveTextContent(`NameError("name 'df' is not defined")`);
});
it("goes back to the last page when a step leaves the object shorter than the page shown", async () => {
let rows = 250;
ipc.debugEvaluateIn.mockImplementation(() => reply({ ...PAGE, rows, shape: [rows, 2] }));
render(<TableViewDialog expression="df" session={7 as DebugSessionId} onClose={() => {}} />);
fireEvent.click(await screen.findByRole("button", { name: "Next Rows" }));
fireEvent.click(await screen.findByRole("button", { name: "Next Rows" }));
expect(await screen.findByText("Rows 201–250 of 250")).toBeInTheDocument();
rows = 50;
stop(null);
stop(10);
await waitFor(() =>
expect(ipc.debugEvaluateIn).toHaveBeenLastCalledWith(
7,
10,
tableExpression("df", { row: 0, column: 0 }),
"clipboard",
),
);
expect(await screen.findByText("Shape (50, 2)")).toBeInTheDocument();
expect(screen.getAllByRole("row")).toHaveLength(3);
});
it("waits for the stopped frame, and doesn't show the previous stop's page meanwhile", async () => {
ipc.debugEvaluateIn.mockImplementation(() => reply(PAGE));
render(<TableViewDialog expression="df" session={7 as DebugSessionId} onClose={() => {}} />);
await screen.findByRole("table");
ipc.debugEvaluateIn.mockClear();
let answer: (v: unknown) => void = () => {};
ipc.debugEvaluateIn.mockImplementation(() => new Promise((r) => (answer = r)));
stop(null);
expect(ipc.debugEvaluateIn).not.toHaveBeenCalled();
expect(screen.queryByRole("table")).toBeNull();
stop(12);
expect(ipc.debugEvaluateIn).toHaveBeenCalledExactlyOnceWith(
7,
12,
tableExpression("df", { row: 0, column: 0 }),
"clipboard",
);
expect(screen.queryByRole("table")).toBeNull();
await act(async () => answer(await reply(PAGE)));
expect(screen.getByRole("table")).toBeInTheDocument();
});
it("puts a DataFrame's dtypes on its columns even when the page has one column", async () => {
ipc.debugEvaluateIn.mockImplementation(() =>
reply({ ...PAGE, shape: [250, 31], columns: 31, dtypes: ["float64"], headers: ["z"], cells: [["1.0"], ["2.0"]] }),
);
render(<TableViewDialog expression="df" session={7 as DebugSessionId} onClose={() => {}} />);
const table = await screen.findByRole("table");
expect(within(table).getAllByRole("columnheader")[1]).toHaveTextContent("zfloat64");
expect(screen.getByText("Shape (250, 31)")).toBeInTheDocument();
});
const frame: Variable = {
name: "df",
value: " a\n0 1",
typeName: "DataFrame",
variablesReference: 5,
evaluateName: "df",
};
const menuFor = (v: Variable) => {
render(
<VariablesView roots={[{ key: "df", kind: "var", variable: v, container: 1 }]} session={7 as DebugSessionId} />,
);
fireEvent.contextMenu(screen.getByRole("treeitem"));
const labels = (useContextMenuStore.getState().menu?.items ?? []).map((i) => ("label" in i ? i.label : "|"));
hideContextMenu();
cleanup();
return labels;
};
it("is offered for a DataFrame in a Python session, and opens outside the Variables view", () => {
render(
<VariablesView
roots={[{ key: "df", kind: "var", variable: frame, container: 1 }]}
session={7 as DebugSessionId}
/>,
);
fireEvent.contextMenu(screen.getByRole("treeitem"));
const item = useContextMenuStore.getState().menu?.items.find((i) => "label" in i && i.label === "View as Table");
act(() => hideContextMenu());
expect(item && "run" in item).toBe(true);
if (item && "run" in item) item.run?.();
// The Variables view unmounts while the program runs; the viewer stays open across steps.
expect(useOverlays.getState().tableView).toEqual({ expression: "df", session: 7 });
});
it("is not offered for other values or other debuggers", () => {
expect(menuFor({ ...frame, typeName: "list" })).not.toContain("View as Table");
session("lldb");
expect(menuFor(frame)).not.toContain("View as Table");
});
});
+2 -1
View File
@@ -68,7 +68,8 @@ const useAnyOverlay = () =>
s.attach ||
s.smartStep ||
s.streamChooser ||
s.streamAbort != null
s.streamAbort != null ||
s.tableView
),
);
+112
View File
@@ -0,0 +1,112 @@
/**
* View as Table (PyCharm's View as Array / DataFrame): one window of a pandas DataFrame /
* Series or numpy array at a time, read with `evaluate` in the paused frame. The debuggee
* slices the object itself, so only the rows and columns on screen cross the wire.
*/
import { stringText } from "./valueText";
/** Type names debugpy reports for values the viewer can show. */
const TABLE_TYPES = new Set(["DataFrame", "Series", "ndarray"]);
export function isTableType(typeName: string | null | undefined): boolean {
return !!typeName && TABLE_TYPES.has(typeName);
}
/** Numbers are right-aligned, as in the database grid. */
export function isNumericDtype(dtype: string | undefined): boolean {
return !!dtype && /^(u?int|float|complex|Int|UInt|Float)\d*$/.test(dtype);
}
export const ROW_PAGE = 100;
export const COLUMN_PAGE = 30;
export interface TableWindow {
row: number;
column: number;
}
export interface TablePage {
kind: "frame" | "series" | "array";
/** The object's own shape, e.g. `[1000, 5]`. */
shape: number[];
rows: number;
columns: number;
/** One dtype per shown column for a DataFrame, else the object's single dtype. */
dtypes: string[];
headers: string[];
index: string[];
cells: string[][];
}
/** `error`: "type" (not a table), "ndim" (more than two dimensions; `ndim` says how many) or the error text. */
export type TableResult = { page: TablePage } | { error: string; ndim?: number };
// Runs in the debuggee. Cells are cut at 200 characters so one huge cell can't flood the reply.
const HELPER = `
def f(o, r0, nr, c0, nc):
import json
s = lambda v: str(v)[:200]
try:
if hasattr(o, 'iloc') and hasattr(o, 'columns'):
k, d = 'frame', o.iloc[r0:r0 + nr, c0:c0 + nc]
R, C = o.shape
dt, h = [str(x) for x in d.dtypes], [s(c) for c in d.columns]
idx, cells = [s(i) for i in d.index], [[s(v) for v in r] for r in d.itertuples(index=False, name=None)]
elif hasattr(o, 'iloc'):
k, d = 'series', o.iloc[r0:r0 + nr]
R, C = len(o), 1
dt, h = [str(o.dtype)], ['' if o.name is None else s(o.name)]
idx, cells = [s(i) for i in d.index], [[s(v)] for v in d]
elif hasattr(o, 'ndim') and hasattr(o, 'dtype'):
if o.ndim > 2:
return json.dumps({'error': 'ndim', 'ndim': o.ndim})
k, a = 'array', (o.reshape(1, 1) if o.ndim == 0 else o)
R, C = a.shape[0], (a.shape[1] if a.ndim == 2 else 1)
d = a[r0:r0 + nr, c0:c0 + nc] if a.ndim == 2 else a[r0:r0 + nr].reshape(-1, 1)
dt, h = [str(o.dtype)], [str(c0 + j) for j in range(d.shape[1])] if a.ndim == 2 else ['0']
idx, cells = [str(r0 + i) for i in range(d.shape[0])], [[s(v) for v in r] for r in d]
else:
return json.dumps({'error': 'type'})
return json.dumps({'kind': k, 'shape': list(o.shape), 'rows': R, 'columns': C, 'dtypes': dt,
'headers': h, 'index': idx, 'cells': cells})
except Exception as e:
return json.dumps({'error': '%s: %s' % (type(e).__name__, e)})
`;
/**
* The window moved back onto the object when a step or another frame left it with fewer rows
* or columns than the window starts at (the last page then); `w` itself when it still fits.
*/
export function clampWindow(w: TableWindow, page: Pick<TablePage, "rows" | "columns">): TableWindow {
const fit = (at: number, total: number, size: number) =>
at < total ? at : Math.max(0, Math.floor((total - 1) / size) * size);
const row = fit(w.row, page.rows, ROW_PAGE);
const column = fit(w.column, page.columns, COLUMN_PAGE);
return row === w.row && column === w.column ? w : { row, column };
}
/**
* One expression (evaluate takes no statements): defines the helper in a fresh namespace
* and calls it. `expression` is passed as an argument, outside the lambda, because a
* lambda body can't see the frame's locals that `eval` was given.
*/
export function tableExpression(expression: string, w: TableWindow): string {
return (
`(lambda g, o: (exec(${JSON.stringify(HELPER)}, g), ` +
`g['f'](o, ${w.row}, ${ROW_PAGE}, ${w.column}, ${COLUMN_PAGE}))[1])({}, (${expression}))`
);
}
/** The helper's reply (a Python string literal holding JSON), or the adapter's own error text. */
export function parseTableResult(value: string): TableResult {
let data: unknown;
try {
data = JSON.parse(stringText(value));
} catch {
return { error: value };
}
const d = data as Record<string, unknown>;
if (typeof d.error === "string")
return d.error === "ndim" ? { error: "ndim", ndim: Number(d.ndim) } : { error: d.error };
return { page: d as unknown as TablePage };
}
+22 -2
View File
@@ -78,12 +78,13 @@ import { EventBreakpointsSection } from "../js/EventBreakpointsSection";
import { StreamChainChooser } from "../streams/StreamChainChooser";
import { StreamAbortDialog } from "../streams/StreamAbortDialog";
import { closeBreakpointPopover, useOverlays } from "./popoverStore";
import { TableViewDialog } from "./TableViewDialog";
import { VariablesView, type VarRoot } from "./VariablesView";
import { useExpressionCompletion } from "./ExpressionCompletion";
import { pushHistory, readHistory } from "./expressionHistory";
import styles from "./Overlays.module.css";
import { isImeKey } from "@/platform/ime";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
export function DebuggerOverlays() {
return (
@@ -96,10 +97,29 @@ export function DebuggerOverlays() {
<SmartStepChooser />
<StreamChainChooser />
<StreamAbortDialog />
<TableView />
</>
);
}
function TableView() {
const view = useOverlays((s) => s.tableView);
// A finished session (Stop, or Restart, which starts another id) has nothing left to show.
const live = useDebug((s) => view != null && isLive(s.sessions[view.session]));
useEffect(() => {
if (view && !live) useOverlays.setState({ tableView: null });
}, [view, live]);
if (!view || !live) return null;
return (
<TableViewDialog
key={`${view.session}:${view.expression}`}
expression={view.expression}
session={view.session}
onClose={() => useOverlays.setState({ tableView: null })}
/>
);
}
function errorText(e: unknown) {
return e instanceof Error ? e.message : String(e);
}
@@ -586,7 +606,7 @@ function BreakpointsDialog() {
<Checkbox
checked={r.bp.enabled}
onChange={(enabled) => updateExceptionClass(r.bp.id, { enabled })}
aria-label={tx`Enable ${name}`}
aria-label={tx`Enable ${r.bp.className || txPart("No class chosen")}`}
/>
<Icon name="breakpoint-exception" size={14} />
<span className={styles.bpName} title={name}>
@@ -0,0 +1,115 @@
.dialog {
height: clamp(320px, 60vh, 760px);
}
/* The table scrolls under a fixed bar, not the whole dialog body. */
.content {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
.bar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-2);
padding-bottom: var(--space-2);
}
.expression {
flex: 1 1 200px;
min-width: 0;
height: var(--h-list-row);
padding: 0 6px;
font-family: var(--font-mono);
font-size: var(--fs-ui);
color: var(--fg);
background: var(--bg-input);
border: 1px solid var(--border);
border-radius: var(--radius-small);
}
.expression:focus {
outline: none;
border-color: var(--focus-ring);
}
.summary,
.pager {
color: var(--fg-secondary);
white-space: nowrap;
}
.pager {
display: inline-flex;
align-items: center;
gap: var(--space-1);
}
.scroll {
flex: 1;
min-height: 0;
overflow: auto;
box-shadow: inset 0 0 0 1px var(--border);
border-radius: var(--radius-small);
}
.table {
border-collapse: separate;
border-spacing: 0;
font-family: var(--font-mono);
font-size: var(--fs-ui);
color: var(--fg);
}
.table th,
.table td {
height: var(--h-list-row);
padding: 0 8px;
white-space: pre;
border-right: 1px solid var(--border);
border-bottom: 1px solid var(--border);
}
.table thead th {
position: sticky;
top: 0;
z-index: 1;
text-align: left;
font-weight: normal;
color: var(--fg-secondary);
background: var(--bg-island);
}
.table .index {
position: sticky;
left: 0;
text-align: right;
font-weight: normal;
color: var(--fg-secondary);
background: var(--bg-island);
}
.table thead .index {
z-index: 2;
}
.table tbody tr:hover td {
background: var(--bg-hover);
}
.numeric {
text-align: right;
}
.dtype {
margin-left: var(--space-1);
color: var(--fg-subtle);
}
.message {
padding: var(--space-3) 0;
color: var(--fg-secondary);
}
@@ -0,0 +1,205 @@
/** View as Table: a DataFrame / Series / ndarray of the paused frame, one page of rows and columns at a time. */
import { useEffect, useRef, useState } from "react";
import clsx from "clsx";
import type { DebugSessionId } from "@/platform/ipc";
import { Dialog, IconButton } from "@/ui";
import { formatMessage, tx } from "@/platform/i18n";
import { evaluate, useDebug } from "../state";
import {
COLUMN_PAGE,
ROW_PAGE,
clampWindow,
isNumericDtype,
parseTableResult,
tableExpression,
type TableResult,
} from "../tableView";
import styles from "./TableViewDialog.module.css";
export function TableViewDialog({
expression: initial,
session,
onClose,
}: {
expression: string;
session: DebugSessionId;
onClose: () => void;
}) {
const [draft, setDraft] = useState(initial);
const [expression, setExpression] = useState(initial);
const [win, setWin] = useState({ row: 0, column: 0 });
const [result, setResult] = useState<TableResult | null>(null);
// A step, a new stop or another frame shows the values the object has there.
const stops = useDebug((st) => st.sessions[session]?.stops);
const frame = useDebug((st) => st.sessions[session]?.selectedFrame);
const paused = useDebug((st) => st.sessions[session]?.status === "paused");
// What the shown page was read for; another expression, stop or frame makes it stale.
const readFor = useRef("");
useEffect(() => {
const key = `${expression}\n${stops}\n${frame}`;
if (readFor.current !== key) {
readFor.current = key;
setResult(null);
}
const s = useDebug.getState().sessions[session];
// Right after a stop the frame is unknown until the stack trace arrives; without a frame,
// debugpy would run the expression in a namespace of its own.
if (!s || s.status !== "paused" || s.selectedFrame == null) return;
let live = true;
evaluate(tableExpression(expression, win), "clipboard", s).then(
(v) => {
if (!live) return;
const r = parseTableResult(v.value);
const fits = "page" in r ? clampWindow(win, r.page) : win;
if (fits !== win) setWin(fits);
else setResult(r);
},
(e: unknown) => live && setResult({ error: e instanceof Error ? e.message : String(e) }),
);
return () => {
live = false;
};
}, [expression, win, session, stops, frame, paused]);
const page = result && "page" in result ? result.page : null;
const error = !paused
? tx("Values are available while the program is paused")
: result && "error" in result
? result.error === "type"
? tx("Not a pandas DataFrame or Series, or a numpy array")
: result.error === "ndim"
? formatMessage(tx("A {n}-dimensional array can't be shown as a table: view a 2-D slice, e.g. a[0]"), {
n: String(result.ndim),
})
: result.error
: null;
const pager = (
at: number,
size: number,
total: number,
move: (to: number) => void,
label: { range: string; previous: string; next: string },
) =>
total > size && (
<span className={styles.pager}>
<IconButton
icon="chevron-left"
size="small"
title={label.previous}
disabled={at === 0}
onClick={() => move(at - size)}
/>
<span>
{formatMessage(label.range, {
from: String(at + 1),
to: String(Math.min(at + size, total)),
total: String(total),
})}
</span>
<IconButton
icon="chevron-right"
size="small"
title={label.next}
disabled={at + size >= total}
onClick={() => move(at + size)}
/>
</span>
);
return (
<Dialog
open
onClose={onClose}
// An element, not a string: Dialog would translate a variable named like a catalog text ("tasks").
title={<span>{initial}</span>}
width="clamp(520px, 70vw, 1100px)"
minWidth={420}
minHeight={260}
resizable="both"
aria-label={formatMessage(tx("Table view of {label}"), { label: initial })}
className={styles.dialog}
>
<div className={styles.content}>
<div className={styles.bar}>
<input
className={styles.expression}
value={draft}
spellCheck={false}
autoComplete="off"
aria-label={tx("Expression")}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key !== "Enter" || !draft.trim()) return;
e.preventDefault();
setExpression(draft.trim());
setWin({ row: 0, column: 0 });
}}
/>
{page && (
<span className={styles.summary}>
{formatMessage(tx("Shape ({shape})"), { shape: page.shape.join(", ") })}
{page.kind !== "frame" ? ` · ${page.dtypes[0]}` : ""}
</span>
)}
{page &&
pager(win.row, ROW_PAGE, page.rows, (row) => setWin({ ...win, row }), {
range: tx("Rows {from}–{to} of {total}"),
previous: tx("Previous Rows"),
next: tx("Next Rows"),
})}
{page &&
pager(win.column, COLUMN_PAGE, page.columns, (column) => setWin({ ...win, column }), {
range: tx("Columns {from}–{to} of {total}"),
previous: tx("Previous Columns"),
next: tx("Next Columns"),
})}
</div>
{error ? (
<div className={styles.message} role="alert">
{error}
</div>
) : page ? (
<div className={styles.scroll} tabIndex={0} role="region" aria-label={tx("Table")}>
<table className={styles.table}>
<thead>
<tr>
<th className={styles.index} />
{page.headers.map((h, i) => (
<th key={i}>
{h}
{page.kind === "frame" && <span className={styles.dtype}>{page.dtypes[i]}</span>}
</th>
))}
</tr>
</thead>
<tbody>
{page.cells.map((row, r) => (
<tr key={r}>
<th scope="row" className={styles.index}>
{page.index[r]}
</th>
{row.map((cell, c) => (
<td
key={c}
className={clsx(
isNumericDtype(page.kind === "frame" ? page.dtypes[c] : page.dtypes[0]) && styles.numeric,
)}
>
{cell}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
) : (
<div className={styles.message}>{tx("Loading…")}</div>
)}
</div>
</Dialog>
);
}
@@ -55,7 +55,8 @@
display: flex;
align-items: center;
gap: var(--space-1);
min-width: min(8ch, 45%);
/* Cap the automatic flex minimum at the space needed for a short preview. */
width: min(14ch, 50%);
flex: 1 1 0;
}
@@ -135,9 +136,8 @@
}
.type {
min-width: 0;
max-width: 25%;
flex: 0 1 auto;
min-width: min(3ch, 10%);
flex: 0 4 auto;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
@@ -19,11 +19,14 @@ import {
removeAllWatches,
removeWatch,
revealFrame,
rootOf,
sessionSupports,
setVariableValue,
useDebug,
} from "../state";
import { blurDebugView, focusDebugView } from "./focusedView";
import { openTableView } from "./popoverStore";
import { isTableType } from "../tableView";
import { classifyValue, oneLine, shownValue, sortVariables } from "../values";
import { stringText, valueText } from "../valueText";
import { workflowSettings } from "@/platform/workflowSettings";
@@ -400,6 +403,9 @@ export function VariablesView({
{ kind: "separator" },
);
if (editable(node)) items.push({ label: "Set Value…", icon: "edit", shortcut: "F2", run: () => startEdit(node) });
const tableExpression = node.evaluateName;
if (tableExpression && session != null && isTableType(node.typeName) && pausedIn(session)?.adapter === "debugpy")
items.push({ label: "View as Table", run: () => openTableView(tableExpression, session) });
items.push(
{ label: "Copy Value", icon: "copy", run: () => void copyValue(node) },
{ label: "Copy Name", run: () => void writeClipboardText(node.name) },
@@ -480,6 +486,12 @@ export function VariablesView({
);
}
/** The session with this id while it is paused, with the adapter its root session started. */
function pausedIn(session: DebugSessionId | null) {
const s = session != null ? useDebug.getState().sessions[session] : undefined;
return s?.status === "paused" ? rootOf(s) : null;
}
/**
* View: the whole value in a popup that a click outside closes. Adapters cut long strings
* short in variables; the value is evaluated again as for copying (`clipboard`), which
+7
View File
@@ -40,6 +40,8 @@ interface OverlayState {
streamChooser: { session: DebugSessionId; frame: number; chains: StreamChainInfo[] } | null;
/** The session whose stream trace "Abort Operation…" asks about. */
streamAbort: DebugSessionId | null;
/** View as Table; it stays open across steps, so it lives here rather than in the Variables view. */
tableView: { expression: string; session: DebugSessionId } | null;
}
export const useOverlays = create<OverlayState>(() => ({
@@ -51,6 +53,7 @@ export const useOverlays = create<OverlayState>(() => ({
smartStep: null,
streamChooser: null,
streamAbort: null,
tableView: null,
}));
export function openBreakpointPopover(path: string, id: string, at: { x: number; y: number }, focusLog = false) {
@@ -61,6 +64,10 @@ export function closeBreakpointPopover() {
useOverlays.setState({ popover: null });
}
export function openTableView(expression: string, session: DebugSessionId) {
useOverlays.setState({ tableView: { expression, session } });
}
export function openEvaluateDialog(expression = "") {
useOverlays.setState({ evaluate: { expression } });
}
+36 -103
View File
@@ -1,5 +1,5 @@
import { EditorState, StateEffect, StateField, type Extension } from "@codemirror/state";
import { ViewPlugin, type EditorView } from "@codemirror/view";
import type { EditorView } from "@codemirror/view";
import type { CompletionContext, CompletionResult } from "@codemirror/autocomplete";
import {
intentionProviders,
@@ -11,16 +11,12 @@ import {
type ContributedIntention,
type EditorDocContext,
} from "@/editor/api";
import { setFileDiagnostics } from "@/editor/lsp/diagnostics";
import { call, commands, isTauri, nextRequestId, type DependencyVersions, type RequestId } from "@/platform/ipc";
import {
DEPENDENCY_INSPECTION,
DEPENDENCY_PRODUCER,
inspectionProfile,
subscribeInspectionProfile,
} from "@/platform/inspections";
import { call, commands, isTauri, nextRequestId, type DependencyVersions } from "@/platform/ipc";
import { DEPENDENCY_INSPECTION, DEPENDENCY_PRODUCER } from "@/platform/inspections";
import { useProject } from "@/platform/project";
import { tx } from "@/platform/i18n";
import { checkEnabled, manifestCheck, type ManifestCheck } from "./manifestCheck";
import { isPythonManifest, pythonRequirements, registerPythonRequirements } from "./python";
const setVersions = StateEffect.define<DependencyVersions[]>();
const versionsField = StateField.define<DependencyVersions[]>({
@@ -32,12 +28,8 @@ const versionsField = StateField.define<DependencyVersions[]>({
},
});
const viewers = new Map<string, number>();
const enabled = () => inspectionProfile()[DEPENDENCY_INSPECTION]?.enabled !== false;
export function dependencyFixes(view: EditorView, from: number, to: number): ContributedIntention[] {
if (!enabled() || view.state.readOnly) return [];
if (!checkEnabled(DEPENDENCY_INSPECTION) || view.state.readOnly) return [];
const text = view.state.doc;
return (view.state.field(versionsField, false) ?? []).flatMap(({ dependency, update }) => {
if (!update || from > dependency.to || to < dependency.from) return [];
@@ -79,95 +71,30 @@ export function versionCompletions(item: DependencyVersions, ctx: CompletionCont
};
}
const cargoCheck: ManifestCheck<DependencyVersions[]> = {
inspection: DEPENDENCY_INSPECTION,
producer: DEPENDENCY_PRODUCER,
fetch: (doc, id) => call(commands.dependencyVersions(doc.doc, null, id)),
apply(view, items, text) {
view.dispatch({ effects: [setVersions.of(items), intentionsChanged.of(null)] });
return items.flatMap(({ dependency, update }) => {
if (!update) return [];
const { latest } = update;
return [
{
range: offsetsToRange(text, dependency.from, dependency.to),
severity: "info" as const,
message: tx`A newer version is available: ${latest}`,
source: "Cargo",
code: null,
},
];
});
},
};
function extension(doc: EditorDocContext): Extension {
const plugin = ViewPlugin.define((view) => {
if (!isTauri()) return {};
viewers.set(doc.path, (viewers.get(doc.path) ?? 0) + 1);
let timer: ReturnType<typeof setTimeout> | undefined;
let request: RequestId | null = null;
let sequence = 0;
let disposed = false;
const clear = () => setFileDiagnostics(doc.path, DEPENDENCY_PRODUCER, []);
const cancel = () => {
sequence++;
if (request !== null) void commands.cancelRequest(request);
request = null;
};
const run = async () => {
if (disposed || !enabled()) return;
const mine = sequence;
const text = view.state.doc;
const root = useProject.getState().project?.root;
const id = nextRequestId();
request = id;
try {
await whenSynced(view);
if (mine !== sequence || disposed) return;
const items = await call(commands.dependencyVersions(doc.doc, null, id));
if (mine !== sequence || disposed || view.state.doc !== text || useProject.getState().project?.root !== root)
return;
view.dispatch({ effects: [setVersions.of(items), intentionsChanged.of(null)] });
setFileDiagnostics(
doc.path,
DEPENDENCY_PRODUCER,
items.flatMap(({ dependency, update }) => {
if (!update) return [];
const { latest } = update;
return [
{
range: offsetsToRange(text, dependency.from, dependency.to),
severity: "info",
message: tx`A newer version is available: ${latest}`,
source: "Cargo",
code: null,
},
];
}),
);
} catch {
// Offline registries and cancelled checks never interrupt editing.
} finally {
if (request === id) request = null;
}
};
const schedule = () => {
cancel();
clear();
clearTimeout(timer);
timer = setTimeout(() => void run(), 500);
};
schedule();
const offProfile = subscribeInspectionProfile(() => {
schedule();
view.dispatch({ effects: intentionsChanged.of(null) });
});
const offProject = useProject.subscribe((state, previous) => {
if (state.project?.root !== previous.project?.root) {
disposed = true;
cancel();
clearTimeout(timer);
clear();
}
});
return {
update: (u) => {
if (u.docChanged) schedule();
},
destroy: () => {
disposed = true;
cancel();
clearTimeout(timer);
offProfile();
offProject();
const remaining = (viewers.get(doc.path) ?? 1) - 1;
if (remaining) viewers.set(doc.path, remaining);
else {
viewers.delete(doc.path);
clear();
}
},
};
});
const plugin = manifestCheck(doc, cargoCheck);
return [
versionsField,
plugin,
@@ -205,13 +132,19 @@ function versionCompletion(doc: EditorDocContext): Extension {
}
export function activate(): () => void {
return registerEditorContribution({
const offPython = registerPythonRequirements();
const offEditor = registerEditorContribution({
id: "dependency-versions",
extensions: (doc) => {
if (doc.virtual || doc.readOnly) return [];
if (/(?:^|\/)Cargo\.toml$/.test(doc.path)) return extension(doc);
if (/(?:^|\/)(?:go\.mod|package\.json)$/.test(doc.path)) return versionCompletion(doc);
if (isPythonManifest(doc.path)) return pythonRequirements(doc);
return [];
},
});
return () => {
offEditor();
offPython();
};
}
+112
View File
@@ -0,0 +1,112 @@
import type { Extension, Text } from "@codemirror/state";
import { ViewPlugin, type EditorView } from "@codemirror/view";
import { intentionsChanged, whenSynced, type EditorDocContext } from "@/editor/api";
import { setFileDiagnostics } from "@/editor/lsp/diagnostics";
import { commands, isTauri, nextRequestId, type Diagnostic, type RequestId } from "@/platform/ipc";
import { inspectionProfile, subscribeInspectionProfile } from "@/platform/inspections";
import { useProject } from "@/platform/project";
/** A backend check of a manifest file, published as one inspection's diagnostics. */
export interface ManifestCheck<T> {
inspection: string;
producer: string;
fetch(doc: EditorDocContext, request: RequestId): Promise<T>;
/** Shows a result computed for `text` (the view's current text); returns the file's diagnostics. */
apply(view: EditorView, result: T, text: Text): Diagnostic[];
/** The file's result went stale or its last editor closed. */
reset?(path: string): void;
/** Other reasons to check again (an install finished); returns the unsubscribe. */
watch?(recheck: () => void): () => void;
/** Check again when the editor gains focus (the environment may have changed meanwhile). */
onFocus?: boolean;
}
export const checkEnabled = (inspection: string) => inspectionProfile()[inspection]?.enabled !== false;
const viewers = new Map<string, number>();
/** Runs `check` 500 ms after the file opens or changes, while its inspection is on. */
export function manifestCheck<T>(doc: EditorDocContext, check: ManifestCheck<T>): Extension {
return ViewPlugin.define((view) => {
if (!isTauri()) return {};
const key = `${check.producer}\n${doc.path}`;
viewers.set(key, (viewers.get(key) ?? 0) + 1);
let timer: ReturnType<typeof setTimeout> | undefined;
let request: RequestId | null = null;
let sequence = 0;
let disposed = false;
const clear = () => {
setFileDiagnostics(doc.path, check.producer, []);
check.reset?.(doc.path);
};
const cancel = () => {
sequence++;
if (request !== null) void commands.cancelRequest(request);
request = null;
};
const run = async () => {
if (disposed || !checkEnabled(check.inspection)) return;
const mine = sequence;
const text = view.state.doc;
const root = useProject.getState().project?.root;
const id = nextRequestId();
request = id;
try {
await whenSynced(view);
if (mine !== sequence || disposed) return;
const result = await check.fetch(doc, id);
if (mine !== sequence || disposed || view.state.doc !== text || useProject.getState().project?.root !== root)
return;
setFileDiagnostics(doc.path, check.producer, check.apply(view, result, text));
} catch {
// Offline registries, missing interpreters and cancelled checks never interrupt editing.
} finally {
if (request === id) request = null;
}
};
// Keeps the current diagnostics until the new result arrives.
const recheck = () => {
cancel();
clearTimeout(timer);
timer = setTimeout(() => void run(), 500);
};
const schedule = () => {
clear();
recheck();
};
schedule();
const offProfile = subscribeInspectionProfile(() => {
schedule();
view.dispatch({ effects: intentionsChanged.of(null) });
});
const offWatch = check.watch?.(recheck);
const offProject = useProject.subscribe((state, previous) => {
if (state.project?.root !== previous.project?.root) {
disposed = true;
cancel();
clearTimeout(timer);
clear();
}
});
return {
update: (u) => {
if (u.docChanged) schedule();
else if (check.onFocus && u.focusChanged && view.hasFocus) recheck();
},
destroy: () => {
disposed = true;
cancel();
clearTimeout(timer);
offProfile();
offWatch?.();
offProject();
const remaining = (viewers.get(key) ?? 1) - 1;
if (remaining) viewers.set(key, remaining);
else {
viewers.delete(key);
clear();
}
},
};
});
}
+143
View File
@@ -0,0 +1,143 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { act, renderHook } from "@testing-library/react";
import type { PythonRequirements } from "@/bindings";
const pythonRequirements = vi.fn();
const sdkPythonPip = vi.fn();
const cancelRequest = vi.fn(async () => {});
const notify = vi.fn();
vi.mock("@tauri-apps/api/core", async (orig) => ({
...(await orig<object>()),
Channel: class {
onmessage = (_: string) => {};
},
}));
vi.mock("@/platform/ipc", async (orig) => {
const actual = await orig<typeof import("@/platform/ipc")>();
return {
...actual,
isTauri: () => true,
commands: { ...actual.commands, pythonRequirements, sdkPythonPip, cancelRequest },
};
});
vi.mock("@/workbench/contributions", async (orig) => ({
...(await orig<typeof import("@/workbench/contributions")>()),
notifications: () => ({ notify }),
}));
const { activate } = await import("./index");
const { useRequirements } = await import("./python");
const { editorContributions, contributedIntentions } = await import("@/editor/api");
const { diagnosticsFor } = await import("@/editor/lsp/diagnostics");
const { lspDoc } = await import("@/editor/lsp/lsp");
const { useProject } = await import("@/platform/project");
const { useEditorBanners } = await import("@/workbench/contributions");
const text = "# 中文 😀\nDjango>=5\nrequests\nnumpy\n";
const span = (s: string) => ({ from: text.indexOf(s), to: text.indexOf(s) + s.length });
const result: PythonRequirements = {
python: "/p/.venv/bin/python",
unsatisfied: [
{ dependency: { package: "Django", requirement: "Django>=5", ...span("Django>=5") }, installed: "4.2" },
{ dependency: { package: "requests", requirement: "requests", ...span("requests") }, installed: null },
],
};
let deactivate: () => void;
const views: EditorView[] = [];
beforeEach(() => {
vi.useFakeTimers();
pythonRequirements.mockResolvedValue({ status: "ok", data: result });
sdkPythonPip.mockResolvedValue({ status: "ok", data: null });
useProject.setState({ project: { root: "/p" } as never, settings: {} as never });
deactivate = activate();
});
afterEach(() => {
views.splice(0).forEach((view) => view.destroy());
deactivate();
useProject.setState({ project: null, settings: null });
vi.clearAllMocks();
vi.useRealTimers();
});
function editor(path = "/p/requirements.txt") {
const ctx = { doc: 3, path, language: "text", uiMode: "Text", readOnly: false };
const contribution = editorContributions().find((c) => c.id === "dependency-versions")!;
const view = new EditorView({
parent: document.body,
state: EditorState.create({
doc: text,
selection: { anchor: span("requests").from },
extensions: [lspDoc.of(ctx), contribution.extensions(ctx)],
}),
});
views.push(view);
return view;
}
const settle = () => vi.advanceTimersByTimeAsync(550);
const banner = (path: string) =>
renderHook(() => useEditorBanners.getState().banners.get("python.requirements")!.useBanner(path)).result.current;
describe("Python requirements", () => {
it.each(["/p/requirements.txt", "/p/requirements-dev.txt", "/p/pyproject.toml"])("checks %s", async (path) => {
editor(path);
await settle();
expect(pythonRequirements).toHaveBeenCalledWith(3, expect.any(Number));
expect(diagnosticsFor(path)).toMatchObject([
{
severity: "warning",
message: "Requirement Django>=5 is not satisfied: 4.2 is installed",
range: { start: { line: 1, col: 0 }, end: { line: 1, col: 9 } },
},
{ severity: "warning", message: "Package requests is not installed", range: { start: { line: 2, col: 0 } } },
]);
});
it("leaves other files alone", async () => {
editor("/p/constraints.txt");
await settle();
expect(pythonRequirements).not.toHaveBeenCalled();
});
it("installs one or all requirements, then checks again", async () => {
const view = editor();
await settle();
const fixes = contributedIntentions(view);
expect(fixes.map((f) => f.label)).toEqual(["Install requirement", "Install all missing requirements"]);
pythonRequirements.mockResolvedValue({ status: "ok", data: { ...result, unsatisfied: [] } });
await fixes[1]!.run();
await vi.waitFor(() => expect(useRequirements.getState().installs).toBe(1));
expect(sdkPythonPip.mock.calls.map((c) => c.slice(0, 4))).toEqual([
["/p/.venv/bin/python", "Django>=5", false, false],
["/p/.venv/bin/python", "requests", false, false],
]);
await settle();
expect(pythonRequirements).toHaveBeenCalledTimes(2);
expect(diagnosticsFor("/p/requirements.txt")).toEqual([]);
expect(notify).not.toHaveBeenCalled();
});
it("reports failed installs in one notification", async () => {
sdkPythonPip.mockResolvedValue({ status: "error", error: { kind: "failed", message: "no matching distribution" } });
const view = editor();
await settle();
await contributedIntentions(view)[0]!.run();
await vi.waitFor(() => expect(notify).toHaveBeenCalledOnce());
expect(notify.mock.calls[0]![0]).toMatchObject({
level: "error",
body: expect.stringContaining("requests: no matching distribution"),
});
});
it("shows a banner until ignored, and none without unsatisfied requirements", async () => {
editor();
await settle();
expect(useRequirements.getState().byPath.get("/p/requirements.txt")).toEqual(result);
expect(banner("/p/requirements.txt")).toMatchObject({
text: "Package requirements are not satisfied",
actions: [{ label: "Install requirements" }, { label: "Ignore" }],
});
act(() => useRequirements.setState({ ignored: true }));
expect(banner("/p/requirements.txt")).toBeNull();
expect(banner("/p/other.txt")).toBeNull();
});
});
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff. Show more