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
107 changed files with 3842 additions and 268 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
+118 -14
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"];
@@ -1331,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,
+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 || {
+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:?}");
}
@@ -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.
+20 -2
View File
@@ -244,12 +244,30 @@ pub(crate) fn is_test_script(name: &str) -> bool {
}
/// The test runner a `package.json` script starts, when its output and test selection differ
/// from Jest / Vitest's: `playwright test`.
/// 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();
tokens.windows(2).any(|w| w[0] == "playwright" && w[1] == "test").then_some("playwright")
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",
+16
View File
@@ -76,6 +76,22 @@ fn playwright_scripts_and_configs() {
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")] {
+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());
+1 -1
View File
@@ -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, Playwright, 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
+2 -2
View File
@@ -74,7 +74,7 @@ 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:*`, and scripts that run `playwright 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>`).
@@ -86,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, Vitest and Playwright 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. **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
+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
@@ -62,7 +62,7 @@ RSpec 有自己的配置类型(**RSpec 测试**)和检测到的 `rspec` 配
| **重新运行**(在“运行”工具窗口中) | `⌘R` | `Ctrl+F5` |
| **重新运行失败的测试** | — | — |
**重新运行失败的测试**(在“运行”工具窗口工具栏和“查找操作”中)只运行上一次失败的测试,会按各个工具自己的过滤语法生成命令。支持 Cargo、Jest / Vitest、Playwright、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。
**重新运行失败的测试**(在“运行”工具窗口工具栏和“查找操作”中)只运行上一次失败的测试,会按各个工具自己的过滤语法生成命令。支持 Cargo、Jest / Vitest、Playwright、`node --test`、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。
## 在代码和测试之间跳转
+2 -2
View File
@@ -74,7 +74,7 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript
打开项目时,OpenIDEA 会自动检测运行配置:
- 每个 `package.json` 脚本一个配置(`npm run build`、`pnpm run dev` 等),覆盖根包、嵌套包和 workspace 成员。名为 `test`、`jest`、`vitest` 或 `test:*` 的脚本,以及运行 `playwright 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>`)。
@@ -86,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 和 Playwright Test 的输出会解析成测试树,支持 **重新运行失败的测试**。Playwright 运行时使用它的 `list` 报告器(配置里指定了其他报告器时除外);从行号栏运行单个测试时按行号选择(`file:line`),有多个 project 的运行会在文件下按 project 分组。**使用覆盖率运行** 支持调用 `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)。
## 调试
+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);
});
-45
View File
@@ -1,45 +0,0 @@
import { expect, test } from "./fixtures";
test("Show Usages distinguishes same-named files without losing the line or snippet", async ({ workbench: page }) => {
await page.setViewportSize({ width: 480, height: 620 });
await page.evaluate(async () => {
const usages = "/src/features/code-insight/usages.ts";
const { useUsagesPopup } = await import(/* @vite-ignore */ usages);
const symbol = "submitOrder";
useUsagesPopup.setState({
open: true,
anchor: { x: 30, y: 90 },
symbol,
groups: (
[
["/dev/acme-api/packages/billing/src/Routes.ts", "return submitOrder(invoice);"],
["/dev/acme-api/packages/checkout/src/Routes.ts", "return submitOrder(cart);"],
["/dev/acme-api/src/Worker.ts", "await submitOrder(job);"],
] as const
).map(([path, text]) => {
const col = text.indexOf(symbol);
return { path, usages: [{ path, line: 6, col, endCol: col + symbol.length, text }] };
}),
});
});
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
const rows = popup.getByRole("option");
const billing = rows.filter({ hasText: "invoice" });
const checkout = rows.filter({ hasText: "cart" });
await expect(rows).toHaveCount(3);
for (const [row, directory] of [
[billing, "billing"],
[checkout, "checkout"],
] as const) {
await expect(row.getByText("Routes.ts", { exact: true })).toBeVisible();
const caption = row.getByText(directory, { exact: true });
await expect(caption).toBeVisible();
expect(await caption.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(row.getByText("7", { exact: true })).toBeVisible();
await expect(row.locator("mark")).toHaveText("submitOrder");
}
await expect(checkout.getByTitle("/dev/acme-api/packages/checkout/src/Routes.ts", { exact: true })).toBeVisible();
await expect(rows.filter({ hasText: "Worker.ts" }).getByText("src", { exact: true })).toHaveCount(0);
});
+1
View File
@@ -10,6 +10,7 @@ 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` |
+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);
});
+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
+10
View File
@@ -79,6 +79,16 @@ const CASES: Record<string, Case | Case[]> = {
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",
+3
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
+71 -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.
@@ -2829,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`. */
@@ -7789,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`. */
@@ -10937,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. */
@@ -11817,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" } |
-1
View File
@@ -40,7 +40,6 @@ import { rootOfPath } from "@/platform/projectRoots";
import { isVirtualUri } from "@/platform/virtualDocs";
import { cornerInset } from "@/editor/core/cm/cornerInset";
export { iconAreaSource, mapLineStart, type IconAreaSource } from "@/editor/core/cm/iconArea";
export { disambiguateTitles } from "@/editor/core/model/tabTitles";
export {
invalidateNavigationProviders,
navigationEpoch,
-6
View File
@@ -26,12 +26,6 @@ describe("disambiguateTitles", () => {
expect(m.get("/r/a/d/f.ts")).toBe("d");
});
it("distinguishes directory names that occur at different depths", () => {
const paths = ["/r/prod/shared/f.ts", "/r/shared/prod/f.ts", "/r/test/shared/f.ts"];
const labels = disambiguateTitles(paths);
expect(paths.map((path) => labels.get(path))).toEqual(["prod/shared", "shared/prod", "test"]);
});
it("ignores duplicates of the same path", () => {
expect(disambiguateTitles(["/p/a/x.ts", "/p/a/x.ts"]).size).toBe(0);
});
+20 -19
View File
@@ -1,6 +1,6 @@
/**
* Directory hints for files that share a name: a distinguishing parent
* directory is shown after the name (`lib.rs — ide-lsp`
* IDEA-style editor tab titles for files that share a name: the nearest parent
* directory that tells them apart is shown after the name (`lib.rs — ide-lsp`
* for `crates/ide-lsp/src/lib.rs` next to `crates/ide-vcs/src/lib.rs`).
*/
@@ -27,24 +27,25 @@ export function disambiguateTitles(paths: readonly string[], titleOf = baseName)
for (const group of groups.values()) {
if (group.length < 2) continue;
const dirs = group.map(parents);
const nameCounts = new Map<string, number>();
const suffixCounts = new Map<string, number>();
const suffixes = dirs.map((names) => {
for (const name of new Set(names)) {
nameCounts.set(name, (nameCounts.get(name) ?? 0) + 1);
}
let suffix = "";
return names.map((name) => {
suffix = suffix ? `${name}/${suffix}` : name;
suffixCounts.set(suffix, (suffixCounts.get(suffix) ?? 0) + 1);
return suffix;
});
});
group.forEach((path, i) => {
const name = dirs[i]!.find((segment) => nameCounts.get(segment) === 1);
const paths = suffixes[i]!;
const hint = name ?? paths.find((suffix, depth) => depth > 0 && suffixCounts.get(suffix) === 1);
out.set(path, hint ?? paths.at(-1) ?? "/");
const own = dirs[i]!;
let hint: string | null = null;
for (let depth = 0; depth < own.length; depth++) {
const seg = own[depth]!;
if (dirs.every((other, j) => j === i || other[depth] !== seg)) {
hint = seg;
break;
}
}
if (hint === null) {
// No single directory is unique: the shortest distinguishing parent path.
const suffix = (d: string[], k: number) => d.slice(0, k).reverse().join("/");
for (let k = 2; k <= own.length && hint === null; k++) {
const mine = suffix(own, k);
if (dirs.every((other, j) => j === i || suffix(other, k) !== mine)) hint = mine;
}
}
out.set(path, hint ?? (own.length ? own.slice().reverse().join("/") : "/"));
});
}
return out;
+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 {
@@ -94,16 +94,10 @@
flex: none;
color: var(--fg-muted);
}
.fileName,
.directory {
min-width: 0;
.fileName {
overflow: hidden;
text-overflow: ellipsis;
}
.directory {
flex: 0 2 auto;
color: var(--fg-subtle);
}
.line {
overflow: hidden;
text-align: right;
+5 -12
View File
@@ -8,7 +8,7 @@ import { create } from "zustand";
import clsx from "clsx";
import { EditorState, StateEffect, StateField } from "@codemirror/state";
import { Decoration, EditorView } from "@codemirror/view";
import { codePreviewExtensions, disambiguateTitles } from "@/editor/api";
import { codePreviewExtensions } from "@/editor/api";
import { basename } from "@/platform/project";
import { shortcutLabel } from "@/platform/keymap";
import { Icon, IconButton, List, Popup, Select, Spinner, fileIconName, listNavigate } from "@/ui";
@@ -86,14 +86,6 @@ function UsagesPopupInner() {
const preview = useUsagesPopupPreview((s) => s.preview);
const rowHeight = useRowHeight(ROW);
const all = useMemo<Usage[]>(() => groups.flatMap((g) => g.usages), [groups]);
const directories = useMemo(
() =>
disambiguateTitles(
groups.map((g) => g.path),
basename,
),
[groups],
);
const [filter, setFilter] = useState("");
const accessOptions = useUsageAccessOptions();
const items = useMemo(
@@ -241,10 +233,11 @@ function UsagesPopupInner() {
}
renderItem={(u) => (
<div className={styles.row} data-testid="usage-row" data-path={u.path} data-line={u.line}>
<span className={styles.file} title={u.path}>
<span className={styles.file}>
<Icon name={fileIconName(basename(u.path), u.path)} size={16} className={styles.icon} />
<span className={styles.fileName}>{basename(u.path)}</span>
{directories.has(u.path) && <span className={styles.directory}>{directories.get(u.path)}</span>}
<span className={styles.fileName} title={u.path}>
{basename(u.path)}
</span>
</span>
<span className={styles.line}>{u.line + 1}</span>
<UsagePreview usage={u} />
+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) => {
+2 -2
View File
@@ -84,7 +84,7 @@ 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 (
@@ -606,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}>
@@ -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);
+5 -5
View File
@@ -10,7 +10,7 @@
import type { BranchInfo } from "@/bindings";
import { buildFileTree, type FileTreeNode } from "@/features/vcs/fileTree";
import type { EffectiveKind } from "@/features/vcs/model";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import type {
CodeReviewCIJob,
CodeReviewCIJobState,
@@ -269,12 +269,12 @@ export function resolveConflicts(input: {
const { details: pr, remotes } = input;
if (input.mergeInProgress) return { error: "Merge is already in progress" };
if (!pr) return { error: "Details have not finished loading" };
if (!pr.headRepository) return { error: tx`${tx("Source")} repository not found` };
if (!pr.baseRepository) return { error: tx`${tx("Target")} repository not found` };
if (!pr.headRepository) return { error: tx`${txPart("Source")} repository not found` };
if (!pr.baseRepository) return { error: tx`${txPart("Target")} repository not found` };
const head = remoteOf(remotes, pr.headRepository.nameWithOwner);
if (!head) return { error: tx`${tx("Source")} remote not found: ${pr.headRepository.url}` };
if (!head) return { error: tx`${txPart("Source")} remote not found: ${pr.headRepository.url}` };
const base = remoteOf(remotes, pr.baseRepository.nameWithOwner);
if (!base) return { error: tx`${tx("Target")} remote not found: ${pr.baseRepository.url}` };
if (!base) return { error: tx`${txPart("Target")} remote not found: ${pr.baseRepository.url}` };
if (input.alreadyResolvedLocally) return { error: "Already resolved locally, push your changes to resolve" };
return { headRemote: head.remote, baseRemote: base.remote, headRefName: pr.headRefName, baseRefName: pr.baseRefName };
}
+2 -2
View File
@@ -9,7 +9,7 @@
* As in IntelliJ, closing a chip's popup without choosing resets the chip.
*/
import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { tx, useTx } from "@/platform/i18n";
import { tx, txPart, useTx } from "@/platform/i18n";
import { Icon, IconButton, Menu, SearchField, showContextMenu, type MenuItem } from "@/ui";
import type { GHLabel, GHUser } from "../api/types";
import { filterCount, type PrSearchValue } from "../data/model";
@@ -151,7 +151,7 @@ function FilterChip({
<IconButton
type="button"
className={styles.chipReset}
aria-label={t`Reset ${name}`}
aria-label={t`Reset ${txPart(title)}`}
onClick={() => onChange(undefined)}
onKeyDown={onKeyDown}
tabIndex={-1}
@@ -6,7 +6,7 @@
* The viewer's toggle shows at once and is undone when the request fails.
*/
import { useState } from "react";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import { IconButton, Popup, tooltipAttrs } from "@/ui";
import type { GHReaction, GHReactionContent } from "../../api/types";
import { useGhRepository } from "../../data/repository";
@@ -101,7 +101,7 @@ export function Reactions({ state, canReact }: ReactionsProps) {
className={styles.pill}
data-own={g.isReactedByCurrentUser || undefined}
disabled={!canReact}
{...tooltipAttrs(tx`${users} reacted with '${name}' emoji`)}
{...tooltipAttrs(tx`${users} reacted with '${txPart(name)}' emoji`)}
onClick={() => toggle(g.content)}
>
<span className={styles.emoji}>{r.emoji}</span>
+1
View File
@@ -104,6 +104,7 @@ const POINT_TITLES: Record<string, string> = {
languages: "Languages",
providers: "Editor Providers",
javaAgents: "Java Agents",
skills: "Agent Skills",
locales: "Translations",
};
+2 -2
View File
@@ -6,7 +6,7 @@
import { useState } from "react";
import { create } from "zustand";
import type { CapabilityInfo, Consent } from "@/bindings";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import { Badge, Checkbox, Dialog, T } from "@/ui";
import { setConsentPrompt, type ConsentRequest } from "./store";
import styles from "./PluginsPage.module.css";
@@ -37,7 +37,7 @@ export function capabilityDescription(cap: CapabilityInfo): string {
// The host appends the agent's contributed JVM flags (`…; JVM options: -XX:…`).
const flagsAt = cap.id === "java.agent" ? cap.description.indexOf(JVM_OPTIONS) : -1;
if (flagsAt >= 0) {
const description = tx(cap.description.slice(0, flagsAt));
const description = txPart(cap.description.slice(0, flagsAt));
const flags = cap.description.slice(flagsAt + JVM_OPTIONS.length);
return tx`${description}; JVM options: ${flags}`;
}
+4 -4
View File
@@ -51,7 +51,7 @@ import {
setViewOption,
useProjectTree,
} from "./store";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
const FOCUS = "projectViewFocus";
const OPEN = "projectOpen";
@@ -187,7 +187,7 @@ export function registerProjectActions(): () => void {
const toggles: Action[] = OPTION_LABELS.map(([key, label]) => ({
id: `project.option.${key}`,
title: tx`Project View: ${label}`,
title: tx`Project View: ${txPart(label)}`,
category: "View",
// IDEA's former name of Always Select Opened File.
keywords: ["project", "tree", "toggle", ...(key === "autoscrollFromSource" ? ["autoscroll from source"] : [])],
@@ -197,7 +197,7 @@ export function registerProjectActions(): () => void {
const modes: Action[] = VIEW_MODES.map(([mode, label]) => ({
id: `project.viewMode.${mode}`,
title: tx`Project View: Show ${label}`,
title: tx`Project View: Show ${txPart(label)}`,
category: "View",
when: OPEN,
keywords: ["project", "pane", "scope", "view as"],
@@ -209,7 +209,7 @@ export function registerProjectActions(): () => void {
const sorts: Action[] = SORT_LABELS.map(([sortBy, label]) => ({
id: `project.sortBy.${sortBy}`,
title: tx`Project View: ${label}`,
title: tx`Project View: ${txPart(label)}`,
category: "View",
keywords: ["project", "tree", "sort", "order"],
toggled: () => useProjectTree.getState().options.sortBy === sortBy,
+4 -2
View File
@@ -37,7 +37,7 @@ import {
import { canDownload } from "./download";
import { isSameOrInside } from "./paths";
import { useProjectTree } from "./store";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
/** Keys handled by the project view itself (the default keymap has no entries for them). */
export const LOCAL_KEYS: Record<string, string> = {
@@ -467,7 +467,9 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
{
id: "unmark",
label:
current === "excluded" ? "Cancel Exclusion" : tx`Unmark as ${roles.find(([r]) => r === current)![1]}`,
current === "excluded"
? "Cancel Exclusion"
: tx`Unmark as ${txPart(roles.find(([r]) => r === current)![1])}`,
run: () => void markDirectory(single.path, null),
},
]
+2 -2
View File
@@ -2,7 +2,7 @@
import { openPopup } from "@/editor/lsp/popupStore";
import { canRevealInFileManager, fileManagerName, revealInFileManager } from "@/platform/fileManager";
import { notifications } from "@/workbench/contributions";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import { nameOf, parentOf } from "./paths";
import { notifyRevealUnavailable } from "./operations";
@@ -24,7 +24,7 @@ async function reveal(path: string) {
try {
await revealInFileManager(path);
} catch (e) {
const fileManager = tx(fileManagerName());
const fileManager = txPart(fileManagerName());
notifications().notify({
level: "error",
title: tx`Cannot reveal in ${fileManager}`,
+3 -3
View File
@@ -45,7 +45,7 @@ import {
startEditing,
useProjectTree,
} from "./store";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import { hostOs, isRemoteWindow } from "@/platform/remote";
import { usePlatform } from "@/platform/platformInfo";
import { pathToCopy, type PathKind } from "@/platform/copyPath";
@@ -890,7 +890,7 @@ export function revealablePath(path: string): string {
/** For a reveal invoked where the menus hide it (shortcut, Search Everywhere) in an SSH or dev-container window. */
export function notifyRevealUnavailable() {
const fileManager = tx(fileManagerName());
const fileManager = txPart(fileManagerName());
notifications().notify({ level: "warning", title: tx`Remote project files cannot be shown in ${fileManager}` });
}
@@ -899,7 +899,7 @@ export async function revealInFinder(nodes: ProjectNode[] = selectedNodes()) {
try {
await revealInFileManager(nodes.map((n) => n.path));
} catch (e) {
const fileManager = tx(fileManagerName());
const fileManager = txPart(fileManagerName());
fail(tx`Cannot reveal in ${fileManager}`, e);
}
}
+2 -2
View File
@@ -11,7 +11,7 @@ import { withDocument } from "@/editor/lsp/files";
import { IpcError } from "@/platform/ipc";
import { libraryEntryPaths } from "@/platform/virtualDocs";
import { isIgnoredName } from "@/platform/ignoredNames";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import { notifications } from "@/workbench/contributions";
import { ipcPath } from "@/platform/paths";
import {
@@ -806,7 +806,7 @@ export function explainHiddenPath(path: string, shown: string) {
notifications().notify({
level: "info",
key: "project.hiddenPath",
title: tx`${nameOf(path)} is hidden because ${title} is off`,
title: tx`${nameOf(path)} is hidden because ${txPart(title)} is off`,
actions: [
{
label: tx(title),
+2 -2
View File
@@ -12,7 +12,7 @@ import { isTauri, type BeforeLaunchTask, type BuildPolicy, type RunConfig } from
import { useWorkflowSettings } from "@/platform/workflowSettings";
import { relativePath, useProject } from "@/platform/project";
import { isRemoteWindow } from "@/platform/remote";
import { useTx, useTxTemplate } from "@/platform/i18n";
import { txPart, useTx, useTxTemplate } from "@/platform/i18n";
import {
Button,
Checkbox,
@@ -832,7 +832,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
icon="close"
size="small"
iconSize={10}
title={tx`Remove '${OPTION_LABELS[id]}'`}
title={tx`Remove '${txPart(OPTION_LABELS[id])}'`}
onClick={() => update(optionPatch(id, false))}
/>
</span>
+2 -2
View File
@@ -5,7 +5,7 @@
* how many came in and why the others were left out.
*/
import type { ReactNode } from "react";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import { call, commands, type RunConfig, type RunImport, type RunImportSource, type SkipReason } from "@/platform/ipc";
import { notifications } from "@/workbench/contributions";
import { loadConfigs, useRun } from "./store";
@@ -89,7 +89,7 @@ export function importSummary(result: RunImport): {
? tx`Imported ${n} run configuration from ${file}`
: tx`Imported ${n} run configurations from ${file}`;
const notes = [
...result.skipped.map((s) => tx`Skipped '${s.name || tx("Unnamed")}': ${skipReasonText(s.reason)}`),
...result.skipped.map((s) => tx`Skipped '${s.name || txPart("Unnamed")}': ${skipReasonText(s.reason)}`),
...result.imported
.filter((c) => c.ignored.length)
.map((c) => tx`Left out of '${c.config.name}': ${c.ignored.join(", ")}`),
+2 -2
View File
@@ -8,7 +8,7 @@ import { create } from "zustand";
import type { RunConfig } from "@/platform/ipc";
import { Checkbox, Dialog } from "@/ui";
import { kindLabel } from "./configs";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import styles from "./RunServices.module.css";
interface Entry {
@@ -78,7 +78,7 @@ function ImportDialog(props: {
return (
<Dialog
open
title={tx`Add Service (${kindLabel(props.kind)})`}
title={tx`Add Service (${txPart(kindLabel(props.kind))})`}
onClose={() => props.onDone(null)}
width={420}
buttons={[
+9 -6
View File
@@ -48,6 +48,7 @@ import {
} from "./testing";
import { PluginTestOutput } from "./testing/plugin";
import { GoTestOutput } from "./testing/go";
import { RecordsOutput } from "./testing/records";
import { DotnetReports } from "./testing/dotnet";
import { moveToReportedClasses } from "./testing/jvm";
import { RubyTestOutput } from "./testing/ruby";
@@ -67,7 +68,7 @@ import { startedPort } from "@/platform/serverPort";
import { tomcatBrowserUrl } from "./tomcat";
import { gradleBootLaunch, gradleDelegation, gradleTestLaunch } from "./gradleRun";
import { openUrl } from "./navigate";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import { UNITY_CONFIG_KIND } from "./unity";
/** The permanent "Current File" pseudo-configuration of the chooser (runs the active file's context). */
@@ -713,8 +714,8 @@ function newRuntime(config: RunConfig): SessionRuntime {
if (tests && parser) tests.apply(parser.feed(line));
};
const framework = tests && parser ? frameworkFor(config) : null;
// PHPUnit `--teamcity` and Gradle's test init script report through service messages, Minitest through
// the IDE's own reporter (RSpec has none: its progress dots must show as they come).
// PHPUnit `--teamcity` and Gradle's test init script report through service messages, Minitest and
// node:test through the IDE's own reporters (RSpec has none: its progress dots must show as they come).
const stdout =
framework === "go"
? new GoTestOutput(feed)
@@ -722,7 +723,9 @@ function newRuntime(config: RunConfig): SessionRuntime {
? new TeamcityOutput(feed)
: framework === "ruby" && config.kind !== "rspec"
? new RubyTestOutput(feed)
: null;
: framework === "node-test"
? new RecordsOutput(feed)
: null;
const runtime: SessionRuntime = {
stdout,
tests,
@@ -1620,7 +1623,7 @@ export async function sendStdin(sessionId: string, text: string): Promise<void>
} catch (e) {
enqueue(sessionId, {
kind: "system",
text: tx`Cannot write to stdin: ${e instanceof Error ? tx(e.message) : String(e)}\n`,
text: tx`Cannot write to stdin: ${e instanceof Error ? txPart(e.message) : String(e)}\n`,
});
}
}
@@ -1632,7 +1635,7 @@ export function writeTerminal(sessionId: string, data: string) {
void call(commands.runStdin(session.runId, data)).catch((e) => {
enqueue(sessionId, {
kind: "system",
text: tx`Cannot write to stdin: ${e instanceof Error ? tx(e.message) : String(e)}\n`,
text: tx`Cannot write to stdin: ${e instanceof Error ? txPart(e.message) : String(e)}\n`,
});
});
}
+4
View File
@@ -18,6 +18,7 @@ import { scanJvmTargets, simpleClassName } from "./jvmTargets";
import { escapeRegExp } from "./testing/rerun";
import { pestFilter, phpunitArgs, phpunitFilter } from "./testing/phpunit";
import { frameworkFor } from "./testing";
import { withNodeTestNamePattern } from "./testing/nodeTest";
export type TargetKind = "main" | "test" | "suite" | "generate";
@@ -473,6 +474,9 @@ export function targetConfig(
});
// Playwright selects by declaration line (`file:line`), which also covers a describe block.
if (frameworkFor(file) === "playwright") return named(withLast(file.args, (f) => `${f}:${target.line + 1}`));
// node:test selects by full name, through NODE_OPTIONS (see `nodeTest.ts`).
if (frameworkFor(file) === "node-test")
return { ...named(file.args), env: withNodeTestNamePattern(file.env, jsNamePattern(target)) };
switch (file.kind) {
case "dotnet-test": {
const methods =
+10 -1
View File
@@ -4,6 +4,8 @@ import { cargoParser } from "./cargo";
import { goParser } from "./go";
import { jsParser } from "./js";
import { jvmParser } from "./jvm";
import { withNodeTestReporter } from "./nodeTest";
import { recordsParser } from "./records";
import { phpunitParser, withTeamcity } from "./phpunit";
import { playwrightParser } from "./playwright";
import { pytestParser } from "./pytest";
@@ -24,6 +26,7 @@ export {
phpunitParser,
playwrightParser,
pytestParser,
recordsParser,
rubyParser,
unittestParser,
zigParser,
@@ -41,6 +44,7 @@ export type Framework =
| "cargo"
| "js"
| "playwright"
| "node-test"
| "pytest"
| "unittest"
| "phpunit"
@@ -51,12 +55,14 @@ export type Framework =
| "zig"
| "auto";
type FrameworkConfig = Pick<RunConfig, "kind" | "command" | "args"> & Partial<Pick<RunConfig, "testRunner">>;
type FrameworkConfig = Pick<RunConfig, "kind" | "command" | "args"> & Partial<Pick<RunConfig, "testRunner" | "env">>;
export function frameworkFor(config: FrameworkConfig): Framework {
const cmd = [config.command, ...config.args].join(" ");
// A `package.json` script names its runner only in package.json: detection records it.
if (config.testRunner === "playwright" || /\bplaywright\s+test\b/.test(cmd)) return "playwright";
if (config.testRunner === "node-test" || /(^|[\s/\\])(node|tsx)(\.exe)?(\s+-\S*)*\s+--test(\s|$)/.test(cmd))
return "node-test";
switch (config.kind) {
case "dotnet-test":
return "dotnet";
@@ -120,6 +126,7 @@ function rubyVerbose<T extends Pick<RunConfig, "kind" | "command" | "args">>(con
* IDEA's runner) unless the user chose a verbosity already.
*/
export function withTestReporting<T extends FrameworkConfig>(config: T): T {
if (frameworkFor(config) === "node-test") return { ...config, env: withNodeTestReporter(config.env ?? {}) };
if (frameworkFor(config) === "playwright") {
// The list reporter prints a line per test; a project's own (`html`, `dot` on CI) may print none.
const chosen = config.args.some((a) => a === "--reporter" || a.startsWith("--reporter="));
@@ -162,6 +169,8 @@ export function createTestParser(config: FrameworkConfig): TestOutputParser {
return jsParser();
case "playwright":
return playwrightParser();
case "node-test":
return recordsParser();
case "pytest":
return pytestParser();
case "unittest":
+136
View File
@@ -0,0 +1,136 @@
import { describe, expect, it } from "vitest";
import type { RunConfig } from "@/platform/ipc";
import { detectRunTargets, targetConfig } from "../targets";
import { createTestParser, frameworkFor, nodeOutput, parseAll, TestResults, withTestReporting } from "./index";
import { withNodeTestNamePattern } from "./nodeTest";
import { RecordsOutput } from "./records";
import { failedTestPaths, rerunFailedConfigs, testsConfigs } from "./rerun";
const cfg = (over: Partial<RunConfig> & { id: string; kind: string }): RunConfig => ({
name: over.id,
command: over.kind,
args: [],
cwd: null,
env: {},
detected: true,
isTest: true,
debugAdapter: "js-debug",
...over,
});
/** `npm run test` whose script is `node --test` (detection records the runner). */
const script = cfg({ id: "npm:test", kind: "npm", command: "npm", args: ["run", "test"], testRunner: "node-test" });
// `node --test` (Node 22.23) with the IDE's reporter next to `spec`, as printed.
const OUTPUT = String.raw`hello from test
▶ cart
✔ adds items (0.4259ms)
@@openidea:test@@{"path":["test/cart.test.mjs","cart","adds items"],"status":"passed","ms":0.4259,"line":5,"col":3}
▶ totals
✔ sums (0.1656ms)
@@openidea:test@@{"path":["test/cart.test.mjs","cart","totals","sums"],"status":"passed","ms":0.1656,"line":7,"col":5}
✔ totals (0.6471ms)
@@openidea:test@@{"path":["test/cart.test.mjs","cart","totals"],"status":"passed","ms":0.6471,"line":6,"col":3}
✖ fails (0.5311ms)
@@openidea:test@@{"path":["test/cart.test.mjs","cart","fails"],"status":"failed","ms":0.5311,"line":9,"col":3,"error":"AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:\n\n1 !== 2\n\n at TestContext.<anonymous> (file:///work/shop/test/cart.test.mjs:9:30)"}
﹣ skipped one (0.057ms) # SKIP
@@openidea:test@@{"path":["test/cart.test.mjs","cart","skipped one"],"status":"skipped","ms":0.057,"line":10,"col":6}
✖ cart (2.3737ms)
@@openidea:test@@{"path":["test/cart.test.mjs","cart"],"status":"failed","ms":2.3737,"line":4,"col":1}
✔ top level (0.3078ms)
@@openidea:test@@{"path":["test/cart.test.mjs","top level"],"status":"passed","ms":0.3078,"line":14,"col":1}
✖ test/broken.test.mjs (52.1ms)
@@openidea:test@@{"path":["test/broken.test.mjs"],"status":"failed","ms":52.1,"error":"'test failed'"}
ℹ tests 6
ℹ pass 3
ℹ fail 2`;
function results(text: string) {
const r = new TestResults();
r.apply(parseAll(createTestParser(script), text));
return r;
}
const key = (...path: string[]) => path.join("\u0000");
describe("node:test reporter records", () => {
it("build the tree from file and describe chain, with durations and locations", () => {
const r = results(OUTPUT);
expect(r.roots.map((n) => n.name)).toEqual(["test/cart.test.mjs", "test/broken.test.mjs"]);
expect(r.counts()).toMatchObject({ passed: 3, failed: 2, skipped: 1 });
const sums = r.get(key("test/cart.test.mjs", "cart", "totals", "sums"))!;
expect(sums.own).toBe("passed");
expect(sums.durationMs).toBe(0.1656);
expect(sums.location).toEqual({ path: "test/cart.test.mjs", line: 7, col: 5, resolve: "path" });
expect(r.get(key("test/cart.test.mjs", "cart", "skipped one"))?.own).toBe("skipped");
});
it("keep a failure's error with the test, and a file that failed to load", () => {
const r = results(OUTPUT);
const fails = r.get(key("test/cart.test.mjs", "cart", "fails"))!;
expect(nodeOutput(fails).join("\n")).toContain("1 !== 2");
expect(r.get("test/broken.test.mjs")?.own).toBe("failed");
expect(failedTestPaths(r)).toEqual([["test/cart.test.mjs", "cart", "fails"], ["test/broken.test.mjs"]]);
});
it("are hidden from the console", () => {
const fed: string[] = [];
const console = new RecordsOutput((line) => fed.push(line)).feed(OUTPUT + "\n");
expect(console).not.toContain("@@openidea");
expect(console).toContain(" ✔ adds items (0.4259ms)\n");
expect(fed.filter((l) => l.startsWith("@@openidea"))).toHaveLength(8);
});
});
describe("node:test configurations", () => {
it("are recognised by the recorded runner or Node's own --test", () => {
expect(frameworkFor(script)).toBe("node-test");
expect(frameworkFor(cfg({ id: "n", kind: "node", command: "node", args: ["--test"] }))).toBe("node-test");
const flags = ["--experimental-strip-types", "--test", "src/"];
expect(frameworkFor(cfg({ id: "n", kind: "node", command: "/usr/bin/node", args: flags }))).toBe("node-test");
expect(frameworkFor(cfg({ id: "n", kind: "node", command: "node", args: ["server.js", "--test"] }))).not.toBe(
"node-test",
);
});
it("report through the IDE's reporter next to spec, once, keeping the user's NODE_OPTIONS", () => {
const launched = withTestReporting({ ...script, env: { NODE_OPTIONS: "--max-old-space-size=4096" } });
const options = launched.env.NODE_OPTIONS!.split(" ");
expect(options.slice(0, 3)).toEqual([
"--max-old-space-size=4096",
"--test-reporter=spec",
"--test-reporter-destination=stdout",
]);
expect(options[3]).toMatch(/^--test-reporter=data:text\/javascript;base64,/);
expect(options[4]).toBe("--test-reporter-destination=stdout");
expect(withTestReporting(launched).env).toEqual(launched.env);
const own = { ...script, env: { NODE_OPTIONS: "--test-reporter=dot" } };
expect(withTestReporting(own).env).toEqual(own.env);
});
it("select tests by full name in NODE_OPTIONS, quoted for Node and replacing an earlier filter", () => {
const env = withNodeTestNamePattern({ NODE_OPTIONS: '--a --test-name-pattern="^x y$" --b' }, '^say "hi" \\d$');
expect(env.NODE_OPTIONS).toBe('--a --b --test-name-pattern="^say \\"hi\\" \\\\d$"');
});
it("rerun failed tests by file and name", async () => {
const [rerun] = await rerunFailedConfigs(script, failedTestPaths(results(OUTPUT)));
expect(rerun!.args).toEqual(["run", "test", "--", "test/cart.test.mjs", "test/broken.test.mjs"]);
expect(rerun!.env.NODE_OPTIONS).toBe('--test-name-pattern="^(?:cart fails)$"');
const direct = cfg({ id: "node", kind: "node", command: "node", args: ["--test"] });
const [selected] = await testsConfigs(direct, [["test/a.test.mjs", "a.b", "c"]], "c");
expect(selected!.args).toEqual(["--test", "test/a.test.mjs"]);
expect(selected!.env.NODE_OPTIONS).toBe('--test-name-pattern="^(?:a\\\\.b c)$"');
});
it("run a gutter target by its file and full name", () => {
const src = "import { describe, it } from 'node:test';\ndescribe('cart', () => {\n it('adds', () => {});\n});";
const [suite, test] = detectRunTargets(src, "test/cart.test.mjs");
const one = targetConfig(test!, "test/cart.test.mjs", [script], src)!;
expect(one.args).toEqual(["run", "test", "--", "test/cart.test.mjs"]);
expect(one.env.NODE_OPTIONS).toBe('--test-name-pattern="^cart adds$"');
expect(targetConfig(suite!, "test/cart.test.mjs", [script], src)!.env.NODE_OPTIONS).toBe(
'--test-name-pattern="^cart"',
);
});
});
+31
View File
@@ -0,0 +1,31 @@
/**
* `node --test`: the IDE's reporter (`nodeTestReporter.js`) runs next to `spec` and prints a
* record per finished test (`records.ts`). It reaches Node through `NODE_OPTIONS`, as does the
* name filter: a `package.json` script's own arguments can't take them (`node --test` reads
* options only before its file patterns).
*/
import REPORTER_SOURCE from "./nodeTestReporter.js?raw";
const REPORTER = `--test-reporter=data:text/javascript;base64,${btoa(REPORTER_SOURCE)}`;
const PATTERN_RE = /(^|\s)--test-name-pattern=(?:"(?:[^"\\]|\\.)*"|\S+)/g;
/** `NODE_OPTIONS` with the IDE's reporter added (once), `spec` keeping the console readable. */
export function withNodeTestReporter(env: Record<string, string>): Record<string, string> {
const options = env.NODE_OPTIONS ?? "";
if (options.includes(REPORTER) || /(^|\s)--test-reporter[=\s]/.test(options)) return env;
const reporters = [
"--test-reporter=spec",
"--test-reporter-destination=stdout",
REPORTER,
"--test-reporter-destination=stdout",
];
return { ...env, NODE_OPTIONS: [options, ...reporters].filter(Boolean).join(" ") };
}
/** `NODE_OPTIONS` selecting the tests whose full name (describe chain and name, space separated) matches `pattern`. */
export function withNodeTestNamePattern(env: Record<string, string>, pattern: string): Record<string, string> {
const options = (env.NODE_OPTIONS ?? "").replace(PATTERN_RE, "").trim();
// NODE_OPTIONS splits at spaces outside double quotes, where a backslash escapes the next character.
const quoted = `"${pattern.replace(/[\\"]/g, "\\$&")}"`;
return { ...env, NODE_OPTIONS: [options, `--test-name-pattern=${quoted}`].filter(Boolean).join(" ") };
}
@@ -0,0 +1,48 @@
// The IDE's node:test reporter (`--test-reporter`, passed as a data: URL through NODE_OPTIONS
// next to `spec`): one record per finished test, which the IDE turns into the test tree and
// hides from the console (`records.ts`). Runs in the user's Node (20+), so plain ESM without dependencies.
import { relative, resolve } from "node:path";
const MARK = "@@openidea:test@@";
const fileOf = (path) => (path ? relative(process.cwd(), path).split("\\").join("/") : "");
function message(error) {
// node:test wraps what the test threw in an ERR_TEST_FAILURE whose `cause` it is.
const cause = error && error.code === "ERR_TEST_FAILURE" && error.cause !== undefined ? error.cause : error;
if (cause instanceof Error) return cause.stack || `${cause.name}: ${cause.message}`;
return String(cause);
}
export default async function* reporter(source) {
/** Per file, the names of the tests being reported, by nesting level. */
const open = new Map();
for await (const { type, data } of source) {
if (type !== "test:start" && type !== "test:pass" && type !== "test:fail") continue;
const file = fileOf(data.file);
// A file without reported tests (none matched, or it failed to load) reports as a test named after it.
const self = data.nesting === 0 && data.file && resolve(data.name) === resolve(data.file);
const names = open.get(file) ?? [];
open.set(file, names);
if (type === "test:start") {
names.length = data.nesting;
names.push(data.name);
continue;
}
const path = [...(file ? [file] : []), ...(self ? [] : [...names.slice(0, data.nesting), data.name])];
const details = data.details ?? {};
const record = {
path,
status:
type === "test:fail" ? "failed" : data.skip !== undefined || data.todo !== undefined ? "skipped" : "passed",
ms: details.duration_ms,
line: self ? undefined : data.line,
col: self ? undefined : data.column,
error:
type === "test:fail" && details.error && details.error.failureType !== "subtestsFailed"
? message(details.error)
: undefined,
};
yield `${MARK}${JSON.stringify(record)}\n`;
}
}
+50
View File
@@ -0,0 +1,50 @@
/**
* Records the IDE's JavaScript test reporters print, one line per finished test
* (`@@openidea:test@@{…}`, see `nodeTestReporter.js`): the test tree reads them, the console hides them.
*/
import { TestStdout, type TestEvent, type TestOutputParser } from "./types";
export const RECORD_MARK = "@@openidea:test@@";
interface TestRecord {
/** The file (relative to the working directory), then the describe chain and the test's name. */
path: string[];
status: "passed" | "failed" | "skipped";
ms?: number;
/** 1-based declaration line and column. */
line?: number;
col?: number;
error?: string;
}
export function recordsParser(): TestOutputParser {
return {
feed(line) {
const at = line.indexOf(RECORD_MARK);
if (at < 0) return [];
let r: TestRecord;
try {
r = JSON.parse(line.slice(at + RECORD_MARK.length)) as TestRecord;
} catch {
return [];
}
if (!Array.isArray(r.path) || !r.path.length) return [];
const events: TestEvent[] = [{ type: "result", path: r.path, status: r.status, durationMs: r.ms }];
if (r.line !== undefined && r.path.length > 1)
events.push({
type: "location",
path: r.path,
location: { path: r.path[0]!, line: r.line, col: r.col, resolve: "path" },
});
for (const text of r.error?.split("\n") ?? []) events.push({ type: "output", path: r.path, line: text });
return events;
},
};
}
/** The console side: the records are the tree's, the runner's own reporter's lines the console's. */
export class RecordsOutput extends TestStdout {
constructor(feedLine: (line: string) => void) {
super(feedLine, (line) => (line.includes(RECORD_MARK) ? "" : line + "\n"));
}
}
+11
View File
@@ -13,6 +13,7 @@ import { withMavenTests } from "../mavenTests";
import { frameworkFor } from "./index";
import { dotnetFilter } from "./dotnet";
import { playwrightProject, playwrightTitles } from "./playwright";
import { withNodeTestNamePattern } from "./nodeTest";
import { nodeStatus, type TestNode, type TestResults } from "./results";
/** Paths of failed tests: failed leaves, plus failed suites without any failed children reported. */
@@ -262,6 +263,16 @@ function builtinTestsConfig(config: RunConfig, paths: string[][], name: string):
case "playwright":
args = playwrightArgs(config, paths);
break;
case "node-test": {
// The files narrow a script's run when it gives `node --test` no patterns of its own; the names always do.
const files = unique(paths.map((p) => p[0]!).filter(Boolean));
const names = unique(paths.filter((p) => p.length > 1).map((p) => p.slice(1).join(" ")));
if (!files.length) return null;
const env = names.length
? withNodeTestNamePattern(config.env, `^(?:${names.map(escapeRegExp).join("|")})$`)
: { ...config.env };
return { ...config, args: appendScriptArgs(config.command, config.args, files), name, detected: true, env };
}
case "pytest":
args = pytestArgs(config.args, paths);
break;
+2 -2
View File
@@ -12,7 +12,7 @@ import clsx from "clsx";
import { openEditorPaths, useEditorRegistry } from "@/editor/api";
import { executeAction } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { t, useTxTemplate, tx } from "@/platform/i18n";
import { t, useTxTemplate, tx, txPart } from "@/platform/i18n";
import { formatBinding, hostBinding, shortcutLabel } from "@/platform/keymap";
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
@@ -1032,7 +1032,7 @@ function EmptyResults({
) : used.length ? (
<div className={styles.emptyOptions}>
{used.length === 1 ? (
<div>{tx`Search option used: ${tx(used[0]!.label)}`}</div>
<div>{tx`Search option used: ${txPart(used[0]!.label)}`}</div>
) : (
<>
<div>
+7 -3
View File
@@ -60,7 +60,7 @@ import { parseIdeaKeymap } from "@/platform/ideaKeymap";
import { RecordShortcutDialog } from "./RecordShortcutDialog";
import { StrokeRecorder } from "./StrokeRecorder";
import styles from "./Keymap.module.css";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
type KNode =
| { kind: "group"; key: string; name: string; path: string[]; children: KNode[] }
@@ -230,7 +230,11 @@ export function KeymapPage() {
...Object.keys(PRESETS).map((id) => ({ value: id, label: PRESET_TITLES[id] ?? id })),
...Object.entries(customs)
.sort(([, a], [, b]) => a.name.localeCompare(b.name))
.map(([id, k]) => ({ value: id, label: k.name, detail: tx`based on ${PRESET_TITLES[k.parent] ?? k.parent}` })),
.map(([id, k]) => ({
value: id,
label: k.name,
detail: tx`based on ${txPart(PRESET_TITLES[k.parent] ?? k.parent)}`,
})),
];
const confirmDelete = async () => {
@@ -268,7 +272,7 @@ export function KeymapPage() {
body: (
<>
<div>
{tx`Imported '${name}' (based on ${PRESET_TITLES[parsed.parent] ?? parsed.parent}): ${parsed.applied} actions.`}
{tx`Imported '${name}' (based on ${txPart(PRESET_TITLES[parsed.parent] ?? parsed.parent)}): ${parsed.applied} actions.`}
</div>
{unknown.length > 0 && <div>{tx`Not available in OpenIDEA (${unknown.length}): ${unknown.join(", ")}.`}</div>}
{parsed.skippedShortcuts > 0 && <div>{tx`Skipped ${parsed.skippedShortcuts} unsupported shortcuts.`}</div>}
+2 -2
View File
@@ -5,7 +5,7 @@
import { useCallback, useId, useLayoutEffect, useRef, useState } from "react";
import clsx from "clsx";
import { FILE_COLOR_NAMES, fileColorCss, validateFileColors, type FileColorEntry } from "@/platform/fileColors";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import { BUILTIN_SCOPES, scopeError, validateScopes, type NamedScope } from "@/platform/scopes";
import { IconButton, Input, List, T, type SelectOption } from "@/ui";
import { ColorSwatches, Row, Section, Select, SettingToggle } from "../components/Form";
@@ -66,7 +66,7 @@ function freshName(taken: readonly string[]): string {
const PATTERN_EXAMPLE = "file:src//*";
function errorText(error: { message: string; at: number }): string {
const message = tx(error.message);
const message = txPart(error.message);
const column = error.at + 1;
return tx`${message} at column ${column}`;
}
+3 -3
View File
@@ -41,7 +41,7 @@ import { ACCENT_PRESETS, LIMITS, type ThemeId } from "../model/schema";
import type { PageSpec } from "./spec";
import { HTTP_PROXY_PAGE } from "./httpProxy";
import styles from "./Behavior.module.css";
import { LOCALES, SUPPORTED_LOCALES, tx, useT, useTx } from "@/platform/i18n";
import { LOCALES, SUPPORTED_LOCALES, tx, txPart, useT, useTx } from "@/platform/i18n";
import { BUILTIN_THEMES, useContributedIconThemes } from "@/platform/themes";
import { currentThemeChoice, originDetail, previewTheme, themeSelectOptions, useThemeChoices } from "@/workbench/theme";
import { themePreview } from "@/workbench/quickSwitch";
@@ -875,14 +875,14 @@ function NotificationGroups() {
value={value.display}
options={DISPLAY_OPTIONS}
onChange={(display) => update({ display })}
aria-label={tx`${title} popup type`}
aria-label={tx`${txPart(title)} popup type`}
/>
</Row>
<Checkbox
checked={value.log}
onChange={(log) => update({ log })}
label={<SearchLabel text="Show in tool window" />}
aria-label={tx`Show ${title} in tool window`}
aria-label={tx`Show ${txPart(title)} in tool window`}
/>
</section>
</div>
@@ -40,7 +40,7 @@ import { executeAction, registerActions } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { ask, confirm, showError } from "@/workbench/messages";
import { parseIcls, SchemeParseError, importScheme, deleteScheme, exportIcls } from "@/platform/icls";
import { tx, useTx } from "@/platform/i18n";
import { tx, txPart, useTx } from "@/platform/i18n";
import { selectPage } from "../../model/staging";
type Overrides = Record<string, Record<string, TextAttributesOverride>>;
@@ -1286,7 +1286,7 @@ function ColorInput({
<Input
mono
className={styles.swatchInput}
aria-label={tx`${label} hex`}
aria-label={tx`${txPart(label)} hex`}
value={draft ?? value}
invalid={draft !== null && !HEX_COLOR.test(draft)}
onChange={(e) => {
@@ -1831,7 +1831,7 @@ export function ColorSchemePage({
</div>
)}
{scheme === "theme-default" && (
<div className={styles.note}>{tx`Follows the IDE theme: currently ${schemeName}.`}</div>
<div className={styles.note}>{tx`Follows the IDE theme: currently ${txPart(schemeName)}.`}</div>
)}
{redGreen && (id === "dark" || id === "light") && (
<div className={styles.note}>
@@ -67,7 +67,7 @@ import {
type LanguageServers,
} from "./inspectionsModel";
import styles from "./Inspections.module.css";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import { useLanguageListVersion } from "@/platform/languageList";
function useLanguages(): LanguageServers[] {
@@ -448,7 +448,7 @@ function InspectionRow({
checked={state === "on"}
indeterminate={state === "mixed"}
onChange={() => onToggle(state !== "on")}
aria-label={tx`Enable ${node.name}`}
aria-label={tx`Enable ${txPart(node.name)}`}
/>
</span>
</span>
+2 -2
View File
@@ -14,7 +14,7 @@ import { LIMITS } from "../../model/schema";
import type { PageSpec } from "../spec";
import { EditorSections, type EditorSection, sectionLabels } from "./kit";
import styles from "./Editor.module.css";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
function FontRow() {
const [family, setFamily] = useSetting<string>("editor.fontFamily");
@@ -123,7 +123,7 @@ function WeightRow({
max={900}
step={50}
integer
aria-label={tx`${label} custom value`}
aria-label={tx`${txPart(label)} custom value`}
/>
)}
</Row>
@@ -10,7 +10,7 @@ import { createFromTemplate, packageFor, packageStyleFor } from "./create";
import { planFile, withKind, type FileTemplate } from "./model";
import { useFileTemplates } from "./store";
import styles from "./NewFileDialog.module.css";
import { tx, VerbatimTextContext } from "@/platform/i18n";
import { tx, txPart, VerbatimTextContext } from "@/platform/i18n";
interface Request {
directory: string;
@@ -231,11 +231,11 @@ function NameStep({
<Dialog
open
onClose={close}
title={tx`New ${tx(template.name)}`}
title={tx`New ${txPart(template.name)}`}
width={hasVariables ? 380 : 320}
position={hasVariables ? "top" : "center"}
popup
aria-label={tx`New ${tx(template.name)}`}
aria-label={tx`New ${txPart(template.name)}`}
className={hasVariables ? styles.variableDialog : styles.nameDialog}
buttons={
hasVariables
+2 -2
View File
@@ -23,7 +23,7 @@ import { syncTemplatesFromStorage } from "./sync";
import { tagAtCaret, updateTag } from "./emmet/editor";
import { loadEmmet } from "./emmet/model";
import { promptAbbreviation, UpdateTagDialogHost } from "./emmet/UpdateTagDialog";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import type { ProjectType } from "@/ui/projectType";
const EDITOR_WHEN = "textEditorActive && !editorReadOnly && (editorFocus || !toolWindowFocus)";
@@ -79,7 +79,7 @@ function directoryOf(arg: unknown): string | null {
function newFileAction(t: FileTemplate): Action {
return {
id: `templates.new.${t.id}`,
title: t.id === "file" ? "New Empty File…" : tx`New ${tx(t.name)}…`,
title: t.id === "file" ? "New Empty File…" : tx`New ${txPart(t.name)}…`,
category: "File",
icon: t.icon,
when: "projectOpen",
+2 -2
View File
@@ -15,7 +15,7 @@ import {
type MouseEvent,
type PointerEvent,
} from "react";
import { tx, txTemplate } from "@/platform/i18n";
import { tx, txPart, txTemplate } from "@/platform/i18n";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { fontWeightOf } from "@/platform/editorSettings";
@@ -1007,7 +1007,7 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
<CheckMark
checked={agg.checked}
indeterminate={agg.indeterminate}
label={tx`Include ${n.label} in commit`}
label={tx`Include ${n.type === "group" && (!n.changelist || n.label === DEFAULT_LIST_NAME) ? txPart(n.label) : n.label} in commit`}
onToggle={() => toggle(selected.has(n.key) && selected.size > 1 ? selectedNodes() : [n])}
/>
)}
+2 -2
View File
@@ -1,4 +1,4 @@
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import clsx from "clsx";
import styles from "../GitLog.module.css";
import { resizeColumnPair, useColumnResize, type ResizeTarget } from "./useColumnResize";
@@ -28,7 +28,7 @@ export function ColumnResizeHandle({
className={clsx(styles.columnResize, disabled && styles.columnResizeDisabled)}
role="separator"
aria-orientation="vertical"
aria-label={disabled ? tx`${tx(title)} column border` : tx`Resize ${tx(title)} column`}
aria-label={disabled ? tx`${txPart(title)} column border` : tx`Resize ${txPart(title)} column`}
aria-valuemin={40}
aria-valuemax={800}
aria-valuenow={target.width}
+2 -2
View File
@@ -1,4 +1,4 @@
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { isMacHost } from "@/platform/keymap";
import { Icon, IconButton, SearchField, type MenuItem } from "@/ui";
@@ -70,7 +70,7 @@ function FilterButton({ label, value, onOpen, onClear, hidden }: LogFilter & { h
<IconButton
type="button"
className={styles.filterClear}
aria-label={tx`Clear ${tx(label)} filter`}
aria-label={tx`Clear ${txPart(label)} filter`}
onClick={onClear}
icon="close"
size="small"
+2 -2
View File
@@ -2,7 +2,7 @@
import type { ChangeKind, FileStatus } from "@/bindings";
import type { FileDecoration } from "@/workbench/contributions";
import { formatDay, formatTimestamp } from "@/platform/dateFormat";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
/** What a file looks like in IDEA's change lists (one kind per file). */
export type EffectiveKind = "modified" | "added" | "deleted" | "renamed" | "untracked" | "ignored" | "conflicted";
@@ -63,7 +63,7 @@ export function statusDecorations(status: readonly FileStatus[], propagate = tru
if (!kind) continue;
const deco: FileDecoration = {
color: KIND_COLOR[kind],
tooltip: fs.renamedFrom ? tx`${KIND_LABEL[kind]} (from ${fs.renamedFrom})` : KIND_LABEL[kind],
tooltip: fs.renamedFrom ? tx`${txPart(KIND_LABEL[kind])} (from ${fs.renamedFrom})` : KIND_LABEL[kind],
};
if (kind === "ignored") deco.faded = true;
// Settings › Version Control › Show directories with changed descendants.
+3 -3
View File
@@ -27,7 +27,7 @@ import tagStyles from "./TagDialog.module.css";
import { ComparisonTree } from "./ComparisonTree";
import { showWorktreeComparison } from "./compareTool";
import { buildFileTree, type FileTreeNode } from "./fileTree";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import { displayPath } from "./compareData";
import { repositoryPath } from "./repositoryPaths";
import { RepoPicker } from "./gitMenuDialogs";
@@ -122,7 +122,7 @@ export function stoppedActions(op: InProgress, message: string): Array<{ label:
{
progress: "Continuing rebase",
success: "Rebase continued",
failure: tx`${controlLabel(op, "continue")} failed`,
failure: tx`${txPart(controlLabel(op, "continue"))} failed`,
onError: conflictsInstead,
errorActions: (m) => stoppedActions(op, m),
},
@@ -219,7 +219,7 @@ export async function controlOperation(control: "continue" | "skip" | "abort", e
{
progress,
success,
failure: tx`${controlLabel(op, control)} failed`,
failure: tx`${txPart(controlLabel(op, control))} failed`,
onError: control === "abort" ? undefined : conflictsInstead,
errorActions: control === "abort" ? undefined : (message) => stoppedActions(op, message),
},
+2 -2
View File
@@ -6,7 +6,7 @@ import { Channel } from "@tauri-apps/api/core";
import { create } from "zustand";
import type { BranchUpdate, GitOperation, RemoteOp } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import { AnsiStream, stripAnsi, type Span } from "@/ui/ansi";
import { call, commands, isCancelled, nextRequestId } from "@/platform/ipc";
import { attachDocument, editorsFor } from "@/editor/api";
@@ -117,7 +117,7 @@ export async function runOp<T>(title: string, fn: () => Promise<T>, opts: OpOpti
if (!opts.quiet && !handled)
notify({
level: "error",
title: tx`${title} failed`,
title: tx`${txPart(title)} failed`,
body: message,
actions: opts.errorActions?.(message),
});
+2 -2
View File
@@ -2,7 +2,7 @@
import { useEffect, useMemo, useState } from "react";
import type { BranchInfo, Commit, PushTags, RemoteOp } from "@/bindings";
import { call, commands } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
import { workflowSettings, type UpdateMethod } from "@/platform/workflowSettings";
import { notifications } from "@/workbench/contributions";
import { Button, Checkbox, Dialog, Input, List, Radio, Select, Spinner, T, Tree } from "@/ui";
@@ -773,7 +773,7 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
return (
<Dialog
open
title={head ? tx`Push Commits to ${upstream ?? "remote"}` : "Push"}
title={head ? tx`Push Commits to ${upstream ?? txPart("remote")}` : "Push"}
onClose={onClose}
width={commits?.length ? PUSH_DIALOG_WIDTH : 620}
minWidth={PUSH_DIALOG_MIN_WIDTH}
+9 -2
View File
@@ -13,6 +13,7 @@ import {
SUPPORTED_LOCALES,
t,
tx,
txPart,
txTemplate,
useI18n,
} from "./i18n";
@@ -195,12 +196,17 @@ describe("t / locales", () => {
expect(txTemplate(built)).toBe("运行 'orders'");
const zh = tx`Run '${name}'`;
expect(zh).toBe("运行 'orders'");
// Substituted text is translated when the catalog has it.
expect(tx`Run '${"Retry"}'`).toBe(`运行 '${tx("Retry")}'`);
// Values are inserted as written, even when the catalog has an entry for them…
expect(tx`Rename directory '${"tasks"}' and its usages to:`).toBe("将目录“tasks”及其用法重命名为:");
expect(tx`Run '${"Retry"}'`).toBe("运行 'Retry'");
// …unless they are marked as UI text, which is translated again after a locale change.
const marked = tx`Run '${txPart("Retry")}'`;
expect(marked).toBe(`运行 '${tx("Retry")}'`);
// Values are inserted as they are, braces included.
expect(tx`Drop ${"stash@{0}"}? This cannot be undone.`).toBe("是否丢弃 stash@{0}?此操作无法撤消。");
await setLocale("en");
expect(tx(zh)).toBe("Run 'orders'");
expect(tx(marked)).toBe("Run 'Retry'");
});
it("loads the Portuguese catalogs", async () => {
@@ -298,6 +304,7 @@ describe("catalogs", () => {
"Claude Code",
"GitHub Copilot",
"Codex",
"SKILL.md",
"Cursor",
"PHP",
"SQL",
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more