From 9b4ee2a6ff52ff7c3bebe529dd7c950649f230dd Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Sun, 22 Nov 2026 15:30:06 +0900 Subject: [PATCH 01/50] feat(run): run Playwright tests with a test tree and Rerun Failed Tests (#5169) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Playwright project had no test tree and no Rerun Failed Tests: its output went through the Jest / Vitest parser, single tests ran with Jest's `-t`, and projects without a `test` script weren't detected at all. - Detection: a `package.json` script that runs `playwright test` is a test configuration and records `testRunner: "playwright"` (new optional `RunExtras.test_runner`, `test-runner` in `run.toml`); a package with a `playwright.config.*` that no script runs gets `npx playwright test`. - Test tree: test runs add `--reporter=list` unless a reporter is named, parsed into file › [project] › describe chain › test with status, duration, location and failure details. - Gutter: `test.describe` blocks and `fixme` / `fail` / `serial` tests get run / debug icons and run by declaration line (`file:line`); in a project with Playwright and another runner, specs run on Playwright's configuration and other tests on the other runner's. - Rerun Failed Tests / run selected tests: the files plus `--grep` on the describe chain and title, with `--project` when the run named projects. New fixture `fixtures/playwright-app`; `smoke/run.test.ts` runs it after `ts-app`. Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-run/src/config.rs | 6 + crates/ide-run/src/detect.rs | 66 +++++- crates/ide-run/src/lib.rs | 7 + crates/ide-run/tests/detect.rs | 25 ++ docs/en/guide/run.mdx | 1 + docs/en/guide/testing.mdx | 4 +- docs/en/languages/javascript.mdx | 5 +- docs/zh/guide/run.mdx | 1 + docs/zh/guide/testing.mdx | 4 +- docs/zh/languages/javascript.mdx | 5 +- fixtures/README.md | 3 +- fixtures/playwright-app/.gitignore | 3 + fixtures/playwright-app/package.json | 15 ++ fixtures/playwright-app/playwright.config.ts | 7 + fixtures/playwright-app/src/checkout.ts | 27 +++ .../playwright-app/tests/checkout.spec.ts | 36 +++ fixtures/playwright-app/tsconfig.json | 13 ++ smoke/run.test.ts | 64 ++++-- src/bindings.ts | 12 + src/features/run/context.ts | 23 +- src/features/run/producers.ts | 2 +- src/features/run/targets.ts | 9 +- src/features/run/testing/index.ts | 21 +- src/features/run/testing/playwright.test.ts | 214 ++++++++++++++++++ src/features/run/testing/playwright.ts | 101 +++++++++ src/features/run/testing/rerun.ts | 31 ++- 26 files changed, 660 insertions(+), 45 deletions(-) create mode 100644 fixtures/playwright-app/.gitignore create mode 100644 fixtures/playwright-app/package.json create mode 100644 fixtures/playwright-app/playwright.config.ts create mode 100644 fixtures/playwright-app/src/checkout.ts create mode 100644 fixtures/playwright-app/tests/checkout.spec.ts create mode 100644 fixtures/playwright-app/tsconfig.json create mode 100644 src/features/run/testing/playwright.test.ts create mode 100644 src/features/run/testing/playwright.ts diff --git a/crates/ide-run/src/config.rs b/crates/ide-run/src/config.rs index cf40ffc931..8a306f0b28 100644 --- a/crates/ide-run/src/config.rs +++ b/crates/ide-run/src/config.rs @@ -118,6 +118,8 @@ struct FileConfig { #[serde(alias = "stopCommand")] stop_command: Option, target: Option, + #[serde(alias = "testRunner")] + test_runner: Option, } pub(crate) fn slug(s: &str) -> String { @@ -183,6 +185,7 @@ fn convert(configs: Vec, local: bool) -> Vec { emulate_terminal: c.emulate_terminal, stop_command: non_empty(c.stop_command), target: non_empty(c.target), + test_runner: non_empty(c.test_runner), }, }); } @@ -298,6 +301,9 @@ fn to_table(c: &RunConfig) -> Table { if let Some(target) = &x.target { t.insert("target", value(target)); } + if let Some(runner) = &x.test_runner { + t.insert("test-runner", value(runner)); + } t } diff --git a/crates/ide-run/src/detect.rs b/crates/ide-run/src/detect.rs index f53738bc12..d009a14ad2 100644 --- a/crates/ide-run/src/detect.rs +++ b/crates/ide-run/src/detect.rs @@ -243,8 +243,32 @@ pub(crate) fn is_test_script(name: &str) -> bool { matches!(name, "test" | "vitest" | "jest") || name.starts_with("test:") } -fn push_scripts(pkg: &Json, pm: &str, prefix: Option<&str>, cwd: Option, out: &mut Vec) { - let Some(scripts) = pkg.get("scripts").and_then(Json::as_object) else { return }; +/// The test runner a `package.json` script starts, when its output and test selection differ +/// from Jest / Vitest's: `playwright test`. +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") +} + +const PLAYWRIGHT_CONFIGS: &[&str] = &[ + "playwright.config.ts", + "playwright.config.js", + "playwright.config.mts", + "playwright.config.mjs", + "playwright.config.cts", + "playwright.config.cjs", +]; + +/// Pushes the package's scripts; returns the test runners they start. +fn push_scripts( + pkg: &Json, + pm: &str, + prefix: Option<&str>, + cwd: Option, + out: &mut Vec, +) -> HashSet<&'static str> { + let mut runners = HashSet::new(); + let Some(scripts) = pkg.get("scripts").and_then(Json::as_object) else { return runners }; let mut names: Vec<&String> = scripts.keys().collect(); names.sort(); for script in names { @@ -254,11 +278,39 @@ fn push_scripts(pkg: &Json, pm: &str, prefix: Option<&str>, cwd: Option }; let mut c = config(id, name, "npm", pm, &["run", script]).in_dir(cwd.clone()).debug("js-debug"); c.extras.module = cwd.as_deref().map(ide_core::ipc_path::to_ipc); - if is_test_script(script) { + let runner = scripts[script].as_str().and_then(script_test_runner); + if is_test_script(script) || runner.is_some() { c = c.test(); } + if let Some(runner) = runner { + c.extras.test_runner = Some(runner.to_owned()); + runners.insert(runner); + } out.push(c); } + runners +} + +/// `npx playwright test` for a package with a Playwright configuration that no script runs +/// (`npm init playwright` adds none). +fn push_playwright( + dir: &Path, + runners: &HashSet<&str>, + prefix: Option<&str>, + cwd: Option, + out: &mut Vec, +) { + if runners.contains("playwright") || first_existing(dir, PLAYWRIGHT_CONFIGS).is_none() { + return; + } + let (id, name) = match prefix { + Some(p) => (format!("playwright:{p}"), format!("{p}: playwright test")), + None => ("playwright".to_owned(), "playwright test".to_owned()), + }; + let mut c = config(id, name, "node", "npx", &["playwright", "test"]).in_dir(cwd.clone()).debug("js-debug").test(); + c.extras.module = cwd.as_deref().map(ide_core::ipc_path::to_ipc); + c.extras.test_runner = Some("playwright".to_owned()); + out.push(c); } fn detect_node(root: &Path, out: &mut Vec) { @@ -275,7 +327,10 @@ fn detect_node(root: &Path, out: &mut Vec) { let pm = package_manager(&dir, &pkg); let rel = relative(root, &dir); let label = ide_core::ipc_path::to_ipc(&rel); - push_scripts(&pkg, pm, (dir != root).then_some(label.as_str()), (dir != root).then_some(rel), out); + let prefix = (dir != root).then_some(label.as_str()); + let cwd = (dir != root).then_some(rel); + let runners = push_scripts(&pkg, pm, prefix, cwd.clone(), out); + push_playwright(&dir, &runners, prefix, cwd, out); for member_dir in ide_core::project_roots::node_workspace_members(&dir) { if !covered.insert(member_dir.clone()) { continue; @@ -288,7 +343,8 @@ fn detect_node(root: &Path, out: &mut Vec) { .map(str::to_owned) .unwrap_or_else(|| ide_core::ipc_path::to_ipc(&rel)); let name = if dir == root { name } else { format!("{label}:{name}") }; - push_scripts(&member, pm, Some(&name), Some(rel), out); + let runners = push_scripts(&member, pm, Some(&name), Some(rel.clone()), out); + push_playwright(&member_dir, &runners, Some(&name), Some(rel), out); } } } diff --git a/crates/ide-run/src/lib.rs b/crates/ide-run/src/lib.rs index e1a0807c03..3278f7dbbc 100644 --- a/crates/ide-run/src/lib.rs +++ b/crates/ide-run/src/lib.rs @@ -182,6 +182,12 @@ pub struct RunExtras { #[serde(default, skip_serializing_if = "Option::is_none")] #[specta(optional)] pub target: Option, + /// The test framework a test configuration runs when detection recognised one that the + /// command line doesn't name (a `package.json` script running `playwright test`): picks the + /// test output parser and how a single test is selected. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub test_runner: Option, } impl Default for RunExtras { @@ -205,6 +211,7 @@ impl Default for RunExtras { emulate_terminal: false, stop_command: None, target: None, + test_runner: None, } } } diff --git a/crates/ide-run/tests/detect.rs b/crates/ide-run/tests/detect.rs index 86ecaaf278..9a964c923b 100644 --- a/crates/ide-run/tests/detect.rs +++ b/crates/ide-run/tests/detect.rs @@ -51,6 +51,31 @@ fn npm_scripts_with_lockfile_package_manager() { assert!(find(&c, "npm:test:e2e").is_test); } +#[test] +fn playwright_scripts_and_configs() { + let dir = project(&[ + ("package.json", r#"{"scripts":{"e2e":"cross-env CI=1 playwright test --project=chromium","test":"vitest"}}"#), + ("playwright.config.ts", ""), + ("site/package.json", r#"{"devDependencies":{"@playwright/test":"^1.56.0"}}"#), + ("site/playwright.config.ts", ""), + ]); + let c = detect(dir.path()); + let e2e = find(&c, "npm:e2e"); + assert!(e2e.is_test); + assert_eq!(e2e.extras.test_runner.as_deref(), Some("playwright")); + assert_eq!(find(&c, "npm:test").extras.test_runner, None); + // The root's script runs Playwright already; the nested package has none. + assert!(!ids(&c).contains(&"playwright")); + let site = find(&c, "playwright:site"); + assert_eq!(cmdline(site), "npx playwright test"); + assert_eq!(site.name, "site: playwright test"); + assert!(site.is_test && site.detected); + assert_eq!(site.kind, "node"); + assert_eq!(site.cwd.as_deref(), Some(Path::new("site"))); + assert_eq!(site.extras.test_runner.as_deref(), Some("playwright")); + assert_eq!(site.debug_adapter.as_deref(), Some("js-debug")); +} + #[test] fn package_manager_selection() { for (lock, pm) in [("yarn.lock", "yarn"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("package-lock.json", "npm")] { diff --git a/docs/en/guide/run.mdx b/docs/en/guide/run.mdx index fa64aca9b6..63436ce87f 100644 --- a/docs/en/guide/run.mdx +++ b/docs/en/guide/run.mdx @@ -19,6 +19,7 @@ When a project opens, OpenIDEA scans its build files (also in nested projects of | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `package.json` | One per `scripts` entry, run with the package manager of the lock file (npm, pnpm, yarn or bun). `test`, `test:*`, `jest` and `vitest` scripts are marked as tests. | | `deno.json` / `deno.jsonc` | Deno tasks | +| `playwright.config.*` | Scripts that run `playwright test` are tests; without one, `npx playwright test` | | `Cargo.toml` | `cargo run` for each binary, `cargo test`, `cargo build`; workspace members are included | | `build.gradle(.kts)` / `pom.xml` | Gradle and Maven run configurations | | `go.mod` / `go.work` | Go programs and tests | diff --git a/docs/en/guide/testing.mdx b/docs/en/guide/testing.mdx index 2972a79bf5..9f6b9ebff4 100644 --- a/docs/en/guide/testing.mdx +++ b/docs/en/guide/testing.mdx @@ -32,7 +32,7 @@ Running a single test creates a temporary run configuration based on the project | Language | Gutter icons on | Runs with | | --------------------------- | --------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | | Rust | `#[test]` functions, `mod tests` | `cargo test`, `cargo nextest` | -| JavaScript / TypeScript | `test`, `it`, `describe`, `suite`, `context` (also `.each`, `.only`, `.skip`) | Jest or Vitest through the project's test script; Deno and Bun | +| JavaScript / TypeScript | `test`, `it`, `describe`, `suite`, `context` (also `.each`, `.only`, `.skip`) | Jest or Vitest via the test script; Playwright Test; Deno, Bun | | Python | pytest `def test_*` and `class Test*`, unittest `TestCase` subclasses | pytest, Django `manage.py test` | | Go | `func TestX(t *testing.T)`, benchmarks | `go test` | | Java, Kotlin, Scala, Groovy | JUnit `@Test`, `@ParameterizedTest`, `@RepeatedTest`, `@TestFactory`, `@TestTemplate`; TestNG | Maven Surefire (`-Dtest=`) or Gradle (`--tests`) | @@ -66,7 +66,7 @@ Detected test configurations show results in the tree automatically. For your ow | **Rerun** (in the Run tool window) | `⌘R` | `Ctrl+F5` | | **Rerun Failed Tests** | — | — | -**Rerun Failed Tests** (in the Run tool window toolbar and Find Action) runs only the tests that failed in the last run, using each tool's filter syntax. It works for Cargo, Jest / Vitest, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks. +**Rerun Failed Tests** (in the Run tool window toolbar and Find Action) runs only the tests that failed in the last run, using each tool's filter syntax. It works for Cargo, Jest / Vitest, Playwright, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks. ## Navigate between code and tests diff --git a/docs/en/languages/javascript.mdx b/docs/en/languages/javascript.mdx index 087f68aaac..1443e314bd 100644 --- a/docs/en/languages/javascript.mdx +++ b/docs/en/languages/javascript.mdx @@ -74,7 +74,8 @@ On both pages, **Formatting provider** chooses between **Automatic (language ser OpenIDEA detects run configurations when the project opens: -- One configuration per `package.json` script (`npm run build`, `pnpm run dev`, …), for the root package, nested packages and workspace members. Scripts named `test`, `jest`, `vitest` or `test:*` are test configurations. +- One configuration per `package.json` script (`npm run build`, `pnpm run dev`, …), for the root package, nested packages and workspace members. Scripts named `test`, `jest`, `vitest` or `test:*`, and scripts that run `playwright test`, 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 `). In `package.json`, the gutter shows run icons on each `scripts` entry to run or debug it. @@ -85,7 +86,7 @@ In `package.json`, the gutter shows run icons on each `scripts` entry to run or - Any other `.js` file runs with `node` (with `deno run` or `bun run` in a project with `deno.json` or `bun.lock`). - A `.ts` file runs with Node.js directly on 22.18+ / 23.6+, with `--experimental-strip-types` on 22.6–22.17 and 23.0–23.5, else through `tsx` or `ts-node`. -Jest and Vitest output is turned into the test tree, with **Rerun Failed Tests**. **Run with Coverage** works for scripts that run `vitest` or `jest` (Vitest needs a coverage provider such as `@vitest/coverage-v8`; the IDE offers to add it) and for `node` / `tsx` / `ts-node` runs through `c8`. See [Testing](/en/guide/testing) and [Coverage](/en/guide/coverage). +Jest, Vitest 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). ## Debugging diff --git a/docs/zh/guide/run.mdx b/docs/zh/guide/run.mdx index 08673a5118..38b36fa52a 100644 --- a/docs/zh/guide/run.mdx +++ b/docs/zh/guide/run.mdx @@ -19,6 +19,7 @@ description: "创建、编辑和启动运行配置,从装订区运行代码, | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `package.json` | 每个 `scripts` 条目一个,使用锁文件对应的包管理器(npm、pnpm、yarn 或 bun)。`test`、`test:*`、`jest`、`vitest` 脚本会标记为测试。 | | `deno.json` / `deno.jsonc` | Deno task | +| `playwright.config.*` | 运行 `playwright test` 的脚本是测试配置;没有这样的脚本时为 `npx playwright test` | | `Cargo.toml` | 每个二进制一个 `cargo run`,以及 `cargo test`、`cargo build`;包含 workspace 成员 | | `build.gradle(.kts)` / `pom.xml` | Gradle、Maven 运行配置 | | `go.mod` / `go.work` | Go 程序和测试 | diff --git a/docs/zh/guide/testing.mdx b/docs/zh/guide/testing.mdx index 200a7af954..8300f3b0e9 100644 --- a/docs/zh/guide/testing.mdx +++ b/docs/zh/guide/testing.mdx @@ -28,7 +28,7 @@ OpenIDEA 直接使用项目自己的测试工具(Cargo、Jest、pytest、Maven | 语言 | 装订区图标位置 | 运行方式 | | --------------------------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | Rust | `#[test]` 函数、`mod tests` | `cargo test`、`cargo nextest` | -| JavaScript / TypeScript | `test`、`it`、`describe`、`suite`、`context`(含 `.each`、`.only`、`.skip`) | 通过项目的测试脚本运行 Jest 或 Vitest;Deno、Bun | +| JavaScript / TypeScript | `test`、`it`、`describe`、`suite`、`context`(含 `.each`、`.only`、`.skip`) | 用测试脚本运行 Jest 或 Vitest;Playwright;Deno、Bun | | Python | pytest 的 `def test_*`、`class Test*`,unittest 的 `TestCase` 子类 | pytest、Django `manage.py test` | | Go | `func TestX(t *testing.T)`、基准测试 | `go test` | | Java、Kotlin、Scala、Groovy | JUnit `@Test`、`@ParameterizedTest`、`@RepeatedTest`、`@TestFactory`、`@TestTemplate`;TestNG | Maven Surefire(`-Dtest=`)或 Gradle(`--tests`) | @@ -62,7 +62,7 @@ RSpec 有自己的配置类型(**RSpec 测试**)和检测到的 `rspec` 配 | **重新运行**(在“运行”工具窗口中) | `⌘R` | `Ctrl+F5` | | **重新运行失败的测试** | — | — | -**重新运行失败的测试**(在“运行”工具窗口工具栏和“查找操作”中)只运行上一次失败的测试,会按各个工具自己的过滤语法生成命令。支持 Cargo、Jest / Vitest、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。 +**重新运行失败的测试**(在“运行”工具窗口工具栏和“查找操作”中)只运行上一次失败的测试,会按各个工具自己的过滤语法生成命令。支持 Cargo、Jest / Vitest、Playwright、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。 ## 在代码和测试之间跳转 diff --git a/docs/zh/languages/javascript.mdx b/docs/zh/languages/javascript.mdx index 912cbaa6fb..80a318d85b 100644 --- a/docs/zh/languages/javascript.mdx +++ b/docs/zh/languages/javascript.mdx @@ -74,7 +74,8 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript 打开项目时,OpenIDEA 会自动检测运行配置: -- 每个 `package.json` 脚本一个配置(`npm run build`、`pnpm run dev` 等),覆盖根包、嵌套包和 workspace 成员。名为 `test`、`jest`、`vitest` 或 `test:*` 的脚本是测试配置。 +- 每个 `package.json` 脚本一个配置(`npm run build`、`pnpm run dev` 等),覆盖根包、嵌套包和 workspace 成员。名为 `test`、`jest`、`vitest` 或 `test:*` 的脚本,以及运行 `playwright test` 的脚本,是测试配置。 +- 有 `playwright.config.*` 但没有脚本运行它的包:通过 `npx` 运行的 `playwright test`。 - `deno.json` / `deno.jsonc` 中每个 task 一个配置(`deno task `)。 在 `package.json` 中,每个 `scripts` 条目旁的边栏图标可以直接运行或调试该脚本。 @@ -85,7 +86,7 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript - 其他 `.js` 文件用 `node` 运行(项目含 `deno.json` 或 `bun.lock` 时改用 `deno run` 或 `bun run`)。 - `.ts` 文件在 Node.js 22.18+ / 23.6+ 上直接运行,在 22.6–22.17 和 23.0–23.5 上加 `--experimental-strip-types`,更早的版本则通过 `tsx` 或 `ts-node` 运行。 -Jest 和 Vitest 的输出会解析成测试树,支持 **重新运行失败的测试**。**使用覆盖率运行** 支持调用 `vitest` 或 `jest` 的脚本(Vitest 需要 `@vitest/coverage-v8` 之类的覆盖率 provider,缺失时 IDE 会提示添加),以及通过 `c8` 运行的 `node` / `tsx` / `ts-node`。详见[测试](/zh/guide/testing)和[覆盖率](/zh/guide/coverage)。 +Jest、Vitest 和 Playwright Test 的输出会解析成测试树,支持 **重新运行失败的测试**。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)。 ## 调试 diff --git a/fixtures/README.md b/fixtures/README.md index b15ecc6a4d..61c56b910b 100644 --- a/fixtures/README.md +++ b/fixtures/README.md @@ -9,6 +9,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` | | `python-app/` | Python 3.10+, pytest | `python -m tasks.cli` (from `src/`) | `pytest` | `OPENIDEA_FAIL=1 pytest` | unused imports in `models.py` | | `go-app/` | Go 1.22+ | `go run ./cmd/server` | `go test ./...` | `OPENIDEA_FAIL=1 go test ./...` | unused `fmt.Sprintf` result in `internal/store/store.go` | | `kotlin-gradle/` | JDK 21, Gradle 8 (no wrapper) | `gradle run` | `gradle test` | `gradle test -PopenideaFail` | unused variable in `App.kt` | @@ -39,7 +40,7 @@ git init -q && git add -A && git commit -qm "initial" # for the VCS checks ``` Then open the folder with **File › Open…** (`⌘⇧⌥O`) or from the Welcome screen. -For `ts-app` / `polyglot/web` run `pnpm install` first; for `python-app` create a +For `ts-app` / `playwright-app` / `polyglot/web` run `pnpm install` first; for `python-app` create a venv (`python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'`); for `php-app` run `composer install` (debugging it needs Xdebug in the PHP on `PATH`). diff --git a/fixtures/playwright-app/.gitignore b/fixtures/playwright-app/.gitignore new file mode 100644 index 0000000000..4569578274 --- /dev/null +++ b/fixtures/playwright-app/.gitignore @@ -0,0 +1,3 @@ +node_modules +test-results +playwright-report diff --git a/fixtures/playwright-app/package.json b/fixtures/playwright-app/package.json new file mode 100644 index 0000000000..35d1d4a699 --- /dev/null +++ b/fixtures/playwright-app/package.json @@ -0,0 +1,15 @@ +{ + "name": "openidea-fixture-checkout", + "version": "0.1.0", + "private": true, + "description": "OpenIDEA QA fixture: Playwright Test specs for a checkout module (no browser needed)", + "type": "module", + "scripts": { + "test": "playwright test", + "lint": "tsc -p . --noEmit" + }, + "devDependencies": { + "@playwright/test": "^1.56.0", + "typescript": "^5.6.0" + } +} diff --git a/fixtures/playwright-app/playwright.config.ts b/fixtures/playwright-app/playwright.config.ts new file mode 100644 index 0000000000..99313f18cd --- /dev/null +++ b/fixtures/playwright-app/playwright.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from "@playwright/test"; + +// The IDE replaces the reporter with `list` for its test tree; `dot` is what a terminal shows. +export default defineConfig({ + testDir: "tests", + reporter: "dot", +}); diff --git a/fixtures/playwright-app/src/checkout.ts b/fixtures/playwright-app/src/checkout.ts new file mode 100644 index 0000000000..a213a6593e --- /dev/null +++ b/fixtures/playwright-app/src/checkout.ts @@ -0,0 +1,27 @@ +export interface Line { + sku: string; + price: number; + quantity: number; +} + +const FREE_SHIPPING_FROM = 50; + +export function subtotal(lines: Line[]): number { + return lines.reduce((sum, l) => sum + l.price * l.quantity, 0); +} + +export function shipping(lines: Line[]): number { + // TODO: shipping by weight instead of a flat rate + return subtotal(lines) >= FREE_SHIPPING_FROM ? 0 : 4.99; +} + +export function applyCoupon(total: number, code: string): number { + if (code === "HALF") return Math.round(total * 50) / 100; + if (code === "TENOFF") return Math.max(0, total - 10); + throw new Error(`unknown coupon: ${code}`); +} + +// An intentional warning: never used. +function roundUp(value: number): number { + return Math.ceil(value); +} diff --git a/fixtures/playwright-app/tests/checkout.spec.ts b/fixtures/playwright-app/tests/checkout.spec.ts new file mode 100644 index 0000000000..315ce0703c --- /dev/null +++ b/fixtures/playwright-app/tests/checkout.spec.ts @@ -0,0 +1,36 @@ +import { expect, test } from "@playwright/test"; +import { applyCoupon, shipping, subtotal, type Line } from "../src/checkout.ts"; + +const mug: Line = { sku: "mug", price: 12, quantity: 2 }; +const lamp: Line = { sku: "lamp", price: 40, quantity: 1 }; + +test.describe("checkout", () => { + test("adds up the lines", () => { + expect(subtotal([mug, lamp])).toBe(64); + }); + + test.describe("shipping", () => { + test("is free from 50", () => { + expect(shipping([mug, lamp])).toBe(0); + }); + + test("is a flat rate below 50", () => { + expect(shipping([mug])).toBe(4.99); + }); + }); + + test("intentionally fails (set OPENIDEA_FAIL=1)", () => { + test.skip(!process.env.OPENIDEA_FAIL, "set OPENIDEA_FAIL=1"); + expect(shipping([lamp])).toBe(0); + }); +}); + +test.describe("coupons", () => { + test("halves the total", () => { + expect(applyCoupon(64, "HALF")).toBe(32); + }); + + test("rejects unknown codes", () => { + expect(() => applyCoupon(64, "NOPE")).toThrow("unknown coupon"); + }); +}); diff --git a/fixtures/playwright-app/tsconfig.json b/fixtures/playwright-app/tsconfig.json new file mode 100644 index 0000000000..9e626e1e5f --- /dev/null +++ b/fixtures/playwright-app/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "noUnusedLocals": true, + "allowImportingTsExtensions": true, + "noEmit": true, + "skipLibCheck": true + }, + "include": ["src", "tests", "playwright.config.ts"] +} diff --git a/smoke/run.test.ts b/smoke/run.test.ts index 6be950dca6..f5a3bf5ddd 100644 --- a/smoke/run.test.ts +++ b/smoke/run.test.ts @@ -1,5 +1,5 @@ /** - * Running and testing each language's `fixtures/` project the way the Run tool window does: + * Running and testing each language's `fixtures/` projects the way the Run tool window does: * the backend detects the configurations, the run store starts them (with its test * reporting), parses the output into the test tree, and reruns the failed tests. */ @@ -50,19 +50,36 @@ const env = (config: RunConfig, vars: Record): RunConfig => ({ }); const args = (config: RunConfig, extra: string[]): RunConfig => ({ ...config, args: [...config.args, ...extra] }); -const CASES: Record = { - typescript: { - fixture: "ts-app", - setup: (root) => execFileSync("npm", ["install", "--no-audit", "--no-fund"], { cwd: root, stdio: "ignore" }), - run: { config: "npm:start", prints: "Total: $134.97" }, - tests: { - config: "npm:test", - failing: (c) => env(c, { OPENIDEA_FAIL: "1" }), - passed: 4, - failed: "intentionally fails (set OPENIDEA_FAIL=1)", - file: "tests/cart.test.ts", +const npmInstall = (root: string) => + execFileSync("npm", ["install", "--no-audit", "--no-fund"], { cwd: root, stdio: "ignore" }); + +/** Each language's fixtures, run one after the other (the JavaScript test runners' in the TypeScript job). */ +const CASES: Record = { + typescript: [ + { + fixture: "ts-app", + setup: npmInstall, + run: { config: "npm:start", prints: "Total: $134.97" }, + tests: { + config: "npm:test", + failing: (c) => env(c, { OPENIDEA_FAIL: "1" }), + passed: 4, + failed: "intentionally fails (set OPENIDEA_FAIL=1)", + file: "tests/cart.test.ts", + }, }, - }, + { + fixture: "playwright-app", + setup: npmInstall, + tests: { + config: "npm:test", + failing: (c) => env(c, { OPENIDEA_FAIL: "1" }), + passed: 5, + failed: "intentionally fails (set OPENIDEA_FAIL=1)", + file: "tests/checkout.spec.ts", + }, + }, + ], python: { fixture: "python-app", // A project venv with pytest, as the fixture's README sets it up. @@ -154,15 +171,20 @@ let server: Server | null = null; let disconnect: (() => void) | null = null; let base = ""; -afterEach(async () => { +async function close() { // As switching projects does: run ids restart with each server. resetRuns(); disconnect?.(); + disconnect = null; await server?.close(); + server = null; // A language server's own process (jdtls's JVM) can outlive the server's for a moment: // deleting its data directory has to wait for it. if (base) rmSync(base, { recursive: true, force: true, maxRetries: 10, retryDelay: 1000 }); -}); + base = ""; +} + +afterEach(close); async function open(c: Case): Promise { base = realpathSync(mkdtempSync(join(tmpdir(), "openidea-smoke-"))); @@ -208,8 +230,7 @@ async function runToEnd(config: RunConfig, timeoutMs = 8 * 60_000): Promise<{ id return { id: session.id, output }; } -async function smoke(language: string) { - const c = CASES[language]!; +async function smoke(c: Case) { await open(c); if (c.run) { @@ -258,6 +279,11 @@ async function smoke(language: string) { expect(again.firstFailure()?.name).toBe(c.tests.failed); } -for (const language of Object.keys(CASES)) { - test(language, () => smoke(language)); +for (const [language, cases] of Object.entries(CASES)) { + test(language, async () => { + for (const [i, c] of [cases].flat().entries()) { + if (i > 0) await close(); + await smoke(c); + } + }); } diff --git a/src/bindings.ts b/src/bindings.ts index 63d52c4c69..5953c313c1 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -11146,6 +11146,12 @@ export type RunExtras_Deserialize = { stopCommand?: string | null, /** Settings › Run Targets id the process runs on (over SSH); `None` = this machine. */ target?: string | null, + /** + * The test framework a test configuration runs when detection recognised one that the + * command line doesn't name (a `package.json` script running `playwright test`): picks the + * test output parser and how a single test is selected. + */ + testRunner?: string | null, }; export type RunExtras_Serialize = { @@ -11190,6 +11196,12 @@ export type RunExtras_Serialize = { stopCommand?: string | null, /** Settings › Run Targets id the process runs on (over SSH); `None` = this machine. */ target?: string | null, + /** + * The test framework a test configuration runs when detection recognised one that the + * command line doesn't name (a `package.json` script running `playwright test`): picks the + * test output parser and how a single test is selected. + */ + testRunner?: string | null, }; /** A process started from a run configuration. */ diff --git a/src/features/run/context.ts b/src/features/run/context.ts index 8d9b597ef4..9f227a8bed 100644 --- a/src/features/run/context.ts +++ b/src/features/run/context.ts @@ -9,6 +9,7 @@ import { djangoLabel, djangoTestsOf, hasDjangoTests } from "./djangoTypes"; import { inGradleModule } from "./gradleModuleTests"; import { systemPython } from "./pythonTypes"; import { phpunitArgs } from "./testing/phpunit"; +import { frameworkFor } from "./testing"; import { goTestParts } from "./goArguments"; import { goBuildType } from "./goTypes"; import { isWindows } from "./jvmTypes"; @@ -54,7 +55,7 @@ const stem = (p: string) => (p.split("/").pop() ?? p).replace(/\.[^.]+$/, ""); /** Kinds whose test configs can run a file of this extension. */ function testKinds(relPath: string): string[] { if (/\.cs$/i.test(relPath)) return ["dotnet-test"]; - if (/\.[cm]?[jt]sx?$/.test(relPath)) return ["npm", "deno", "bun"]; + if (/\.[cm]?[jt]sx?$/.test(relPath)) return ["npm", "deno", "bun", "node"]; if (/\.py$/.test(relPath)) return ["pytest", "python", "django-test"]; if (/\.php$/.test(relPath)) return ["phpunit"]; if (/_spec\.rb$/.test(relPath)) return ["rspec", "rake", "ruby"]; @@ -198,18 +199,31 @@ function applyPytestTemplate(config: RunConfig): RunConfig { return { ...config, command: line.command, args: line.args }; } +/** A Playwright spec: it imports Playwright Test, or uses its `test.describe` / `test.step` / `test.use`. */ +export function isPlaywrightSpec(content: string): boolean { + return /['"]@playwright\/test['"]|\btest\.(?:describe|step|use)\s*[.(]/.test(content); +} + +/** A project with Playwright and another JS runner: specs run on Playwright's configurations, other tests on the rest. */ +function byRunner(bases: RunConfig[], content: string): RunConfig[] { + const playwright = bases.filter((c) => frameworkFor(c) === "playwright"); + if (!playwright.length || playwright.length === bases.length) return bases; + return isPlaywrightSpec(content) ? playwright : bases.filter((c) => !playwright.includes(c)); +} + /** * Test configurations that can run `relPath` equally well (same, closest working * directory: `npm run test` and `npm run test:unit`…); the default one first. + * `content` (the file's text) tells a Playwright spec from other JS tests. */ -export function testBasesFor(relPath: string, configs: RunConfig[]): RunConfig[] { +export function testBasesFor(relPath: string, configs: RunConfig[], content?: string): RunConfig[] { const kinds = testKinds(relPath); // Configurations produced from a test or file are results of narrowing, never bases for it. const candidates = configs .filter((c) => c.isTest && kinds.includes(c.kind) && !c.id.startsWith("context:")) .sort((a, b) => kinds.indexOf(a.kind) - kinds.indexOf(b.kind)); const best = allClosest(candidates, relPath); - if (best.length) return best; + if (best.length) return content === undefined ? best : byRunner(best, content); const fallback = implicitPytest(relPath, configs); return fallback ? [fallback] : []; } @@ -224,7 +238,7 @@ export function testConfigFor( base?: RunConfig, content?: string, ): RunConfig | null { - base ??= testBasesFor(relPath, configs)[0]; + base ??= testBasesFor(relPath, configs, content)[0]; if (!base) return null; const file = relToCwd(relPath, base); switch (base.kind) { @@ -244,6 +258,7 @@ export function testConfigFor( return derived(base, relPath, { args }); } case "deno": + case "node": return derived(base, relPath, { args: [...base.args, file] }); case "pytest": case "python": diff --git a/src/features/run/producers.ts b/src/features/run/producers.ts index fad5a5daea..0953785fed 100644 --- a/src/features/run/producers.ts +++ b/src/features/run/producers.ts @@ -1216,7 +1216,7 @@ export function produceContextChoices(input: ContextInput, env: ToolEnv): Produc const rel = relTo(input.path, input.root); const cmake = cmakeTargets(input); if (cmake.length > 1) return cmake.map((config) => ({ name: config.name, scope: produced.scope, config })); - const bases = testBasesFor(rel, [...input.configs]); + const bases = testBasesFor(rel, [...input.configs], input.content); if (bases.length < 2) return [produced]; let element: RunTarget | null = null; if (produced.scope === "element") { diff --git a/src/features/run/targets.ts b/src/features/run/targets.ts index 4335e0f2ae..bbb89df13c 100644 --- a/src/features/run/targets.ts +++ b/src/features/run/targets.ts @@ -17,6 +17,7 @@ import { djangoLabel, djangoTestsOf } from "./djangoTypes"; import { scanJvmTargets, simpleClassName } from "./jvmTargets"; import { escapeRegExp } from "./testing/rerun"; import { pestFilter, phpunitArgs, phpunitFilter } from "./testing/phpunit"; +import { frameworkFor } from "./testing"; export type TargetKind = "main" | "test" | "suite" | "generate"; @@ -132,8 +133,9 @@ function rustTargets(lines: string[], relPath: string): RunTarget[] { ); } +/** Jest / Vitest `describe` / `test` / `it`, and Playwright's `test.describe` and modifiers. */ const JS_RE = - /^(\s*)(describe|suite|context|test|it)\b(?:\.(?:only|skip|todo|concurrent|failing|sequential))*(\.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[] = []; @@ -146,7 +148,7 @@ function jsTargets(lines: string[]): RunTarget[] { const name = m[5]!.replace(/\\(.)/g, "$1"); const parameterized = !!m[3] || (m[4] === "`" && name.includes("${")) || /%[sdifjo#%p]|\$\w+/.test(name); const path = [...stack.map((s) => s.name), name]; - const isSuite = m[2] === "describe" || m[2] === "suite" || m[2] === "context"; + const isSuite = m[2] === "test.describe" || m[2] === "describe" || m[2] === "suite" || m[2] === "context"; out.push({ line: i, kind: isSuite ? "suite" : "test", name: path.join(" > "), path, parameterized }); if (isSuite) stack.push({ indent, name }); } @@ -469,6 +471,8 @@ export function targetConfig( env: { ...file.env }, detected: true, }); + // 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}`)); switch (file.kind) { case "dotnet-test": { const methods = @@ -482,6 +486,7 @@ export function targetConfig( case "npm": case "bun": case "deno": + case "node": return named([...file.args, "-t", jsNamePattern(target)]); case "pytest": case "python": diff --git a/src/features/run/testing/index.ts b/src/features/run/testing/index.ts index 901020c926..1695d8e620 100644 --- a/src/features/run/testing/index.ts +++ b/src/features/run/testing/index.ts @@ -5,11 +5,13 @@ import { goParser } from "./go"; import { jsParser } from "./js"; import { jvmParser } from "./jvm"; import { phpunitParser, withTeamcity } from "./phpunit"; +import { playwrightParser } from "./playwright"; import { pytestParser } from "./pytest"; import { rubyParser } from "./ruby"; import { unittestParser } from "./unittest"; import { zigParser } from "./zig"; import type { TestEvent, TestOutputParser } from "./types"; +import { appendScriptArgs } from "../scriptArgs"; export type { TestEvent, TestOutputParser, TestStatus } from "./types"; export { formatDuration, parseDuration } from "./types"; @@ -20,6 +22,7 @@ export { jsParser, jvmParser, phpunitParser, + playwrightParser, pytestParser, rubyParser, unittestParser, @@ -37,6 +40,7 @@ export function combinedParser(parsers: TestOutputParser[]): TestOutputParser { export type Framework = | "cargo" | "js" + | "playwright" | "pytest" | "unittest" | "phpunit" @@ -47,8 +51,12 @@ export type Framework = | "zig" | "auto"; -export function frameworkFor(config: Pick): Framework { +type FrameworkConfig = Pick & Partial>; + +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"; switch (config.kind) { case "dotnet-test": return "dotnet"; @@ -111,7 +119,12 @@ function rubyVerbose>(con * reach the tree. `-v` (Django: `-v 2`) adds one line per test (live, like * IDEA's runner) unless the user chose a verbosity already. */ -export function withTestReporting>(config: T): T { +export function withTestReporting(config: T): T { + 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=")); + return chosen ? config : { ...config, args: appendScriptArgs(config.command, config.args, ["--reporter=list"]) }; + } if (frameworkFor(config) === "go" && config.args[0] === "test") { const boundary = config.args.findIndex((a) => a === "-args" || a === "--"); const tool = boundary < 0 ? config.args : config.args.slice(0, boundary); @@ -139,7 +152,7 @@ export function withTestReporting): TestOutputParser { +export function createTestParser(config: FrameworkConfig): TestOutputParser { switch (frameworkFor(config)) { case "dotnet": return { feed: () => [] }; @@ -147,6 +160,8 @@ export function createTestParser(config: Pick & { 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 e2e` whose script is `playwright test` (detection records the runner). */ +const script = cfg({ id: "npm:e2e", kind: "npm", command: "npm", args: ["run", "e2e"], testRunner: "playwright" }); +/** The configuration detected for a `playwright.config.ts` no script runs. */ +const npx = cfg({ id: "playwright", kind: "node", command: "npx", args: ["playwright", "test"] }); + +function results(text: string, config: RunConfig = script) { + const r = new TestResults(); + r.apply(parseAll(createTestParser(config), text)); + return r; +} + +const key = (...path: string[]) => path.join("\u0000"); + +// `npx playwright test --reporter=list` in a Windows console (no UTF-8 marks), as printed. +const WINDOWS = ` +Running 5 tests using 1 worker + + ok 1 tests\\cart.spec.ts:4:3 › cart › adds items (2ms) + ok 2 tests\\cart.spec.ts:8:5 › cart › totals › sums (0ms) + x 3 tests\\cart.spec.ts:12:3 › cart › fails (1ms) + - 4 tests\\cart.spec.ts:15:8 › cart › skipped one +hello from test + ok 5 tests\\cart.spec.ts:18:1 › top level (0ms) + + + 1) tests\\cart.spec.ts:12:3 › cart › fails ─────────────────────────────────────── + + Error: expect(received).toBe(expected) // Object.is equality + + Expected: 2 + Received: 1 + + 11 | }); + 12 | test("fails", () => { + > 13 | expect(1).toBe(2); + | ^ + 14 | }); + at C:\\work\\shop\\tests\\cart.spec.ts:13:15 + + 1 failed + tests\\cart.spec.ts:12:3 › cart › fails ─────────────────────────────────────── + 1 skipped + 3 passed (563ms) +`; + +// macOS / Linux, with projects and a retried test. +const PROJECTS = ` +Running 4 tests using 2 workers + + ✓ 1 [chromium] › e2e/home.spec.ts:3:5 › home › has title (1.2s) + ✘ 2 [firefox] › e2e/home.spec.ts:3:5 › home › has title (5.0s) + ✓ 3 [firefox] › e2e/home.spec.ts:3:5 › home › has title (retry #1) (980ms) + ✘ 4 [chromium] › e2e/home.spec.ts:9:5 › home › links @smoke (1.0m) + + 1) [chromium] › e2e/home.spec.ts:9:5 › home › links @smoke ────────────────────── + + Error: Timed out 5000ms waiting for expect(locator).toBeVisible() + + 1 failed + [chromium] › e2e/home.spec.ts:9:5 › home › links @smoke ──────────────────────── + 1 flaky + [firefox] › e2e/home.spec.ts:3:5 › home › has title ──────────────────────────── + 1 passed (1.1m) +`; + +describe("Playwright list reporter", () => { + it("builds the tree from file, describe chain and title, with durations and locations", () => { + const r = results(WINDOWS); + expect(r.counts()).toMatchObject({ passed: 3, failed: 1, skipped: 1 }); + expect(r.roots.map((n) => n.name)).toEqual(["tests/cart.spec.ts"]); + const sums = r.get(key("tests/cart.spec.ts", "cart", "totals", "sums"))!; + expect(sums.own).toBe("passed"); + expect(sums.durationMs).toBe(0); + expect(sums.location).toEqual({ path: "tests/cart.spec.ts", line: 8, col: 5, resolve: "path" }); + expect(r.get(key("tests/cart.spec.ts", "cart", "skipped one"))?.own).toBe("skipped"); + expect(r.get(key("tests/cart.spec.ts", "top level"))?.own).toBe("passed"); + expect(r.summary).toMatchObject({ passed: 3, failed: 1, skipped: 1, durationMs: 563 }); + }); + + it("keeps a failure's details, up to the summary", () => { + const r = results(WINDOWS); + const failure = r.firstFailure()!; + expect(failure.path).toEqual(["tests/cart.spec.ts", "cart", "fails"]); + expect(failure.location).toMatchObject({ path: "tests/cart.spec.ts", line: 12 }); + const output = nodeOutput(failure).join("\n"); + expect(output).toContain("Expected: 2"); + expect(output).toContain("at C:\\work\\shop\\tests\\cart.spec.ts:13:15"); + expect(output).not.toContain("1 skipped"); + }); + + it("groups by project; a test that passed only on a retry (flaky) stays failed", () => { + const r = results(PROJECTS); + expect(r.get(key("e2e/home.spec.ts", "[chromium]", "home", "has title"))?.own).toBe("passed"); + const firefox = r.get(key("e2e/home.spec.ts", "[firefox]", "home", "has title"))!; + expect(firefox.own).toBe("failed"); + expect(firefox.durationMs).toBe(980); + const links = r.get(key("e2e/home.spec.ts", "[chromium]", "home", "links @smoke"))!; + expect(links.own).toBe("failed"); + expect(links.durationMs).toBe(60_000); + expect(nodeOutput(links).join("\n")).toContain("Timed out 5000ms"); + expect(r.counts()).toMatchObject({ passed: 1, failed: 2 }); + }); +}); + +describe("Playwright configurations", () => { + it("are recognised by the recorded runner or the command line", () => { + expect(frameworkFor(script)).toBe("playwright"); + expect(frameworkFor(npx)).toBe("playwright"); + expect(frameworkFor({ kind: "shell", command: "pnpm exec playwright test --ui", args: [] })).toBe("playwright"); + expect(frameworkFor({ kind: "npm", command: "npm", args: ["run", "test"] })).toBe("js"); + }); + + it("report through the list reporter unless the configuration chose one", () => { + expect(withTestReporting(script).args).toEqual(["run", "e2e", "--", "--reporter=list"]); + expect(withTestReporting(npx).args).toEqual(["playwright", "test", "--reporter=list"]); + const chosen = { ...npx, args: ["playwright", "test", "--reporter=dot"] }; + expect(withTestReporting(chosen)).toBe(chosen); + }); + + it("rerun failed tests by file and title, per project", async () => { + const one = await rerunFailedConfigs(script, failedTestPaths(results(WINDOWS))); + expect(one.map((c) => c.args)).toEqual([ + ["run", "e2e", "--", "tests/cart.spec.ts", "--grep", "(?:^| )(?:cart fails)(?: @\\S+)*$"], + ]); + expect(new RegExp(one[0]!.args.at(-1)!).test(" cart.spec.ts cart fails @slow")).toBe(true); + expect(new RegExp(one[0]!.args.at(-1)!).test(" cart.spec.ts cart fails later")).toBe(false); + + const paths = [ + ["e2e/a.spec.ts", "[chromium]", "a", "one"], + ["e2e/b.spec.ts", "[firefox]", "b.c", "two"], + ]; + const split = await testsConfigs({ ...npx, args: ["playwright", "test", "--project=webkit"] }, paths, "2 tests"); + expect(split.map((c) => [c.name, c.args])).toEqual([ + [ + "2 tests (chromium)", + ["playwright", "test", "e2e/a.spec.ts", "--grep", "(?:^| )(?:a one)(?: @\\S+)*$", "--project", "chromium"], + ], + [ + "2 tests (firefox)", + ["playwright", "test", "e2e/b.spec.ts", "--grep", "(?:^| )(?:b\\.c two)(?: @\\S+)*$", "--project", "firefox"], + ], + ]); + }); +}); + +describe("Playwright gutter targets", () => { + const spec = [ + 'import { test, expect } from "@playwright/test";', // 0 + "", + "test.describe('cart', () => {", // 2 + " test.describe.serial('totals', () => {", // 3 + " test('sums', async ({ page }) => {});", // 4 + " test.fixme('rounds', async () => {});", // 5 + " });", + " test.fail('known bug', async () => {", // 7 + " await test.step('opens', async () => {});", + " });", + "});", + ].join("\n"); + + it("finds test.describe blocks and modified tests, not steps", () => { + expect(detectRunTargets(spec, "e2e/cart.spec.ts").map((t) => [t.line, t.kind, t.path.join("/")])).toEqual([ + [2, "suite", "cart"], + [3, "suite", "cart/totals"], + [4, "test", "cart/totals/sums"], + [5, "test", "cart/totals/rounds"], + [7, "test", "cart/known bug"], + ]); + }); + + it("run a test or describe block by its declaration line", () => { + const [cart, , sums] = detectRunTargets(spec, "e2e/cart.spec.ts"); + expect(targetConfig(sums!, "e2e/cart.spec.ts", [script], spec)?.args).toEqual([ + "run", + "e2e", + "--", + "e2e/cart.spec.ts:5", + ]); + const web = { ...npx, cwd: "web", module: "web" }; + expect(targetConfig(cart!, "web/e2e/cart.spec.ts", [web], spec)?.args).toEqual([ + "playwright", + "test", + "e2e/cart.spec.ts:3", + ]); + }); + + it("send specs to Playwright and other tests to the project's other runner", () => { + const vitest = cfg({ id: "npm:test", kind: "npm", command: "npm", args: ["run", "test"] }); + const configs = [vitest, npx]; + expect(testBasesFor("e2e/cart.spec.ts", configs, spec).map((c) => c.id)).toEqual(["playwright"]); + const unit = "import { test } from 'vitest';\ntest('adds', () => {});"; + expect(testBasesFor("src/cart.test.ts", configs, unit).map((c) => c.id)).toEqual(["npm:test"]); + expect(testBasesFor("src/cart.test.ts", configs).map((c) => c.id)).toEqual(["npm:test", "playwright"]); + }); +}); diff --git a/src/features/run/testing/playwright.ts b/src/features/run/testing/playwright.ts new file mode 100644 index 0000000000..b4703616e5 --- /dev/null +++ b/src/features/run/testing/playwright.ts @@ -0,0 +1,101 @@ +/** + * Playwright Test's `list` reporter (the run adds `--reporter=list`): one line per finished + * test, ` ✓ 3 [chromium] › tests/cart.spec.ts:12:3 › cart › adds (25ms)` (`ok` / `x` on + * Windows consoles), then the failures' details and the summary. + */ +import { parseDuration, type TestEvent, type TestOutputParser, type TestStatus } from "./types"; + +const SEP = " › "; +const RESULT_RE = /^\s+(✓|ok|✘|x|-)\s+\d+\s+(.+)$/; +const FAILURE_HEADER_RE = /^\s+\d+\) (.+?) ─+$/; +const SUMMARY_RE = /^\s+(\d+) (passed|failed|flaky|skipped|did not run|interrupted)(?: \(([^)]+)\))?$/; +const TITLE_LOCATION_RE = /^(.+):(\d+):(\d+)$/; +const DURATION_RE = /\s\((\d+(?:\.\d+)?(?:ms|s|m|h))\)$/; +const RETRY_RE = /\s\(retry #\d+\)$/; + +/** A printed test title: `[project] › file:line:col › describe › test`. */ +export interface PlaywrightTitle { + /** Results tree path: the file, `[project]` when the run names projects, then the titles. */ + path: string[]; + file: string; + line: number; + col: number; +} + +export function parsePlaywrightTitle(text: string): PlaywrightTitle | null { + const parts = text.split(SEP); + const project = /^\[(.+)\]$/.exec(parts[0] ?? ""); + if (project) parts.shift(); + const loc = TITLE_LOCATION_RE.exec(parts.shift() ?? ""); + if (!loc || !parts.length) return null; + const file = loc[1]!.replace(/\\/g, "/"); + return { + path: [file, ...(project ? [`[${project[1]}]`] : []), ...parts], + file, + line: Number(loc[2]), + col: Number(loc[3]), + }; +} + +/** The `[project]` segment of a results path, if any. */ +export function playwrightProject(path: readonly string[]): string | null { + const m = /^\[(.+)\]$/.exec(path[1] ?? ""); + return m && path.length > 2 ? m[1]! : null; +} + +/** The describe chain and test title of a results path (without the file and project). */ +export function playwrightTitles(path: readonly string[]): string[] { + return path.slice(playwrightProject(path) === null ? 1 : 2); +} + +function markStatus(mark: string): Exclude { + if (mark === "✓" || mark === "ok") return "passed"; + return mark === "-" ? "skipped" : "failed"; +} + +export function playwrightParser(): TestOutputParser { + /** The test whose failure details the following lines are. */ + let failure: string[] | null = null; + return { + feed(raw) { + const line = raw.replace(/\s+$/, ""); + const events: TestEvent[] = []; + let m: RegExpExecArray | null; + if ((m = SUMMARY_RE.exec(line))) { + failure = null; + const n = Number(m[1]); + const durationMs = parseDuration(m[3]); + if (m[2] === "passed") events.push({ type: "summary", passed: n, durationMs }); + else if (m[2] === "failed") events.push({ type: "summary", failed: n }); + else if (m[2] === "skipped") events.push({ type: "summary", skipped: n }); + return events; + } + if ((m = FAILURE_HEADER_RE.exec(line))) { + const title = parsePlaywrightTitle(m[1]!); + failure = title?.path ?? null; + return events; + } + const result = RESULT_RE.exec(line); + const duration = result && DURATION_RE.exec(result[2]!); + const title = result && parsePlaywrightTitle(result[2]!.slice(0, duration?.index).replace(RETRY_RE, "")); + if (result && title) { + // Failures print at the end, or after their test with PLAYWRIGHT_LIST_PRINT_FAILURES_INLINE. + failure = null; + events.push({ + type: "result", + path: title.path, + status: markStatus(result[1]!), + durationMs: parseDuration(duration?.[1]), + }); + events.push({ + type: "location", + path: title.path, + location: { path: title.file, line: title.line, col: title.col, resolve: "path" }, + }); + return events; + } + if (failure) events.push({ type: "output", path: failure, line: raw }); + return events; + }, + }; +} diff --git a/src/features/run/testing/rerun.ts b/src/features/run/testing/rerun.ts index cb9caa8141..d3c089440c 100644 --- a/src/features/run/testing/rerun.ts +++ b/src/features/run/testing/rerun.ts @@ -12,6 +12,7 @@ import { goTestParts, withoutGoSelection } from "../goArguments"; import { withMavenTests } from "../mavenTests"; import { frameworkFor } from "./index"; import { dotnetFilter } from "./dotnet"; +import { playwrightProject, playwrightTitles } from "./playwright"; import { nodeStatus, type TestNode, type TestResults } from "./results"; /** Paths of failed tests: failed leaves, plus failed suites without any failed children reported. */ @@ -86,6 +87,27 @@ function jsArgs(config: RunConfig, paths: string[][]): string[] | null { return appendScriptArgs(config.command, args, [...files, ...filter]); } +/** + * Playwright: the files, `--grep` on the describe chain and title (its grep text is the project, + * the file relative to the test directory, the titles and the tags, space separated), and the + * project when the run named one (`testsConfigs` splits a selection by project). + */ +function playwrightArgs(config: RunConfig, paths: string[][]): string[] | null { + const files = unique(paths.map((p) => p[0]!).filter(Boolean)); + if (!files.length) return null; + const titles = unique(paths.map((p) => playwrightTitles(p).join(" ")).filter(Boolean)); + const project = playwrightProject(paths[0]!); + const grep = titles.length ? ["--grep", `(?:^| )(?:${titles.map(escapeRegExp).join("|")})(?: @\\S+)*$`] : []; + const { before, after } = splitDashDash(config.args); + const flags = ["-g", "--grep", ...(project === null ? [] : ["--project"])]; + const args = after === null ? dropFlag(before, flags) : [...before, "--", ...dropFlag(after, flags)]; + return appendScriptArgs(config.command, args, [ + ...files, + ...grep, + ...(project === null ? [] : ["--project", project]), + ]); +} + function pytestArgs(base: string[], paths: string[][]): string[] | null { const ids = unique(paths.map((p) => p.join("::"))); if (!ids.length) return null; @@ -168,7 +190,7 @@ export function rerunFailedConfigs(config: RunConfig, paths: string[][]): RunCon return testsConfigs(config, paths, `Failed: ${baseName}`); } -/** Go filters apply to every package in an invocation, so each package keeps its own selection. */ +/** Go filters apply to every package of an invocation, Playwright's to every project: each keeps its own selection. */ export function testsConfigs(config: RunConfig, paths: string[][], name: string): RunConfig[] | Promise { if (!paths.length) return []; if (config.params?.framework === "plugin") { @@ -177,8 +199,10 @@ export function testsConfigs(config: RunConfig, paths: string[][], name: string) return selected instanceof Promise ? selected.then(list) : list(selected); } const groups = new Map(); + const framework = frameworkFor(config); for (const path of paths) { - const key = frameworkFor(config) === "go" ? (path[0] ?? "") : ""; + const key = + framework === "go" ? (path[0] ?? "") : framework === "playwright" ? (playwrightProject(path) ?? "") : ""; const group = groups.get(key) ?? []; group.push(path); groups.set(key, group); @@ -235,6 +259,9 @@ function builtinTestsConfig(config: RunConfig, paths: string[][], name: string): case "js": args = jsArgs(config, paths); break; + case "playwright": + args = playwrightArgs(config, paths); + break; case "pytest": args = pytestArgs(config.args, paths); break; From 88f494ca505844b4ab4323ee62705c704e191a84 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Sun, 22 Nov 2026 15:31:17 +0900 Subject: [PATCH 02/50] feat(debugger): view pandas and numpy values as a table (#5166) In a Python debug session, a DataFrame, Series or ndarray variable or watch only showed a one-line repr. It now has View as Table in its context menu: a resizable window with column headers (with dtypes for a DataFrame), the index, the shape, and pagers for rows (100 per page) and columns (30 per page). Each page is one `evaluate` in the paused frame: a small helper slices the object in the debuggee and returns only that page as JSON, so the whole object never goes over DAP. The expression can be edited (e.g. `a[0]` for a 3-D array), and the window stays open across steps, refreshing after each step or frame change. Closes #5165 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- .../debugger/__tests__/tableView.test.tsx | 245 ++++++++++++++++++ src/features/debugger/index.ts | 3 +- src/features/debugger/tableView.ts | 112 ++++++++ src/features/debugger/ui/Overlays.tsx | 20 ++ .../debugger/ui/TableViewDialog.module.css | 115 ++++++++ src/features/debugger/ui/TableViewDialog.tsx | 205 +++++++++++++++ src/features/debugger/ui/VariablesView.tsx | 12 + src/features/debugger/ui/popoverStore.ts | 7 + src/platform/locales/text/en.json | 14 +- src/platform/locales/text/zh.json | 14 +- 10 files changed, 744 insertions(+), 3 deletions(-) create mode 100644 src/features/debugger/__tests__/tableView.test.tsx create mode 100644 src/features/debugger/tableView.ts create mode 100644 src/features/debugger/ui/TableViewDialog.module.css create mode 100644 src/features/debugger/ui/TableViewDialog.tsx diff --git a/src/features/debugger/__tests__/tableView.test.tsx b/src/features/debugger/__tests__/tableView.test.tsx new file mode 100644 index 0000000000..151110f828 --- /dev/null +++ b/src/features/debugger/__tests__/tableView.test.tsx @@ -0,0 +1,245 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; + +const ipc = vi.hoisted(() => ({ debugEvaluateIn: vi.fn() })); +vi.mock("@/platform/ipc", async (original) => { + const real = await original(); + return { ...real, commands: { ...real.commands, ...ipc } }; +}); + +import type { DebugSessionId, Variable } from "@/platform/ipc"; +import { adoptSession, useDebug } from "../state"; +import { clampWindow, isTableType, parseTableResult, tableExpression } from "../tableView"; +import { TableViewDialog } from "../ui/TableViewDialog"; +import { VariablesView } from "../ui/VariablesView"; +import { useOverlays } from "../ui/popoverStore"; +import { hideContextMenu, useContextMenuStore } from "@/ui/Menu"; + +/** How debugpy shows the helper's JSON reply: Python's repr of a str. */ +const pyRepr = (o: unknown) => `'${JSON.stringify(o).replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`; +const reply = (o: unknown) => + Promise.resolve({ + status: "ok" as const, + data: { name: "", value: pyRepr(o), typeName: "str", variablesReference: 0, evaluateName: null }, + }); + +const PAGE = { + kind: "frame" as const, + shape: [250, 2], + rows: 250, + columns: 2, + dtypes: ["object", "float64"], + headers: ["name", "score"], + index: ["0", "1"], + cells: [ + ['it\'s "x"', "1.5"], + ["日本", "nan"], + ], +}; + +function session(adapter = "debugpy") { + useDebug.setState({ sessions: {}, active: null }); + adoptSession(7, { adapter }); + useDebug.setState((s) => ({ + sessions: { 7: { ...s.sessions[7]!, status: "paused", selectedFrame: 10 } }, + active: 7, + })); +} + +/** A `stopped` event as `state.ts` records it: the frame is unknown until the stack trace arrives. */ +function stop(frame: number | null) { + act(() => + useDebug.setState((s) => ({ + sessions: { + 7: { ...s.sessions[7]!, stops: s.sessions[7]!.stops + (frame == null ? 1 : 0), selectedFrame: frame }, + }, + })), + ); +} + +beforeEach(() => session()); +afterEach(() => { + cleanup(); + vi.clearAllMocks(); + useDebug.setState({ sessions: {}, active: null }); + useOverlays.setState({ tableView: null }); +}); + +describe("table view model", () => { + it("knows the types debugpy reports for DataFrame, Series and ndarray", () => { + expect(["DataFrame", "Series", "ndarray"].every(isTableType)).toBe(true); + expect(isTableType("list")).toBe(false); + expect(isTableType(null)).toBe(false); + }); + + it("reads the helper's reply through Python's string quoting", () => { + expect(parseTableResult(pyRepr(PAGE))).toEqual({ page: PAGE }); + expect(parseTableResult(pyRepr({ error: "ndim", ndim: 3 }))).toEqual({ error: "ndim", ndim: 3 }); + expect(parseTableResult("NameError: name 'df' is not defined")).toEqual({ + error: "NameError: name 'df' is not defined", + }); + }); + + it("moves a window the object no longer reaches back to its last page", () => { + const w = { row: 100, column: 30 }; + expect(clampWindow(w, { rows: 250, columns: 45 })).toBe(w); + expect(clampWindow({ row: 200, column: 30 }, { rows: 50, columns: 45 })).toEqual({ row: 0, column: 30 }); + expect(clampWindow({ row: 200, column: 30 }, { rows: 150, columns: 12 })).toEqual({ row: 100, column: 0 }); + expect(clampWindow({ row: 100, column: 0 }, { rows: 0, columns: 0 })).toEqual({ row: 0, column: 0 }); + }); + + it("passes the expression outside the helper's lambda, with the page window", () => { + const e = tableExpression("frames['a']", { row: 100, column: 30 }); + expect(e).toMatch( + /^\(lambda g, o: \(exec\(".*", g\), g\['f'\]\(o, 100, 100, 30, 30\)\)\[1\]\)\(\{\}, \(frames\['a'\]\)\)$/s, + ); + }); +}); + +describe("View as Table", () => { + it("shows a page with headers, dtypes and index, and fetches the next rows on demand", async () => { + ipc.debugEvaluateIn.mockImplementation(() => reply(PAGE)); + render( {}} />); + const table = await screen.findByRole("table"); + expect( + within(table) + .getAllByRole("columnheader") + .map((h) => h.textContent), + ).toEqual(["", "nameobject", "scorefloat64"]); + expect(within(table).getAllByRole("row")[1]!.textContent).toBe('0it\'s "x"1.5'); + expect(screen.getByText("Shape (250, 2)")).toBeInTheDocument(); + expect(screen.getByText("Rows 1–100 of 250")).toBeInTheDocument(); + expect(ipc.debugEvaluateIn).toHaveBeenCalledWith(7, 10, tableExpression("df", { row: 0, column: 0 }), "clipboard"); + + fireEvent.click(screen.getByRole("button", { name: "Next Rows" })); + await waitFor(() => + expect(ipc.debugEvaluateIn).toHaveBeenLastCalledWith( + 7, + 10, + tableExpression("df", { row: 100, column: 0 }), + "clipboard", + ), + ); + expect(await screen.findByText("Rows 101–200 of 250")).toBeInTheDocument(); + }); + + it("asks for a 2-D slice of an array with more dimensions", async () => { + ipc.debugEvaluateIn.mockImplementation(() => reply({ error: "ndim", ndim: 3 })); + render( {}} />); + expect(await screen.findByRole("alert")).toHaveTextContent("A 3-dimensional array can't be shown as a table"); + }); + + it("shows the exception of an expression that fails in the frame", async () => { + // With the `clipboard` context debugpy answers with the exception's repr as the value. + ipc.debugEvaluateIn.mockImplementation(() => + Promise.resolve({ + status: "ok" as const, + data: { + name: "", + value: `NameError("name 'df' is not defined")`, + typeName: "NameError", + variablesReference: 3, + evaluateName: null, + }, + }), + ); + render( {}} />); + expect(await screen.findByRole("alert")).toHaveTextContent(`NameError("name 'df' is not defined")`); + }); + + it("goes back to the last page when a step leaves the object shorter than the page shown", async () => { + let rows = 250; + ipc.debugEvaluateIn.mockImplementation(() => reply({ ...PAGE, rows, shape: [rows, 2] })); + render( {}} />); + fireEvent.click(await screen.findByRole("button", { name: "Next Rows" })); + fireEvent.click(await screen.findByRole("button", { name: "Next Rows" })); + expect(await screen.findByText("Rows 201–250 of 250")).toBeInTheDocument(); + + rows = 50; + stop(null); + stop(10); + await waitFor(() => + expect(ipc.debugEvaluateIn).toHaveBeenLastCalledWith( + 7, + 10, + tableExpression("df", { row: 0, column: 0 }), + "clipboard", + ), + ); + expect(await screen.findByText("Shape (50, 2)")).toBeInTheDocument(); + expect(screen.getAllByRole("row")).toHaveLength(3); + }); + + it("waits for the stopped frame, and doesn't show the previous stop's page meanwhile", async () => { + ipc.debugEvaluateIn.mockImplementation(() => reply(PAGE)); + render( {}} />); + await screen.findByRole("table"); + ipc.debugEvaluateIn.mockClear(); + let answer: (v: unknown) => void = () => {}; + ipc.debugEvaluateIn.mockImplementation(() => new Promise((r) => (answer = r))); + + stop(null); + expect(ipc.debugEvaluateIn).not.toHaveBeenCalled(); + expect(screen.queryByRole("table")).toBeNull(); + stop(12); + expect(ipc.debugEvaluateIn).toHaveBeenCalledExactlyOnceWith( + 7, + 12, + tableExpression("df", { row: 0, column: 0 }), + "clipboard", + ); + expect(screen.queryByRole("table")).toBeNull(); + await act(async () => answer(await reply(PAGE))); + expect(screen.getByRole("table")).toBeInTheDocument(); + }); + + it("puts a DataFrame's dtypes on its columns even when the page has one column", async () => { + ipc.debugEvaluateIn.mockImplementation(() => + reply({ ...PAGE, shape: [250, 31], columns: 31, dtypes: ["float64"], headers: ["z"], cells: [["1.0"], ["2.0"]] }), + ); + render( {}} />); + const table = await screen.findByRole("table"); + expect(within(table).getAllByRole("columnheader")[1]).toHaveTextContent("zfloat64"); + expect(screen.getByText("Shape (250, 31)")).toBeInTheDocument(); + }); + + const frame: Variable = { + name: "df", + value: " a\n0 1", + typeName: "DataFrame", + variablesReference: 5, + evaluateName: "df", + }; + const menuFor = (v: Variable) => { + render( + , + ); + fireEvent.contextMenu(screen.getByRole("treeitem")); + const labels = (useContextMenuStore.getState().menu?.items ?? []).map((i) => ("label" in i ? i.label : "|")); + hideContextMenu(); + cleanup(); + return labels; + }; + + it("is offered for a DataFrame in a Python session, and opens outside the Variables view", () => { + render( + , + ); + fireEvent.contextMenu(screen.getByRole("treeitem")); + const item = useContextMenuStore.getState().menu?.items.find((i) => "label" in i && i.label === "View as Table"); + act(() => hideContextMenu()); + expect(item && "run" in item).toBe(true); + if (item && "run" in item) item.run?.(); + // The Variables view unmounts while the program runs; the viewer stays open across steps. + expect(useOverlays.getState().tableView).toEqual({ expression: "df", session: 7 }); + }); + + it("is not offered for other values or other debuggers", () => { + expect(menuFor({ ...frame, typeName: "list" })).not.toContain("View as Table"); + session("lldb"); + expect(menuFor(frame)).not.toContain("View as Table"); + }); +}); diff --git a/src/features/debugger/index.ts b/src/features/debugger/index.ts index 94e7633d35..0246e98e58 100644 --- a/src/features/debugger/index.ts +++ b/src/features/debugger/index.ts @@ -68,7 +68,8 @@ const useAnyOverlay = () => s.attach || s.smartStep || s.streamChooser || - s.streamAbort != null + s.streamAbort != null || + s.tableView ), ); diff --git a/src/features/debugger/tableView.ts b/src/features/debugger/tableView.ts new file mode 100644 index 0000000000..c5cbdca813 --- /dev/null +++ b/src/features/debugger/tableView.ts @@ -0,0 +1,112 @@ +/** + * View as Table (PyCharm's View as Array / DataFrame): one window of a pandas DataFrame / + * Series or numpy array at a time, read with `evaluate` in the paused frame. The debuggee + * slices the object itself, so only the rows and columns on screen cross the wire. + */ +import { stringText } from "./valueText"; + +/** Type names debugpy reports for values the viewer can show. */ +const TABLE_TYPES = new Set(["DataFrame", "Series", "ndarray"]); + +export function isTableType(typeName: string | null | undefined): boolean { + return !!typeName && TABLE_TYPES.has(typeName); +} + +/** Numbers are right-aligned, as in the database grid. */ +export function isNumericDtype(dtype: string | undefined): boolean { + return !!dtype && /^(u?int|float|complex|Int|UInt|Float)\d*$/.test(dtype); +} + +export const ROW_PAGE = 100; +export const COLUMN_PAGE = 30; + +export interface TableWindow { + row: number; + column: number; +} + +export interface TablePage { + kind: "frame" | "series" | "array"; + /** The object's own shape, e.g. `[1000, 5]`. */ + shape: number[]; + rows: number; + columns: number; + /** One dtype per shown column for a DataFrame, else the object's single dtype. */ + dtypes: string[]; + headers: string[]; + index: string[]; + cells: string[][]; +} + +/** `error`: "type" (not a table), "ndim" (more than two dimensions; `ndim` says how many) or the error text. */ +export type TableResult = { page: TablePage } | { error: string; ndim?: number }; + +// Runs in the debuggee. Cells are cut at 200 characters so one huge cell can't flood the reply. +const HELPER = ` +def f(o, r0, nr, c0, nc): + import json + s = lambda v: str(v)[:200] + try: + if hasattr(o, 'iloc') and hasattr(o, 'columns'): + k, d = 'frame', o.iloc[r0:r0 + nr, c0:c0 + nc] + R, C = o.shape + dt, h = [str(x) for x in d.dtypes], [s(c) for c in d.columns] + idx, cells = [s(i) for i in d.index], [[s(v) for v in r] for r in d.itertuples(index=False, name=None)] + elif hasattr(o, 'iloc'): + k, d = 'series', o.iloc[r0:r0 + nr] + R, C = len(o), 1 + dt, h = [str(o.dtype)], ['' if o.name is None else s(o.name)] + idx, cells = [s(i) for i in d.index], [[s(v)] for v in d] + elif hasattr(o, 'ndim') and hasattr(o, 'dtype'): + if o.ndim > 2: + return json.dumps({'error': 'ndim', 'ndim': o.ndim}) + k, a = 'array', (o.reshape(1, 1) if o.ndim == 0 else o) + R, C = a.shape[0], (a.shape[1] if a.ndim == 2 else 1) + d = a[r0:r0 + nr, c0:c0 + nc] if a.ndim == 2 else a[r0:r0 + nr].reshape(-1, 1) + dt, h = [str(o.dtype)], [str(c0 + j) for j in range(d.shape[1])] if a.ndim == 2 else ['0'] + idx, cells = [str(r0 + i) for i in range(d.shape[0])], [[s(v) for v in r] for r in d] + else: + return json.dumps({'error': 'type'}) + return json.dumps({'kind': k, 'shape': list(o.shape), 'rows': R, 'columns': C, 'dtypes': dt, + 'headers': h, 'index': idx, 'cells': cells}) + except Exception as e: + return json.dumps({'error': '%s: %s' % (type(e).__name__, e)}) +`; + +/** + * The window moved back onto the object when a step or another frame left it with fewer rows + * or columns than the window starts at (the last page then); `w` itself when it still fits. + */ +export function clampWindow(w: TableWindow, page: Pick): TableWindow { + const fit = (at: number, total: number, size: number) => + at < total ? at : Math.max(0, Math.floor((total - 1) / size) * size); + const row = fit(w.row, page.rows, ROW_PAGE); + const column = fit(w.column, page.columns, COLUMN_PAGE); + return row === w.row && column === w.column ? w : { row, column }; +} + +/** + * One expression (evaluate takes no statements): defines the helper in a fresh namespace + * and calls it. `expression` is passed as an argument, outside the lambda, because a + * lambda body can't see the frame's locals that `eval` was given. + */ +export function tableExpression(expression: string, w: TableWindow): string { + return ( + `(lambda g, o: (exec(${JSON.stringify(HELPER)}, g), ` + + `g['f'](o, ${w.row}, ${ROW_PAGE}, ${w.column}, ${COLUMN_PAGE}))[1])({}, (${expression}))` + ); +} + +/** The helper's reply (a Python string literal holding JSON), or the adapter's own error text. */ +export function parseTableResult(value: string): TableResult { + let data: unknown; + try { + data = JSON.parse(stringText(value)); + } catch { + return { error: value }; + } + const d = data as Record; + if (typeof d.error === "string") + return d.error === "ndim" ? { error: "ndim", ndim: Number(d.ndim) } : { error: d.error }; + return { page: d as unknown as TablePage }; +} diff --git a/src/features/debugger/ui/Overlays.tsx b/src/features/debugger/ui/Overlays.tsx index d7fb2f0df1..e7a3c6d386 100644 --- a/src/features/debugger/ui/Overlays.tsx +++ b/src/features/debugger/ui/Overlays.tsx @@ -78,6 +78,7 @@ import { EventBreakpointsSection } from "../js/EventBreakpointsSection"; import { StreamChainChooser } from "../streams/StreamChainChooser"; import { StreamAbortDialog } from "../streams/StreamAbortDialog"; import { closeBreakpointPopover, useOverlays } from "./popoverStore"; +import { TableViewDialog } from "./TableViewDialog"; import { VariablesView, type VarRoot } from "./VariablesView"; import { useExpressionCompletion } from "./ExpressionCompletion"; import { pushHistory, readHistory } from "./expressionHistory"; @@ -96,10 +97,29 @@ export function DebuggerOverlays() { + ); } +function TableView() { + const view = useOverlays((s) => s.tableView); + // A finished session (Stop, or Restart, which starts another id) has nothing left to show. + const live = useDebug((s) => view != null && isLive(s.sessions[view.session])); + useEffect(() => { + if (view && !live) useOverlays.setState({ tableView: null }); + }, [view, live]); + if (!view || !live) return null; + return ( + useOverlays.setState({ tableView: null })} + /> + ); +} + function errorText(e: unknown) { return e instanceof Error ? e.message : String(e); } diff --git a/src/features/debugger/ui/TableViewDialog.module.css b/src/features/debugger/ui/TableViewDialog.module.css new file mode 100644 index 0000000000..62d4f8c475 --- /dev/null +++ b/src/features/debugger/ui/TableViewDialog.module.css @@ -0,0 +1,115 @@ +.dialog { + height: clamp(320px, 60vh, 760px); +} + +/* The table scrolls under a fixed bar, not the whole dialog body. */ +.content { + display: flex; + flex-direction: column; + height: 100%; + min-height: 0; +} + +.bar { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: var(--space-2); + padding-bottom: var(--space-2); +} + +.expression { + flex: 1 1 200px; + min-width: 0; + height: var(--h-list-row); + padding: 0 6px; + font-family: var(--font-mono); + font-size: var(--fs-ui); + color: var(--fg); + background: var(--bg-input); + border: 1px solid var(--border); + border-radius: var(--radius-small); +} + +.expression:focus { + outline: none; + border-color: var(--focus-ring); +} + +.summary, +.pager { + color: var(--fg-secondary); + white-space: nowrap; +} + +.pager { + display: inline-flex; + align-items: center; + gap: var(--space-1); +} + +.scroll { + flex: 1; + min-height: 0; + overflow: auto; + box-shadow: inset 0 0 0 1px var(--border); + border-radius: var(--radius-small); +} + +.table { + border-collapse: separate; + border-spacing: 0; + font-family: var(--font-mono); + font-size: var(--fs-ui); + color: var(--fg); +} + +.table th, +.table td { + height: var(--h-list-row); + padding: 0 8px; + white-space: pre; + border-right: 1px solid var(--border); + border-bottom: 1px solid var(--border); +} + +.table thead th { + position: sticky; + top: 0; + z-index: 1; + text-align: left; + font-weight: normal; + color: var(--fg-secondary); + background: var(--bg-island); +} + +.table .index { + position: sticky; + left: 0; + text-align: right; + font-weight: normal; + color: var(--fg-secondary); + background: var(--bg-island); +} + +.table thead .index { + z-index: 2; +} + +.table tbody tr:hover td { + background: var(--bg-hover); +} + +.numeric { + text-align: right; +} + +.dtype { + margin-left: var(--space-1); + color: var(--fg-subtle); +} + +.message { + padding: var(--space-3) 0; + color: var(--fg-secondary); +} diff --git a/src/features/debugger/ui/TableViewDialog.tsx b/src/features/debugger/ui/TableViewDialog.tsx new file mode 100644 index 0000000000..27273b82da --- /dev/null +++ b/src/features/debugger/ui/TableViewDialog.tsx @@ -0,0 +1,205 @@ +/** View as Table: a DataFrame / Series / ndarray of the paused frame, one page of rows and columns at a time. */ +import { useEffect, useRef, useState } from "react"; +import clsx from "clsx"; +import type { DebugSessionId } from "@/platform/ipc"; +import { Dialog, IconButton } from "@/ui"; +import { formatMessage, tx } from "@/platform/i18n"; +import { evaluate, useDebug } from "../state"; +import { + COLUMN_PAGE, + ROW_PAGE, + clampWindow, + isNumericDtype, + parseTableResult, + tableExpression, + type TableResult, +} from "../tableView"; +import styles from "./TableViewDialog.module.css"; + +export function TableViewDialog({ + expression: initial, + session, + onClose, +}: { + expression: string; + session: DebugSessionId; + onClose: () => void; +}) { + const [draft, setDraft] = useState(initial); + const [expression, setExpression] = useState(initial); + const [win, setWin] = useState({ row: 0, column: 0 }); + const [result, setResult] = useState(null); + // A step, a new stop or another frame shows the values the object has there. + const stops = useDebug((st) => st.sessions[session]?.stops); + const frame = useDebug((st) => st.sessions[session]?.selectedFrame); + const paused = useDebug((st) => st.sessions[session]?.status === "paused"); + + // What the shown page was read for; another expression, stop or frame makes it stale. + const readFor = useRef(""); + + useEffect(() => { + const key = `${expression}\n${stops}\n${frame}`; + if (readFor.current !== key) { + readFor.current = key; + setResult(null); + } + const s = useDebug.getState().sessions[session]; + // Right after a stop the frame is unknown until the stack trace arrives; without a frame, + // debugpy would run the expression in a namespace of its own. + if (!s || s.status !== "paused" || s.selectedFrame == null) return; + let live = true; + evaluate(tableExpression(expression, win), "clipboard", s).then( + (v) => { + if (!live) return; + const r = parseTableResult(v.value); + const fits = "page" in r ? clampWindow(win, r.page) : win; + if (fits !== win) setWin(fits); + else setResult(r); + }, + (e: unknown) => live && setResult({ error: e instanceof Error ? e.message : String(e) }), + ); + return () => { + live = false; + }; + }, [expression, win, session, stops, frame, paused]); + + const page = result && "page" in result ? result.page : null; + const error = !paused + ? tx("Values are available while the program is paused") + : result && "error" in result + ? result.error === "type" + ? tx("Not a pandas DataFrame or Series, or a numpy array") + : result.error === "ndim" + ? formatMessage(tx("A {n}-dimensional array can't be shown as a table: view a 2-D slice, e.g. a[0]"), { + n: String(result.ndim), + }) + : result.error + : null; + + const pager = ( + at: number, + size: number, + total: number, + move: (to: number) => void, + label: { range: string; previous: string; next: string }, + ) => + total > size && ( + + move(at - size)} + /> + + {formatMessage(label.range, { + from: String(at + 1), + to: String(Math.min(at + size, total)), + total: String(total), + })} + + = total} + onClick={() => move(at + size)} + /> + + ); + + return ( + {initial}} + width="clamp(520px, 70vw, 1100px)" + minWidth={420} + minHeight={260} + resizable="both" + aria-label={formatMessage(tx("Table view of {label}"), { label: initial })} + className={styles.dialog} + > +
+
+ setDraft(e.target.value)} + onKeyDown={(e) => { + if (e.key !== "Enter" || !draft.trim()) return; + e.preventDefault(); + setExpression(draft.trim()); + setWin({ row: 0, column: 0 }); + }} + /> + {page && ( + + {formatMessage(tx("Shape ({shape})"), { shape: page.shape.join(", ") })} + {page.kind !== "frame" ? ` · ${page.dtypes[0]}` : ""} + + )} + {page && + pager(win.row, ROW_PAGE, page.rows, (row) => setWin({ ...win, row }), { + range: tx("Rows {from}–{to} of {total}"), + previous: tx("Previous Rows"), + next: tx("Next Rows"), + })} + {page && + pager(win.column, COLUMN_PAGE, page.columns, (column) => setWin({ ...win, column }), { + range: tx("Columns {from}–{to} of {total}"), + previous: tx("Previous Columns"), + next: tx("Next Columns"), + })} +
+ {error ? ( +
+ {error} +
+ ) : page ? ( +
+ + + + + ))} + + + + {page.cells.map((row, r) => ( + + + {row.map((cell, c) => ( + + ))} + + ))} + +
+ {page.headers.map((h, i) => ( + + {h} + {page.kind === "frame" && {page.dtypes[i]}} +
+ {page.index[r]} + + {cell} +
+
+ ) : ( +
{tx("Loading…")}
+ )} +
+
+ ); +} diff --git a/src/features/debugger/ui/VariablesView.tsx b/src/features/debugger/ui/VariablesView.tsx index 301e3f6e3d..c18a0d3d2a 100644 --- a/src/features/debugger/ui/VariablesView.tsx +++ b/src/features/debugger/ui/VariablesView.tsx @@ -19,11 +19,14 @@ import { removeAllWatches, removeWatch, revealFrame, + rootOf, sessionSupports, setVariableValue, useDebug, } from "../state"; import { blurDebugView, focusDebugView } from "./focusedView"; +import { openTableView } from "./popoverStore"; +import { isTableType } from "../tableView"; import { classifyValue, oneLine, shownValue, sortVariables } from "../values"; import { stringText, valueText } from "../valueText"; import { workflowSettings } from "@/platform/workflowSettings"; @@ -400,6 +403,9 @@ export function VariablesView({ { kind: "separator" }, ); if (editable(node)) items.push({ label: "Set Value…", icon: "edit", shortcut: "F2", run: () => startEdit(node) }); + const tableExpression = node.evaluateName; + if (tableExpression && session != null && isTableType(node.typeName) && pausedIn(session)?.adapter === "debugpy") + items.push({ label: "View as Table", run: () => openTableView(tableExpression, session) }); items.push( { label: "Copy Value", icon: "copy", run: () => void copyValue(node) }, { label: "Copy Name", run: () => void writeClipboardText(node.name) }, @@ -480,6 +486,12 @@ export function VariablesView({ ); } +/** The session with this id while it is paused, with the adapter its root session started. */ +function pausedIn(session: DebugSessionId | null) { + const s = session != null ? useDebug.getState().sessions[session] : undefined; + return s?.status === "paused" ? rootOf(s) : null; +} + /** * View: the whole value in a popup that a click outside closes. Adapters cut long strings * short in variables; the value is evaluated again as for copying (`clipboard`), which diff --git a/src/features/debugger/ui/popoverStore.ts b/src/features/debugger/ui/popoverStore.ts index 845266696c..87a4b70860 100644 --- a/src/features/debugger/ui/popoverStore.ts +++ b/src/features/debugger/ui/popoverStore.ts @@ -40,6 +40,8 @@ interface OverlayState { streamChooser: { session: DebugSessionId; frame: number; chains: StreamChainInfo[] } | null; /** The session whose stream trace "Abort Operation…" asks about. */ streamAbort: DebugSessionId | null; + /** View as Table; it stays open across steps, so it lives here rather than in the Variables view. */ + tableView: { expression: string; session: DebugSessionId } | null; } export const useOverlays = create(() => ({ @@ -51,6 +53,7 @@ export const useOverlays = create(() => ({ smartStep: null, streamChooser: null, streamAbort: null, + tableView: null, })); export function openBreakpointPopover(path: string, id: string, at: { x: number; y: number }, focusLog = false) { @@ -61,6 +64,10 @@ export function closeBreakpointPopover() { useOverlays.setState({ popover: null }); } +export function openTableView(expression: string, session: DebugSessionId) { + useOverlays.setState({ tableView: { expression, session } }); +} + export function openEvaluateDialog(expression = "") { useOverlays.setState({ evaluate: { expression } }); } diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index aa007f28b4..c250b6a01a 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -3040,5 +3040,17 @@ "Mail:": "Mail:", "A folder with this name already exists and is not empty": "A folder with this name already exists and is not empty", "Show Only Affected Changes": "Show Only Affected Changes", - "Layout": "Layout" + "Layout": "Layout", + "Values are available while the program is paused": "Values are available while the program is paused", + "Not a pandas DataFrame or Series, or a numpy array": "Not a pandas DataFrame or Series, or a numpy array", + "A {n}-dimensional array can't be shown as a table: view a 2-D slice, e.g. a[0]": "A {n}-dimensional array can't be shown as a table: view a 2-D slice, e.g. a[0]", + "Table view of {label}": "Table view of {label}", + "Shape ({shape})": "Shape ({shape})", + "Rows {from}–{to} of {total}": "Rows {from}–{to} of {total}", + "Columns {from}–{to} of {total}": "Columns {from}–{to} of {total}", + "View as Table": "View as Table", + "Previous Rows": "Previous Rows", + "Next Rows": "Next Rows", + "Previous Columns": "Previous Columns", + "Next Columns": "Next Columns" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 75f5af9fea..1cfc96f78f 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -9358,5 +9358,17 @@ "Homepage:": "主页:", "Mail:": "邮件:", "Show Only Affected Changes": "仅显示受影响的变更", - "Layout": "布局" + "Layout": "布局", + "Values are available while the program is paused": "程序暂停时才能查看值", + "Not a pandas DataFrame or Series, or a numpy array": "不是 pandas DataFrame、Series 或 numpy 数组", + "A {n}-dimensional array can't be shown as a table: view a 2-D slice, e.g. a[0]": "{n} 维数组无法显示为表格:请查看二维切片,例如 a[0]", + "Table view of {label}": "{label} 的表格视图", + "Shape ({shape})": "形状 ({shape})", + "Rows {from}–{to} of {total}": "第 {from}–{to} 行,共 {total} 行", + "Columns {from}–{to} of {total}": "第 {from}–{to} 列,共 {total} 列", + "View as Table": "以表格查看", + "Previous Rows": "上一组行", + "Next Rows": "下一组行", + "Previous Columns": "上一组列", + "Next Columns": "下一组列" } From c632dfa01c8d21497f550bcf74a4469fcab90323 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Sun, 22 Nov 2026 15:34:50 +0900 Subject: [PATCH 03/50] feat(python): add a Python Console tool window (#5164) Adds a Python Console tool window: an interactive interpreter of the project's Python (the one Settings and the status bar show; in a workspace, the member the active file is in), started in the project root with the source roots on `PYTHONPATH`. It uses IPython when the interpreter has it and plain Python otherwise, in its own `__main__`. Enter runs the input, Shift+Enter adds a line, Up/Down recall earlier inputs, and while code runs a typed line answers its `input()`. A Variables pane lists the console's globals after each run. Execute Selection in Python Console (`python.console.executeSelection`, Alt+Shift+E, also in the editor context menu of Python files) sends the selection or the current line, starting the console if needed; a selection inside an indented block is dedented. The console is a small driver script run on the existing Run process host, so there are no backend changes. Closes #5148 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- src/features/index.ts | 2 + src/features/python-console/ConsoleView.tsx | 142 +++++++++++ .../python-console/PythonConsole.module.css | 85 +++++++ src/features/python-console/console.py | 103 ++++++++ src/features/python-console/console.test.ts | 67 ++++++ src/features/python-console/index.ts | 57 +++++ src/features/python-console/protocol.test.ts | 38 +++ src/features/python-console/protocol.ts | 43 ++++ src/features/python-console/selection.test.ts | 20 ++ src/features/python-console/selection.ts | 12 + src/features/python-console/store.test.ts | 85 +++++++ src/features/python-console/store.ts | 221 ++++++++++++++++++ src/platform/keymaps/ideaParity.test.ts | 1 + src/platform/keymaps/intellij-macos.ts | 1 + src/platform/keymaps/intellij-windows.ts | 1 + src/platform/locales/text/en.json | 10 + src/platform/locales/text/zh.json | 10 + 17 files changed, 898 insertions(+) create mode 100644 src/features/python-console/ConsoleView.tsx create mode 100644 src/features/python-console/PythonConsole.module.css create mode 100644 src/features/python-console/console.py create mode 100644 src/features/python-console/console.test.ts create mode 100644 src/features/python-console/index.ts create mode 100644 src/features/python-console/protocol.test.ts create mode 100644 src/features/python-console/protocol.ts create mode 100644 src/features/python-console/selection.test.ts create mode 100644 src/features/python-console/selection.ts create mode 100644 src/features/python-console/store.test.ts create mode 100644 src/features/python-console/store.ts diff --git a/src/features/index.ts b/src/features/index.ts index a062a2d025..ecccffd69e 100644 --- a/src/features/index.ts +++ b/src/features/index.ts @@ -37,6 +37,7 @@ import { activate as scratch } from "./scratch"; import { activate as libraries } from "./libraries"; import { activate as viewers } from "./viewers"; import { activate as notebook } from "./notebook"; +import { activate as pythonConsole } from "./python-console"; import { activate as web } from "./web"; import { activate as analysis } from "./analysis"; import { activate as services } from "./services"; @@ -91,6 +92,7 @@ const features: Array<[string, Activate]> = [ ["scratch", scratch], ["libraries", libraries], ["notebook", notebook], + ["python-console", pythonConsole], ["viewers", viewers], ["web", web], ["analysis", analysis], diff --git a/src/features/python-console/ConsoleView.tsx b/src/features/python-console/ConsoleView.tsx new file mode 100644 index 0000000000..b756e00749 --- /dev/null +++ b/src/features/python-console/ConsoleView.tsx @@ -0,0 +1,142 @@ +/** Python Console tool window: output, the input box below it, and the console's variables beside them. */ +import { useEffect, useLayoutEffect, useRef, useState } from "react"; +import { executeAction } from "@/platform/actions"; +import { useConsoleFont } from "@/platform/consoleFont"; +import { useTx } from "@/platform/i18n"; +import { Button, EmptyState, IconButton, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui"; +import { spanStyle } from "@/ui/ansi"; +import { clearOutput, execute, restartConsole, sendInput, startConsole, stopConsole, useConsole } from "./store"; +import styles from "./PythonConsole.module.css"; + +export function ConsoleView() { + const { status, header, output, variables, noInterpreter } = useConsole(); + const font = useConsoleFont(); + const t = useTx(); + const outputRef = useRef(null); + const follow = useRef(true); + + useEffect(() => void startConsole(), []); + useLayoutEffect(() => { + const el = outputRef.current; + if (el && follow.current) el.scrollTop = el.scrollHeight; + }, [output]); + + if (noInterpreter && status === "stopped") { + return ( + + + + + } + > + Select an interpreter for this project to use the Python Console. + + ); + } + + const fontStyle = { fontFamily: font.family, fontSize: font.size, lineHeight: `${font.rowHeight}px` }; + return ( +
+
+ + + + {header ?? (status === "starting" ? Starting… : null)} +
+ + +
{ + const el = e.currentTarget; + follow.current = el.scrollHeight - el.scrollTop - el.clientHeight < 4; + }} + > + {output.map((s, i) => ( + + {s.text} + + ))} +
+ +
+ + + {variables.length ? ( +
+ {variables.map((v) => ( +
+ {v.name} + {v.type} + {v.value} +
+ ))} +
+ ) : ( + + )} +
+
+
+ ); +} + +/** Enter runs the input (or, while code runs, answers its `input()`); Shift+Enter adds a line; ↑/↓ recall. */ +function ConsoleInput({ style, busy }: { style: React.CSSProperties; busy: boolean }) { + const [text, setText] = useState(""); + const browse = useRef(null); + const t = useTx(); + return ( +