Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 23cfd13466 fix(vcs): give commit subjects room beside compact refs 2026-11-22 17:04:40 +08:00
Deng Liuтаdengliu 3d56af936d feat(dev): add dogfood:remote task to build and stage openidea-server (#5139)
Adds `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean] [--install-rust]` (also `mise run dogfood:remote`) for dogfooding backend changes in Remote Development without cross-compiling locally. It reads the host from Settings › Tools › SSH Configurations, checks SSH reachability and the minimum Rust version, syncs the backend workspace to `~/.cache/openidea-dogfood/workspace`, builds `openidea-server` there, installs it at the `~/.openidea/server/<version>/<build_id>` path `ensure_server` expects (so connecting doesn't upload another binary), stages the matching binary locally (`--clean` restores the release one), and asks before restarting a running server. The `build_id` hash uses `blake3` from the new `@noble/hashes` devDependency. Rust is installed on the host only with `--install-rust`.

Closes #5135

Co-authored-by: dengliu <[email protected]>
2026-11-22 15:35:33 +08:00
Deng Liuтаdengliu 0a3eac8652 feat(agents): parse context:fork and paths/globs skill metadata and show badges (#5162)
Skills now parse `context: fork` and `paths` / `globs` frontmatter (inline, bracketed or YAML list). Settings › Agents › Skills shows `context: fork` and `paths (n)` badges, with the patterns in the inspector, and the session Skills picker shows fork / paths pills. `SKILL.md` is still staged untouched, so CLIs that support these fields natively apply them. Frontmatter key lookup is case-insensitive.

Part of #5113

Co-authored-by: dengliu <[email protected]>
2026-11-22 15:33:47 +08:00
LU XIANGRUIтаwildcatDownstairs 70702934d1 feat(run): run Mocha tests with a test tree and Rerun Failed Tests (#5173)
Mocha runs showed no test tree, and single tests ran with Jest's `-t`. A `package.json` script that runs `mocha` is now a test configuration with `testRunner: "mocha"`. Test runs import the IDE's hook (`mochaHook.js`, a `data:` URL in `NODE_OPTIONS`), which prints a record per finished test (file, suite chain, status, duration, declaration line, error) next to the run's own reporter; the records become the tree and are hidden from the console. Gutter icons, Rerun Failed Tests and running selected tests use Mocha's own `--grep`. New fixture `fixtures/mocha-app`, run by `smoke/run.test.ts` in the TypeScript job.

Closes #5153

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 15:24:38 +08:00
LU XIANGRUIтаwildcatDownstairs 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 XIANGRUIтаwildcatDownstairs 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 Liuтаdengliu 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
103 змінених файлів з 5067 додано та 162 видалено

No files matched your search

+1
Переглянути файл
@@ -80,6 +80,7 @@ Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
this worktree's running MCP bridges and actual ports.
- `pnpm build` — typecheck + bundle frontend.
- `pnpm dogfood:build` / `pnpm dogfood:install` (or `mise run dogfood:build` / `mise run dogfood:install`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
Створено
+1
Переглянути файл
@@ -4146,6 +4146,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
name = "ide-agent"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"blake3",
"dunce",
"encoding_rs",
+1
Переглянути файл
@@ -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
+5
Переглянути файл
@@ -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};
+6
Переглянути файл
@@ -948,6 +948,12 @@ pub struct AgentSkill {
/// True when frontmatter sets `disable-model-invocation: true` (defaults to `slashOnly`).
#[serde(default)]
pub disable_model_invocation: bool,
/// True when frontmatter sets `context: fork` (passed through natively to supporting CLIs).
#[serde(default)]
pub context_fork: bool,
/// Optional `paths` / `globs` patterns from frontmatter (passed through natively to supporting CLIs).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub paths: Vec<String>,
/// The `SKILL.md` passes validation (`name` matches its folder, `description` present).
pub valid: bool,
/// What validation found (`name` mismatch, missing or over-long description…).
File diff suppressed because it is too large. Load diff
+95 -8
Переглянути файл
@@ -125,10 +125,9 @@ fn file_name(path: &Path) -> Option<String> {
path.file_name()?.to_str().map(str::to_owned)
}
/// The `key: value` lines between the leading `---` fences (folded `>` / `|` values joined).
struct Frontmatter {
fields: Vec<(String, String)>,
/// Where the body starts.
lists: Vec<(String, Vec<String>)>,
body: usize,
}
@@ -138,22 +137,42 @@ impl Frontmatter {
let mut lines = text.split_inclusive('\n');
let mut offset = 0;
let mut fields: Vec<(String, String)> = Vec::new();
let mut lists: Vec<(String, Vec<String>)> = Vec::new();
match lines.next() {
Some(first) if first.trim_end() == "---" => offset += first.len(),
_ => return Self { fields, body: 0 },
_ => return Self { fields, lists, body: 0 },
}
for line in lines {
offset += line.len();
let line = line.trim_end();
if line == "---" {
return Self { fields, body: offset };
return Self { fields, lists, body: offset };
}
if line.starts_with([' ', '\t']) {
let unindented_list_item = (line == "-" || line.starts_with("- ") || line.starts_with("-\t"))
&& fields.last().is_some_and(|(_, v)| v.is_empty());
if line.starts_with([' ', '\t']) || unindented_list_item {
let trimmed = line.trim();
if let Some(rest) = trimmed.strip_prefix('-')
&& (rest.is_empty() || rest.starts_with([' ', '\t']))
&& let Some((key, _)) = fields.last()
{
let item = unquote(rest.trim());
if !item.is_empty() {
if let Some((_, existing)) = lists.iter_mut().find(|(k, _)| k == key) {
existing.push(item.to_owned());
} else {
lists.push((key.clone(), vec![item.to_owned()]));
}
}
if unindented_list_item {
continue;
}
}
if let Some((_, value)) = fields.last_mut() {
if !value.is_empty() {
value.push(' ');
}
value.push_str(line.trim());
value.push_str(trimmed);
}
continue;
}
@@ -164,11 +183,15 @@ impl Frontmatter {
}
}
// No closing fence: not frontmatter.
Self { fields: Vec::new(), body: 0 }
Self { fields: Vec::new(), lists: Vec::new(), body: 0 }
}
fn get(&self, key: &str) -> Option<&str> {
self.fields.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
self.fields.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v.as_str())
}
fn list(&self, key: &str) -> Option<&[String]> {
self.lists.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v.as_slice())
}
/// `description`, else the body's first line.
@@ -505,6 +528,8 @@ fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSour
let hint = meta.get("argument-hint").map(|h| strip_ansi(h).trim().to_owned()).filter(|h| !h.is_empty());
let user_invocable = !meta.get("user-invocable").is_some_and(|v| v.eq_ignore_ascii_case("false"));
let disable_model_invocation = meta.get("disable-model-invocation").is_some_and(|v| v.eq_ignore_ascii_case("true"));
let context_fork = meta.get("context").is_some_and(|v| strip_ansi(v).trim().eq_ignore_ascii_case("fork"));
let paths = parse_skill_paths(&meta);
AgentSkill {
name,
description: truncate(&description),
@@ -514,11 +539,35 @@ fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSour
also_in: Vec::new(),
user_invocable,
disable_model_invocation,
context_fork,
paths,
valid: warnings.is_empty(),
warnings,
}
}
fn parse_skill_paths(meta: &Frontmatter) -> Vec<String> {
for key in ["paths", "globs"] {
if let Some(items) = meta.list(key) {
let cleaned: Vec<String> =
items.iter().map(|s| strip_ansi(s).trim().to_owned()).filter(|s| !s.is_empty()).collect();
if !cleaned.is_empty() {
return cleaned;
}
}
if let Some(raw) = meta.get(key) {
let trimmed = strip_ansi(raw);
let inner = trimmed.trim().strip_prefix('[').and_then(|s| s.strip_suffix(']')).unwrap_or(trimmed.trim());
let cleaned: Vec<String> =
inner.split(',').map(|p| unquote(p.trim()).trim().to_owned()).filter(|p| !p.is_empty()).collect();
if !cleaned.is_empty() {
return cleaned;
}
}
}
Vec::new()
}
/// A skill's mode, as one policy layer of the settings has it.
type Policies = BTreeMap<String, AgentSkillPolicy>;
@@ -1034,6 +1083,8 @@ mod tests {
also_in: Vec::new(),
user_invocable: true,
disable_model_invocation: false,
context_fork: false,
paths: Vec::new(),
valid: true,
warnings: Vec::new(),
}
@@ -1435,4 +1486,40 @@ mod tests {
let _ = stage(&farm, "claude", &off_states, &ws, Some(&home)).unwrap();
assert!(!farm.join(".claude/skills/release-notes").exists());
}
#[test]
fn parses_context_fork_and_paths_frontmatter_and_preserves_file_on_stage() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let ws = root.join("ws");
let raw_md = "---\n\
name: verify-ux\n\
description: Verify UX layouts in an isolated subagent\n\
context: fork\n\
paths:\n\
- \"src/**/*.tsx\"\n\
- crates/ide-agent/**/*.rs\n\
---\n\nRun visual checks.\n";
write(&ws.join(".openidea/skills/verify-ux/SKILL.md"), raw_md);
write(
&ws.join(".agents/skills/inline-globs/SKILL.md"),
"---\nname: inline-globs\ndescription: Scoped by globs\nglobs: [\"e2e/*.spec.ts\", \"src/ui/*.tsx\"]\n---\n",
);
let found = discover_skills(&ws, None);
let verify = found.iter().find(|s| s.name == "verify-ux").unwrap();
assert!(verify.context_fork);
assert_eq!(verify.paths, ["src/**/*.tsx", "crates/ide-agent/**/*.rs"]);
let inline = found.iter().find(|s| s.name == "inline-globs").unwrap();
assert!(!inline.context_fork);
assert_eq!(inline.paths, ["e2e/*.spec.ts", "src/ui/*.tsx"]);
// Staging passes `SKILL.md` through untouched so native CLIs execute `context: fork` / `paths`.
let states = resolve(found, None, &BTreeMap::new(), &BTreeMap::new(), true);
let farm = farm_dir(&root.join("store"), "fork-passthrough");
let _ = stage(&farm, "copilot", &states, &ws, None).unwrap();
let staged_md = std::fs::read_to_string(farm.join("copilot/verify-ux/SKILL.md")).unwrap();
assert_eq!(staged_md, raw_md);
}
}
+114 -2
Переглянути файл
@@ -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;
@@ -1116,6 +1117,114 @@ pub fn agent_skills_set_mode(
))
}
/// 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>]`).
fn skills_maps(
host: &Host,
@@ -1364,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,
+23 -2
Переглянути файл
@@ -244,12 +244,33 @@ 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`, `mocha`, or `node --test` (`tsx --test`) with Node's own
/// reporters (the IDE adds its reporter next to them, which a reporter chosen here would clash with).
fn script_test_runner(script: &str) -> Option<&'static str> {
let tokens: Vec<&str> = script.split(|c: char| c.is_whitespace() || matches!(c, '&' | '|' | ';')).collect();
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");
}
if tokens.iter().any(|t| matches!(t.rsplit('/').next(), Some("mocha" | "_mocha"))) {
return Some("mocha");
}
let node = tokens.iter().position(|t| matches!(*t, "node" | "tsx"))?;
// Node's own options: up to the script (`node server.js --test` passes `--test` to the program).
let mut options = Vec::new();
for t in &tokens[node + 1..] {
let value = options.last().is_some_and(|o| NODE_VALUE_OPTIONS.contains(o));
if !value && !t.starts_with('-') {
break;
}
options.push(*t);
}
(options.contains(&"--test") && !options.iter().any(|t| t.starts_with("--test-reporter"))).then_some("node-test")
}
/// Node options whose value is the next argument.
const NODE_VALUE_OPTIONS: &[&str] =
&["-r", "--require", "--import", "--loader", "--experimental-loader", "-C", "--conditions", "--env-file"];
const PLAYWRIGHT_CONFIGS: &[&str] = &[
"playwright.config.ts",
"playwright.config.js",
+30
Переглянути файл
@@ -76,6 +76,36 @@ 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 mocha_scripts() {
let dir = project(&[(
"package.json",
r#"{"scripts":{"spec":"mocha --recursive","test":"nyc ./node_modules/.bin/mocha","lint":"eslint mocha.config.js"}}"#,
)]);
let c = detect(dir.path());
let spec = find(&c, "npm:spec");
assert!(spec.is_test);
assert_eq!(spec.extras.test_runner.as_deref(), Some("mocha"));
assert_eq!(find(&c, "npm:test").extras.test_runner.as_deref(), Some("mocha"));
assert!(!find(&c, "npm:lint").is_test);
}
#[test]
fn package_manager_selection() {
for (lock, pm) in [("yarn.lock", "yarn"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("package-lock.json", "npm")] {
+7
Переглянути файл
@@ -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
Переглянути файл
@@ -67,7 +67,7 @@ mise run dev
`setup` runs `pnpm install` in this worktree. `dev` and `dev:app` use the same worktree-aware launchers as the direct commands. No shell activation is needed for `mise run`.
Run `mise tasks` to list all tasks. `mise run build` builds the frontend (not a desktop installer); `mise run dogfood:build` and `mise run dogfood:install` build and locally install a grey-icon dogfood desktop app that shares settings and data with the release app. Only one of the two apps runs at a time, since they share one instance; settings written by the newer dogfood build can make an older release ignore the settings file. The dogfood app never updates itself: run `dogfood:install` again to pick up new changes. `mise run test` runs Vitest and `cargo test --workspace`; `mise run check` runs the format, lint, type and unused-code checks, then both test suites. Neither requires nextest or the plugin WASM target.
Run `mise tasks` to list all tasks. `mise run build` builds the frontend (not a desktop installer); `mise run dogfood:build` and `mise run dogfood:install` build and locally install a grey-icon dogfood desktop app that shares settings and data with the release app. Only one of the two apps runs at a time, since they share one instance; settings written by the newer dogfood build can make an older release ignore the settings file. The dogfood app never updates itself: run `dogfood:install` again to pick up new changes. `mise run dogfood:remote <remote_name>` builds and stages `openidea-server` on an SSH host configured in **Tools › SSH Configurations** (`--clean` removes the override). `mise run test` runs Vitest and `cargo test --workspace`; `mise run check` runs the format, lint, type and unused-code checks, then both test suites. Neither requires nextest or the plugin WASM target.
## Worktrees
+1 -1
Переглянути файл
@@ -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`, Mocha, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks.
## Navigate between code and tests
+2 -2
Переглянути файл
@@ -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`, `node --test` or `mocha`, are test configurations.
- `playwright test` (through `npx`) for a package with a `playwright.config.*` that no script runs.
- One per task in `deno.json` / `deno.jsonc` (`deno task <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, `node --test` and Mocha output is turned into the test tree, with **Rerun Failed Tests**. Playwright runs report through its `list` reporter unless the configuration names another; a test in the gutter runs by its line (`file:line`), and runs with several projects show each project under its file. `node --test` runs report through the IDE's reporter next to `spec`, added to `NODE_OPTIONS` (a script that chooses its own `--test-reporter` runs without the tree); single tests and reruns are selected by full name (`--test-name-pattern`). Mocha runs keep their reporter and load an IDE hook through `NODE_OPTIONS` that reports each test with its line; single tests and reruns use `--grep`, and tests in `test/` get gutter icons whatever their file name. **Run with Coverage** works for scripts that run `vitest` or `jest` (Vitest needs a coverage provider such as `@vitest/coverage-v8`; the IDE offers to add it) and for `node` / `tsx` / `ts-node` runs through `c8`. See [Testing](/en/guide/testing) and [Coverage](/en/guide/coverage).
## Debugging
+1 -1
Переглянути файл
@@ -67,7 +67,7 @@ mise run dev
`setup` 在当前 worktree 中执行 `pnpm install`。`dev` 和 `dev:app` 都沿用原来的启动脚本,保留 worktree 隔离。使用 `mise run` 不需要在 shell 中激活 mise。
运行 `mise tasks` 可以查看全部任务。`mise run build` 构建前端,不生成桌面安装包;`mise run dogfood:build` 和 `mise run dogfood:install` 用于构建并在本地安装灰色图标的 dogfood 桌面版(与正式版共享设置和数据)。两者共用同一个实例,同一时间只能运行一个;较新的 dogfood 版写入的设置可能让较旧的正式版忽略整个设置文件。dogfood 版不会自动更新,需要更新时重新运行 `dogfood:install`。`mise run test` 运行 Vitest 和 `cargo test --workspace`;`mise run check` 先检查格式、代码规范、类型和未使用的代码,再运行这两套测试。两者都不需要 nextest 或插件的 WASM 目标。
运行 `mise tasks` 可以查看全部任务。`mise run build` 构建前端,不生成桌面安装包;`mise run dogfood:build` 和 `mise run dogfood:install` 用于构建并在本地安装灰色图标的 dogfood 桌面版(与正式版共享设置和数据)。两者共用同一个实例,同一时间只能运行一个;较新的 dogfood 版写入的设置可能让较旧的正式版忽略整个设置文件。dogfood 版不会自动更新,需要更新时重新运行 `dogfood:install`。`mise run dogfood:remote <remote_name>` 在 **工具 › SSH 配置** 中指定的远程主机上构建并部署 `openidea-server`(`--clean` 可移除覆盖)。`mise run test` 运行 Vitest 和 `cargo test --workspace`;`mise run check` 先检查格式、代码规范、类型和未使用的代码,再运行这两套测试。两者都不需要 nextest 或插件的 WASM 目标。
## Worktree
+1 -1
Переглянути файл
@@ -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`、Mocha、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。
## 在代码和测试之间跳转
+2 -2
Переглянути файл
@@ -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` 或 `mocha` 的脚本,是测试配置。
- 有 `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` 和 Mocha 的输出会解析成测试树,支持 **重新运行失败的测试**。Playwright 运行时使用它的 `list` 报告器(配置里指定了其他报告器时除外);从行号栏运行单个测试时按行号选择(`file:line`),有多个 project 的运行会在文件下按 project 分组。`node --test` 运行时,IDE 通过 `NODE_OPTIONS` 在 `spec` 旁加上自己的报告器(脚本自己指定了 `--test-reporter` 时不显示测试树);单个测试和重新运行按完整名称选择(`--test-name-pattern`)。Mocha 运行保留它自己的报告器,并通过 `NODE_OPTIONS` 加载 IDE 的钩子,逐个报告测试及其所在行;单个测试和重新运行使用 `--grep`,`test/` 目录下的测试不论文件名都有行号栏图标。**使用覆盖率运行** 支持调用 `vitest` 或 `jest` 的脚本(Vitest 需要 `@vitest/coverage-v8` 之类的覆盖率 provider,缺失时 IDE 会提示添加),以及通过 `c8` 运行的 `node` / `tsx` / `ts-node`。详见[测试](/zh/guide/testing)和[覆盖率](/zh/guide/coverage)。
## 调试
+118
Переглянути файл
@@ -73,6 +73,8 @@ const initialSkills: AgentSkillState[] = [
alsoIn: ["claudeWorkspace"],
userInvocable: true,
disableModelInvocation: false,
contextFork: true,
paths: ["src/**/*.tsx", "e2e/*.spec.ts"],
valid: true,
warnings: [],
},
@@ -206,6 +208,90 @@ test("manages multi-level skills in Settings and per-session overrides via Compo
);
return skills;
};
handlers.agent_skills_browse = () => ({
owner: "vercel-labs",
repo: "agent-skills",
gitRef: "main",
treeSha: "9f8e7d6c",
truncated: false,
skills: [
{ folderName: "find-skills", subpath: "skills/find-skills", fileCount: 2, totalBytes: 1420 },
{ folderName: "web-design-audit", subpath: "skills/web-design-audit", fileCount: 1, totalBytes: 860 },
],
});
handlers.agent_skills_preview = ({ subpath }) =>
subpath === "skills/web-design-audit"
? {
owner: "vercel-labs",
repo: "agent-skills",
gitRef: "main",
treeSha: "9f8e7d6c",
subpath: "skills/web-design-audit",
skillName: "web-design-audit",
description: "Audit responsive layout and contrast tokens",
skillMarkdown:
"---\nname: web-design-audit\ndescription: Audit responsive layout and contrast tokens\n---\n\nCheck spacing and contrast tokens.\n",
files: [{ path: "SKILL.md", size: 860, executable: false, symlink: false }],
scanWarnings: [],
alreadyInstalledUser: false,
alreadyInstalledWorkspace: false,
}
: {
owner: "vercel-labs",
repo: "agent-skills",
gitRef: "main",
treeSha: "9f8e7d6c",
subpath: "skills/find-skills",
skillName: "find-skills",
description: "Discover reusable SKILL.md workflows and inspect bundled scripts",
skillMarkdown:
"---\nname: find-skills\ndescription: Discover reusable SKILL.md workflows and inspect bundled scripts\nallowed-tools:\n - Bash(gh:*)\n---\n\nInspect candidate SKILL.md files before installing.\n",
files: [
{ path: "SKILL.md", size: 980, executable: false, symlink: false },
{ path: "scripts/inspect.sh", size: 440, executable: true, symlink: false },
],
scanWarnings: [
{
kind: "executableScript",
file: "scripts/inspect.sh",
message: "Contains executable file mode (100755)",
},
{
kind: "allowedToolsShell",
file: "SKILL.md",
message: "`allowed-tools` grants shell/command execution (`Bash(gh:*)`)",
},
],
alreadyInstalledUser: false,
alreadyInstalledWorkspace: false,
};
handlers.agent_skills_install = ({ input }) => {
const req = input as { subpath: string; scope: "user" | "workspace" };
const installedName = req.subpath.endsWith("web-design-audit") ? "web-design-audit" : "find-skills";
skills = [
...skills,
{
skill: {
name: installedName,
description: "Discover reusable SKILL.md workflows and inspect bundled scripts",
hint: null,
path:
req.scope === "workspace"
? `/dev/openidea/.agents/skills/${installedName}`
: `/Users/dev/.agents/skills/${installedName}`,
source: req.scope === "workspace" ? "workspace" : "user",
alsoIn: [],
userInvocable: true,
disableModelInvocation: false,
valid: true,
warnings: [],
},
mode: "auto",
origin: "none",
},
];
return skills;
};
handlers.agent_set_skill_overrides = ({ overrides }) => {
currentTask = { ...currentTask, skillOverrides: overrides as Record<string, AgentSkillMode> };
return currentTask;
@@ -242,6 +328,8 @@ test("manages multi-level skills in Settings and per-session overrides via Compo
const sessionPopup = page.getByRole("dialog", { name: "Session Skills" });
await expect(sessionPopup).toBeVisible();
await expect(sessionPopup).toContainText("verify");
await expect(sessionPopup).toContainText("fork");
await expect(sessionPopup).toContainText("paths");
await expect(sessionPopup).toContainText("impeccable");
await expect(sessionPopup).toContainText("Plugins");
await expect(sessionPopup).toContainText("release-notes");
@@ -268,9 +356,12 @@ test("manages multi-level skills in Settings and per-session overrides via Compo
await expect(settingsDialog).toBeVisible();
await expect(settingsDialog.getByRole("heading", { name: "Skills" })).toBeVisible();
await expect(settingsDialog.getByTitle(".claude/skills").first()).toHaveText("Claude Code");
await expect(settingsDialog.getByText("context: fork")).toBeVisible();
await expect(settingsDialog.getByText("paths (2)")).toBeVisible();
await settingsDialog.getByRole("button", { name: /^verify/ }).click();
await expect(settingsDialog.getByText("Claude Code (.claude/skills)")).toBeVisible();
await expect(settingsDialog.getByText("src/**/*.tsx, e2e/*.spec.ts")).toBeVisible();
await expect(settingsDialog.getByText("SKILL.md is valid")).toBeVisible();
await settingsDialog.getByRole("tab", { name: /Plugins/ }).click();
@@ -282,4 +373,31 @@ test("manages multi-level skills in Settings and per-session overrides via Compo
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` });
}
});
+2 -2
Переглянути файл
@@ -117,7 +117,7 @@ test("fits a wide graph and saved columns without horizontal scrolling", async (
expect(await list.evaluate((element) => element.scrollLeft)).toBe(0);
});
test("keeps ref names visible when a long commit subject competes for space", async ({ workbench: page }) => {
test("keeps expanded ref names visible when a long commit subject competes for space", async ({ workbench: page }) => {
const branch = "origin/feature/workspace-settings";
const tag = "v2.1";
const summary = "Keep workspace settings and commit references visible ".repeat(4).trim();
@@ -127,7 +127,7 @@ test("keeps ref names visible when a long commit subject competes for space", as
const options = "/src/features/vcs/logOptions.ts";
const { useGitLog } = await import(/* @vite-ignore */ log);
const { useLogOptions } = await import(/* @vite-ignore */ options);
useLogOptions.setState({ tagNames: true });
useLogOptions.setState({ tagNames: true, compactRefs: false });
const [first, ...rest] = useGitLog.getState().commits;
useGitLog.setState({ commits: [{ ...first, summary, refs: [branch, `tag: ${tag}`] }, ...rest] });
},
+51
Переглянути файл
@@ -112,6 +112,57 @@ test("Git Log separates commit message typography from compact metadata", async
await expect(author).toHaveCSS("font-size", "12px");
});
test("compact Git Log refs give the subject room on either side", async ({ workbench: page }) => {
await page.setViewportSize({ width: 630, height: 720 });
const refSubject = "Reconcile shipping credits";
const longReference = "release-quarterly-settlement-and-backoffice-invoice-reconciliation";
await page.evaluate(
async ({ refSubject, longReference }) => {
const optionsModule = "/src/features/vcs/logOptions.ts";
const logModule = "/src/features/vcs/logStore.ts";
const { setLogOptions } = await import(/* @vite-ignore */ optionsModule);
const { useGitLog } = await import(/* @vite-ignore */ logModule);
setLogOptions({ showBranches: false, showDetails: false });
const [first, ...rest] = useGitLog.getState().commits;
useGitLog.setState({
commits: [{ ...first, summary: refSubject, message: refSubject, refs: [longReference] }, ...rest],
});
},
{ refSubject, longReference },
);
const row = page.getByRole("listbox", { name: "Commits" }).getByRole("option").filter({ hasText: refSubject });
const subject = row.getByText(refSubject, { exact: true });
const ref = row.getByTitle(longReference, { exact: true });
const expectLayout = async () => {
await expect
.poll(() =>
subject.evaluate((el) => {
const text = document.createRange();
text.selectNodeContents(el);
return el.getBoundingClientRect().width + 0.02 >= text.getBoundingClientRect().width;
}),
)
.toBe(true);
await expect
.poll(() =>
ref.evaluate((el) => {
const refs = el.parentElement!;
return refs.clientWidth / refs.parentElement!.clientWidth;
}),
)
.toBeLessThanOrEqual(0.34);
await expect(ref).toHaveCSS("font-size", "12px");
await expect(subject).toHaveCSS("font-size", "13px");
};
await expectLayout();
await expect.poll(async () => (await subject.boundingBox())!.x < (await ref.boundingBox())!.x).toBe(true);
await page.getByRole("toolbar", { name: "Log filters" }).getByRole("button", { name: "View Options" }).click();
await page.getByRole("menuitemcheckbox", { name: "References on the Left" }).click();
await expectLayout();
await expect.poll(async () => (await subject.boundingBox())!.x > (await ref.boundingBox())!.x).toBe(true);
});
test("a second click on a Git Log toolbar button closes its popup", async ({ workbench: page }) => {
const toolbar = page.getByRole("toolbar", { name: "Log filters" });
const branchPopup = page.getByRole("dialog", { name: "Filter by Branch" });
+3 -1
Переглянути файл
@@ -10,6 +10,8 @@ something to show.
| `rust-app/` | cargo | `cargo run` | `cargo test` | `cargo test --features failing-tests` | unused variable in `src/parser.rs` |
| `ts-app/` | Node 22+, pnpm/npm | `pnpm start` | `pnpm test` (vitest) | `OPENIDEA_FAIL=1 pnpm test` | unused function in `src/index.ts` |
| `playwright-app/` | Node 22+, npm (Playwright Test, no browser needed) | — | `npm test` | `OPENIDEA_FAIL=1 npm test` | unused function in `src/checkout.ts` |
| `node-test-app/` | Node 22+, npm (no dependencies) | — | `npm test` (node:test) | `OPENIDEA_FAIL=1 npm test` | unused constant in `src/inventory.js` |
| `mocha-app/` | Node 22+, npm | — | `npm test` (Mocha) | `OPENIDEA_FAIL=1 npm test` | unused constant in `src/pricing.js` |
| `python-app/` | Python 3.10+, pytest | `python -m tasks.cli` (from `src/`) | `pytest` | `OPENIDEA_FAIL=1 pytest` | unused imports in `models.py` |
| `go-app/` | Go 1.22+ | `go run ./cmd/server` | `go test ./...` | `OPENIDEA_FAIL=1 go test ./...` | unused `fmt.Sprintf` result in `internal/store/store.go` |
| `kotlin-gradle/` | JDK 21, Gradle 8 (no wrapper) | `gradle run` | `gradle test` | `gradle test -PopenideaFail` | unused variable in `App.kt` |
@@ -40,7 +42,7 @@ git init -q && git add -A && git commit -qm "initial" # for the VCS checks
```
Then open the folder with **File › Open…** (`⌘⇧⌥O`) or from the Welcome screen.
For `ts-app` / `playwright-app` / `polyglot/web` run `pnpm install` first; for `python-app` create a
For `ts-app` / `playwright-app` / `mocha-app` / `polyglot/web` run `pnpm install` first; for `python-app` create a
venv (`python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'`); for
`php-app` run `composer install` (debugging it needs Xdebug in the PHP on `PATH`).
+1
Переглянути файл
@@ -0,0 +1 @@
node_modules
+13
Переглянути файл
@@ -0,0 +1,13 @@
{
"name": "openidea-fixture-pricing",
"version": "0.1.0",
"private": true,
"description": "OpenIDEA QA fixture: Mocha specs for a small pricing module",
"type": "module",
"scripts": {
"test": "mocha"
},
"devDependencies": {
"mocha": "^10.8.0"
}
}
+14
Переглянути файл
@@ -0,0 +1,14 @@
export function withTax(net, rate) {
if (rate < 0) throw new RangeError("tax rate must not be negative");
return Math.round(net * (1 + rate) * 100) / 100;
}
export function bulkDiscount(quantity) {
// TODO: read the tiers from the catalog instead of hard-coding them
if (quantity >= 100) return 0.15;
if (quantity >= 10) return 0.05;
return 0;
}
// An intentional warning: never used.
const CURRENCY = "EUR";
+29
Переглянути файл
@@ -0,0 +1,29 @@
import assert from "node:assert/strict";
import { bulkDiscount, withTax } from "../src/pricing.js";
describe("pricing", function () {
describe("withTax", function () {
it("adds the rate", function () {
assert.equal(withTax(100, 0.2), 120);
});
it("rejects a negative rate", function () {
assert.throws(() => withTax(100, -0.1), RangeError);
});
});
describe("bulkDiscount", function () {
it("has no discount for a few items", function () {
assert.equal(bulkDiscount(3), 0);
});
it("discounts large orders", function () {
assert.equal(bulkDiscount(250), 0.15);
});
});
it("intentionally fails (set OPENIDEA_FAIL=1)", function () {
if (!process.env.OPENIDEA_FAIL) this.skip();
assert.equal(withTax(10, 0.1), 11.5);
});
});
+1
Переглянути файл
@@ -0,0 +1 @@
node_modules
+10
Переглянути файл
@@ -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
Переглянути файл
@@ -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;
+27
Переглянути файл
@@ -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);
});
+4
Переглянути файл
@@ -29,6 +29,10 @@ description = "Build and install the local dogfood desktop app"
depends = ["dogfood:build"]
run = "pnpm dogfood:install --no-build"
[tasks."dogfood:remote"]
description = "Build and install a local dogfood openidea-server on a configured SSH remote"
run = "pnpm dogfood:remote"
[tasks.test]
description = "Run the frontend and Rust workspace tests"
run = ["pnpm test", "cargo test --workspace"]
+3 -1
Переглянути файл
@@ -35,7 +35,8 @@
"eval": "node evals/run.ts",
"release:prepare": "node scripts/release-prepare.ts",
"dogfood:build": "node scripts/dogfood.ts build",
"dogfood:install": "node scripts/dogfood.ts install"
"dogfood:install": "node scripts/dogfood.ts install",
"dogfood:remote": "node scripts/dogfood-remote.ts"
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged"
@@ -94,6 +95,7 @@
},
"devDependencies": {
"@lezer/generator": "^1.8.1",
"@noble/hashes": "^2.4.0",
"@playwright/test": "^1.64.1",
"@tauri-apps/cli": "^2",
"@testing-library/jest-dom": "^7.0.1",
Створено
+30 -19
Переглянути файл
@@ -154,6 +154,9 @@ importers:
'@lezer/generator':
specifier: ^1.8.1
version: 1.8.1
'@noble/hashes':
specifier: ^2.4.0
version: 2.4.0
'@playwright/test':
specifier: ^1.64.1
version: 1.64.1
@@ -162,7 +165,7 @@ importers:
version: 2.12.3
'@testing-library/jest-dom':
specifier: ^7.0.1
version: 7.0.1(@testing-library/[email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])))
version: 7.0.1(@testing-library/[email protected])([email protected](@types/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])))
'@testing-library/react':
specifier: ^16.3.3
version: 16.3.3(@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
@@ -183,7 +186,7 @@ importers:
version: 6.1.2([email protected](@types/[email protected])([email protected])([email protected]))
jsdom:
specifier: ^30.1.3
version: 30.1.3
version: 30.1.3(@noble/[email protected])
knip:
specifier: ^6.43.0
version: 6.43.0
@@ -210,7 +213,7 @@ importers:
version: 8.3.4(@types/[email protected])([email protected])([email protected])
vitest:
specifier: ^5.0.5
version: 5.0.5(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected]))
version: 5.0.5(@types/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected]))
yaml:
specifier: ^2.9.1
version: 2.9.1
@@ -530,6 +533,10 @@ packages:
'@emnapi/core': ^1.7.1 || 2.0.0-beta.2
'@emnapi/runtime': ^1.7.1 || 2.0.0-beta.2
'@noble/[email protected]':
resolution: {integrity: sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==}
engines: {node: '>= 20.19.0'}
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-A6xv7hDtnTm+xlZ7utn6rRQpRMJHRhVr3gjRGqlx0RUX84mNk0pAsy6YN/wWhuOTkaZhRrrzaLxf0NfbH77j2w==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -2703,7 +2710,9 @@ snapshots:
tslib: 2.8.1
optional: true
'@exodus/[email protected]': {}
'@exodus/[email protected](@noble/[email protected])':
optionalDependencies:
'@noble/hashes': 2.4.0
'@floating-ui/[email protected]':
dependencies:
@@ -2854,6 +2863,8 @@ snapshots:
'@tybys/wasm-util': 0.10.4
optional: true
'@noble/[email protected]': {}
'@oxc-parser/[email protected]':
optional: true
@@ -3241,7 +3252,7 @@ snapshots:
picocolors: 1.1.1
pretty-format: 27.5.1
'@testing-library/[email protected](@testing-library/[email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])))':
'@testing-library/[email protected](@testing-library/[email protected])([email protected](@types/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])))':
dependencies:
'@adobe/css-tools': 4.5.0
'@testing-library/dom': 10.4.2
@@ -3251,7 +3262,7 @@ snapshots:
picocolors: 1.1.1
redent: 3.0.0
optionalDependencies:
vitest: 5.0.5(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected]))
vitest: 5.0.5(@types/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected]))
'@testing-library/[email protected](@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':
dependencies:
@@ -3706,10 +3717,10 @@ snapshots:
d3: 7.9.0
lodash-es: 4.18.1
[email protected]:
[email protected](@noble/[email protected]):
dependencies:
whatwg-mimetype: 5.0.0
whatwg-url: 17.3.0
whatwg-url: 17.3.0(@noble/[email protected])
transitivePeerDependencies:
- '@noble/hashes'
@@ -3774,9 +3785,9 @@ snapshots:
[email protected]: {}
[email protected]:
[email protected](@noble/[email protected]):
dependencies:
'@exodus/bytes': 1.16.0
'@exodus/bytes': 1.16.0(@noble/[email protected])
transitivePeerDependencies:
- '@noble/hashes'
@@ -3800,17 +3811,17 @@ snapshots:
[email protected]: {}
[email protected]:
[email protected](@noble/[email protected]):
dependencies:
'@asamuzakjp/css-color': 7.1.7
'@asamuzakjp/dom-selector': 10.0.4
'@bramus/specificity': 2.4.3
'@csstools/css-syntax-patches-for-csstree': 1.1.15([email protected])
'@exodus/bytes': 1.16.0
'@exodus/bytes': 1.16.0(@noble/[email protected])
css-tree: 3.2.1
data-urls: 8.0.0
data-urls: 8.0.0(@noble/[email protected])
decimal.js: 10.6.0
html-encoding-sniffer: 7.0.0
html-encoding-sniffer: 7.0.0(@noble/[email protected])
is-potential-custom-element-name: 1.0.1
lru-cache: 11.5.3
parse5: 8.0.1
@@ -3820,7 +3831,7 @@ snapshots:
w3c-xmlserializer: 6.0.0
webidl-conversions: 8.0.1
whatwg-mimetype: 5.0.0
whatwg-url: 17.3.0
whatwg-url: 17.3.0(@noble/[email protected])
xml-name-validator: 5.0.0
transitivePeerDependencies:
- '@noble/hashes'
@@ -4241,7 +4252,7 @@ snapshots:
jiti: 2.7.0
yaml: 2.9.1
[email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])):
[email protected](@types/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])):
dependencies:
'@types/chai': 5.2.3
'@vitest/mocker': 5.0.5([email protected](@types/[email protected])([email protected])([email protected]))
@@ -4259,7 +4270,7 @@ snapshots:
why-is-node-running: 3.2.1
optionalDependencies:
'@types/node': 26.6.5
jsdom: 30.1.3
jsdom: 30.1.3(@noble/[email protected])
transitivePeerDependencies:
- msw
@@ -4275,9 +4286,9 @@ snapshots:
[email protected]: {}
[email protected]:
[email protected](@noble/[email protected]):
dependencies:
'@exodus/bytes': 1.16.0
'@exodus/bytes': 1.16.0(@noble/[email protected])
tr46: 7.0.0
webidl-conversions: 8.0.1
transitivePeerDependencies:
+225
Переглянути файл
@@ -0,0 +1,225 @@
// @vitest-environment node
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
BIN_MARK,
blake3Hex16,
buildSshArgs,
cleanLocalDogfoodServers,
extractFramedBinary,
formatSshConnectionError,
isRustVersionAtLeast,
loadSshConfigs,
normalizeRemotePlatform,
parseDogfoodRemoteArgs,
parseRunningServerPids,
parseToml,
readWorkspaceMetadata,
resolveAppDirs,
resolveSshConfig,
stageLocalDogfoodServer,
workspaceTarArgs,
} from "./dogfood-remote.ts";
function blake3TestInput(length: number): Uint8Array {
const buf = new Uint8Array(length);
for (let i = 0; i < length; i++) {
buf[i] = i % 251;
}
return buf;
}
describe("dogfood:remote", () => {
it("computes the 16-character BLAKE3 build_id expected by remote_dev::ensure_server", () => {
// Reference vector (input[i] = i % 251, 2049 bytes -> multi-chunk tree) matching `blake3::hash(bytes).to_hex()[..16]`.
expect(blake3Hex16(blake3TestInput(2049))).toBe("5f4d72f40d7a5f82");
});
it("parses both UI inline-table and [[ssh.configs]] TOML settings formats", () => {
const temp = mkdtempSync(join(tmpdir(), "openidea-dogfood-remote-"));
try {
const configDir = join(temp, "config");
mkdirSync(configDir, { recursive: true });
writeFileSync(
join(configDir, "settings.toml"),
[
"# Global settings written by Settings › Tools › SSH Configurations",
"[appearance]",
'locale = "en"',
"",
"[ssh]",
'configs = [{ id = "cfg-1", name = "my-remote", host = "remote-host.example.com", port = 2222, user = "alice", auth = "keyPair", keyFile = "~/.ssh/id_ed25519", saveSecret = false }]',
"",
].join("\n"),
);
const loaded = loadSshConfigs(configDir);
expect(loaded).toEqual([
{
id: "cfg-1",
name: "my-remote",
host: "remote-host.example.com",
port: 2222,
user: "alice",
auth: "keyPair",
keyFile: "~/.ssh/id_ed25519",
},
]);
const resolved = resolveSshConfig(loaded, "my-remote");
expect(buildSshArgs(resolved, ["StrictHostKeyChecking=no"], "/Users/alice")).toEqual([
"-p",
"2222",
"-l",
"alice",
"-i",
join("/Users/alice", ".ssh", "id_ed25519"),
"-o",
"ConnectTimeout=10",
"-o",
"StrictHostKeyChecking=no",
"--",
"remote-host.example.com",
]);
expect(() => resolveSshConfig(loaded, "missing-box")).toThrow(/Available SSH configurations: my-remote/);
const tableDoc = parseToml(
["[[ssh.configs]]", 'name = "alt-remote"', 'host = "alt.example.com"', 'user = "bob"', 'auth = "openSsh"'].join(
"\n",
),
);
expect(tableDoc).toEqual({
ssh: {
configs: [{ name: "alt-remote", host: "alt.example.com", user: "bob", auth: "openSsh" }],
},
});
} finally {
rmSync(temp, { recursive: true, force: true });
}
});
it("resolves config and custom local-data directories like ide_host::data_dirs", () => {
const temp = mkdtempSync(join(tmpdir(), "openidea-dirs-"));
try {
const cfgRoot = join(temp, "cfg");
const customLocalRoot = join(temp, "custom-caches");
mkdirSync(join(cfgRoot, "ai.l0ng.openidea"), { recursive: true });
writeFileSync(join(cfgRoot, "ai.l0ng.openidea", "local-data-dir.txt"), `${customLocalRoot}\n`);
expect(
resolveAppDirs({
platform: "darwin",
env: { OPENIDEA_CONFIG_DIR: cfgRoot },
home: "/Users/alice",
}),
).toEqual({
configDir: join(cfgRoot, "ai.l0ng.openidea"),
localDataDir: join(customLocalRoot, "ai.l0ng.openidea"),
});
} finally {
rmSync(temp, { recursive: true, force: true });
}
});
it("parses CLI flags and normalizes remote uname platforms", () => {
expect(
parseDogfoodRemoteArgs(["--", "my-remote", "--install-rust", "--restart", "--ssh-opt", "Port=2222"]),
).toEqual({
remoteName: "my-remote",
clean: false,
installRust: true,
restart: "always",
sshOpts: ["Port=2222"],
});
expect(parseDogfoodRemoteArgs(["--clean"])).toEqual({
remoteName: undefined,
clean: true,
installRust: false,
restart: "prompt",
sshOpts: [],
});
expect(() => parseDogfoodRemoteArgs(["my-remote", "--restart", "--no-restart"])).toThrow(/Cannot pass both/);
expect(() => parseDogfoodRemoteArgs([])).toThrow(/Usage:/);
expect(normalizeRemotePlatform("Linux x86_64\n")).toEqual({ os: "linux", arch: "x86_64" });
expect(normalizeRemotePlatform("Linux aarch64")).toEqual({ os: "linux", arch: "aarch64" });
expect(normalizeRemotePlatform("Darwin arm64")).toEqual({ os: "macos", arch: "aarch64" });
});
it("handles connection errors, Rust version checks, and running openidea-server PID detection", () => {
const repoRoot = join(import.meta.dirname, "..");
const meta = readWorkspaceMetadata(repoRoot);
expect(meta.version).toMatch(/^\d+\.\d+\.\d+/);
expect(meta.rustVersion).toMatch(/^\d+\.\d+/);
expect(isRustVersionAtLeast("rustc 1.96.0 (0000000 2026-06-01)", "1.96")).toBe(true);
expect(isRustVersionAtLeast("rustc 1.100.0-nightly (abcdef0 2026-11-01)", "1.96")).toBe(true);
expect(isRustVersionAtLeast("rustc 1.75.0 (82e1608df 2023-12-21)", "1.96")).toBe(false);
expect(isRustVersionAtLeast("no-rustc", "1.96")).toBe(false);
const errMsg = formatSshConnectionError(
"my-remote",
"[email protected]:22",
"Warning: Permanently added 'remote-host.example.com' (ED25519) to the list of known hosts.\nssh: connect to host remote-host.example.com port 22: Connection refused\n",
255,
);
expect(errMsg).toContain("Cannot connect to SSH remote 'my-remote' ([email protected]:22)");
expect(errMsg).toContain("Connection refused");
expect(errMsg).not.toContain("Permanently added");
const psText = [
" 101 /bin/bash",
" 4321 /home/alice/.openidea/server/0.1.50/42bd8ae098588d22/openidea-server --stdio",
" 4399 openidea-server --stdio",
" 4500 grep openidea-server",
].join("\n");
expect(parseRunningServerPids(psText)).toEqual([4321, 4399]);
});
it("backs up an existing cached release server on stage and restores it on --clean", () => {
const temp = mkdtempSync(join(tmpdir(), "openidea-stage-"));
try {
const serverDir = join(temp, "server", "0.1.50", "linux-aarch64");
mkdirSync(serverDir, { recursive: true });
const binPath = join(serverDir, "openidea-server");
writeFileSync(binPath, "official-release-binary");
const dogfoodBytes = Buffer.from("dogfood-server-binary-v1");
const id1 = blake3Hex16(dogfoodBytes);
stageLocalDogfoodServer(temp, "0.1.50", "linux", "aarch64", dogfoodBytes, id1);
expect(readFileSync(binPath, "utf8")).toBe("dogfood-server-binary-v1");
// A second dogfood build must keep the original release backup intact.
const dogfoodBytes2 = Buffer.from("dogfood-server-binary-v2");
const id2 = blake3Hex16(dogfoodBytes2);
stageLocalDogfoodServer(temp, "0.1.50", "linux", "aarch64", dogfoodBytes2, id2);
expect(readFileSync(binPath, "utf8")).toBe("dogfood-server-binary-v2");
const cleaned = cleanLocalDogfoodServers(temp, "0.1.50", "linux-aarch64");
expect(cleaned).toEqual([{ platformKey: "linux-aarch64", buildId: id2, restoredRelease: true }]);
expect(existsSync(binPath)).toBe(true);
expect(readFileSync(binPath, "utf8")).toBe("official-release-binary");
} finally {
rmSync(temp, { recursive: true, force: true });
}
});
it("strips login shell banners before the framed binary stream and verifies SHA-256", () => {
const payload = Buffer.from([0x7f, 0x45, 0x4c, 0x46, 1, 2, 3, 4]);
const sha = createHash("sha256").update(payload).digest("hex");
const framed = Buffer.concat([Buffer.from(`Welcome to Ubuntu!\n${BIN_MARK}${sha}\n`, "utf8"), payload]);
expect(extractFramedBinary(framed)).toEqual(payload);
expect(() => extractFramedBinary(Buffer.from(`${BIN_MARK}${"0".repeat(64)}\ncorrupt`))).toThrow(/SHA-256 mismatch/);
});
it("anchors tar Cargo target exclusions so nested source folders like crates/ide-ssh/src/target stay included", () => {
const args = workspaceTarArgs();
expect(args).not.toContain("--exclude=target");
expect(args).toContain("--exclude=plugins/target");
expect(args).toContain("crates");
expect(args).toContain("generators");
});
});
File diff suppressed because it is too large. Load diff
+21
Переглянути файл
@@ -79,6 +79,27 @@ 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",
},
},
{
fixture: "mocha-app",
setup: npmInstall,
tests: {
config: "npm:test",
failing: (c) => env(c, { OPENIDEA_FAIL: "1" }),
passed: 4,
failed: "intentionally fails (set OPENIDEA_FAIL=1)",
file: "test/pricing.spec.js",
},
},
],
python: {
fixture: "python-app",
+3
Переглянути файл
@@ -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
+75
Переглянути файл
@@ -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, 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.
@@ -2898,6 +2904,10 @@ export type AgentSkill_Deserialize = {
userInvocable?: boolean,
/** True when frontmatter sets `disable-model-invocation: true` (defaults to `slashOnly`). */
disableModelInvocation?: boolean,
/** True when frontmatter sets `context: fork` (passed through natively to supporting CLIs). */
contextFork?: boolean,
/** Optional `paths` / `globs` patterns from frontmatter (passed through natively to supporting CLIs). */
paths?: string[],
/** The `SKILL.md` passes validation (`name` matches its folder, `description` present). */
valid: boolean,
/** What validation found (`name` mismatch, missing or over-long description…). */
@@ -2920,6 +2930,10 @@ export type AgentSkill_Serialize = {
userInvocable: boolean,
/** True when frontmatter sets `disable-model-invocation: true` (defaults to `slashOnly`). */
disableModelInvocation: boolean,
/** True when frontmatter sets `context: fork` (passed through natively to supporting CLIs). */
contextFork: boolean,
/** Optional `paths` / `globs` patterns from frontmatter (passed through natively to supporting CLIs). */
paths?: string[],
/** The `SKILL.md` passes validation (`name` matches its folder, `description` present). */
valid: boolean,
/** What validation found (`name` mismatch, missing or over-long description…). */
@@ -7791,6 +7805,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`. */
@@ -10939,6 +10965,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. */
@@ -11819,6 +11886,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" } |
+2 -2
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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;
}
+146 -2
Переглянути файл
@@ -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";
@@ -46,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 }));
@@ -149,4 +157,140 @@ 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());
});
it("displays context: fork and paths badges and expands paths in the inspector", async () => {
const forked = [
state("verify-ux", "workspace", "auto", {
contextFork: true,
paths: ["src/**/*.tsx", "e2e/*.spec.ts"],
}),
];
render(<SkillsPage backend={{ list: vi.fn(async () => forked), setMode: vi.fn(async () => forked) }} />);
await waitFor(() => expect(screen.getByText("verify-ux")).toBeInTheDocument());
expect(screen.getByText("context: fork")).toBeInTheDocument();
expect(screen.getByText("paths (2)")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: /^verify-ux/ }));
expect(await screen.findByText("src/**/*.tsx, e2e/*.spec.ts")).toBeInTheDocument();
});
});
+38
Переглянути файл
@@ -13,6 +13,7 @@ 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,
@@ -50,11 +51,13 @@ function groupsForTab(tab: SourceTab): readonly SkillSource[] {
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.
@@ -141,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>
@@ -269,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>
);
}
@@ -342,6 +362,16 @@ function SkillCard({
{skill.alsoIn?.map((s) => tx(SKILL_SOURCE_GROUPS[s].label)).join(", ")}
</span>
)}
{skill.contextFork && (
<span className={page.tag} title={tx("Runs in a subagent where supported (context: fork)")}>
context: fork
</span>
)}
{(skill.paths?.length ?? 0) > 0 && (
<span className={page.tag} title={skill.paths?.join(", ")}>
{formatMessage(tx("paths ({count})"), { count: skill.paths?.length ?? 0 })}
</span>
)}
{!skill.valid && (
<span className={clsx(page.tag, page.tagWarning)}>
<T>Invalid SKILL.md</T>
@@ -406,6 +436,14 @@ function SkillCard({
</span>
</>
)}
{(skill.paths?.length ?? 0) > 0 && (
<>
<span className={page.metaLabel}>
<T>Paths</T>
</span>
<span className={page.metaValue}>{skill.paths?.join(", ")}</span>
</>
)}
<span className={page.metaLabel}>
<T>Validation</T>
</span>
+25
Переглянути файл
@@ -165,6 +165,31 @@ describe("SkillsPicker", () => {
await waitFor(() => expect(screen.getByRole("button", { name: "Skills" })).toHaveTextContent("Skills3/5"));
});
it("shows fork and paths pills on skills with context: fork and paths frontmatter", async () => {
const richSkills: AgentSkillState[] = [
{
skill: {
name: "verify-ux",
description: "Verify UX layouts",
path: "/ws/.agents/skills/verify-ux",
source: "workspace",
contextFork: true,
paths: ["src/**/*.tsx", "e2e/*.spec.ts"],
valid: true,
warnings: [],
},
mode: "auto",
origin: "none",
},
];
render(<Harness skills={richSkills} />);
fireEvent.click(screen.getByRole("button", { name: "Skills" }));
expect(await screen.findByText("fork")).toBeInTheDocument();
expect(screen.getByText("paths")).toBeInTheDocument();
expect(screen.getByTitle("Verify UX layouts · src/**/*.tsx, e2e/*.spec.ts")).toBeInTheDocument();
});
it("shows an empty state without skills", async () => {
render(<Harness skills={[]} />);
+5 -2
Переглянути файл
@@ -154,7 +154,8 @@ function GroupRows({
function SessionSkillRow({ item, onToggle }: { item: SessionSkillItem; onToggle: (enabled: boolean) => void }) {
const tx = useTx();
const description = item.state.skill.description;
const { skill } = item.state;
const description = skill.description;
return (
<PickerRow
name={item.name}
@@ -162,10 +163,12 @@ function SessionSkillRow({ item, onToggle }: { item: SessionSkillItem; onToggle:
<>
<ModePill mode={item.mode} />
{item.overridden && <PickerSessionPill />}
{skill.contextFork && <PickerPill>fork</PickerPill>}
{(skill.paths?.length ?? 0) > 0 && <PickerPill>paths</PickerPill>}
</>
}
sub={description || undefined}
subTitle={description}
subTitle={skill.paths?.length ? `${description} · ${skill.paths.join(", ")}` : description}
controls={
item.locked ? (
<PickerPill>
+2 -2
Переглянути файл
@@ -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 {
+23 -1
Переглянути файл
@@ -5,18 +5,40 @@
*/
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. */
+2 -2
Переглянути файл
@@ -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
Переглянути файл
@@ -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
+4 -4
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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}>
+5 -5
Переглянути файл
@@ -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
Переглянути файл
@@ -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}
+2 -2
Переглянути файл
@@ -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>
+2 -2
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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,
// node:test and Mocha 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" || framework === "mocha"
? 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`,
});
});
}
+9 -3
Переглянути файл
@@ -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";
@@ -133,9 +134,9 @@ function rustTargets(lines: string[], relPath: string): RunTarget[] {
);
}
/** Jest / Vitest `describe` / `test` / `it`, and Playwright's `test.describe` and modifiers. */
/** Jest / Vitest `describe` / `test` / `it` (Mocha's `specify` too), and Playwright's `test.describe` and modifiers. */
const JS_RE =
/^(\s*)(test\.describe|describe|suite|context|test|it)\b(?:\.(?:only|skip|todo|concurrent|failing|sequential|fixme|fail|serial|parallel))*(\.each\s*(?:\(.*?\)|`[^`]*`))?\s*\(\s*(['"`])((?:\\.|(?!\4).)*)\4/;
/^(\s*)(test\.describe|describe|suite|context|test|it|specify)\b(?:\.(?:only|skip|todo|concurrent|failing|sequential|fixme|fail|serial|parallel))*(\.each\s*(?:\(.*?\)|`[^`]*`))?\s*\(\s*(['"`])((?:\\.|(?!\4).)*)\4/;
function jsTargets(lines: string[]): RunTarget[] {
const out: RunTarget[] = [];
@@ -380,7 +381,8 @@ export function detectRunTargets(text: string, relPath: string, django = false):
case "rust":
return rustTargets(lines, relPath);
case "js":
return /\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)__tests__\//.test(relPath) ? jsTargets(lines) : [];
// `test/`: where Mocha (and `node --test`) look for tests by default, whatever the file's name.
return /\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)(__tests__|test)\//.test(relPath) ? jsTargets(lines) : [];
case "python":
return pythonTargets(lines).filter(
(t) =>
@@ -473,6 +475,10 @@ 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)) };
if (frameworkFor(file) === "mocha") return named([...file.args, "--grep", jsNamePattern(target)]);
switch (file.kind) {
case "dotnet-test": {
const methods =
+15 -1
Переглянути файл
@@ -4,6 +4,9 @@ import { cargoParser } from "./cargo";
import { goParser } from "./go";
import { jsParser } from "./js";
import { jvmParser } from "./jvm";
import { withMochaHook } from "./mocha";
import { withNodeTestReporter } from "./nodeTest";
import { recordsParser } from "./records";
import { phpunitParser, withTeamcity } from "./phpunit";
import { playwrightParser } from "./playwright";
import { pytestParser } from "./pytest";
@@ -24,6 +27,7 @@ export {
phpunitParser,
playwrightParser,
pytestParser,
recordsParser,
rubyParser,
unittestParser,
zigParser,
@@ -41,6 +45,8 @@ export type Framework =
| "cargo"
| "js"
| "playwright"
| "node-test"
| "mocha"
| "pytest"
| "unittest"
| "phpunit"
@@ -51,12 +57,15 @@ 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";
if (config.testRunner === "mocha" || /(^|[\s/\\])_?mocha(\.cmd|\.js)?(\s|$)/.test(cmd)) return "mocha";
switch (config.kind) {
case "dotnet-test":
return "dotnet";
@@ -120,6 +129,8 @@ 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) === "mocha") return { ...config, env: withMochaHook(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 +173,9 @@ export function createTestParser(config: FrameworkConfig): TestOutputParser {
return jsParser();
case "playwright":
return playwrightParser();
case "node-test":
case "mocha":
return recordsParser();
case "pytest":
return pytestParser();
case "unittest":
+119
Переглянути файл
@@ -0,0 +1,119 @@
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 { failedTestPaths, rerunFailedConfigs } 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 `mocha` (detection records the runner). */
const script = cfg({ id: "npm:test", kind: "npm", command: "npm", args: ["run", "test"], testRunner: "mocha" });
// `mocha` (10.8, spec reporter) with the IDE's hook, as printed.
const OUTPUT = String.raw`
pricing
withTax
✔ adds the rate
@@openidea:test@@{"path":["test/pricing.spec.js","pricing","withTax","adds the rate"],"status":"passed","ms":0,"line":6,"col":5}
1) intentionally fails (set OPENIDEA_FAIL=1)
@@openidea:test@@{"path":["test/pricing.spec.js","pricing","intentionally fails (set OPENIDEA_FAIL=1)"],"status":"failed","ms":1,"line":25,"col":3,"error":"AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:\n\n11 !== 11.5\n\n at Context.<anonymous> (file:///work/shop/test/pricing.spec.js:27:12)"}
- later
@@openidea:test@@{"path":["test/pricing.spec.js","pricing","later"],"status":"skipped","line":29,"col":3}
1 passing (3ms)
1 pending
1 failing
`;
function results(text: string) {
const r = new TestResults();
r.apply(parseAll(createTestParser(script), text));
return r;
}
describe("Mocha runs", () => {
it("are recognised by the recorded runner or the command line", () => {
expect(frameworkFor(script)).toBe("mocha");
expect(frameworkFor(cfg({ id: "x", kind: "node", command: "npx", args: ["mocha", "--recursive"] }))).toBe("mocha");
expect(frameworkFor(cfg({ id: "x", kind: "shell", command: "./node_modules/.bin/_mocha", args: [] }))).toBe(
"mocha",
);
expect(frameworkFor(cfg({ id: "x", kind: "node", command: "node", args: ["mocha.config.js"] }))).not.toBe("mocha");
});
it("load the IDE's hook through NODE_OPTIONS, once", () => {
const launched = withTestReporting({ ...script, env: { NODE_OPTIONS: "--enable-source-maps" } });
const [own, hook] = launched.env.NODE_OPTIONS!.split(" ");
expect(own).toBe("--enable-source-maps");
expect(hook).toMatch(/^--import=data:text\/javascript;base64,/);
expect(withTestReporting(launched).env).toEqual(launched.env);
expect(launched.args).toEqual(script.args);
});
it("build the tree from the hook's records, with declaration lines and failures", () => {
const r = results(OUTPUT);
expect(r.counts()).toMatchObject({ passed: 1, failed: 1, skipped: 1 });
const adds = r.get(["test/pricing.spec.js", "pricing", "withTax", "adds the rate"].join("\u0000"))!;
expect(adds.location).toEqual({ path: "test/pricing.spec.js", line: 6, col: 5, resolve: "path" });
expect(nodeOutput(r.firstFailure()!).join("\n")).toContain("11 !== 11.5");
});
it("rerun failed tests by file and full title with --grep", async () => {
const [rerun] = await rerunFailedConfigs(
{ ...script, args: ["run", "test", "--", "--grep", "old"] },
failedTestPaths(results(OUTPUT)),
);
expect(rerun!.args).toEqual([
"run",
"test",
"--",
"test/pricing.spec.js",
"--grep",
"^(?:pricing intentionally fails \\(set OPENIDEA_FAIL=1\\))$",
]);
});
});
describe("Mocha gutter targets", () => {
const src = [
"describe('pricing', function () {", // 0
" specify('adds tax', function () {});", // 1
" context('bulk', function () {", // 2
" it('discounts', function () {});", // 3
" });",
"});",
].join("\n");
it("are found in test/ whatever the file's name, `specify` included", () => {
expect(detectRunTargets(src, "test/pricing.js").map((t) => [t.line, t.kind, t.path.join("/")])).toEqual([
[0, "suite", "pricing"],
[1, "test", "pricing/adds tax"],
[2, "suite", "pricing/bulk"],
[3, "test", "pricing/bulk/discounts"],
]);
expect(detectRunTargets(src, "lib/pricing.js")).toEqual([]);
});
it("run by file and full title", () => {
const targets = detectRunTargets(src, "test/pricing.js");
expect(targetConfig(targets[3]!, "test/pricing.js", [script], src)?.args).toEqual([
"run",
"test",
"--",
"test/pricing.js",
"--grep",
"^pricing bulk discounts$",
]);
});
});
+15
Переглянути файл
@@ -0,0 +1,15 @@
/**
* Mocha: the IDE's hook (`mochaHook.js`), imported through `NODE_OPTIONS`, prints a record per
* finished test (`records.ts`) next to the run's own reporter, whichever it is. Tests are selected
* with Mocha's own `--grep`.
*/
import HOOK_SOURCE from "./mochaHook.js?raw";
const HOOK = `--import=data:text/javascript;base64,${btoa(HOOK_SOURCE)}`;
/** `NODE_OPTIONS` with the IDE's hook added (once). */
export function withMochaHook(env: Record<string, string>): Record<string, string> {
const options = env.NODE_OPTIONS ?? "";
if (options.includes(HOOK)) return env;
return { ...env, NODE_OPTIONS: [options, HOOK].filter(Boolean).join(" ") };
}
+79
Переглянути файл
@@ -0,0 +1,79 @@
// The IDE's Mocha hook (`--import`, passed as a data: URL through NODE_OPTIONS): once Mocha is
// loaded, every test a run reports also prints a record (`records.ts`) next to the run's own
// reporter, with the line the test is declared on (Mocha reports none). Runs in the user's
// Node (20+), so plain ESM without dependencies; reporting must never break a test run.
import Module from "node:module";
import { relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const MARK = "@@openidea:test@@";
const DECLARED = Symbol("openidea.declared");
const FRAME = /(?:\(|\s)((?:file:\/\/\/?)?(?:[A-Za-z]:)?[^:()]+):(\d+):(\d+)\)?$/;
const fileOf = (path) => relative(process.cwd(), path).split("\\").join("/");
/** Where in `file` the code running now was called from: a test's declaration while Mocha loads the file. */
function declaredIn(file) {
for (const frame of (new Error().stack ?? "").split("\n").slice(1)) {
const m = FRAME.exec(frame);
if (!m) continue;
const path = m[1].startsWith("file:") ? fileURLToPath(m[1]) : m[1];
if (resolve(path) === file) return { line: Number(m[2]), col: Number(m[3]) };
}
return null;
}
function report(test, status, error) {
try {
if (!test.file) return;
const at = test[DECLARED];
const record = {
path: [fileOf(test.file), ...test.titlePath()],
status,
ms: test.duration,
line: at?.line,
col: at?.col,
error: error === undefined ? undefined : String((error && error.stack) || error),
};
process.stdout.write(`${MARK}${JSON.stringify(record)}\n`);
} catch {
// A test object without its usual shape (a plugin's): no record.
}
}
function watch(Mocha) {
const addTest = Mocha.Suite.prototype.addTest;
Mocha.Suite.prototype.addTest = function (test) {
try {
if (test && test.file) test[DECLARED] = declaredIn(resolve(test.file));
} catch {
// No declaration line.
}
return addTest.call(this, test);
};
const run = Mocha.Runner.prototype.run;
Mocha.Runner.prototype.run = function (...args) {
this.on("pass", (test) => report(test, "passed"));
this.on("pending", (test) => report(test, "skipped"));
// A failing hook fails the test it ran for, or reports as itself.
this.on("fail", (runnable, error) =>
report(runnable.type === "hook" ? (runnable.ctx?.currentTest ?? runnable) : runnable, "failed", error),
);
return run.apply(this, args);
};
}
const load = Module._load;
let watching = false;
Module._load = function (...args) {
const exports = load.apply(this, args);
if (!watching && typeof exports === "function" && exports.Runner && exports.Suite && exports.reporters) {
watching = true;
try {
watch(exports);
} catch {
// Another Mocha than expected: the run goes on without records.
}
}
return exports;
};
+136
Переглянути файл
@@ -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
Переглянути файл
@@ -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(" ") };
}
+48
Переглянути файл
@@ -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
Переглянути файл
@@ -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"));
}
}
+23
Переглянути файл
@@ -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,28 @@ 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 "mocha": {
// Mocha's `--grep` matches a test's full title: its describe chain and name, space separated.
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 { before, after } = splitDashDash(config.args);
const flags = ["-g", "--grep", "-f", "--fgrep"];
const base = after === null ? dropFlag(before, flags) : [...before, "--", ...dropFlag(after, flags)];
const grep = names.length ? ["--grep", `^(?:${names.map(escapeRegExp).join("|")})$`] : [];
args = appendScriptArgs(config.command, base, [...files, ...grep]);
break;
}
case "pytest":
args = pytestArgs(config.args, paths);
break;
+2 -2
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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>
+3 -3
Переглянути файл
@@ -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}>
+2 -2
Переглянути файл
@@ -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
Переглянути файл
@@ -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>
+3 -3
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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])}
/>
)}
+20 -1
Переглянути файл
@@ -405,9 +405,12 @@
.subject {
flex: 0 1 auto;
min-width: var(--log-subject-min);
color: var(--fg);
}
.subjectText {
display: block;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg);
}
.headSubject {
font-weight: 600;
@@ -437,6 +440,22 @@
flex: none;
max-width: calc(100% - var(--log-subject-min) - var(--space-1-5));
}
.commitText > .refsCompact {
flex: 0 1 auto;
max-width: calc(100% / 3);
}
.commitText:has(> .refsCompact) > .subject {
/* Protect a short subject while leaving room for compact reference names. */
flex: 0 1000 max-content;
min-width: auto;
width: min(75%, 24ch);
}
.commitText > .refs .ref {
font-size: var(--fs-small);
}
.refsCompact .ref {
min-width: 11px;
}
.refsLeft {
margin-left: 0;
}
+2 -2
Переглянути файл
@@ -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}
+1 -1
Переглянути файл
@@ -37,7 +37,7 @@ export function RefLabels({
}) {
const labels = refLabels(refs, { compact, tagNames }, remoteNames);
return (
<span className={clsx(styles.refs, left && styles.refsLeft)}>
<span className={clsx(styles.refs, compact && styles.refsCompact, left && styles.refsLeft)}>
{labels.map((l) => (
<span key={`${l.kind}:${l.title}`} className={clsx(styles.ref, REF_KIND_CLASS[l.kind])} title={l.title}>
{l.text && <span className={styles.refText}>{l.text}</span>}
+3 -1
Переглянути файл
@@ -134,7 +134,9 @@ function CommitRowView({
setTooltip(false);
}}
>
<IssueText text={c.summary} />
<span className={styles.subjectText}>
<IssueText text={c.summary} />
</span>
</span>
{!opts.refsOnLeft && refs}
</span>
+2 -2
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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}
+12 -2
Переглянути файл
@@ -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,10 @@ describe("catalogs", () => {
"Claude Code",
"GitHub Copilot",
"Codex",
"SKILL.md",
"context: fork",
"paths ({count})",
"paths",
"Cursor",
"PHP",
"SQL",
+17 -2
Переглянути файл
@@ -174,7 +174,8 @@ export function useT(): Translate {
*
* As a tag it translates text built at runtime: `` tx`Remove data source '${name}'?` ``
* looks up `"Remove data source '{name}'?"` (whatever the placeholder names) and fills
* in the values, each translated as text when the catalog has it. The result is
* in the values as written: a file called `tasks` stays `tasks`. UI text among the
* values is marked with {@link txPart} to be translated as well. The result is
* remembered, so the UI primitives, which pass their strings through `tx` as they
* render, translate it again after a locale change or once the catalog has loaded.
*/
@@ -221,6 +222,17 @@ export function useGivenTx(): typeof tx {
return useContext(VerbatimTextContext) ? asWritten : bound;
}
/** UI text filling a `tx` template, translated with it: `` tx`Rename ${txPart(kind)} '${name}'` ``. */
class TxPart {
constructor(readonly text: string) {}
toString() {
return this.text;
}
}
/** Marks a `tx` tag value as UI text to translate; other values are inserted as written. */
export const txPart = (text: string): unknown => new TxPart(text);
function translateSource(texts: Catalog, text: string | TemplateStringsArray | undefined, values: unknown[]) {
// A tag without `${}` spells out its whole text, which is looked up as written.
if (text !== undefined && typeof text !== "string" && !values.length) text = text[0]!;
@@ -262,7 +274,10 @@ const interleave = (strings: readonly string[], parts: readonly string[]) =>
strings.reduce((out, s, i) => out + parts[i - 1] + s);
function formatBuilt(texts: Catalog, { strings, values }: Built): string {
const parts = values.map((v) => (typeof v === "string" ? (texts[v] ?? rebuild(texts, v) ?? v) : String(v)));
const parts = values.map((v) => {
if (v instanceof TxPart) return texts[v.text] ?? rebuild(texts, v.text) ?? v.text;
return typeof v === "string" ? (rebuild(texts, v) ?? v) : String(v);
});
const shape = shapesOf(texts).get(strings.join("{}"));
if (!shape) return interleave(strings, parts);
const params: MessageParams = {};
+2 -2
Переглянути файл
@@ -18,7 +18,7 @@ import {
type InspectionRef,
type ProfileOverrides,
} from "./inspections";
import { tx } from "@/platform/i18n";
import { tx, txPart } from "@/platform/i18n";
/** Menu rows (structurally `@/ui` `MenuItem`s). */
export type ControlItem =
@@ -107,7 +107,7 @@ export function problemControls(inspection: InspectionRef): ControlItem[] {
return [
{
id: "inspection.disable",
label: tx`Disable Inspection '${inspection.name}'`,
label: tx`Disable Inspection '${txPart(inspection.name)}'`,
verbatim: true,
run: () => report(disableInspection(inspection.id)),
},
+2
Переглянути файл
@@ -428,6 +428,8 @@ export const vscodeMacos: Record<string, string[]> = {
"agents.cycleEffort": ["Alt+T"],
"agents.showToolWindow": [],
"agents.sendToAgent": [],
// Python Console: VS Code's Shift+Enter would shadow typing in Python files, so unbound.
"python.console.executeSelection": [],
// Search fields (find bar, Find in Files): last, so they win over editor keys while one is focused.
"find.openInWindow": ["Alt+F7"],
"find.field.newLine": ["Meta+Shift+Enter"],
+31
Переглянути файл
@@ -3023,6 +3023,37 @@
"Configure skills for this session": "Configure skills for this session",
"No skills found in .agents/skills, .openidea/skills, ~/.agents/skills, or the CLI folders of Claude Code, GitHub Copilot, Codex, and Cursor.": "No skills found in .agents/skills, .openidea/skills, ~/.agents/skills, or the CLI folders of Claude Code, GitHub Copilot, Codex, and Cursor.",
"This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling.": "This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling.",
"Install Skill…": "Install Skill…",
"Install Agent Skill": "Install Agent Skill",
"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.": "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.",
"owner/repo, owner/repo@skill, or GitHub URL": "owner/repo, owner/repo@skill, or GitHub URL",
"Skill repository": "Skill repository",
"Fetch": "Fetch",
"Install location": "Install location",
"User (~/.agents/skills)": "User (~/.agents/skills)",
"Workspace (.agents/skills)": "Workspace (.agents/skills)",
"SKILL.md": "SKILL.md",
"{count} skills found": "{count} skills found",
"Available skills": "Available skills",
"Scanning SKILL.md and bundled files…": "Scanning SKILL.md and bundled files…",
"Static scan passed: no hidden Unicode, out-of-root symlinks, shell tool grants, or executable scripts detected.": "Static scan passed: no hidden Unicode, out-of-root symlinks, shell tool grants, or executable scripts detected.",
"Static security scan warnings": "Static security scan warnings",
"Static security scan found {count} warnings": "Static security scan found {count} warnings",
"Hidden Unicode": "Hidden Unicode",
"Out-of-root symlink": "Out-of-root symlink",
"Executable script": "Executable script",
"Shell tool grant": "Shell tool grant",
"I reviewed these warnings and want to install this skill": "I reviewed these warnings and want to install this skill",
"Replace existing {name} folder in the selected location": "Replace existing {name} folder in the selected location",
"Skill preview": "Skill preview",
"Files ({count})": "Files ({count})",
"Symlink": "Symlink",
"Runs in a subagent where supported (context: fork)": "Runs in a subagent where supported (context: fork)",
"context: fork": "context: fork",
"paths ({count})": "paths ({count})",
"fork": "fork",
"paths": "paths",
"Paths": "Paths",
"Cannot find the source of {0}": "Cannot find the source of {0}",
"JavaScript and TypeScript": "JavaScript and TypeScript",
"Global function": "Global function",
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff. Show more