mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-22 09:39:27 -10:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9b59961127 | ||
|
|
8e541d5b45 | ||
|
|
87c4659547 | ||
|
|
3475dbd688 | ||
|
|
0800e8445f |
No files matched your search
Generated
+1
@@ -4146,6 +4146,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
name = "ide-agent"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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};
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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,
|
||||
|
||||
@@ -244,12 +244,30 @@ pub(crate) fn is_test_script(name: &str) -> bool {
|
||||
}
|
||||
|
||||
/// The test runner a `package.json` script starts, when its output and test selection differ
|
||||
/// from Jest / Vitest's: `playwright test`.
|
||||
/// from Jest / Vitest's: `playwright test`, or `node --test` (`tsx --test`) with Node's own
|
||||
/// reporters (the IDE adds its reporter next to them, which a reporter chosen here would clash with).
|
||||
fn script_test_runner(script: &str) -> Option<&'static str> {
|
||||
let tokens: Vec<&str> = script.split(|c: char| c.is_whitespace() || matches!(c, '&' | '|' | ';')).collect();
|
||||
tokens.windows(2).any(|w| w[0] == "playwright" && w[1] == "test").then_some("playwright")
|
||||
if tokens.windows(2).any(|w| w[0] == "playwright" && w[1] == "test") {
|
||||
return Some("playwright");
|
||||
}
|
||||
let node = tokens.iter().position(|t| matches!(*t, "node" | "tsx"))?;
|
||||
// Node's own options: up to the script (`node server.js --test` passes `--test` to the program).
|
||||
let mut options = Vec::new();
|
||||
for t in &tokens[node + 1..] {
|
||||
let value = options.last().is_some_and(|o| NODE_VALUE_OPTIONS.contains(o));
|
||||
if !value && !t.starts_with('-') {
|
||||
break;
|
||||
}
|
||||
options.push(*t);
|
||||
}
|
||||
(options.contains(&"--test") && !options.iter().any(|t| t.starts_with("--test-reporter"))).then_some("node-test")
|
||||
}
|
||||
|
||||
/// Node options whose value is the next argument.
|
||||
const NODE_VALUE_OPTIONS: &[&str] =
|
||||
&["-r", "--require", "--import", "--loader", "--experimental-loader", "-C", "--conditions", "--env-file"];
|
||||
|
||||
const PLAYWRIGHT_CONFIGS: &[&str] = &[
|
||||
"playwright.config.ts",
|
||||
"playwright.config.js",
|
||||
|
||||
@@ -76,6 +76,22 @@ fn playwright_scripts_and_configs() {
|
||||
assert_eq!(site.debug_adapter.as_deref(), Some("js-debug"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_test_scripts() {
|
||||
let dir = project(&[(
|
||||
"package.json",
|
||||
r#"{"scripts":{"test":"node --import tsx --test","check":"tsx --test src/","tap":"node --test --test-reporter=tap","start":"node server.js --test"}}"#,
|
||||
)]);
|
||||
let c = detect(dir.path());
|
||||
assert_eq!(find(&c, "npm:test").extras.test_runner.as_deref(), Some("node-test"));
|
||||
let check = find(&c, "npm:check");
|
||||
assert!(check.is_test);
|
||||
assert_eq!(check.extras.test_runner.as_deref(), Some("node-test"));
|
||||
// A reporter of its own: run as written, without the IDE's.
|
||||
assert_eq!(find(&c, "npm:tap").extras.test_runner, None);
|
||||
assert_eq!(find(&c, "npm:start").extras.test_runner, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_manager_selection() {
|
||||
for (lock, pm) in [("yarn.lock", "yarn"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("package-lock.json", "npm")] {
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -66,7 +66,7 @@ Detected test configurations show results in the tree automatically. For your ow
|
||||
| **Rerun** (in the Run tool window) | `⌘R` | `Ctrl+F5` |
|
||||
| **Rerun Failed Tests** | — | — |
|
||||
|
||||
**Rerun Failed Tests** (in the Run tool window toolbar and Find Action) runs only the tests that failed in the last run, using each tool's filter syntax. It works for Cargo, Jest / Vitest, Playwright, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks.
|
||||
**Rerun Failed Tests** (in the Run tool window toolbar and Find Action) runs only the tests that failed in the last run, using each tool's filter syntax. It works for Cargo, Jest / Vitest, Playwright, `node --test`, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks.
|
||||
|
||||
## Navigate between code and tests
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ On both pages, **Formatting provider** chooses between **Automatic (language ser
|
||||
|
||||
OpenIDEA detects run configurations when the project opens:
|
||||
|
||||
- One configuration per `package.json` script (`npm run build`, `pnpm run dev`, …), for the root package, nested packages and workspace members. Scripts named `test`, `jest`, `vitest` or `test:*`, and scripts that run `playwright test`, are test configurations.
|
||||
- One configuration per `package.json` script (`npm run build`, `pnpm run dev`, …), for the root package, nested packages and workspace members. Scripts named `test`, `jest`, `vitest` or `test:*`, and scripts that run `playwright test` or `node --test`, are test configurations.
|
||||
- `playwright test` (through `npx`) for a package with a `playwright.config.*` that no script runs.
|
||||
- One per task in `deno.json` / `deno.jsonc` (`deno task <name>`).
|
||||
|
||||
@@ -86,7 +86,7 @@ In `package.json`, the gutter shows run icons on each `scripts` entry to run or
|
||||
- Any other `.js` file runs with `node` (with `deno run` or `bun run` in a project with `deno.json` or `bun.lock`).
|
||||
- A `.ts` file runs with Node.js directly on 22.18+ / 23.6+, with `--experimental-strip-types` on 22.6–22.17 and 23.0–23.5, else through `tsx` or `ts-node`.
|
||||
|
||||
Jest, Vitest and Playwright Test output is turned into the test tree, with **Rerun Failed Tests**. Playwright runs report through its `list` reporter unless the configuration names another; a test in the gutter runs by its line (`file:line`), and runs with several projects show each project under its file. **Run with Coverage** works for scripts that run `vitest` or `jest` (Vitest needs a coverage provider such as `@vitest/coverage-v8`; the IDE offers to add it) and for `node` / `tsx` / `ts-node` runs through `c8`. See [Testing](/en/guide/testing) and [Coverage](/en/guide/coverage).
|
||||
Jest, Vitest, Playwright Test and `node --test` output is turned into the test tree, with **Rerun Failed Tests**. Playwright runs report through its `list` reporter unless the configuration names another; a test in the gutter runs by its line (`file:line`), and runs with several projects show each project under its file. `node --test` runs report through the IDE's reporter next to `spec`, added to `NODE_OPTIONS` (a script that chooses its own `--test-reporter` runs without the tree); single tests and reruns are selected by full name (`--test-name-pattern`). **Run with Coverage** works for scripts that run `vitest` or `jest` (Vitest needs a coverage provider such as `@vitest/coverage-v8`; the IDE offers to add it) and for `node` / `tsx` / `ts-node` runs through `c8`. See [Testing](/en/guide/testing) and [Coverage](/en/guide/coverage).
|
||||
|
||||
## Debugging
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ RSpec 有自己的配置类型(**RSpec 测试**)和检测到的 `rspec` 配
|
||||
| **重新运行**(在“运行”工具窗口中) | `⌘R` | `Ctrl+F5` |
|
||||
| **重新运行失败的测试** | — | — |
|
||||
|
||||
**重新运行失败的测试**(在“运行”工具窗口工具栏和“查找操作”中)只运行上一次失败的测试,会按各个工具自己的过滤语法生成命令。支持 Cargo、Jest / Vitest、Playwright、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。
|
||||
**重新运行失败的测试**(在“运行”工具窗口工具栏和“查找操作”中)只运行上一次失败的测试,会按各个工具自己的过滤语法生成命令。支持 Cargo、Jest / Vitest、Playwright、`node --test`、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。
|
||||
|
||||
## 在代码和测试之间跳转
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript
|
||||
|
||||
打开项目时,OpenIDEA 会自动检测运行配置:
|
||||
|
||||
- 每个 `package.json` 脚本一个配置(`npm run build`、`pnpm run dev` 等),覆盖根包、嵌套包和 workspace 成员。名为 `test`、`jest`、`vitest` 或 `test:*` 的脚本,以及运行 `playwright test` 的脚本,是测试配置。
|
||||
- 每个 `package.json` 脚本一个配置(`npm run build`、`pnpm run dev` 等),覆盖根包、嵌套包和 workspace 成员。名为 `test`、`jest`、`vitest` 或 `test:*` 的脚本,以及运行 `playwright test` 或 `node --test` 的脚本,是测试配置。
|
||||
- 有 `playwright.config.*` 但没有脚本运行它的包:通过 `npx` 运行的 `playwright test`。
|
||||
- `deno.json` / `deno.jsonc` 中每个 task 一个配置(`deno task <name>`)。
|
||||
|
||||
@@ -86,7 +86,7 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript
|
||||
- 其他 `.js` 文件用 `node` 运行(项目含 `deno.json` 或 `bun.lock` 时改用 `deno run` 或 `bun run`)。
|
||||
- `.ts` 文件在 Node.js 22.18+ / 23.6+ 上直接运行,在 22.6–22.17 和 23.0–23.5 上加 `--experimental-strip-types`,更早的版本则通过 `tsx` 或 `ts-node` 运行。
|
||||
|
||||
Jest、Vitest 和 Playwright Test 的输出会解析成测试树,支持 **重新运行失败的测试**。Playwright 运行时使用它的 `list` 报告器(配置里指定了其他报告器时除外);从行号栏运行单个测试时按行号选择(`file:line`),有多个 project 的运行会在文件下按 project 分组。**使用覆盖率运行** 支持调用 `vitest` 或 `jest` 的脚本(Vitest 需要 `@vitest/coverage-v8` 之类的覆盖率 provider,缺失时 IDE 会提示添加),以及通过 `c8` 运行的 `node` / `tsx` / `ts-node`。详见[测试](/zh/guide/testing)和[覆盖率](/zh/guide/coverage)。
|
||||
Jest、Vitest、Playwright Test 和 `node --test` 的输出会解析成测试树,支持 **重新运行失败的测试**。Playwright 运行时使用它的 `list` 报告器(配置里指定了其他报告器时除外);从行号栏运行单个测试时按行号选择(`file:line`),有多个 project 的运行会在文件下按 project 分组。`node --test` 运行时,IDE 通过 `NODE_OPTIONS` 在 `spec` 旁加上自己的报告器(脚本自己指定了 `--test-reporter` 时不显示测试树);单个测试和重新运行按完整名称选择(`--test-name-pattern`)。**使用覆盖率运行** 支持调用 `vitest` 或 `jest` 的脚本(Vitest 需要 `@vitest/coverage-v8` 之类的覆盖率 provider,缺失时 IDE 会提示添加),以及通过 `c8` 运行的 `node` / `tsx` / `ts-node`。详见[测试](/zh/guide/testing)和[覆盖率](/zh/guide/coverage)。
|
||||
|
||||
## 调试
|
||||
|
||||
|
||||
@@ -206,6 +206,90 @@ test("manages multi-level skills in Settings and per-session overrides via Compo
|
||||
);
|
||||
return skills;
|
||||
};
|
||||
handlers.agent_skills_browse = () => ({
|
||||
owner: "vercel-labs",
|
||||
repo: "agent-skills",
|
||||
gitRef: "main",
|
||||
treeSha: "9f8e7d6c",
|
||||
truncated: false,
|
||||
skills: [
|
||||
{ folderName: "find-skills", subpath: "skills/find-skills", fileCount: 2, totalBytes: 1420 },
|
||||
{ folderName: "web-design-audit", subpath: "skills/web-design-audit", fileCount: 1, totalBytes: 860 },
|
||||
],
|
||||
});
|
||||
handlers.agent_skills_preview = ({ subpath }) =>
|
||||
subpath === "skills/web-design-audit"
|
||||
? {
|
||||
owner: "vercel-labs",
|
||||
repo: "agent-skills",
|
||||
gitRef: "main",
|
||||
treeSha: "9f8e7d6c",
|
||||
subpath: "skills/web-design-audit",
|
||||
skillName: "web-design-audit",
|
||||
description: "Audit responsive layout and contrast tokens",
|
||||
skillMarkdown:
|
||||
"---\nname: web-design-audit\ndescription: Audit responsive layout and contrast tokens\n---\n\nCheck spacing and contrast tokens.\n",
|
||||
files: [{ path: "SKILL.md", size: 860, executable: false, symlink: false }],
|
||||
scanWarnings: [],
|
||||
alreadyInstalledUser: false,
|
||||
alreadyInstalledWorkspace: false,
|
||||
}
|
||||
: {
|
||||
owner: "vercel-labs",
|
||||
repo: "agent-skills",
|
||||
gitRef: "main",
|
||||
treeSha: "9f8e7d6c",
|
||||
subpath: "skills/find-skills",
|
||||
skillName: "find-skills",
|
||||
description: "Discover reusable SKILL.md workflows and inspect bundled scripts",
|
||||
skillMarkdown:
|
||||
"---\nname: find-skills\ndescription: Discover reusable SKILL.md workflows and inspect bundled scripts\nallowed-tools:\n - Bash(gh:*)\n---\n\nInspect candidate SKILL.md files before installing.\n",
|
||||
files: [
|
||||
{ path: "SKILL.md", size: 980, executable: false, symlink: false },
|
||||
{ path: "scripts/inspect.sh", size: 440, executable: true, symlink: false },
|
||||
],
|
||||
scanWarnings: [
|
||||
{
|
||||
kind: "executableScript",
|
||||
file: "scripts/inspect.sh",
|
||||
message: "Contains executable file mode (100755)",
|
||||
},
|
||||
{
|
||||
kind: "allowedToolsShell",
|
||||
file: "SKILL.md",
|
||||
message: "`allowed-tools` grants shell/command execution (`Bash(gh:*)`)",
|
||||
},
|
||||
],
|
||||
alreadyInstalledUser: false,
|
||||
alreadyInstalledWorkspace: false,
|
||||
};
|
||||
handlers.agent_skills_install = ({ input }) => {
|
||||
const req = input as { subpath: string; scope: "user" | "workspace" };
|
||||
const installedName = req.subpath.endsWith("web-design-audit") ? "web-design-audit" : "find-skills";
|
||||
skills = [
|
||||
...skills,
|
||||
{
|
||||
skill: {
|
||||
name: installedName,
|
||||
description: "Discover reusable SKILL.md workflows and inspect bundled scripts",
|
||||
hint: null,
|
||||
path:
|
||||
req.scope === "workspace"
|
||||
? `/dev/openidea/.agents/skills/${installedName}`
|
||||
: `/Users/dev/.agents/skills/${installedName}`,
|
||||
source: req.scope === "workspace" ? "workspace" : "user",
|
||||
alsoIn: [],
|
||||
userInvocable: true,
|
||||
disableModelInvocation: false,
|
||||
valid: true,
|
||||
warnings: [],
|
||||
},
|
||||
mode: "auto",
|
||||
origin: "none",
|
||||
},
|
||||
];
|
||||
return skills;
|
||||
};
|
||||
handlers.agent_set_skill_overrides = ({ overrides }) => {
|
||||
currentTask = { ...currentTask, skillOverrides: overrides as Record<string, AgentSkillMode> };
|
||||
return currentTask;
|
||||
@@ -282,4 +366,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` });
|
||||
}
|
||||
});
|
||||
@@ -62,3 +62,59 @@ test("keeps values and their full-value action readable in a narrow debugger", a
|
||||
.poll(() => routing.getByText(routingValue, { exact: true }).evaluate((el) => el.scrollWidth <= el.clientWidth + 1))
|
||||
.toBe(true);
|
||||
});
|
||||
|
||||
test("keeps a decimal value legible beside a long runtime type", async ({ workbench: page }) => {
|
||||
const name = "dailySettlementTotal";
|
||||
const type = "ExactSettlementAmountForCrossBorderReconciliation";
|
||||
const value = "12486245.8067";
|
||||
const countName = "pendingInvoices";
|
||||
await page.setViewportSize({ width: 1100, height: 720 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ name, type, value, countName }) => {
|
||||
const debugModule = "/src/features/debugger/state.ts";
|
||||
const layoutModule = "/src/workbench/toolwindows/store.ts";
|
||||
const serviceModule = "/src/workbench/contributions.ts";
|
||||
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
|
||||
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
|
||||
const { toolWindowService } = await import(/* @vite-ignore */ serviceModule);
|
||||
window.__ipc.handlers.debug_scopes = () => [{ name: "Locals", variablesReference: 100, expensive: false }];
|
||||
window.__ipc.handlers.debug_variables = () => [
|
||||
{ name, value, typeName: type, variablesReference: 0, evaluateName: name },
|
||||
{ name: countName, value: "327", typeName: "int", variablesReference: 0, evaluateName: countName },
|
||||
];
|
||||
adoptSession(92, {
|
||||
name: "Settlement",
|
||||
adapter: "debugpy",
|
||||
status: "paused",
|
||||
selectedFrame: 11,
|
||||
frames: [{ id: 11, name: "settle", path: null, line: 0, column: 0, presentationHint: null }],
|
||||
});
|
||||
moveToolWindow("debug", "right");
|
||||
setToolWindowSize("right", 280);
|
||||
toolWindowService().show("debug", true);
|
||||
},
|
||||
{ name, type, value, countName },
|
||||
);
|
||||
const debug = page.getByRole("region", { name: "Debug", exact: true });
|
||||
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
|
||||
const variable = debug.getByRole("treeitem").filter({ hasText: name });
|
||||
const amount = variable.getByText(value, { exact: true });
|
||||
const annotation = variable.getByTitle(`{${type}}`, { exact: true });
|
||||
await expect(amount).toBeVisible();
|
||||
await expect.poll(() => amount.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await expect(variable.getByTitle("Show", { exact: true })).toBeHidden();
|
||||
await expect(annotation).toBeVisible();
|
||||
|
||||
const shortValueName = debug.getByText(countName, { exact: true });
|
||||
await expect.poll(() => shortValueName.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
|
||||
await page.setViewportSize({ width: 1440, height: 760 });
|
||||
await page.evaluate(async () => {
|
||||
const layoutModule = "/src/workbench/toolwindows/store.ts";
|
||||
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
|
||||
moveToolWindow("debug", "bottom");
|
||||
setToolWindowSize("bottom", 310);
|
||||
});
|
||||
await expect.poll(() => annotation.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
});
|
||||
@@ -10,6 +10,7 @@ something to show.
|
||||
| `rust-app/` | cargo | `cargo run` | `cargo test` | `cargo test --features failing-tests` | unused variable in `src/parser.rs` |
|
||||
| `ts-app/` | Node 22+, pnpm/npm | `pnpm start` | `pnpm test` (vitest) | `OPENIDEA_FAIL=1 pnpm test` | unused function in `src/index.ts` |
|
||||
| `playwright-app/` | Node 22+, npm (Playwright Test, no browser needed) | — | `npm test` | `OPENIDEA_FAIL=1 npm test` | unused function in `src/checkout.ts` |
|
||||
| `node-test-app/` | Node 22+, npm (no dependencies) | — | `npm test` (node:test) | `OPENIDEA_FAIL=1 npm test` | unused constant in `src/inventory.js` |
|
||||
| `python-app/` | Python 3.10+, pytest | `python -m tasks.cli` (from `src/`) | `pytest` | `OPENIDEA_FAIL=1 pytest` | unused imports in `models.py` |
|
||||
| `go-app/` | Go 1.22+ | `go run ./cmd/server` | `go test ./...` | `OPENIDEA_FAIL=1 go test ./...` | unused `fmt.Sprintf` result in `internal/store/store.go` |
|
||||
| `kotlin-gradle/` | JDK 21, Gradle 8 (no wrapper) | `gradle run` | `gradle test` | `gradle test -PopenideaFail` | unused variable in `App.kt` |
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
node_modules
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
export class Inventory {
|
||||
#stock = new Map();
|
||||
|
||||
receive(sku, quantity) {
|
||||
if (!Number.isInteger(quantity) || quantity <= 0) throw new RangeError("quantity must be a positive integer");
|
||||
this.#stock.set(sku, this.count(sku) + quantity);
|
||||
return this;
|
||||
}
|
||||
|
||||
ship(sku, quantity) {
|
||||
// TODO: reserve stock for open orders before shipping
|
||||
if (quantity > this.count(sku)) throw new Error(`not enough ${sku} in stock`);
|
||||
this.#stock.set(sku, this.count(sku) - quantity);
|
||||
return this;
|
||||
}
|
||||
|
||||
count(sku) {
|
||||
return this.#stock.get(sku) ?? 0;
|
||||
}
|
||||
}
|
||||
|
||||
// An intentional warning: never used.
|
||||
const RESTOCK_LEVEL = 5;
|
||||
@@ -0,0 +1,27 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { Inventory } from "../src/inventory.js";
|
||||
|
||||
describe("inventory", () => {
|
||||
it("counts received stock", () => {
|
||||
assert.equal(new Inventory().receive("mug", 3).receive("mug", 2).count("mug"), 5);
|
||||
});
|
||||
|
||||
describe("shipping", () => {
|
||||
it("takes items out of stock", () => {
|
||||
assert.equal(new Inventory().receive("mug", 3).ship("mug", 2).count("mug"), 1);
|
||||
});
|
||||
|
||||
it("refuses more than is in stock", () => {
|
||||
assert.throws(() => new Inventory().ship("mug", 1), /not enough mug/);
|
||||
});
|
||||
});
|
||||
|
||||
it("intentionally fails (set OPENIDEA_FAIL=1)", { skip: !process.env.OPENIDEA_FAIL }, () => {
|
||||
assert.equal(new Inventory().receive("mug", 1).count("mug"), 2);
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects non-positive quantities", () => {
|
||||
assert.throws(() => new Inventory().receive("mug", 0), RangeError);
|
||||
});
|
||||
@@ -79,6 +79,16 @@ const CASES: Record<string, Case | Case[]> = {
|
||||
file: "tests/checkout.spec.ts",
|
||||
},
|
||||
},
|
||||
{
|
||||
fixture: "node-test-app",
|
||||
tests: {
|
||||
config: "npm:test",
|
||||
failing: (c) => env(c, { OPENIDEA_FAIL: "1" }),
|
||||
passed: 4,
|
||||
failed: "intentionally fails (set OPENIDEA_FAIL=1)",
|
||||
file: "test/inventory.test.js",
|
||||
},
|
||||
},
|
||||
],
|
||||
python: {
|
||||
fixture: "python-app",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
@@ -7791,6 +7797,18 @@ export type InstallPreview = {
|
||||
needsConsent: boolean,
|
||||
};
|
||||
|
||||
export type InstallRemoteSkillRequest = {
|
||||
owner: string,
|
||||
repo: string,
|
||||
gitRef: string,
|
||||
subpath: string,
|
||||
scope: McpScope,
|
||||
/** Must be `true` when the static security scan produces any warnings. */
|
||||
confirmWarnings?: boolean,
|
||||
/** Must be `true` to replace an existing folder of the same name in `scope`. */
|
||||
overwrite?: boolean,
|
||||
};
|
||||
|
||||
/** The settings folder of a JetBrains IDE (or Android Studio) of this user. */
|
||||
export type InstalledIdeSettings = {
|
||||
/** The IDE and its version: `IntelliJ IDEA 2025.2`. */
|
||||
@@ -10939,6 +10957,47 @@ export type RemoteSession = {
|
||||
commands: string[],
|
||||
};
|
||||
|
||||
export type RemoteSkillBrowseResult = {
|
||||
owner: string,
|
||||
repo: string,
|
||||
gitRef: string,
|
||||
treeSha: string,
|
||||
truncated: boolean,
|
||||
skills: RemoteSkillCandidate[],
|
||||
};
|
||||
|
||||
export type RemoteSkillCandidate = {
|
||||
/** Target folder name (`<name>` under `.agents/skills/<name>`). */
|
||||
folderName: string,
|
||||
/** Repository-relative directory holding `SKILL.md` (`""` when at repository root). */
|
||||
subpath: string,
|
||||
fileCount: number,
|
||||
totalBytes: number,
|
||||
};
|
||||
|
||||
export type RemoteSkillFile = {
|
||||
/** Path relative to the skill folder (e.g. `"SKILL.md"`, `"scripts/check.sh"`). */
|
||||
path: string,
|
||||
size: number,
|
||||
executable: boolean,
|
||||
symlink: boolean,
|
||||
};
|
||||
|
||||
export type RemoteSkillPreview = {
|
||||
owner: string,
|
||||
repo: string,
|
||||
gitRef: string,
|
||||
treeSha: string,
|
||||
subpath: string,
|
||||
skillName: string,
|
||||
description: string,
|
||||
skillMarkdown: string,
|
||||
files: RemoteSkillFile[],
|
||||
scanWarnings: SkillScanWarning[],
|
||||
alreadyInstalledUser: boolean,
|
||||
alreadyInstalledWorkspace: boolean,
|
||||
};
|
||||
|
||||
/** Where [`remote_connect`] is (`fraction`: 0..1 of a download / upload). */
|
||||
export type RemoteStage = "connecting" |
|
||||
/** `devcontainer up`: building or starting the container. */
|
||||
@@ -11819,6 +11878,14 @@ export type SizeSource =
|
||||
*/
|
||||
"addressGaps" | "layout";
|
||||
|
||||
export type SkillScanWarning = {
|
||||
kind: SkillScanWarningKind,
|
||||
file: string,
|
||||
message: string,
|
||||
};
|
||||
|
||||
export type SkillScanWarningKind = "hiddenUnicode" | "outOfRootSymlink" | "executableScript" | "allowedToolsShell";
|
||||
|
||||
export type SkipReason =
|
||||
/** A configuration with this name already exists. */
|
||||
{ kind: "nameTaken" } |
|
||||
|
||||
@@ -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") },
|
||||
];
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,124 @@ describe("SkillsPage", () => {
|
||||
expect(await screen.findByText(/does not match the folder/)).toBeInTheDocument();
|
||||
expect(screen.queryByText("SKILL.md is valid")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("browses a GitHub repo, previews SKILL.md & files, gates on static scan warnings, and installs", async () => {
|
||||
const project = { root: "/proj", name: "Proj", trusted: true, isGit: true } as ProjectInfo;
|
||||
useProject.setState({ project });
|
||||
|
||||
const installCalls: InstallRemoteSkillRequest[] = [];
|
||||
const previews: Record<string, RemoteSkillPreview> = {
|
||||
"skills/clean-doc": {
|
||||
owner: "acme",
|
||||
repo: "skills",
|
||||
gitRef: "main",
|
||||
treeSha: "abc123",
|
||||
subpath: "skills/clean-doc",
|
||||
skillName: "clean-doc",
|
||||
description: "Clean documentation helper",
|
||||
skillMarkdown: "---\nname: clean-doc\ndescription: Clean documentation helper\n---\nWrite clear docs.\n",
|
||||
files: [{ path: "SKILL.md", size: 92, executable: false, symlink: false }],
|
||||
scanWarnings: [],
|
||||
alreadyInstalledUser: false,
|
||||
alreadyInstalledWorkspace: false,
|
||||
},
|
||||
"skills/deploy-script": {
|
||||
owner: "acme",
|
||||
repo: "skills",
|
||||
gitRef: "main",
|
||||
treeSha: "abc123",
|
||||
subpath: "skills/deploy-script",
|
||||
skillName: "deploy-script",
|
||||
description: "Deploys staging builds",
|
||||
skillMarkdown:
|
||||
"---\nname: deploy-script\ndescription: Deploys staging builds\nallowed-tools: Bash(git:*)\n---\nRun deploy.\n",
|
||||
files: [
|
||||
{ path: "SKILL.md", size: 112, executable: false, symlink: false },
|
||||
{ path: "scripts/deploy.sh", size: 48, executable: true, symlink: false },
|
||||
],
|
||||
scanWarnings: [
|
||||
{
|
||||
kind: "executableScript",
|
||||
file: "scripts/deploy.sh",
|
||||
message: "Contains executable file mode (100755)",
|
||||
},
|
||||
{
|
||||
kind: "allowedToolsShell",
|
||||
file: "SKILL.md",
|
||||
message: "`allowed-tools` grants shell/command execution (`Bash(git:*)`)",
|
||||
},
|
||||
],
|
||||
alreadyInstalledUser: false,
|
||||
alreadyInstalledWorkspace: false,
|
||||
},
|
||||
};
|
||||
|
||||
const installerBackend: SkillsBackend = {
|
||||
...backend(),
|
||||
browse: vi.fn(async () => ({
|
||||
owner: "acme",
|
||||
repo: "skills",
|
||||
gitRef: "main",
|
||||
treeSha: "abc123",
|
||||
truncated: false,
|
||||
skills: [
|
||||
{ folderName: "clean-doc", subpath: "skills/clean-doc", fileCount: 1, totalBytes: 92 },
|
||||
{ folderName: "deploy-script", subpath: "skills/deploy-script", fileCount: 2, totalBytes: 160 },
|
||||
],
|
||||
})),
|
||||
preview: vi.fn(async (_owner, _repo, _ref, subpath) => {
|
||||
const found = previews[subpath];
|
||||
if (!found) throw new Error(`missing preview for ${subpath}`);
|
||||
return found;
|
||||
}),
|
||||
install: vi.fn(async (input) => {
|
||||
installCalls.push(input);
|
||||
return [...SKILLS, state("deploy-script", input.scope === "workspace" ? "workspace" : "user")];
|
||||
}),
|
||||
};
|
||||
|
||||
render(<SkillsPage backend={installerBackend} />);
|
||||
await waitFor(() => expect(screen.getByText("tdd")).toBeInTheDocument());
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Install Skill…" }));
|
||||
const dialog = await screen.findByRole("dialog", { name: "Install Agent Skill" });
|
||||
fireEvent.change(within(dialog).getByLabelText("Skill repository"), { target: { value: "acme/skills" } });
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Fetch" }));
|
||||
|
||||
// First candidate (`clean-doc`) has 0 warnings -> Install is immediately enabled.
|
||||
expect(await within(dialog).findByText(/Static scan passed/)).toBeInTheDocument();
|
||||
expect(within(dialog).getByRole("button", { name: "Install" })).toBeEnabled();
|
||||
|
||||
// Switch to `deploy-script` -> warnings require confirmation checkbox before Install enables.
|
||||
fireEvent.click(within(dialog).getByRole("option", { name: /deploy-script/ }));
|
||||
expect(await within(dialog).findByText(/Static security scan found 2 warnings/)).toBeInTheDocument();
|
||||
const installBtn = within(dialog).getByRole("button", { name: "Install" });
|
||||
expect(installBtn).toBeDisabled();
|
||||
|
||||
// Inspect bundled file list tab.
|
||||
fireEvent.click(within(dialog).getByRole("tab", { name: /Files \(2\)/ }));
|
||||
expect(within(dialog).getAllByText("scripts/deploy.sh")).toHaveLength(2);
|
||||
expect(within(dialog).getByText("Executable")).toBeInTheDocument();
|
||||
|
||||
// Confirm warnings and install into Workspace (.agents/skills).
|
||||
pick("Install location", "Workspace (.agents/skills)");
|
||||
fireEvent.click(within(dialog).getByLabelText("I reviewed these warnings and want to install this skill"));
|
||||
expect(installBtn).toBeEnabled();
|
||||
fireEvent.click(installBtn);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(installCalls).toEqual([
|
||||
{
|
||||
owner: "acme",
|
||||
repo: "skills",
|
||||
gitRef: "main",
|
||||
subpath: "skills/deploy-script",
|
||||
scope: "workspace",
|
||||
confirmWarnings: true,
|
||||
overwrite: false,
|
||||
},
|
||||
]),
|
||||
);
|
||||
await waitFor(() => expect(screen.getByText("deploy-script")).toBeInTheDocument());
|
||||
});
|
||||
});
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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)),
|
||||
})),
|
||||
|
||||
@@ -46,7 +46,7 @@ import {
|
||||
} from "./store";
|
||||
import { openTableData } from "./treeActions";
|
||||
import styles from "./Database.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { tx, txPart } from "@/platform/i18n";
|
||||
|
||||
/** Read-only SQL with the editor's syntax colours (IDEA's dialog Preview pane). */
|
||||
function SqlPreview({ sql, label = "Preview" }: { sql: string; label?: string }) {
|
||||
@@ -130,7 +130,7 @@ function RenameDialog({ id, object }: { id: string; object: DbObjectRef | null }
|
||||
>
|
||||
<div className={styles.dialogBody}>
|
||||
<label className={styles.formLabelLeft} htmlFor="db-rename">
|
||||
{tx`Rename ${what} '${initial}' to:`}
|
||||
{tx`Rename ${txPart(what)} '${initial}' to:`}
|
||||
</label>
|
||||
<Input
|
||||
id="db-rename"
|
||||
@@ -166,7 +166,7 @@ function DropDialog({ id, object }: { id: string; object: DbObjectRef }) {
|
||||
>
|
||||
<div className={styles.dialogBody}>
|
||||
<div className={styles.dialogLead}>
|
||||
{tx`Drop ${KIND_LABEL[object.kind]}`} <strong>{reference(driver, object)}</strong>
|
||||
{tx`Drop ${txPart(KIND_LABEL[object.kind])}`} <strong>{reference(driver, object)}</strong>
|
||||
{tx`? This cannot be undone.`}
|
||||
</div>
|
||||
<Checkbox
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { tx, txPart } from "@/platform/i18n";
|
||||
import { Button, Checkbox, Dialog, EmptyState, Icon, Select, Spinner, T, Tree, type SelectOption } from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { CodePreview } from "./CodePreview";
|
||||
@@ -72,14 +72,14 @@ function SidePicker({ label, side, onChange }: { label: string; side: Side; onCh
|
||||
<T>{label}</T>
|
||||
</span>
|
||||
<Select
|
||||
aria-label={tx`${tx(label)} data source`}
|
||||
aria-label={tx`${txPart(label)} data source`}
|
||||
value={side.id || null}
|
||||
placeholder="<data source>"
|
||||
options={sourceOptions}
|
||||
onChange={(id) => onChange({ id, schema: sourceById(id)?.driver === "sqlite" ? "main" : "" })}
|
||||
/>
|
||||
<Select
|
||||
aria-label={tx`${tx(label)} schema`}
|
||||
aria-label={tx`${txPart(label)} schema`}
|
||||
value={side.schema || null}
|
||||
placeholder="<schema>"
|
||||
options={schemaOptions}
|
||||
@@ -129,7 +129,7 @@ function migrates(source: Side, target: Side): string {
|
||||
}
|
||||
|
||||
function includeLabel(r: Row): string {
|
||||
const name = r.kind === "group" ? tx(r.label) : r.diff.name;
|
||||
const name = r.kind === "group" ? txPart(r.label) : r.diff.name;
|
||||
return tx`Include ${name}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -84,7 +84,7 @@ import { useExpressionCompletion } from "./ExpressionCompletion";
|
||||
import { pushHistory, readHistory } from "./expressionHistory";
|
||||
import styles from "./Overlays.module.css";
|
||||
import { isImeKey } from "@/platform/ime";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { tx, txPart } from "@/platform/i18n";
|
||||
|
||||
export function DebuggerOverlays() {
|
||||
return (
|
||||
@@ -606,7 +606,7 @@ function BreakpointsDialog() {
|
||||
<Checkbox
|
||||
checked={r.bp.enabled}
|
||||
onChange={(enabled) => updateExceptionClass(r.bp.id, { enabled })}
|
||||
aria-label={tx`Enable ${name}`}
|
||||
aria-label={tx`Enable ${r.bp.className || txPart("No class chosen")}`}
|
||||
/>
|
||||
<Icon name="breakpoint-exception" size={14} />
|
||||
<span className={styles.bpName} title={name}>
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
min-width: min(8ch, 45%);
|
||||
/* Cap the automatic flex minimum at the space needed for a short preview. */
|
||||
width: min(14ch, 50%);
|
||||
flex: 1 1 0;
|
||||
}
|
||||
|
||||
@@ -135,9 +136,8 @@
|
||||
}
|
||||
|
||||
.type {
|
||||
min-width: 0;
|
||||
max-width: 25%;
|
||||
flex: 0 1 auto;
|
||||
min-width: min(3ch, 10%);
|
||||
flex: 0 4 auto;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--fg-subtle);
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
* As in IntelliJ, closing a chip's popup without choosing resets the chip.
|
||||
*/
|
||||
import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
import { tx, useTx } from "@/platform/i18n";
|
||||
import { tx, txPart, useTx } from "@/platform/i18n";
|
||||
import { Icon, IconButton, Menu, SearchField, showContextMenu, type MenuItem } from "@/ui";
|
||||
import type { GHLabel, GHUser } from "../api/types";
|
||||
import { filterCount, type PrSearchValue } from "../data/model";
|
||||
@@ -151,7 +151,7 @@ function FilterChip({
|
||||
<IconButton
|
||||
type="button"
|
||||
className={styles.chipReset}
|
||||
aria-label={t`Reset ${name}`}
|
||||
aria-label={t`Reset ${txPart(title)}`}
|
||||
onClick={() => onChange(undefined)}
|
||||
onKeyDown={onKeyDown}
|
||||
tabIndex={-1}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
* The viewer's toggle shows at once and is undone when the request fails.
|
||||
*/
|
||||
import { useState } from "react";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { tx, txPart } from "@/platform/i18n";
|
||||
import { IconButton, Popup, tooltipAttrs } from "@/ui";
|
||||
import type { GHReaction, GHReactionContent } from "../../api/types";
|
||||
import { useGhRepository } from "../../data/repository";
|
||||
@@ -101,7 +101,7 @@ export function Reactions({ state, canReact }: ReactionsProps) {
|
||||
className={styles.pill}
|
||||
data-own={g.isReactedByCurrentUser || undefined}
|
||||
disabled={!canReact}
|
||||
{...tooltipAttrs(tx`${users} reacted with '${name}' emoji`)}
|
||||
{...tooltipAttrs(tx`${users} reacted with '${txPart(name)}' emoji`)}
|
||||
onClick={() => toggle(g.content)}
|
||||
>
|
||||
<span className={styles.emoji}>{r.emoji}</span>
|
||||
|
||||
@@ -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}`;
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,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}`,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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(", ")}`),
|
||||
|
||||
@@ -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={[
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
} from "./testing";
|
||||
import { PluginTestOutput } from "./testing/plugin";
|
||||
import { GoTestOutput } from "./testing/go";
|
||||
import { RecordsOutput } from "./testing/records";
|
||||
import { DotnetReports } from "./testing/dotnet";
|
||||
import { moveToReportedClasses } from "./testing/jvm";
|
||||
import { RubyTestOutput } from "./testing/ruby";
|
||||
@@ -67,7 +68,7 @@ import { startedPort } from "@/platform/serverPort";
|
||||
import { tomcatBrowserUrl } from "./tomcat";
|
||||
import { gradleBootLaunch, gradleDelegation, gradleTestLaunch } from "./gradleRun";
|
||||
import { openUrl } from "./navigate";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { tx, txPart } from "@/platform/i18n";
|
||||
import { UNITY_CONFIG_KIND } from "./unity";
|
||||
|
||||
/** The permanent "Current File" pseudo-configuration of the chooser (runs the active file's context). */
|
||||
@@ -713,8 +714,8 @@ function newRuntime(config: RunConfig): SessionRuntime {
|
||||
if (tests && parser) tests.apply(parser.feed(line));
|
||||
};
|
||||
const framework = tests && parser ? frameworkFor(config) : null;
|
||||
// PHPUnit `--teamcity` and Gradle's test init script report through service messages, Minitest through
|
||||
// the IDE's own reporter (RSpec has none: its progress dots must show as they come).
|
||||
// PHPUnit `--teamcity` and Gradle's test init script report through service messages, Minitest and
|
||||
// node:test through the IDE's own reporters (RSpec has none: its progress dots must show as they come).
|
||||
const stdout =
|
||||
framework === "go"
|
||||
? new GoTestOutput(feed)
|
||||
@@ -722,7 +723,9 @@ function newRuntime(config: RunConfig): SessionRuntime {
|
||||
? new TeamcityOutput(feed)
|
||||
: framework === "ruby" && config.kind !== "rspec"
|
||||
? new RubyTestOutput(feed)
|
||||
: null;
|
||||
: framework === "node-test"
|
||||
? new RecordsOutput(feed)
|
||||
: null;
|
||||
const runtime: SessionRuntime = {
|
||||
stdout,
|
||||
tests,
|
||||
@@ -1620,7 +1623,7 @@ export async function sendStdin(sessionId: string, text: string): Promise<void>
|
||||
} catch (e) {
|
||||
enqueue(sessionId, {
|
||||
kind: "system",
|
||||
text: tx`Cannot write to stdin: ${e instanceof Error ? tx(e.message) : String(e)}\n`,
|
||||
text: tx`Cannot write to stdin: ${e instanceof Error ? txPart(e.message) : String(e)}\n`,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1632,7 +1635,7 @@ export function writeTerminal(sessionId: string, data: string) {
|
||||
void call(commands.runStdin(session.runId, data)).catch((e) => {
|
||||
enqueue(sessionId, {
|
||||
kind: "system",
|
||||
text: tx`Cannot write to stdin: ${e instanceof Error ? tx(e.message) : String(e)}\n`,
|
||||
text: tx`Cannot write to stdin: ${e instanceof Error ? txPart(e.message) : String(e)}\n`,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import { scanJvmTargets, simpleClassName } from "./jvmTargets";
|
||||
import { escapeRegExp } from "./testing/rerun";
|
||||
import { pestFilter, phpunitArgs, phpunitFilter } from "./testing/phpunit";
|
||||
import { frameworkFor } from "./testing";
|
||||
import { withNodeTestNamePattern } from "./testing/nodeTest";
|
||||
|
||||
export type TargetKind = "main" | "test" | "suite" | "generate";
|
||||
|
||||
@@ -473,6 +474,9 @@ export function targetConfig(
|
||||
});
|
||||
// Playwright selects by declaration line (`file:line`), which also covers a describe block.
|
||||
if (frameworkFor(file) === "playwright") return named(withLast(file.args, (f) => `${f}:${target.line + 1}`));
|
||||
// node:test selects by full name, through NODE_OPTIONS (see `nodeTest.ts`).
|
||||
if (frameworkFor(file) === "node-test")
|
||||
return { ...named(file.args), env: withNodeTestNamePattern(file.env, jsNamePattern(target)) };
|
||||
switch (file.kind) {
|
||||
case "dotnet-test": {
|
||||
const methods =
|
||||
|
||||
@@ -4,6 +4,8 @@ import { cargoParser } from "./cargo";
|
||||
import { goParser } from "./go";
|
||||
import { jsParser } from "./js";
|
||||
import { jvmParser } from "./jvm";
|
||||
import { withNodeTestReporter } from "./nodeTest";
|
||||
import { recordsParser } from "./records";
|
||||
import { phpunitParser, withTeamcity } from "./phpunit";
|
||||
import { playwrightParser } from "./playwright";
|
||||
import { pytestParser } from "./pytest";
|
||||
@@ -24,6 +26,7 @@ export {
|
||||
phpunitParser,
|
||||
playwrightParser,
|
||||
pytestParser,
|
||||
recordsParser,
|
||||
rubyParser,
|
||||
unittestParser,
|
||||
zigParser,
|
||||
@@ -41,6 +44,7 @@ export type Framework =
|
||||
| "cargo"
|
||||
| "js"
|
||||
| "playwright"
|
||||
| "node-test"
|
||||
| "pytest"
|
||||
| "unittest"
|
||||
| "phpunit"
|
||||
@@ -51,12 +55,14 @@ export type Framework =
|
||||
| "zig"
|
||||
| "auto";
|
||||
|
||||
type FrameworkConfig = Pick<RunConfig, "kind" | "command" | "args"> & Partial<Pick<RunConfig, "testRunner">>;
|
||||
type FrameworkConfig = Pick<RunConfig, "kind" | "command" | "args"> & Partial<Pick<RunConfig, "testRunner" | "env">>;
|
||||
|
||||
export function frameworkFor(config: FrameworkConfig): Framework {
|
||||
const cmd = [config.command, ...config.args].join(" ");
|
||||
// A `package.json` script names its runner only in package.json: detection records it.
|
||||
if (config.testRunner === "playwright" || /\bplaywright\s+test\b/.test(cmd)) return "playwright";
|
||||
if (config.testRunner === "node-test" || /(^|[\s/\\])(node|tsx)(\.exe)?(\s+-\S*)*\s+--test(\s|$)/.test(cmd))
|
||||
return "node-test";
|
||||
switch (config.kind) {
|
||||
case "dotnet-test":
|
||||
return "dotnet";
|
||||
@@ -120,6 +126,7 @@ function rubyVerbose<T extends Pick<RunConfig, "kind" | "command" | "args">>(con
|
||||
* IDEA's runner) unless the user chose a verbosity already.
|
||||
*/
|
||||
export function withTestReporting<T extends FrameworkConfig>(config: T): T {
|
||||
if (frameworkFor(config) === "node-test") return { ...config, env: withNodeTestReporter(config.env ?? {}) };
|
||||
if (frameworkFor(config) === "playwright") {
|
||||
// The list reporter prints a line per test; a project's own (`html`, `dot` on CI) may print none.
|
||||
const chosen = config.args.some((a) => a === "--reporter" || a.startsWith("--reporter="));
|
||||
@@ -162,6 +169,8 @@ export function createTestParser(config: FrameworkConfig): TestOutputParser {
|
||||
return jsParser();
|
||||
case "playwright":
|
||||
return playwrightParser();
|
||||
case "node-test":
|
||||
return recordsParser();
|
||||
case "pytest":
|
||||
return pytestParser();
|
||||
case "unittest":
|
||||
|
||||
@@ -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"',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* `node --test`: the IDE's reporter (`nodeTestReporter.js`) runs next to `spec` and prints a
|
||||
* record per finished test (`records.ts`). It reaches Node through `NODE_OPTIONS`, as does the
|
||||
* name filter: a `package.json` script's own arguments can't take them (`node --test` reads
|
||||
* options only before its file patterns).
|
||||
*/
|
||||
import REPORTER_SOURCE from "./nodeTestReporter.js?raw";
|
||||
|
||||
const REPORTER = `--test-reporter=data:text/javascript;base64,${btoa(REPORTER_SOURCE)}`;
|
||||
const PATTERN_RE = /(^|\s)--test-name-pattern=(?:"(?:[^"\\]|\\.)*"|\S+)/g;
|
||||
|
||||
/** `NODE_OPTIONS` with the IDE's reporter added (once), `spec` keeping the console readable. */
|
||||
export function withNodeTestReporter(env: Record<string, string>): Record<string, string> {
|
||||
const options = env.NODE_OPTIONS ?? "";
|
||||
if (options.includes(REPORTER) || /(^|\s)--test-reporter[=\s]/.test(options)) return env;
|
||||
const reporters = [
|
||||
"--test-reporter=spec",
|
||||
"--test-reporter-destination=stdout",
|
||||
REPORTER,
|
||||
"--test-reporter-destination=stdout",
|
||||
];
|
||||
return { ...env, NODE_OPTIONS: [options, ...reporters].filter(Boolean).join(" ") };
|
||||
}
|
||||
|
||||
/** `NODE_OPTIONS` selecting the tests whose full name (describe chain and name, space separated) matches `pattern`. */
|
||||
export function withNodeTestNamePattern(env: Record<string, string>, pattern: string): Record<string, string> {
|
||||
const options = (env.NODE_OPTIONS ?? "").replace(PATTERN_RE, "").trim();
|
||||
// NODE_OPTIONS splits at spaces outside double quotes, where a backslash escapes the next character.
|
||||
const quoted = `"${pattern.replace(/[\\"]/g, "\\$&")}"`;
|
||||
return { ...env, NODE_OPTIONS: [options, `--test-name-pattern=${quoted}`].filter(Boolean).join(" ") };
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// The IDE's node:test reporter (`--test-reporter`, passed as a data: URL through NODE_OPTIONS
|
||||
// next to `spec`): one record per finished test, which the IDE turns into the test tree and
|
||||
// hides from the console (`records.ts`). Runs in the user's Node (20+), so plain ESM without dependencies.
|
||||
import { relative, resolve } from "node:path";
|
||||
|
||||
const MARK = "@@openidea:test@@";
|
||||
|
||||
const fileOf = (path) => (path ? relative(process.cwd(), path).split("\\").join("/") : "");
|
||||
|
||||
function message(error) {
|
||||
// node:test wraps what the test threw in an ERR_TEST_FAILURE whose `cause` it is.
|
||||
const cause = error && error.code === "ERR_TEST_FAILURE" && error.cause !== undefined ? error.cause : error;
|
||||
if (cause instanceof Error) return cause.stack || `${cause.name}: ${cause.message}`;
|
||||
return String(cause);
|
||||
}
|
||||
|
||||
export default async function* reporter(source) {
|
||||
/** Per file, the names of the tests being reported, by nesting level. */
|
||||
const open = new Map();
|
||||
for await (const { type, data } of source) {
|
||||
if (type !== "test:start" && type !== "test:pass" && type !== "test:fail") continue;
|
||||
const file = fileOf(data.file);
|
||||
// A file without reported tests (none matched, or it failed to load) reports as a test named after it.
|
||||
const self = data.nesting === 0 && data.file && resolve(data.name) === resolve(data.file);
|
||||
const names = open.get(file) ?? [];
|
||||
open.set(file, names);
|
||||
if (type === "test:start") {
|
||||
names.length = data.nesting;
|
||||
names.push(data.name);
|
||||
continue;
|
||||
}
|
||||
const path = [...(file ? [file] : []), ...(self ? [] : [...names.slice(0, data.nesting), data.name])];
|
||||
const details = data.details ?? {};
|
||||
const record = {
|
||||
path,
|
||||
status:
|
||||
type === "test:fail" ? "failed" : data.skip !== undefined || data.todo !== undefined ? "skipped" : "passed",
|
||||
ms: details.duration_ms,
|
||||
line: self ? undefined : data.line,
|
||||
col: self ? undefined : data.column,
|
||||
error:
|
||||
type === "test:fail" && details.error && details.error.failureType !== "subtestsFailed"
|
||||
? message(details.error)
|
||||
: undefined,
|
||||
};
|
||||
yield `${MARK}${JSON.stringify(record)}\n`;
|
||||
}
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import { withMavenTests } from "../mavenTests";
|
||||
import { frameworkFor } from "./index";
|
||||
import { dotnetFilter } from "./dotnet";
|
||||
import { playwrightProject, playwrightTitles } from "./playwright";
|
||||
import { withNodeTestNamePattern } from "./nodeTest";
|
||||
import { nodeStatus, type TestNode, type TestResults } from "./results";
|
||||
|
||||
/** Paths of failed tests: failed leaves, plus failed suites without any failed children reported. */
|
||||
@@ -262,6 +263,16 @@ function builtinTestsConfig(config: RunConfig, paths: string[][], name: string):
|
||||
case "playwright":
|
||||
args = playwrightArgs(config, paths);
|
||||
break;
|
||||
case "node-test": {
|
||||
// The files narrow a script's run when it gives `node --test` no patterns of its own; the names always do.
|
||||
const files = unique(paths.map((p) => p[0]!).filter(Boolean));
|
||||
const names = unique(paths.filter((p) => p.length > 1).map((p) => p.slice(1).join(" ")));
|
||||
if (!files.length) return null;
|
||||
const env = names.length
|
||||
? withNodeTestNamePattern(config.env, `^(?:${names.map(escapeRegExp).join("|")})$`)
|
||||
: { ...config.env };
|
||||
return { ...config, args: appendScriptArgs(config.command, config.args, files), name, detected: true, env };
|
||||
}
|
||||
case "pytest":
|
||||
args = pytestArgs(config.args, paths);
|
||||
break;
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>}
|
||||
|
||||
@@ -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}`;
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ import { ACCENT_PRESETS, LIMITS, type ThemeId } from "../model/schema";
|
||||
import type { PageSpec } from "./spec";
|
||||
import { HTTP_PROXY_PAGE } from "./httpProxy";
|
||||
import styles from "./Behavior.module.css";
|
||||
import { LOCALES, SUPPORTED_LOCALES, tx, useT, useTx } from "@/platform/i18n";
|
||||
import { LOCALES, SUPPORTED_LOCALES, tx, txPart, useT, useTx } from "@/platform/i18n";
|
||||
import { BUILTIN_THEMES, useContributedIconThemes } from "@/platform/themes";
|
||||
import { currentThemeChoice, originDetail, previewTheme, themeSelectOptions, useThemeChoices } from "@/workbench/theme";
|
||||
import { themePreview } from "@/workbench/quickSwitch";
|
||||
@@ -875,14 +875,14 @@ function NotificationGroups() {
|
||||
value={value.display}
|
||||
options={DISPLAY_OPTIONS}
|
||||
onChange={(display) => update({ display })}
|
||||
aria-label={tx`${title} popup type`}
|
||||
aria-label={tx`${txPart(title)} popup type`}
|
||||
/>
|
||||
</Row>
|
||||
<Checkbox
|
||||
checked={value.log}
|
||||
onChange={(log) => update({ log })}
|
||||
label={<SearchLabel text="Show in tool window" />}
|
||||
aria-label={tx`Show ${title} in tool window`}
|
||||
aria-label={tx`Show ${txPart(title)} in tool window`}
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -40,7 +40,7 @@ import { executeAction, registerActions } from "@/platform/actions";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { ask, confirm, showError } from "@/workbench/messages";
|
||||
import { parseIcls, SchemeParseError, importScheme, deleteScheme, exportIcls } from "@/platform/icls";
|
||||
import { tx, useTx } from "@/platform/i18n";
|
||||
import { tx, txPart, useTx } from "@/platform/i18n";
|
||||
import { selectPage } from "../../model/staging";
|
||||
|
||||
type Overrides = Record<string, Record<string, TextAttributesOverride>>;
|
||||
@@ -1286,7 +1286,7 @@ function ColorInput({
|
||||
<Input
|
||||
mono
|
||||
className={styles.swatchInput}
|
||||
aria-label={tx`${label} hex`}
|
||||
aria-label={tx`${txPart(label)} hex`}
|
||||
value={draft ?? value}
|
||||
invalid={draft !== null && !HEX_COLOR.test(draft)}
|
||||
onChange={(e) => {
|
||||
@@ -1831,7 +1831,7 @@ export function ColorSchemePage({
|
||||
</div>
|
||||
)}
|
||||
{scheme === "theme-default" && (
|
||||
<div className={styles.note}>{tx`Follows the IDE theme: currently ${schemeName}.`}</div>
|
||||
<div className={styles.note}>{tx`Follows the IDE theme: currently ${txPart(schemeName)}.`}</div>
|
||||
)}
|
||||
{redGreen && (id === "dark" || id === "light") && (
|
||||
<div className={styles.note}>
|
||||
|
||||
@@ -67,7 +67,7 @@ import {
|
||||
type LanguageServers,
|
||||
} from "./inspectionsModel";
|
||||
import styles from "./Inspections.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { tx, txPart } from "@/platform/i18n";
|
||||
import { useLanguageListVersion } from "@/platform/languageList";
|
||||
|
||||
function useLanguages(): LanguageServers[] {
|
||||
@@ -448,7 +448,7 @@ function InspectionRow({
|
||||
checked={state === "on"}
|
||||
indeterminate={state === "mixed"}
|
||||
onChange={() => onToggle(state !== "on")}
|
||||
aria-label={tx`Enable ${node.name}`}
|
||||
aria-label={tx`Enable ${txPart(node.name)}`}
|
||||
/>
|
||||
</span>
|
||||
</span>
|
||||
|
||||
@@ -14,7 +14,7 @@ import { LIMITS } from "../../model/schema";
|
||||
import type { PageSpec } from "../spec";
|
||||
import { EditorSections, type EditorSection, sectionLabels } from "./kit";
|
||||
import styles from "./Editor.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { tx, txPart } from "@/platform/i18n";
|
||||
|
||||
function FontRow() {
|
||||
const [family, setFamily] = useSetting<string>("editor.fontFamily");
|
||||
@@ -123,7 +123,7 @@ function WeightRow({
|
||||
max={900}
|
||||
step={50}
|
||||
integer
|
||||
aria-label={tx`${label} custom value`}
|
||||
aria-label={tx`${txPart(label)} custom value`}
|
||||
/>
|
||||
)}
|
||||
</Row>
|
||||
|
||||
@@ -10,7 +10,7 @@ import { createFromTemplate, packageFor, packageStyleFor } from "./create";
|
||||
import { planFile, withKind, type FileTemplate } from "./model";
|
||||
import { useFileTemplates } from "./store";
|
||||
import styles from "./NewFileDialog.module.css";
|
||||
import { tx, VerbatimTextContext } from "@/platform/i18n";
|
||||
import { tx, txPart, VerbatimTextContext } from "@/platform/i18n";
|
||||
|
||||
interface Request {
|
||||
directory: string;
|
||||
@@ -231,11 +231,11 @@ function NameStep({
|
||||
<Dialog
|
||||
open
|
||||
onClose={close}
|
||||
title={tx`New ${tx(template.name)}`}
|
||||
title={tx`New ${txPart(template.name)}`}
|
||||
width={hasVariables ? 380 : 320}
|
||||
position={hasVariables ? "top" : "center"}
|
||||
popup
|
||||
aria-label={tx`New ${tx(template.name)}`}
|
||||
aria-label={tx`New ${txPart(template.name)}`}
|
||||
className={hasVariables ? styles.variableDialog : styles.nameDialog}
|
||||
buttons={
|
||||
hasVariables
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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])}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -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,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,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.
|
||||
|
||||
@@ -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),
|
||||
},
|
||||
|
||||
@@ -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,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}
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
SUPPORTED_LOCALES,
|
||||
t,
|
||||
tx,
|
||||
txPart,
|
||||
txTemplate,
|
||||
useI18n,
|
||||
} from "./i18n";
|
||||
@@ -195,12 +196,17 @@ describe("t / locales", () => {
|
||||
expect(txTemplate(built)).toBe("运行 'orders'");
|
||||
const zh = tx`Run '${name}'`;
|
||||
expect(zh).toBe("运行 'orders'");
|
||||
// Substituted text is translated when the catalog has it.
|
||||
expect(tx`Run '${"Retry"}'`).toBe(`运行 '${tx("Retry")}'`);
|
||||
// Values are inserted as written, even when the catalog has an entry for them…
|
||||
expect(tx`Rename directory '${"tasks"}' and its usages to:`).toBe("将目录“tasks”及其用法重命名为:");
|
||||
expect(tx`Run '${"Retry"}'`).toBe("运行 'Retry'");
|
||||
// …unless they are marked as UI text, which is translated again after a locale change.
|
||||
const marked = tx`Run '${txPart("Retry")}'`;
|
||||
expect(marked).toBe(`运行 '${tx("Retry")}'`);
|
||||
// Values are inserted as they are, braces included.
|
||||
expect(tx`Drop ${"stash@{0}"}? This cannot be undone.`).toBe("是否丢弃 stash@{0}?此操作无法撤消。");
|
||||
await setLocale("en");
|
||||
expect(tx(zh)).toBe("Run 'orders'");
|
||||
expect(tx(marked)).toBe("Run 'Retry'");
|
||||
});
|
||||
|
||||
it("loads the Portuguese catalogs", async () => {
|
||||
@@ -298,6 +304,7 @@ describe("catalogs", () => {
|
||||
"Claude Code",
|
||||
"GitHub Copilot",
|
||||
"Codex",
|
||||
"SKILL.md",
|
||||
"Cursor",
|
||||
"PHP",
|
||||
"SQL",
|
||||
|
||||
+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 = {};
|
||||
|
||||
@@ -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)),
|
||||
},
|
||||
|
||||
@@ -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"],
|
||||
|
||||
@@ -3023,6 +3023,31 @@
|
||||
"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",
|
||||
"Cannot find the source of {0}": "Cannot find the source of {0}",
|
||||
"JavaScript and TypeScript": "JavaScript and TypeScript",
|
||||
"Global function": "Global function",
|
||||
|
||||
@@ -9344,6 +9344,30 @@
|
||||
"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.": "未在 .agents/skills、.openidea/skills、~/.agents/skills 或 Claude Code、GitHub Copilot、Codex 与 Cursor 的 CLI 文件夹中找到技能。",
|
||||
"This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling.": "该 CLI 会自己发现这个文件夹:关闭只会让 OpenIDEA 的 / 菜单不再提供该技能,并且只在 CLI 支持禁用时生效。",
|
||||
"Install 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.": "输入 GitHub 仓库(owner/repo、owner/repo@skill、owner/repo/path@ref 或 GitHub URL)。预览并完成静态扫描后,只会下载所选技能文件夹。",
|
||||
"owner/repo, owner/repo@skill, or GitHub URL": "owner/repo、owner/repo@skill 或 GitHub URL",
|
||||
"Skill repository": "技能仓库",
|
||||
"Install location": "安装位置",
|
||||
"User (~/.agents/skills)": "用户 (~/.agents/skills)",
|
||||
"Workspace (.agents/skills)": "工作区 (.agents/skills)",
|
||||
"SKILL.md": "SKILL.md",
|
||||
"{count} skills found": "找到 {count} 个技能",
|
||||
"Available skills": "可用技能",
|
||||
"Scanning SKILL.md and bundled files…": "正在扫描 SKILL.md 与随附文件…",
|
||||
"Static scan passed: no hidden Unicode, out-of-root symlinks, shell tool grants, or executable scripts detected.": "静态扫描通过:未发现隐藏 Unicode、越界符号链接、Shell 工具授权或可执行脚本。",
|
||||
"Static security scan warnings": "静态安全扫描警告",
|
||||
"Static security scan found {count} warnings": "静态安全扫描发现 {count} 项警告",
|
||||
"Hidden Unicode": "隐藏 Unicode",
|
||||
"Out-of-root symlink": "越界符号链接",
|
||||
"Executable script": "可执行脚本",
|
||||
"Shell tool grant": "Shell 工具授权",
|
||||
"I reviewed these warnings and want to install this skill": "我已查看上述警告并确认安装此技能",
|
||||
"Replace existing {name} folder in the selected location": "替换所选位置中已有的 {name} 文件夹",
|
||||
"Skill preview": "技能预览",
|
||||
"Files ({count})": "文件 ({count})",
|
||||
"Symlink": "符号链接",
|
||||
"Cannot find the source of {0}": "找不到 {0} 的源代码",
|
||||
"JavaScript and TypeScript": "JavaScript 和 TypeScript",
|
||||
"Global function": "全局函数",
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
*
|
||||
* Text counts as translatable when it is a literal (or a branch of `?:` / `??` /
|
||||
* `||` around one) that reaches the translation layer directly:
|
||||
* - the first argument of `tx` / `txTemplate`, or of a function bound from
|
||||
* - the first argument of `tx` / `txPart` / `txTemplate`, or of a function bound from
|
||||
* `useTx()` / `useTxTemplate()` in the same file;
|
||||
* - the plain-text children of `<T>` and the other `TEXT_CHILDREN` primitives;
|
||||
* - a `TEXT_PROPS` attribute of a component (`<Row hint="…">`), and `data-tooltip`;
|
||||
@@ -527,7 +527,7 @@ function scanTypeScript(): Scan {
|
||||
true,
|
||||
file.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
|
||||
);
|
||||
const exact = new Set(["tx"]);
|
||||
const exact = new Set(["tx", "txPart"]);
|
||||
const template = new Set(["txTemplate"]);
|
||||
for (const m of source.matchAll(/(?:const|let)\s+(\w+)\s*=\s*useTx(Template)?\(\)/g))
|
||||
(m[2] ? template : exact).add(m[1]!);
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
} from "./statusBarWidgets";
|
||||
import { cancelTask, canCancel, useTasks, type BackgroundTask } from "./tasks";
|
||||
import styles from "./StatusBar.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { tx, txPart } from "@/platform/i18n";
|
||||
|
||||
/**
|
||||
* Orders status items: on both sides a higher priority sits closer to the
|
||||
@@ -240,7 +240,9 @@ export function StatusInfo() {
|
||||
function TaskCancel({ task: t }: { task: BackgroundTask }) {
|
||||
if (t.done) return null;
|
||||
if (canCancel(t))
|
||||
return <IconButton icon="stop" size="small" title={tx`Cancel ${t.title}`} onClick={() => cancelTask(t.id)} />;
|
||||
return (
|
||||
<IconButton icon="stop" size="small" title={tx`Cancel ${txPart(t.title)}`} onClick={() => cancelTask(t.id)} />
|
||||
);
|
||||
const reason = t.cancelling ? tx("Cancelling…") : t.uncancellable;
|
||||
if (!reason) return null;
|
||||
// A disabled button gets no pointer events; the wrapper shows why.
|
||||
@@ -309,7 +311,7 @@ export function TaskStatus() {
|
||||
<BarButton
|
||||
data-background-tasks
|
||||
aria-expanded={open}
|
||||
aria-label={tx`Background tasks: ${current.title}`}
|
||||
aria-label={tx`Background tasks: ${txPart(current.title)}`}
|
||||
tooltip={current.message ?? current.title}
|
||||
onClick={() => useTaskPopup.setState({ open: !open })}
|
||||
className={styles.task}
|
||||
|
||||
Reference in new issue
Block a user