Compare commits

..
Author SHA1 Message Date
l0ng-ai 9b59961127 fix(debugger): keep values readable beside long type labels 2026-11-22 15:45:28 +08:00
43 changed files with 126 additions and 2038 deletions

No files matched your search

-1
View File
@@ -80,7 +80,6 @@ Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
this worktree's running MCP bridges and actual ports.
- `pnpm build` — typecheck + bundle frontend.
- `pnpm dogfood:build` / `pnpm dogfood:install` (or `mise run dogfood:build` / `mise run dogfood:install`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
-6
View File
@@ -948,12 +948,6 @@ pub struct AgentSkill {
/// True when frontmatter sets `disable-model-invocation: true` (defaults to `slashOnly`).
#[serde(default)]
pub disable_model_invocation: bool,
/// True when frontmatter sets `context: fork` (passed through natively to supporting CLIs).
#[serde(default)]
pub context_fork: bool,
/// Optional `paths` / `globs` patterns from frontmatter (passed through natively to supporting CLIs).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub paths: Vec<String>,
/// The `SKILL.md` passes validation (`name` matches its folder, `description` present).
pub valid: bool,
/// What validation found (`name` mismatch, missing or over-long description…).
+8 -95
View File
@@ -125,9 +125,10 @@ fn file_name(path: &Path) -> Option<String> {
path.file_name()?.to_str().map(str::to_owned)
}
/// The `key: value` lines between the leading `---` fences (folded `>` / `|` values joined).
struct Frontmatter {
fields: Vec<(String, String)>,
lists: Vec<(String, Vec<String>)>,
/// Where the body starts.
body: usize,
}
@@ -137,42 +138,22 @@ impl Frontmatter {
let mut lines = text.split_inclusive('\n');
let mut offset = 0;
let mut fields: Vec<(String, String)> = Vec::new();
let mut lists: Vec<(String, Vec<String>)> = Vec::new();
match lines.next() {
Some(first) if first.trim_end() == "---" => offset += first.len(),
_ => return Self { fields, lists, body: 0 },
_ => return Self { fields, body: 0 },
}
for line in lines {
offset += line.len();
let line = line.trim_end();
if line == "---" {
return Self { fields, lists, body: offset };
return Self { fields, body: offset };
}
let unindented_list_item = (line == "-" || line.starts_with("- ") || line.starts_with("-\t"))
&& fields.last().is_some_and(|(_, v)| v.is_empty());
if line.starts_with([' ', '\t']) || unindented_list_item {
let trimmed = line.trim();
if let Some(rest) = trimmed.strip_prefix('-')
&& (rest.is_empty() || rest.starts_with([' ', '\t']))
&& let Some((key, _)) = fields.last()
{
let item = unquote(rest.trim());
if !item.is_empty() {
if let Some((_, existing)) = lists.iter_mut().find(|(k, _)| k == key) {
existing.push(item.to_owned());
} else {
lists.push((key.clone(), vec![item.to_owned()]));
}
}
if unindented_list_item {
continue;
}
}
if line.starts_with([' ', '\t']) {
if let Some((_, value)) = fields.last_mut() {
if !value.is_empty() {
value.push(' ');
}
value.push_str(trimmed);
value.push_str(line.trim());
}
continue;
}
@@ -183,15 +164,11 @@ impl Frontmatter {
}
}
// No closing fence: not frontmatter.
Self { fields: Vec::new(), lists: Vec::new(), body: 0 }
Self { fields: Vec::new(), body: 0 }
}
fn get(&self, key: &str) -> Option<&str> {
self.fields.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v.as_str())
}
fn list(&self, key: &str) -> Option<&[String]> {
self.lists.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v.as_slice())
self.fields.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
}
/// `description`, else the body's first line.
@@ -528,8 +505,6 @@ fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSour
let hint = meta.get("argument-hint").map(|h| strip_ansi(h).trim().to_owned()).filter(|h| !h.is_empty());
let user_invocable = !meta.get("user-invocable").is_some_and(|v| v.eq_ignore_ascii_case("false"));
let disable_model_invocation = meta.get("disable-model-invocation").is_some_and(|v| v.eq_ignore_ascii_case("true"));
let context_fork = meta.get("context").is_some_and(|v| strip_ansi(v).trim().eq_ignore_ascii_case("fork"));
let paths = parse_skill_paths(&meta);
AgentSkill {
name,
description: truncate(&description),
@@ -539,35 +514,11 @@ fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSour
also_in: Vec::new(),
user_invocable,
disable_model_invocation,
context_fork,
paths,
valid: warnings.is_empty(),
warnings,
}
}
fn parse_skill_paths(meta: &Frontmatter) -> Vec<String> {
for key in ["paths", "globs"] {
if let Some(items) = meta.list(key) {
let cleaned: Vec<String> =
items.iter().map(|s| strip_ansi(s).trim().to_owned()).filter(|s| !s.is_empty()).collect();
if !cleaned.is_empty() {
return cleaned;
}
}
if let Some(raw) = meta.get(key) {
let trimmed = strip_ansi(raw);
let inner = trimmed.trim().strip_prefix('[').and_then(|s| s.strip_suffix(']')).unwrap_or(trimmed.trim());
let cleaned: Vec<String> =
inner.split(',').map(|p| unquote(p.trim()).trim().to_owned()).filter(|p| !p.is_empty()).collect();
if !cleaned.is_empty() {
return cleaned;
}
}
}
Vec::new()
}
/// A skill's mode, as one policy layer of the settings has it.
type Policies = BTreeMap<String, AgentSkillPolicy>;
@@ -1083,8 +1034,6 @@ mod tests {
also_in: Vec::new(),
user_invocable: true,
disable_model_invocation: false,
context_fork: false,
paths: Vec::new(),
valid: true,
warnings: Vec::new(),
}
@@ -1486,40 +1435,4 @@ mod tests {
let _ = stage(&farm, "claude", &off_states, &ws, Some(&home)).unwrap();
assert!(!farm.join(".claude/skills/release-notes").exists());
}
#[test]
fn parses_context_fork_and_paths_frontmatter_and_preserves_file_on_stage() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let ws = root.join("ws");
let raw_md = "---\n\
name: verify-ux\n\
description: Verify UX layouts in an isolated subagent\n\
context: fork\n\
paths:\n\
- \"src/**/*.tsx\"\n\
- crates/ide-agent/**/*.rs\n\
---\n\nRun visual checks.\n";
write(&ws.join(".openidea/skills/verify-ux/SKILL.md"), raw_md);
write(
&ws.join(".agents/skills/inline-globs/SKILL.md"),
"---\nname: inline-globs\ndescription: Scoped by globs\nglobs: [\"e2e/*.spec.ts\", \"src/ui/*.tsx\"]\n---\n",
);
let found = discover_skills(&ws, None);
let verify = found.iter().find(|s| s.name == "verify-ux").unwrap();
assert!(verify.context_fork);
assert_eq!(verify.paths, ["src/**/*.tsx", "crates/ide-agent/**/*.rs"]);
let inline = found.iter().find(|s| s.name == "inline-globs").unwrap();
assert!(!inline.context_fork);
assert_eq!(inline.paths, ["e2e/*.spec.ts", "src/ui/*.tsx"]);
// Staging passes `SKILL.md` through untouched so native CLIs execute `context: fork` / `paths`.
let states = resolve(found, None, &BTreeMap::new(), &BTreeMap::new(), true);
let farm = farm_dir(&root.join("store"), "fork-passthrough");
let _ = stage(&farm, "copilot", &states, &ws, None).unwrap();
let staged_md = std::fs::read_to_string(farm.join("copilot/verify-ux/SKILL.md")).unwrap();
assert_eq!(staged_md, raw_md);
}
}
+1 -4
View File
@@ -244,16 +244,13 @@ 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`, `mocha`, or `node --test` (`tsx --test`) with Node's own
/// from Jest / Vitest's: `playwright test`, or `node --test` (`tsx --test`) with Node's own
/// reporters (the IDE adds its reporter next to them, which a reporter chosen here would clash with).
fn script_test_runner(script: &str) -> Option<&'static str> {
let tokens: Vec<&str> = script.split(|c: char| c.is_whitespace() || matches!(c, '&' | '|' | ';')).collect();
if tokens.windows(2).any(|w| w[0] == "playwright" && w[1] == "test") {
return Some("playwright");
}
if tokens.iter().any(|t| matches!(t.rsplit('/').next(), Some("mocha" | "_mocha"))) {
return Some("mocha");
}
let node = tokens.iter().position(|t| matches!(*t, "node" | "tsx"))?;
// Node's own options: up to the script (`node server.js --test` passes `--test` to the program).
let mut options = Vec::new();
-14
View File
@@ -92,20 +92,6 @@ fn node_test_scripts() {
assert_eq!(find(&c, "npm:start").extras.test_runner, None);
}
#[test]
fn mocha_scripts() {
let dir = project(&[(
"package.json",
r#"{"scripts":{"spec":"mocha --recursive","test":"nyc ./node_modules/.bin/mocha","lint":"eslint mocha.config.js"}}"#,
)]);
let c = detect(dir.path());
let spec = find(&c, "npm:spec");
assert!(spec.is_test);
assert_eq!(spec.extras.test_runner.as_deref(), Some("mocha"));
assert_eq!(find(&c, "npm:test").extras.test_runner.as_deref(), Some("mocha"));
assert!(!find(&c, "npm:lint").is_test);
}
#[test]
fn package_manager_selection() {
for (lock, pm) in [("yarn.lock", "yarn"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("package-lock.json", "npm")] {
+1 -1
View File
@@ -67,7 +67,7 @@ mise run dev
`setup` runs `pnpm install` in this worktree. `dev` and `dev:app` use the same worktree-aware launchers as the direct commands. No shell activation is needed for `mise run`.
Run `mise tasks` to list all tasks. `mise run build` builds the frontend (not a desktop installer); `mise run dogfood:build` and `mise run dogfood:install` build and locally install a grey-icon dogfood desktop app that shares settings and data with the release app. Only one of the two apps runs at a time, since they share one instance; settings written by the newer dogfood build can make an older release ignore the settings file. The dogfood app never updates itself: run `dogfood:install` again to pick up new changes. `mise run dogfood:remote <remote_name>` builds and stages `openidea-server` on an SSH host configured in **Tools › SSH Configurations** (`--clean` removes the override). `mise run test` runs Vitest and `cargo test --workspace`; `mise run check` runs the format, lint, type and unused-code checks, then both test suites. Neither requires nextest or the plugin WASM target.
Run `mise tasks` to list all tasks. `mise run build` builds the frontend (not a desktop installer); `mise run dogfood:build` and `mise run dogfood:install` build and locally install a grey-icon dogfood desktop app that shares settings and data with the release app. Only one of the two apps runs at a time, since they share one instance; settings written by the newer dogfood build can make an older release ignore the settings file. The dogfood app never updates itself: run `dogfood:install` again to pick up new changes. `mise run test` runs Vitest and `cargo test --workspace`; `mise run check` runs the format, lint, type and unused-code checks, then both test suites. Neither requires nextest or the plugin WASM target.
## Worktrees
+1 -1
View File
@@ -66,7 +66,7 @@ Detected test configurations show results in the tree automatically. For your ow
| **Rerun** (in the Run tool window) | `⌘R` | `Ctrl+F5` |
| **Rerun Failed Tests** | — | — |
**Rerun Failed Tests** (in the Run tool window toolbar and Find Action) runs only the tests that failed in the last run, using each tool's filter syntax. It works for Cargo, Jest / Vitest, Playwright, `node --test`, Mocha, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks.
**Rerun Failed Tests** (in the Run tool window toolbar and Find Action) runs only the tests that failed in the last run, using each tool's filter syntax. It works for Cargo, Jest / Vitest, Playwright, `node --test`, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks.
## Navigate between code and tests
+2 -2
View File
@@ -74,7 +74,7 @@ On both pages, **Formatting provider** chooses between **Automatic (language ser
OpenIDEA detects run configurations when the project opens:
- One configuration per `package.json` script (`npm run build`, `pnpm run dev`, …), for the root package, nested packages and workspace members. Scripts named `test`, `jest`, `vitest` or `test:*`, and scripts that run `playwright test`, `node --test` or `mocha`, 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, Playwright Test, `node --test` and Mocha output is turned into the test tree, with **Rerun Failed Tests**. Playwright runs report through its `list` reporter unless the configuration names another; a test in the gutter runs by its line (`file:line`), and runs with several projects show each project under its file. `node --test` runs report through the IDE's reporter next to `spec`, added to `NODE_OPTIONS` (a script that chooses its own `--test-reporter` runs without the tree); single tests and reruns are selected by full name (`--test-name-pattern`). Mocha runs keep their reporter and load an IDE hook through `NODE_OPTIONS` that reports each test with its line; single tests and reruns use `--grep`, and tests in `test/` get gutter icons whatever their file name. **Run with Coverage** works for scripts that run `vitest` or `jest` (Vitest needs a coverage provider such as `@vitest/coverage-v8`; the IDE offers to add it) and for `node` / `tsx` / `ts-node` runs through `c8`. See [Testing](/en/guide/testing) and [Coverage](/en/guide/coverage).
Jest, Vitest, Playwright Test and `node --test` output is turned into the test tree, with **Rerun Failed Tests**. Playwright runs report through its `list` reporter unless the configuration names another; a test in the gutter runs by its line (`file:line`), and runs with several projects show each project under its file. `node --test` runs report through the IDE's reporter next to `spec`, added to `NODE_OPTIONS` (a script that chooses its own `--test-reporter` runs without the tree); single tests and reruns are selected by full name (`--test-name-pattern`). **Run with Coverage** works for scripts that run `vitest` or `jest` (Vitest needs a coverage provider such as `@vitest/coverage-v8`; the IDE offers to add it) and for `node` / `tsx` / `ts-node` runs through `c8`. See [Testing](/en/guide/testing) and [Coverage](/en/guide/coverage).
## Debugging
+1 -1
View File
@@ -67,7 +67,7 @@ mise run dev
`setup` 在当前 worktree 中执行 `pnpm install`。`dev` 和 `dev:app` 都沿用原来的启动脚本,保留 worktree 隔离。使用 `mise run` 不需要在 shell 中激活 mise。
运行 `mise tasks` 可以查看全部任务。`mise run build` 构建前端,不生成桌面安装包;`mise run dogfood:build` 和 `mise run dogfood:install` 用于构建并在本地安装灰色图标的 dogfood 桌面版(与正式版共享设置和数据)。两者共用同一个实例,同一时间只能运行一个;较新的 dogfood 版写入的设置可能让较旧的正式版忽略整个设置文件。dogfood 版不会自动更新,需要更新时重新运行 `dogfood:install`。`mise run dogfood:remote <remote_name>` 在 **工具 › SSH 配置** 中指定的远程主机上构建并部署 `openidea-server`(`--clean` 可移除覆盖)。`mise run test` 运行 Vitest 和 `cargo test --workspace`;`mise run check` 先检查格式、代码规范、类型和未使用的代码,再运行这两套测试。两者都不需要 nextest 或插件的 WASM 目标。
运行 `mise tasks` 可以查看全部任务。`mise run build` 构建前端,不生成桌面安装包;`mise run dogfood:build` 和 `mise run dogfood:install` 用于构建并在本地安装灰色图标的 dogfood 桌面版(与正式版共享设置和数据)。两者共用同一个实例,同一时间只能运行一个;较新的 dogfood 版写入的设置可能让较旧的正式版忽略整个设置文件。dogfood 版不会自动更新,需要更新时重新运行 `dogfood:install`。`mise run test` 运行 Vitest 和 `cargo test --workspace`;`mise run check` 先检查格式、代码规范、类型和未使用的代码,再运行这两套测试。两者都不需要 nextest 或插件的 WASM 目标。
## Worktree
+1 -1
View File
@@ -62,7 +62,7 @@ RSpec 有自己的配置类型(**RSpec 测试**)和检测到的 `rspec` 配
| **重新运行**(在“运行”工具窗口中) | `⌘R` | `Ctrl+F5` |
| **重新运行失败的测试** | — | — |
**重新运行失败的测试**(在“运行”工具窗口工具栏和“查找操作”中)只运行上一次失败的测试,会按各个工具自己的过滤语法生成命令。支持 Cargo、Jest / Vitest、Playwright、`node --test`、Mocha、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。
**重新运行失败的测试**(在“运行”工具窗口工具栏和“查找操作”中)只运行上一次失败的测试,会按各个工具自己的过滤语法生成命令。支持 Cargo、Jest / Vitest、Playwright、`node --test`、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。
## 在代码和测试之间跳转
+2 -2
View File
@@ -74,7 +74,7 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript
打开项目时,OpenIDEA 会自动检测运行配置:
- 每个 `package.json` 脚本一个配置(`npm run build`、`pnpm run dev` 等),覆盖根包、嵌套包和 workspace 成员。名为 `test`、`jest`、`vitest` 或 `test:*` 的脚本,以及运行 `playwright test`、`node --test` 或 `mocha` 的脚本,是测试配置。
- 每个 `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、`node --test` 和 Mocha 的输出会解析成测试树,支持 **重新运行失败的测试**。Playwright 运行时使用它的 `list` 报告器(配置里指定了其他报告器时除外);从行号栏运行单个测试时按行号选择(`file:line`),有多个 project 的运行会在文件下按 project 分组。`node --test` 运行时,IDE 通过 `NODE_OPTIONS` 在 `spec` 旁加上自己的报告器(脚本自己指定了 `--test-reporter` 时不显示测试树);单个测试和重新运行按完整名称选择(`--test-name-pattern`)。Mocha 运行保留它自己的报告器,并通过 `NODE_OPTIONS` 加载 IDE 的钩子,逐个报告测试及其所在行;单个测试和重新运行使用 `--grep`,`test/` 目录下的测试不论文件名都有行号栏图标。**使用覆盖率运行** 支持调用 `vitest` 或 `jest` 的脚本(Vitest 需要 `@vitest/coverage-v8` 之类的覆盖率 provider,缺失时 IDE 会提示添加),以及通过 `c8` 运行的 `node` / `tsx` / `ts-node`。详见[测试](/zh/guide/testing)和[覆盖率](/zh/guide/coverage)。
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)。
## 调试
-7
View File
@@ -73,8 +73,6 @@ const initialSkills: AgentSkillState[] = [
alsoIn: ["claudeWorkspace"],
userInvocable: true,
disableModelInvocation: false,
contextFork: true,
paths: ["src/**/*.tsx", "e2e/*.spec.ts"],
valid: true,
warnings: [],
},
@@ -328,8 +326,6 @@ test("manages multi-level skills in Settings and per-session overrides via Compo
const sessionPopup = page.getByRole("dialog", { name: "Session Skills" });
await expect(sessionPopup).toBeVisible();
await expect(sessionPopup).toContainText("verify");
await expect(sessionPopup).toContainText("fork");
await expect(sessionPopup).toContainText("paths");
await expect(sessionPopup).toContainText("impeccable");
await expect(sessionPopup).toContainText("Plugins");
await expect(sessionPopup).toContainText("release-notes");
@@ -356,12 +352,9 @@ test("manages multi-level skills in Settings and per-session overrides via Compo
await expect(settingsDialog).toBeVisible();
await expect(settingsDialog.getByRole("heading", { name: "Skills" })).toBeVisible();
await expect(settingsDialog.getByTitle(".claude/skills").first()).toHaveText("Claude Code");
await expect(settingsDialog.getByText("context: fork")).toBeVisible();
await expect(settingsDialog.getByText("paths (2)")).toBeVisible();
await settingsDialog.getByRole("button", { name: /^verify/ }).click();
await expect(settingsDialog.getByText("Claude Code (.claude/skills)")).toBeVisible();
await expect(settingsDialog.getByText("src/**/*.tsx, e2e/*.spec.ts")).toBeVisible();
await expect(settingsDialog.getByText("SKILL.md is valid")).toBeVisible();
await settingsDialog.getByRole("tab", { name: /Plugins/ }).click();
+56
View File
@@ -62,3 +62,59 @@ test("keeps values and their full-value action readable in a narrow debugger", a
.poll(() => routing.getByText(routingValue, { exact: true }).evaluate((el) => el.scrollWidth <= el.clientWidth + 1))
.toBe(true);
});
test("keeps a decimal value legible beside a long runtime type", async ({ workbench: page }) => {
const name = "dailySettlementTotal";
const type = "ExactSettlementAmountForCrossBorderReconciliation";
const value = "12486245.8067";
const countName = "pendingInvoices";
await page.setViewportSize({ width: 1100, height: 720 });
await stubDesktop(page);
await page.evaluate(
async ({ name, type, value, countName }) => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const serviceModule = "/src/workbench/contributions.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
const { toolWindowService } = await import(/* @vite-ignore */ serviceModule);
window.__ipc.handlers.debug_scopes = () => [{ name: "Locals", variablesReference: 100, expensive: false }];
window.__ipc.handlers.debug_variables = () => [
{ name, value, typeName: type, variablesReference: 0, evaluateName: name },
{ name: countName, value: "327", typeName: "int", variablesReference: 0, evaluateName: countName },
];
adoptSession(92, {
name: "Settlement",
adapter: "debugpy",
status: "paused",
selectedFrame: 11,
frames: [{ id: 11, name: "settle", path: null, line: 0, column: 0, presentationHint: null }],
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 280);
toolWindowService().show("debug", true);
},
{ name, type, value, countName },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
const variable = debug.getByRole("treeitem").filter({ hasText: name });
const amount = variable.getByText(value, { exact: true });
const annotation = variable.getByTitle(`{${type}}`, { exact: true });
await expect(amount).toBeVisible();
await expect.poll(() => amount.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(variable.getByTitle("Show", { exact: true })).toBeHidden();
await expect(annotation).toBeVisible();
const shortValueName = debug.getByText(countName, { exact: true });
await expect.poll(() => shortValueName.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await page.setViewportSize({ width: 1440, height: 760 });
await page.evaluate(async () => {
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
moveToolWindow("debug", "bottom");
setToolWindowSize("bottom", 310);
});
await expect.poll(() => annotation.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
});
-58
View File
@@ -284,64 +284,6 @@ test("test results keep counts, actions and selected output visible as the pane
await expect(output).toContainText(message);
});
test("test results keep elapsed time beside the counts", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1060, height: 740 });
const lines = [
"test_tax (test_ledger.CheckoutTests.test_tax) ... ok",
"test_refund (test_ledger.CheckoutTests.test_refund) ... FAIL",
"test_callback (test_ledger.CheckoutTests.test_callback) ... skipped 'Requires a callback'",
"Ran 3 tests in 0.170s",
"FAILED (failures=1, skipped=1)",
];
await stubRun(page, [{ kind: "stderr", text: lines.join("\n") + "\n" }], 1, {
id: "django:checkout-tests",
name: "Checkout tests",
kind: "django-test",
command: "python",
args: ["manage.py", "test", "-v", "2"],
isTest: true,
});
await page.keyboard.press("Control+r");
const run = page.getByRole("region", { name: "Run", exact: true });
const summary = run.getByRole("status").filter({ hasText: "1 failing" });
const ignored = summary.getByText("1 ignored", { exact: true });
const elapsed = summary.getByText("170 ms", { exact: true });
await expect(elapsed).toBeVisible();
for (const width of [1060, 540]) {
await page.setViewportSize({ width, height: 740 });
await expect
.poll(async () => {
const [count, duration] = await Promise.all([ignored.boundingBox(), elapsed.boundingBox()]);
return count && duration && Math.abs(count.y - duration.y) <= 1 ? duration.x - count.x - count.width : Infinity;
})
.toBeLessThanOrEqual(12);
}
await expect(summary).toHaveCSS("border-bottom-width", "2px");
});
test("test results retain a running label after the first test starts", async ({ workbench: page }) => {
const name = "TestCheckoutTotals";
await stubRun(
page,
[{ kind: "stdout", text: JSON.stringify({ Package: "example.com/checkout", Action: "run", Test: name }) + "\n" }],
null,
{
id: "go:checkout-tests",
name: "Checkout tests",
kind: "go",
command: "go",
args: ["test", "-json"],
isTest: true,
},
);
await page.keyboard.press("Control+r");
const run = page.getByRole("region", { name: "Run", exact: true });
await expect(run.getByRole("treeitem", { name: new RegExp(name) })).toBeVisible();
const summary = run.getByRole("status").filter({ hasText: "Running…" });
await expect(summary).toBeVisible();
await expect(summary).toHaveCSS("border-bottom-width", "2px");
});
test("test results group failure navigation and let users hide row durations", async ({ workbench: page }) => {
await page.setViewportSize({ width: 540, height: 740 });
const first = "TestCheckoutTotalsWithTaxRoundingAndPendingRefunds";
+1 -2
View File
@@ -11,7 +11,6 @@ something to show.
| `ts-app/` | Node 22+, pnpm/npm | `pnpm start` | `pnpm test` (vitest) | `OPENIDEA_FAIL=1 pnpm test` | unused function in `src/index.ts` |
| `playwright-app/` | Node 22+, npm (Playwright Test, no browser needed) | — | `npm test` | `OPENIDEA_FAIL=1 npm test` | unused function in `src/checkout.ts` |
| `node-test-app/` | Node 22+, npm (no dependencies) | — | `npm test` (node:test) | `OPENIDEA_FAIL=1 npm test` | unused constant in `src/inventory.js` |
| `mocha-app/` | Node 22+, npm | — | `npm test` (Mocha) | `OPENIDEA_FAIL=1 npm test` | unused constant in `src/pricing.js` |
| `python-app/` | Python 3.10+, pytest | `python -m tasks.cli` (from `src/`) | `pytest` | `OPENIDEA_FAIL=1 pytest` | unused imports in `models.py` |
| `go-app/` | Go 1.22+ | `go run ./cmd/server` | `go test ./...` | `OPENIDEA_FAIL=1 go test ./...` | unused `fmt.Sprintf` result in `internal/store/store.go` |
| `kotlin-gradle/` | JDK 21, Gradle 8 (no wrapper) | `gradle run` | `gradle test` | `gradle test -PopenideaFail` | unused variable in `App.kt` |
@@ -42,7 +41,7 @@ git init -q && git add -A && git commit -qm "initial" # for the VCS checks
```
Then open the folder with **File › Open…** (`⌘⇧⌥O`) or from the Welcome screen.
For `ts-app` / `playwright-app` / `mocha-app` / `polyglot/web` run `pnpm install` first; for `python-app` create a
For `ts-app` / `playwright-app` / `polyglot/web` run `pnpm install` first; for `python-app` create a
venv (`python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'`); for
`php-app` run `composer install` (debugging it needs Xdebug in the PHP on `PATH`).
-1
View File
@@ -1 +0,0 @@
node_modules
-13
View File
@@ -1,13 +0,0 @@
{
"name": "openidea-fixture-pricing",
"version": "0.1.0",
"private": true,
"description": "OpenIDEA QA fixture: Mocha specs for a small pricing module",
"type": "module",
"scripts": {
"test": "mocha"
},
"devDependencies": {
"mocha": "^10.8.0"
}
}
-14
View File
@@ -1,14 +0,0 @@
export function withTax(net, rate) {
if (rate < 0) throw new RangeError("tax rate must not be negative");
return Math.round(net * (1 + rate) * 100) / 100;
}
export function bulkDiscount(quantity) {
// TODO: read the tiers from the catalog instead of hard-coding them
if (quantity >= 100) return 0.15;
if (quantity >= 10) return 0.05;
return 0;
}
// An intentional warning: never used.
const CURRENCY = "EUR";
-29
View File
@@ -1,29 +0,0 @@
import assert from "node:assert/strict";
import { bulkDiscount, withTax } from "../src/pricing.js";
describe("pricing", function () {
describe("withTax", function () {
it("adds the rate", function () {
assert.equal(withTax(100, 0.2), 120);
});
it("rejects a negative rate", function () {
assert.throws(() => withTax(100, -0.1), RangeError);
});
});
describe("bulkDiscount", function () {
it("has no discount for a few items", function () {
assert.equal(bulkDiscount(3), 0);
});
it("discounts large orders", function () {
assert.equal(bulkDiscount(250), 0.15);
});
});
it("intentionally fails (set OPENIDEA_FAIL=1)", function () {
if (!process.env.OPENIDEA_FAIL) this.skip();
assert.equal(withTax(10, 0.1), 11.5);
});
});
-4
View File
@@ -29,10 +29,6 @@ description = "Build and install the local dogfood desktop app"
depends = ["dogfood:build"]
run = "pnpm dogfood:install --no-build"
[tasks."dogfood:remote"]
description = "Build and install a local dogfood openidea-server on a configured SSH remote"
run = "pnpm dogfood:remote"
[tasks.test]
description = "Run the frontend and Rust workspace tests"
run = ["pnpm test", "cargo test --workspace"]
+1 -3
View File
@@ -35,8 +35,7 @@
"eval": "node evals/run.ts",
"release:prepare": "node scripts/release-prepare.ts",
"dogfood:build": "node scripts/dogfood.ts build",
"dogfood:install": "node scripts/dogfood.ts install",
"dogfood:remote": "node scripts/dogfood-remote.ts"
"dogfood:install": "node scripts/dogfood.ts install"
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged"
@@ -95,7 +94,6 @@
},
"devDependencies": {
"@lezer/generator": "^1.8.1",
"@noble/hashes": "^2.4.0",
"@playwright/test": "^1.64.1",
"@tauri-apps/cli": "^2",
"@testing-library/jest-dom": "^7.0.1",
+19 -30
View File
@@ -154,9 +154,6 @@ importers:
'@lezer/generator':
specifier: ^1.8.1
version: 1.8.1
'@noble/hashes':
specifier: ^2.4.0
version: 2.4.0
'@playwright/test':
specifier: ^1.64.1
version: 1.64.1
@@ -165,7 +162,7 @@ importers:
version: 2.12.3
'@testing-library/jest-dom':
specifier: ^7.0.1
version: 7.0.1(@testing-library/[email protected])([email protected](@types/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])))
version: 7.0.1(@testing-library/[email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])))
'@testing-library/react':
specifier: ^16.3.3
version: 16.3.3(@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
@@ -186,7 +183,7 @@ importers:
version: 6.1.2([email protected](@types/[email protected])([email protected])([email protected]))
jsdom:
specifier: ^30.1.3
version: 30.1.3(@noble/[email protected])
version: 30.1.3
knip:
specifier: ^6.43.0
version: 6.43.0
@@ -213,7 +210,7 @@ importers:
version: 8.3.4(@types/[email protected])([email protected])([email protected])
vitest:
specifier: ^5.0.5
version: 5.0.5(@types/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected]))
version: 5.0.5(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected]))
yaml:
specifier: ^2.9.1
version: 2.9.1
@@ -533,10 +530,6 @@ packages:
'@emnapi/core': ^1.7.1 || 2.0.0-beta.2
'@emnapi/runtime': ^1.7.1 || 2.0.0-beta.2
'@noble/[email protected]':
resolution: {integrity: sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==}
engines: {node: '>= 20.19.0'}
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-A6xv7hDtnTm+xlZ7utn6rRQpRMJHRhVr3gjRGqlx0RUX84mNk0pAsy6YN/wWhuOTkaZhRrrzaLxf0NfbH77j2w==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -2710,9 +2703,7 @@ snapshots:
tslib: 2.8.1
optional: true
'@exodus/[email protected](@noble/[email protected])':
optionalDependencies:
'@noble/hashes': 2.4.0
'@exodus/[email protected]': {}
'@floating-ui/[email protected]':
dependencies:
@@ -2863,8 +2854,6 @@ snapshots:
'@tybys/wasm-util': 0.10.4
optional: true
'@noble/[email protected]': {}
'@oxc-parser/[email protected]':
optional: true
@@ -3252,7 +3241,7 @@ snapshots:
picocolors: 1.1.1
pretty-format: 27.5.1
'@testing-library/[email protected](@testing-library/[email protected])([email protected](@types/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])))':
'@testing-library/[email protected](@testing-library/[email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])))':
dependencies:
'@adobe/css-tools': 4.5.0
'@testing-library/dom': 10.4.2
@@ -3262,7 +3251,7 @@ snapshots:
picocolors: 1.1.1
redent: 3.0.0
optionalDependencies:
vitest: 5.0.5(@types/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected]))
vitest: 5.0.5(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected]))
'@testing-library/[email protected](@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':
dependencies:
@@ -3717,10 +3706,10 @@ snapshots:
d3: 7.9.0
lodash-es: 4.18.1
[email protected](@noble/[email protected]):
[email protected]:
dependencies:
whatwg-mimetype: 5.0.0
whatwg-url: 17.3.0(@noble/[email protected])
whatwg-url: 17.3.0
transitivePeerDependencies:
- '@noble/hashes'
@@ -3785,9 +3774,9 @@ snapshots:
[email protected]: {}
[email protected](@noble/[email protected]):
[email protected]:
dependencies:
'@exodus/bytes': 1.16.0(@noble/[email protected])
'@exodus/bytes': 1.16.0
transitivePeerDependencies:
- '@noble/hashes'
@@ -3811,17 +3800,17 @@ snapshots:
[email protected]: {}
[email protected](@noble/[email protected]):
[email protected]:
dependencies:
'@asamuzakjp/css-color': 7.1.7
'@asamuzakjp/dom-selector': 10.0.4
'@bramus/specificity': 2.4.3
'@csstools/css-syntax-patches-for-csstree': 1.1.15([email protected])
'@exodus/bytes': 1.16.0(@noble/[email protected])
'@exodus/bytes': 1.16.0
css-tree: 3.2.1
data-urls: 8.0.0(@noble/[email protected])
data-urls: 8.0.0
decimal.js: 10.6.0
html-encoding-sniffer: 7.0.0(@noble/[email protected])
html-encoding-sniffer: 7.0.0
is-potential-custom-element-name: 1.0.1
lru-cache: 11.5.3
parse5: 8.0.1
@@ -3831,7 +3820,7 @@ snapshots:
w3c-xmlserializer: 6.0.0
webidl-conversions: 8.0.1
whatwg-mimetype: 5.0.0
whatwg-url: 17.3.0(@noble/[email protected])
whatwg-url: 17.3.0
xml-name-validator: 5.0.0
transitivePeerDependencies:
- '@noble/hashes'
@@ -4252,7 +4241,7 @@ snapshots:
jiti: 2.7.0
yaml: 2.9.1
[email protected](@types/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])):
[email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])):
dependencies:
'@types/chai': 5.2.3
'@vitest/mocker': 5.0.5([email protected](@types/[email protected])([email protected])([email protected]))
@@ -4270,7 +4259,7 @@ snapshots:
why-is-node-running: 3.2.1
optionalDependencies:
'@types/node': 26.6.5
jsdom: 30.1.3(@noble/[email protected])
jsdom: 30.1.3
transitivePeerDependencies:
- msw
@@ -4286,9 +4275,9 @@ snapshots:
[email protected]: {}
[email protected](@noble/[email protected]):
[email protected]:
dependencies:
'@exodus/bytes': 1.16.0(@noble/[email protected])
'@exodus/bytes': 1.16.0
tr46: 7.0.0
webidl-conversions: 8.0.1
transitivePeerDependencies:
-225
View File
@@ -1,225 +0,0 @@
// @vitest-environment node
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
BIN_MARK,
blake3Hex16,
buildSshArgs,
cleanLocalDogfoodServers,
extractFramedBinary,
formatSshConnectionError,
isRustVersionAtLeast,
loadSshConfigs,
normalizeRemotePlatform,
parseDogfoodRemoteArgs,
parseRunningServerPids,
parseToml,
readWorkspaceMetadata,
resolveAppDirs,
resolveSshConfig,
stageLocalDogfoodServer,
workspaceTarArgs,
} from "./dogfood-remote.ts";
function blake3TestInput(length: number): Uint8Array {
const buf = new Uint8Array(length);
for (let i = 0; i < length; i++) {
buf[i] = i % 251;
}
return buf;
}
describe("dogfood:remote", () => {
it("computes the 16-character BLAKE3 build_id expected by remote_dev::ensure_server", () => {
// Reference vector (input[i] = i % 251, 2049 bytes -> multi-chunk tree) matching `blake3::hash(bytes).to_hex()[..16]`.
expect(blake3Hex16(blake3TestInput(2049))).toBe("5f4d72f40d7a5f82");
});
it("parses both UI inline-table and [[ssh.configs]] TOML settings formats", () => {
const temp = mkdtempSync(join(tmpdir(), "openidea-dogfood-remote-"));
try {
const configDir = join(temp, "config");
mkdirSync(configDir, { recursive: true });
writeFileSync(
join(configDir, "settings.toml"),
[
"# Global settings written by Settings › Tools › SSH Configurations",
"[appearance]",
'locale = "en"',
"",
"[ssh]",
'configs = [{ id = "cfg-1", name = "my-remote", host = "remote-host.example.com", port = 2222, user = "alice", auth = "keyPair", keyFile = "~/.ssh/id_ed25519", saveSecret = false }]',
"",
].join("\n"),
);
const loaded = loadSshConfigs(configDir);
expect(loaded).toEqual([
{
id: "cfg-1",
name: "my-remote",
host: "remote-host.example.com",
port: 2222,
user: "alice",
auth: "keyPair",
keyFile: "~/.ssh/id_ed25519",
},
]);
const resolved = resolveSshConfig(loaded, "my-remote");
expect(buildSshArgs(resolved, ["StrictHostKeyChecking=no"], "/Users/alice")).toEqual([
"-p",
"2222",
"-l",
"alice",
"-i",
join("/Users/alice", ".ssh", "id_ed25519"),
"-o",
"ConnectTimeout=10",
"-o",
"StrictHostKeyChecking=no",
"--",
"remote-host.example.com",
]);
expect(() => resolveSshConfig(loaded, "missing-box")).toThrow(/Available SSH configurations: my-remote/);
const tableDoc = parseToml(
["[[ssh.configs]]", 'name = "alt-remote"', 'host = "alt.example.com"', 'user = "bob"', 'auth = "openSsh"'].join(
"\n",
),
);
expect(tableDoc).toEqual({
ssh: {
configs: [{ name: "alt-remote", host: "alt.example.com", user: "bob", auth: "openSsh" }],
},
});
} finally {
rmSync(temp, { recursive: true, force: true });
}
});
it("resolves config and custom local-data directories like ide_host::data_dirs", () => {
const temp = mkdtempSync(join(tmpdir(), "openidea-dirs-"));
try {
const cfgRoot = join(temp, "cfg");
const customLocalRoot = join(temp, "custom-caches");
mkdirSync(join(cfgRoot, "ai.l0ng.openidea"), { recursive: true });
writeFileSync(join(cfgRoot, "ai.l0ng.openidea", "local-data-dir.txt"), `${customLocalRoot}\n`);
expect(
resolveAppDirs({
platform: "darwin",
env: { OPENIDEA_CONFIG_DIR: cfgRoot },
home: "/Users/alice",
}),
).toEqual({
configDir: join(cfgRoot, "ai.l0ng.openidea"),
localDataDir: join(customLocalRoot, "ai.l0ng.openidea"),
});
} finally {
rmSync(temp, { recursive: true, force: true });
}
});
it("parses CLI flags and normalizes remote uname platforms", () => {
expect(
parseDogfoodRemoteArgs(["--", "my-remote", "--install-rust", "--restart", "--ssh-opt", "Port=2222"]),
).toEqual({
remoteName: "my-remote",
clean: false,
installRust: true,
restart: "always",
sshOpts: ["Port=2222"],
});
expect(parseDogfoodRemoteArgs(["--clean"])).toEqual({
remoteName: undefined,
clean: true,
installRust: false,
restart: "prompt",
sshOpts: [],
});
expect(() => parseDogfoodRemoteArgs(["my-remote", "--restart", "--no-restart"])).toThrow(/Cannot pass both/);
expect(() => parseDogfoodRemoteArgs([])).toThrow(/Usage:/);
expect(normalizeRemotePlatform("Linux x86_64\n")).toEqual({ os: "linux", arch: "x86_64" });
expect(normalizeRemotePlatform("Linux aarch64")).toEqual({ os: "linux", arch: "aarch64" });
expect(normalizeRemotePlatform("Darwin arm64")).toEqual({ os: "macos", arch: "aarch64" });
});
it("handles connection errors, Rust version checks, and running openidea-server PID detection", () => {
const repoRoot = join(import.meta.dirname, "..");
const meta = readWorkspaceMetadata(repoRoot);
expect(meta.version).toMatch(/^\d+\.\d+\.\d+/);
expect(meta.rustVersion).toMatch(/^\d+\.\d+/);
expect(isRustVersionAtLeast("rustc 1.96.0 (0000000 2026-06-01)", "1.96")).toBe(true);
expect(isRustVersionAtLeast("rustc 1.100.0-nightly (abcdef0 2026-11-01)", "1.96")).toBe(true);
expect(isRustVersionAtLeast("rustc 1.75.0 (82e1608df 2023-12-21)", "1.96")).toBe(false);
expect(isRustVersionAtLeast("no-rustc", "1.96")).toBe(false);
const errMsg = formatSshConnectionError(
"my-remote",
"[email protected]:22",
"Warning: Permanently added 'remote-host.example.com' (ED25519) to the list of known hosts.\nssh: connect to host remote-host.example.com port 22: Connection refused\n",
255,
);
expect(errMsg).toContain("Cannot connect to SSH remote 'my-remote' ([email protected]:22)");
expect(errMsg).toContain("Connection refused");
expect(errMsg).not.toContain("Permanently added");
const psText = [
" 101 /bin/bash",
" 4321 /home/alice/.openidea/server/0.1.50/42bd8ae098588d22/openidea-server --stdio",
" 4399 openidea-server --stdio",
" 4500 grep openidea-server",
].join("\n");
expect(parseRunningServerPids(psText)).toEqual([4321, 4399]);
});
it("backs up an existing cached release server on stage and restores it on --clean", () => {
const temp = mkdtempSync(join(tmpdir(), "openidea-stage-"));
try {
const serverDir = join(temp, "server", "0.1.50", "linux-aarch64");
mkdirSync(serverDir, { recursive: true });
const binPath = join(serverDir, "openidea-server");
writeFileSync(binPath, "official-release-binary");
const dogfoodBytes = Buffer.from("dogfood-server-binary-v1");
const id1 = blake3Hex16(dogfoodBytes);
stageLocalDogfoodServer(temp, "0.1.50", "linux", "aarch64", dogfoodBytes, id1);
expect(readFileSync(binPath, "utf8")).toBe("dogfood-server-binary-v1");
// A second dogfood build must keep the original release backup intact.
const dogfoodBytes2 = Buffer.from("dogfood-server-binary-v2");
const id2 = blake3Hex16(dogfoodBytes2);
stageLocalDogfoodServer(temp, "0.1.50", "linux", "aarch64", dogfoodBytes2, id2);
expect(readFileSync(binPath, "utf8")).toBe("dogfood-server-binary-v2");
const cleaned = cleanLocalDogfoodServers(temp, "0.1.50", "linux-aarch64");
expect(cleaned).toEqual([{ platformKey: "linux-aarch64", buildId: id2, restoredRelease: true }]);
expect(existsSync(binPath)).toBe(true);
expect(readFileSync(binPath, "utf8")).toBe("official-release-binary");
} finally {
rmSync(temp, { recursive: true, force: true });
}
});
it("strips login shell banners before the framed binary stream and verifies SHA-256", () => {
const payload = Buffer.from([0x7f, 0x45, 0x4c, 0x46, 1, 2, 3, 4]);
const sha = createHash("sha256").update(payload).digest("hex");
const framed = Buffer.concat([Buffer.from(`Welcome to Ubuntu!\n${BIN_MARK}${sha}\n`, "utf8"), payload]);
expect(extractFramedBinary(framed)).toEqual(payload);
expect(() => extractFramedBinary(Buffer.from(`${BIN_MARK}${"0".repeat(64)}\ncorrupt`))).toThrow(/SHA-256 mismatch/);
});
it("anchors tar Cargo target exclusions so nested source folders like crates/ide-ssh/src/target stay included", () => {
const args = workspaceTarArgs();
expect(args).not.toContain("--exclude=target");
expect(args).toContain("--exclude=plugins/target");
expect(args).toContain("crates");
expect(args).toContain("generators");
});
});
File diff suppressed because it is too large. Load diff
-11
View File
@@ -89,17 +89,6 @@ const CASES: Record<string, Case | Case[]> = {
file: "test/inventory.test.js",
},
},
{
fixture: "mocha-app",
setup: npmInstall,
tests: {
config: "npm:test",
failing: (c) => env(c, { OPENIDEA_FAIL: "1" }),
passed: 4,
failed: "intentionally fails (set OPENIDEA_FAIL=1)",
file: "test/pricing.spec.js",
},
},
],
python: {
fixture: "python-app",
-8
View File
@@ -2904,10 +2904,6 @@ export type AgentSkill_Deserialize = {
userInvocable?: boolean,
/** True when frontmatter sets `disable-model-invocation: true` (defaults to `slashOnly`). */
disableModelInvocation?: boolean,
/** True when frontmatter sets `context: fork` (passed through natively to supporting CLIs). */
contextFork?: boolean,
/** Optional `paths` / `globs` patterns from frontmatter (passed through natively to supporting CLIs). */
paths?: string[],
/** The `SKILL.md` passes validation (`name` matches its folder, `description` present). */
valid: boolean,
/** What validation found (`name` mismatch, missing or over-long description…). */
@@ -2930,10 +2926,6 @@ export type AgentSkill_Serialize = {
userInvocable: boolean,
/** True when frontmatter sets `disable-model-invocation: true` (defaults to `slashOnly`). */
disableModelInvocation: boolean,
/** True when frontmatter sets `context: fork` (passed through natively to supporting CLIs). */
contextFork: boolean,
/** Optional `paths` / `globs` patterns from frontmatter (passed through natively to supporting CLIs). */
paths?: string[],
/** The `SKILL.md` passes validation (`name` matches its folder, `description` present). */
valid: boolean,
/** What validation found (`name` mismatch, missing or over-long description…). */
-16
View File
@@ -277,20 +277,4 @@ describe("SkillsPage", () => {
);
await waitFor(() => expect(screen.getByText("deploy-script")).toBeInTheDocument());
});
it("displays context: fork and paths badges and expands paths in the inspector", async () => {
const forked = [
state("verify-ux", "workspace", "auto", {
contextFork: true,
paths: ["src/**/*.tsx", "e2e/*.spec.ts"],
}),
];
render(<SkillsPage backend={{ list: vi.fn(async () => forked), setMode: vi.fn(async () => forked) }} />);
await waitFor(() => expect(screen.getByText("verify-ux")).toBeInTheDocument());
expect(screen.getByText("context: fork")).toBeInTheDocument();
expect(screen.getByText("paths (2)")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: /^verify-ux/ }));
expect(await screen.findByText("src/**/*.tsx, e2e/*.spec.ts")).toBeInTheDocument();
});
});
-18
View File
@@ -362,16 +362,6 @@ function SkillCard({
{skill.alsoIn?.map((s) => tx(SKILL_SOURCE_GROUPS[s].label)).join(", ")}
</span>
)}
{skill.contextFork && (
<span className={page.tag} title={tx("Runs in a subagent where supported (context: fork)")}>
context: fork
</span>
)}
{(skill.paths?.length ?? 0) > 0 && (
<span className={page.tag} title={skill.paths?.join(", ")}>
{formatMessage(tx("paths ({count})"), { count: skill.paths?.length ?? 0 })}
</span>
)}
{!skill.valid && (
<span className={clsx(page.tag, page.tagWarning)}>
<T>Invalid SKILL.md</T>
@@ -436,14 +426,6 @@ function SkillCard({
</span>
</>
)}
{(skill.paths?.length ?? 0) > 0 && (
<>
<span className={page.metaLabel}>
<T>Paths</T>
</span>
<span className={page.metaValue}>{skill.paths?.join(", ")}</span>
</>
)}
<span className={page.metaLabel}>
<T>Validation</T>
</span>
-25
View File
@@ -165,31 +165,6 @@ describe("SkillsPicker", () => {
await waitFor(() => expect(screen.getByRole("button", { name: "Skills" })).toHaveTextContent("Skills3/5"));
});
it("shows fork and paths pills on skills with context: fork and paths frontmatter", async () => {
const richSkills: AgentSkillState[] = [
{
skill: {
name: "verify-ux",
description: "Verify UX layouts",
path: "/ws/.agents/skills/verify-ux",
source: "workspace",
contextFork: true,
paths: ["src/**/*.tsx", "e2e/*.spec.ts"],
valid: true,
warnings: [],
},
mode: "auto",
origin: "none",
},
];
render(<Harness skills={richSkills} />);
fireEvent.click(screen.getByRole("button", { name: "Skills" }));
expect(await screen.findByText("fork")).toBeInTheDocument();
expect(screen.getByText("paths")).toBeInTheDocument();
expect(screen.getByTitle("Verify UX layouts · src/**/*.tsx, e2e/*.spec.ts")).toBeInTheDocument();
});
it("shows an empty state without skills", async () => {
render(<Harness skills={[]} />);
+2 -5
View File
@@ -154,8 +154,7 @@ function GroupRows({
function SessionSkillRow({ item, onToggle }: { item: SessionSkillItem; onToggle: (enabled: boolean) => void }) {
const tx = useTx();
const { skill } = item.state;
const description = skill.description;
const description = item.state.skill.description;
return (
<PickerRow
name={item.name}
@@ -163,12 +162,10 @@ function SessionSkillRow({ item, onToggle }: { item: SessionSkillItem; onToggle:
<>
<ModePill mode={item.mode} />
{item.overridden && <PickerSessionPill />}
{skill.contextFork && <PickerPill>fork</PickerPill>}
{(skill.paths?.length ?? 0) > 0 && <PickerPill>paths</PickerPill>}
</>
}
sub={description || undefined}
subTitle={skill.paths?.length ? `${description} · ${skill.paths.join(", ")}` : description}
subTitle={description}
controls={
item.locked ? (
<PickerPill>
@@ -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);
+7 -16
View File
@@ -258,12 +258,12 @@
.testStatusBar {
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
min-height: 28px;
border-bottom: 1px solid var(--border);
}
.testToolbar {
flex-wrap: wrap;
gap: var(--space-1);
padding: var(--space-0-5) var(--space-1);
}
@@ -275,36 +275,27 @@
border-inline-end: 1px solid var(--border);
}
.testStatusBar {
gap: var(--space-2);
gap: var(--space-0-5) var(--space-2);
padding: var(--space-0-5) var(--space-2);
border-block-end-width: var(--space-0-5);
font-size: var(--fs-ui);
color: var(--fg-secondary);
}
.testStatusBar[data-outcome="passed"] {
border-block-end-color: var(--success);
}
.testStatusBar[data-outcome="skipped"] {
border-block-end-color: var(--warning);
}
.testStatusBar[data-running] {
border-block-end-color: var(--accent);
}
.testStatusBar[data-outcome="failed"] {
border-block-end-color: var(--danger);
}
.testCounts {
flex: 1 1 auto;
display: flex;
flex-wrap: wrap;
gap: var(--space-0-5) var(--space-2);
min-width: 0;
white-space: nowrap;
}
.testStatus {
.testStatus,
.testTotalDuration {
flex: none;
}
.testTotalDuration {
margin-left: auto;
color: var(--fg-subtle);
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
}
.testTree {
+13 -10
View File
@@ -112,24 +112,27 @@ export function TestStatusBar({
running: boolean;
}) {
const counts = useMemo(() => results.counts(), [results, version]); // eslint-disable-line react-hooks/exhaustive-deps
const outcome = counts.failed ? "failed" : counts.passed ? "passed" : counts.skipped ? "skipped" : null;
const status = running
? "running"
: counts.failed
? "failed"
: counts.passed
? "passed"
: counts.skipped
? "skipped"
: null;
const duration = results.summary.durationMs;
return (
<div
className={styles.testStatusBar}
role="status"
data-running={running || undefined}
data-outcome={outcome ?? undefined}
>
<StatusIcon status={running ? "running" : outcome} />
<div className={styles.testStatusBar} role="status">
<StatusIcon status={status} />
<span className={styles.testCounts}>
{counts.failed > 0 && <span className={styles.failed}>{tx`${counts.failed} failing`}</span>}
{counts.passed > 0 && <span>{tx`${counts.passed} passed`}</span>}
{counts.skipped > 0 && <span className={styles.skipped}>{tx`${counts.skipped} ignored`}</span>}
{!outcome && <span className={styles.skipped}>{running ? tx("Running…") : tx("No tests")}</span>}
{duration !== undefined && <span className={styles.testTotalDuration}>{formatDuration(duration)}</span>}
{counts.total === 0 && <span className={styles.skipped}>{running ? tx("Running…") : tx("No tests")}</span>}
</span>
{duration !== undefined && <span className={styles.testTotalDuration}>{formatDuration(duration)}</span>}
</div>
);
}
+3 -3
View File
@@ -714,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,
// node:test and Mocha through the IDE's own reporters (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)
@@ -723,7 +723,7 @@ function newRuntime(config: RunConfig): SessionRuntime {
? new TeamcityOutput(feed)
: framework === "ruby" && config.kind !== "rspec"
? new RubyTestOutput(feed)
: framework === "node-test" || framework === "mocha"
: framework === "node-test"
? new RecordsOutput(feed)
: null;
const runtime: SessionRuntime = {
+3 -5
View File
@@ -134,9 +134,9 @@ function rustTargets(lines: string[], relPath: string): RunTarget[] {
);
}
/** Jest / Vitest `describe` / `test` / `it` (Mocha's `specify` too), and Playwright's `test.describe` and modifiers. */
/** Jest / Vitest `describe` / `test` / `it`, and Playwright's `test.describe` and modifiers. */
const JS_RE =
/^(\s*)(test\.describe|describe|suite|context|test|it|specify)\b(?:\.(?:only|skip|todo|concurrent|failing|sequential|fixme|fail|serial|parallel))*(\.each\s*(?:\(.*?\)|`[^`]*`))?\s*\(\s*(['"`])((?:\\.|(?!\4).)*)\4/;
/^(\s*)(test\.describe|describe|suite|context|test|it)\b(?:\.(?:only|skip|todo|concurrent|failing|sequential|fixme|fail|serial|parallel))*(\.each\s*(?:\(.*?\)|`[^`]*`))?\s*\(\s*(['"`])((?:\\.|(?!\4).)*)\4/;
function jsTargets(lines: string[]): RunTarget[] {
const out: RunTarget[] = [];
@@ -381,8 +381,7 @@ export function detectRunTargets(text: string, relPath: string, django = false):
case "rust":
return rustTargets(lines, relPath);
case "js":
// `test/`: where Mocha (and `node --test`) look for tests by default, whatever the file's name.
return /\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)(__tests__|test)\//.test(relPath) ? jsTargets(lines) : [];
return /\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)__tests__\//.test(relPath) ? jsTargets(lines) : [];
case "python":
return pythonTargets(lines).filter(
(t) =>
@@ -478,7 +477,6 @@ export function targetConfig(
// node:test selects by full name, through NODE_OPTIONS (see `nodeTest.ts`).
if (frameworkFor(file) === "node-test")
return { ...named(file.args), env: withNodeTestNamePattern(file.env, jsNamePattern(target)) };
if (frameworkFor(file) === "mocha") return named([...file.args, "--grep", jsNamePattern(target)]);
switch (file.kind) {
case "dotnet-test": {
const methods =
-5
View File
@@ -4,7 +4,6 @@ import { cargoParser } from "./cargo";
import { goParser } from "./go";
import { jsParser } from "./js";
import { jvmParser } from "./jvm";
import { withMochaHook } from "./mocha";
import { withNodeTestReporter } from "./nodeTest";
import { recordsParser } from "./records";
import { phpunitParser, withTeamcity } from "./phpunit";
@@ -46,7 +45,6 @@ export type Framework =
| "js"
| "playwright"
| "node-test"
| "mocha"
| "pytest"
| "unittest"
| "phpunit"
@@ -65,7 +63,6 @@ export function frameworkFor(config: FrameworkConfig): Framework {
if (config.testRunner === "playwright" || /\bplaywright\s+test\b/.test(cmd)) return "playwright";
if (config.testRunner === "node-test" || /(^|[\s/\\])(node|tsx)(\.exe)?(\s+-\S*)*\s+--test(\s|$)/.test(cmd))
return "node-test";
if (config.testRunner === "mocha" || /(^|[\s/\\])_?mocha(\.cmd|\.js)?(\s|$)/.test(cmd)) return "mocha";
switch (config.kind) {
case "dotnet-test":
return "dotnet";
@@ -130,7 +127,6 @@ function rubyVerbose<T extends Pick<RunConfig, "kind" | "command" | "args">>(con
*/
export function withTestReporting<T extends FrameworkConfig>(config: T): T {
if (frameworkFor(config) === "node-test") return { ...config, env: withNodeTestReporter(config.env ?? {}) };
if (frameworkFor(config) === "mocha") return { ...config, env: withMochaHook(config.env ?? {}) };
if (frameworkFor(config) === "playwright") {
// The list reporter prints a line per test; a project's own (`html`, `dot` on CI) may print none.
const chosen = config.args.some((a) => a === "--reporter" || a.startsWith("--reporter="));
@@ -174,7 +170,6 @@ export function createTestParser(config: FrameworkConfig): TestOutputParser {
case "playwright":
return playwrightParser();
case "node-test":
case "mocha":
return recordsParser();
case "pytest":
return pytestParser();
-119
View File
@@ -1,119 +0,0 @@
import { describe, expect, it } from "vitest";
import type { RunConfig } from "@/platform/ipc";
import { detectRunTargets, targetConfig } from "../targets";
import { createTestParser, frameworkFor, nodeOutput, parseAll, TestResults, withTestReporting } from "./index";
import { failedTestPaths, rerunFailedConfigs } from "./rerun";
const cfg = (over: Partial<RunConfig> & { id: string; kind: string }): RunConfig => ({
name: over.id,
command: over.kind,
args: [],
cwd: null,
env: {},
detected: true,
isTest: true,
debugAdapter: "js-debug",
...over,
});
/** `npm run test` whose script is `mocha` (detection records the runner). */
const script = cfg({ id: "npm:test", kind: "npm", command: "npm", args: ["run", "test"], testRunner: "mocha" });
// `mocha` (10.8, spec reporter) with the IDE's hook, as printed.
const OUTPUT = String.raw`
pricing
withTax
✔ adds the rate
@@openidea:test@@{"path":["test/pricing.spec.js","pricing","withTax","adds the rate"],"status":"passed","ms":0,"line":6,"col":5}
1) intentionally fails (set OPENIDEA_FAIL=1)
@@openidea:test@@{"path":["test/pricing.spec.js","pricing","intentionally fails (set OPENIDEA_FAIL=1)"],"status":"failed","ms":1,"line":25,"col":3,"error":"AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:\n\n11 !== 11.5\n\n at Context.<anonymous> (file:///work/shop/test/pricing.spec.js:27:12)"}
- later
@@openidea:test@@{"path":["test/pricing.spec.js","pricing","later"],"status":"skipped","line":29,"col":3}
1 passing (3ms)
1 pending
1 failing
`;
function results(text: string) {
const r = new TestResults();
r.apply(parseAll(createTestParser(script), text));
return r;
}
describe("Mocha runs", () => {
it("are recognised by the recorded runner or the command line", () => {
expect(frameworkFor(script)).toBe("mocha");
expect(frameworkFor(cfg({ id: "x", kind: "node", command: "npx", args: ["mocha", "--recursive"] }))).toBe("mocha");
expect(frameworkFor(cfg({ id: "x", kind: "shell", command: "./node_modules/.bin/_mocha", args: [] }))).toBe(
"mocha",
);
expect(frameworkFor(cfg({ id: "x", kind: "node", command: "node", args: ["mocha.config.js"] }))).not.toBe("mocha");
});
it("load the IDE's hook through NODE_OPTIONS, once", () => {
const launched = withTestReporting({ ...script, env: { NODE_OPTIONS: "--enable-source-maps" } });
const [own, hook] = launched.env.NODE_OPTIONS!.split(" ");
expect(own).toBe("--enable-source-maps");
expect(hook).toMatch(/^--import=data:text\/javascript;base64,/);
expect(withTestReporting(launched).env).toEqual(launched.env);
expect(launched.args).toEqual(script.args);
});
it("build the tree from the hook's records, with declaration lines and failures", () => {
const r = results(OUTPUT);
expect(r.counts()).toMatchObject({ passed: 1, failed: 1, skipped: 1 });
const adds = r.get(["test/pricing.spec.js", "pricing", "withTax", "adds the rate"].join("\u0000"))!;
expect(adds.location).toEqual({ path: "test/pricing.spec.js", line: 6, col: 5, resolve: "path" });
expect(nodeOutput(r.firstFailure()!).join("\n")).toContain("11 !== 11.5");
});
it("rerun failed tests by file and full title with --grep", async () => {
const [rerun] = await rerunFailedConfigs(
{ ...script, args: ["run", "test", "--", "--grep", "old"] },
failedTestPaths(results(OUTPUT)),
);
expect(rerun!.args).toEqual([
"run",
"test",
"--",
"test/pricing.spec.js",
"--grep",
"^(?:pricing intentionally fails \\(set OPENIDEA_FAIL=1\\))$",
]);
});
});
describe("Mocha gutter targets", () => {
const src = [
"describe('pricing', function () {", // 0
" specify('adds tax', function () {});", // 1
" context('bulk', function () {", // 2
" it('discounts', function () {});", // 3
" });",
"});",
].join("\n");
it("are found in test/ whatever the file's name, `specify` included", () => {
expect(detectRunTargets(src, "test/pricing.js").map((t) => [t.line, t.kind, t.path.join("/")])).toEqual([
[0, "suite", "pricing"],
[1, "test", "pricing/adds tax"],
[2, "suite", "pricing/bulk"],
[3, "test", "pricing/bulk/discounts"],
]);
expect(detectRunTargets(src, "lib/pricing.js")).toEqual([]);
});
it("run by file and full title", () => {
const targets = detectRunTargets(src, "test/pricing.js");
expect(targetConfig(targets[3]!, "test/pricing.js", [script], src)?.args).toEqual([
"run",
"test",
"--",
"test/pricing.js",
"--grep",
"^pricing bulk discounts$",
]);
});
});
-15
View File
@@ -1,15 +0,0 @@
/**
* Mocha: the IDE's hook (`mochaHook.js`), imported through `NODE_OPTIONS`, prints a record per
* finished test (`records.ts`) next to the run's own reporter, whichever it is. Tests are selected
* with Mocha's own `--grep`.
*/
import HOOK_SOURCE from "./mochaHook.js?raw";
const HOOK = `--import=data:text/javascript;base64,${btoa(HOOK_SOURCE)}`;
/** `NODE_OPTIONS` with the IDE's hook added (once). */
export function withMochaHook(env: Record<string, string>): Record<string, string> {
const options = env.NODE_OPTIONS ?? "";
if (options.includes(HOOK)) return env;
return { ...env, NODE_OPTIONS: [options, HOOK].filter(Boolean).join(" ") };
}
-79
View File
@@ -1,79 +0,0 @@
// The IDE's Mocha hook (`--import`, passed as a data: URL through NODE_OPTIONS): once Mocha is
// loaded, every test a run reports also prints a record (`records.ts`) next to the run's own
// reporter, with the line the test is declared on (Mocha reports none). Runs in the user's
// Node (20+), so plain ESM without dependencies; reporting must never break a test run.
import Module from "node:module";
import { relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const MARK = "@@openidea:test@@";
const DECLARED = Symbol("openidea.declared");
const FRAME = /(?:\(|\s)((?:file:\/\/\/?)?(?:[A-Za-z]:)?[^:()]+):(\d+):(\d+)\)?$/;
const fileOf = (path) => relative(process.cwd(), path).split("\\").join("/");
/** Where in `file` the code running now was called from: a test's declaration while Mocha loads the file. */
function declaredIn(file) {
for (const frame of (new Error().stack ?? "").split("\n").slice(1)) {
const m = FRAME.exec(frame);
if (!m) continue;
const path = m[1].startsWith("file:") ? fileURLToPath(m[1]) : m[1];
if (resolve(path) === file) return { line: Number(m[2]), col: Number(m[3]) };
}
return null;
}
function report(test, status, error) {
try {
if (!test.file) return;
const at = test[DECLARED];
const record = {
path: [fileOf(test.file), ...test.titlePath()],
status,
ms: test.duration,
line: at?.line,
col: at?.col,
error: error === undefined ? undefined : String((error && error.stack) || error),
};
process.stdout.write(`${MARK}${JSON.stringify(record)}\n`);
} catch {
// A test object without its usual shape (a plugin's): no record.
}
}
function watch(Mocha) {
const addTest = Mocha.Suite.prototype.addTest;
Mocha.Suite.prototype.addTest = function (test) {
try {
if (test && test.file) test[DECLARED] = declaredIn(resolve(test.file));
} catch {
// No declaration line.
}
return addTest.call(this, test);
};
const run = Mocha.Runner.prototype.run;
Mocha.Runner.prototype.run = function (...args) {
this.on("pass", (test) => report(test, "passed"));
this.on("pending", (test) => report(test, "skipped"));
// A failing hook fails the test it ran for, or reports as itself.
this.on("fail", (runnable, error) =>
report(runnable.type === "hook" ? (runnable.ctx?.currentTest ?? runnable) : runnable, "failed", error),
);
return run.apply(this, args);
};
}
const load = Module._load;
let watching = false;
Module._load = function (...args) {
const exports = load.apply(this, args);
if (!watching && typeof exports === "function" && exports.Runner && exports.Suite && exports.reporters) {
watching = true;
try {
watch(exports);
} catch {
// Another Mocha than expected: the run goes on without records.
}
}
return exports;
};
-12
View File
@@ -273,18 +273,6 @@ function builtinTestsConfig(config: RunConfig, paths: string[][], name: string):
: { ...config.env };
return { ...config, args: appendScriptArgs(config.command, config.args, files), name, detected: true, env };
}
case "mocha": {
// Mocha's `--grep` matches a test's full title: its describe chain and name, space separated.
const files = unique(paths.map((p) => p[0]!).filter(Boolean));
const names = unique(paths.filter((p) => p.length > 1).map((p) => p.slice(1).join(" ")));
if (!files.length) return null;
const { before, after } = splitDashDash(config.args);
const flags = ["-g", "--grep", "-f", "--fgrep"];
const base = after === null ? dropFlag(before, flags) : [...before, "--", ...dropFlag(after, flags)];
const grep = names.length ? ["--grep", `^(?:${names.map(escapeRegExp).join("|")})$`] : [];
args = appendScriptArgs(config.command, base, [...files, ...grep]);
break;
}
case "pytest":
args = pytestArgs(config.args, paths);
break;
-3
View File
@@ -305,9 +305,6 @@ describe("catalogs", () => {
"GitHub Copilot",
"Codex",
"SKILL.md",
"context: fork",
"paths ({count})",
"paths",
"Cursor",
"PHP",
"SQL",
-6
View File
@@ -3048,12 +3048,6 @@
"Skill preview": "Skill preview",
"Files ({count})": "Files ({count})",
"Symlink": "Symlink",
"Runs in a subagent where supported (context: fork)": "Runs in a subagent where supported (context: fork)",
"context: fork": "context: fork",
"paths ({count})": "paths ({count})",
"fork": "fork",
"paths": "paths",
"Paths": "Paths",
"Cannot find the source of {0}": "Cannot find the source of {0}",
"JavaScript and TypeScript": "JavaScript and TypeScript",
"Global function": "Global function",
-4
View File
@@ -9368,10 +9368,6 @@
"Skill preview": "技能预览",
"Files ({count})": "文件 ({count})",
"Symlink": "符号链接",
"Runs in a subagent where supported (context: fork)": "在支持的 CLI 中以子代理运行(context: fork)",
"context: fork": "context: fork",
"paths ({count})": "paths ({count})",
"paths": "paths",
"Cannot find the source of {0}": "找不到 {0} 的源代码",
"JavaScript and TypeScript": "JavaScript 和 TypeScript",
"Global function": "全局函数",