Compare commits

..
Author SHA1 Message Date
l0ng-ai 98856fd5a1 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	e2e/debugVariablesLayout.spec.ts
2026-11-22 20:34:54 +08:00
l0ng-ai d3be99543d fix(run): anchor console fold controls in the gutter (#5198)
Expanded output has a collapse control beside its row in the Run console gutter. It stays at the left edge while long output scrolls horizontally. A fold at the start of the buffer keeps its control after expansion, and activating a focused fold control leaves process input alone.
2026-11-22 20:34:31 +08:00
l0ng-ai f0cc99a4c7 fix(vcs): give commit subjects room beside compact refs (#5191)
Give Git Log commit subjects room beside long reference labels. Compact References View keeps labels within about a third of the available text column, with the full reference on hover. References in the log use the small UI font and the layout works on either side of the subject.
2026-11-22 20:34:26 +08:00
l0ng-ai 8db16dea32 fix(editor): keep same-name tabs distinguishable (#5187)
Same-name editor tabs show the distinguishing directory before the filename. In a narrow split, the directory gives up space first and the filename stays intact when it fits. The Hidden Tabs picker uses the same path label.
2026-11-22 20:34:21 +08:00
l0ng-ai 6a7297519c fix(settings): keep the current page visible in breadcrumbs (#5196)
Keep the current page name visible as the Settings pane narrows. Parent labels shorten first, and the breadcrumb tooltip shows the full path.
2026-11-22 20:33:01 +08:00
l0ng-ai 08362db3ca fix(run): keep the test summary together and clarify its status (#5186)
Keep elapsed time beside the test counts in the Run window at the same text size. The summary keeps its Running label when the first test has started and no results have arrived yet. A thin line below the summary shows the current state alongside the icon and counts.
2026-11-22 20:32:57 +08:00
l0ng-ai b7f3df0472 fix(debugger): keep values readable beside long type labels (#5185)
Keep debugger values readable beside long runtime types. The row reserves space for a value preview based on its length, so short values leave more room for names. A truncated type can still be read on hover, and the full type appears when the pane has room.
2026-11-22 20:32:52 +08:00
l0ng-ai c5824771c1 fix(editor): make workspace refactoring previews easier to scan (#5183)
Separate the filename from its directory in workspace refactoring previews. This gives same-named files distinct locations and frees space for rename targets and occurrence counts. Hovering a file or a rename target shows its full path.
2026-11-22 20:32:47 +08:00
l0ng-ai 40e5f9b7b3 fix(usages): distinguish files with the same name in the popup (#5181)
Add a muted directory caption beside each filename that appears in more than one file in Show Usages. Identical filenames, line numbers and snippets can otherwise make two results indistinguishable until selected. The popup uses the same directory labels as editor tabs, including a longer suffix when directory names repeat at different depths.
2026-11-22 20:32:41 +08:00
l0ng-ai 8bc82d08c6 fix(vcs): give outgoing commit messages a clear subject (#5180)
Give the selected commit's subject a stronger weight and separate it from the body in the Push dialog. The preview uses the editor's font settings for the message and compact text for the revision, author and date, matching the message hierarchy in Git Log.
2026-11-22 20:32:23 +08:00
l0ng-ai b0473f17b5 fix(run): keep the configuration header visible while scrolling (#5175)
Keep the configuration name and project-file checkbox visible above the scrolling options in Run/Debug Configurations. Long forms previously scrolled these controls out of view, so editing the name or changing where a configuration is saved meant returning to the top.
2026-11-22 20:31:59 +08:00
l0ng-ai 21264641ba fix(search): clarify Recent Locations file captions (#5170)
Recent Locations now shows the filename once, with a symbol breadcrumb or its parent directory beside it. Directory captions distinguish entries with the same filename, and hovering over a caption reveals the full project-relative path.
2026-11-22 20:31:00 +08:00
l0ng-ai 3ce4578600 fix(editor): separate quick fixes in the intentions popup (#5167)
Separate quick fixes from other actions in the Intentions popup with a divider. The divider is skipped during keyboard navigation and disappears when filtering leaves a single group. The popup keeps the chosen action selected when more results arrive from the language server.
2026-11-22 20:30:36 +08:00
l0ng-ai e89b565a78 fix(diff): keep revision filenames readable in narrow panes (#5163)
Keep filenames visible in side-by-side revision headings. Long directories elide before the filename, and the title tooltip shows the complete path and revision. Revision paths use the standard 13 px UI text size.
2026-11-22 20:28:36 +08:00
l0ng-ai b2a1ee2204 fix(run): keep primary actions in view in side docks (#5159)
Keep Rerun and Stop together and give narrow Run docks more room for output. When the toolbar gets narrow, Scroll to End and Soft-Wrap move into More Actions and keep their checked states. The same menu opens the current run configuration, and a wider panel shows the console toggles on the toolbar.
2026-11-22 20:28:31 +08:00
l0ng-ai 828cb271d9 fix(search): keep file locations readable in Find in Files (#5145)
Give line numbers their own space at the right edge of Find in Files and Replace in Files results. Long file labels can still fit with an ellipsis, and hovering reveals the full relative path. Consecutive hits in the same file use quieter filename text so the line numbers are easier to scan.
2026-11-22 20:28:26 +08:00
l0ng-ai ed369c2a6d fix(debugger): group line breakpoint actions (#5141)
Group a line breakpoint's logging controls under Actions in the Breakpoints dialog and gutter popup. The dialog includes Remove once hit in the same group. The gutter popup uses the standard 13 px text size for the condition and hit count labels.
2026-11-22 20:28:20 +08:00
l0ng-ai 3103ec19f9 fix(vcs): Add to .gitignore and Show History act on the focused Project view (#5215)
Add to .gitignore, Add to .git/info/exclude and Show History for File took the active editor's file even when the shortcut was pressed in the Project view. Like Add to VCS they now take the Project view's selection while it has focus and the open file otherwise.
2026-11-22 20:07:24 +08:00
Aevion 026ef8794f fix(vcs): Add to VCS stages the Project view's selection (#5210)
Pressing Add to VCS (Option+Cmd+A) with a folder selected in the Project view reported "Nothing to add" instead of staging the unversioned files in it: the action resolved its targets from the active editor's file only. While the Project view has focus it now takes the Project view's selection; from the editor it still adds the open file.

Co-authored-by: aevioni <[email protected]>
2026-11-22 20:03:40 +08:00
l0ng-ai 7e77c270b7 fix(java): resolve compileOnly project dependencies in Gradle builds (#5213)
Gradle's Eclipse model, which jdtls imports a Gradle build through, leaves out project dependencies a source set only compiles against (compileOnly / testCompileOnly(project(":a"))), so their classes showed as unresolved although Gradle compiled them. jdtls's Gradle import now runs an init script that adds every project on the main and test compile classpaths, keeping test-only ones marked as test code.

On macOS, Buildship stores a build's arguments joined by spaces and splits them again, and jdtls passes its own init scripts from its configuration area under Application Support, so every import that set a Gradle JDK, user home or argument failed ("The specified initialization script '.../Application' does not exist"). A jdtls install under a path with spaces now gets a configuration area in the user's cache directory, and our init script goes to the first directory without spaces.

Fixes #5090
2026-11-22 19:56:38 +08:00
Emir 9abca932d1 feat(settings): pick a custom accent colour with the colour picker (#5204)
The custom swatch of Settings > Appearance > Accent color now opens the editor's colour picker (opaque: RGB and HEX fields, recent colours, eyedropper where available) instead of a native colour input and hex field. The new value is staged and saved with Settings Apply.

The picker moves from the color-preview feature to src/ui so both features use the same component.

Co-authored-by: laot7490 <[email protected]>
2026-11-22 19:33:55 +08:00
Muuandmuutot ce6c61aa5e feat(settings): preview Diff & Merge colours in a real merge view (#5098)
Settings > Editor > Color Scheme > Diff & Merge now previews the colours in a three-pane merge view (left / result / right) painted with the same CodeMirror diff decorations as a real merge, including a folded unchanged fragment with the wave separator. Clicking a coloured line selects its attribute.

The preview is a mergeSchemePreview editor kind registered from the VCS settings pages, so it also works in the standalone Settings window, which never activates the workbench diff viewer, and the settings feature does not import the VCS feature.

Co-authored-by: muutot <[email protected]>
2026-11-22 19:27:01 +08:00
LU XIANGRUIandwildcatDownstairs 9e8722feb6 feat(lsp): lint and format with Biome (#5200)
Adds Biome as a language server (lint diagnostics and code actions) and as a formatter for CSS, GraphQL, JavaScript, TypeScript (and JSX), JSON and JSONC, with a Languages & Frameworks > Biome settings page (path, provider, run on save, enabled languages).

Biome formats instead of Prettier and oxfmt below a biome.json / biome.jsonc or a Biome installation, unless the nearest configuration sets formatter.enabled to false, in which case Prettier keeps formatting. Resolved conflicts with the Tailwind CSS language server: both servers are listed in the language definitions, registry tests and docs.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 19:18:37 +08:00
faysou f2950defcf perf(markdown): render preview math as SVG (#5048)
Typeset equations with MathJax before painting the Markdown preview.
Load MathJax on demand, preserve accessible MathML, and fall back
to KaTeX for unsupported equations.
2026-11-22 19:06:38 +08:00
LU XIANGRUIandwildcatDownstairs 0130847bc0 feat(languages): start the Tailwind CSS language server in Tailwind projects (#5199)
Runs @tailwindcss/language-server next to the language's own servers for HTML, CSS, JS/JSX, TS/TSX, Vue, Svelte and Astro, only below a tailwind.config.* (v3) or a package.json listing tailwindcss in dependencies or devDependencies (v4), with one-click install like the ESLint and Angular servers. JSON root markers (package.json#…) now match a key with any non-null value, not only objects. Adds fixtures/tailwind-app and an ignored real-server test.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 18:55:05 +08:00
LU XIANGRUIandwildcatDownstairs b9f9e2668a fix(debugger): adopt child sessions whose ids an earlier backend used (#5197)
A window whose project moves to another backend process (a remote reconnect, or a new openidea-server in the smoke tests) sees session ids numbered from 1 again. ownSession checked the ids of forgotten sessions before looking for a known parent, so a new child's started event reusing such an id was dropped, along with every later event of that child: the Debug tool window never showed the pause. started is a session's first event and can't be a late event of a forgotten session, so it no longer stops there; a child is still adopted only under a session of this window, and other late events of forgotten ids stay ignored.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 18:51:58 +08:00
LU XIANGRUIandwildcatDownstairs 1f39eb8e63 fix(run): keep Jest and Vitest gutter runs as they were (#5194)
#5173 gave every JS file in test/ gutter targets and #5169 made all kind-node test configurations bases for gutter runs, so Jest/Vitest projects gained run icons in test/ helpers and imported npx jest configurations started running gutter targets. test/ now counts only in projects with a Mocha or node --test configuration, and only Playwright's node configurations are gutter bases.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 18:50:42 +08:00
l0ng-ai a4db4a9e3f fix(vcs): commit a new file's edits made after Add to Git (#5202)
Add to Git stages a new file as it was created, usually empty; edits afterwards leave it partially staged, and Commit included partially staged files with only their staged part, so the first commit held the empty file and the content needed a second commit. A partially staged file whose staged side is an addition is now included whole by default (also when committing selected files) and loses the partial badge; other partially staged files keep committing their staged part.

Fixes #5189
2026-11-22 18:48:23 +08:00
l0ng-ai ca05825d7c fix(debugger): stabilize the inline variable editor 2026-11-22 17:50:58 +08:00
l0ng-ai c209e189e0 docs(plugins): format the run-targets process tables (#5193)
Re-aligns the Running programs tables in docs/{en,zh}/plugins/guides/run-targets.mdx so pnpm format:check passes on main again. Whitespace only.
2026-11-22 17:44:20 +08:00
Muuandmuutot 0b83b3ffbc style(ui): compact metrics for combo boxes and editor tabs (#5188)
Compact mode now also steps the combo box label padding (9/6 → 6/6, ComboBox.padding.compact) and radius (4px → 2px, ComboBox.arc.compact), and the editor tab pill's inline padding (8px → 6px, EditorTabs.tabInsets.compact), through new --combo-pad-start/end, --radius-combo and --tab-pad-x tokens. Toolbar and tool window stripe button radii stay at 6px → 4px (MainToolbar.Button.arc and Button.ToolWindow.arc 12 → 8).

Co-authored-by: muutot <[email protected]>
2026-11-22 16:55:22 +08:00
l0ng-ai 7caec95fee fix(java): stop reusing launch snapshots after Build › Rebuild (#5190)
Launch snapshots are reused while a module's sources keep their fingerprint. Build › Rebuild Project cleaned and recompiled target/classes but left the launch records untouched, so the next run kept loading a snapshot that could hold classes the clean removed (a class compiled under its old package), and Spring found two beans with the same name.

A Rebuild now clears the fingerprint of every launch record in the project, so the next launch copies the rebuilt outputs; the records stay, so those modules keep delegating to Maven.

Fixes #5179
2026-11-22 16:46:53 +08:00
Deng Liuanddengliu 3d56af936d feat(dev): add dogfood:remote task to build and stage openidea-server (#5139)
Adds `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean] [--install-rust]` (also `mise run dogfood:remote`) for dogfooding backend changes in Remote Development without cross-compiling locally. It reads the host from Settings › Tools › SSH Configurations, checks SSH reachability and the minimum Rust version, syncs the backend workspace to `~/.cache/openidea-dogfood/workspace`, builds `openidea-server` there, installs it at the `~/.openidea/server/<version>/<build_id>` path `ensure_server` expects (so connecting doesn't upload another binary), stages the matching binary locally (`--clean` restores the release one), and asks before restarting a running server. The `build_id` hash uses `blake3` from the new `@noble/hashes` devDependency. Rust is installed on the host only with `--install-rust`.

Closes #5135

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

Part of #5113

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

Closes #5153

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 15:24:38 +08:00
LU XIANGRUIandwildcatDownstairs 8e541d5b45 feat(run): run node:test tests with a test tree and Rerun Failed Tests (#5172)
`node --test` runs showed no test tree, and single tests ran with Jest's `-t`.

- Detection: a `package.json` script whose Node options include `--test` (also `tsx --test`) is a test configuration with `testRunner: "node-test"`; a script that picks its own `--test-reporter` runs as written.
- Test tree: test runs add the IDE's reporter (`nodeTestReporter.js`, passed as a `data:` URL) next to `spec` through `NODE_OPTIONS`, which works through `npm run`, Node's per-file child processes and remote run targets. It prints a record per test (file, describe chain, status, duration, declaration line, error); the records become the tree and are hidden from the console, which keeps `spec`'s output.
- Gutter, Rerun Failed Tests, run selected tests: select by full name with `--test-name-pattern` in `NODE_OPTIONS`, plus the files.

New fixture `fixtures/node-test-app`, run by `smoke/run.test.ts` in the TypeScript job.

Closes #5152

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 15:19:57 +08:00
LU XIANGRUIandwildcatDownstairs 87c4659547 fix(i18n): insert tx template values as written (#5177)
In the Chinese UI, Rename on a folder named `tasks` read 将目录“任务”及其用法重命名为:. The `tx` template tag translated every interpolated string that had a catalog entry of its own, so a file, branch, script or container name that matched a UI word (`tasks`, `Retry`) was shown translated. Values are now inserted as written. Call sites that interpolate the app's own UI words (kind labels, option titles, "Source"/"Target") mark them with the new `txPart(...)`, which is also translated again after a language change; the text catalog guard checks `txPart` literals too. `txTemplate` still translates captured parts.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 15:14:54 +08:00
l0ng-ai 3475dbd688 fix: restore frontend tests after the skill installer and Python Console (#5182)
Three frontend tests failed on main after #5157 and #5164: SkillsPage.module.css read an undeclared --r-sm (now --radius-small); the SKILL.md catalog entry is a file name kept as written in Chinese, so it joins the same-as-English list; and the VS Code presets lacked python.console.executeSelection, which stays unbound there because Shift+Enter would shadow typing in Python files.
2026-11-22 15:14:02 +08:00
Deng Liuanddengliu 0800e8445f feat(agents): native GitHub skill browser, preview, static scan, and installer (#5157)
Settings › Agents › Skills gets Install Skill…: enter a GitHub source in the forms `npx skills add` accepts (`owner/repo`, `owner/repo@skill`, `owner/repo#ref`, `owner/repo/path[@ref]`, GitHub tree URLs, pasted skills.sh links), pick one of the skills found, preview its `SKILL.md` and file list, and install it into `~/.agents/skills` (default) or the workspace `.agents/skills` (trusted projects only). Sources resolve through GitHub's Git Trees and Blobs APIs over the existing `ide-tools` HTTP client, with no curated repository list and no Node or git dependency, retrying unauthenticated when an ambient GitHub token gets HTTP 401 on a public repository. Only the selected skill's subtree is downloaded (capped at 2 MiB / 256 files) and installed atomically through a staging folder. A static scan flags hidden or bidirectional Unicode, out-of-root symlinks (omitted on disk), executable scripts and `allowed-tools` shell grants; the user must confirm the warnings, and the backend checks that confirmation again before writing.

Part of #5115

Co-authored-by: dengliu <[email protected]>
2026-11-22 15:09:01 +08:00
Deng Liuanddengliu b7ac5f1bbb feat(plugins): declarative [[contributes.skills]] in plugin.toml (API 1.15) (#5144)
Plugins can now bundle `SKILL.md` folders with a manifest-only `[[contributes.skills]]` extension point (API 1.15, no WIT change). They appear under Plugins in Settings › Agents › Skills and the Composer Skills picker while the plugin is enabled, and are staged into each CLI's per-session skill folder from the plugin's package directory; disabling or uninstalling the plugin removes them right away. Load-time validation keeps `path` inside the package (no `..` or escaping symlinks), requires `<dir>/SKILL.md` with the usual folder-name and frontmatter rules, and caps a skill folder at 2 MiB / 256 files; an invalid entry becomes a plugin load warning without failing the rest of the plugin. Every file of a valid skill folder is part of the package files, so versioned installs and remote sync copy supporting scripts and references. Workspace and user skills win on a name clash. Includes a declarative fixture plugin and docs.

Closes #5114

Co-authored-by: dengliu <[email protected]>
2026-11-22 15:02:11 +08:00
l0ng-ai f473cd9927 fix(agents): give Codex skill paths one separator on Windows (#5158)
Skill roots are joined as `.agents/skills`, so a SKILL.md path that could not be canonicalized kept a forward slash on Windows and failed hub_staging_hands_each_cli_its_own_tree. Rebuild the path from its components before handing it to Codex.
2026-11-22 14:44:44 +08:00
LU XIANGRUIandwildcatDownstairs 9a3b97a5fa feat(python): flag requirements the interpreter does not satisfy and offer to install them (#5168)
`requirements*.txt` and `pyproject.toml` (`[project]` dependencies, optional dependencies, `[dependency-groups]`) now mark each requirement the project's interpreter doesn't have installed, or whose installed version misses the specifier. A banner offers Install requirements, and the quick fixes are Install requirement and Install all missing requirements; installs use the same pip/uv path as the interpreter settings page, run as a background task, report failures in one notification and re-check the file. The interpreter judges the requirements itself (with `packaging` or pip's vendored copy), so PEP 440 specifiers, PEP 503 names and markers behave as pip does; Rust only parses the files for spans, skipping `-r`, `-e`, options, URLs and paths. Nothing is checked without a local interpreter, for a container interpreter, or in Restricted Mode. It is a new inspection, "Unsatisfied package requirements", and the Cargo version check now shares the same editor plugin (`manifestCheck.ts`).

Closes #5147

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 14:43:09 +08:00
LU XIANGRUIandwildcatDownstairs c632dfa01c 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 <[email protected]>
2026-11-22 14:34:50 +08:00
LU XIANGRUIandwildcatDownstairs 88f494ca50 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 <[email protected]>
2026-11-22 14:31:17 +08:00
LU XIANGRUIandwildcatDownstairs 9b4ee2a6ff feat(run): run Playwright tests with a test tree and Rerun Failed Tests (#5169)
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 <[email protected]>
2026-11-22 14:30:06 +08:00
LU XIANGRUIandwildcatDownstairs e75d438f70 feat(python): update imports when a module or package is renamed or moved (#5171)
Renaming or moving a Python module or package left every import of it broken: basedpyright has no `workspace/willRenameFiles`, so no reference updates reached the move preview. `refactor_file_move_edits` now maps the moved paths to dotted module names from the project's Python roots (`src/` layout or the project root, `tests/`), and `Syntax::python_import_edits` rewrites the import statements of each project `.py`/`.pyi` file from its tree-sitter tree. It covers `import a.b` (with qualified uses `a.b.X`), `import a.b as c`, `from a.b import X`, `from a import b`, relative imports (kept relative, also in the moved files themselves) and package moves; when a rename changes the name an import binds, the import keeps it with an alias. The edits join the existing move preview and undo. A Python server that answers `willRenameFiles` still wins. The Python language smoke now checks file moves.

Closes #5146

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 14:26:50 +08:00
LU XIANGRUIandwildcatDownstairs a67b27c33a feat(editor): highlight CSS, GraphQL, SQL and HTML in template literals (#5160)
In JavaScript and TypeScript files, embedded code in template literals showed as one string. The body of a tagged template literal is now parsed in the language its tag names: CSS for styled-components / emotion / Lit (`styled.div`, `styled(Comp)`, `.attrs(…)`, `css`, `createGlobalStyle`, `keyframes`, `injectGlobal`, parsed as declarations plus nested rules), GraphQL for `gql` / `graphql` (also the `graphql(`…`)` call form), SQL for `sql` and HTML for `html`; a `/* GraphQL */`-style comment before a plain literal works too. Substitutions stay JavaScript. CSS, SQL and HTML use the same modes as files in those languages; GraphQL gets a small stream mode used only inside literals (`.graphql` files keep tree-sitter highlighting). The embedded mode loads lazily, comment toggling and bracket matching follow it, and Angular TypeScript files and Markdown `ts` fences get the same injection.

Closes #5150

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 14:24:24 +08:00
Akbar Husain 62028362d6 feat(remote): forward ports of a WSL project (#5140)
The Ports tool window existed only for SSH hosts and dev containers; a WSL project refused to forward. A WSL distribution shares this machine's loopback (as `forward_web_url` already assumes), so a port it listens on is reachable here on the same port without a tunnel. The route decision is now a pure `forward_route(target, host)` (SSH channel tunnel, container exec tunnel, or WSL's shared loopback; another host stays reachable from a dev container only), and `Forward::Wsl` reports the port unchanged and owns no resource. The Ports tool window registers for WSL sessions, remembered ports are scoped per distribution and folder (`wsl:<distro>:<root>`), the refusal and its string are gone, and the remote docs describe it.

Co-authored-by: akbar1214 <[email protected]>
2026-11-22 14:23:05 +08:00
315 changed files with 14402 additions and 1504 deletions

No files matched your search

+1
View File
@@ -80,6 +80,7 @@ Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
this worktree's running MCP bridges and actual ports.
- `pnpm build` — typecheck + bundle frontend.
- `pnpm dogfood:build` / `pnpm dogfood:install` (or `mise run dogfood:build` / `mise run dogfood:install`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
Generated
+2
View File
@@ -4146,6 +4146,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
name = "ide-agent"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"blake3",
"dunce",
"encoding_rs",
@@ -4845,6 +4846,7 @@ dependencies = [
name = "ide-sdk"
version = "0.1.50"
dependencies = [
"dirs 6.0.0",
"dunce",
"flate2",
"ide-core",
+1
View File
@@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
encoding_rs.workspace = true
base64.workspace = true
blake3.workspace = true
ide-vfs.workspace = true
ide-core.workspace = true
+17 -3
View File
@@ -23,6 +23,7 @@ mod provider;
pub mod registry;
pub mod security;
mod shell;
pub mod skill_installer;
pub mod skills;
mod timeline;
mod worktree;
@@ -31,6 +32,10 @@ pub use catalogs::AgentCatalogs;
pub use cli_update::{AgentCliOffer, AgentCliUpdateResult};
pub use external::ExternalSession;
pub use model::*;
pub use skill_installer::{
InstallRemoteSkillRequest, RemoteSkillBrowseResult, RemoteSkillCandidate, RemoteSkillFile, RemoteSkillPreview,
SkillScanWarning, SkillScanWarningKind,
};
use conversation::{Conversation, SavedSubagent, Session};
use ide_core::{IdeError, IdeResult, IpcPath};
@@ -145,11 +150,19 @@ pub struct SkillsPolicy {
pub workspace_trusted: bool,
/// All workspace folders (the project root plus any multi-repo workspace members).
pub workspace_roots: Vec<PathBuf>,
/// Validated `<dir>` folders contributed by live OpenIDEA plugins (`[[contributes.skills]]`).
pub plugin_dirs: Vec<PathBuf>,
}
impl Default for SkillsPolicy {
fn default() -> Self {
Self { user: BTreeMap::new(), workspace: BTreeMap::new(), workspace_trusted: true, workspace_roots: Vec::new() }
Self {
user: BTreeMap::new(),
workspace: BTreeMap::new(),
workspace_trusted: true,
workspace_roots: Vec::new(),
plugin_dirs: Vec::new(),
}
}
}
@@ -818,10 +831,11 @@ impl AgentManager {
(policy, shared.paths.project_root.clone())
};
let roots = if policy.workspace_roots.is_empty() { vec![root] } else { policy.workspace_roots };
let plugin_dirs = policy.plugin_dirs;
let home = self.shared.paths.home_dir.clone();
blocking(move || {
Ok(skills::resolve(
skills::discover_skills_in(&roots, home.as_deref()),
skills::discover_skills_with_plugins(&roots, home.as_deref(), &plugin_dirs),
None,
&policy.workspace,
&policy.user,
@@ -2142,7 +2156,7 @@ impl Task {
};
blocking(move || {
Ok(skills::resolve(
skills::discover_skills_in(&roots, home.as_deref()),
skills::discover_skills_with_plugins(&roots, home.as_deref(), &policy.plugin_dirs),
Some(&overrides),
&policy.workspace,
&policy.user,
+9 -1
View File
@@ -898,6 +898,8 @@ pub enum AgentSkillSource {
Workspace,
/// The user's `~/.agents/skills` (what `npx skills add` fills).
User,
/// Contributed by an enabled OpenIDEA plugin (`[[contributes.skills]]`).
Plugin,
/// The project's `.claude/skills`.
ClaudeWorkspace,
/// `~/.claude/skills`.
@@ -920,7 +922,7 @@ impl AgentSkillSource {
/// Whether skills of this source are only read, never delivered by OpenIDEA: the CLI
/// discovers them itself, so "off" holds only where the CLI supports a native disable.
pub fn discovered(&self) -> bool {
!matches!(self, Self::Workspace | Self::User)
!matches!(self, Self::Workspace | Self::User | Self::Plugin)
}
}
@@ -946,6 +948,12 @@ pub struct AgentSkill {
/// True when frontmatter sets `disable-model-invocation: true` (defaults to `slashOnly`).
#[serde(default)]
pub disable_model_invocation: bool,
/// True when frontmatter sets `context: fork` (passed through natively to supporting CLIs).
#[serde(default)]
pub context_fork: bool,
/// Optional `paths` / `globs` patterns from frontmatter (passed through natively to supporting CLIs).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub paths: Vec<String>,
/// The `SKILL.md` passes validation (`name` matches its folder, `description` present).
pub valid: bool,
/// What validation found (`name` mismatch, missing or over-long description…).
File diff suppressed because it is too large. Load diff
+218 -26
View File
@@ -125,10 +125,9 @@ fn file_name(path: &Path) -> Option<String> {
path.file_name()?.to_str().map(str::to_owned)
}
/// The `key: value` lines between the leading `---` fences (folded `>` / `|` values joined).
struct Frontmatter {
fields: Vec<(String, String)>,
/// Where the body starts.
lists: Vec<(String, Vec<String>)>,
body: usize,
}
@@ -138,22 +137,42 @@ impl Frontmatter {
let mut lines = text.split_inclusive('\n');
let mut offset = 0;
let mut fields: Vec<(String, String)> = Vec::new();
let mut lists: Vec<(String, Vec<String>)> = Vec::new();
match lines.next() {
Some(first) if first.trim_end() == "---" => offset += first.len(),
_ => return Self { fields, body: 0 },
_ => return Self { fields, lists, body: 0 },
}
for line in lines {
offset += line.len();
let line = line.trim_end();
if line == "---" {
return Self { fields, body: offset };
return Self { fields, lists, body: offset };
}
if line.starts_with([' ', '\t']) {
let unindented_list_item = (line == "-" || line.starts_with("- ") || line.starts_with("-\t"))
&& fields.last().is_some_and(|(_, v)| v.is_empty());
if line.starts_with([' ', '\t']) || unindented_list_item {
let trimmed = line.trim();
if let Some(rest) = trimmed.strip_prefix('-')
&& (rest.is_empty() || rest.starts_with([' ', '\t']))
&& let Some((key, _)) = fields.last()
{
let item = unquote(rest.trim());
if !item.is_empty() {
if let Some((_, existing)) = lists.iter_mut().find(|(k, _)| k == key) {
existing.push(item.to_owned());
} else {
lists.push((key.clone(), vec![item.to_owned()]));
}
}
if unindented_list_item {
continue;
}
}
if let Some((_, value)) = fields.last_mut() {
if !value.is_empty() {
value.push(' ');
}
value.push_str(line.trim());
value.push_str(trimmed);
}
continue;
}
@@ -164,11 +183,15 @@ impl Frontmatter {
}
}
// No closing fence: not frontmatter.
Self { fields: Vec::new(), body: 0 }
Self { fields: Vec::new(), lists: Vec::new(), body: 0 }
}
fn get(&self, key: &str) -> Option<&str> {
self.fields.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
self.fields.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v.as_str())
}
fn list(&self, key: &str) -> Option<&[String]> {
self.lists.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v.as_slice())
}
/// `description`, else the body's first line.
@@ -247,6 +270,17 @@ pub fn discover_skills(workspace: &Path, home: Option<&Path>) -> Vec<AgentSkill>
/// folders) and `home`, in source precedence order, symlinked duplicates collapsed by
/// canonical path while recording secondary sources in [`AgentSkill::also_in`].
pub fn discover_skills_in(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<AgentSkill> {
discover_skills_with_plugins(workspaces, home, &[])
}
/// [`discover_skills_in`] plus the `<dir>` skill folders contributed by enabled OpenIDEA
/// plugins (`[[contributes.skills]]`). Workspace and user skills take precedence on a name
/// clash; a plugin skill is never silently renamed.
pub fn discover_skills_with_plugins(
workspaces: &[PathBuf],
home: Option<&Path>,
plugin_skill_dirs: &[PathBuf],
) -> Vec<AgentSkill> {
let mut out: Vec<AgentSkill> = Vec::new();
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
let mut seen_names: HashSet<String> = HashSet::new();
@@ -273,29 +307,59 @@ pub fn discover_skills_in(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Ag
}
if let Some(home) = home {
roots.extend(HOME_ROOTS.iter().map(|(rel, source)| (home.join(rel), *source)));
roots.extend(copilot_installed_plugin_roots(&home.join(".copilot")));
}
let mut push_skill = |skill: AgentSkill| {
let path = dunce::canonicalize(&skill.path.0).unwrap_or_else(|_| skill.path.0.clone());
if !seen_paths.insert(path.clone()) {
if let Some(existing) = out.iter_mut().find(|s| s.path.0 == path)
&& existing.source != skill.source
&& !existing.also_in.contains(&skill.source)
{
existing.also_in.push(skill.source);
}
return;
}
if !seen_names.insert(skill.name.to_ascii_lowercase()) {
return;
}
out.push(AgentSkill { path: path.into(), ..skill });
};
for (root, source) in roots {
for skill in skills_of(&root, source) {
let path = dunce::canonicalize(&skill.path.0).unwrap_or_else(|_| skill.path.0.clone());
if !seen_paths.insert(path.clone()) {
if let Some(existing) = out.iter_mut().find(|s| s.path.0 == path)
&& existing.source != source
&& !existing.also_in.contains(&source)
{
existing.also_in.push(source);
}
continue;
push_skill(skill);
}
}
for dir in plugin_skill_dirs {
let Some(folder) = file_name(dir) else { continue };
if !dir.is_dir() {
continue;
}
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
push_skill(parse_skill_file(dir, &folder, &text, AgentSkillSource::Plugin));
}
if let Some(home) = home {
for (root, source) in copilot_installed_plugin_roots(&home.join(".copilot")) {
for skill in skills_of(&root, source) {
push_skill(skill);
}
if !seen_names.insert(skill.name.to_ascii_lowercase()) {
continue;
}
out.push(AgentSkill { path: path.into(), ..skill });
}
}
out
}
/// Validates a plugin-contributed `<folder>/SKILL.md` against the hub's folder-name and
/// frontmatter rules (`name` 1–64 `[a-z0-9-]`, matching `folder`, non-empty `description` ≤ 1024 chars).
pub fn validate_plugin_skill(dir: &Path, folder: &str, text: &str) -> Result<AgentSkill, String> {
if !valid_name(folder) {
return Err(format!("skill folder `{folder}` must be 1-64 lowercase letters, digits or hyphens"));
}
let skill = parse_skill_file(dir, folder, text, AgentSkillSource::Plugin);
if !skill.valid {
return Err(skill.warnings.join("; "));
}
Ok(skill)
}
const SKIP_MONOREPO_DIRS: &[&str] =
&["node_modules", "target", "dist", "build", "out", "vendor", "coverage", ".git", ".openidea", ".idea"];
@@ -464,6 +528,8 @@ fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSour
let hint = meta.get("argument-hint").map(|h| strip_ansi(h).trim().to_owned()).filter(|h| !h.is_empty());
let user_invocable = !meta.get("user-invocable").is_some_and(|v| v.eq_ignore_ascii_case("false"));
let disable_model_invocation = meta.get("disable-model-invocation").is_some_and(|v| v.eq_ignore_ascii_case("true"));
let context_fork = meta.get("context").is_some_and(|v| strip_ansi(v).trim().eq_ignore_ascii_case("fork"));
let paths = parse_skill_paths(&meta);
AgentSkill {
name,
description: truncate(&description),
@@ -473,11 +539,35 @@ fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSour
also_in: Vec::new(),
user_invocable,
disable_model_invocation,
context_fork,
paths,
valid: warnings.is_empty(),
warnings,
}
}
fn parse_skill_paths(meta: &Frontmatter) -> Vec<String> {
for key in ["paths", "globs"] {
if let Some(items) = meta.list(key) {
let cleaned: Vec<String> =
items.iter().map(|s| strip_ansi(s).trim().to_owned()).filter(|s| !s.is_empty()).collect();
if !cleaned.is_empty() {
return cleaned;
}
}
if let Some(raw) = meta.get(key) {
let trimmed = strip_ansi(raw);
let inner = trimmed.trim().strip_prefix('[').and_then(|s| s.strip_suffix(']')).unwrap_or(trimmed.trim());
let cleaned: Vec<String> =
inner.split(',').map(|p| unquote(p.trim()).trim().to_owned()).filter(|p| !p.is_empty()).collect();
if !cleaned.is_empty() {
return cleaned;
}
}
}
Vec::new()
}
/// A skill's mode, as one policy layer of the settings has it.
type Policies = BTreeMap<String, AgentSkillPolicy>;
@@ -662,11 +752,12 @@ pub fn stage(
/// Codex `[[skills.config]]` matches `path` against the canonical `SKILL.md` document path.
fn codex_skill_md_path(skill_dir: &Path) -> String {
let md = skill_dir.join("SKILL.md");
dunce::canonicalize(&md)
let md = dunce::canonicalize(&md)
.or_else(|_| dunce::canonicalize(skill_dir).map(|dir| dir.join("SKILL.md")))
.unwrap_or(md)
.to_string_lossy()
.into_owned()
.unwrap_or(md);
// Skill roots are joined as `.agents/skills`; rebuilding from components gives Windows
// one separator when the path could not be canonicalized.
md.components().collect::<PathBuf>().to_string_lossy().into_owned()
}
fn direct_link_matches(root: &Path, name: &str, target: &Path) -> bool {
@@ -992,6 +1083,8 @@ mod tests {
also_in: Vec::new(),
user_invocable: true,
disable_model_invocation: false,
context_fork: false,
paths: Vec::new(),
valid: true,
warnings: Vec::new(),
}
@@ -1330,4 +1423,103 @@ mod tests {
);
}
}
#[test]
fn plugin_skills_yield_to_workspace_and_user_and_stage_to_all_clis() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let ws = root.join("ws");
let home = root.join("home");
let plugin_pkg = root.join("plugins/acme.tools/1.0.0");
write(&ws.join(".agents/skills/clash-ws/SKILL.md"), "---\nname: clash-ws\ndescription: workspace copy\n---\n");
write(&home.join(".agents/skills/clash-user/SKILL.md"), "---\nname: clash-user\ndescription: user copy\n---\n");
write(&plugin_pkg.join("skills/clash-ws/SKILL.md"), "---\nname: clash-ws\ndescription: plugin copy\n---\n");
write(&plugin_pkg.join("skills/clash-user/SKILL.md"), "---\nname: clash-user\ndescription: plugin copy\n---\n");
write(
&plugin_pkg.join("skills/release-notes/SKILL.md"),
"---\nname: release-notes\ndescription: draft release notes\n---\n",
);
let plugin_dirs = vec![
plugin_pkg.join("skills/clash-ws"),
plugin_pkg.join("skills/clash-user"),
plugin_pkg.join("skills/release-notes"),
];
let found = discover_skills_with_plugins(std::slice::from_ref(&ws), Some(&home), &plugin_dirs);
let summary: Vec<(&str, AgentSkillSource, &str)> =
found.iter().map(|s| (s.name.as_str(), s.source, s.description.as_str())).collect();
assert_eq!(
summary,
[
("clash-ws", AgentSkillSource::Workspace, "workspace copy"),
("clash-user", AgentSkillSource::User, "user copy"),
("release-notes", AgentSkillSource::Plugin, "draft release notes"),
],
"workspace and user skills win on name clash without renaming plugin skills"
);
assert!(!AgentSkillSource::Plugin.discovered());
let states = resolve(found.clone(), None, &BTreeMap::new(), &BTreeMap::new(), true);
for provider in ["claude", "copilot", "codex"] {
let farm = farm_dir(&root.join("store"), &format!("plugin-{provider}"));
let _ = stage(&farm, provider, &states, &ws, Some(&home)).unwrap();
}
assert!(
listed(&farm_dir(&root.join("store"), "plugin-claude").join(".claude/skills"))
.contains(&"release-notes".into())
);
assert!(
listed(&farm_dir(&root.join("store"), "plugin-copilot").join("copilot")).contains(&"release-notes".into())
);
assert!(listed(&farm_dir(&root.join("store"), "plugin-codex").join("codex")).contains(&"release-notes".into()));
// Turning a plugin skill off omits it from every CLI's staged farm.
let off_states = resolve(
found,
None,
&BTreeMap::new(),
&BTreeMap::from([("release-notes".to_owned(), policy(AgentSkillMode::Off).unwrap())]),
true,
);
let farm = farm_dir(&root.join("store"), "plugin-off");
let _ = stage(&farm, "claude", &off_states, &ws, Some(&home)).unwrap();
assert!(!farm.join(".claude/skills/release-notes").exists());
}
#[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 -2
View File
@@ -4459,9 +4459,8 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl
let root = root.to_path_buf();
move || SkillsPolicy {
user: BTreeMap::from([("tdd".into(), AgentSkillPolicy { mode: AgentSkillMode::Off })]),
workspace: BTreeMap::new(),
workspace_trusted: true,
workspace_roots: vec![root.clone()],
..SkillsPolicy::default()
}
}));
+14 -2
View File
@@ -1206,6 +1206,7 @@ pub struct LanguagesSettings {
pub typescript: TypeScriptSettings,
pub prettier: ExternalFormatterSettings,
pub oxfmt: ExternalFormatterSettings,
pub biome: ExternalFormatterSettings,
pub ruff: ExternalFormatterSettings,
pub java: JavaSettings,
pub ruby: RubySettings,
@@ -1226,6 +1227,10 @@ impl Default for LanguagesSettings {
typescript: TypeScriptSettings::default(),
prettier: ExternalFormatterSettings::default(),
oxfmt: ExternalFormatterSettings::default(),
biome: ExternalFormatterSettings {
languages: BIOME_LANGUAGES.iter().map(|&l| l.into()).collect(),
..ExternalFormatterSettings::default()
},
ruff: ExternalFormatterSettings {
languages: vec!["python".into()],
..ExternalFormatterSettings::default()
@@ -1297,6 +1302,7 @@ impl LanguagesSettings {
match tool {
ExternalFormatter::Prettier => &self.prettier,
ExternalFormatter::Oxfmt => &self.oxfmt,
ExternalFormatter::Biome => &self.biome,
ExternalFormatter::Ruff => &self.ruff,
}
}
@@ -1308,6 +1314,7 @@ impl LanguagesSettings {
pub enum ExternalFormatter {
Prettier,
Oxfmt,
Biome,
Ruff,
}
@@ -1317,16 +1324,21 @@ impl ExternalFormatter {
match self {
Self::Prettier => "prettier",
Self::Oxfmt => "oxfmt",
Self::Biome => "biome",
Self::Ruff => "ruff",
}
}
}
/// An external formatter (Prettier, oxfmt, Ruff) and the languages it formats.
/// The languages Biome formats (of those Prettier formats).
pub const BIOME_LANGUAGES: [&str; 8] =
["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"];
/// An external formatter (Prettier, oxfmt, Biome, Ruff) and the languages it formats.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ExternalFormatterSettings {
/// Empty path: project node_modules (Prettier/oxfmt), managed installation, then PATH.
/// Empty path: project node_modules (Prettier/oxfmt/Biome), managed installation, then PATH.
pub path: String,
/// Ruff only: directory containing its configuration, or a configuration file.
pub configuration_directory: String,
+22 -1
View File
@@ -122,13 +122,34 @@ pub struct Prepared {
pub key: Option<String>,
/// User-facing one-liner for the plugin details page ("Insert Date").
pub label: String,
/// When set, this entry is skipped with a plugin load warning instead of failing the plugin.
pub warning: Option<String>,
/// Makes it take effect. Must not fail for reasons `prepare` could have checked.
pub commit: Commit,
}
impl Prepared {
pub fn new(label: impl Into<String>, commit: impl FnOnce() -> Result<Disposable, String> + Send + 'static) -> Self {
Self { capabilities: Vec::new(), files: Vec::new(), key: None, label: label.into(), commit: Box::new(commit) }
Self {
capabilities: Vec::new(),
files: Vec::new(),
key: None,
label: label.into(),
warning: None,
commit: Box::new(commit),
}
}
/// Skips an invalid declaration with a load warning while letting the rest of the plugin load.
pub fn skipped(warning: impl Into<String>) -> Self {
Self {
capabilities: Vec::new(),
files: Vec::new(),
key: None,
label: String::new(),
warning: Some(warning.into()),
commit: Box::new(|| Ok(Disposable::noop())),
}
}
pub fn key(mut self, key: impl Into<String>) -> Self {
+6
View File
@@ -270,6 +270,12 @@ impl ExtensionRegistry {
let prepared = point
.prepare(pkg, decl)
.map_err(|e| format!("contributes.{point_id}[{i}]: {}", strip_prefix(&e, point_id)))?;
if let Some(warning) = prepared.warning {
let msg = format!("contributes.{point_id}[{i}]: {}", strip_prefix(&warning, point_id));
tracing::warn!(plugin = %pkg.id(), "{msg}");
set.warnings.push(msg);
continue;
}
for cap in &prepared.capabilities {
if !set.capabilities.contains(cap) {
set.capabilities.push(cap.clone());
+64 -8
View File
@@ -2,7 +2,7 @@
use crate::Host;
use ide_core::event::NotifyLevel;
use ide_core::settings::{ExternalFormatter, LanguagesSettings, Settings};
use ide_core::settings::{BIOME_LANGUAGES, ExternalFormatter, LanguagesSettings, Settings};
use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, LanguageId, Pos, Range, TextEdit};
use ide_language::{LanguageConfig, PhpAlignment, Syntax};
use ide_lsp::types::FormatOptions;
@@ -10,9 +10,28 @@ use ide_tools::{Tools, formatter};
use std::path::Path;
const OXFMT_CONFIGS: [&str; 4] = [".oxfmtrc.json", ".oxfmtrc.jsonc", "oxfmt.config.ts", "oxfmt.config.mts"];
/// A Biome configuration, or Biome installed as a project dependency (it then uses its defaults).
const BIOME_MARKERS: [&str; 3] = ["biome.json", "biome.jsonc", "node_modules/@biomejs/biome/package.json"];
/// Reformat Code uses Biome below a Biome configuration or installation, unless the nearest
/// configuration turns its formatter off (Biome lints, another tool formats).
fn biome_formats(file: &Path) -> bool {
let config = ["biome.json", "biome.jsonc"]
.iter()
.filter_map(|name| formatter::find_up(file, Path::new(name)))
.max_by_key(|path| path.components().count());
match config {
Some(config) => !std::fs::read_to_string(&config)
.ok()
.and_then(|text| serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text)).ok())
.is_some_and(|v| v.pointer("/formatter/enabled") == Some(&serde_json::Value::Bool(false))),
None => BIOME_MARKERS.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some()),
}
}
fn supports_external_format(language: &LanguageConfig, tool: ExternalFormatter) -> bool {
match language.formatter.as_ref().map(|f| f.tool.as_str()) {
Some("prettier") if tool == ExternalFormatter::Biome => BIOME_LANGUAGES.contains(&language.id.as_str()),
Some("prettier") => matches!(tool, ExternalFormatter::Prettier | ExternalFormatter::Oxfmt),
Some("ruff") => tool == ExternalFormatter::Ruff,
_ => false,
@@ -20,9 +39,9 @@ fn supports_external_format(language: &LanguageConfig, tool: ExternalFormatter)
}
/// The external formatter of a file, for a language with an external formatter.
/// `forced` names the tool (Reformat with Prettier, oxfmt, or Ruff). Ruff is
/// the base formatter for Python; oxfmt can replace Prettier for its languages
/// when configured or selected. A tool that cannot format the language is
/// `forced` names the tool (Reformat with Prettier, oxfmt, Biome, or Ruff). Ruff is
/// the base formatter for Python; Biome, then oxfmt, can replace Prettier for their
/// languages when configured or selected. A tool that cannot format the language is
/// rejected even when explicitly requested.
fn external_tool(
forced: Option<ExternalFormatter>,
@@ -30,7 +49,7 @@ fn external_tool(
file: &Path,
settings: &LanguagesSettings,
) -> IdeResult<Option<ExternalFormatter>> {
use ExternalFormatter::{Oxfmt, Prettier, Ruff};
use ExternalFormatter::{Biome, Oxfmt, Prettier, Ruff};
let Some(language) = language.filter(|l| l.formatter.is_some()) else {
return match forced {
Some(tool) => Err(IdeError::invalid(format!(
@@ -56,8 +75,11 @@ fn external_tool(
if language.formatter.as_ref().is_some_and(|f| f.tool == "ruff") {
return Ok(enabled(Ruff).then_some(Ruff));
}
let oxfmt_config = || OXFMT_CONFIGS.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some());
Ok(if enabled(Oxfmt) && (settings.oxfmt.prefer || oxfmt_config()) {
let found = |names: &[&str]| names.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some());
let biome = enabled(Biome) && supports_external_format(language, Biome);
Ok(if biome && (settings.biome.prefer || biome_formats(file)) {
Some(Biome)
} else if enabled(Oxfmt) && (settings.oxfmt.prefer || found(&OXFMT_CONFIGS)) {
Some(Oxfmt)
} else {
enabled(Prettier).then_some(Prettier)
@@ -385,7 +407,7 @@ async fn provider_edits(
#[cfg(test)]
mod tests {
use super::*;
use ExternalFormatter::{Oxfmt, Prettier, Ruff};
use ExternalFormatter::{Biome, Oxfmt, Prettier, Ruff};
use ide_core::LanguageId;
use ide_language::LanguageRegistry;
@@ -428,6 +450,40 @@ mod tests {
assert_eq!(prettier.message, "Prettier cannot format Python files");
let oxfmt = tool(Some(Oxfmt), "python", file, &settings).unwrap_err();
assert_eq!(oxfmt.message, "oxfmt cannot format Python files");
let biome = tool(Some(Biome), "python", file, &settings).unwrap_err();
assert_eq!(biome.message, "Biome cannot format Python files");
}
#[test]
fn biome_config_or_dependency_selects_biome_for_its_languages() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::create_dir_all(root.join("web/src")).unwrap();
let (web, api, readme) = (root.join("web/src/app.ts"), root.join("api/main.ts"), root.join("web/README.md"));
let mut settings = LanguagesSettings::default();
for marker in BIOME_MARKERS {
let path = root.join("web").join(marker);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, "{}").unwrap();
assert_eq!(tool(None, "typescript", &web, &settings).unwrap(), Some(Biome), "{marker}");
assert_eq!(tool(None, "typescript", &api, &settings).unwrap(), Some(Prettier), "{marker}");
// Biome doesn't format Markdown: Prettier keeps it.
assert_eq!(tool(None, "markdown", &readme, &settings).unwrap(), Some(Prettier), "{marker}");
std::fs::remove_file(&path).unwrap();
}
std::fs::write(root.join("web/biome.json"), "{}").unwrap();
std::fs::write(root.join("web/.oxfmtrc.json"), "{}").unwrap();
assert_eq!(tool(None, "css", &web, &settings).unwrap(), Some(Biome));
settings.biome.languages.retain(|l| l != "css");
assert_eq!(tool(None, "css", &web, &settings).unwrap(), Some(Oxfmt));
// Biome only lints here: Prettier keeps formatting.
std::fs::remove_file(root.join("web/.oxfmtrc.json")).unwrap();
std::fs::write(root.join("web/biome.json"), r#"{ "formatter": { "enabled": false } }"#).unwrap();
assert_eq!(tool(None, "typescript", &web, &settings).unwrap(), Some(Prettier));
settings.biome.prefer = true;
assert_eq!(tool(None, "typescript", &api, &settings).unwrap(), Some(Biome));
let markdown = tool(Some(Biome), "markdown", &readme, &settings).unwrap_err();
assert_eq!(markdown.message, "Biome cannot format Markdown files");
}
#[test]
+164 -27
View File
@@ -8,8 +8,9 @@ use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe,
AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
CustomAgentInput, ExternalSession, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer,
McpServerInput, McpTransport, NewAgentTask, SkillsPolicy,
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, McpExternalSource, McpImportSelection,
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, RemoteSkillBrowseResult,
RemoteSkillPreview, SkillsPolicy,
};
use ide_command::command;
use ide_core::error::ErrorKind;
@@ -1040,15 +1041,20 @@ pub fn agent_set_skill_overrides(
host.project(window)?.agents.set_skill_overrides(&task, overrides)
}
/// Every skill discovered in the project and the user's folders, with the mode a session
/// of this project runs it with (without any session's own overrides).
/// Every skill discovered in the project, the user's folders and enabled plugins, with
/// the mode a session runs it with (without any session's own overrides).
#[command(trust = always)]
pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult<Vec<AgentSkillState>> {
let project = host.project(window)?;
let (policy, home) = (skills_policy(&project), dirs::home_dir());
let project = host.project(window).ok().filter(|p| !p.light);
let policy = host_skills_policy(host, project.as_deref());
let home = dirs::home_dir();
tokio::task::spawn_blocking(move || {
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_in(&policy.workspace_roots, home.as_deref()),
ide_agent::skills::discover_skills_with_plugins(
&policy.workspace_roots,
home.as_deref(),
&policy.plugin_dirs,
),
None,
&policy.workspace,
&policy.user,
@@ -1100,20 +1106,123 @@ pub fn agent_skills_set_mode(
}
}
}
match project {
Some(project) => {
let policy = skills_policy(&project);
let home = dirs::home_dir();
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_in(&policy.workspace_roots, home.as_deref()),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
}
None => Ok(Vec::new()),
let policy = host_skills_policy(host, project.as_deref());
let home = dirs::home_dir();
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_plugins(&policy.workspace_roots, home.as_deref(), &policy.plugin_dirs),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
}
/// Resolves a GitHub `owner/repo[/path][@ref]` source and lists the `SKILL.md` skills in it.
#[command(trust = always)]
pub async fn agent_skills_browse(
host: &Host,
source: String,
request: RequestId,
) -> IdeResult<RemoteSkillBrowseResult> {
let cancel = host.begin_request(request);
let search_path = ide_core::tool_path::search_path();
let res = tokio::task::spawn_blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::skill_installer::browse_skills(&fetcher, &source, &cancel)
})
.await
.map_err(join_err);
host.end_request(request);
res?
}
/// Fetches one skill's `SKILL.md`, file list, and static security scan warnings before installation.
#[command(trust = always)]
pub async fn agent_skills_preview(
host: &Host,
window: &str,
owner: String,
repo: String,
git_ref: String,
subpath: String,
request: RequestId,
) -> IdeResult<RemoteSkillPreview> {
let cancel = host.begin_request(request);
let ws_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
let home = dirs::home_dir();
let search_path = ide_core::tool_path::search_path();
let res = tokio::task::spawn_blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::skill_installer::preview_skill(
&fetcher,
ide_agent::skill_installer::RepoRef { owner: &owner, repo: &repo, git_ref: &git_ref },
&subpath,
home.as_deref(),
ws_root.as_deref(),
&cancel,
)
})
.await
.map_err(join_err);
host.end_request(request);
res?
}
/// Installs the selected skill subtree into `~/.agents/skills` (User) or `<workspace>/.agents/skills` (Workspace).
#[command(trust = always)]
pub async fn agent_skills_install(
host: &Host,
window: &str,
input: InstallRemoteSkillRequest,
request: RequestId,
) -> IdeResult<Vec<AgentSkillState>> {
let project = host.project(window).ok().filter(|p| !p.light);
if input.scope == McpScope::Workspace {
host.require_trust(window)?;
}
let ws_root = project.as_ref().map(|p| p.root.clone());
let home = dirs::home_dir();
let cancel = host.begin_request(request);
let search_path = ide_core::tool_path::search_path();
let install_home = home.clone();
let install_ws = ws_root.clone();
let res = tokio::task::spawn_blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::skill_installer::install_skill(
&fetcher,
&input,
install_home.as_deref(),
install_ws.as_deref(),
&cancel,
)
})
.await
.map_err(join_err);
host.end_request(request);
res??;
let event = IdeEvent::SettingsChanged { key: "agents.skills".into() };
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
let policy = host_skills_policy(host, project.as_deref());
tokio::task::spawn_blocking(move || {
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_plugins(
&policy.workspace_roots,
home.as_deref(),
&policy.plugin_dirs,
),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
.map_err(join_err)?
}
/// The user's and the workspace's skill policies (`[agents.skills.<name>]`).
@@ -1173,13 +1282,38 @@ pub(crate) fn workspace_skill_roots(root: &std::path::Path) -> Vec<std::path::Pa
roots
}
/// The skill policies a session of `project` resolves against.
fn skills_policy(project: &crate::Project) -> SkillsPolicy {
SkillsPolicy {
user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.skills.clone(),
workspace: project.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.skills.clone(),
workspace_trusted: project.trusted.load(std::sync::atomic::Ordering::Acquire),
workspace_roots: workspace_skill_roots(&project.root),
/// The skill policies a session of `project` (or global Settings without a project) resolves against.
fn host_skills_policy(host: &Host, project: Option<&crate::Project>) -> SkillsPolicy {
match project {
Some(project) => {
let workspace_trusted = project.trusted.load(std::sync::atomic::Ordering::Acquire);
let plugin_dirs = host
.plugin_host()
.map(|plugins| plugins.skill_dirs(Some(&project.root), workspace_trusted))
.unwrap_or_default();
SkillsPolicy {
user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.skills.clone(),
workspace: project
.settings
.layer(ide_workspace::settings::SettingsScope::Project)
.agents
.skills
.clone(),
workspace_trusted,
workspace_roots: workspace_skill_roots(&project.root),
plugin_dirs,
}
}
None => {
let plugin_dirs = host.plugin_host().map(|plugins| plugins.skill_dirs(None, true)).unwrap_or_default();
SkillsPolicy {
user: host.global_settings.effective().agents.skills.clone(),
workspace: Default::default(),
workspace_trusted: true,
workspace_roots: Vec::new(),
plugin_dirs,
}
}
}
}
@@ -1339,7 +1473,10 @@ ide_command::domain!(
agent_set_env,
agent_set_mcp_overrides,
agent_set_skill_overrides,
agent_skills_browse,
agent_skills_install,
agent_skills_list,
agent_skills_preview,
agent_skills_set_mode,
agent_stop_background,
agent_subscribe,
+7 -1
View File
@@ -906,6 +906,7 @@ pub async fn build_run(
let detected = project.detected_roots.read().clone();
let config_dir = host.config_dir.clone();
let token = host.begin_project_request(window, request);
let launch_project = project.clone();
let result = tokio::task::spawn_blocking(move || {
// Fast path (#2476): an unchanged single-project Maven build skips
// Maven entirely. Previous diagnostics stay: nothing changed, so they
@@ -1003,7 +1004,12 @@ pub async fn build_run(
};
let result = compile::run(&root, &plan, &token, &|e| {
let _ = on_event.send(e);
})?;
});
if kind == BuildKind::Rebuild {
// The clean removed outputs that earlier launch snapshots still hold.
launch_project.java_launch_snapshots.lock().forget_reusable_snapshots();
}
let result = result?;
if result.success && single && kind == BuildKind::Build {
let model = with_profiles(load(&root, &cache, &settings), &cache);
compile::record_menu_build(&cache, &root, &model, file.as_deref(), &token);
+99 -2
View File
@@ -2,7 +2,10 @@
use crate::Host;
use ide_command::command;
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, RequestId};
use ide_workspace::dependencies::{DependencyVersionSource, DependencyVersions, cargo, go, maven, npm};
use ide_workspace::dependencies::{
DependencyVersionSource, DependencyVersions, PythonRequirements, UnsatisfiedRequirement, cargo, go, maven, npm,
python,
};
use std::collections::BTreeMap;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::path::{Path, PathBuf};
@@ -254,6 +257,50 @@ pub async fn dependency_versions(
result
}
/// The requirements of a `requirements*.txt` / `pyproject.toml` the project's interpreter
/// doesn't satisfy; `None` for other files, or with no local interpreter to ask.
#[command(trust = trusted)]
pub async fn python_requirements(
host: &Host,
window: &str,
doc: DocId,
request: RequestId,
) -> IdeResult<Option<PythonRequirements>> {
let project = host.project(window)?;
let config_dir = host.config_dir.clone();
let cancel = host.begin_project_read_request(window, request);
let result = host
.blocking(move || {
let snap = project.documents.snapshot(doc)?;
let name = snap.path.file_name().and_then(|n| n.to_str()).unwrap_or_default();
if snap.large || snap.read_only {
return Ok(None);
}
let dependencies = python::requirements(name, &snap.text);
if dependencies.is_empty() {
return Ok(None);
}
// Running the interpreter runs project code (sitecustomize, .pth files).
project.require_trust()?;
let Some(python) = crate::ops::sdk::effective_python(&config_dir, &project, snap.path.parent()) else {
return Ok(None);
};
let requirements: Vec<&str> = dependencies.iter().map(|d| d.requirement.as_str()).collect();
let states = ide_sdk::python::unsatisfied_requirements(&python, &requirements, &cancel)?;
let unsatisfied = dependencies
.into_iter()
.zip(states)
.filter_map(|(dependency, state)| {
state.map(|s| UnsatisfiedRequirement { dependency, installed: s.installed })
})
.collect();
Ok(Some(PythonRequirements { python: python.into(), unsatisfied }))
})
.await;
host.end_request(request);
result
}
#[cfg(test)]
mod tests {
use super::*;
@@ -313,6 +360,56 @@ mod tests {
host.close_project("main");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn requirements_are_checked_against_the_project_virtualenv() {
let Some(base) = ide_core::tool_path::find_command(
"python3",
&ide_core::tool_path::search_path_in(&std::env::temp_dir()),
&std::env::temp_dir(),
) else {
return;
};
let temp = tempfile::tempdir().unwrap();
let base_dir = dunce::canonicalize(temp.path()).unwrap();
let root = base_dir.join("project");
std::fs::create_dir(&root).unwrap();
let status = std::process::Command::new(base)
.args(["-I", "-m", "venv", "--without-pip"])
.arg(root.join(".venv"))
.status()
.unwrap();
assert!(status.success());
let text = "# 中文\nopenidea-missing-xyz>=1\n-r other.txt\n";
let path = root.join("requirements.txt");
std::fs::write(&path, text).unwrap();
let host = Host::new(HostConfig {
config_dir: base_dir.join("config"),
data_dir: base_dir.join("data"),
local_data_dir: base_dir.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let project = host.open_project("main", &root).unwrap();
let info = project.documents.open(&path).unwrap();
// Restricted Mode never runs the interpreter.
assert!(python_requirements(&host, "main", info.id, RequestId(429)).await.is_err());
project.trusted.store(true, std::sync::atomic::Ordering::Release);
let found = python_requirements(&host, "main", info.id, RequestId(430)).await.unwrap().unwrap();
assert!(found.python.0.starts_with(root.join(".venv")));
assert_eq!(found.unsatisfied.len(), 1);
assert_eq!(found.unsatisfied[0].dependency.package, "openidea-missing-xyz");
assert_eq!(found.unsatisfied[0].installed, None);
let other = root.join("notes.txt");
std::fs::write(&other, text).unwrap();
let info = project.documents.open(&other).unwrap();
assert!(python_requirements(&host, "main", info.id, RequestId(431)).await.unwrap().is_none());
host.close_project("main");
}
struct CachedNpm;
impl DependencyVersionSource for CachedNpm {
fn id(&self) -> &'static str {
@@ -361,4 +458,4 @@ mod tests {
}
}
ide_command::domain!(dependencies: dependency_versions);
ide_command::domain!(dependencies: dependency_versions, python_requirements);
+64
View File
@@ -135,6 +135,16 @@ impl Session {
}
}
/// Build › Rebuild replaced the module outputs. The recorded snapshots were copied from
/// the outputs before the clean and may hold classes it removed (a class moved to another
/// package leaves its old file behind when jdtls wrote it), so none of them is reused:
/// the next launch copies the rebuilt outputs.
pub(crate) fn forget_reusable_snapshots(&mut self) {
if let Err(error) = forget_reusable_snapshots(&self.cache) {
tracing::warn!(%error, "Cannot invalidate Java launch snapshots");
}
}
pub(super) fn build(
&mut self,
root: &Path,
@@ -341,6 +351,32 @@ impl Drop for Session {
}
}
/// Clears the fingerprint of every launch record under `cache`, so no snapshot matches the
/// sources any more. The records stay: their modules keep delegating to Maven.
fn forget_reusable_snapshots(cache: &Path) -> std::io::Result<()> {
let records = cache.join("java-launch/records");
if !records.try_exists()? {
return Ok(());
}
let mut pending = vec![records];
while let Some(dir) = pending.pop() {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let kind = entry.file_type()?;
if kind.is_dir() {
pending.push(entry.path());
} else if kind.is_file() && entry.path().extension().is_some_and(|ext| ext == "json") {
let outputs: Option<Outputs> = serde_json::from_slice(&fs::read(entry.path())?).unwrap_or(None);
if let Some(mut outputs) = outputs.filter(|o| o.fingerprint.is_some()) {
outputs.fingerprint = None;
write_record(&entry.path(), &outputs).map_err(|e| std::io::Error::other(e.message))?;
}
}
}
}
Ok(())
}
fn referenced_snapshots(cache: &Path) -> std::io::Result<HashSet<PathBuf>> {
let mut referenced = HashSet::new();
let records = cache.join("java-launch/records");
@@ -610,6 +646,34 @@ mod tests {
);
}
#[test]
fn a_menu_rebuild_stops_reusing_snapshots_that_hold_removed_classes() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root);
let cancel = CancellationToken::new();
// A class jdtls wrote for a source since moved to another package; an incremental
// Maven build leaves it in target/classes.
fs::create_dir_all(root.join("target/classes")).unwrap();
fs::write(root.join("target/classes/Stale.class"), "stale").unwrap();
let mut session = Session::new(root.join("cache"));
let first = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert!(first.snapshot.join("0/Stale.class").is_file());
let reused = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_eq!(reused.snapshot, first.snapshot);
// Build › Rebuild cleans the outputs and compiles again.
fs::remove_file(root.join("target/classes/Stale.class")).unwrap();
session.forget_reusable_snapshots();
assert!(has_record(root, &root.join("cache"), root));
let next = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_ne!(next.snapshot, first.snapshot);
assert!(!next.snapshot.join("0/Stale.class").exists());
assert!(next.snapshot.join("0/Main.class").is_file());
let again = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_eq!(again.snapshot, next.snapshot);
}
#[test]
fn jdt_errors_reuse_an_unchanged_snapshot_and_rebuild_only_on_a_cache_miss() {
let dir = tempfile::tempdir().unwrap();
+127 -3
View File
@@ -3,10 +3,14 @@
use crate::Host;
use ide_command::command;
use ide_core::{IdeResult, RequestId, WorkspaceEdit};
use ide_core::{FileEdit, IdeResult, RequestId, WorkspaceEdit};
use ide_language::Syntax;
use ide_lsp::types::FileRenameEdits;
use ide_workspace::file_moves::moved_path;
use ide_workspace::roots::{ProjectRoots, RootKind};
use ide_workspace::{FileMove, UndoOutcome};
use std::path::PathBuf;
use parking_lot::Mutex;
use std::path::{Path, PathBuf};
use super::doc::blocking;
@@ -24,16 +28,110 @@ pub async fn refactor_file_move_edits(
) -> IdeResult<FileRenameEdits> {
let project = host.project(window)?;
let token = host.begin_request(request);
let result = project.lsp.will_rename_files(&pairs(&moves), token).await;
let result = project.lsp.will_rename_files(&pairs(&moves), token.clone()).await;
host.end_request(request);
let mut result = result?;
let syntax = host.syntax();
blocking(move || {
// basedpyright has no `workspace/willRenameFiles`; a Python server that answered wins.
if !result.edit.files.iter().any(|f| matches!(f, FileEdit::Edit { path, .. } if is_python(path))) {
let python = python_import_edits(&project, &syntax, &moves, &|| token.is_cancelled());
result.edit.files.extend(python.files);
}
project.documents.prepare_workspace_edit(&mut result.edit)?;
Ok(result)
})
.await
}
fn is_python(path: &Path) -> bool {
path.extension().is_some_and(|e| e == "py" || e == "pyi")
}
/// The dotted name of a Python module file or package folder, from its project's Python roots
/// (`src/a/b.py` → `a.b` in a `src` layout).
fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -> Option<String> {
let rel = path.strip_prefix(root).ok()?.to_string_lossy().replace('\\', "/");
let base = roots
.root_for(&rel)
.filter(|r| matches!(r.kind, RootKind::Source | RootKind::Test))
.map_or("", |r| r.path.as_str());
let inner = if base.is_empty() { rel.as_str() } else { rel.strip_prefix(base)?.trim_start_matches('/') };
let inner = if is_dir { inner } else { inner.strip_suffix(".py").or_else(|| inner.strip_suffix(".pyi"))? };
let inner = inner.strip_suffix("/__init__").unwrap_or(inner);
let valid = |s: &str| {
s.chars().next().is_some_and(|c| !c.is_ascii_digit()) && s.chars().all(|c| c == '_' || c.is_alphanumeric())
};
(!inner.is_empty() && inner.split('/').all(valid)).then(|| inner.replace('/', "."))
}
/// The package relative imports in `file` start from.
fn python_package(root: &Path, roots: &ProjectRoots, file: &Path) -> String {
let Some(module) = python_module(root, roots, file, false) else { return String::new() };
if file.file_stem().is_some_and(|s| s == "__init__") {
module
} else {
module.rsplit_once('.').map_or(String::new(), |(p, _)| p.to_owned())
}
}
/// Import updates in the project's Python files for `moves` (paths before the move).
fn python_import_edits(
project: &crate::project::Project,
syntax: &Syntax,
moves: &[FileMove],
cancelled: &(dyn Fn() -> bool + Sync),
) -> WorkspaceEdit {
let root = &project.root;
let roots = project.roots();
let renames: Vec<(String, String)> = moves
.iter()
.filter_map(|m| {
let is_dir = m.from.is_dir();
if !is_dir && (!is_python(&m.from) || m.from.file_stem().is_some_and(|s| s == "__init__")) {
return None;
}
let old = python_module(root, &roots, &m.from, is_dir)?;
let new = python_module(root, &roots, &m.to, is_dir)?;
(old != new).then_some((old, new))
})
.collect();
if renames.is_empty() {
return WorkspaceEdit::default();
}
let names: Vec<&str> = renames.iter().map(|(old, _)| old.rsplit('.').next().unwrap_or(old)).collect();
let found: Mutex<Vec<(PathBuf, Vec<ide_core::TextEdit>)>> = Mutex::new(Vec::new());
ide_vfs::walk_files(root, &project.exclude_globs(), |path| {
if cancelled() || !is_python(path) {
return;
}
let moved = moved_path(path, moves);
let text = match project.documents.text_of(path) {
Some(t) => t,
None => match std::fs::read_to_string(path) {
Ok(t) => t,
Err(_) => return,
},
};
if moved == path && !names.iter().any(|n| text.contains(n)) {
return;
}
let edits = syntax.python_import_edits(
&text,
&python_package(root, &roots, path),
&python_package(root, &roots, &moved),
&renames,
);
if !edits.is_empty() {
found.lock().push((path.to_path_buf(), edits));
}
});
let mut files = found.into_inner();
files.sort_by(|a, b| a.0.cmp(&b.0));
let files = files.into_iter().map(|(path, edits)| FileEdit::Edit { path: path.into(), edits, version: None });
WorkspaceEdit { files: files.collect(), ..Default::default() }
}
/// Applies `edit` (from [`refactor_file_move_edits`], possibly empty), moves the
/// files and notifies the servers. Returns the id for [`refactor_undo_file_move`].
#[command(trust = always)]
@@ -111,3 +209,29 @@ ide_command::domain!(
refactor_move_files,
refactor_undo_file_move,
);
#[cfg(test)]
mod tests {
use super::*;
use ide_workspace::roots::SourceFolder;
#[test]
fn python_module_names_follow_the_roots() {
let root = Path::new("/p");
let folder = |path: &str, kind| SourceFolder { path: path.into(), kind, detected_from: None };
let roots = ProjectRoots::compute(
vec![folder("src", RootKind::Source), folder("tests", RootKind::Test)],
&Default::default(),
);
let name = |p: &str, dir| python_module(root, &roots, &root.join(p), dir);
assert_eq!(name("src/tasks/models.py", false).as_deref(), Some("tasks.models"));
assert_eq!(name("src/tasks/__init__.py", false).as_deref(), Some("tasks"));
assert_eq!(name("src/tasks", true).as_deref(), Some("tasks"));
assert_eq!(name("tests/test_models.py", false).as_deref(), Some("test_models"));
assert_eq!(name("scripts/run.pyi", false).as_deref(), Some("scripts.run"));
assert_eq!(name("my-scripts/run.py", false), None);
assert_eq!(name("src/tasks/notes.txt", false), None);
assert_eq!(python_package(root, &roots, &root.join("src/tasks/cli.py")), "tasks");
assert_eq!(python_package(root, &roots, &root.join("src/tasks/__init__.py")), "tasks");
}
}
+31 -24
View File
@@ -120,6 +120,33 @@ pub async fn sdk_python_interpreter(host: &Host, window: &str, path: PathBuf) ->
.map_err(join_err)?
}
/// The interpreter of the workspace member `near` belongs to, else the project's.
pub(crate) fn effective_python(
config_dir: &std::path::Path,
project: &crate::Project,
near: Option<&std::path::Path>,
) -> Option<PathBuf> {
let project_root = &project.root;
let member = ide_workspace::workspace::Workspace::load(project_root).ok().flatten().and_then(|w| {
let near = near?;
w.projects.into_iter().filter(|root| near.starts_with(root)).max_by_key(|root| root.components().count())
});
let (root, settings) = match member {
Some(root) => {
let settings = ide_workspace::SettingsStore::load(config_dir, Some(&root)).effective();
(root, settings)
}
None => (project_root.clone(), project.settings.effective()),
};
// A member with no Python of its own falls back to the primary project's
// (the same chain run configurations use), so every answer names one interpreter.
ide_sdk::apply::python_interpreter_near(&root, near, &settings).or_else(|| {
(&root != project_root)
.then(|| ide_sdk::apply::python_interpreter(project_root, &project.settings.effective()))
.flatten()
})
}
/// The interpreter the project uses: the configured one, else its virtualenv.
#[command(trust = trusted)]
pub async fn sdk_python_effective(
@@ -129,31 +156,11 @@ pub async fn sdk_python_effective(
) -> IdeResult<Option<ide_core::IpcPath>> {
host.require_trust(window)?;
let project = host.project(window)?;
let (config_dir, project_root) = (host.config_dir.clone(), project.root.clone());
let config_dir = host.config_dir.clone();
// Loading a member's settings needs more stack than a sync command's main thread has left.
tokio::task::spawn_blocking(move || {
let member = ide_workspace::workspace::Workspace::load(&project_root).ok().flatten().and_then(|w| {
let near = near.as_deref()?;
w.projects.into_iter().filter(|root| near.starts_with(root)).max_by_key(|root| root.components().count())
});
let (root, settings) = match member {
Some(root) => {
let settings = ide_workspace::SettingsStore::load(&config_dir, Some(&root)).effective();
(root, settings)
}
None => (project_root.clone(), project.settings.effective()),
};
// A member with no Python of its own falls back to the primary project's
// (the same chain run configurations use), so every answer names one interpreter.
let interpreter = ide_sdk::apply::python_interpreter_near(&root, near.as_deref(), &settings).or_else(|| {
(root != project_root)
.then(|| ide_sdk::apply::python_interpreter(&project_root, &project.settings.effective()))
.flatten()
});
Ok(interpreter.map(Into::into))
})
.await
.map_err(join_err)?
tokio::task::spawn_blocking(move || Ok(effective_python(&config_dir, &project, near.as_deref()).map(Into::into)))
.await
.map_err(join_err)?
}
/// The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`.
+19 -1
View File
@@ -53,6 +53,7 @@ mod run_detectors;
pub mod run_targets;
pub mod search;
mod semantic_tokens;
mod skills;
mod snippets;
mod theme;
mod types;
@@ -385,6 +386,8 @@ pub struct PluginHost {
run_detectors: Arc<run_detectors::RunDetectors>,
/// `[[contributes.javaAgents]]` of enabled plugins.
java_agents: Arc<java_agents::JavaAgents>,
/// `[[contributes.skills]]` of enabled plugins.
skills: Arc<skills::PluginSkills>,
/// `[[contributes.providers]]` of enabled plugins.
providers: Arc<providers::Providers>,
navigation: Mutex<navigation::NavigationIndex>,
@@ -411,6 +414,8 @@ pub struct PluginHost {
announced_theme: Mutex<Option<ActiveTheme>>,
/// [`PluginLanguages::revision`] last announced with `LanguagesChanged`.
announced_languages: AtomicU64,
/// [`skills::PluginSkills::revision`] last announced to open projects.
announced_skills: AtomicU64,
/// `PATH` used to resolve `process:` programs at grant time.
path_var: RwLock<PathVar>,
/// (plugin id, `process:` capability) → the approved program; read by the
@@ -470,7 +475,8 @@ impl PluginHost {
let run_detectors: Arc<run_detectors::RunDetectors> = Arc::default();
let providers: Arc<providers::Providers> = Arc::default();
let java_agents: Arc<java_agents::JavaAgents> = Arc::default();
register_builtin_points(&registry, &ui, &languages, &run_detectors, &java_agents, &providers)
let skills: Arc<skills::PluginSkills> = Arc::default();
register_builtin_points(&registry, &ui, &languages, &run_detectors, &java_agents, &providers, &skills)
.map_err(IdeError::internal)?;
let pins: Arc<RwLock<HashMap<(String, String), ProgramPin>>> = Arc::default();
let policy_pins = pins.clone();
@@ -506,6 +512,7 @@ impl PluginHost {
languages,
run_detectors,
java_agents,
skills,
providers,
navigation: Mutex::default(),
endpoints: Mutex::default(),
@@ -521,6 +528,7 @@ impl PluginHost {
startup_finished: AtomicBool::new(false),
announced_theme: Mutex::new(None),
announced_languages: AtomicU64::new(0),
announced_skills: AtomicU64::new(0),
path_var: RwLock::new(Arc::new(|| std::env::var_os("PATH"))),
pins,
};
@@ -2915,6 +2923,16 @@ impl PluginHost {
if self.announced_languages.swap(languages, Ordering::AcqRel) != languages {
self.emit(None, PluginEvent::LanguagesChanged);
}
let skills = self.skills.revision();
if self.announced_skills.swap(skills, Ordering::AcqRel) != skills
&& let Some(workspace) = self.shared.workspace.read().clone()
&& let Some(host) = workspace.database_host()
{
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
p.sink.emit(ide_core::IdeEvent::SettingsChanged { key: "agents.skills".into() });
}
}
let active = self.active_theme();
let mut announced = self.announced_theme.lock();
if *announced != active {
+2
View File
@@ -66,6 +66,7 @@ pub fn register_builtin_points(
run_detectors: &Arc<super::run_detectors::RunDetectors>,
java_agents: &Arc<super::java_agents::JavaAgents>,
providers: &Arc<super::providers::Providers>,
skills: &Arc<super::skills::PluginSkills>,
) -> Result<(), String> {
registry.register(Arc::new(UiPoint::new(COMMANDS, ui.clone(), command)))?;
registry.register(Arc::new(super::theme::ThemesPoint::new(ui.clone())))?;
@@ -73,6 +74,7 @@ pub fn register_builtin_points(
registry.register(Arc::new(UiPoint::new(super::icons::POINT_ID, ui.clone(), super::icons::icon_theme)))?;
registry.register(Arc::new(super::run_detectors::RunDetectorsPoint::new(run_detectors.clone())))?;
registry.register(Arc::new(super::java_agents::JavaAgentsPoint::new(java_agents.clone())))?;
registry.register(Arc::new(super::skills::SkillsPoint::new(skills.clone())))?;
registry.register(Arc::new(super::navigation::IndexersPoint))?;
registry.register(Arc::new(super::providers::ProvidersPoint::new(providers.clone())))?;
registry.register(Arc::new(UiPoint::new(super::providers::SECRETS_POINT, ui.clone(), super::providers::secret)))?;
+250
View File
@@ -0,0 +1,250 @@
//! The `skills` extension point (API 1.15): declarative `SKILL.md` folders inside a
//! plugin package (`[[contributes.skills]]`), discovered directly from live plugins'
//! package directories and staged into agent sessions through [`ide_agent::skills`].
//!
//! ```toml
//! [[contributes.skills]]
//! path = "skills/release-notes/SKILL.md"
//! ```
//!
//! Invalid entries emit a plugin load warning (`Prepared::skipped`) rather than failing
//! the whole plugin; `engines.openidea` compatibility (`^1.15`) remains a manifest check.
use super::PluginHost;
use ide_extension::{Disposable, ExtensionPoint, Package, Placement, Prepared, decode};
use parking_lot::RwLock;
use serde::Deserialize;
use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
pub const POINT_ID: &str = "skills";
/// Maximum total size of all files inside one contributed skill folder (2 MiB).
pub const MAX_SKILL_DIR_BYTES: u64 = 2 << 20;
const MAX_SKILL_FILES: usize = 256;
const MAX_SKILL_DEPTH: usize = 16;
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct Decl {
path: PathBuf,
}
#[derive(Clone, Debug)]
struct ContributedSkill {
plugin_id: String,
name: String,
/// Package-relative directory holding `SKILL.md` (e.g. `skills/release-notes`).
rel_dir: PathBuf,
}
/// Contributed skills of loaded plugins.
#[derive(Default)]
pub struct PluginSkills {
items: RwLock<Vec<(u64, ContributedSkill)>>,
seq: AtomicU64,
revision: AtomicU64,
}
impl PluginSkills {
pub fn revision(&self) -> u64 {
self.revision.load(Ordering::Acquire)
}
fn add(self: &Arc<Self>, item: ContributedSkill) -> Disposable {
let seq = self.seq.fetch_add(1, Ordering::Relaxed);
self.items.write().push((seq, item));
self.revision.fetch_add(1, Ordering::AcqRel);
let weak = Arc::downgrade(self);
Disposable::new(move || {
if let Some(this) = weak.upgrade() {
this.items.write().retain(|(s, _)| *s != seq);
this.revision.fetch_add(1, Ordering::AcqRel);
}
})
}
}
pub struct SkillsPoint {
store: Arc<PluginSkills>,
}
impl SkillsPoint {
pub fn new(store: Arc<PluginSkills>) -> Self {
Self { store }
}
}
impl ExtensionPoint for SkillsPoint {
fn id(&self) -> &'static str {
POINT_ID
}
fn placement(&self) -> Placement {
Placement::Workspace
}
fn prepare(&self, pkg: &Package, decl: toml::Value) -> Result<Prepared, String> {
pkg.manifest.needs_api("contributes.skills", 15)?;
match self.prepare_entry(pkg, decl) {
Ok(prepared) => Ok(prepared),
Err(warning) => Ok(Prepared::skipped(warning)),
}
}
}
impl SkillsPoint {
fn prepare_entry(&self, pkg: &Package, decl: toml::Value) -> Result<Prepared, String> {
let d: Decl = decode(POINT_ID, decl)?;
if d.path.as_os_str().is_empty() || !d.path.components().all(|c| matches!(c, Component::Normal(_))) {
return Err(format!("{}: `path` must be a relative path inside the plugin", d.path.display()));
}
if d.path.file_name().and_then(|n| n.to_str()) != Some("SKILL.md") {
return Err(format!("{}: must point to `<dir>/SKILL.md`", d.path.display()));
}
let Some(rel_dir) = d.path.parent().filter(|p| !p.as_os_str().is_empty()) else {
return Err(format!("{}: must live inside a `<name>/SKILL.md` folder", d.path.display()));
};
let Some(folder) = rel_dir.file_name().and_then(|n| n.to_str()) else {
return Err(format!("{}: invalid skill folder name", d.path.display()));
};
// Reject duplicate skill folder names across distinct paths in the same plugin.
for other in pkg.manifest.declarations(POINT_ID) {
let Some(other_path) = other.get("path").and_then(|v| v.as_str()).map(Path::new) else { continue };
if other_path == d.path {
break;
}
if other_path.file_name().and_then(|n| n.to_str()) == Some("SKILL.md")
&& other_path.parent().and_then(|p| p.file_name()).and_then(|n| n.to_str()) == Some(folder)
{
return Err(format!("duplicate skill `{folder}` in plugin"));
}
}
let pkg_root = pkg.dir.canonicalize().map_err(|e| format!("plugin directory: {e}"))?;
let abs_dir = pkg.resolve(rel_dir)?;
if !abs_dir.is_dir() {
return Err(format!("{}: not a directory", rel_dir.display()));
}
let _ = pkg.resolve(&d.path)?;
let mut files = Vec::new();
let mut total_bytes = 0u64;
let mut visited_dirs = HashSet::new();
visited_dirs.insert(abs_dir.clone());
collect_skill_files(
&pkg_root,
&pkg.dir.join(rel_dir),
rel_dir,
0,
&mut visited_dirs,
&mut files,
&mut total_bytes,
folder,
)?;
files.sort();
let text = pkg.read_text(&d.path)?;
ide_agent::skills::validate_plugin_skill(&abs_dir, folder, &text)
.map_err(|e| format!("{}: {e}", d.path.display()))?;
let label = format!("/{folder}");
let key = folder.to_owned();
let item = ContributedSkill {
plugin_id: pkg.id().to_owned(),
name: folder.to_owned(),
rel_dir: rel_dir.to_path_buf(),
};
let store = self.store.clone();
let mut prepared = Prepared::new(label, move || Ok(store.add(item))).key(key);
prepared.files = files;
Ok(prepared)
}
}
#[allow(clippy::too_many_arguments)]
fn collect_skill_files(
pkg_root: &Path,
abs_dir: &Path,
rel_dir: &Path,
depth: usize,
visited_dirs: &mut HashSet<PathBuf>,
files: &mut Vec<PathBuf>,
total_bytes: &mut u64,
skill_name: &str,
) -> Result<(), String> {
if depth > MAX_SKILL_DEPTH {
return Err(format!("{}: directory nesting exceeds {MAX_SKILL_DEPTH} levels", rel_dir.display()));
}
let entries = std::fs::read_dir(abs_dir).map_err(|e| format!("{}: {e}", rel_dir.display()))?;
for entry in entries {
let entry = entry.map_err(|e| format!("{}: {e}", rel_dir.display()))?;
let name = entry.file_name();
let entry_abs = entry.path();
let entry_rel = rel_dir.join(&name);
let sym_meta = std::fs::symlink_metadata(&entry_abs).map_err(|e| format!("{}: {e}", entry_rel.display()))?;
let canon = entry_abs
.canonicalize()
.map_err(|_| format!("{}: broken symlink or unreadable entry", entry_rel.display()))?;
if !canon.starts_with(pkg_root) {
return Err(format!("{}: points outside the plugin", entry_rel.display()));
}
let meta = if sym_meta.file_type().is_symlink() {
std::fs::metadata(&entry_abs).map_err(|e| format!("{}: {e}", entry_rel.display()))?
} else {
sym_meta
};
if meta.is_dir() {
if !visited_dirs.insert(canon.clone()) {
return Err(format!("{}: cyclic directory link", entry_rel.display()));
}
collect_skill_files(
pkg_root,
&entry_abs,
&entry_rel,
depth + 1,
visited_dirs,
files,
total_bytes,
skill_name,
)?;
visited_dirs.remove(&canon);
} else if meta.is_file() {
if files.len() >= MAX_SKILL_FILES {
return Err(format!("skill `{skill_name}` exceeds {MAX_SKILL_FILES} files"));
}
*total_bytes = total_bytes.saturating_add(meta.len());
if *total_bytes > MAX_SKILL_DIR_BYTES {
return Err(format!("skill `{skill_name}` exceeds {} MiB", MAX_SKILL_DIR_BYTES >> 20));
}
files.push(entry_rel);
} else {
return Err(format!("{}: unsupported file type in skill folder", entry_rel.display()));
}
}
Ok(())
}
impl PluginHost {
/// Skill directories (`<plugin_dir>/<rel_dir>`) contributed by live plugins for `root`.
/// Project-local `.openidea/plugins/` packages only apply to their own trusted project.
pub fn skill_dirs(&self, root: Option<&Path>, workspace_trusted: bool) -> Vec<PathBuf> {
let mut entries: Vec<(String, String, PathBuf)> = Vec::new();
for (_, item) in self.skills.items.read().iter() {
let Ok(plugin) = self.get(&item.plugin_id) else { continue };
if !plugin.status().is_live() {
continue;
}
if let Some(dev_root) = plugin.dev_root.as_deref()
&& (!workspace_trusted || root != Some(dev_root))
{
continue;
}
entries.push((item.plugin_id.clone(), item.name.clone(), plugin.dir().join(&item.rel_dir)));
}
entries.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
entries.into_iter().map(|(_, _, path)| path).collect()
}
}
+12 -1
View File
@@ -286,6 +286,10 @@ impl Host {
lombok.jar(),
);
ide_sdk::apply::configure_gradle_runtime(cfg, root, server_root, &effective);
let gradle_dirs: Vec<_> = std::iter::once(data_dir.join("gradle"))
.chain(dirs::cache_dir().map(|dir| dir.join("openidea").join("gradle")))
.collect();
ide_sdk::apply::configure_gradle_classpath(cfg, &gradle_dirs);
ide_sdk::apply::configure_maven_sources(cfg, &effective);
ide_sdk::jdtls::launch_directly(cfg);
}
@@ -765,13 +769,20 @@ impl Host {
let skill_settings = settings.clone();
let skill_root = root.clone();
let trust = self.trust.clone();
let plugin_host = self.plugin_host.read().clone();
agents.set_skills_policy_hook(Box::new(move || {
let layer = |scope| skill_settings.layer(scope).agents.skills.clone();
let workspace_trusted = trust.window_trusted(&skill_root).unwrap_or(false);
let plugin_dirs = plugin_host
.upgrade()
.map(|plugins| plugins.skill_dirs(Some(&skill_root), workspace_trusted))
.unwrap_or_default();
ide_agent::SkillsPolicy {
user: layer(ide_workspace::settings::SettingsScope::Global),
workspace: layer(ide_workspace::settings::SettingsScope::Project),
workspace_trusted: trust.window_trusted(&skill_root).unwrap_or(false),
workspace_trusted,
workspace_roots: crate::ops::agent::workspace_skill_roots(&skill_root),
plugin_dirs,
}
}));
agents.set_mcp_servers_hook(Box::new(move || {
+2 -2
View File
@@ -742,8 +742,8 @@ const PYTHON: Checks = Checks {
typed("src/tasks/models.py", "from enum import IntEnum", "import abc"),
Imports::Before("import os"),
)),
// basedpyright has no `workspace/willRenameFiles`.
file_move: None,
// basedpyright has no `workspace/willRenameFiles`: the IDE rewrites the imports.
file_move: Some(("src/tasks/models.py", "src/tasks/domain.py", "src/tasks/cli.py", "from .domain import")),
};
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+109
View File
@@ -7313,3 +7313,112 @@ fn a_freshly_installed_plugin_gets_the_post_install_settings_event() {
"freshly installed plugin got no post-install event: {received}"
);
}
#[test]
fn contributes_skills_installs_discovers_and_tracks_plugin_lifecycle() {
let f = fixture(Limits::default());
let info = f.install(&sample("agent-skills"));
assert_eq!(info.status, PluginStatus::Static);
assert!(info.warnings.is_empty(), "{:?}", info.warnings);
assert!(info.contributions.iter().any(|c| c.point == "skills" && c.label == "/release-notes"));
let dirs = f.host.skill_dirs(Some(&f.project), true);
assert_eq!(dirs.len(), 1);
assert!(dirs[0].join("SKILL.md").is_file(), "SKILL.md copied to install dir");
assert!(
dirs[0].join("references/template.md").is_file(),
"bundled supporting files in the skill folder copied to install dir"
);
let discovered = ide_agent::skills::discover_skills_with_plugins(std::slice::from_ref(&f.project), None, &dirs);
assert_eq!(discovered.len(), 1);
assert_eq!(discovered[0].name, "release-notes");
assert_eq!(discovered[0].source, ide_agent::AgentSkillSource::Plugin);
assert_eq!(discovered[0].hint.as_deref(), Some("[tag]"));
// Workspace skill with the same name wins; the plugin skill is never silently renamed.
let ws_skill = f.project.join(".agents/skills/release-notes");
std::fs::create_dir_all(&ws_skill).unwrap();
std::fs::write(ws_skill.join("SKILL.md"), "---\nname: release-notes\ndescription: workspace override\n---\n")
.unwrap();
let clashed = ide_agent::skills::discover_skills_with_plugins(std::slice::from_ref(&f.project), None, &dirs);
assert_eq!(clashed.len(), 1);
assert_eq!(clashed[0].source, ide_agent::AgentSkillSource::Workspace);
assert_eq!(clashed[0].description, "workspace override");
// Disabling or uninstalling removes the plugin's skill directories immediately.
f.host.set_enabled("test.agent-skills", false).unwrap();
assert!(f.host.skill_dirs(Some(&f.project), true).is_empty());
f.host.set_enabled("test.agent-skills", true).unwrap();
assert_eq!(f.host.skill_dirs(Some(&f.project), true).len(), 1);
f.host.uninstall("test.agent-skills").unwrap();
assert!(f.host.skill_dirs(Some(&f.project), true).is_empty());
}
#[test]
fn contributes_skills_needs_api_1_15_and_warns_without_failing_plugin_on_bad_entries() {
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
// Older `engines.openidea` is refused at the manifest check.
let old_api = tmp.path().join("old-api");
copy_dir(&sample("agent-skills"), &old_api);
let manifest = std::fs::read_to_string(old_api.join("plugin.toml")).unwrap();
std::fs::write(old_api.join("plugin.toml"), manifest.replace("\"^1.15\"", "\"^1.14\"")).unwrap();
let err = f.host.install_from_dir(&old_api, &Consent::all()).unwrap_err();
assert!(err.message.contains("new in plugin API 1.15"), "{err:?}");
// Invalid skill entries emit load warnings while valid skills and the plugin itself still load.
let pkg = tmp.path().join("mixed-skills");
std::fs::create_dir_all(pkg.join("skills/good-skill")).unwrap();
std::fs::write(pkg.join("skills/good-skill/SKILL.md"), "---\nname: good-skill\ndescription: valid skill\n---\n")
.unwrap();
std::fs::create_dir_all(pkg.join("skills/wrong-name")).unwrap();
std::fs::write(
pkg.join("skills/wrong-name/SKILL.md"),
"---\nname: mismatched\ndescription: bad frontmatter name\n---\n",
)
.unwrap();
std::fs::create_dir_all(pkg.join("skills/not-skill-md")).unwrap();
std::fs::write(pkg.join("skills/not-skill-md/README.md"), "nope\n").unwrap();
std::fs::create_dir_all(pkg.join("skills/oversize")).unwrap();
std::fs::write(pkg.join("skills/oversize/SKILL.md"), "---\nname: oversize\ndescription: too big\n---\n").unwrap();
std::fs::write(pkg.join("skills/oversize/blob.bin"), vec![b'x'; (2 << 20) + 16]).unwrap();
#[allow(unused_mut)]
let mut manifest = String::from(
"id = \"acme.mixed-skills\"\n\
name = \"Mixed Skills\"\n\
version = \"1.0.0\"\n\
engines.openidea = \"^1.15\"\n\n\
[[contributes.skills]]\npath = \"skills/good-skill/SKILL.md\"\n\
[[contributes.skills]]\npath = \"../outside/SKILL.md\"\n\
[[contributes.skills]]\npath = \"skills/not-skill-md/README.md\"\n\
[[contributes.skills]]\npath = \"skills/wrong-name/SKILL.md\"\n\
[[contributes.skills]]\npath = \"skills/oversize/SKILL.md\"\n",
);
#[cfg(unix)]
{
let outside = tmp.path().join("outside.txt");
std::fs::write(&outside, "secret\n").unwrap();
std::fs::create_dir_all(pkg.join("skills/escape-link")).unwrap();
std::fs::write(
pkg.join("skills/escape-link/SKILL.md"),
"---\nname: escape-link\ndescription: has escaping symlink\n---\n",
)
.unwrap();
std::os::unix::fs::symlink(&outside, pkg.join("skills/escape-link/leak.txt")).unwrap();
manifest.push_str("[[contributes.skills]]\npath = \"skills/escape-link/SKILL.md\"\n");
}
std::fs::write(pkg.join("plugin.toml"), manifest).unwrap();
let info = f.install(&pkg);
assert_eq!(info.status, PluginStatus::Static, "bad skill entries must not fail the plugin");
let expected_warnings = if cfg!(unix) { 5 } else { 4 };
assert_eq!(info.warnings.len(), expected_warnings, "{:?}", info.warnings);
assert!(info.warnings.iter().all(|w| w.starts_with("contributes.skills[")), "{:?}", info.warnings);
let dirs = f.host.skill_dirs(Some(&f.project), true);
assert_eq!(dirs.len(), 1);
assert!(dirs[0].ends_with("skills/good-skill"), "{dirs:?}");
}
+2 -1
View File
@@ -156,7 +156,8 @@ pub struct LanguageServerConfig {
pub requires_env: Vec<String>,
/// Files whose presence marks a workspace root, e.g. `Cargo.toml`;
/// `file#table` requires the TOML file to contain that dotted table, e.g.
/// `pyproject.toml#tool.ruff`.
/// `pyproject.toml#tool.ruff`, or the JSON file that dotted key, e.g.
/// `package.json#devDependencies.tailwindcss`.
#[serde(default)]
pub root_markers: Vec<String>,
/// Serve only files below a root marker, not the whole project: a framework's
+21 -5
View File
@@ -58,11 +58,12 @@ pub fn arduino_sketch_root(project: &Path, path: &Path) -> Option<PathBuf> {
/// `dir` contains `marker`: a relative path, a file name pattern with one
/// `*` (`*.csproj`), or a TOML or JSON file name (no pattern) and a dotted table
/// it must contain (`pyproject.toml#tool.ruff`, `package.json#eslintConfig`).
/// or JSON key it must contain (`pyproject.toml#tool.ruff`, `package.json#eslintConfig`,
/// `package.json#devDependencies.tailwindcss`).
fn has_marker(dir: &Path, marker: &str) -> bool {
if let Some((file, table)) = marker.split_once('#') {
return if file.ends_with(".json") {
has_json_object(&dir.join(file), table)
has_json_key(&dir.join(file), table)
} else {
has_toml_table(&dir.join(file), table)
};
@@ -88,11 +89,12 @@ fn has_toml_table(file: &Path, table: &str) -> bool {
table.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(toml::Value::is_table)
}
/// `file` parses as JSON and has the dotted object `key` (`eslintConfig`).
fn has_json_object(file: &Path, key: &str) -> bool {
/// `file` parses as JSON and has the dotted `key` with a value other than `null`:
/// an object (`eslintConfig`) or a dependency's version (`dependencies.tailwindcss`).
fn has_json_key(file: &Path, key: &str) -> bool {
let Ok(text) = std::fs::read_to_string(file) else { return false };
let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else { return false };
key.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(serde_json::Value::is_object)
key.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(|v| !v.is_null())
}
/// `path` is (or, after its creation or removal, was) a root marker of the
@@ -177,6 +179,20 @@ mod tests {
assert!(!is_marker_path(&root.join("svc/setup.cfg"), "pyproject.toml#tool.ruff"));
}
#[test]
fn json_markers_need_their_key() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
let marker = "package.json#devDependencies.tailwindcss";
std::fs::write(dir.join("package.json"), r#"{"devDependencies": {"vite": "^7.0.0"}}"#).unwrap();
assert!(!has_marker(dir, marker));
std::fs::write(dir.join("package.json"), r#"{"devDependencies": {"tailwindcss": "^4.1.0"}}"#).unwrap();
assert!(has_marker(dir, marker) && !has_marker(dir, "package.json#dependencies.tailwindcss"));
std::fs::write(dir.join("package.json"), r#"{"eslintConfig": null}"#).unwrap();
assert!(!has_marker(dir, "package.json#eslintConfig"));
assert!(is_marker_path(&dir.join("package.json"), marker));
}
#[test]
fn patterns_match_file_names() {
let tmp = tempfile::tempdir().unwrap();
+68 -2
View File
@@ -715,9 +715,20 @@ mod tests {
// it); before the HTML server (hover, rename and symbols take the first).
assert_eq!(
names("typescript"),
["vtsls", "typescript-language-server", "angular-language-server", "oxlint", "eslint"]
[
"vtsls",
"typescript-language-server",
"angular-language-server",
"oxlint",
"eslint",
"biome",
"tailwindcss-language-server"
]
);
assert_eq!(
names("html"),
["angular-language-server", "vscode-html-language-server", "tailwindcss-language-server"]
);
assert_eq!(names("html"), ["angular-language-server", "vscode-html-language-server"]);
for lang in ["typescript", "html"] {
let cfg = reg.get(&LanguageId::new(lang)).unwrap();
let angular = cfg.language_servers.iter().find(|s| s.name == "angular-language-server").unwrap();
@@ -744,6 +755,34 @@ mod tests {
}
}
#[test]
fn biome_lints_files_below_its_config_or_installation() {
let reg = reg();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
for dir in ["apps/web/src", "apps/admin/node_modules/@biomejs/biome", "apps/api"] {
std::fs::create_dir_all(root.join(dir)).unwrap();
}
std::fs::write(root.join("apps/web/biome.jsonc"), "{}").unwrap();
for lang in
["javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc", "css", "graphql"]
{
let cfg = reg.get(&LanguageId::new(lang)).unwrap();
let biome = cfg.language_servers.iter().find(|s| s.name == "biome").unwrap();
assert_eq!(
(biome.command.as_str(), biome.args.as_slice()),
("biome", ["lsp-proxy".to_string()].as_slice())
);
assert!(biome.require_root_marker && !biome.fallback, "{lang}");
// Reformat Code runs `biome format`: the server's formatting would race the language's own.
assert_eq!(biome.features, ["code-action", "diagnostics"], "{lang}");
let served = |file: &str| crate::marked_root(Some(root), &root.join(file), &biome.root_markers);
assert_eq!(served("apps/web/src/main.ts"), Some(root.join("apps/web")), "{lang}");
assert_eq!(served("apps/admin/main.ts"), Some(root.join("apps/admin")), "{lang}");
assert_eq!(served("apps/api/main.ts"), None, "{lang}");
}
}
#[test]
fn eslint_serves_js_files_only_below_its_config() {
let reg = reg();
@@ -771,6 +810,33 @@ mod tests {
}
}
#[test]
fn tailwind_serves_web_files_only_in_tailwind_projects() {
let reg = reg();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
for dir in ["v3/src", "v4/src", "plain/src"] {
std::fs::create_dir_all(root.join(dir)).unwrap();
}
std::fs::write(root.join("v3/tailwind.config.js"), "module.exports = {};").unwrap();
std::fs::write(root.join("v4/package.json"), r#"{"devDependencies": {"tailwindcss": "^4.1.0"}}"#).unwrap();
std::fs::write(root.join("plain/package.json"), r#"{"devDependencies": {"vite": "^7.0.0"}}"#).unwrap();
for lang in
["html", "css", "javascript", "javascriptreact", "typescript", "typescriptreact", "vue", "svelte", "astro"]
{
let cfg = reg.get(&LanguageId::new(lang)).unwrap();
// Last: the language's own servers answer hover first.
let tailwind = cfg.language_servers.last().unwrap();
assert_eq!(tailwind.name, "tailwindcss-language-server", "{lang}");
assert_eq!(tailwind.args, ["--stdio"], "{lang}");
assert!(tailwind.require_root_marker && !tailwind.fallback, "{lang}");
let served = |file: &str| crate::marked_root(Some(root), &root.join(file), &tailwind.root_markers);
assert_eq!(served("v3/src/app.css"), Some(root.join("v3")), "{lang}");
assert_eq!(served("v4/src/app.css"), Some(root.join("v4")), "{lang}");
assert_eq!(served("plain/src/app.css"), None, "{lang}: package.json without tailwindcss");
}
}
#[test]
fn laravel_lsp_serves_php_files_only_below_artisan() {
let reg = reg();
+1
View File
@@ -12,6 +12,7 @@ mod literals;
mod outline;
mod php_align;
mod python_facts;
mod python_imports;
mod rst;
mod selection;
mod sfc;
@@ -0,0 +1,404 @@
//! Import updates for moved Python modules and packages, which basedpyright leaves to the
//! client (no `workspace/willRenameFiles`). Works on dotted module names; the caller maps
//! files to them from the project's roots.
use super::lines::LineIndex;
use crate::{LanguageId, Syntax};
use ide_core::TextEdit;
use tree_sitter::{Node, Tree};
impl Syntax {
/// Edits that keep the imports of a Python `text` resolving after `moves` (old → new
/// dotted names; a package covers its submodules). `package` is the package relative
/// imports start from (`a.b` for `a/b/c.py` and `a/b/__init__.py`), `new_package` the
/// same after the move.
pub fn python_import_edits(
&self,
text: &str,
package: &str,
new_package: &str,
moves: &[(String, String)],
) -> Vec<TextEdit> {
self.analyze(&LanguageId::new("python"), text, |_, tree, text| {
Some(Rewrite { text, idx: LineIndex::new(text), package, new_package, moves, edits: Vec::new() }.run(tree))
})
.unwrap_or_default()
}
}
struct Rewrite<'a> {
text: &'a str,
idx: LineIndex<'a>,
package: &'a str,
new_package: &'a str,
moves: &'a [(String, String)],
edits: Vec<TextEdit>,
}
impl Rewrite<'_> {
fn run(mut self, tree: &Tree) -> Vec<TextEdit> {
let mut imports = Vec::new();
let mut chains = Vec::new();
collect(tree.root_node(), &mut |n| match n.kind() {
"import_statement" | "import_from_statement" => imports.push(n),
"attribute" if !inside_import(n) => chains.push(n),
_ => {}
});
let mut renamed: Vec<(String, String)> = Vec::new();
for node in imports {
if node.kind() == "import_statement" {
self.import(node, &mut renamed);
} else {
self.import_from(node);
}
}
// `import a.b` is used as `a.b.x`: those chains follow the import.
for node in chains {
let t = self.src(node);
if let Some((_, new)) = renamed.iter().find(|(old, _)| *old == t) {
self.edit(node, new.clone());
}
}
self.edits.sort_by_key(|e| (e.range.start.line, e.range.start.col));
self.edits
}
fn src(&self, n: Node) -> &str {
self.text.get(n.byte_range()).unwrap_or_default()
}
fn edit(&mut self, n: Node, new_text: String) {
self.edits.push(TextEdit { range: self.idx.range(n.start_byte(), n.end_byte()), new_text });
}
/// `import a.b`, `import a.b as c`.
fn import(&mut self, node: Node, renamed: &mut Vec<(String, String)>) {
let mut cursor = node.walk();
for item in node.children_by_field_name("name", &mut cursor) {
let (name, aliased) = match item.kind() {
"aliased_import" => match item.child_by_field_name("name") {
Some(n) => (n, true),
None => continue,
},
_ => (item, false),
};
let old = self.src(name).to_owned();
let Some(new) = map_module(&old, self.moves) else { continue };
if aliased {
self.edit(name, new);
} else if old.contains('.') {
renamed.push((old, new.clone()));
self.edit(name, new);
} else {
// The bound name stays, so the rest of the file needs no change.
self.edit(name, format!("{new} as {old}"));
}
}
}
/// `from m import x`, `from .m import x as y`, `from . import m`.
fn import_from(&mut self, node: Node) {
let Some(module) = node.child_by_field_name("module_name") else { return };
let relative = (module.kind() == "relative_import").then(|| {
let mut cursor = module.walk();
let dots = module
.children(&mut cursor)
.find(|c| c.kind() == "import_prefix")
.map_or(0, |p| self.src(p).matches('.').count());
let rest = module.child(1).filter(|c| c.kind() == "dotted_name").map_or("", |c| self.src(c));
(dots, rest.to_owned())
});
let source = match &relative {
Some((dots, rest)) => match resolve(*dots, rest, self.package) {
Some(s) => s,
None => return,
},
None => self.src(module).to_owned(),
};
let target = map_module(&source, self.moves).unwrap_or_else(|| source.clone());
// Imported submodules that moved on their own (`from pkg import models`).
let mut cursor = node.walk();
let names: Vec<Node> = node.children_by_field_name("name", &mut cursor).collect();
let mut moved: Vec<(Node, String, String, String)> = Vec::new(); // (item, parent, name, bound)
for &item in &names {
let (name, alias) = match item.kind() {
"aliased_import" => (item.child_by_field_name("name"), item.child_by_field_name("alias")),
_ => (Some(item), None),
};
let Some(name) = name else { continue };
let n = self.src(name).to_owned();
let full = join(&source, &n);
let Some(new) = map_module(&full, self.moves) else { continue };
if new == join(&target, &n) {
continue;
}
let (parent, last) =
new.rsplit_once('.').map_or((String::new(), new.clone()), |(p, l)| (p.into(), l.into()));
let bound = alias.map_or(n, |a| self.src(a).to_owned());
moved.push((item, parent, last, bound));
}
let as_name =
|last: &str, bound: &str| if last == bound { last.to_owned() } else { format!("{last} as {bound}") };
// Renamed inside the same package: only the name changes.
let in_place: Vec<(Node, String)> =
moved.iter().filter(|m| m.1 == target).map(|m| (m.0, as_name(&m.2, &m.3))).collect();
moved.retain(|m| m.1 != target);
let render = |module: &str, rw: &Self| match &relative {
Some((dots, rest)) if resolve(*dots, rest, rw.new_package).as_deref() == Some(module) => None,
Some(_) => Some(relative_to(module, rw.new_package).unwrap_or_else(|| module.to_owned())),
None => Some(module.to_owned()),
};
let all_one_parent = !moved.is_empty()
&& moved.len() == names.len()
&& moved.iter().all(|m| m.1 == moved[0].1 && !m.1.is_empty());
if all_one_parent {
let parent = moved[0].1.clone();
if let Some(m) = render(&parent, self).filter(|m| m != self.src(module)) {
self.edit(module, m);
}
for (item, _, last, bound) in moved {
let new = as_name(&last, &bound);
if new != self.src(item) {
self.edit(item, new);
}
}
return;
}
if moved.is_empty() {
if let Some(m) = render(&target, self).filter(|m| m != self.src(module)) {
self.edit(module, m);
}
for (item, text) in in_place {
self.edit(item, text);
}
return;
}
// ponytail: a split statement loses a multi-line names list's layout; fine for the rare
// "some names of one `from` moved elsewhere" case.
let indent = line_indent(self.text, node.start_byte());
let mut parents: Vec<&str> = Vec::new();
for m in &moved {
if !parents.contains(&m.1.as_str()) {
parents.push(&m.1);
}
}
let mut added: Vec<String> = Vec::new();
for parent in parents {
let items: Vec<String> = moved.iter().filter(|m| m.1 == parent).map(|m| as_name(&m.2, &m.3)).collect();
added.push(if parent.is_empty() {
format!("import {}", items.join(", "))
} else {
let from = render(parent, self).unwrap_or_else(|| self.src(module).to_owned());
format!("from {from} import {}", items.join(", "))
});
}
let kept: Vec<String> = names
.iter()
.filter(|n| !moved.iter().any(|m| m.0 == **n))
.map(|n| in_place.iter().find(|(i, _)| i == n).map_or_else(|| self.src(*n).to_owned(), |(_, t)| t.clone()))
.collect();
let sep = format!("\n{indent}");
if kept.is_empty() {
self.edit(node, added.join(&sep));
return;
}
if let Some(m) = render(&target, self).filter(|m| m != self.src(module)) {
self.edit(module, m);
}
let (first, last) = (names[0], names[names.len() - 1]);
let range = self.idx.range(first.start_byte(), last.end_byte());
self.edits.push(TextEdit { range, new_text: kept.join(", ") });
let end = self.idx.pos(node.end_byte());
self.edits.push(TextEdit {
range: ide_core::Range { start: end, end },
new_text: format!("{sep}{}", added.join(&sep)),
});
}
}
fn collect<'t>(node: Node<'t>, f: &mut impl FnMut(Node<'t>)) {
f(node);
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
collect(child, f);
}
}
fn inside_import(mut n: Node) -> bool {
while let Some(p) = n.parent() {
if matches!(p.kind(), "import_statement" | "import_from_statement" | "future_import_statement") {
return true;
}
n = p;
}
false
}
fn line_indent(text: &str, byte: usize) -> &str {
let start = text[..byte].rfind('\n').map_or(0, |i| i + 1);
&text[start..byte]
}
fn join(a: &str, b: &str) -> String {
match (a.is_empty(), b.is_empty()) {
(true, _) => b.to_owned(),
(_, true) => a.to_owned(),
_ => format!("{a}.{b}"),
}
}
/// `name` after `moves` (the longest moved prefix wins), if it changed.
fn map_module(name: &str, moves: &[(String, String)]) -> Option<String> {
moves
.iter()
.filter(|(from, _)| name == from || name.strip_prefix(from.as_str()).is_some_and(|r| r.starts_with('.')))
.max_by_key(|(from, _)| from.len())
.map(|(from, to)| format!("{to}{}", &name[from.len()..]))
.filter(|new| new != name)
}
/// The absolute module `from <dots><rest> import` names inside `package`.
fn resolve(dots: usize, rest: &str, package: &str) -> Option<String> {
let segs: Vec<&str> = package.split('.').filter(|s| !s.is_empty()).collect();
let keep = segs.len().checked_sub(dots.checked_sub(1)?)?;
if keep == 0 {
return None;
}
Some(join(&segs[..keep].join("."), rest))
}
/// The shortest relative form of `module` from `package`, if they share a top-level package.
fn relative_to(module: &str, package: &str) -> Option<String> {
let segs: Vec<&str> = package.split('.').filter(|s| !s.is_empty()).collect();
(1..=segs.len()).find_map(|dots| {
let base = segs[..segs.len() + 1 - dots].join(".");
let rest = if module == base { "" } else { module.strip_prefix(&base)?.strip_prefix('.')? };
Some(format!("{}{rest}", ".".repeat(dots)))
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::syntax::lines::byte_at;
fn apply(text: &str, package: &str, new_package: &str, moves: &[(&str, &str)]) -> String {
let moves: Vec<(String, String)> = moves.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect();
let mut edits = Syntax::new().python_import_edits(text, package, new_package, &moves);
edits.sort_by_key(|e| std::cmp::Reverse((e.range.start.line, e.range.start.col)));
let mut out = text.to_owned();
for e in edits {
let (s, t) = (byte_at(&out, e.range.start).unwrap(), byte_at(&out, e.range.end).unwrap());
out.replace_range(s..t, &e.new_text);
}
out
}
const RENAME: &[(&str, &str)] = &[("pkg.models", "pkg.domain")];
#[test]
fn absolute_imports() {
let src = "import pkg.models\nimport pkg.models as m\nfrom pkg.models import Task, Priority\nimport pkg.modelsx\n\nx = pkg.models.Task()\ny = m.Task\n";
assert_eq!(
apply(src, "app", "app", RENAME),
"import pkg.domain\nimport pkg.domain as m\nfrom pkg.domain import Task, Priority\nimport pkg.modelsx\n\nx = pkg.domain.Task()\ny = m.Task\n"
);
}
#[test]
fn bound_names_keep_their_alias() {
let src = "from pkg import models\nfrom pkg import models as mo, cli\nimport models\n";
let moves = &[("pkg.models", "pkg.domain"), ("models", "domain")];
assert_eq!(
apply(src, "app", "app", moves),
"from pkg import domain as models\nfrom pkg import domain as mo, cli\nimport domain as models\n"
);
}
#[test]
fn relative_imports() {
let src = "from .models import Task\nfrom . import models\nfrom . import cli\n";
assert_eq!(
apply(src, "pkg", "pkg", RENAME),
"from .domain import Task\nfrom . import domain as models\nfrom . import cli\n"
);
let src = "from ..models import Task\nfrom .. import models, cli\n";
assert_eq!(
apply(src, "pkg.sub", "pkg.sub", RENAME),
"from ..domain import Task\nfrom .. import domain as models, cli\n"
);
}
#[test]
fn module_moved_to_another_package() {
let moves = &[("pkg.models", "core.models")];
assert_eq!(apply("from .models import Task\n", "pkg", "pkg", moves), "from core.models import Task\n");
assert_eq!(apply("from pkg import models\n", "app", "app", moves), "from core import models\n");
assert_eq!(
apply("def f():\n from pkg import cli, models\n", "app", "app", moves),
"def f():\n from pkg import cli\n from core import models\n"
);
let moves = &[("pkg.models", "core.models"), ("pkg.cli", "pkg.main"), ("pkg.util", "util")];
assert_eq!(
apply("from pkg import cli, models, util, other\n", "app", "app", moves),
"from pkg import main as cli, other\nfrom core import models\nimport util\n"
);
assert_eq!(
apply("from . import models\n", "pkg.sub", "pkg.sub", &[("pkg.sub.models", "pkg.models")]),
"from .. import models\n"
);
}
#[test]
fn the_moved_file_keeps_its_relative_imports_resolving() {
// pkg/cli.py → other/cli.py: `.models` (pkg.models) did not move.
let moves = &[("pkg.cli", "other.cli")];
assert_eq!(apply("from .models import Task\n", "pkg", "other", moves), "from pkg.models import Task\n");
// pkg/sub/cli.py → pkg/cli.py
let moves = &[("pkg.sub.cli", "pkg.cli")];
assert_eq!(apply("from ..models import Task\n", "pkg.sub", "pkg", moves), "from .models import Task\n");
}
#[test]
fn package_moves() {
let moves = &[("pkg", "lib.pkg")];
let src =
"import pkg\nimport pkg.models\nfrom pkg.models import Task\nfrom pkg import models\n\npkg.models.Task()\n";
assert_eq!(
apply(src, "", "", moves),
"import lib.pkg as pkg\nimport lib.pkg.models\nfrom lib.pkg.models import Task\nfrom lib.pkg import models\n\nlib.pkg.models.Task()\n"
);
// Inside the moved package, relative imports still resolve.
assert_eq!(
apply("from .models import Task\nfrom . import cli\n", "pkg", "lib.pkg", moves),
"from .models import Task\nfrom . import cli\n"
);
// Absolute self-imports follow it.
assert_eq!(
apply("from pkg.models import Task\n", "pkg", "lib.pkg", moves),
"from lib.pkg.models import Task\n"
);
}
#[test]
fn unrelated_imports_are_untouched() {
let src = "from __future__ import annotations\nimport os\nfrom datetime import date\nfrom pkgx import models\nfrom . import *\n";
assert_eq!(apply(src, "pkg", "pkg", RENAME), src);
}
#[test]
fn helpers() {
assert_eq!(resolve(1, "m", "a.b").as_deref(), Some("a.b.m"));
assert_eq!(resolve(2, "", "a.b").as_deref(), Some("a"));
assert_eq!(resolve(3, "m", "a.b"), None);
assert_eq!(relative_to("a.b.m", "a.b").as_deref(), Some(".m"));
assert_eq!(relative_to("a.c", "a.b").as_deref(), Some("..c"));
assert_eq!(relative_to("x.c", "a.b"), None);
assert_eq!(map_module("pkg.models.sub", RENAME_OWNED.as_slice()).as_deref(), Some("pkg.domain.sub"));
}
static RENAME_OWNED: std::sync::LazyLock<Vec<(String, String)>> =
std::sync::LazyLock::new(|| vec![("pkg.models".into(), "pkg.domain".into())]);
}
+67
View File
@@ -947,6 +947,73 @@ async fn angular_language_server_end_to_end() {
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// The Tailwind CSS server on `fixtures/tailwind-app` (Tailwind 4, `@theme` colours), with
/// the built-in definitions: class completion in JSX and `@apply`, hover with the generated
/// CSS, and the class conflict warning. Set `OPENIDEA_TEST_NPM_TOOLS` to a dir with
/// `npm i @tailwindcss/language-server`; the fixture's own `tailwindcss` isn't needed.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires @tailwindcss/language-server (OPENIDEA_TEST_NPM_TOOLS)"]
async fn tailwindcss_language_server_end_to_end() {
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/tailwind-app");
for file in ["package.json", "index.html", "src/app.css", "src/App.tsx"] {
std::fs::create_dir_all(root.join(file).parent().unwrap()).unwrap();
std::fs::copy(fixture.join(file), root.join(file)).unwrap();
}
let builtin = LanguageRegistry::load(None).unwrap();
let languages = ["typescriptreact", "css"].map(|id| {
let mut cfg = builtin.get(&LanguageId::new(id)).unwrap();
cfg.language_servers.retain(|s| s.name == "tailwindcss-language-server");
let bin = tools.join("node_modules/.bin/tailwindcss-language-server");
cfg.language_servers[0].command = bin.to_string_lossy().into_owned();
cfg
});
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(languages.to_vec()));
let (tsx, css) = (DocId::next(), DocId::next());
let tsx_path = root.join("src/App.tsx");
let css_path = root.join("src/app.css");
let tsx_text = std::fs::read_to_string(&tsx_path).unwrap();
let css_text = std::fs::read_to_string(&css_path).unwrap();
mgr.did_open(tsx, &tsx_path, &LanguageId::new("typescriptreact"), 1, &tsx_text);
mgr.did_open(css, &css_path, &LanguageId::new("css"), 1, &css_text);
let at = |text: &str, needle: &str, offset: usize| {
let (line, l) = text.lines().enumerate().find(|(_, l)| l.contains(needle)).unwrap();
Pos::new(line as u32, (l.find(needle).unwrap() + offset) as u32)
};
// The project's own `@theme` colour, in `className` and after `@apply`.
let in_class = at(&tsx_text, "className=\"flex flex-col", "className=\"".len());
let in_apply = at(&css_text, "@apply rounded-md", "@apply ".len());
for (doc, pos) in [(tsx, in_class), (css, in_apply)] {
retry("class completion", Duration::from_secs(60), || {
let mgr = mgr.clone();
async move {
let list = mgr.completion(doc, pos, None, Default::default()).await.ok()?;
list.items.iter().any(|i| i.label == "bg-brand-500").then_some(())
}
})
.await;
}
let hover = mgr.hover(tsx, at(&tsx_text, "bg-white", 1), Default::default()).await.unwrap().unwrap();
assert!(hover.contents.value.contains("background-color"), "{}", hover.contents.value);
let hover = mgr.hover(tsx, at(&tsx_text, "text-brand-700", 1), Default::default()).await.unwrap().unwrap();
assert!(hover.contents.value.contains("--color-brand-700"), "{}", hover.contents.value);
// `flex block`: both set `display`.
retry("class conflict", Duration::from_secs(30), || {
let found = events.lock().iter().any(|e| {
matches!(e, IdeEvent::Diagnostics { path, items, .. }
if path.ends_with("src/App.tsx")
&& items.iter().any(|d| d.message.contains("applies the same CSS properties")))
});
async move { found.then_some(()) }
})
.await;
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// A notebook's code cells on basedpyright and Ruff (LSP 3.17 notebook sync): names flow from
/// earlier cells, IPython magics parse, and locations and diagnostics name the cells.
#[tokio::test(flavor = "multi_thread")]
@@ -0,0 +1,9 @@
id = "test.agent-skills"
name = "Agent Skills Fixture"
version = "1.0.0"
description = "Declarative plugin contributing an agent skill."
authors = ["OpenIDEA contributors"]
engines.openidea = "^1.15"
[[contributes.skills]]
path = "skills/release-notes/SKILL.md"
@@ -0,0 +1,7 @@
---
name: release-notes
description: Draft concise release notes from merged commits and pull requests.
argument-hint: "[tag]"
---
Summarize user-visible changes since the given release tag using `references/template.md`.
@@ -0,0 +1,7 @@
## Added
- Summary of user-facing features.
## Fixed
- Summary of resolved bugs.
+6
View File
@@ -118,6 +118,8 @@ struct FileConfig {
#[serde(alias = "stopCommand")]
stop_command: Option<String>,
target: Option<String>,
#[serde(alias = "testRunner")]
test_runner: Option<String>,
}
pub(crate) fn slug(s: &str) -> String {
@@ -183,6 +185,7 @@ fn convert(configs: Vec<FileConfig>, local: bool) -> Vec<RunConfig> {
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
}
+82 -5
View File
@@ -243,8 +243,53 @@ 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<PathBuf>, out: &mut Vec<RunConfig>) {
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`, `mocha`, or `node --test` (`tsx --test`) with Node's own
/// reporters (the IDE adds its reporter next to them, which a reporter chosen here would clash with).
fn script_test_runner(script: &str) -> Option<&'static str> {
let tokens: Vec<&str> = script.split(|c: char| c.is_whitespace() || matches!(c, '&' | '|' | ';')).collect();
if tokens.windows(2).any(|w| w[0] == "playwright" && w[1] == "test") {
return Some("playwright");
}
if tokens.iter().any(|t| matches!(t.rsplit('/').next(), Some("mocha" | "_mocha"))) {
return Some("mocha");
}
let node = tokens.iter().position(|t| matches!(*t, "node" | "tsx"))?;
// Node's own options: up to the script (`node server.js --test` passes `--test` to the program).
let mut options = Vec::new();
for t in &tokens[node + 1..] {
let value = options.last().is_some_and(|o| NODE_VALUE_OPTIONS.contains(o));
if !value && !t.starts_with('-') {
break;
}
options.push(*t);
}
(options.contains(&"--test") && !options.iter().any(|t| t.starts_with("--test-reporter"))).then_some("node-test")
}
/// Node options whose value is the next argument.
const NODE_VALUE_OPTIONS: &[&str] =
&["-r", "--require", "--import", "--loader", "--experimental-loader", "-C", "--conditions", "--env-file"];
const PLAYWRIGHT_CONFIGS: &[&str] = &[
"playwright.config.ts",
"playwright.config.js",
"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<PathBuf>,
out: &mut Vec<RunConfig>,
) -> 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 +299,39 @@ fn push_scripts(pkg: &Json, pm: &str, prefix: Option<&str>, cwd: Option<PathBuf>
};
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<PathBuf>,
out: &mut Vec<RunConfig>,
) {
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<RunConfig>) {
@@ -275,7 +348,10 @@ fn detect_node(root: &Path, out: &mut Vec<RunConfig>) {
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 +364,8 @@ fn detect_node(root: &Path, out: &mut Vec<RunConfig>) {
.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);
}
}
}
+7
View File
@@ -182,6 +182,12 @@ pub struct RunExtras {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub target: Option<String>,
/// 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<String>,
}
impl Default for RunExtras {
@@ -205,6 +211,7 @@ impl Default for RunExtras {
emulate_terminal: false,
stop_command: None,
target: None,
test_runner: None,
}
}
}
+55
View File
@@ -51,6 +51,61 @@ 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 node_test_scripts() {
let dir = project(&[(
"package.json",
r#"{"scripts":{"test":"node --import tsx --test","check":"tsx --test src/","tap":"node --test --test-reporter=tap","start":"node server.js --test"}}"#,
)]);
let c = detect(dir.path());
assert_eq!(find(&c, "npm:test").extras.test_runner.as_deref(), Some("node-test"));
let check = find(&c, "npm:check");
assert!(check.is_test);
assert_eq!(check.extras.test_runner.as_deref(), Some("node-test"));
// A reporter of its own: run as written, without the IDE's.
assert_eq!(find(&c, "npm:tap").extras.test_runner, None);
assert_eq!(find(&c, "npm:start").extras.test_runner, None);
}
#[test]
fn mocha_scripts() {
let dir = project(&[(
"package.json",
r#"{"scripts":{"spec":"mocha --recursive","test":"nyc ./node_modules/.bin/mocha","lint":"eslint mocha.config.js"}}"#,
)]);
let c = detect(dir.path());
let spec = find(&c, "npm:spec");
assert!(spec.is_test);
assert_eq!(spec.extras.test_runner.as_deref(), Some("mocha"));
assert_eq!(find(&c, "npm:test").extras.test_runner.as_deref(), Some("mocha"));
assert!(!find(&c, "npm:lint").is_test);
}
#[test]
fn package_manager_selection() {
for (lock, pm) in [("yarn.lock", "yarn"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("package-lock.json", "npm")] {
+1
View File
@@ -6,6 +6,7 @@ edition.workspace = true
license.workspace = true
[dependencies]
dirs.workspace = true
dunce.workspace = true
ignore.workspace = true
ide-core.workspace = true
+110
View File
@@ -537,6 +537,42 @@ pub fn configure_gradle_runtime(cfg: &mut LanguageServerConfig, root: &Path, bui
merge(cfg.settings.get_or_insert_with(|| json!({})), json!({"java": {"import": {"gradle": gradle}}}));
}
/// Gradle's Eclipse model, which jdtls imports the build through, leaves out project dependencies
/// a source set only compiles against (`compileOnly(project(":a"))`) and marks some as test-only,
/// so their classes don't resolve in the editor although Gradle compiles. jdtls's Gradle import
/// runs an init script that adds them, written to the first of `dirs` whose path has no
/// whitespace: Buildship stores the import's arguments joined by spaces and splits them again,
/// so `Application Support` would break the path. The name carries the script's hash, so
/// releases running side by side never overwrite each other's script.
pub fn configure_gradle_classpath(cfg: &mut LanguageServerConfig, dirs: &[PathBuf]) {
const SCRIPT: &str = include_str!("gradle-classpath.init.gradle");
if cfg.name != "jdtls" {
return;
}
let mut hash = 0xcbf29ce484222325u64;
for byte in SCRIPT.bytes() {
hash = (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3);
}
let name = format!("openidea-classpath-{hash:016x}.init.gradle");
let Some(script) = dirs
.iter()
.map(|dir| dir.join(&name))
.filter(|script| !script.to_string_lossy().contains(char::is_whitespace))
.find(|script| {
std::fs::read(script).ok().as_deref() == Some(SCRIPT.as_bytes())
|| script.parent().is_some_and(|dir| std::fs::create_dir_all(dir).is_ok())
&& std::fs::write(script, SCRIPT).is_ok()
})
else {
tracing::warn!("no directory without spaces for the Gradle classpath init script: {dirs:?}");
return;
};
merge(
cfg.settings.get_or_insert_with(|| json!({})),
json!({"java": {"import": {"gradle": {"arguments": ["--init-script", script.to_string_lossy()]}}}}),
);
}
/// Settings › Build Tools › Maven › Automatically download sources and Always update
/// snapshots → jdtls `java.maven.downloadSources` / `java.maven.updateSnapshots`.
pub fn configure_maven_sources(cfg: &mut LanguageServerConfig, s: &Settings) {
@@ -1424,6 +1460,14 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
if name == astro::SERVER {
astro::configure(cfg, root, server_root, s);
}
// Biome lints with the project's own version (its configuration follows that version's
// schema); an explicit executable setting still wins.
if name == "biome"
&& cfg.command == "biome"
&& let Some(bin) = crate::npm::project_bin("biome", root, server_root)
{
cfg.command = bin.to_string_lossy().into_owned();
}
if name == crate::arduino::SERVER {
crate::arduino::configure(cfg, root, server_root, s);
}
@@ -2521,6 +2565,33 @@ mod maven_linkage_tests {
assert_eq!(gradle["user"]["home"], resolved("/caches/gradle"));
}
#[test]
fn gradle_import_adds_the_projects_a_source_set_compiles_against() {
let temp = tempfile::tempdir().unwrap();
let spaced = temp.path().join("Application Support").join("gradle");
let plain = temp.path().join("cache").join("gradle");
let mut cfg = custom_server("jdtls", &LanguageServerSettings::default());
cfg.settings = Some(json!({"java": {"import": {"gradle": {"enabled": true}}}}));
configure_gradle_classpath(&mut cfg, &[spaced.clone(), plain.clone()]);
let gradle = &cfg.settings.as_ref().unwrap()["java"]["import"]["gradle"];
assert_eq!(gradle["enabled"], json!(true), "merged, not replaced");
let args = gradle["arguments"].as_array().unwrap();
assert_eq!(args[0], json!("--init-script"));
let script = PathBuf::from(args[1].as_str().unwrap());
assert_eq!(script.parent(), Some(plain.as_path()), "Buildship splits arguments at spaces");
assert!(!spaced.exists());
let text = std::fs::read_to_string(&script).unwrap();
assert!(text.contains("compileClasspath") && text.contains("whenMerged"));
let mut other = custom_server("pyright", &LanguageServerSettings::default());
configure_gradle_classpath(&mut other, &[plain]);
assert!(other.settings.is_none(), "only jdtls imports Gradle builds");
let mut nowhere = custom_server("jdtls", &LanguageServerSettings::default());
configure_gradle_classpath(&mut nowhere, &[spaced]);
assert!(nowhere.settings.is_none(), "no usable directory: the import runs without it");
}
#[test]
fn gradle_import_of_a_gradle_build_runs_on_the_project_jdk_like_the_ides_builds() {
let temp = tempfile::tempdir().unwrap();
@@ -2743,3 +2814,42 @@ mod conda_activation_tests {
assert_eq!(conda_activation(&plain.join("bin").join("python"), "bash", Some(conda), None), None);
}
}
#[cfg(test)]
mod biome_tests {
use super::*;
fn binary(dir: &Path) -> PathBuf {
let bin = dir.join(if cfg!(windows) { "biome.cmd" } else { "biome" });
std::fs::create_dir_all(dir).unwrap();
std::fs::write(&bin, "").unwrap();
#[cfg(unix)]
std::fs::set_permissions(&bin, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
bin
}
#[test]
fn biome_runs_the_projects_own_biome_unless_an_executable_is_set() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
let web = root.join("apps/web");
let configured = |s: &Settings, server_root: &Path| {
let mut cfg = custom_server("biome", &LanguageServerSettings::default());
cfg.command = "biome".into();
configure_server(&mut cfg, &root, server_root, s);
PathBuf::from(cfg.command)
};
let workspace = binary(&root.join("node_modules/.bin"));
assert_eq!(configured(&Settings::default(), &web), workspace);
let member = binary(&web.join("node_modules/.bin"));
assert_eq!(configured(&Settings::default(), &web), member);
// Outside the project: not the project's installation.
binary(&tmp.path().join("node_modules/.bin"));
assert_eq!(configured(&Settings::default(), &tmp.path().join("other")), PathBuf::from("biome"));
let custom = binary(&tmp.path().join("custom"));
let mut s = Settings::default();
s.tools
.insert("biome".into(), ide_core::settings::ToolSettings { path: custom.to_string_lossy().into_owned() });
assert_eq!(configured(&s, &web), custom);
}
}
+2 -5
View File
@@ -1,7 +1,7 @@
//! Astro (Volar) requires a TypeScript language-service library at initialize.
use crate::apply::{merge_init_options, setting_path, tsdk};
use crate::npm::{has_ts_api, own_typescript, package_dir};
use crate::npm::{has_ts_api, own_typescript, package_dir, project_bin};
use ide_core::settings::Settings;
use ide_core::tool_path::{find_command, search_path};
use ide_language::LanguageServerConfig;
@@ -20,10 +20,7 @@ pub(crate) fn configure(cfg: &mut LanguageServerConfig, root: &Path, server_root
// A project's installation wins over managed / global tools. Explicit
// executable settings still win, as they do for other language servers.
if cfg.command == SERVER
&& let Some(bin) = server_root
.ancestors()
.take_while(|dir| dir.starts_with(root))
.find_map(|dir| find_command(SERVER, dir.join("node_modules/.bin").as_os_str(), server_root))
&& let Some(bin) = project_bin(SERVER, root, server_root)
{
cfg.command = bin.to_string_lossy().into_owned();
}
@@ -0,0 +1,37 @@
// Gradle's Eclipse model leaves out project dependencies a source set only compiles against
// (compileOnly, compileOnlyApi), and marks some as test-only. Add each project the main or test
// compile classpath names, so Java code sees the classes it compiles against.
allprojects {
plugins.withId('java') {
apply plugin: 'eclipse'
eclipse.classpath.file.whenMerged { classpath ->
def projectOf = { dep ->
def path
try { path = dep.path } catch (MissingPropertyException ignored) { path = dep.dependencyProject.path }
rootProject.findProject(path)
}
def wanted = [:]
['testCompileClasspath', 'compileClasspath'].each { name ->
def configuration = configurations.findByName(name)
if (configuration == null) return
configuration.allDependencies.withType(ProjectDependency).each { dep ->
def target = projectOf(dep)
if (target == null || target == project) return
def eclipseName = target.extensions.findByName('eclipse')?.project?.name ?: target.name
wanted['/' + eclipseName] = name == 'compileClasspath'
}
}
def existing = classpath.entries.findAll { it instanceof org.gradle.plugins.ide.eclipse.model.ProjectDependency }
wanted.each { path, main ->
def entry = existing.find { it.path == path }
if (entry == null) {
entry = new org.gradle.plugins.ide.eclipse.model.ProjectDependency(path)
entry.entryAttributes['without_test_code'] = 'true'
classpath.entries.add(entry)
}
if (main) entry.entryAttributes.remove('test')
else if (!entry.entryAttributes.containsKey('test')) entry.entryAttributes['test'] = 'true'
}
}
}
}
+48 -2
View File
@@ -287,8 +287,8 @@ pub fn launch_directly(cfg: &mut LanguageServerConfig) {
return;
}
let Some(script) = script_for(cfg) else { return };
let Some(install) =
jdtls_home(&script).and_then(|h| find_install(&h, std::env::consts::OS, std::env::consts::ARCH))
let home = jdtls_home(&script);
let Some(install) = home.as_deref().and_then(|h| find_install(h, std::env::consts::OS, std::env::consts::ARCH))
else {
return;
};
@@ -307,14 +307,60 @@ pub fn launch_directly(cfg: &mut LanguageServerConfig) {
cfg.launch_error = Some(error);
return;
}
let area = home.as_deref().and_then(|home| configuration_area(home, &cfg.args, dirs::cache_dir()));
cfg.args = java_args(&install, jdk.major, &cfg.args);
if let Some(area) = area
&& let Some(jar) = cfg.args.iter().position(|a| a == "-jar")
{
cfg.args.insert(jar, format!("-Dosgi.configuration.area={}", area.to_string_lossy()));
}
cfg.command = java.to_string_lossy().into_owned();
}
/// Equinox extracts bundle files, jdtls's Gradle init scripts among them, into its writable
/// configuration area, `<home>/configuration` unless the launch names one. jdtls passes those
/// scripts to every Gradle import as `--init-script` arguments, and Buildship stores a build's
/// arguments joined by spaces and splits them again. Under a home with spaces (macOS's
/// `Application Support`) each import that sets a Gradle JDK, user home or argument then fails
/// with "The specified initialization script '…/Application' does not exist". Such a home
/// gets an area without spaces in the user's cache directory, one per install.
fn configuration_area(home: &Path, args: &[String], cache: Option<PathBuf>) -> Option<PathBuf> {
let parsed = split_script_args(args);
let named = parsed.jvm.iter().any(|a| a.starts_with("-Dosgi.configuration.area="))
|| parsed.rest.iter().any(|a| a == "-configuration");
if named || !home.join("configuration").to_string_lossy().contains(char::is_whitespace) {
return None;
}
let mut hash = 0xcbf29ce484222325u64;
for byte in home.to_string_lossy().bytes() {
hash = (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3);
}
Some(cache?.join("openidea").join("jdtls-configuration").join(format!("{hash:016x}")))
.filter(|area| !area.to_string_lossy().contains(char::is_whitespace))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_home_with_spaces_gets_a_configuration_area_without_them() {
let cache = Some(PathBuf::from("/cache"));
let spaced = Path::new("/Users/me/Library/Application Support/openidea/tools/jdtls");
let area = configuration_area(spaced, &[], cache.clone()).unwrap();
assert!(area.starts_with("/cache/openidea/jdtls-configuration"));
assert_eq!(configuration_area(spaced, &[], cache.clone()), Some(area), "one per install");
assert_ne!(
configuration_area(Path::new("/opt/My Tools/jdtls"), &[], cache.clone()),
configuration_area(spaced, &[], cache.clone())
);
assert_eq!(configuration_area(Path::new("/opt/jdtls"), &[], cache.clone()), None, "the default is fine");
let own = strings(&["--jvm-arg=-Dosgi.configuration.area=/mine"]);
assert_eq!(configuration_area(spaced, &own, cache.clone()), None, "the user's area stays");
assert_eq!(configuration_area(spaced, &strings(&["-configuration", "/mine"]), cache), None);
assert_eq!(configuration_area(spaced, &[], Some(PathBuf::from("/My Cache"))), None);
}
fn strings(args: &[&str]) -> Vec<String> {
args.iter().map(|s| s.to_string()).collect()
}
+7
View File
@@ -10,6 +10,13 @@ pub(crate) fn has_ts_api(lib: &Path) -> bool {
lib.join("typescript.js").is_file()
}
/// `command` installed in the project: the nearest `node_modules/.bin` from `server_root` up to `root`.
pub(crate) fn project_bin(command: &str, root: &Path, server_root: &Path) -> Option<PathBuf> {
server_root.ancestors().take_while(|dir| dir.starts_with(root)).find_map(|dir| {
ide_core::tool_path::find_command(command, dir.join("node_modules/.bin").as_os_str(), server_root)
})
}
/// The native executable of TypeScript 7 (`typescript` 7+, whose `tsc` is native, or
/// `@typescript/native-preview`'s `tsgo`), from its package directory or its `lib`.
/// These packages have no JavaScript API (`lib/typescript.js`); their platform package
+77 -1
View File
@@ -1,7 +1,7 @@
//! Python environments: creating virtualenvs and managing packages with pip
//! (or `uv pip` for environments created by uv, which ship without pip).
use crate::exec::{query_in, stream, which};
use crate::exec::{query_in, query_in_cancellable, stream, which};
use crate::{Sdk, bin_dir, exe, venv_of};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
@@ -320,6 +320,82 @@ pub fn install_package(
stream(&program, &args, dir.as_ref().map(|d| d.path()), &pip_env(python), cancel, on_line).map(|_| ())
}
/// Run by the interpreter itself, so markers and PEP 440 specifiers are judged as pip would:
/// prints, per requirement of `argv[1]` (a JSON list), `null` when satisfied or not applicable
/// there, else `{"installed": <version or null>}`.
const CHECK_REQUIREMENTS: &str = r#"
import json, re, sys
try:
from packaging.requirements import Requirement
except Exception:
try:
from pip._vendor.packaging.requirements import Requirement
except Exception:
Requirement = None
from importlib import metadata
norm = lambda n: re.sub(r"[-_.]+", "-", n).lower()
installed = {}
for d in metadata.distributions():
name = d.metadata["Name"]
if name:
installed.setdefault(norm(name), d.version)
out = []
for line in json.loads(sys.argv[1]):
try:
if Requirement:
r = Requirement(line)
name, spec, applies = r.name, r.specifier, r.marker is None or r.marker.evaluate({"extra": ""})
else:
# Without packaging only names are compared; a marker can't be judged.
name, spec, applies = re.match(r"[A-Za-z0-9._-]+", line).group(0), None, ";" not in line
version = installed.get(norm(name))
if not applies or (version is not None and (spec is None or spec.contains(version, prereleases=True))):
out.append(None)
else:
out.append({"installed": version})
except Exception:
out.append(None)
print(json.dumps(out))
"#;
#[derive(Debug, Deserialize, PartialEq)]
pub struct Unsatisfied {
/// The version installed that misses the specifier; `None` when not installed.
pub installed: Option<String>,
}
/// Which of `requirements` (PEP 508 strings) `python` doesn't satisfy, in order;
/// `None` for satisfied ones, for ones whose marker excludes this interpreter, and
/// for ones it can't parse.
pub fn unsatisfied_requirements(
python: &Path,
requirements: &[&str],
cancel: &CancellationToken,
) -> IdeResult<Vec<Option<Unsatisfied>>> {
let list = serde_json::to_string(requirements).map_err(|e| IdeError::internal(e.to_string()))?;
let dir = neutral_dir().ok_or_else(|| IdeError::internal("no temporary directory"))?;
let out = query_in_cancellable(
python,
&["-c", CHECK_REQUIREMENTS, &list],
dir.path(),
&[],
Duration::from_secs(20),
cancel,
);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let out =
out.ok_or_else(|| IdeError::unavailable(format!("cannot check requirements with {}", python.display())))?;
let json = out.lines().rev().find(|l| l.starts_with('[')).unwrap_or("");
let result: Vec<Option<Unsatisfied>> =
serde_json::from_str(json).map_err(|e| IdeError::internal(format!("unexpected output: {e}")))?;
if result.len() != requirements.len() {
return Err(IdeError::internal("unexpected output: wrong number of results"));
}
Ok(result)
}
pub fn uninstall_package(
python: &Path,
name: &str,
+44
View File
@@ -6,6 +6,7 @@ use crate::apply::{
};
use crate::python::parse_pip_list;
use crate::{bin_dir, exe, venv_of};
use ide_core::CancellationToken;
use ide_core::settings::Settings;
use ide_language::LanguageServerConfig;
use ide_run::RunConfig;
@@ -3184,3 +3185,46 @@ fn server_command_paths_report_executables_set_for_built_in_servers() {
]
);
}
#[test]
fn unsatisfied_requirements_are_judged_by_the_interpreter() {
let Some(base) = crate::exec::which("python3").or_else(|| crate::exec::which("python")) else { return };
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("env");
// System site packages: pip's vendored `packaging` when the base has pip.
let status = std::process::Command::new(base)
.args(["-I", "-m", "venv", "--without-pip", "--system-site-packages"])
.arg(&home)
.status()
.unwrap();
assert!(status.success());
let python = home.join(bin_dir()).join(exe("python"));
let site = std::process::Command::new(&python)
.args(["-c", "import sysconfig; print(sysconfig.get_paths()['purelib'])"])
.output()
.unwrap();
let site = std::path::PathBuf::from(String::from_utf8(site.stdout).unwrap().trim());
let info = site.join("Fake.Dist_Pkg-1.0.dist-info");
std::fs::create_dir_all(&info).unwrap();
std::fs::write(info.join("METADATA"), "Metadata-Version: 2.1\nName: Fake.Dist_Pkg\nVersion: 1.0\n").unwrap();
let packaging = std::process::Command::new(&python)
.args(["-c", "import pip._vendor.packaging.requirements"])
.status()
.is_ok_and(|s| s.success());
let cancel = CancellationToken::new();
let found = crate::python::unsatisfied_requirements(
&python,
&[
"fake-dist-pkg",
"FAKE_dist.pkg>=0.5",
"fake-dist-pkg>=2",
"openidea-not-installed-xyz[extra]==1",
"openidea-not-installed-xyz; sys_platform == 'nowhere'",
],
&cancel,
)
.unwrap();
let missing = || Some(crate::python::Unsatisfied { installed: None });
let old = packaging.then(|| crate::python::Unsatisfied { installed: Some("1.0".into()) });
assert_eq!(found, [None, None, old, missing(), None]);
}
+51 -4
View File
@@ -62,13 +62,22 @@ fn package_bin(package: &Path, tool: &str) -> IdeResult<PathBuf> {
Ok(path)
}
/// Prettier and Ruff format ranges for some languages (`config.range`); oxfmt formats whole files only.
/// Prettier and Ruff format ranges for some languages (`config.range`); oxfmt and Biome format whole files only.
pub fn supports_range(tool: &str, config: &FormatterConfig) -> bool {
matches!(tool, "prettier" | "ruff") && config.range
}
fn is_formatter(tool: &str) -> bool {
crate::registry::find(tool).is_some_and(|t| t.kind == crate::ToolKind::Formatter || t.name == "ruff")
crate::registry::find(tool)
.is_some_and(|t| t.kind == crate::ToolKind::Formatter || matches!(t.name, "ruff" | "biome"))
}
/// The npm package that provides `tool`'s CLI.
fn npm_package(tool: &str) -> &str {
match tool {
"biome" => "@biomejs/biome",
_ => tool,
}
}
impl Tools {
@@ -81,7 +90,7 @@ impl Tools {
if !is_formatter(tool) {
return Err(IdeError::unavailable(format!("Unknown external formatter: {tool}")));
}
let package = Path::new("node_modules").join(tool);
let package = Path::new("node_modules").join(npm_package(tool));
let manifest = package.join("package.json");
let (path, node) = if let Some(custom) = custom.filter(|p| p.is_dir()) {
(package_bin(custom, tool)?, true)
@@ -108,7 +117,7 @@ impl Tools {
}
/// Every tool resolves its configuration itself. Prettier's project configuration
/// overrides the editor indentation passed here; oxfmt and Ruff read their own
/// overrides the editor indentation passed here; oxfmt, Biome and Ruff read their own
/// configuration files. Ruff also discovers the nearest `pyproject.toml`,
/// `ruff.toml`, or `.ruff.toml` from the stdin filename.
pub fn arguments(
@@ -137,6 +146,12 @@ pub fn arguments(
}
return args;
}
if tool == "biome" {
// Biome finds its `biome.json` and ignore files from the file's path itself.
let mut path = OsString::from("--stdin-file-path=");
path.push(file);
return vec!["format".into(), path];
}
if tool == "prettier" {
let parser = if config.parser == "markdown" && file.extension().is_some_and(|s| s == "mdx") {
"mdx"
@@ -323,6 +338,38 @@ mod tests {
assert!(unknown.message.contains("Unknown external formatter"), "{}", unknown.message);
}
#[test]
fn biome_runs_the_nearest_biomejs_package_with_the_file_path() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let package = root.join("node_modules/@biomejs/biome");
std::fs::create_dir_all(package.join("bin")).unwrap();
std::fs::write(package.join("package.json"), r#"{"bin":{"biome":"bin/biome"}}"#).unwrap();
std::fs::write(package.join("bin/biome"), "").unwrap();
std::fs::write(root.join(".prettierignore"), "dist").unwrap();
let file = root.join("packages/web/src/app.ts");
let path = std::env::var_os("PATH").unwrap_or_default();
let tools = Tools::with_paths(root.join("tools"), path, crate::platform::Platform::current());
let command = tools.formatter_command("biome", &file, None).unwrap();
let program = Path::new(command.get_program()).file_stem().unwrap().to_string_lossy().into_owned();
assert_eq!(program, "node");
let script: Vec<_> = command.get_args().collect();
assert_eq!(
Path::new(&script[0]).components().collect::<Vec<_>>(),
package.join("bin/biome").components().collect::<Vec<_>>()
);
let config = FormatterConfig { tool: "prettier".into(), parser: "typescript".into(), range: true };
let range =
Some(FormatRange { start_offset: 3, end_offset: 9, start_line: 1, start_col: 1, end_line: 1, end_col: 7 });
let mut stdin_path = OsString::from("--stdin-file-path=");
stdin_path.push(&file);
// No Prettier ignore files or indentation: Biome reads its own configuration.
assert_eq!(arguments("biome", &config, &file, 4, false, range, None), ["format".into(), stdin_path]);
assert!(!supports_range("biome", &config));
}
#[test]
fn ruff_formats_stdin_and_uses_its_config_and_range_flags() {
let config = FormatterConfig { tool: "ruff".into(), parser: "python".into(), range: true };
+7
View File
@@ -405,6 +405,13 @@ impl Http {
self
}
/// Skips `GITHUB_TOKEN` / `GH_TOKEN` / `gh auth token` (e.g. retrying a public GitHub endpoint after HTTP 401).
pub fn without_github_auth(mut self) -> Self {
self.gh = None;
self.explicit_github_token = None;
self
}
fn base(&self, url: &str, cancel: &CancellationToken) -> IdeResult<(Command, Option<String>)> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
+25 -1
View File
@@ -201,6 +201,18 @@ pub static TOOLS: &[ToolSpec] = &[
needs: NODE,
homepage: "https://oxc.rs/docs/guide/usage/linter",
},
// Linter and formatter: `biome lsp-proxy` lints, and Reformat Code runs `biome format`.
ToolSpec {
name: "biome",
display: "Biome",
kind: LanguageServer,
commands: &["biome"],
method: Method::Npm { packages: &["@biomejs/biome"] },
fallback: None,
version: ver("biome"),
needs: NODE,
homepage: "https://biomejs.dev",
},
ToolSpec {
name: "eslint",
display: "ESLint Language Server",
@@ -444,6 +456,18 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://angular.dev/tools/language-service",
needs: &[],
},
ToolSpec {
name: "tailwindcss-language-server",
display: "Tailwind CSS Language Server",
kind: LanguageServer,
commands: &["tailwindcss-language-server"],
// Brings Tailwind CSS 3 and 4 for projects whose own `tailwindcss` isn't installed yet.
method: Method::Npm { packages: &["@tailwindcss/language-server"] },
fallback: None,
version: V,
homepage: "https://github.com/tailwindlabs/tailwindcss-intellisense",
needs: NODE,
},
ToolSpec {
name: "graphql-lsp",
display: "GraphQL Language Server",
@@ -1286,7 +1310,7 @@ mod tests {
known.insert((d.adapter.clone(), d.command.clone()));
}
}
// The host selects the formatter of each file (Prettier or oxfmt) and runs its own CLIs.
// The host selects the formatter of each file (Prettier, oxfmt or Biome) and runs its own CLIs.
for t in TOOLS.iter().filter(|t| !matches!(t.kind, Plugin | Formatter | Cli)) {
assert!(
known.contains(&(t.name.to_string(), t.commands[0].to_string())),
@@ -4,6 +4,7 @@ pub mod cargo;
pub mod go;
pub mod maven;
pub mod npm;
pub mod python;
pub use cache::VersionCache;
use ide_core::{CancellationToken, IdeResult};
@@ -48,3 +49,20 @@ pub struct DependencyVersions {
pub versions: Vec<String>,
pub update: Option<DependencyUpdate>,
}
/// A requirement the project's interpreter does not satisfy.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct UnsatisfiedRequirement {
pub dependency: ManifestDependency,
/// The installed version that misses the specifier; `None` when not installed.
pub installed: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PythonRequirements {
/// The interpreter checked, which installs go to.
pub python: ide_core::IpcPath,
pub unsatisfied: Vec<UnsatisfiedRequirement>,
}
@@ -0,0 +1,193 @@
//! Python requirements in `requirements*.txt` and `pyproject.toml`. Whether one is
//! satisfied is up to the interpreter (`ide-sdk`): markers and PEP 440 depend on it.
use super::ManifestDependency;
use toml_edit::{Document, Item};
/// `requirements.txt`, `requirements-dev.txt`, `requirements/base.txt`'s siblings named alike.
pub fn is_requirements_file(name: &str) -> bool {
name.starts_with("requirements") && name.ends_with(".txt")
}
/// The requirements of a manifest, by file name; `requirement` is the PEP 508 string
/// and `from..to` its UTF-16 span.
pub fn requirements(file_name: &str, text: &str) -> Vec<ManifestDependency> {
if file_name == "pyproject.toml" {
pyproject(text)
} else if is_requirements_file(file_name) {
requirements_txt(text)
} else {
Vec::new()
}
}
/// The distribution name a requirement starts with, if it names one (not a URL, path or archive).
fn named(requirement: &str) -> Option<ManifestDependency> {
let end = requirement
.find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')))
.unwrap_or(requirement.len());
let name = requirement[..end].trim_end_matches(['.', '-', '_']);
let rest = requirement[end..].trim_start();
if name.is_empty()
|| !name.as_bytes()[0].is_ascii_alphanumeric()
|| rest.starts_with([':', '/', '\\'])
|| !rest.starts_with('@') && [".whl", ".zip", ".tar.gz", ".tgz"].iter().any(|ext| requirement.ends_with(ext))
|| requirement.contains("://") && !rest.starts_with(['@', '['])
{
return None;
}
Some(ManifestDependency { package: name.to_owned(), requirement: requirement.to_owned(), from: 0, to: 0 })
}
fn utf16(text: &str, byte: usize) -> u32 {
text[..byte].encode_utf16().count() as u32
}
fn requirements_txt(text: &str) -> Vec<ManifestDependency> {
let mut out = Vec::new();
let mut start = 0;
for line in text.split_inclusive('\n') {
let line_start = start;
start += line.len();
let body = line.trim_end_matches(['\n', '\r']);
// A comment starts the line or follows whitespace; per-requirement options (`--hash`) follow ` -`.
let cut = [" #", "\t#", " --", "\t--", " \\"].iter().filter_map(|m| body.find(m)).min().unwrap_or(body.len());
let content = body[..cut].trim_end();
let lead = content.len() - content.trim_start().len();
let requirement = content.trim_start();
if requirement.is_empty() || requirement.starts_with(['#', '-']) || is_continuation(text, line_start) {
continue;
}
if let Some(mut dep) = named(requirement) {
dep.from = utf16(text, line_start + lead);
dep.to = utf16(text, line_start + lead + requirement.len());
out.push(dep);
}
}
out
}
/// The previous physical line ends with `\`: this one continues it (its options).
fn is_continuation(text: &str, line_start: usize) -> bool {
text[..line_start].trim_end_matches(['\n', '\r']).ends_with('\\')
}
fn pyproject(text: &str) -> Vec<ManifestDependency> {
let Ok(doc) = text.parse::<Document<String>>() else { return Vec::new() };
let mut arrays = Vec::new();
if let Some(project) = doc.get("project").and_then(Item::as_table_like) {
arrays.extend(project.get("dependencies"));
if let Some(extras) = project.get("optional-dependencies").and_then(Item::as_table_like) {
arrays.extend(extras.iter().map(|(_, item)| item));
}
}
// PEP 735 groups; `{ include-group = "…" }` entries aren't strings and are skipped.
if let Some(groups) = doc.get("dependency-groups").and_then(Item::as_table_like) {
arrays.extend(groups.iter().map(|(_, item)| item));
}
let mut out = Vec::new();
for value in arrays.into_iter().filter_map(Item::as_array).flat_map(|a| a.iter()) {
let (Some(requirement), Some(span)) = (value.as_str(), value.span()) else { continue };
let Some(raw) = text.get(span.clone()) else { continue };
let delimiter = if raw.starts_with("\"\"\"") || raw.starts_with("'''") { 3 } else { 1 };
if let Some(mut dep) = named(requirement.trim()) {
dep.from = utf16(text, span.start + delimiter);
dep.to = utf16(text, span.end - delimiter);
out.push(dep);
}
}
out.sort_unstable_by_key(|d| d.from);
out
}
#[cfg(test)]
mod tests {
use super::*;
fn names(deps: &[ManifestDependency], text: &str) -> Vec<(String, String)> {
let units: Vec<u16> = text.encode_utf16().collect();
deps.iter()
.map(|d| {
let span = String::from_utf16(&units[d.from as usize..d.to as usize]).unwrap();
assert_eq!(span, d.requirement, "span matches the requirement");
(d.package.clone(), d.requirement.clone())
})
.collect()
}
#[test]
fn requirements_txt_keeps_named_requirements_only() {
let text = "# 中文 😀 comment\n\
Django>=4.2,<5 # web\n\
typing_extensions\n\
requests[socks]==2.31.0 ; python_version >= \"3.8\"\n\
-r base.txt\n\
--index-url https://pypi.org/simple\n\
-e ./local\n\
./pkg\n\
/abs/path\n\
https://example.com/x.tar.gz\n\
foo-1.0-py3-none-any.whl\n\
pkg @ https://example.com/pkg.zip\n\
numpy==1.26.4 \\\n --hash=sha256:abc \\\n --hash=sha256:def\n\
\n \n\
black --config-settings=x=y\n";
let deps = requirements("requirements.txt", text);
assert_eq!(
names(&deps, text),
[
("Django", "Django>=4.2,<5"),
("typing_extensions", "typing_extensions"),
("requests", "requests[socks]==2.31.0 ; python_version >= \"3.8\""),
("pkg", "pkg @ https://example.com/pkg.zip"),
("numpy", "numpy==1.26.4"),
("black", "black"),
]
.map(|(a, b)| (a.to_owned(), b.to_owned()))
);
}
#[test]
fn requirements_files_by_name() {
assert!(is_requirements_file("requirements.txt"));
assert!(is_requirements_file("requirements-dev.txt"));
assert!(!is_requirements_file("constraints.txt"));
assert!(requirements("notes.txt", "django\n").is_empty());
}
#[test]
fn pyproject_project_extras_and_groups() {
let text = r#"[build-system]
requires = ["setuptools"]
[project]
name = "demo"
dependencies = [
"flask>=3", # 注释
'PyYAML',
"local @ file:///tmp/x",
]
[project.optional-dependencies]
test = ["pytest>=8; python_version>='3.9'"]
[dependency-groups]
dev = ["ruff", { include-group = "test" }]
[tool.poetry.dependencies]
ignored = "^1"
"#;
let deps = requirements("pyproject.toml", text);
assert_eq!(
names(&deps, text),
[
("flask", "flask>=3"),
("PyYAML", "PyYAML"),
("local", "local @ file:///tmp/x"),
("pytest", "pytest>=8; python_version>='3.9'"),
("ruff", "ruff"),
]
.map(|(a, b)| (a.to_owned(), b.to_owned()))
);
assert!(requirements("pyproject.toml", "[project\n").is_empty());
}
}
+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 test` runs Vitest and `cargo test --workspace`; `mise run check` runs the format, lint, type and unused-code checks, then both test suites. Neither requires nextest or the plugin WASM target.
Run `mise tasks` to list all tasks. `mise run build` builds the frontend (not a desktop installer); `mise run dogfood:build` and `mise run dogfood:install` build and locally install a grey-icon dogfood desktop app that shares settings and data with the release app. Only one of the two apps runs at a time, since they share one instance; settings written by the newer dogfood build can make an older release ignore the settings file. The dogfood app never updates itself: run `dogfood:install` again to pick up new changes. `mise run dogfood:remote <remote_name>` builds and stages `openidea-server` on an SSH host configured in **Tools › SSH Configurations** (`--clean` removes the override). `mise run test` runs Vitest and `cargo test --workspace`; `mise run check` runs the format, lint, type and unused-code checks, then both test suites. Neither requires nextest or the plugin WASM target.
## Worktrees
+1 -1
View File
@@ -88,7 +88,7 @@ All folding commands are also in **Code › Folding**. Fold regions come from th
| **Auto-Indent Lines** | `⌃⌥I` | `Ctrl+Alt+I` |
| **Optimize Imports** | `⌃⌥O` | `Ctrl+Alt+O` |
**Reformat Code** formats the selection, or the whole file when nothing is selected, as one undo step. The formatting comes from the file's language server or from the formatter the language is configured with (for example Ruff for Python, Prettier or oxfmt for web languages; find their commands as **Reformat with …** in Find Action). **Reformat File…** also lets you choose the scope and optimize imports.
**Reformat Code** formats the selection, or the whole file when nothing is selected, as one undo step. The formatting comes from the file's language server or from the formatter the language is configured with (for example Ruff for Python, Prettier, oxfmt or Biome for web languages; find their commands as **Reformat with …** in Find Action). **Reformat File…** also lets you choose the scope and optimize imports.
Indentation and other style options are under **Settings › Editor › Code Style**, with a page per language. `.editorconfig` files in the project are read too.
+1 -1
View File
@@ -62,7 +62,7 @@ When the language server cannot help, Introduce Variable and Introduce Constant
## Move, copy and rename files
In the Project view, **Rename…** (`⇧F6` / `Shift+F6`), **Move…** (`F6`, drag and drop, or cut and paste) and **Copy…** (`F5`, copy and paste, or `⌥`-drag / `Alt`-drag) open a dialog. With **Search for references** on, references to the file are updated through the language servers that support it (for example imports in TypeScript); **Search in comments and strings** also looks there. The changes are shown in a preview first.
In the Project view, **Rename…** (`⇧F6` / `Shift+F6`), **Move…** (`F6`, drag and drop, or cut and paste) and **Copy…** (`F5`, copy and paste, or `⌥`-drag / `Alt`-drag) open a dialog. With **Search for references** on, references to the file are updated through the language servers that support it (for example imports in TypeScript); Python imports are updated by the IDE itself; **Search in comments and strings** also looks there. The changes are shown in a preview first.
In the editor, **Move…** on a symbol runs the server's move refactoring, where the language has one. In Java it asks where to: a top-level class goes to another package (its package declaration, imports and every reference follow), a static member or nested class to another class, an instance method to the class of one of its fields or parameters; warnings are confirmed in **Problems Detected** first.
+4
View File
@@ -134,6 +134,10 @@ needed. The status bar then shows **WSL: `<distribution>`**.
Opening a folder under `\\wsl.localhost\<distribution>\` also opens it through the distribution.
**Browse** is not available for WSL.
The **Ports** tool window is available in a WSL window too. Because the distribution shares this machine's
`localhost`, a forwarded port is reachable here on the same port; the window lists, opens and remembers ports as it
does for SSH.
## Other uses of SSH configurations
- **Run targets** (**Settings › Build, Execution, Deployment › Run Targets**) run a configuration on an SSH host. See
+1
View File
@@ -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 |
+2 -2
View File
@@ -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, `node --test`, Mocha, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks.
## Navigate between code and tests
+87 -87
View File
@@ -34,7 +34,7 @@ For a recognized file, support comes in layers:
A language can list more than one server:
- **Alternatives** (shown as `a → b` in the table below): only the first one that is installed runs. Python, for example, uses basedpyright, and falls back to pyright, ty or pyrefly only when basedpyright is missing. In **Settings › Languages & Frameworks › Language Servers** you can pick one of them or set the choice to **Automatic** (the first one available).
- **Additions** (shown as `+ b`): run next to the main server, usually only in projects that use them. Ruff joins basedpyright in projects with a Ruff configuration; oxlint joins vtsls in projects with an oxlint configuration; the Angular and Laravel servers join in Angular and Laravel projects.
- **Additions** (shown as `+ b`): run next to the main server, usually only in projects that use them. Ruff joins basedpyright in projects with a Ruff configuration; oxlint joins vtsls in projects with an oxlint configuration; Biome joins the JavaScript, TypeScript, JSON, CSS and GraphQL servers in projects with a Biome configuration or installation; the Angular, Laravel and Tailwind CSS servers join in Angular, Laravel and Tailwind CSS projects.
## Installing language servers and debuggers
@@ -91,92 +91,92 @@ Selecting a language server on the Language Servers page shows its settings, whi
The table lists every built-in language definition. Server and debugger names in **bold** can be installed from the IDE; the others you install yourself (the install hint in the IDE says how). "Highlighting" and "Tree-sitter" mark instant highlighting and the bundled grammar for outline and folding.
| Language | ID | Files | Highlighting | Tree-sitter | Language servers | Debugger |
| ------------------- | ------------------ | ----------------------------------------------------------- | ------------ | ----------- | ------------------------------------------------------------------------------------- | ------------------------ |
| .env | `dotenv` | `.env` | Yes | — | — | — |
| Arduino | `arduino` | `.ino` | Yes | Yes | arduino-language-server | — |
| AsciiDoc | `asciidoc` | `.adoc`, `.asciidoc` | Yes | — | — | — |
| Astro | `astro` | `.astro` | Yes | — | **astro-ls** + **oxlint** | — |
| Batch | `bat` | `.bat`, `.cmd` | Yes | — | — | — |
| C | `c` | `.c`, `.h` | Yes | Yes | **clangd** | lldb-dap |
| C# | `csharp` | `.cs`, `.csx` | Yes | Yes | **csharp-ls** | **netcoredbg** |
| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | Yes | Yes | **clangd** | lldb-dap |
| Clojure | `clojure` | `.clj`, `.cljs`, `.cljc`, `.cljd`, `.edn`, … | Yes | — | **clojure-lsp** | — |
| CMake | `cmake` | `.cmake` | Yes | Yes | **neocmakelsp** → cmake-language-server | — |
| CSS | `css` | `.css`, `.pcss`, `.postcss` | Yes | Yes | **vscode-css-language-server** | — |
| D | `d` | `.d`, `.di` | Yes | — | serve-d | — |
| Dart | `dart` | `.dart` | Yes | Yes | dart | dart |
| Diff | `diff` | `.diff`, `.patch`, `.rej` | Yes | — | — | — |
| Django Template | `django-html` | `.djhtml`, `templates/*.html`, `*.txt` | Yes | Yes | **vscode-html-language-server**, **djlsp** | — |
| Dockerfile | `dockerfile` | `.dockerfile`, `.containerfile` | Yes | — | **dockerfile-language-server** | — |
| Elixir | `elixir` | `.ex`, `.exs` | Yes | Yes | **elixir-ls** | **elixir-ls-debugger** |
| ERB | `erb` | `.erb`, `.html.erb`, `.rhtml`, `.js.erb`, `.text.erb`, … | Yes | — | — | — |
| Erlang | `erlang` | `.erl`, `.hrl`, `.escript`, `.app.src` | Yes | — | elp | — |
| F# | `fsharp` | `.fs`, `.fsi`, `.fsx` | Yes | — | **fsautocomplete** | **netcoredbg** |
| GDScript | `gdscript` | `.gd` | Yes | Yes | godot | godot |
| Git Attributes | `gitattributes` | `.gitattributes` | — | — | — | — |
| Go | `go` | `.go` | Yes | Yes | **gopls** | **delve** |
| Go Module | `go.mod` | `go.mod` | Yes | — | **gopls** | — |
| Go Workspace | `go.work` | `go.work` | Yes | — | **gopls** | — |
| Godot Resource | `godot-resource` | `.tscn`, `.tres`, `.godot`, `.import` | Yes | — | — | — |
| Godot Shader | `gdshader` | `.gdshader`, `.gdshaderinc` | Yes | — | — | — |
| GraphQL | `graphql` | `.graphql`, `.graphqls`, `.gql` | Yes | Yes | **graphql-lsp** | — |
| Groovy | `groovy` | `.groovy`, `.gradle`, `.gvy`, `.gy`, `.gsh` | Yes | — | groovy-language-server | — |
| Haskell | `haskell` | `.hs`, `.hs-boot`, `.hsig` | Yes | Yes | haskell-language-server | — |
| HCL | `hcl` | `.hcl`, `.nomad`, `.pkr.hcl` | Yes | Yes | — | — |
| HTML | `html` | `.html`, `.htm`, `.xhtml`, `.shtml`, `.html.tmpl` | Yes | Yes | **vscode-html-language-server** + **angular-language-server** | — |
| HTTP Request | `http` | `.http`, `.rest` | Yes | — | — | — |
| Ignore File | `ignore` | `.gitignore`, `.dockerignore` | — | — | — | — |
| INI | `ini` | `.ini`, `.cfg`, `.conf`, `.cnf`, `.inf`, … | Yes | — | — | — |
| Java | `java` | `.java` | Yes | Yes | **jdtls** → **java-analyzer** → **kmp-lsp** | **java-debug** |
| JavaScript | `javascript` | `.js`, `.mjs`, `.cjs` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** |
| JavaScript JSX | `javascriptreact` | `.jsx` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** |
| JSON | `json` | `.json`, `.geojson`, `.topojson`, `.webmanifest`, `.har`, … | Yes | Yes | **vscode-json-language-server** | — |
| JSON with Comments | `jsonc` | `.jsonc`, `.code-workspace`, `.code-snippets` | Yes | Yes | **vscode-json-language-server** | — |
| JSP | `jsp` | `.jsp`, `.jspx`, `.jspf`, `.jsph`, `.tag`, … | Yes | — | — | — |
| Julia | `julia` | `.jl` | Yes | — | julia-languageserver | — |
| Kotlin | `kotlin` | `.kt`, `.kts` | Yes | Yes | **kotlin-lsp** → **kotlin-language-server** → **kmp-lsp** | **kotlin-debug-adapter** |
| LaTeX | `latex` | `.tex`, `.ltx`, `.sty`, `.cls`, `.dtx`, … | Yes | — | **texlab** | — |
| Less | `less` | `.less` | Yes | — | **vscode-css-language-server** | — |
| Log | `log` | `.log` | Yes | — | — | — |
| Lua | `lua` | `.lua`, `.luau`, `.rockspec` | Yes | Yes | **lua-language-server** | — |
| Makefile | `makefile` | `.mk`, `.mak`, `.make` | Yes | Yes | — | — |
| Markdown | `markdown` | `.md`, `.markdown`, `.mdown`, `.mkd`, `.mkdn`, … | Yes | Yes | **marksman** | — |
| Nix | `nix` | `.nix` | Yes | Yes | nil → nixd | — |
| Objective-C | `objective-c` | `.m` | Yes | — | **clangd** | lldb-dap |
| Objective-C++ | `objective-cpp` | `.mm` | Yes | — | **clangd** | lldb-dap |
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | Yes | Yes | ocamllsp | ocamlearlybird |
| OCaml Interface | `ocaml.interface` | `.mli` | Yes | Yes | ocamllsp | — |
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | Yes | — | **perlnavigator** | — |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | Yes | Yes | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** |
| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — |
| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | Yes | — | powershell-editor-services | — |
| Prisma | `prisma` | `.prisma` | Yes | Yes | **prisma-language-server** | — |
| Properties | `properties` | `.properties`, `.prefs` | Yes | — | — | — |
| Protocol Buffers | `proto` | `.proto` | Yes | Yes | **buf** | — |
| Python | `python` | `.py`, `.pyi`, `.pyw` | Yes | Yes | **basedpyright** → **pyright** → **ty** → **pyrefly** + **ruff** | **debugpy** |
| R | `r` | `.r`, `.rprofile` | Yes | — | r-languageserver | — |
| reStructuredText | `restructuredtext` | `.rst` | Yes | — | — | — |
| Ruby | `ruby` | `.rb`, `.rake`, `.gemspec`, `.ru`, `.rbi`, … | Yes | Yes | **ruby-lsp** → **solargraph** | rdbg |
| Rust | `rust` | `.rs` | Yes | Yes | **rust-analyzer** | **codelldb** |
| Sass | `sass` | `.sass` | Yes | — | — | — |
| Scala | `scala` | `.scala`, `.sc`, `.sbt`, `.mill` | Yes | Yes | metals | — |
| SCSS | `scss` | `.scss` | Yes | — | **vscode-css-language-server** | — |
| Shell Script | `shellscript` | `.sh`, `.bash`, `.zsh`, `.ksh`, `.ash`, … | Yes | Yes | **bash-language-server** | **bash-debug** |
| Slint | `slint` | `.slint` | Yes | — | **slint-lsp** | — |
| SQL | `sql` | `.sql`, `.ddl`, `.dml`, `.psql`, `.pgsql`, … | Yes | — | **sqls** | — |
| Svelte | `svelte` | `.svelte` | Yes | — | **svelte-language-server** + **oxlint** | — |
| Swift | `swift` | `.swift`, `.swiftinterface` | Yes | Yes | sourcekit-lsp | lldb-dap |
| Terraform | `terraform` | `.tf`, `.tofu`, `.tftest.hcl` | Yes | Yes | **terraform-ls** | — |
| Terraform Variables | `terraform-vars` | `.tfvars` | Yes | Yes | **terraform-ls** | — |
| TOML | `toml` | `.toml` | Yes | Yes | **taplo** | — |
| TypeScript | `typescript` | `.ts`, `.mts`, `.cts` | Yes | Yes | **vtsls** → **typescript-language-server** + **angular-language-server** + **oxlint** | **js-debug** |
| TypeScript JSX | `typescriptreact` | `.tsx` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** |
| Typst | `typst` | `.typ` | — | — | **tinymist** | — |
| Vue | `vue` | `.vue` | Yes | — | **vue-language-server**, **vtsls** + **oxlint** | — |
| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | Yes | Yes | **lemminx** | — |
| YAML | `yaml` | `.yaml`, `.yml` | Yes | Yes | **yaml-language-server** | — |
| Zig | `zig` | `.zig`, `.zon` | Yes | Yes | **zls** | **codelldb** |
| Language | ID | Files | Highlighting | Tree-sitter | Language servers | Debugger |
| ------------------- | ------------------ | ----------------------------------------------------------- | ------------ | ----------- | ------------------------------------------------------------------------------------------------- | ------------------------ |
| .env | `dotenv` | `.env` | Yes | — | — | — |
| Arduino | `arduino` | `.ino` | Yes | Yes | arduino-language-server | — |
| AsciiDoc | `asciidoc` | `.adoc`, `.asciidoc` | Yes | — | — | — |
| Astro | `astro` | `.astro` | Yes | — | **astro-ls** + **oxlint** | — |
| Batch | `bat` | `.bat`, `.cmd` | Yes | — | — | — |
| C | `c` | `.c`, `.h` | Yes | Yes | **clangd** | lldb-dap |
| C# | `csharp` | `.cs`, `.csx` | Yes | Yes | **csharp-ls** | **netcoredbg** |
| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | Yes | Yes | **clangd** | lldb-dap |
| Clojure | `clojure` | `.clj`, `.cljs`, `.cljc`, `.cljd`, `.edn`, … | Yes | — | **clojure-lsp** | — |
| CMake | `cmake` | `.cmake` | Yes | Yes | **neocmakelsp** → cmake-language-server | — |
| CSS | `css` | `.css`, `.pcss`, `.postcss` | Yes | Yes | **vscode-css-language-server** + **biome** | — |
| D | `d` | `.d`, `.di` | Yes | — | serve-d | — |
| Dart | `dart` | `.dart` | Yes | Yes | dart | dart |
| Diff | `diff` | `.diff`, `.patch`, `.rej` | Yes | — | — | — |
| Django Template | `django-html` | `.djhtml`, `templates/*.html`, `*.txt` | Yes | Yes | **vscode-html-language-server**, **djlsp** | — |
| Dockerfile | `dockerfile` | `.dockerfile`, `.containerfile` | Yes | — | **dockerfile-language-server** | — |
| Elixir | `elixir` | `.ex`, `.exs` | Yes | Yes | **elixir-ls** | **elixir-ls-debugger** |
| ERB | `erb` | `.erb`, `.html.erb`, `.rhtml`, `.js.erb`, `.text.erb`, … | Yes | — | — | — |
| Erlang | `erlang` | `.erl`, `.hrl`, `.escript`, `.app.src` | Yes | — | elp | — |
| F# | `fsharp` | `.fs`, `.fsi`, `.fsx` | Yes | — | **fsautocomplete** | **netcoredbg** |
| GDScript | `gdscript` | `.gd` | Yes | Yes | godot | godot |
| Git Attributes | `gitattributes` | `.gitattributes` | — | — | — | — |
| Go | `go` | `.go` | Yes | Yes | **gopls** | **delve** |
| Go Module | `go.mod` | `go.mod` | Yes | — | **gopls** | — |
| Go Workspace | `go.work` | `go.work` | Yes | — | **gopls** | — |
| Godot Resource | `godot-resource` | `.tscn`, `.tres`, `.godot`, `.import` | Yes | — | — | — |
| Godot Shader | `gdshader` | `.gdshader`, `.gdshaderinc` | Yes | — | — | — |
| GraphQL | `graphql` | `.graphql`, `.graphqls`, `.gql` | Yes | Yes | **graphql-lsp** + **biome** | — |
| Groovy | `groovy` | `.groovy`, `.gradle`, `.gvy`, `.gy`, `.gsh` | Yes | — | groovy-language-server | — |
| Haskell | `haskell` | `.hs`, `.hs-boot`, `.hsig` | Yes | Yes | haskell-language-server | — |
| HCL | `hcl` | `.hcl`, `.nomad`, `.pkr.hcl` | Yes | Yes | — | — |
| HTML | `html` | `.html`, `.htm`, `.xhtml`, `.shtml`, `.html.tmpl` | Yes | Yes | **vscode-html-language-server** + **angular-language-server** | — |
| HTTP Request | `http` | `.http`, `.rest` | Yes | — | — | — |
| Ignore File | `ignore` | `.gitignore`, `.dockerignore` | — | — | — | — |
| INI | `ini` | `.ini`, `.cfg`, `.conf`, `.cnf`, `.inf`, … | Yes | — | — | — |
| Java | `java` | `.java` | Yes | Yes | **jdtls** → **java-analyzer** → **kmp-lsp** | **java-debug** |
| JavaScript | `javascript` | `.js`, `.mjs`, `.cjs` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** |
| JavaScript JSX | `javascriptreact` | `.jsx` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** |
| JSON | `json` | `.json`, `.geojson`, `.topojson`, `.webmanifest`, `.har`, … | Yes | Yes | **vscode-json-language-server** + **biome** | — |
| JSON with Comments | `jsonc` | `.jsonc`, `.code-workspace`, `.code-snippets` | Yes | Yes | **vscode-json-language-server** + **biome** | — |
| JSP | `jsp` | `.jsp`, `.jspx`, `.jspf`, `.jsph`, `.tag`, … | Yes | — | — | — |
| Julia | `julia` | `.jl` | Yes | — | julia-languageserver | — |
| Kotlin | `kotlin` | `.kt`, `.kts` | Yes | Yes | **kotlin-lsp** → **kotlin-language-server** → **kmp-lsp** | **kotlin-debug-adapter** |
| LaTeX | `latex` | `.tex`, `.ltx`, `.sty`, `.cls`, `.dtx`, … | Yes | — | **texlab** | — |
| Less | `less` | `.less` | Yes | — | **vscode-css-language-server** | — |
| Log | `log` | `.log` | Yes | — | — | — |
| Lua | `lua` | `.lua`, `.luau`, `.rockspec` | Yes | Yes | **lua-language-server** | — |
| Makefile | `makefile` | `.mk`, `.mak`, `.make` | Yes | Yes | — | — |
| Markdown | `markdown` | `.md`, `.markdown`, `.mdown`, `.mkd`, `.mkdn`, … | Yes | Yes | **marksman** | — |
| Nix | `nix` | `.nix` | Yes | Yes | nil → nixd | — |
| Objective-C | `objective-c` | `.m` | Yes | — | **clangd** | lldb-dap |
| Objective-C++ | `objective-cpp` | `.mm` | Yes | — | **clangd** | lldb-dap |
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | Yes | Yes | ocamllsp | ocamlearlybird |
| OCaml Interface | `ocaml.interface` | `.mli` | Yes | Yes | ocamllsp | — |
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | Yes | — | **perlnavigator** | — |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | Yes | Yes | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** |
| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — |
| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | Yes | — | powershell-editor-services | — |
| Prisma | `prisma` | `.prisma` | Yes | Yes | **prisma-language-server** | — |
| Properties | `properties` | `.properties`, `.prefs` | Yes | — | — | — |
| Protocol Buffers | `proto` | `.proto` | Yes | Yes | **buf** | — |
| Python | `python` | `.py`, `.pyi`, `.pyw` | Yes | Yes | **basedpyright** → **pyright** → **ty** → **pyrefly** + **ruff** | **debugpy** |
| R | `r` | `.r`, `.rprofile` | Yes | — | r-languageserver | — |
| reStructuredText | `restructuredtext` | `.rst` | Yes | — | — | — |
| Ruby | `ruby` | `.rb`, `.rake`, `.gemspec`, `.ru`, `.rbi`, … | Yes | Yes | **ruby-lsp** → **solargraph** | rdbg |
| Rust | `rust` | `.rs` | Yes | Yes | **rust-analyzer** | **codelldb** |
| Sass | `sass` | `.sass` | Yes | — | — | — |
| Scala | `scala` | `.scala`, `.sc`, `.sbt`, `.mill` | Yes | Yes | metals | — |
| SCSS | `scss` | `.scss` | Yes | — | **vscode-css-language-server** | — |
| Shell Script | `shellscript` | `.sh`, `.bash`, `.zsh`, `.ksh`, `.ash`, … | Yes | Yes | **bash-language-server** | **bash-debug** |
| Slint | `slint` | `.slint` | Yes | — | **slint-lsp** | — |
| SQL | `sql` | `.sql`, `.ddl`, `.dml`, `.psql`, `.pgsql`, … | Yes | — | **sqls** | — |
| Svelte | `svelte` | `.svelte` | Yes | — | **svelte-language-server** + **oxlint** | — |
| Swift | `swift` | `.swift`, `.swiftinterface` | Yes | Yes | sourcekit-lsp | lldb-dap |
| Terraform | `terraform` | `.tf`, `.tofu`, `.tftest.hcl` | Yes | Yes | **terraform-ls** | — |
| Terraform Variables | `terraform-vars` | `.tfvars` | Yes | Yes | **terraform-ls** | — |
| TOML | `toml` | `.toml` | Yes | Yes | **taplo** | — |
| TypeScript | `typescript` | `.ts`, `.mts`, `.cts` | Yes | Yes | **vtsls** → **typescript-language-server** + **angular-language-server** + **oxlint** + **biome** | **js-debug** |
| TypeScript JSX | `typescriptreact` | `.tsx` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** |
| Typst | `typst` | `.typ` | — | — | **tinymist** | — |
| Vue | `vue` | `.vue` | Yes | — | **vue-language-server**, **vtsls** + **oxlint** | — |
| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | Yes | Yes | **lemminx** | — |
| YAML | `yaml` | `.yaml`, `.yml` | Yes | Yes | **yaml-language-server** | — |
| Zig | `zig` | `.zig`, `.zon` | Yes | Yes | **zls** | **codelldb** |
Notes:
+23 -14
View File
@@ -7,16 +7,18 @@ OpenIDEA edits JavaScript (`.js`, `.mjs`, `.cjs`, `.jsx`) and TypeScript (`.ts`,
## Language servers
| Files | Server | Notes |
| ------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| JS, JSX, TS, TSX | `vtsls` | Default TypeScript server. |
| JS, JSX, TS, TSX | `typescript-language-server` | Fallback: used only while `vtsls` is not installed. |
| `.vue` | `vue-language-server` + `vtsls` | Vue's hybrid mode: TypeScript inside `.vue` files comes from `vtsls` with `@vue/typescript-plugin`. |
| `.svelte` | `svelte-language-server` | |
| `.astro` | `astro-ls` | Needs Node.js and a TypeScript library. |
| TS and HTML in Angular projects | `angular-language-server` (`ngserver`) | Only below `angular.json` or `node_modules/@angular/core`. |
| All of the above | `oxlint` | Only below an `.oxlintrc.json`, `.oxlintrc.jsonc`, `oxlint.config.ts` or `oxlint.config.mts`. |
| All of the above | `vscode-eslint-language-server` (ESLint) | Only below an ESLint configuration (`eslint.config.*`, `.eslintrc*` or `eslintConfig` in `package.json`); runs the project's own `eslint`. |
| Files | Server | Notes |
| ------------------------------- | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| JS, JSX, TS, TSX | `vtsls` | Default TypeScript server. |
| JS, JSX, TS, TSX | `typescript-language-server` | Fallback: used only while `vtsls` is not installed. |
| `.vue` | `vue-language-server` + `vtsls` | Vue's hybrid mode: TypeScript inside `.vue` files comes from `vtsls` with `@vue/typescript-plugin`. |
| `.svelte` | `svelte-language-server` | |
| `.astro` | `astro-ls` | Needs Node.js and a TypeScript library. |
| TS and HTML in Angular projects | `angular-language-server` (`ngserver`) | Only below `angular.json` or `node_modules/@angular/core`. |
| All of the above | `oxlint` | Only below an `.oxlintrc.json`, `.oxlintrc.jsonc`, `oxlint.config.ts` or `oxlint.config.mts`. |
| All of the above | `vscode-eslint-language-server` (ESLint) | Only below an ESLint configuration (`eslint.config.*`, `.eslintrc*` or `eslintConfig` in `package.json`); runs the project's own `eslint`. |
| JS, JSX, TS, TSX, JSON, CSS | `biome lsp-proxy` (Biome) | Only below a `biome.json` / `biome.jsonc` or an installed `@biomejs/biome`; runs the project's own `biome`. |
| All of the above, HTML and CSS | `tailwindcss-language-server` (Tailwind CSS) | Only below a `tailwind.config.*` or a `package.json` that depends on `tailwindcss`: class completion, hover with the generated CSS, and class diagnostics. |
The TypeScript servers start for a workspace marked by `tsconfig.json`, `jsconfig.json` or `package.json`. Files outside any `tsconfig.json` / `jsconfig.json` are still registered with tsserver, so loose scripts get code insight too.
@@ -47,7 +49,8 @@ All servers, debuggers and formatters are listed in **Settings › Languages & F
| `vtsls`, `typescript-language-server` | npm (`@vtsls/language-server`; `typescript-language-server` + `typescript@6`) |
| `vue-language-server`, `svelte-language-server`, `astro-ls`, `angular-language-server` | npm |
| `oxlint` | npm |
| Prettier, oxfmt | npm |
| `tailwindcss-language-server` | npm (`@tailwindcss/language-server`) |
| Prettier, oxfmt, Biome | npm |
| JavaScript Debugger (vscode-js-debug) | GitHub release (`microsoft/vscode-js-debug`) |
The Astro and Angular servers also run from the project's own `node_modules/.bin` when it has them.
@@ -67,14 +70,20 @@ The Astro and Angular servers also run from the project's own `node_modules/.bin
- **Prettier** (**Settings › Languages & Frameworks › Prettier**) formats JavaScript, JSX, TypeScript, TSX, JSON, Vue, HTML, CSS, SCSS, Less, GraphQL, YAML and Markdown by default. The executable is found in the project's `node_modules`, then the managed installation, then `PATH`, unless you set **Prettier path**.
- **oxfmt** (**Settings › Languages & Frameworks › oxfmt**) replaces Prettier for an enabled language in files below an oxfmt configuration (`.oxfmtrc.json`, `oxfmt.config.ts`), or when it is the selected provider.
- **Biome** (**Settings › Languages & Frameworks › Biome**) replaces Prettier and oxfmt for JavaScript, JSX, TypeScript, TSX, JSON, CSS and GraphQL in files below a `biome.json` / `biome.jsonc` or an installed `@biomejs/biome` (unless the configuration sets `formatter.enabled` to `false`), or when it is the selected provider. It formats whole files and reads its own configuration.
On both pages, **Formatting provider** chooses between **Automatic (language server first)** and the tool itself, **Run on save** formats on save, and **Enabled languages** limits which languages the tool handles.
On these pages, **Formatting provider** chooses between **Automatic (language server first)** and the tool itself, **Run on save** formats on save, and **Enabled languages** limits which languages the tool handles.
### Biome lint
In a Biome project, Biome's diagnostics show in the editor and the Problems tool window, and `⌥⏎` / `Alt+Enter` offers its quick fixes and suppressions. Biome's safe fixes (`source.fixAll.biome`) run with **Code › Code Cleanup** and, when **Settings › Tools › Actions on Save › Run code cleanup** is on, on save. When Biome's formatter is enabled, its fix-all formats the file too.
## Run and test
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`, `node --test` or `mocha`, are test configurations.
- `playwright test` (through `npx`) for a package with a `playwright.config.*` that no script runs.
- One per task in `deno.json` / `deno.jsonc` (`deno task <name>`).
In `package.json`, the gutter shows run icons on each `scripts` entry to run or debug it.
@@ -85,7 +94,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, 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 in projects that test with Mocha or `node --test`, tests in `test/` get gutter icons whatever their file name. **Run with Coverage** works for scripts that run `vitest` or `jest` (Vitest needs a coverage provider such as `@vitest/coverage-v8`; the IDE offers to add it) and for `node` / `tsx` / `ts-node` runs through `c8`. See [Testing](/en/guide/testing) and [Coverage](/en/guide/coverage).
## Debugging
+2
View File
@@ -21,6 +21,8 @@ basedpyright starts in its `standard` type-checking mode instead of its own stri
Ruff starts only for files below a Ruff configuration: a `ruff.toml`, a `.ruff.toml`, or a `pyproject.toml` that contains a `[tool.ruff]` table. basedpyright has no formatter, so formatting comes from Ruff.
Moving or renaming a module or package in the Project view with **Search for references** on updates the `import` and `from … import` statements that refer to it, relative imports included, in the same preview as the move. basedpyright has no file-move support, so the IDE finds these imports itself from the syntax tree. When a rename changes the name an import binds, the import keeps it as an alias: `from pkg import models` becomes `from pkg import domain as models`.
To pick the type checker yourself, open **Settings › Languages & Frameworks › Language Servers**, select any of the four servers and change **Language server for Python**. **Automatic** uses the first installed one in the order above; you can also choose one server or **None**.
## Setup
+8 -8
View File
@@ -297,14 +297,14 @@ launching as before.
## Running programs
| Function | What it does |
| ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- |
| `Project::run_process(program, &args, stdin)` | Runs the pinned program in the project root and waits: `{ status, stdout, stderr }`, 4 MiB each. |
| `host::run_command(&Command, Some(&project), stdin)` | API 1.3: the same, with environment variables added by `Command::env`. |
| `host::run_captured(&Command, Some(&project), stdin, options)` | API 1.15: configurable output limit (up to 128 MiB per stream); errors explicitly if either stdout or stderr overflows. |
| `host::start(&Command, Some(&project))` | API 1.3: a `Child` left running: `poll`, `write`, `close_stdin`, `wait`, `kill`. At most 8. |
| `host::start_stream(&Command, Some(&project), options)` | API 1.15: lossless streaming with backpressure and bounded buffer, terminating with an explicit error on total overflow.|
| `host::open_terminal(title, program, &args)` | A Terminal tab running the program (see [Views](/en/plugins/guides/views)). |
| Function | What it does |
| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `Project::run_process(program, &args, stdin)` | Runs the pinned program in the project root and waits: `{ status, stdout, stderr }`, 4 MiB each. |
| `host::run_command(&Command, Some(&project), stdin)` | API 1.3: the same, with environment variables added by `Command::env`. |
| `host::run_captured(&Command, Some(&project), stdin, options)` | API 1.15: configurable output limit (up to 128 MiB per stream); errors explicitly if either stdout or stderr overflows. |
| `host::start(&Command, Some(&project))` | API 1.3: a `Child` left running: `poll`, `write`, `close_stdin`, `wait`, `kill`. At most 8. |
| `host::start_stream(&Command, Some(&project), options)` | API 1.15: lossless streaming with backpressure and bounded buffer, terminating with an explicit error on total overflow. |
| `host::open_terminal(title, program, &args)` | A Terminal tab running the program (see [Views](/en/plugins/guides/views)). |
```rust
use openidea_plugin::host::{self, Command};
+1
View File
@@ -124,6 +124,7 @@ Each contribution point is a table (`[contributes.settings]`) or an array of tab
| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?` | no | [Run targets](/en/plugins/guides/run-targets) |
| `runConfigurations` | `files` (API 1.4) | yes | [Run targets](/en/plugins/guides/run-targets) |
| `javaAgents` | `path`, `args?` (API 1.10); `vmOptions?`, `jdk?` (API 1.14) | no | [README: Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) |
| `skills` | `path` (`skills/<name>/SKILL.md`, API 1.15) | no | [README: API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) |
| `mcpTools` | `name`, `description`, `inputSchema`, `readOnly`, `destructive` (API 1.4) | yes | [MCP tools](/en/plugins/guides/mcp) |
| `themes` | `path`, `editor-scheme?` | no | [Themes](/en/plugins/guides/themes) |
| `iconThemes` | `id`, `label`, `path` | no | [Icon themes](/en/plugins/guides/icon-themes) |
+1
View File
@@ -29,6 +29,7 @@ The plugin API has one version number: the version of the WIT package in [`wit/`
| 1.12.0 | In development on `main` | `ui.set-console-rules`: highlight rules (regex, palette colours, styles) for Run and Debug console output |
| 1.13.0 | OpenIDEA 0.1.49 | Optional `search-provider` export and `searchCategories`: custom Search Everywhere tabs with cancellable queries |
| 1.14.0 | In development on `main` | Optional `hover-actions` export: left-edge line actions revealed by line-edge hover, with an anchor line and inclusive trigger range; `[[contributes.javaAgents]]` `vmOptions` / `jdk`: JVM flags (optionally JetBrains Runtime–only) before `-javaagent:`; `ui.set-status-item-menu` / `set-window-status-item-menu`: a menu on a status bar item |
| 1.15.0 | In development on `main` | `caret-moved` event; declarative `[[contributes.skills]]` (`path = "skills/<name>/SKILL.md"`) for bundling agent skills in plugins |
The full list of what each version added is in [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md).
+1 -1
View File
@@ -55,7 +55,7 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"]
| Plugins | Plugins |
| Version Control | Commit; Confirmation; Directory Mappings; Issue Navigation; Log; Shelf; Git; GitHub |
| Build, Execution, Deployment | CMake; Gradle; Maven; Console; Debugger (Data Views, Stepping); Python Debugger; Run/Debug; Run Targets; Deployment (Options) |
| Languages & Frameworks | Language Servers; Go (Build Tags, Go Modules); Java; Markdown; Node.js; PHP; Python Interpreter; Prettier; oxfmt; Ruff; Ruby; Rust; TypeScript |
| Languages & Frameworks | Language Servers; Go (Build Tags, Go Modules); Java; Markdown; Node.js; PHP; Python Interpreter; Prettier; oxfmt; Biome; Ruff; Ruby; Rust; TypeScript |
| Tools | Agents (Chat); Terminal; Actions on Save; External Tools; SSH Configurations; MCP Server |
| Security | Project Trust |
+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 test` 运行 Vitest 和 `cargo test --workspace`;`mise run check` 先检查格式、代码规范、类型和未使用的代码,再运行这两套测试。两者都不需要 nextest 或插件的 WASM 目标。
运行 `mise tasks` 可以查看全部任务。`mise run build` 构建前端,不生成桌面安装包;`mise run dogfood:build` 和 `mise run dogfood:install` 用于构建并在本地安装灰色图标的 dogfood 桌面版(与正式版共享设置和数据)。两者共用同一个实例,同一时间只能运行一个;较新的 dogfood 版写入的设置可能让较旧的正式版忽略整个设置文件。dogfood 版不会自动更新,需要更新时重新运行 `dogfood:install`。`mise run dogfood:remote <remote_name>` 在 **工具 › SSH 配置** 中指定的远程主机上构建并部署 `openidea-server`(`--clean` 可移除覆盖)。`mise run test` 运行 Vitest 和 `cargo test --workspace`;`mise run check` 先检查格式、代码规范、类型和未使用的代码,再运行这两套测试。两者都不需要 nextest 或插件的 WASM 目标。
## Worktree
+1 -1
View File
@@ -88,7 +88,7 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
| **自动缩进行** | `⌃⌥I` | `Ctrl+Alt+I` |
| **优化导入** | `⌃⌥O` | `Ctrl+Alt+O` |
**重新格式化代码** 格式化选区,没有选区时格式化整个文件,整体算一步撤销。格式化由文件的语言服务器或该语言配置的格式化工具完成(例如 Python 用 Ruff,Web 语言用 Prettier 或 oxfmt;在查找操作里搜 **使用 … 重新格式化** 可以指定工具)。**重新格式化文件…** 还能选择范围并顺便优化导入。
**重新格式化代码** 格式化选区,没有选区时格式化整个文件,整体算一步撤销。格式化由文件的语言服务器或该语言配置的格式化工具完成(例如 Python 用 Ruff,Web 语言用 Prettier、oxfmt 或 Biome;在查找操作里搜 **使用 … 重新格式化** 可以指定工具)。**重新格式化文件…** 还能选择范围并顺便优化导入。
缩进等代码风格选项在 **设置 › 编辑器 › 代码样式** 中,每种语言一个页面。项目里的 `.editorconfig` 也会生效。
+1 -1
View File
@@ -57,7 +57,7 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
## 移动、复制和重命名文件
在项目视图中,**重命名…**(`⇧F6` / `Shift+F6`)、**移动…**(`F6`、拖放或剪切后粘贴)和 **复制…**(`F5`、复制后粘贴,或按住 `⌥` / `Alt` 拖动)会打开对话框。勾选 **搜索引用** 后,支持此功能的语言服务器会更新对该文件的引用(例如 TypeScript 的 import);**在注释和字符串中搜索** 会把注释和字符串也算进去。改动会先显示预览。
在项目视图中,**重命名…**(`⇧F6` / `Shift+F6`)、**移动…**(`F6`、拖放或剪切后粘贴)和 **复制…**(`F5`、复制后粘贴,或按住 `⌥` / `Alt` 拖动)会打开对话框。勾选 **搜索引用** 后,支持此功能的语言服务器会更新对该文件的引用(例如 TypeScript 的 import),Python 的 import 由 IDE 自己更新;**在注释和字符串中搜索** 会把注释和字符串也算进去。改动会先显示预览。
在编辑器中对符号执行 **移动…**,会调用该语言服务器的移动重构(如果有的话)。在 Java 中会先询问目标:顶层类移动到其他包(包声明、import 和所有引用随之更新),静态成员或嵌套类移动到其他类,实例方法移动到其某个字段或形参的类;有警告时先在 **检测到问题** 中确认。
+2
View File
@@ -106,6 +106,8 @@ Shell。IDE 内置的 SSH 客户端会使用配置里保存的密码、密钥或
打开 `\\wsl.localhost\<distribution>\` 下的文件夹时,也会自动通过该发行版打开。WSL 方式不支持**浏览**。
WSL 窗口中也可以使用**端口**工具窗口。由于发行版与本机的 `localhost` 相通,转发的端口在本机可用同一端口访问;端口的列表、在浏览器中打开和记忆方式与 SSH 相同。
## SSH 配置的其他用途
- **运行目标**(**设置 › 构建、执行、部署 › 运行目标**)可以在 SSH 主机上执行运行配置,见[运行配置](/zh/guide/run)。
+1
View File
@@ -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 程序和测试 |
+2 -2
View File
@@ -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、`node --test`、Mocha、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。
## 在代码和测试之间跳转
+87 -87
View File
@@ -32,7 +32,7 @@ OpenIDEA 用一个小的定义文件 `languages/<id>.toml` 描述每种语言:
一种语言可以配置多个服务器:
- **备选**(下表中写作 `a → b`):只运行第一个已安装的。例如 Python 默认用 basedpyright,只有它缺失时才退回 pyright、ty 或 pyrefly。在 **设置 › 语言和框架 › 语言服务器** 中可以指定其中一个,或选 **自动**(使用第一个可用的)。
- **附加**(写作 `+ b`):和主服务器同时运行,通常只在用到它的项目中启用。带 Ruff 配置的项目里 Ruff 与 basedpyright 一起运行;带 oxlint 配置的项目里 oxlint 与 vtsls 一起运行;Angular 和 Laravel 项目里分别加上 Angular 和 Laravel 的服务器。
- **附加**(写作 `+ b`):和主服务器同时运行,通常只在用到它的项目中启用。带 Ruff 配置的项目里 Ruff 与 basedpyright 一起运行;带 oxlint 配置的项目里 oxlint 与 vtsls 一起运行;带 Biome 配置或安装了 Biome 的项目里 Biome 与 JavaScript、TypeScript、JSON、CSS 和 GraphQL 的服务器一起运行;Angular、Laravel 和 Tailwind CSS 项目里分别加上 Angular、Laravel 和 Tailwind CSS 的服务器。
## 安装语言服务器和调试器
@@ -86,92 +86,92 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
下表列出全部内置语言定义。**加粗** 的服务器和调试器可以在 IDE 中一键安装,其余需要自行安装(IDE 中的安装提示会说明方法)。"高亮"和"Tree-sitter"两列分别表示是否有即时高亮,以及是否有用于大纲和折叠的内置语法。
| 语言 | ID | 文件 | 高亮 | Tree-sitter | 语言服务器 | 调试器 |
| ------------------- | ------------------ | ----------------------------------------------------------- | ---- | ----------- | ------------------------------------------------------------------------------------- | ------------------------ |
| .env | `dotenv` | `.env` | 是 | — | — | — |
| Arduino | `arduino` | `.ino` | 是 | 是 | arduino-language-server | — |
| AsciiDoc | `asciidoc` | `.adoc`, `.asciidoc` | 是 | — | — | — |
| Astro | `astro` | `.astro` | 是 | — | **astro-ls** + **oxlint** | — |
| Batch | `bat` | `.bat`, `.cmd` | 是 | — | — | — |
| C | `c` | `.c`, `.h` | 是 | 是 | **clangd** | lldb-dap |
| C# | `csharp` | `.cs`, `.csx` | 是 | 是 | **csharp-ls** | **netcoredbg** |
| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | 是 | 是 | **clangd** | lldb-dap |
| Clojure | `clojure` | `.clj`, `.cljs`, `.cljc`, `.cljd`, `.edn`, … | 是 | — | **clojure-lsp** | — |
| CMake | `cmake` | `.cmake` | 是 | 是 | **neocmakelsp** → cmake-language-server | — |
| CSS | `css` | `.css`, `.pcss`, `.postcss` | 是 | 是 | **vscode-css-language-server** | — |
| D | `d` | `.d`, `.di` | 是 | — | serve-d | — |
| Dart | `dart` | `.dart` | 是 | 是 | dart | dart |
| Diff | `diff` | `.diff`, `.patch`, `.rej` | 是 | — | — | — |
| Django Template | `django-html` | `.djhtml`, `templates/*.html`, `*.txt` | 是 | 是 | **vscode-html-language-server**, **djlsp** | — |
| Dockerfile | `dockerfile` | `.dockerfile`, `.containerfile` | 是 | — | **dockerfile-language-server** | — |
| Elixir | `elixir` | `.ex`, `.exs` | 是 | 是 | **elixir-ls** | **elixir-ls-debugger** |
| ERB | `erb` | `.erb`, `.html.erb`, `.rhtml`, `.js.erb`, `.text.erb`, … | 是 | — | — | — |
| Erlang | `erlang` | `.erl`, `.hrl`, `.escript`, `.app.src` | 是 | — | elp | — |
| F# | `fsharp` | `.fs`, `.fsi`, `.fsx` | 是 | — | **fsautocomplete** | **netcoredbg** |
| GDScript | `gdscript` | `.gd` | 是 | 是 | godot | godot |
| Git Attributes | `gitattributes` | `.gitattributes` | — | — | — | — |
| Go | `go` | `.go` | 是 | 是 | **gopls** | **delve** |
| Go Module | `go.mod` | `go.mod` | 是 | — | **gopls** | — |
| Go Workspace | `go.work` | `go.work` | 是 | — | **gopls** | — |
| Godot Resource | `godot-resource` | `.tscn`, `.tres`, `.godot`, `.import` | 是 | — | — | — |
| Godot Shader | `gdshader` | `.gdshader`, `.gdshaderinc` | 是 | — | — | — |
| GraphQL | `graphql` | `.graphql`, `.graphqls`, `.gql` | 是 | 是 | **graphql-lsp** | — |
| Groovy | `groovy` | `.groovy`, `.gradle`, `.gvy`, `.gy`, `.gsh` | 是 | — | groovy-language-server | — |
| Haskell | `haskell` | `.hs`, `.hs-boot`, `.hsig` | 是 | 是 | haskell-language-server | — |
| HCL | `hcl` | `.hcl`, `.nomad`, `.pkr.hcl` | 是 | 是 | — | — |
| HTML | `html` | `.html`, `.htm`, `.xhtml`, `.shtml`, `.html.tmpl` | 是 | 是 | **vscode-html-language-server** + **angular-language-server** | — |
| HTTP Request | `http` | `.http`, `.rest` | 是 | — | — | — |
| Ignore File | `ignore` | `.gitignore`, `.dockerignore` | — | — | — | — |
| INI | `ini` | `.ini`, `.cfg`, `.conf`, `.cnf`, `.inf`, … | 是 | — | — | — |
| Java | `java` | `.java` | 是 | 是 | **jdtls** → **java-analyzer** → **kmp-lsp** | **java-debug** |
| JavaScript | `javascript` | `.js`, `.mjs`, `.cjs` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** |
| JavaScript JSX | `javascriptreact` | `.jsx` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** |
| JSON | `json` | `.json`, `.geojson`, `.topojson`, `.webmanifest`, `.har`, … | 是 | 是 | **vscode-json-language-server** | — |
| JSON with Comments | `jsonc` | `.jsonc`, `.code-workspace`, `.code-snippets` | 是 | 是 | **vscode-json-language-server** | — |
| JSP | `jsp` | `.jsp`, `.jspx`, `.jspf`, `.jsph`, `.tag`, … | 是 | — | — | — |
| Julia | `julia` | `.jl` | 是 | — | julia-languageserver | — |
| Kotlin | `kotlin` | `.kt`, `.kts` | 是 | 是 | **kotlin-lsp** → **kotlin-language-server** → **kmp-lsp** | **kotlin-debug-adapter** |
| LaTeX | `latex` | `.tex`, `.ltx`, `.sty`, `.cls`, `.dtx`, … | 是 | — | **texlab** | — |
| Less | `less` | `.less` | 是 | — | **vscode-css-language-server** | — |
| Log | `log` | `.log` | 是 | — | — | — |
| Lua | `lua` | `.lua`, `.luau`, `.rockspec` | 是 | 是 | **lua-language-server** | — |
| Makefile | `makefile` | `.mk`, `.mak`, `.make` | 是 | 是 | — | — |
| Markdown | `markdown` | `.md`, `.markdown`, `.mdown`, `.mkd`, `.mkdn`, … | 是 | 是 | **marksman** | — |
| Nix | `nix` | `.nix` | 是 | 是 | nil → nixd | — |
| Objective-C | `objective-c` | `.m` | 是 | — | **clangd** | lldb-dap |
| Objective-C++ | `objective-cpp` | `.mm` | 是 | — | **clangd** | lldb-dap |
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | 是 | 是 | ocamllsp | ocamlearlybird |
| OCaml Interface | `ocaml.interface` | `.mli` | 是 | 是 | ocamllsp | — |
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | 是 | — | **perlnavigator** | — |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | 是 | 是 | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** |
| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — |
| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | 是 | — | powershell-editor-services | — |
| Prisma | `prisma` | `.prisma` | 是 | 是 | **prisma-language-server** | — |
| Properties | `properties` | `.properties`, `.prefs` | 是 | — | — | — |
| Protocol Buffers | `proto` | `.proto` | 是 | 是 | **buf** | — |
| Python | `python` | `.py`, `.pyi`, `.pyw` | 是 | 是 | **basedpyright** → **pyright** → **ty** → **pyrefly** + **ruff** | **debugpy** |
| R | `r` | `.r`, `.rprofile` | 是 | — | r-languageserver | — |
| reStructuredText | `restructuredtext` | `.rst` | 是 | — | — | — |
| Ruby | `ruby` | `.rb`, `.rake`, `.gemspec`, `.ru`, `.rbi`, … | 是 | 是 | **ruby-lsp** → **solargraph** | rdbg |
| Rust | `rust` | `.rs` | 是 | 是 | **rust-analyzer** | **codelldb** |
| Sass | `sass` | `.sass` | 是 | — | — | — |
| Scala | `scala` | `.scala`, `.sc`, `.sbt`, `.mill` | 是 | 是 | metals | — |
| SCSS | `scss` | `.scss` | 是 | — | **vscode-css-language-server** | — |
| Shell Script | `shellscript` | `.sh`, `.bash`, `.zsh`, `.ksh`, `.ash`, … | 是 | 是 | **bash-language-server** | **bash-debug** |
| Slint | `slint` | `.slint` | 是 | — | **slint-lsp** | — |
| SQL | `sql` | `.sql`, `.ddl`, `.dml`, `.psql`, `.pgsql`, … | 是 | — | **sqls** | — |
| Svelte | `svelte` | `.svelte` | 是 | — | **svelte-language-server** + **oxlint** | — |
| Swift | `swift` | `.swift`, `.swiftinterface` | 是 | 是 | sourcekit-lsp | lldb-dap |
| Terraform | `terraform` | `.tf`, `.tofu`, `.tftest.hcl` | 是 | 是 | **terraform-ls** | — |
| Terraform Variables | `terraform-vars` | `.tfvars` | 是 | 是 | **terraform-ls** | — |
| TOML | `toml` | `.toml` | 是 | 是 | **taplo** | — |
| TypeScript | `typescript` | `.ts`, `.mts`, `.cts` | 是 | 是 | **vtsls** → **typescript-language-server** + **angular-language-server** + **oxlint** | **js-debug** |
| TypeScript JSX | `typescriptreact` | `.tsx` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** |
| Typst | `typst` | `.typ` | — | — | **tinymist** | — |
| Vue | `vue` | `.vue` | 是 | — | **vue-language-server**, **vtsls** + **oxlint** | — |
| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | 是 | 是 | **lemminx** | — |
| YAML | `yaml` | `.yaml`, `.yml` | 是 | 是 | **yaml-language-server** | — |
| Zig | `zig` | `.zig`, `.zon` | 是 | 是 | **zls** | **codelldb** |
| 语言 | ID | 文件 | 高亮 | Tree-sitter | 语言服务器 | 调试器 |
| ------------------- | ------------------ | ----------------------------------------------------------- | ---- | ----------- | ------------------------------------------------------------------------------------------------- | ------------------------ |
| .env | `dotenv` | `.env` | 是 | — | — | — |
| Arduino | `arduino` | `.ino` | 是 | 是 | arduino-language-server | — |
| AsciiDoc | `asciidoc` | `.adoc`, `.asciidoc` | 是 | — | — | — |
| Astro | `astro` | `.astro` | 是 | — | **astro-ls** + **oxlint** | — |
| Batch | `bat` | `.bat`, `.cmd` | 是 | — | — | — |
| C | `c` | `.c`, `.h` | 是 | 是 | **clangd** | lldb-dap |
| C# | `csharp` | `.cs`, `.csx` | 是 | 是 | **csharp-ls** | **netcoredbg** |
| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | 是 | 是 | **clangd** | lldb-dap |
| Clojure | `clojure` | `.clj`, `.cljs`, `.cljc`, `.cljd`, `.edn`, … | 是 | — | **clojure-lsp** | — |
| CMake | `cmake` | `.cmake` | 是 | 是 | **neocmakelsp** → cmake-language-server | — |
| CSS | `css` | `.css`, `.pcss`, `.postcss` | 是 | 是 | **vscode-css-language-server** + **biome** | — |
| D | `d` | `.d`, `.di` | 是 | — | serve-d | — |
| Dart | `dart` | `.dart` | 是 | 是 | dart | dart |
| Diff | `diff` | `.diff`, `.patch`, `.rej` | 是 | — | — | — |
| Django Template | `django-html` | `.djhtml`, `templates/*.html`, `*.txt` | 是 | 是 | **vscode-html-language-server**, **djlsp** | — |
| Dockerfile | `dockerfile` | `.dockerfile`, `.containerfile` | 是 | — | **dockerfile-language-server** | — |
| Elixir | `elixir` | `.ex`, `.exs` | 是 | 是 | **elixir-ls** | **elixir-ls-debugger** |
| ERB | `erb` | `.erb`, `.html.erb`, `.rhtml`, `.js.erb`, `.text.erb`, … | 是 | — | — | — |
| Erlang | `erlang` | `.erl`, `.hrl`, `.escript`, `.app.src` | 是 | — | elp | — |
| F# | `fsharp` | `.fs`, `.fsi`, `.fsx` | 是 | — | **fsautocomplete** | **netcoredbg** |
| GDScript | `gdscript` | `.gd` | 是 | 是 | godot | godot |
| Git Attributes | `gitattributes` | `.gitattributes` | — | — | — | — |
| Go | `go` | `.go` | 是 | 是 | **gopls** | **delve** |
| Go Module | `go.mod` | `go.mod` | 是 | — | **gopls** | — |
| Go Workspace | `go.work` | `go.work` | 是 | — | **gopls** | — |
| Godot Resource | `godot-resource` | `.tscn`, `.tres`, `.godot`, `.import` | 是 | — | — | — |
| Godot Shader | `gdshader` | `.gdshader`, `.gdshaderinc` | 是 | — | — | — |
| GraphQL | `graphql` | `.graphql`, `.graphqls`, `.gql` | 是 | 是 | **graphql-lsp** + **biome** | — |
| Groovy | `groovy` | `.groovy`, `.gradle`, `.gvy`, `.gy`, `.gsh` | 是 | — | groovy-language-server | — |
| Haskell | `haskell` | `.hs`, `.hs-boot`, `.hsig` | 是 | 是 | haskell-language-server | — |
| HCL | `hcl` | `.hcl`, `.nomad`, `.pkr.hcl` | 是 | 是 | — | — |
| HTML | `html` | `.html`, `.htm`, `.xhtml`, `.shtml`, `.html.tmpl` | 是 | 是 | **vscode-html-language-server** + **angular-language-server** | — |
| HTTP Request | `http` | `.http`, `.rest` | 是 | — | — | — |
| Ignore File | `ignore` | `.gitignore`, `.dockerignore` | — | — | — | — |
| INI | `ini` | `.ini`, `.cfg`, `.conf`, `.cnf`, `.inf`, … | 是 | — | — | — |
| Java | `java` | `.java` | 是 | 是 | **jdtls** → **java-analyzer** → **kmp-lsp** | **java-debug** |
| JavaScript | `javascript` | `.js`, `.mjs`, `.cjs` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** |
| JavaScript JSX | `javascriptreact` | `.jsx` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** |
| JSON | `json` | `.json`, `.geojson`, `.topojson`, `.webmanifest`, `.har`, … | 是 | 是 | **vscode-json-language-server** + **biome** | — |
| JSON with Comments | `jsonc` | `.jsonc`, `.code-workspace`, `.code-snippets` | 是 | 是 | **vscode-json-language-server** + **biome** | — |
| JSP | `jsp` | `.jsp`, `.jspx`, `.jspf`, `.jsph`, `.tag`, … | 是 | — | — | — |
| Julia | `julia` | `.jl` | 是 | — | julia-languageserver | — |
| Kotlin | `kotlin` | `.kt`, `.kts` | 是 | 是 | **kotlin-lsp** → **kotlin-language-server** → **kmp-lsp** | **kotlin-debug-adapter** |
| LaTeX | `latex` | `.tex`, `.ltx`, `.sty`, `.cls`, `.dtx`, … | 是 | — | **texlab** | — |
| Less | `less` | `.less` | 是 | — | **vscode-css-language-server** | — |
| Log | `log` | `.log` | 是 | — | — | — |
| Lua | `lua` | `.lua`, `.luau`, `.rockspec` | 是 | 是 | **lua-language-server** | — |
| Makefile | `makefile` | `.mk`, `.mak`, `.make` | 是 | 是 | — | — |
| Markdown | `markdown` | `.md`, `.markdown`, `.mdown`, `.mkd`, `.mkdn`, … | 是 | 是 | **marksman** | — |
| Nix | `nix` | `.nix` | 是 | 是 | nil → nixd | — |
| Objective-C | `objective-c` | `.m` | 是 | — | **clangd** | lldb-dap |
| Objective-C++ | `objective-cpp` | `.mm` | 是 | — | **clangd** | lldb-dap |
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | 是 | 是 | ocamllsp | ocamlearlybird |
| OCaml Interface | `ocaml.interface` | `.mli` | 是 | 是 | ocamllsp | — |
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | 是 | — | **perlnavigator** | — |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | 是 | 是 | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** |
| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — |
| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | 是 | — | powershell-editor-services | — |
| Prisma | `prisma` | `.prisma` | 是 | 是 | **prisma-language-server** | — |
| Properties | `properties` | `.properties`, `.prefs` | 是 | — | — | — |
| Protocol Buffers | `proto` | `.proto` | 是 | 是 | **buf** | — |
| Python | `python` | `.py`, `.pyi`, `.pyw` | 是 | 是 | **basedpyright** → **pyright** → **ty** → **pyrefly** + **ruff** | **debugpy** |
| R | `r` | `.r`, `.rprofile` | 是 | — | r-languageserver | — |
| reStructuredText | `restructuredtext` | `.rst` | 是 | — | — | — |
| Ruby | `ruby` | `.rb`, `.rake`, `.gemspec`, `.ru`, `.rbi`, … | 是 | 是 | **ruby-lsp** → **solargraph** | rdbg |
| Rust | `rust` | `.rs` | 是 | 是 | **rust-analyzer** | **codelldb** |
| Sass | `sass` | `.sass` | 是 | — | — | — |
| Scala | `scala` | `.scala`, `.sc`, `.sbt`, `.mill` | 是 | 是 | metals | — |
| SCSS | `scss` | `.scss` | 是 | — | **vscode-css-language-server** | — |
| Shell Script | `shellscript` | `.sh`, `.bash`, `.zsh`, `.ksh`, `.ash`, … | 是 | 是 | **bash-language-server** | **bash-debug** |
| Slint | `slint` | `.slint` | 是 | — | **slint-lsp** | — |
| SQL | `sql` | `.sql`, `.ddl`, `.dml`, `.psql`, `.pgsql`, … | 是 | — | **sqls** | — |
| Svelte | `svelte` | `.svelte` | 是 | — | **svelte-language-server** + **oxlint** | — |
| Swift | `swift` | `.swift`, `.swiftinterface` | 是 | 是 | sourcekit-lsp | lldb-dap |
| Terraform | `terraform` | `.tf`, `.tofu`, `.tftest.hcl` | 是 | 是 | **terraform-ls** | — |
| Terraform Variables | `terraform-vars` | `.tfvars` | 是 | 是 | **terraform-ls** | — |
| TOML | `toml` | `.toml` | 是 | 是 | **taplo** | — |
| TypeScript | `typescript` | `.ts`, `.mts`, `.cts` | 是 | 是 | **vtsls** → **typescript-language-server** + **angular-language-server** + **oxlint** + **biome** | **js-debug** |
| TypeScript JSX | `typescriptreact` | `.tsx` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** + **biome** | **js-debug** |
| Typst | `typst` | `.typ` | — | — | **tinymist** | — |
| Vue | `vue` | `.vue` | 是 | — | **vue-language-server**, **vtsls** + **oxlint** | — |
| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | 是 | 是 | **lemminx** | — |
| YAML | `yaml` | `.yaml`, `.yml` | 是 | 是 | **yaml-language-server** | — |
| Zig | `zig` | `.zig`, `.zon` | 是 | 是 | **zls** | **codelldb** |
说明:
+23 -13
View File
@@ -7,16 +7,18 @@ OpenIDEA 打开 JavaScript(`.js`、`.mjs`、`.cjs`、`.jsx`)和 TypeScript
## 语言服务器
| 文件 | 服务器 | 说明 |
| --------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| JS、JSX、TS、TSX | `vtsls` | 默认的 TypeScript 服务器。 |
| JS、JSX、TS、TSX | `typescript-language-server` | 备选:仅在未安装 `vtsls` 时使用。 |
| `.vue` | `vue-language-server` + `vtsls` | Vue 的 hybrid 模式:`.vue` 中的 TypeScript 由加载了 `@vue/typescript-plugin` 的 `vtsls` 处理。 |
| `.svelte` | `svelte-language-server` | |
| `.astro` | `astro-ls` | 需要 Node.js 和 TypeScript 库。 |
| Angular 项目中的 TS 和 HTML | `angular-language-server`(`ngserver`) | 只在 `angular.json` 或 `node_modules/@angular/core` 所在目录之下启用。 |
| 以上全部 | `oxlint` | 只在存在 `.oxlintrc.json`、`.oxlintrc.jsonc`、`oxlint.config.ts` 或 `oxlint.config.mts` 的目录之下启用。 |
| 以上全部 | `vscode-eslint-language-server`(ESLint) | 只在 ESLint 配置(`eslint.config.*`、`.eslintrc*` 或 `package.json` 中的 `eslintConfig`)所在目录之下启用,运行项目自己的 `eslint`。 |
| 文件 | 服务器 | 说明 |
| --------------------------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| JS、JSX、TS、TSX | `vtsls` | 默认的 TypeScript 服务器。 |
| JS、JSX、TS、TSX | `typescript-language-server` | 备选:仅在未安装 `vtsls` 时使用。 |
| `.vue` | `vue-language-server` + `vtsls` | Vue 的 hybrid 模式:`.vue` 中的 TypeScript 由加载了 `@vue/typescript-plugin` 的 `vtsls` 处理。 |
| `.svelte` | `svelte-language-server` | |
| `.astro` | `astro-ls` | 需要 Node.js 和 TypeScript 库。 |
| Angular 项目中的 TS 和 HTML | `angular-language-server`(`ngserver`) | 只在 `angular.json` 或 `node_modules/@angular/core` 所在目录之下启用。 |
| 以上全部 | `oxlint` | 只在存在 `.oxlintrc.json`、`.oxlintrc.jsonc`、`oxlint.config.ts` 或 `oxlint.config.mts` 的目录之下启用。 |
| 以上全部 | `vscode-eslint-language-server`(ESLint) | 只在 ESLint 配置(`eslint.config.*`、`.eslintrc*` 或 `package.json` 中的 `eslintConfig`)所在目录之下启用,运行项目自己的 `eslint`。 |
| JS、JSX、TS、TSX、JSON、CSS | `biome lsp-proxy`(Biome) | 只在 `biome.json` / `biome.jsonc` 所在目录或安装了 `@biomejs/biome` 的项目之下启用,运行项目自己的 `biome`。 |
| 以上全部及 HTML、CSS | `tailwindcss-language-server`(Tailwind CSS) | 只在 `tailwind.config.*` 或依赖了 `tailwindcss` 的 `package.json` 所在目录之下启用:类名补全、悬停显示生成的 CSS、类名诊断。 |
TypeScript 服务器以 `tsconfig.json`、`jsconfig.json` 或 `package.json` 所在目录为工作区根。不属于任何 `tsconfig.json` / `jsconfig.json` 的文件也会注册给 tsserver,零散脚本同样有代码智能。
@@ -47,7 +49,9 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript
| `vtsls`、`typescript-language-server` | npm(`@vtsls/language-server`;`typescript-language-server` + `typescript@6`) |
| `vue-language-server`、`svelte-language-server`、`astro-ls`、`angular-language-server` | npm |
| `oxlint` | npm |
| `tailwindcss-language-server` | npm(`@tailwindcss/language-server`) |
| Prettier、oxfmt | npm |
| Prettier、oxfmt、Biome | npm |
| JavaScript 调试器(vscode-js-debug) | GitHub release(`microsoft/vscode-js-debug`) |
如果项目自己的 `node_modules/.bin` 里有 Astro 或 Angular 服务器,会优先使用项目里的。
@@ -67,14 +71,20 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript
- **Prettier**(**设置 › 语言和框架 › Prettier**)默认处理 JavaScript、JSX、TypeScript、TSX、JSON、Vue、HTML、CSS、SCSS、Less、GraphQL、YAML 和 Markdown。未设置 **Prettier 路径** 时,依次查找项目 `node_modules`、IDE 管理的安装、`PATH`。
- **oxfmt**(**设置 › 语言和框架 › oxfmt**)在 oxfmt 配置文件(`.oxfmtrc.json`、`oxfmt.config.ts`)所在目录之下,或被选为格式化工具时,替代 Prettier 处理已启用的语言。
- **Biome**(**设置 › 语言和框架 › Biome**)在 `biome.json` / `biome.jsonc` 所在目录或安装了 `@biomejs/biome` 的项目之下(配置里 `formatter.enabled` 为 `false` 时除外),或被选为格式化工具时,替代 Prettier 和 oxfmt 处理 JavaScript、JSX、TypeScript、TSX、JSON、CSS 和 GraphQL。它总是格式化整个文件,并读取自己的配置。
两个页面上,**格式化工具** 可选 **自动(优先语言服务器)** 或工具本身,**保存时运行** 控制保存时格式化,**启用的语言** 限定工具处理哪些语言。
这些页面上,**格式化工具** 可选 **自动(优先语言服务器)** 或工具本身,**保存时运行** 控制保存时格式化,**启用的语言** 限定工具处理哪些语言。
### Biome 检查
在 Biome 项目中,Biome 的诊断显示在编辑器和“问题”工具窗口里,`⌥⏎` / `Alt+Enter` 提供它的快速修复和抑制。Biome 的安全修复(`source.fixAll.biome`)随 **代码 › 代码清理** 运行;开启 **设置 › 工具 › 保存时操作 › 运行代码清理** 后,保存时也会运行。Biome 的格式化器开启时,它的全部修复也会格式化文件。
## 运行与测试
打开项目时,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`、`node --test` 或 `mocha` 的脚本,是测试配置。
- 有 `playwright.config.*` 但没有脚本运行它的包:通过 `npx` 运行的 `playwright test`。
- `deno.json` / `deno.jsonc` 中每个 task 一个配置(`deno task <name>`)。
在 `package.json` 中,每个 `scripts` 条目旁的边栏图标可以直接运行或调试该脚本。
@@ -85,7 +95,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、`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`,在用 Mocha 或 `node --test` 测试的项目里,`test/` 目录下的测试不论文件名都有行号栏图标。**使用覆盖率运行** 支持调用 `vitest` 或 `jest` 的脚本(Vitest 需要 `@vitest/coverage-v8` 之类的覆盖率 provider,缺失时 IDE 会提示添加),以及通过 `c8` 运行的 `node` / `tsx` / `ts-node`。详见[测试](/zh/guide/testing)和[覆盖率](/zh/guide/coverage)。
## 调试
+2
View File
@@ -21,6 +21,8 @@ basedpyright 以 `standard` 类型检查模式启动,而不是它自带的更
Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`,或包含 `[tool.ruff]` 表的 `pyproject.toml`。basedpyright 本身不提供格式化,格式化由 Ruff 负责。
移动或重命名模块、包时(项目视图中,勾选 **搜索引用**),引用它的 `import` 和 `from … import` 语句(包括相对导入)会一起更新,和移动操作显示在同一个预览里。basedpyright 不支持文件移动,所以这些导入由 IDE 根据语法树自己查找。如果重命名改变了导入绑定的名字,导入会用别名保留原名:`from pkg import models` 变成 `from pkg import domain as models`。
想手动指定类型检查器,打开 **设置 › 语言和框架 › 语言服务器**,选中这四个服务器中的任意一个,修改 **Python 语言服务器**。**自动** 会按上表顺序使用第一个已安装的服务器;也可以固定选一个,或选 **无**。
## 环境配置
+8 -8
View File
@@ -254,14 +254,14 @@ register_plugin!(MyPlugin, run_target_validation);
## 运行程序
| 函数 | 作用 |
| ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- |
| `Project::run_process(program, &args, stdin)` | 在项目根目录运行已固定的程序并等待结束:`{ status, stdout, stderr }`,各 4 MiB。 |
| `host::run_command(&Command, Some(&project), stdin)` | API 1.3:同上,可用 `Command::env` 追加环境变量。 |
| `host::run_captured(&Command, Some(&project), stdin, options)` | API 1.15:可配置输出上限(每个流最高 128 MiB),stdout 或 stderr 溢出时明确报错。 |
| `host::start(&Command, Some(&project))` | API 1.3:保持运行的 `Child`:`poll`、`write`、`close_stdin`、`wait`、`kill`。最多 8 个。 |
| `host::start_stream(&Command, Some(&project), options)` | API 1.15:基于管道背压的有界无损流式传输,超出总预算时明确报错并终止进程。 |
| `host::open_terminal(title, program, &args)` | 运行该程序的终端标签页(见 [视图](/zh/plugins/guides/views))。 |
| 函数 | 作用 |
| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| `Project::run_process(program, &args, stdin)` | 在项目根目录运行已固定的程序并等待结束:`{ status, stdout, stderr }`,各 4 MiB。 |
| `host::run_command(&Command, Some(&project), stdin)` | API 1.3:同上,可用 `Command::env` 追加环境变量。 |
| `host::run_captured(&Command, Some(&project), stdin, options)` | API 1.15:可配置输出上限(每个流最高 128 MiB),stdout 或 stderr 溢出时明确报错。 |
| `host::start(&Command, Some(&project))` | API 1.3:保持运行的 `Child`:`poll`、`write`、`close_stdin`、`wait`、`kill`。最多 8 个。 |
| `host::start_stream(&Command, Some(&project), options)` | API 1.15:基于管道背压的有界无损流式传输,超出总预算时明确报错并终止进程。 |
| `host::open_terminal(title, program, &args)` | 运行该程序的终端标签页(见 [视图](/zh/plugins/guides/views))。 |
```rust
use openidea_plugin::host::{self, Command};
+1
View File
@@ -124,6 +124,7 @@ optional = ["net:api.openai.com", "secrets"]
| `runDetectors` | `id`、`name`、`files`、`command`、`args?`、`test?`、`framework?` | 否 | [运行目标](/zh/plugins/guides/run-targets) |
| `runConfigurations` | `files`(API 1.4) | 是 | [运行目标](/zh/plugins/guides/run-targets) |
| `javaAgents` | `path`、`args?`(API 1.10);`vmOptions?`、`jdk?`(API 1.14) | 否 | [README:Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) |
| `skills` | `path`(`skills/<name>/SKILL.md`,API 1.15) | 否 | [README:API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) |
| `mcpTools` | `name`、`description`、`inputSchema`、`readOnly`、`destructive`(API 1.4) | 是 | [MCP 工具](/zh/plugins/guides/mcp) |
| `themes` | `path`、`editor-scheme?` | 否 | [主题](/zh/plugins/guides/themes) |
| `iconThemes` | `id`、`label`、`path` | 否 | [图标主题](/zh/plugins/guides/icon-themes) |
+1
View File
@@ -26,6 +26,7 @@ description: "engines.openidea、插件 API 从 1.0 到 1.13 的各个版本,
| 1.12.0 | `main` 上开发中 | `ui.set-console-rules`:Run/Debug 控制台输出的高亮规则(正则、调色板颜色、文本样式) |
| 1.13.0 | OpenIDEA 0.1.49 | 新增 `search-provider` 导出和 `searchCategories` 贡献点:可取消查询的全局搜索自定义分类 |
| 1.14.0 | `main` 上开发中 | 可选 `hover-actions` 导出:行内侧 hover 显示的左侧操作,带锚定行和包含式触发行范围; `[[contributes.javaAgents]]` 的 `vmOptions` / `jdk`:在 `-javaagent:` 之前注入 JVM 参数(可选仅 JetBrains Runtime);`ui.set-status-item-menu` / `set-window-status-item-menu`:状态栏项菜单 |
| 1.15.0 | `main` 上开发中 | `caret-moved` 事件;声明式 `[[contributes.skills]]`(`path = "skills/<name>/SKILL.md"`),在插件包中打包代理技能 |
每个版本新增内容的完整列表见 [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md)。
+1 -1
View File
@@ -55,7 +55,7 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"]
| 插件 | 插件 |
| 版本控制 | 提交;确认;目录映射;问题导航;日志;搁置;Git;GitHub |
| 构建、执行、部署 | CMake;Gradle;Maven;控制台;调试器(数据视图、单步执行);Python 调试器;运行/调试;运行目标;部署(选项) |
| 语言和框架 | 语言服务器;Go(构建标签、Go 模块);Java;Markdown;Node.js;PHP;Python 解释器;Prettier;oxfmt;Ruff;Ruby;Rust;TypeScript |
| 语言和框架 | 语言服务器;Go(构建标签、Go 模块);Java;Markdown;Node.js;PHP;Python 解释器;Prettier;oxfmt;Biome;Ruff;Ruby;Rust;TypeScript |
| 工具 | 智能体(聊天);终端;保存时操作;外部工具;SSH 配置;MCP 服务器 |
| 安全 | 项目信任 |
+142
View File
@@ -73,6 +73,8 @@ const initialSkills: AgentSkillState[] = [
alsoIn: ["claudeWorkspace"],
userInvocable: true,
disableModelInvocation: false,
contextFork: true,
paths: ["src/**/*.tsx", "e2e/*.spec.ts"],
valid: true,
warnings: [],
},
@@ -111,6 +113,22 @@ const initialSkills: AgentSkillState[] = [
mode: "off",
origin: "user",
},
{
skill: {
name: "release-notes",
description: "Draft concise release notes from merged commits and pull requests",
hint: "[tag]",
path: "/Users/dev/Library/Application Support/ai.l0ng.openidea/plugins/acme.release-tools/1.0.0/skills/release-notes",
source: "plugin",
alsoIn: [],
userInvocable: true,
disableModelInvocation: false,
valid: true,
warnings: [],
},
mode: "auto",
origin: "none",
},
{
skill: {
name: "pg-tune",
@@ -190,6 +208,90 @@ test("manages multi-level skills in Settings and per-session overrides via Compo
);
return skills;
};
handlers.agent_skills_browse = () => ({
owner: "vercel-labs",
repo: "agent-skills",
gitRef: "main",
treeSha: "9f8e7d6c",
truncated: false,
skills: [
{ folderName: "find-skills", subpath: "skills/find-skills", fileCount: 2, totalBytes: 1420 },
{ folderName: "web-design-audit", subpath: "skills/web-design-audit", fileCount: 1, totalBytes: 860 },
],
});
handlers.agent_skills_preview = ({ subpath }) =>
subpath === "skills/web-design-audit"
? {
owner: "vercel-labs",
repo: "agent-skills",
gitRef: "main",
treeSha: "9f8e7d6c",
subpath: "skills/web-design-audit",
skillName: "web-design-audit",
description: "Audit responsive layout and contrast tokens",
skillMarkdown:
"---\nname: web-design-audit\ndescription: Audit responsive layout and contrast tokens\n---\n\nCheck spacing and contrast tokens.\n",
files: [{ path: "SKILL.md", size: 860, executable: false, symlink: false }],
scanWarnings: [],
alreadyInstalledUser: false,
alreadyInstalledWorkspace: false,
}
: {
owner: "vercel-labs",
repo: "agent-skills",
gitRef: "main",
treeSha: "9f8e7d6c",
subpath: "skills/find-skills",
skillName: "find-skills",
description: "Discover reusable SKILL.md workflows and inspect bundled scripts",
skillMarkdown:
"---\nname: find-skills\ndescription: Discover reusable SKILL.md workflows and inspect bundled scripts\nallowed-tools:\n - Bash(gh:*)\n---\n\nInspect candidate SKILL.md files before installing.\n",
files: [
{ path: "SKILL.md", size: 980, executable: false, symlink: false },
{ path: "scripts/inspect.sh", size: 440, executable: true, symlink: false },
],
scanWarnings: [
{
kind: "executableScript",
file: "scripts/inspect.sh",
message: "Contains executable file mode (100755)",
},
{
kind: "allowedToolsShell",
file: "SKILL.md",
message: "`allowed-tools` grants shell/command execution (`Bash(gh:*)`)",
},
],
alreadyInstalledUser: false,
alreadyInstalledWorkspace: false,
};
handlers.agent_skills_install = ({ input }) => {
const req = input as { subpath: string; scope: "user" | "workspace" };
const installedName = req.subpath.endsWith("web-design-audit") ? "web-design-audit" : "find-skills";
skills = [
...skills,
{
skill: {
name: installedName,
description: "Discover reusable SKILL.md workflows and inspect bundled scripts",
hint: null,
path:
req.scope === "workspace"
? `/dev/openidea/.agents/skills/${installedName}`
: `/Users/dev/.agents/skills/${installedName}`,
source: req.scope === "workspace" ? "workspace" : "user",
alsoIn: [],
userInvocable: true,
disableModelInvocation: false,
valid: true,
warnings: [],
},
mode: "auto",
origin: "none",
},
];
return skills;
};
handlers.agent_set_skill_overrides = ({ overrides }) => {
currentTask = { ...currentTask, skillOverrides: overrides as Record<string, AgentSkillMode> };
return currentTask;
@@ -226,7 +328,11 @@ 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");
await expect(sessionPopup).toContainText("Untrusted workspace");
// Enable default-off `impeccable` for this session and turn `pg-tune` off for this session.
@@ -250,12 +356,48 @@ 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();
await expect(settingsDialog.getByText("release-notes")).toBeVisible();
await expect(settingsDialog.getByText("[[contributes.skills]]")).toBeVisible();
if (screenshotDir) {
await settingsDialog.screenshot({ path: `${screenshotDir}/after-settings-skills-plugins.png` });
await settingsDialog.getByRole("tab", { name: /All Sources/ }).click();
await settingsDialog.screenshot({ path: `${screenshotDir}/after-settings-skills.png` });
}
// Open Install Skill… dialog, fetch repository, verify static scan warning gate, confirm, and install.
await settingsDialog.getByRole("button", { name: "Install Skill…" }).click();
const installDialog = page.getByRole("dialog", { name: "Install Agent Skill" });
await expect(installDialog).toBeVisible();
await installDialog.getByLabel("Skill repository").fill("vercel-labs/agent-skills");
await installDialog.getByRole("button", { name: "Fetch" }).click();
await expect(installDialog.getByText("Static security scan found 2 warnings")).toBeVisible();
const installBtn = installDialog.getByRole("button", { name: "Install", exact: true });
await expect(installBtn).toBeDisabled();
if (screenshotDir) {
await installDialog.screenshot({ path: `${screenshotDir}/after-install-skill-dialog.png` });
}
await installDialog.getByLabel("I reviewed these warnings and want to install this skill").click();
await expect(installBtn).toBeEnabled();
await installBtn.click();
await expect(installDialog).toHaveCount(0);
await settingsDialog.getByRole("tab", { name: /^User/ }).click();
await expect(settingsDialog.getByText("find-skills")).toBeVisible();
if (screenshotDir) {
await settingsDialog.screenshot({ path: `${screenshotDir}/after-settings-skills-installed.png` });
}
});
+12 -3
View File
@@ -18,18 +18,27 @@ test("keeps breakpoint details editable when the dialog gets narrow", async ({ w
const list = dialog.getByRole("listbox", { name: "All breakpoints" });
const condition = dialog.locator('input[aria-label="Condition"]');
await expect(condition).toHaveValue("amount > 100");
const actions = dialog.getByRole("group", { name: "Actions", exact: true });
await expect(actions).toBeVisible();
await expect(dialog.getByText("Condition", { exact: true })).toHaveCSS("font-size", "13px");
await expect(dialog.getByText("Hit count", { exact: true })).toHaveCSS("font-size", "13px");
await expect.poll(async () => (await condition.boundingBox())?.width ?? 0).toBeGreaterThanOrEqual(240);
await expect(dialog.getByRole("button", { name: "Done", exact: true })).toBeInViewport({ ratio: 1 });
await condition.fill("amount > 250");
await dialog.getByRole("checkbox", { name: "Evaluate and log", exact: true }).check();
await dialog.getByRole("textbox", { name: "Evaluate and log", exact: true }).fill("total: {amount}");
await actions.getByRole("checkbox", { name: '"Breakpoint hit" message', exact: true }).check();
await actions.getByRole("checkbox", { name: "Evaluate and log", exact: true }).check();
const log = actions.getByRole("textbox", { name: "Evaluate and log", exact: true });
await log.fill("total: {amount}");
const temporary = actions.getByRole("checkbox", { name: "Remove once hit", exact: true });
await temporary.check();
const first = list.getByRole("option", { name: /CheckInternationalSettlementBeforeDispatch\.java:8/ });
await expect(first.getByText(":8", { exact: true })).toBeInViewport({ ratio: 1 });
await list.getByRole("option", { name: /Receipt\.java:5/ }).click();
await expect(condition).toHaveValue("");
await first.click();
await expect(condition).toHaveValue("amount > 250");
await expect(dialog.getByRole("textbox", { name: "Evaluate and log", exact: true })).toHaveValue("total: {amount}");
await expect(log).toHaveValue("total: {amount}");
await expect(temporary).toBeChecked();
await page.setViewportSize({ width: 1080, height: 760 });
const divider = dialog.locator('[data-separator][aria-orientation="vertical"]');
+52
View File
@@ -715,6 +715,58 @@ test("rename keeps the typed name, uses the editor font and shows long preview n
await expect.poll(() => ipcCalls(page, "apply_workspace_edit")).toHaveLength(1);
});
test("intentions separate quick fixes from other actions and navigate across the divider", async ({
workbench: page,
}) => {
const editor = await openSample(page);
const fix = "Correct the Order type";
const refactor = "Extract the order value";
await page.evaluate(
({ file, edit, fix, refactor }) => {
const action = (title: string, kind: string, newText: string) => ({
title,
kind,
isPreferred: false,
disabledReason: null,
edit: { files: [{ kind: "edit", path: file, edits: [{ range: edit, new_text: newText }] }] },
command: null,
data: null,
server: 1,
});
window.__ipc.handlers.lsp_code_actions = () => [
action(refactor, "refactor.extract", "ExtractedOrder"),
action(fix, "quickfix", "CorrectOrder"),
];
window.__ipc.handlers.lsp_execute_code_action = () => [];
},
{ file: FILE, edit: range(20, 19, 24), fix, refactor },
);
await caretAt(editor, page, "val order: Order", "Order ");
await page.keyboard.press("Alt+Enter");
const popup = page.getByRole("dialog", { name: "Intentions", exact: true });
const list = popup.getByRole("listbox", { name: "Intentions" });
const divider = list.locator("[class*=listDivider]");
const preview = popup.locator('[aria-label="Preview"] pre');
await expect(list.getByRole("option", { name: fix })).toBeVisible();
await page.keyboard.type("order");
await expect(list.getByRole("option")).toHaveText([fix, refactor]);
await expect(divider).toHaveCount(1);
await expect(list.getByRole("option", { name: fix })).toHaveAttribute("aria-selected", "true");
await expect(preview).toContainText("CorrectOrder");
await list.press("ArrowDown");
await expect(list.getByRole("option", { name: refactor })).toHaveAttribute("aria-selected", "true");
await expect(preview).toContainText("ExtractedOrder");
for (const _character of "order") await list.press("Backspace");
await page.keyboard.type("extract");
await expect(list.getByRole("option")).toHaveText([refactor]);
await expect(divider).toHaveCount(0);
await list.press("Enter");
await expect(popup).toBeHidden();
await expect.poll(() => ipcCalls(page, "lsp_execute_code_action")).toHaveLength(1);
});
test("intention previews fit narrow windows and wrap long code lines", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1600, height: 900 });
const editor = await openSample(page);
+151 -34
View File
@@ -4,61 +4,178 @@ const amountName = "regionalSettlementAmountFromExternalProcessorBeforeRounding"
const routingName = "settlementRoutingReferenceForCrossBorderReconciliation";
const routingText = "APR-2026 / eu-west / batch-701 / settlement complete";
const routingValue = "'" + routingText + "'";
const invalidValueMessage = "The settlement amount must be a valid decimal expression.";
test("keeps values and their full-value action readable in a narrow debugger", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1220, height: 760 });
test.describe("a paused session with editable values", () => {
test.beforeEach(async ({ workbench: page }) => {
await page.setViewportSize({ width: 1220, height: 760 });
await stubDesktop(page);
await page.evaluate(
async ({ amountName, routingName, routingValue, invalidValueMessage }) => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const servicesModule = "/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 */ servicesModule);
const h = window.__ipc.handlers;
let amountValue = "47.74";
const amount = () => ({
name: amountName,
value: amountValue,
typeName: "float",
variablesReference: 0,
evaluateName: amountName,
});
h.debug_scopes = () => [{ name: "Locals", variablesReference: 100, expensive: false }];
h.debug_variables = () => [
amount(),
{ name: routingName, value: routingValue, typeName: "str", variablesReference: 0, evaluateName: routingName },
];
h.debug_set_variable = ({ value }) => {
if (value === "invalid") throw { kind: "invalid", message: invalidValueMessage, detail: null };
amountValue = String(value);
return amount();
};
adoptSession(91, {
name: "Checkout",
adapter: "debugpy",
status: "paused",
selectedFrame: 11,
frames: [{ id: 11, name: "checkout", path: null, line: 0, column: 0, presentationHint: null }],
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 390);
toolWindowService().show("debug", true);
},
{ amountName, routingName, routingValue, invalidValueMessage },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
});
test("keeps values and their full-value action readable in a narrow debugger", async ({ workbench: page }) => {
const debug = page.getByRole("region", { name: "Debug", exact: true });
const amount = debug.getByText("47.74", { exact: true });
await expect
.poll(() => amount.evaluate((el) => el.clientWidth > 0 && el.scrollWidth <= el.clientWidth + 1))
.toBe(true);
const routing = debug.getByRole("treeitem").filter({ hasText: routingName });
const show = routing.getByTitle("Show", { exact: true });
await expect(show).toBeInViewport({ ratio: 1 });
await show.click();
const dialog = page.getByRole("dialog", { name: `Value of ${routingName}` });
await expect(dialog.getByText(routingText, { exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
await page.setViewportSize({ width: 1640, height: 760 });
await page.evaluate(async () => {
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { moveToolWindow } = await import(/* @vite-ignore */ layoutModule);
moveToolWindow("debug", "bottom");
});
await expect(show).toBeHidden();
await expect
.poll(() =>
routing.getByText(routingValue, { exact: true }).evaluate((el) => el.scrollWidth <= el.clientWidth + 1),
)
.toBe(true);
});
test("keeps the variable label and input in place when editing a value", async ({ workbench: page }) => {
const debug = page.getByRole("region", { name: "Debug", exact: true });
const row = debug.getByRole("treeitem").filter({ hasText: amountName });
const name = row.getByText(amountName, { exact: true });
await row.click();
const nameBefore = (await name.boundingBox())!;
const equal = row.getByText("=", { exact: true });
const equalBefore = (await equal.boundingBox())!;
const color = await name.evaluate((el) => getComputedStyle(el).color);
await page.keyboard.press("F2");
const input = row.getByRole("textbox", { name: `New value of ${amountName}` });
await expect(input).toBeFocused();
await expect(input).toHaveValue("47.74");
await expect(name).toHaveCSS("color", color);
expect((await name.boundingBox())!.x).toBeCloseTo(nameBefore.x, 0);
expect((await equal.boundingBox())!.x).toBeCloseTo(equalBefore.x, 0);
await expect(row.locator("svg")).toHaveCount(1);
await input.fill("invalid");
await input.press("Enter");
await expect(input).toHaveAttribute("aria-invalid", "true");
await expect(input).toHaveAttribute("title", invalidValueMessage);
await expect(input).toBeInViewport({ ratio: 1 });
expect((await input.boundingBox())!.width).toBeGreaterThan(60);
expect((await equal.boundingBox())!.x).toBeCloseTo(equalBefore.x, 0);
await input.press("Escape");
await expect(input).toBeHidden();
await expect(row).toContainText("47.74");
await page.keyboard.press("F2");
await expect(input).toHaveValue("47.74");
await input.fill("48.25");
await input.press("Enter");
await expect(input).toBeHidden();
await expect(row).toContainText("48.25");
});
});
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 ({ amountName, routingName, routingValue }) => {
async ({ name, type, value, countName }) => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const servicesModule = "/src/workbench/contributions.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 */ servicesModule);
const h = window.__ipc.handlers;
h.debug_scopes = () => [{ name: "Locals", variablesReference: 100, expensive: false }];
h.debug_variables = () => [
{ name: amountName, value: "47.74", typeName: "float", variablesReference: 0, evaluateName: amountName },
{ name: routingName, value: routingValue, typeName: "str", variablesReference: 0, evaluateName: routingName },
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(91, {
name: "Checkout",
adoptSession(92, {
name: "Settlement",
adapter: "debugpy",
status: "paused",
selectedFrame: 11,
frames: [{ id: 11, name: "checkout", path: null, line: 0, column: 0, presentationHint: null }],
frames: [{ id: 11, name: "settle", path: null, line: 0, column: 0, presentationHint: null }],
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 390);
setToolWindowSize("right", 280);
toolWindowService().show("debug", true);
},
{ amountName, routingName, routingValue },
{ name, type, value, countName },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
const amount = debug.getByText("47.74", { exact: true });
await expect
.poll(() => amount.evaluate((el) => el.clientWidth > 0 && el.scrollWidth <= el.clientWidth + 1))
.toBe(true);
const routing = debug.getByRole("treeitem").filter({ hasText: routingName });
const show = routing.getByTitle("Show", { exact: true });
await expect(show).toBeInViewport({ ratio: 1 });
await show.click();
const dialog = page.getByRole("dialog", { name: `Value of ${routingName}` });
await expect(dialog.getByText(routingText, { exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
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();
await page.setViewportSize({ width: 1640, height: 760 });
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 } = await import(/* @vite-ignore */ layoutModule);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
moveToolWindow("debug", "bottom");
setToolWindowSize("bottom", 310);
});
await expect(show).toBeHidden();
await expect
.poll(() => routing.getByText(routingValue, { exact: true }).evaluate((el) => el.scrollWidth <= el.clientWidth + 1))
.toBe(true);
await expect.poll(() => annotation.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
});
+65 -1
View File
@@ -1,6 +1,6 @@
import type { EditorView } from "@codemirror/view";
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
import { expect, stubDesktop, test } from "./fixtures";
async function openChain(page: Page) {
await page.evaluate(async () => {
@@ -46,6 +46,70 @@ test("a narrow diff keeps navigation, settings and the difference count visible"
await expect(toolbar).toContainText("1 of 1 differences");
});
test("revision titles keep both filenames in view when the diff divider moves", async ({ workbench: page }) => {
const leftName = "OrderRoutes.ts";
const rightName = "OrdersRoutes.ts";
const directory = "services/customer-orders/fulfillment/warehouse-routing/primary";
await page.setViewportSize({ width: 800, height: 650 });
await stubDesktop(page);
await page.evaluate(
async ({ directory, leftName, rightName }) => {
const inputPath = "/src/features/vcs/diffInput.ts";
const layoutPath = "/src/workbench/toolwindows/store.ts";
const { openDiff } = await import(inputPath);
const { hideAllToolWindows } = await import(layoutPath);
const leftPath = `/dev/acme-api/${directory}/${leftName}`;
const rightPath = `/dev/acme-api/${directory}/${rightName}`;
window.__ipc.handlers.vcs_file_at = (args) =>
args.rev === "7b70e02c" ? "export const region = 'east';\r\n" : "export const region = 'west';\n";
window.__ipc.handlers.vcs_file_mode = () => "100644";
hideAllToolWindows();
localStorage.setItem("openidea.vcs.diffOptions", JSON.stringify({ mode: "split", alignChanges: false }));
await openDiff({
path: rightPath,
left: { type: "rev", rev: "7b70e02c", path: leftPath },
right: { type: "rev", rev: "a8c5f31d", path: rightPath },
});
},
{ directory, leftName, rightName },
);
const left = page.getByTitle(/^7b70e02c .*OrderRoutes\.ts$/);
const right = page.getByTitle(/^a8c5f31d .*OrdersRoutes\.ts$/);
const filenamesFit = async () => {
for (const [title, filename] of [
[left, leftName],
[right, rightName],
] as const) {
await expect(title).toBeVisible();
expect(await title.getAttribute("title")).toContain(`${directory}/${filename}`);
const text = title.locator("span").filter({ hasText: filename }).last();
expect(
await text.evaluate((el, filename) => {
const node = el.firstChild!;
const range = document.createRange();
range.setStart(node, (node.textContent ?? "").length - filename.length);
range.setEnd(node, (node.textContent ?? "").length);
const bounds = range.getBoundingClientRect();
const clip = el.getBoundingClientRect();
return bounds.left >= clip.left - 1 && bounds.right <= clip.right + 1;
}, filename),
`${filename} is visible within its revision label`,
).toBe(true);
}
};
await filenamesFit();
const divider = page.getByRole("separator", { name: "Resize diff panes" });
const { x, y, width, height } = (await divider.boundingBox())!;
const leftWidth = (await left.boundingBox())!.width;
await page.mouse.move(x + width / 2, y + height / 2);
await page.mouse.down();
await page.mouse.move(x + width / 2 - 96, y + height / 2, { steps: 4 });
await page.mouse.up();
await expect.poll(async () => (await left.boundingBox())!.width).toBeLessThan(leftWidth - 60);
await filenamesFit();
});
test("a medium-width diff keeps its full status beside the viewer tools", async ({ workbench: page }) => {
await page.setViewportSize({ width: 490, height: 650 });
await page.evaluate(async () => {
+1 -1
View File
@@ -526,7 +526,7 @@ test("Markdown preview keeps following find and edits after scrolling the source
await content.focus();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText("- **$`v_0`$ Flat wings.**");
await expect(preview.locator("strong .katex annotation")).toHaveText("v_0");
await expect(preview.locator("strong [data-math-svg] > svg")).toHaveAttribute("aria-label", "v_0");
});
test("Markdown preview aligns Mermaid diagrams to their container align attribute", async ({ workbench: page }) => {
+46
View File
@@ -69,3 +69,49 @@ test("the bottom single row keeps a long selected tab visible alongside the hidd
await pane.getByRole("tab", { name: shortFile, exact: true }).press("End");
await expectCloseToFit(tab);
});
test("same-name tabs keep the filename beside a shortened directory", async ({ workbench: page }) => {
const filename = "AllocationRule.ts";
const first = "qa";
const second = "backoffice-reconciliation";
await openSplit(page, [`${first}/${filename}`, `${second}/${filename}`], "top");
await page.setViewportSize({ width: 900, height: 760 });
const pane = page.locator("section[data-pane-id]").filter({
has: page.getByRole("tab").filter({ hasText: second }),
});
const selected = pane.getByRole("tab").filter({ hasText: second });
await expect(selected).toHaveText(`${second}/${filename}`);
await expectCloseToFit(selected);
const directory = selected.getByText(`${second}/`, { exact: true });
const name = selected.getByText(filename, { exact: true });
await expect.poll(() => directory.evaluate((el) => el.clientWidth > 0 && el.scrollWidth > el.clientWidth)).toBe(true);
await expect
.poll(() =>
name.evaluate((el) => {
const text = document.createRange();
text.selectNodeContents(el);
return el.getBoundingClientRect().width >= text.getBoundingClientRect().width;
}),
)
.toBe(true);
await pane.getByRole("button", { name: "Show Hidden Tabs" }).click();
const picker = page.getByRole("grid", { name: "Hidden Editor Tabs" });
await expect(picker.getByRole("gridcell").filter({ hasText: `${first}/${filename}` })).toBeVisible();
await page.keyboard.press("Enter");
const firstTab = pane.getByRole("tab").filter({ hasText: first });
await expectCloseToFit(firstTab);
await expect
.poll(() =>
firstTab.getByText(`${first}/`, { exact: true }).evaluate((el) => {
const text = document.createRange();
text.selectNodeContents(el);
return Math.abs(el.clientWidth - text.getBoundingClientRect().width);
}),
)
.toBeLessThanOrEqual(1);
await firstTab.locator("..").getByRole("button", { name: "Close Tab", exact: true }).click();
await expect(page.getByRole("tab", { name: filename, exact: true })).toHaveAttribute("aria-selected", "true");
});
+2 -2
View File
@@ -117,7 +117,7 @@ test("fits a wide graph and saved columns without horizontal scrolling", async (
expect(await list.evaluate((element) => element.scrollLeft)).toBe(0);
});
test("keeps ref names visible when a long commit subject competes for space", async ({ workbench: page }) => {
test("keeps expanded ref names visible when a long commit subject competes for space", async ({ workbench: page }) => {
const branch = "origin/feature/workspace-settings";
const tag = "v2.1";
const summary = "Keep workspace settings and commit references visible ".repeat(4).trim();
@@ -127,7 +127,7 @@ test("keeps ref names visible when a long commit subject competes for space", as
const options = "/src/features/vcs/logOptions.ts";
const { useGitLog } = await import(/* @vite-ignore */ log);
const { useLogOptions } = await import(/* @vite-ignore */ options);
useLogOptions.setState({ tagNames: true });
useLogOptions.setState({ tagNames: true, compactRefs: false });
const [first, ...rest] = useGitLog.getState().commits;
useGitLog.setState({ commits: [{ ...first, summary, refs: [branch, `tag: ${tag}`] }, ...rest] });
},
+51
View File
@@ -112,6 +112,57 @@ test("Git Log separates commit message typography from compact metadata", async
await expect(author).toHaveCSS("font-size", "12px");
});
test("compact Git Log refs give the subject room on either side", async ({ workbench: page }) => {
await page.setViewportSize({ width: 630, height: 720 });
const refSubject = "Reconcile shipping credits";
const longReference = "release-quarterly-settlement-and-backoffice-invoice-reconciliation";
await page.evaluate(
async ({ refSubject, longReference }) => {
const optionsModule = "/src/features/vcs/logOptions.ts";
const logModule = "/src/features/vcs/logStore.ts";
const { setLogOptions } = await import(/* @vite-ignore */ optionsModule);
const { useGitLog } = await import(/* @vite-ignore */ logModule);
setLogOptions({ showBranches: false, showDetails: false });
const [first, ...rest] = useGitLog.getState().commits;
useGitLog.setState({
commits: [{ ...first, summary: refSubject, message: refSubject, refs: [longReference] }, ...rest],
});
},
{ refSubject, longReference },
);
const row = page.getByRole("listbox", { name: "Commits" }).getByRole("option").filter({ hasText: refSubject });
const subject = row.getByText(refSubject, { exact: true });
const ref = row.getByTitle(longReference, { exact: true });
const expectLayout = async () => {
await expect
.poll(() =>
subject.evaluate((el) => {
const text = document.createRange();
text.selectNodeContents(el);
return el.getBoundingClientRect().width + 0.02 >= text.getBoundingClientRect().width;
}),
)
.toBe(true);
await expect
.poll(() =>
ref.evaluate((el) => {
const refs = el.parentElement!;
return refs.clientWidth / refs.parentElement!.clientWidth;
}),
)
.toBeLessThanOrEqual(0.34);
await expect(ref).toHaveCSS("font-size", "12px");
await expect(subject).toHaveCSS("font-size", "13px");
};
await expectLayout();
await expect.poll(async () => (await subject.boundingBox())!.x < (await ref.boundingBox())!.x).toBe(true);
await page.getByRole("toolbar", { name: "Log filters" }).getByRole("button", { name: "View Options" }).click();
await page.getByRole("menuitemcheckbox", { name: "References on the Left" }).click();
await expectLayout();
await expect.poll(async () => (await subject.boundingBox())!.x > (await ref.boundingBox())!.x).toBe(true);
});
test("a second click on a Git Log toolbar button closes its popup", async ({ workbench: page }) => {
const toolbar = page.getByRole("toolbar", { name: "Log filters" });
const branchPopup = page.getByRole("dialog", { name: "Filter by Branch" });
+39
View File
@@ -93,3 +93,42 @@ test("Recent Locations keeps all snippet lines visible when the editor font grow
await expect(row.getByText("changed", { exact: true })).toBeInViewport({ ratio: 1 });
await expect(filter).toBeFocused();
});
test("Recent Locations shows each file name once with its parent directory", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const tracking = "/src/features/search/common/tracking.ts";
const { useTracking } = await import(/* @vite-ignore */ tracking);
const now = Date.now();
useTracking.setState({
locations: [
["README.md", "# Shop API"],
["packages/billing/Routes.ts", "registerBillingRoutes();"],
["packages/checkout/Routes.ts", "registerCheckoutRoutes();"],
].map(([path, snippet], index) => ({
path: `/dev/acme-api/${path}`,
line: 0,
col: 0,
changed: false,
time: now - index * 60000,
snippet: [snippet],
snippetStart: 0,
})),
});
});
await openRecent(page, "recentLocations");
const dialog = page.getByRole("dialog", { name: "Recent Locations", exact: true });
const rows = dialog.getByRole("option");
await expect(rows).toHaveCount(3);
await expect(rows.filter({ hasText: "# Shop API" }).getByText("README.md", { exact: true })).toHaveCount(1);
const billing = rows.filter({ hasText: "registerBillingRoutes();" });
const checkout = rows.filter({ hasText: "registerCheckoutRoutes();" });
await expect(billing.getByText("packages/billing", { exact: true })).toBeVisible();
await expect(checkout.getByText("packages/checkout", { exact: true })).toBeVisible();
await expect(checkout.getByTitle("packages/checkout/Routes.ts", { exact: true })).toBeVisible();
await dialog.getByRole("textbox", { name: "Filter recent locations" }).fill("packages/checkout");
await expect(rows).toHaveCount(1);
await expect(rows.first()).toContainText("registerCheckoutRoutes();");
});
+63
View File
@@ -0,0 +1,63 @@
import { expect, test } from "./fixtures";
test("the workspace refactoring preview separates filenames from directories and keeps outcomes readable", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 420, height: 620 });
await page.evaluate(async () => {
const popupPath = "/src/editor/lsp/popupStore.ts";
const editPath = "/src/editor/lsp/workspaceEdit.ts";
const { openPopup } = await import(/* @vite-ignore */ popupPath);
const { summarizeWorkspaceEdit } = await import(/* @vite-ignore */ editPath);
const root = "/dev/acme-api";
const edit = {
range: { start: { line: 0, col: 0 }, end: { line: 0, col: 9 } },
new_text: "postInvoice",
};
openPopup({
kind: "preview",
title: "Rename 'saveOrder' to 'postInvoice'",
summary: summarizeWorkspaceEdit({
files: [
{ kind: "edit", path: `${root}/README.md`, edits: [edit] },
{ kind: "edit", path: `${root}/packages/billing/src/Routes.ts`, edits: [edit, edit] },
{ kind: "edit", path: `${root}/packages/checkout/src/Routes.ts`, edits: [edit] },
{
kind: "rename",
from: `${root}/packages/checkout/src/Invoice.ts`,
to: `${root}/packages/checkout/src/InvoiceReconciliationForInternationalOrders.ts`,
},
],
}),
renameThemeClasses: "",
confirmLabel: "Do Refactor",
onConfirm: () => {
document.body.dataset.refactorConfirmed = "true";
},
});
});
const dialog = page.getByRole("dialog", { name: "Rename 'saveOrder' to 'postInvoice'" });
const rows = dialog.getByRole("list", { name: "Changes" }).getByRole("listitem");
await expect(rows).toHaveCount(4);
await expect(dialog.getByText("4 occurrences in 4 files")).toBeVisible();
const root = rows.filter({ hasText: "README.md" });
await expect(root.getByText("README.md", { exact: true })).toHaveCount(1);
const billing = rows.filter({ hasText: "2 occurrences" });
await expect(billing.getByText("Routes.ts", { exact: true })).toBeVisible();
await expect(billing.getByText("packages/billing/src", { exact: true })).toBeVisible();
await expect(billing.getByTitle("packages/billing/src/Routes.ts", { exact: true })).toBeVisible();
const checkout = rows.filter({ hasText: "packages/checkout/src" }).filter({ hasText: "Routes.ts" });
await expect(checkout.getByText("packages/checkout/src", { exact: true })).toBeVisible();
const rename = rows.filter({ hasText: "Invoice.ts" });
const target = rename.getByText("→ InvoiceReconciliationForInternationalOrders.ts", { exact: true });
await expect(target).toBeVisible();
await expect(target).toHaveAttribute("title", "packages/checkout/src/InvoiceReconciliationForInternationalOrders.ts");
expect((await target.boundingBox())!.width).toBeGreaterThan(35);
await expect(dialog.getByRole("button", { name: "Do Refactor", exact: true })).toBeInViewport();
await dialog.getByRole("button", { name: "Do Refactor", exact: true }).click();
await expect(dialog).toBeHidden();
await expect(page.locator("body")).toHaveAttribute("data-refactor-confirmed", "true");
});
+164
View File
@@ -76,6 +76,73 @@ test("⌃R runs the selected configuration and shows its output and exit", async
expect(started).toMatchObject({ config: { id: "npm:dev", command: "npm", args: ["run", "dev"] } });
});
test("expanded console folds stay reachable at the start of their rows", async ({ workbench: page }) => {
const heading = "Reconciling orders for the overnight settlement and inventory reporting pipeline";
await stubRun(
page,
[
{
kind: "stdout",
text: [
"TRACE Reused inventory connection",
"TRACE Loaded warehouse configuration",
heading,
"TRACE Checked warehouse audit result",
"TRACE Updated inventory snapshot",
"Processed 24 orders",
"",
].join("\n"),
},
],
null,
);
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
const { settings } = useProject.getState();
useProject.setState({
settings: { ...settings, console: { ...settings?.console, foldPatterns: ["TRACE "] } },
});
moveToolWindow("run", "right");
setToolWindowSize("right", 320);
});
await page.keyboard.press("Control+r");
const log = page.getByRole("region", { name: "Run", exact: true }).getByRole("log");
const expand = log.getByTitle("Expand folded lines", { exact: true });
const collapse = log.getByRole("button", { name: "Collapse folded lines", exact: true });
await expect(expand).toHaveCount(2);
await expand.first().click();
await expect(log.getByText("TRACE Reused inventory connection", { exact: true })).toBeVisible();
await expect(collapse).toHaveCount(1);
await collapse.press("Space");
await expect(expand).toHaveCount(2);
await expand.first().press("Enter");
await expect(collapse).toBeFocused();
await expand.last().click();
await expect(collapse).toHaveCount(2);
for (const scrollLeft of [0, 120]) {
await log.evaluate((element, x) => (element.scrollLeft = x), scrollLeft);
expect(await log.evaluate((element) => element.scrollLeft)).toBe(scrollLeft);
for (const control of await collapse.all()) {
const aligned = await control.evaluate((button) => {
const log = button.closest('[role="log"]')!.getBoundingClientRect();
const row = button.closest("[data-index]")!.getBoundingClientRect();
const box = button.getBoundingClientRect();
return Math.abs(box.left - log.left) <= 1 && box.top >= row.top && box.bottom <= row.bottom + 1;
});
expect(aligned).toBe(true);
}
}
await collapse.first().click();
await collapse.first().click();
await expect(expand).toHaveCount(2);
expect(await ipcCalls(page, "run_stdin")).toEqual([]);
});
test("⌘F2 stops a running process", async ({ workbench: page }) => {
await stubRun(page, [{ kind: "stdout", text: "Watching for changes…\n" }], null);
await page.keyboard.press("Control+r");
@@ -122,6 +189,45 @@ test("a long Run tab fits its side panel with room for the pin and close buttons
await expect(run).toBeHidden();
});
test("the Run toolbar keeps primary actions in one row in a side dock", async ({ workbench: page }) => {
const output = "Waiting for orders. ".repeat(8).trim();
await stubRun(page, [{ kind: "stdout", text: `${output}\n` }], null);
const dock = async (width: number) => {
await page.evaluate(async (width) => {
const path = "/src/workbench/toolwindows/store.ts";
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ path);
moveToolWindow("run", "right");
setToolWindowSize("right", width);
}, width);
};
await dock(200);
await page.keyboard.press("Control+r");
const run = page.getByRole("region", { name: "Run", exact: true });
const toolbar = run.getByRole("toolbar", { name: "Run actions" });
const console = run.getByRole("log");
await expect(console).toContainText(output);
await expect
.poll(() => toolbar.evaluate((el) => new Set([...el.querySelectorAll("button")].map((b) => b.offsetTop)).size))
.toBe(1);
const more = toolbar.getByRole("button", { name: "More Actions" });
const menu = page.getByRole("menu", { name: "More Actions" });
await more.press("Enter");
const wrap = menu.getByRole("menuitemcheckbox", { name: "Soft-Wrap" });
await expect(wrap).toHaveAttribute("aria-checked", "false");
await expect(menu.getByRole("menuitemcheckbox", { name: "Scroll to End" })).toHaveAttribute("aria-checked", "true");
await wrap.click();
await expect(menu).toBeHidden();
await expect.poll(() => console.evaluate((el) => el.scrollWidth <= el.clientWidth + 1)).toBe(true);
await dock(340);
await expect(toolbar.getByRole("button", { name: "Soft-Wrap" })).toHaveAttribute("aria-pressed", "true");
await expect(toolbar.getByRole("button", { name: "Scroll to End" })).toBeVisible();
await more.click();
await expect(menu.getByRole("menuitemcheckbox")).toHaveCount(0);
await menu.getByRole("menuitem", { name: "Edit Configurations…" }).click();
await expect(page.getByRole("dialog", { name: "Run/Debug Configurations" })).toBeVisible();
});
test("a short Run pane has room for the full toolbar above the output", async ({ workbench: page }) => {
await page.setViewportSize({ width: 400, height: 500 });
const output = "Watching for changes…";
@@ -284,6 +390,64 @@ 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";
+8 -2
View File
@@ -2,7 +2,7 @@ import type { Locator, Page } from "@playwright/test";
import { expect, test } from "./fixtures";
for (const height of [990, 700, 560]) {
test(`run configurations dialog keeps its toolbar and scrolls only inside the panes at ${height}px`, async ({
test(`run configurations dialog keeps its toolbar and name visible while scrolling at ${height}px`, async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 900, height });
@@ -62,9 +62,13 @@ async function resize(page: Page, dialog: Locator, dy: number) {
async function checkScrolling(page: Page, dialog: Locator) {
const body = dialog.locator("[data-dialog-body]");
const list = dialog.getByRole("tree", { name: "Run configurations", exact: true });
const form = dialog.locator('[class*="_editForm_"]');
const form = dialog.locator('[class*="_formSettings_"]');
const nameField = dialog.getByRole("textbox", { name: "Name", exact: true });
await list.evaluate((el) => (el.scrollTop = 0));
await form.evaluate((el) => (el.scrollTop = 0));
// Measure once the dialog's opening animation has settled.
await dialog.evaluate((el) => Promise.all(el.getAnimations().map((animation) => animation.finished)));
const nameTop = (await nameField.boundingBox())!.y;
await list.hover();
await page.mouse.wheel(0, 200);
await expect.poll(() => list.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
@@ -74,6 +78,8 @@ async function checkScrolling(page: Page, dialog: Locator) {
await page.mouse.wheel(0, 200);
await expect.poll(() => form.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
expect(await list.evaluate((el) => el.scrollTop)).toBe(listTop);
expect((await nameField.boundingBox())!.y).toBeCloseTo(nameTop, 0);
await expect(dialog.getByRole("checkbox", { name: /Store as project file/ })).toBeInViewport({ ratio: 1 });
const overflow = await body.evaluate((el) => ({
scroll: el.scrollHeight,
client: el.clientHeight,
+3 -3
View File
@@ -112,7 +112,7 @@ test("resizing the configuration dialog grows its panes and keeps the footer vis
await expect(dialog.getByRole("tree", { name: "Run configurations", exact: true })).toBeVisible();
await expect.poll(async () => (await content.boundingBox())!.height).toBeLessThan(initial);
await expect
.poll(() => dialog.locator("[class*='editForm_']").evaluate((el) => el.scrollHeight - el.clientHeight))
.poll(() => dialog.locator("[class*='_formSettings_']").evaluate((el) => el.scrollHeight - el.clientHeight))
.toBeGreaterThan(0);
});
@@ -144,7 +144,7 @@ test("Java, npm and Python forms fit narrow and zoomed content panes", async ({
for (const width of [1024, 640, 520]) {
await page.setViewportSize({ width, height: 820 });
await expect
.poll(() => dialog.locator("[class*='editForm_']").evaluate((el) => el.scrollWidth - el.clientWidth), {
.poll(() => dialog.locator("[class*='_formSettings_']").evaluate((el) => el.scrollWidth - el.clientWidth), {
message: `${kind}, ${width}px, ${zoom * 100}%`,
})
.toBeLessThanOrEqual(1);
@@ -204,7 +204,7 @@ for (const locale of ["en", "zh"]) {
)
.toMatchObject({ overflow: expect.any(Number), footerFits: true, footerVisible: true });
await expect
.poll(() => dialog.locator("[class*='editForm_']").evaluate((el) => el.scrollWidth - el.clientWidth))
.poll(() => dialog.locator("[class*='_formSettings_']").evaluate((el) => el.scrollWidth - el.clientWidth))
.toBeLessThanOrEqual(1);
const tasks = dialog.getByRole("list");
await tasks.scrollIntoViewIfNeeded();
+18 -6
View File
@@ -5,6 +5,8 @@
import type { Page } from "@playwright/test";
import { expect, stubDesktop, test } from "./fixtures";
const LONG_RESULT_PATH = "config/RegionalOrderReconciliationEndpointsForSandboxEnvironments.txt";
async function run(page: Page, id: string) {
await page.evaluate(async (id) => {
const actionsModule = "/src/platform/actions.ts";
@@ -15,15 +17,16 @@ async function run(page: Page, id: string) {
async function stubFindMatches(page: Page) {
await stubDesktop(page);
await page.evaluate(() => {
await page.evaluate((longPath) => {
window.__ipc.handlers.search_validate = () => null;
window.__ipc.handlers.search_start = (args) => {
const send = (event: unknown) => window.__ipc.send(args.onEvent, event);
const text = "base=http://localhost:8080";
setTimeout(() => {
for (let i = 0; i < 12; i++) {
const relPath = `config/endpoint-${i}.txt`;
const matches = [{ line: 0, text, ranges: [[5, text.length]], textOffset: 0 }];
const relPath = i === 0 ? longPath : `config/endpoint-${i}.txt`;
const lines = i === 0 ? [12344, 12345] : [0];
const matches = lines.map((line) => ({ line, text, ranges: [[5, text.length]], textOffset: 0 }));
send({
type: "file",
file: { path: `/dev/acme-api/${relPath}`, relPath, matches },
@@ -31,12 +34,12 @@ async function stubFindMatches(page: Page) {
}
send({
type: "done",
summary: { files: 12, matches: 12, limitHit: false, cancelled: false, elapsedMs: 4 },
summary: { files: 12, matches: 13, limitHit: false, cancelled: false, elapsedMs: 4 },
});
}, 20);
return null;
};
});
}, LONG_RESULT_PATH);
}
async function expectControlsFit(page: Page) {
@@ -74,7 +77,8 @@ test.describe("search popups at the minimum window width", () => {
await expect(page.getByRole("dialog").locator("header [aria-live]")).toContainText(/match/);
const dialog = page.getByRole("dialog");
const title = dialog.getByText(id === "find.inPath" ? "Find in Files" : "Replace in Files", { exact: true });
const count = dialog.getByText("12 matches in 12 files", { exact: true });
const count = dialog.getByText("13 matches in 12 files", { exact: true });
const line = dialog.getByText("12345", { exact: true });
for (const [width, height] of [
[400, 500],
[600, 700],
@@ -87,6 +91,14 @@ test.describe("search popups at the minimum window width", () => {
expect(
await text.evaluate((el) => el.getClientRects().length === 1 && el.scrollWidth <= el.clientWidth),
).toBe(true);
await expect(line).toBeVisible();
expect(
await line.evaluate(
(el) => el.getBoundingClientRect().right <= el.parentElement!.getBoundingClientRect().right + 0.5,
),
"the line number fits even when the long filename is elided",
).toBe(true);
await expect(line.locator("..").getByTitle(LONG_RESULT_PATH)).toBeVisible();
for (const name of ["Search Context", "Pin Window"])
await dialog.getByRole("button", { name, exact: true }).click({ trial: true });
}
+33
View File
@@ -1,5 +1,38 @@
import { expect, test } from "./fixtures";
test("keeps the current settings page name readable when the path is wider than the pane", async ({
workbench: page,
}) => {
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const search = settings.getByRole("textbox", { name: "Search settings" });
await search.fill("Maven");
const path = settings.getByLabel("Breadcrumb", { exact: true });
const parent = path.getByText("Build, Execution, Deployment", { exact: true });
const current = path.getByText("Maven", { exact: true });
await expect(current).toBeVisible();
await search.clear();
for (const width of [400, 560, 1120]) {
await page.setViewportSize({ width, height: 720 });
await expect
.poll(() =>
current.evaluate((label) => {
const box = label.getBoundingClientRect();
const trail = label.closest("[aria-label=Breadcrumb]")!.getBoundingClientRect();
return label.clientWidth >= label.scrollWidth && box.width > 0 && box.right <= trail.right + 1;
}),
)
.toBe(true);
}
await expect(parent).toBeInViewport({ ratio: 1 });
expect(await parent.evaluate((label) => label.scrollWidth <= label.clientWidth)).toBe(true);
await settings.getByRole("button", { name: "Back", exact: true }).click();
await expect(current).toBeHidden();
await settings.getByRole("button", { name: "Forward", exact: true }).click();
await expect(current).toBeVisible();
});
test("dirty settings keep scope labels and navigation inside the page header", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
await expect(page.getByRole("dialog", { name: "Settings", exact: true })).toBeVisible();
+29
View File
@@ -0,0 +1,29 @@
import { expect, test } from "./fixtures";
test("template literals highlight and comment in their embedded language", async ({ workbench: page }) => {
await page.evaluate(async () => {
const backendPath = "/src/editor/core/backend.ts";
const contributionsPath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(contributionsPath);
docBackend().files.set(
"/dev/acme-api/styles.ts",
"const Button = styled.button`\n padding: 4px;\n`;\nconst QUERY = gql`\n query Cart { total }\n`;\nconst plain = `margin: 0`;\n",
);
await editorService().openFile("/dev/acme-api/styles.ts");
});
const content = page.locator('.cm-editor[data-language="TypeScript"] .cm-content');
await expect(content).toBeVisible();
// Each word of an embedded language is a token of its own; a plain literal stays one string.
await expect(content.locator("span").filter({ hasText: /^padding$/ })).toBeVisible();
await expect(content.locator("span").filter({ hasText: /^query$/ })).toBeVisible();
await expect(content.locator("span").filter({ hasText: /^`margin: 0`$/ })).toBeVisible();
await content.evaluate((element) => {
const view = (element as HTMLElement & { cmTile: { view: import("@codemirror/view").EditorView } }).cmTile.view;
view.dispatch({ selection: { anchor: view.state.doc.toString().indexOf("query") } });
view.focus();
});
await page.keyboard.press("Meta+/");
await expect(content).toContainText("# query Cart { total }");
});
+45
View File
@@ -0,0 +1,45 @@
import { expect, test } from "./fixtures";
test("Show Usages distinguishes same-named files without losing the line or snippet", async ({ workbench: page }) => {
await page.setViewportSize({ width: 480, height: 620 });
await page.evaluate(async () => {
const usages = "/src/features/code-insight/usages.ts";
const { useUsagesPopup } = await import(/* @vite-ignore */ usages);
const symbol = "submitOrder";
useUsagesPopup.setState({
open: true,
anchor: { x: 30, y: 90 },
symbol,
groups: (
[
["/dev/acme-api/packages/billing/src/Routes.ts", "return submitOrder(invoice);"],
["/dev/acme-api/packages/checkout/src/Routes.ts", "return submitOrder(cart);"],
["/dev/acme-api/src/Worker.ts", "await submitOrder(job);"],
] as const
).map(([path, text]) => {
const col = text.indexOf(symbol);
return { path, usages: [{ path, line: 6, col, endCol: col + symbol.length, text }] };
}),
});
});
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
const rows = popup.getByRole("option");
const billing = rows.filter({ hasText: "invoice" });
const checkout = rows.filter({ hasText: "cart" });
await expect(rows).toHaveCount(3);
for (const [row, directory] of [
[billing, "billing"],
[checkout, "checkout"],
] as const) {
await expect(row.getByText("Routes.ts", { exact: true })).toBeVisible();
const caption = row.getByText(directory, { exact: true });
await expect(caption).toBeVisible();
expect(await caption.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(row.getByText("7", { exact: true })).toBeVisible();
await expect(row.locator("mark")).toHaveText("submitOrder");
}
await expect(checkout.getByTitle("/dev/acme-api/packages/checkout/src/Routes.ts", { exact: true })).toBeVisible();
await expect(rows.filter({ hasText: "Worker.ts" }).getByText("src", { exact: true })).toHaveCount(0);
});
+6 -1
View File
@@ -9,6 +9,9 @@ something to show.
| ---------------- | --------------------------------------------------------------- | ----------------------------------- | -------------------- | ------------------------------------- | -------------------------------------------------------- |
| `rust-app/` | cargo | `cargo run` | `cargo test` | `cargo test --features failing-tests` | unused variable in `src/parser.rs` |
| `ts-app/` | Node 22+, pnpm/npm | `pnpm start` | `pnpm test` (vitest) | `OPENIDEA_FAIL=1 pnpm test` | unused function in `src/index.ts` |
| `playwright-app/` | Node 22+, npm (Playwright Test, no browser needed) | — | `npm test` | `OPENIDEA_FAIL=1 npm test` | unused function in `src/checkout.ts` |
| `node-test-app/` | Node 22+, npm (no dependencies) | — | `npm test` (node:test) | `OPENIDEA_FAIL=1 npm test` | unused constant in `src/inventory.js` |
| `mocha-app/` | Node 22+, npm | — | `npm test` (Mocha) | `OPENIDEA_FAIL=1 npm test` | unused constant in `src/pricing.js` |
| `python-app/` | Python 3.10+, pytest | `python -m tasks.cli` (from `src/`) | `pytest` | `OPENIDEA_FAIL=1 pytest` | unused imports in `models.py` |
| `go-app/` | Go 1.22+ | `go run ./cmd/server` | `go test ./...` | `OPENIDEA_FAIL=1 go test ./...` | unused `fmt.Sprintf` result in `internal/store/store.go` |
| `kotlin-gradle/` | JDK 21, Gradle 8 (no wrapper) | `gradle run` | `gradle test` | `gradle test -PopenideaFail` | unused variable in `App.kt` |
@@ -16,7 +19,9 @@ something to show.
| `c-app/` | gcc / g++ 12+, make, GDB 14+ | `make all` | — | — | — |
| `php-app/` | PHP 8.5, Composer | `composer quote` | `vendor/bin/pest` | `OPENIDEA_FAIL=1 vendor/bin/pest` | unused variable in `ThresholdCustoms.php` |
| `django-app/` | Python 3.10+, Django 5.2+ | `python manage.py runserver` | `python manage.py test` | `OPENIDEA_FAIL=1 python manage.py test` | unused import in `shop/views.py` |
| `tailwind-app/` | Node 22+, pnpm/npm, Tailwind CSS 4, React | `pnpm dev` | — | — | `flex` conflicting with `block` in `src/App.tsx` |
| `zig-app/` | Zig 0.17 | `zig build run` | `zig build test` | — | — |
| `biome-app/` | Node 22+, `@biomejs/biome` (`npm install`) | `npm start` | — | — | `let` never reassigned, `==` and a duplicate CSS `color` (Biome) |
| `polyglot/` | Go, TS, Python, C, shell, SQL, TOML/YAML/JSON, proto, Terraform | `make` | `make test` | — | unused variable in `native/hash.c` |
The fixtures are standalone: `rust-app` declares its own `[workspace]` and
@@ -39,7 +44,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` / `mocha-app` / `polyglot/web` run `pnpm install` first (`npm install` for `biome-app`); 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`).
+27
View File
@@ -0,0 +1,27 @@
{
"$schema": "https://biomejs.dev/schemas/2.6.8/schema.json",
"files": {
"includes": ["**", "!node_modules"]
},
"formatter": {
"enabled": true,
"indentStyle": "space",
"indentWidth": 2,
"lineWidth": 100
},
"javascript": {
"formatter": {
"quoteStyle": "single"
}
},
"linter": {
"enabled": true,
"rules": {
"preset": "recommended",
"style": {
"useConst": "error",
"useTemplate": "warn"
}
}
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"name": "openidea-fixture-biome",
"version": "0.1.0",
"private": true,
"description": "OpenIDEA QA fixture: Biome lint diagnostics, fixes and formatting",
"type": "module",
"scripts": {
"start": "node --experimental-strip-types src/index.ts",
"lint": "biome lint",
"format": "biome format --write",
"check": "biome check"
},
"devDependencies": {
"@biomejs/biome": "2.6.8"
}
}
+21
View File
@@ -0,0 +1,21 @@
export interface Item {
name: string
price: number
quantity: number
}
export function total(items: Item[]): number {
let sum = 0
for (const item of items) sum += item.price * item.quantity
return sum
}
// Intentional Biome problems: `let` never reassigned (useConst, safe fix),
// string concatenation (useTemplate) and `==` (noDoubleEquals).
export function describe(items: Item[]): string {
let label = "Cart: " + items.length + " items"
if (items.length == 0) {
return "Cart is empty"
}
return label
}
+2
View File
@@ -0,0 +1,2 @@
{ "currency": "EUR",
"discounts": [ 5, 10,15 ] }
+9
View File
@@ -0,0 +1,9 @@
import { describe, total, type Item } from "./cart.ts"
const items: Item[] = [
{ name: "Notebook", price: 4.5, quantity: 2 },
{ name: "Pen", price: 1.25, quantity: 4 },
]
// Set a breakpoint here
console.log(describe(items), "-", total(items).toFixed(2))
Loaded 100 of 315 files, more files were not shown because too many files have changed in this diff. Show more