Compare commits

...
Author SHA1 Message Date
l0ng-ai 19207f1102 fix(agents): keep selection highlights within reply text 2026-11-24 14:55:39 +08:00
Deng Liu 51766249f9 fix(services): keep Docker Compose dashboard actions pinned on scroll (#5534) 2026-11-24 14:47:11 +08:00
l0ng-ai ff55bcdf9a fix(vcs): keep Git Log file selection in place (#5563) 2026-11-24 13:52:30 +08:00
l0ng-ai fd6d1d5d0e ci(smoke): build the smoke binaries once for every language (#5395)
Each language job compiled the language_smoke / project_smoke tests and
openidea-server itself, about 4-5 minutes of the same work nine times. A
build job now compiles them once and hands them on as an artifact; the
language jobs only install their tools and run the binaries.
2026-11-24 13:25:13 +08:00
l0ng-ai 9ad5bad82e fix(vcs): refresh status after git commands run outside the IDE in subfolder projects, worktrees and submodules (#5555)
The project file watcher only reports Git metadata in the .git folders it
sees: the project root's and nested repositories'. When the project is a
subfolder of its repository, a linked worktree, a mapped repository
elsewhere, or a submodule (.git/modules/<name>), a commit, checkout or
reset in a terminal wrote nothing the watcher reported, so file statuses
stayed stale until something else triggered a refresh.

Watch HEAD, index, packed-refs and refs/** of those git directories, follow
repository changes, and emit VcsChanged for them (ignoring the IDE's own
index writes).
2026-11-24 13:25:08 +08:00
l0ng-ai fec50f3925 fix(agents): show a sent message before recording the turn checkout (#5536)
The user's message was only added to the conversation after the pre-turn checkout was recorded, which can take seconds in a large repository, so pressing Enter appeared to do nothing and the view did not scroll to the new message.
2026-11-24 12:15:56 +08:00
l0ng-ai 8b3d9adcfe fix(agents): keep the new-task composer height when typing the first character (#5535)
The home composer's taller minimum height overrode the composer rule by selector, so stylesheet load order could reset it to the single-line height once CodeMirror re-rendered. The home view now sets a --composer-min-height variable that the composer rule reads.
2026-11-24 12:15:49 +08:00
l0ng-ai 457174a442 feat(workbench): keep rarely used tool windows off the stripe by default (#5531)
Bookmarks and TODO are listed under the stripe's "…" until first opened. The Database
window is on the stripe by default only while the project has data sources. Of the
Flutter DevTools windows only Flutter Inspector has a stripe button; Deep Links,
DevTools and DevTools Extensions wait under "…". A user's own stripe choice still wins.
2026-11-24 12:15:23 +08:00
Deng Liuanddengliu de868f1677 feat(remote): persist remote backend, terminals, runs, agents, and workbench state across window close (#4385)
Closing a remote window (SSH, WSL, Dev Containers) used to end openidea-server --stdio and tear down terminals, runs (running their stop commands), indexing and agent turns. openidea-server --attach now connects through a detached per-project daemon (private 0700 run dir, owner check, flock) that keeps them alive across disconnects; reopening reattaches terminals with bounded scrollback and OSC state, runs and agent turns, and restores remote editor tabs, tool windows and plugin views. The close dialog offers Keep Backend Running / Stop Backend; Stop Remote Backend shuts the daemon down on demand. A disconnected backend with no live work exits after an idle timeout (3 hours by default; presets, custom or Never in Settings › Tools › Remote Development, host override wins). The socket is keyed by project, so a new build replaces an idle backend of another build and reports a busy one; a window taken over by another shows that instead of a dropped connection. Clean documents are released on disconnect while dirty buffers keep the backend alive.

Also: a plugin-owned PTY keeps its exit hook across reattach (reattach only rebinds the forwarding sink), and a recent project clicked again while it is still opening joins that attempt instead of connecting twice (a double click made the second attach take over and fail the first).

Co-authored-by: dengliu <[email protected]>
2026-11-24 11:42:00 +08:00
l0ng-ai e27fc0d867 refactor(run): remove the npm tool window
Detected npm scripts are already in the run configuration list and runnable from the
package.json gutter. Remove the separate npm tool window, its package scan and e2e spec.
The editor context menu Run / Debug on a package.json script line stays.
2026-11-24 10:59:41 +08:00
l0ng-ai c50c2ea629 feat(editor): support Helm and Go templates (#5522)
Helm chart manifests and .tpl helpers keep YAML highlighting with Go template actions and are served by helm-ls (installable from Settings › Language Servers, pinned 0.5.4). Standalone .gotmpl / .tmpl / .go.tmpl files are a Go Template language: template actions highlighted, the Go icon, and gopls. Adds a small chart fixture.
2026-11-24 10:50:03 +08:00
l0ng-ai 3e9e86edf1 fix(services): keep a disconnected Docker connection disconnected across restarts (#5519)
Disconnecting a Docker connection in Services was remembered only in memory, so after a restart opening Services dialled every saved connection again (including SSH ones the user had disconnected). The Disconnect intent is now saved per connection; panel startup and the 10 s poll skip it until Connect clears the flag. Older settings keep connecting automatically.
2026-11-24 10:36:20 +08:00
l0ng-ai cb24be4c19 docs(readme): switch the WeChat group QR code to group 4 2026-11-24 10:32:53 +08:00
l0ng-ai 52e3276f93 test(ide-host): compile the code action stub only where its test runs (#5516)
The code action stub carries the cfg(unix) of its only test, fixing Windows clippy on main.
2026-11-24 10:24:30 +08:00
l0ng-ai fcf5406de0 fix(keymap): list Smart Type completion and Rearrange Code in every preset (#5515)
Smart Type completion is in the VS Code preset and Rearrange Code is listed (no default shortcut) in the IntelliJ and VS Code presets, fixing the keymap and Vim :action tests on main.
2026-11-24 10:22:47 +08:00
Deng Liuanddengliu aee72d994e chore(dev): replace dogfood:build/install with dogfood:local and dogfood:all (#5271)
dogfood:local builds and installs the local dogfood app (--build-only skips installation); dogfood:all <remote_name> runs it alongside dogfood:remote in parallel with [local]/[remote] prefixed output, validates the SSH configuration before the local build starts, stops the sibling process tree on failure, and runs the remote restart prompt once after both finish. AGENTS.md, mise tasks and the setup docs use the new names.

Co-authored-by: dengliu <[email protected]>
2026-11-24 08:57:51 +08:00
LU XIANGRUIandwildcatDownstairs 397522e099 feat(editor): show language server colors in the gutter (#5229)
Tailwind color classes (`bg-red-500`, `text-brand-700`, `@apply bg-brand-500` in CSS) and the colors a CSS server knows beyond the built-in literal detector (`hwb()`…) now show swatches in the editor gutter. This was the remaining acceptance criterion of #5154. The editor never asked language servers for `textDocument/documentColor`; it only drew swatches for literals it found itself and for colors that plugins reported.
- Backend (`ide-lsp`): the client advertises `colorProvider`. `document_colors` asks every server that has it and tags each color with its server, then drops the answer if the document version changed in the meantime. `color_presentations` asks that server for `textDocument/colorPresentation`. A presentation without its own `textEdit` replaces the color's range with its label. New commands `lsp_document_colors` / `lsp_color_presentations`; bindings regenerated.
- Frontend (`color-preview`): `lspColors.ts` sits next to the plugin source and shares its swatch and picker flow, now in `providerSwatch.ts`. A server color gets no swatch when the built-in detector already shows a literal at the same range, and two servers reporting the same range (CSS + Tailwind) get one swatch. The gutter follows Settings › Editor › General › Gutter Icons › Color preview, and while that is off the editor sends no requests. Picking a color applies the server's single presentation, or offers a menu when there are several.
- Tailwind only presents arbitrary values (`border-[#16a34a]` → `border-[#2563eb]` / `[rgb(…)]` / `[hsl(…)]`). For palette classes like `bg-red-500` it returns none, as in VS Code. In that case a hint says the color can't be changed with the picker (new string, en + zh).

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 08:45:02 +08:00
LU XIANGRUIandwildcatDownstairs f7e1dbe5eb feat(python): suppress the IDE's Python inspections with # noinspection comments (#5341)
The IDE's own Python inspections (Circular inheritance, Inconsistent '@override', Abstract method not implemented, Redundant override) could only be turned off for the whole profile. They now honour PyCharm's `# noinspection <Id>` comment (several ids comma-separated, or `ALL`): directly above a statement it covers that statement, above a `def` / `class` (or its decorators) the whole definition, and among the file's leading comments followed by a blank line the whole file. The parser reports these regions with the Python facts the inspections already read. Alt+Enter on such a problem offers Suppress for statement / function / class, which writes the comment at the definition's indentation or adds the id to a `# noinspection` comment already there.
While testing, the ⌥↵ options row for these problems read "Python builtin:python-abstract-method", and Disable inspection wrote an override for an id that doesn't exist: the checks publish under one producer with their inspection id as the code, and that id was not looked up. It now is.
Ruff and basedpyright problems need nothing new: both servers already offer their own suppress fixes (`# noqa: CODE`, `# pyright: ignore[rule]`), shown in the same menu.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 08:38:43 +08:00
LU XIANGRUIandwildcatDownstairs 52096fc904 feat(python): add Smart Type completion (#5351)
Ctrl+Shift+Space now runs **Smart Type** completion in Python files (Code › Code Completion › Smart Type, `code.smartTypeCompletion`): the lookup keeps the items whose type fits the caret's expected type, with that type in the right-hand column. basedpyright's completion items carry no type, so the candidates are resolved and their type is read from the documentation's code block.
The expected type comes from the active parameter's annotation (signature help), an annotated assignment `x: T = |`, or the enclosing function's `-> T` for `return |` (also in `async def`). A member access being typed (`x: T = task.|`, `return self.|`) is skipped over to find it. Keywords and comparisons are not taken for an assignment (`else: x = |`, `ok: bool = a <= |`).
An item fits when each member of its type's union fits the expected union:
- types are compared in a canonical form: module prefixes dropped, `typing` aliases lowered, `Optional` / `Union` and spacing read alike (`List[Optional[int]]` is `list[int | None]`);
- numbers are promoted as PEP 484 says: `float` accepts `int`, `complex` accepts both, and `bool` counts as an `int`;
- a class fits as any of its bases, from the project's classes (`Dog` for `Animal`);

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 08:38:28 +08:00
LU XIANGRUIandwildcatDownstairs 296c3d1477 feat(python): navigate between implementations and their .pyi stubs (#5339)
A Python module's type stub (`.pyi`) was invisible from the implementation, and jumping between a declaration and its stub meant finding the other file by hand. Functions, classes and methods that both files declare now get a gutter icon: in the `.py` it opens the stub declaration, in the `.pyi` the implementation. A new `nav_python_stubs` command finds the counterpart and matches declarations by qualified name on the tree-sitter outline of both texts, unsaved edits included. The counterpart is looked for:
- beside the file (`m.py` ↔ `m.pyi`);
- in a PEP 561 stub package beside the package (`pkg/m.py` ↔ `pkg-stubs/m.pyi`), or for a single module (`six.py` ↔ `six-stubs/__init__.pyi`);
- in the stub folder basedpyright reads (`stubPath` from `pyrightconfig.json` or `[tool.basedpyright]` / `[tool.pyright]` in `pyproject.toml`, else `typings/`), by module name. Modules are searched in the project's Python roots and its virtualenv's `site-packages`, so a `typings/requests/api.pyi` pairs with the installed `requests/api.py` both ways.
Navigate › **Stub / Implementation** (Find Action) does the same from the caret, and Related Symbol (⌃⌘↑) lists the counterpart. Markers refresh when a file where the counterpart may be changes, and a counterpart over the large-file limit still opens but gets no markers.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 08:32:17 +08:00
LU XIANGRUIandwildcatDownstairs c72a162b5c feat(python): create a function, class or method from an unresolved reference (#5355)
On an unresolved name in Python, Alt+Enter only offered basedpyright's "Add `# pyright: ignore[...]`" (and an import when one matches). It now also offers PyCharm's **Create function 'foo'** and **Create class 'Foo'** on an undefined name, and **Create method 'bar' in 'Greeter'** on a missing method called on `self`/`cls`. Parameters come from the call site: a keyword keeps its keyword, a plain-name argument keeps its name, others become `param1`, `param2`…, with `*args` / `**kwargs` for starred arguments; positional and starred names are renamed so they never repeat the receiver or a keyword. The function or class goes above the top-level statement that uses it; the method goes at the end of the enclosing class, a `@classmethod` when the calling method is one (none is offered from a `@staticmethod`). The caret lands on the `pass` body.
The server says what is unresolved (`reportUndefinedVariable` / `reportAttributeAccessIssue`, and the equivalent codes of Ruff, ty and pyrefly); the parse tree says where and how it is used. The fixes are local quick fixes, so they also show in the problem hover's quick-fix list.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 08:23:02 +08:00
LU XIANGRUIandwildcatDownstairs 3989b2715c feat(editor): write Python docstring stubs in the selected format (#5352)
Typing `"""` and Enter under a Python `def` always inserted reStructuredText `:param` / `:return:` fields: **Settings › Python › Docstrings** only changed highlighting. The stub now follows that setting (reStructuredText, Epytext, Google, NumPy, or Plain for a summary line only), lists the exceptions the function body raises (`raise X` / `raise X(...)`, nested functions skipped), and also closes a docstring under a `class`. The setting's hint and the Python docs page say so.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 08:20:48 +08:00
Akbar Husain aa1b6c1ce0 perf(lint): fix React performance lint violations (#5503)
Clears the React-specific violations reported by oxlint's `perf` category: 123 array-index keys, 28 constructed context values and 6 object/array default props. Keys now use a stable data id where one exists, and the index with a short documented suppression where position is the real identity (editable rows, streams, repeated data). Context values are memoized or hoisted, and default literals are module-level constants. Enabling the `perf` category itself is handled separately; this PR only fixes the violations.

Co-authored-by: akbar1214 <[email protected]>
2026-11-24 08:06:54 +08:00
Mr0Bread 2afd636314 perf(agents): drop a hidden session tab's painted history (#5494)
A kept-alive session tab (up to 5, `KEPT_TABS`) painted its whole conversation and never gave any of it back: `Stream` opens at the last `ENTRY_BATCH` (40) entries, then the "following the end" effect (`Stream.tsx`, the `useEffect` on `[start]`) keeps adding batches until the full history is DOM, hidden or not. Five long tabs therefore held every turn as DOM nodes (WebKit keeps layout/style/render-tree memory for all of it).
Now a tab that was left at the end of its conversation and stays hidden for 30 s drops back to its recent tail, and a hidden tab no longer paints more batches. When it is shown again it is at the end as before and re-paints the earlier entries in the background exactly as when it first opened.
Independent of #5462 (hidden tabs stop rendering), #5467 (per-chunk re-render) and the Rust PRs.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 08:06:38 +08:00
l0ng-ai de11bc02f1 fix(vcs): keep the log mounted while another Git tab is shown (#5454)
Switching between Console / Worktrees and Log in the Git tool window stuttered on every click of Log: the log view was unmounted whenever another tab was shown and rebuilt on return. The log now stays mounted (inert and unfocusable) while hidden; switching back takes ~33 ms instead of 70–100 ms.
2026-11-24 07:30:01 +08:00
faysouandfaysou 2f8d5f5118 fix(ui): keep the arrow cursor during scrollbar drags (#5504)
Dragging a scrollbar thumb across a split divider could show the resize cursor while the page was still scrolling. In a side-by-side Markdown editor, pressing the outside edge of the source thumb could start resizing the pane.
Keep the arrow until the scrollbar drag ends and keep the source thumb clear of the Markdown divider. A transparent surface catches the pointer during the drag, so grabbing the thumb does not change inherited styles across the document.

Co-authored-by: faysou <[email protected]>
2026-11-24 07:29:51 +08:00
Delaruno20andDelaruno20 4b4c25d7b1 fix(notebook): cell toolbar shows the file icon for Insert and Delete (#5505)
In the notebook editor, "Insert Code Cell Below" and "Delete Cell" (and the "Add Code Cell" /
"Add Markdown Cell" buttons) show the generic file icon instead of a plus and a trash can. They
ask for the icons `add` and `delete`, which are not in `src/ui/icons.tsx`; `IconButton` accepts
any string, so the unknown names fall back to `ICONS.file`. They now use `plus` and `trash`.

Co-authored-by: Delaruno20 <[email protected]>
2026-11-24 07:29:37 +08:00
Mr0Bread ca0f71bc39 refactor: share one CLI process runner between ide-docker, ide-github and ide-android (#5502)
`ide-docker`, `ide-github` and `ide-android` each carried a private copy of the same CLI runner (bounded `run`, cancellable line `stream`, SIGTERM-then-kill, output decoding): 570 lines, ~90% identical. The copies now live once in `ide_core::cli_process`; each crate keeps a ~35-line `process.rs` that binds its tool name and decoding and keeps its old call signatures, so no caller changes. `ide-core` already depended on by all three; no `Cargo.toml` / lockfile change. No behaviour change.
The three genuine differences are explicit parameters (3 knobs): `Decoding` (`ToolOutput` / `Utf8Lossy`), `Input` (`Inline` / `Threaded` stdin) and `CarriageReturn` (`EndsLine` / `Dropped`). The tool name only feeds the error texts. Android's batching loop stays in `ide-android`; it drives the shared `Lines` reader.
### Difference table (old code, before the change)
| Aspect | docker | github | android | Class | Now |
|---|---|---|---|---|---|
| spawn setup (`stdin` null, `stdout`/`stderr` piped, `own_group`, `ide_core::process::prepare`) | same | same | same | identical | shared `configure` |

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 07:02:30 +08:00
Mr0Bread b60b743843 refactor(ide-host): shared test HostConfig constructors replace ~100 copied literals (#5501)
`HostConfig` (9 fields) was written out as a full struct literal in about 100 tests of `ide-host`, almost all of them the same boilerplate, so a new field meant editing ~100 places. This adds one base constructor for tests and migrates every literal that is a plain variant of it. Tests that differ keep struct-update overrides (`HostConfig { sink_for: .., ..HostConfig::for_test(&base) }`). No builder.
- Unit tests (`src/`): `#[cfg(test)] pub(crate) fn HostConfig::for_test(base: &Path)` in `lib.rs`.
- Integration tests (`tests/`): `tests/common/mod.rs` with `host_config(base: &Path)`, pulled in with `mod common;`. It builds the same value as `for_test`.
Both build: `config`, `data`, and `data` again as the machine-local dir (the layout most tests used), `LanguageRegistry::load(None)`, empty syntax, a sink that drops events, identity owner, `Handle::current()`, `project_environment: false`.
Why not one constructor for both: integration tests compile against the crate without `cfg(test)`, so a shared one needs a new `testing` cargo feature plus a dev-dependency on the crate itself (nothing in `ide-host` does that today). Two small definitions need no feature, no `Cargo.toml` change and no public item.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 07:02:21 +08:00
Mr0Bread e6461f4935 refactor: one Utf8Decoder shared by ide-run and ide-terminal (#5499)
`Utf8Decoder` (incremental UTF-8 decoding for byte streams that split code points across reads) existed twice: in `ide-run` ("kept local so the crates stay independent") and in `ide-terminal`. The code was identical. It now lives once in `ide_core::utf8`; both crates already depended on `ide-core`, so there is no new dependency edge and no `Cargo.toml` change. `OutputDecoder`, `MixedDecoder` and `NativeDecoder` (encoding_rs based, ide-run only) stay in `ide-run` and import the shared type.
No behaviour change. The decoder was moved, not rewritten; ide-terminal's file was `git mv`'d to `ide-core/src/utf8.rs`.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 07:02:12 +08:00
Mr0Bread 0ef62c4999 refactor: use ide_core::jsonc in ide-agent instead of a private copy (#5498)
`ide-agent` carried a private JSONC stripper (`strip_jsonc` + `remove_trailing_commas` in `mcp.rs`) next to `ide_core::jsonc::strip`, which five other crates already use. Both callers in `ide-agent` (`parse_jsonc_value` in `mcp.rs`, the Copilot `config.json` read in `skills.rs`) now call `ide_core::jsonc::strip`, and the private copy is deleted (-94 lines).
To make the swap lossless I changed two small things in `ide_core::jsonc::strip` (these are the only behaviour changes, listed so they are not missed):
1. **Block comments keep their line breaks** (the private copy did; core dropped them). Without this, a JSON parse error in a pasted MCP config would report the wrong line after a multi-line `/* … */`, and `1/*\n*/2` was wrongly accepted as `12`. A comment is now whitespace, as in real JSONC.
2. **A trailing comma is dropped only when separated from `}`/`]` by ASCII whitespace** (core used Unicode `is_whitespace`). The private copy used ASCII whitespace. Inputs with e.g. NBSP before `]` were invalid either way; only the error text differed.
One more effect, only in `skills.rs`: core strips a leading UTF-8 BOM, the private copy did not. `~/.copilot/config.json` with a BOM previously failed to parse and its plugins were silently skipped; now it parses. (`mcp.rs` already stripped the BOM before calling.)

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 07:02:04 +08:00
Mr0Bread 7d39ab693c refactor: remove pass-through wrappers and redundant re-exports (#5497)
Several items only forwarded to another function or re-exported it, so each had an extra name to maintain and hid where the real code lives. This removes them and points every caller at the real definition. No behaviour change.
Removed (each was a pure forward, same arguments, no extra logic):
- `ide_run::which` (a bare `pub use ide_core::process::{executable_names, find_executable, find_executable_in}`): module deleted, 22 callers (ide-run, ide-profiler, ide-sdk, ide-run tests) now call `ide_core::process::…`.
- `ide_run::detect::package_manager(root, _pkg)` (the `_pkg` parameter was unused), `detect::subdirs` (→ `project_roots::children`) and `detect::build_dirs` (→ `project_roots::discover`).
- `ide_build::compile::package_manager` (→ `project_roots::package_manager`).
- `ide_lsp::is_virtual_uri` re-export (`uri.rs` and `lib.rs`). No caller used `ide_lsp::is_virtual_uri`; the one internal use now calls `ide_core::is_virtual_uri`, like every other crate.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 07:01:55 +08:00
Mr0Bread 71b4e1c367 refactor: keep test-only helpers out of production APIs (#5495)
Some `pub` items existed only to serve tests: they widened public APIs, and four were thin wrappers over the production entry point, so tests ran a different path than production. Each item below was re-checked on current `origin/main` with `lsp` references and `rg -w` across crates, `tests/`, benches, `src-tauri` and docs, then handled by the rule in the last column.
| Item | Users found | Decision |
|---|---|---|
| `LspManager::references` | only `ide-lsp/tests/{mock_server,real_servers}.rs` (38 calls); production uses `references_streaming` | wrapper deleted; tests call `references_streaming(.., true, cancel, None)` (the wrapper's exact body); doc merged |
| `McpServer::start` | in-crate test, `ide-mcp/tests/server.rs`, `ide-host/tests/mcp.rs`; production uses `start_with` | wrapper deleted; callers pass `ServerOptions::default()` (the wrapper's exact body) |
| `ide_mcp::endpoint_url` | in-crate test, `ide-mcp/tests/server.rs` | deleted; callers use `endpoint_url_at(Ipv4Addr::LOCALHOST.into(), ..)` |

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 07:01:46 +08:00
LU XIANGRUIandwildcatDownstairs 90bba44ba7 feat(python): add the Python Packages tool window (#5448)
Packages of the project's interpreter could only be managed in the Settings window, by typing an exact requirement. This adds a **Python Packages** tool window: the installed list with upgrade markers, a PyPI project looked up by its exact name, a version picker, and install / upgrade / uninstall through the same pip / uv path as Settings › Python › Dependencies.
The lookup is a new `pypi_package` command (`https://pypi.org/pypi/<name>/json`, HTTPS only, cancellable). The package list hook moved to `src/platform/pythonPackages.ts` so the settings page and the tool window share it.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 06:40:00 +08:00
LU XIANGRUIandwildcatDownstairs 68c4fe60ec feat(python): apply Code Style › Python to Ruff and Black (#5378)
Editor › Code Style › Python has indent, tab character and hard wrap, but Ruff and Black ignored them: without a configuration of their own they always formatted with 4 spaces at 88 columns, whatever the editor used. Now, when no Ruff configuration applies to the file (`ruff.toml`, `.ruff.toml` or `pyproject.toml` with `[tool.ruff]` in its folder or above, the user's Ruff configuration, or the configured Ruff configuration directory), Ruff gets the indentation and line length the editor uses, as `--config line-length / indent-width / format.indent-style`: the file's `.editorconfig` (`indent_size`, `indent_style`, `max_line_length`), then the values set on the page. Black, without `[tool.black]` in its project (found as Black finds it) and without a user configuration where Black would read one, gets the line length as `--line-length` (it has no indentation settings). Values set in neither place are not passed: the global hard wrap (120) is not Ruff's or Black's default (88), so existing projects keep formatting as before. The page says when these values apply.

Also adds Black as a selectable Python formatter (#5340's commits, which this branch was stacked on).

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 06:30:41 +08:00
wangfeiandhapput 558a98e74e fix(workbench): keep title bar and tabs visible while a project opens (#5484)
Opening a project as a new tab (or a new window) kept the full-screen boot
splash over the entire window until the project finished opening, so the title
bar and the window-group tab strip were hidden behind a bare logo + progress
screen. The splash was held for the whole `launch` promise, the opening view
rendered a `bare` title bar without tabs, and a loading tab fell back to the
window title ("OpenIDEA").

Co-authored-by: happut <[email protected]>
2026-11-24 06:06:31 +08:00
TWINKLE 8d701da584 feat(agents): copy an agent reference for files and selected code (#5469)
Co-authored-by: H-TWINKLE <[email protected]>
2026-11-24 06:01:19 +08:00
Muuandmuutot bd0f28cd3b feat(spelling): save typos to custom dictionaries with a default dictionary setting (#5466)
Co-authored-by: muutot <[email protected]>
2026-11-24 06:01:01 +08:00
LU XIANGRUIandwildcatDownstairs ea7ec41064 feat(python): optimize imports with Ruff's CLI without a Ruff configuration (#5373)
Optimize Imports in Python came only from the Ruff language server, which starts only below a Ruff configuration, so in other projects it said "Optimize imports is not available" and the Optimize imports options on save, before commit and in Code Cleanup did nothing. When no server offers `source.organizeImports` for a Python file, the IDE now runs `ruff check --extend-select I --fixable I,F401 --fix --exit-zero` on the unsaved text and offers the result as the organize-imports action, for the editor and for the MCP tools' organize-imports step alike. Imports are sorted; unused ones are removed where the project's Ruff rules check F401 (Ruff's defaults do; an `ignore` or `select` without it keeps them). It reads the project's Ruff settings or the configured Ruff configuration directory. Ruff comes from the file's project environment first (`.venv/bin/ruff`), as the Ruff language server does, then the IDE's copy and `PATH`. Without Ruff the action is disabled with "Install Ruff to optimize imports in Python files". Projects with a Ruff configuration keep using the Ruff server, which only sorts.
The first commit (Ruff from the project environment for Reformat Code too) answers a review comment on #5372, which was merged before it landed there.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 05:53:51 +08:00
LU XIANGRUIandwildcatDownstairs b1db1c6c3d feat(new-project): .NET solution name and SDK version (#5385)
The .NET entry of File › New Project had no way to create a solution or pick the SDK. It now has:
- **Create solution** (on by default) and **Solution name** (defaults to the project name). As in Visual Studio, the folder gets `<Solution>.sln`/`.slnx` at the top and the project in its own subfolder (`dotnet new sln`, then `dotnet sln add`). Unchecked, the layout is the same as before: the project at the top, no solution.
- **SDK version** lists the SDKs from `dotnet --list-sdks`, 8.0 and later, newest first. Older ones are left out because Blazor Web App and the templates' current options need SDK 8. The chosen one is pinned with `dotnet new globaljson --sdk-version … --roll-forward latestFeature`, which runs before `dotnet new <template>`. Without a roll-forward policy, `global.json` defaults to `latestPatch`: the project would then fail to build on a machine with only another feature band of the same .NET version, such as a teammate's or this one after an SDK update. `dotnet new` resolves the SDK through `global.json`, so the template also targets the pinned SDK's framework (10.0.401 gives `net10.0` on a machine whose default SDK is 11). **Automatic** writes no `global.json`.
How it is built: a new `dotnet` SDK kind in `ide-sdk` (detection runs in `sdk_detect`'s `spawn_blocking`), SDK field options that submit the version instead of the home (`version = true`) and leave out SDKs below a `min`, and `if-set` on generator steps (it already existed for arguments), so the pinning step runs only when a version is chosen. The New Project dialog now detects SDKs for any SDK field kind, not only `jdk`.
Edge cases: an empty or invalid solution name marks the field and disables Create. A solution name equal to the project name gives `App/App.slnx` + `App/App/App.csproj`. The generator now requires SDK 8.0 or later through `dotnet --version`, and a version command that exits with an error no longer counts as a version. So a missing `dotnet`, or a runtime-only install (no SDK), shows "dotnet is not installed" with the install hint and disables Create. An SDK 7 default shows that 8.0 or later is needed.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 05:30:14 +08:00
Mr0Bread 33ffa6cac1 refactor(plugin): make HostApi methods required, drop dead default bodies (#5489)
`HostApi` (`crates/ide-plugin/src/runtime.rs`) had 66 methods with default bodies (`Err(... unavailable on this host)`, `Ok(Vec::new())`, `let _ = (...)`). Its only implementor, `PluginApi`, overrides all of them, so those bodies could never run. They had to be kept in sync with real behaviour and let a forgotten override compile silently. They are now required methods (doc comments kept, signatures unchanged). No behaviour change.
`HostApi::project_of(&self, path)` is the one default that stays: `PluginApi` does not override it and it is live (`wit_host.rs` calls it, and the `project-of` guest fixtures exercise it). `PluginApi`'s own `project_of(window)` belongs to a different trait.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 05:29:51 +08:00
Mr0Bread a8aefa57c8 refactor(heap,index): compile test and bench support only for tests and benches (#5491)
`ide_heap::testing` (~430 lines of `.hprof` fixture builders) and `ide_index::bench_support` (`SyntheticIndex`) were `#[doc(hidden)] pub mod`s, so they were compiled into the desktop app and `openidea-server` and were part of the public API of both crates. Only tests and benches use them. They are now behind a `testing` feature (`ide-heap`) and a `bench-support` feature (`ide-index`), plus `cfg(test)` for in-crate tests. This follows what `ide-ssh` already does. `bench-support` is named for what it holds: a bench-only builder, not shared test fixtures.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 05:29:43 +08:00
Mr0Bread 1c24b77239 chore: remove unreferenced Rust items (#5493)
Removes ten `pub` Rust items that nothing references: not in production code, tests, benches, macros, strings, docs or `cfg`-gated code. They only widen public APIs and have to be kept up to date. No user-visible change.
Removed: `ExtensionRegistry::point_ids`, `Project::with_backend`, `diagnostics_store::RecordSinkFactory`, `ide_android::platform_tools_dir`, `ide_db::sql::ORACLE_SYSTEM_SCHEMAS`, `ide_run::go::package_sources`, `ide_build::maven::ALL_PHASES`, and `has_providers` / `has_views` / `has_hover_actions` on the plugin runtime. Two knock-on cleanups: the `PathBuf` import in `go.rs` became unused (removed), and the doc comment of `package_sources` (about Go's own build-file selection and `-find`) moved onto `package_info`, which it also describes.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 05:29:34 +08:00
Mr0Bread ae5c94e7d0 chore(deps): remove unused Rust dependencies (#5487)
Removes 25 Cargo dependency declarations that no code uses (found by `cargo shear`, each re-checked by hand): 11 unused internal crates in `src-tauri` (all still reach the app through `ide-host`), 12 unused deps in nine `crates/*` manifests, and the `anyhow` and `dashmap` entries in the root `[workspace.dependencies]` that no member uses. This shrinks the manifests and `Cargo.lock` edges. Only `Cargo.toml` files and `Cargo.lock` change; no Rust source is touched.
Removed:
- `ide-analysis`: `tracing`, `tree-sitter`
- `ide-android`: dev-dependency `tempfile` (the empty `[dev-dependencies]` header went with it)
- `ide-coverage`: `tracing`
- `ide-http`: `tracing`

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 05:29:23 +08:00
LU XIANGRUIandwildcatDownstairs fe9ee6a7a7 feat(python): create and detect Hatch environments (#5450)
"Add Python Interpreter" has a new **Hatch Environment** type. It lists the environments the project defines (`hatch env show --json`, without Hatch's internal `hatch-*` ones), runs `hatch env create <env>` with the chosen base interpreter as `HATCH_PYTHON`, and the result becomes the project interpreter. Hatch keeps an environment that already exists, whatever `HATCH_PYTHON` says. So if it was built on another Python version, nothing is changed and the dialog says so, rather than reporting it as created. The project's Hatch environments are also detected, with their own icon: `default` is listed as `Python 3.13 (Hatch: <project>)` and the others as `Python 3.13 (Hatch: <project>:<env>)`. The `default` one is the project interpreter when none is configured (after a `.venv` or pixi environment in the project, before the mise/asdf pin).
Until now Hatch was only a run wrapper (`hatch run`), and its data directory was not searched, so its environments never appeared. Detection does not start hatch:
- Hatch keeps environments at `<data>/env/virtual/<project name>/<project id>/<env>`, where the id is the first 8 characters of the URL-safe base64 SHA-256 of the project path.
- On Windows and macOS Hatch case-folds the path first (`ß` becomes `ss`); the IDE does the same for the letters a path is likely to hold.
- The project is the nearest folder, the opened one or above, with a `pyproject.toml` or `setup.py`, as for Hatch.
- The data directory is `HATCH_DATA_DIR` or the platform default.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 05:24:23 +08:00
LU XIANGRUIandwildcatDownstairs b5bff2fdfa feat(python): show the latest version of installed packages (#5433)
Settings › Python › Dependencies listed installed packages with their versions only, so finding out what can be upgraded meant running `pip list --outdated` in a terminal. The page now has a **Latest** column: once the installed list is shown, it asks the interpreter's package manager for newer releases in the background (`pip list --outdated --format json`, or `uv pip list --outdated` for uv environments) and marks the packages that can be upgraded.
Asking pip instead of the PyPI JSON API gives the newest release this interpreter can install, from the index pip is configured to use, in one command.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 05:08:30 +08:00
LU XIANGRUIandwildcatDownstairs e5f078913c feat(python): add Rearrange Code for Python classes (#5392)
There was no Rearrange Code for any language. **Rearrange Code** (Code menu, Find Action, IdeaVim's `RearrangeCode`) now orders the methods of every Python class in the file, nested ones included, as one undo step: `__new__` / `__init__` / `__post_init__`, other dunder methods, public, `_protected`, then `__private` methods, each group in its original order. The docstring and class attributes before the first method stay put; a method moves with its decorators and the comment lines directly above it; definitions sharing a name (a property and its setter, `@overload` stubs) move together in their order. Blank lines between methods stay where they were.
A class is left unchanged when moving could change it: other statements among its methods (`alias = method`, a nested class), standalone comments or `# region` / `# fmt: off` markers among them, or a decorator, default value or annotation that names another of its methods (`@_retry`, `@_visit.register`, `cb=_default`). Files with syntax errors are not rearranged.
The order is computed from one tree-sitter parse in `ide-language` (`Syntax::rearranged`); comments come from the syntax tree, so a `#` line inside a string is not taken for one. A language-neutral `doc_rearrange` command returns UTF-16 edits, so other languages can add an arrangement later. Backend errors are reported like formatting errors. There is no settings page yet.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 05:07:03 +08:00
Mr0Bread 5006e1934d fix(agents): confirm a Markdown code block copy with a check (#5488)
The Copy button in the top-right corner of a Markdown code block (agent replies) gave no sign that a click did anything: it copied silently and looked the same. After a successful copy it now shows a check in the success colour for two seconds and its label reads "Copied", then goes back to "Copy Code". Reply-level copy already behaves this way (`ReplyActions`).

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:41:31 +08:00
Mr0Bread 14d6d6892d fix(agents): skip code fences when titling a task from its prompt (#5486)
Starting an Agent Task with a pasted Markdown block named the tab "```text". The task title is the first non-empty line of the prompt (`title_of`), which for a pasted block is the opening code fence. The same title also names the worktree branch.
`title_of` now skips lines that open a code fence (``` or ~~~) and uses the first line after them.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:41:22 +08:00
Mr0Bread 080b7e80e7 perf(agents): stop re-rendering and rescanning the whole conversation for every streamed chunk (#5467)
While an agent streams, the visible session did work proportional to the whole conversation for every chunk: every earlier turn's reply and fold re-rendered, and the Composer re-read every tool output to rebuild the session assets. In a 170-turn conversation (2212 entries) that cost 12 ms per chunk in the stream and 7 ms in the composer; now it is 3 ms and 1 ms. Visible output, folding, turn numbers and reply actions are unchanged.
Root cause: the stream rebuilds its derived data for each chunk, and the props that carry it are new objects each time, so `memo` never held.
- `Entry:agent` (`session/messages.tsx`): `reply` (a fresh `ReplyTurn` from `replyTurns`) and `time` (a fresh `ReplyTimes` from `replyTimes`) for every earlier agent message.
- `TurnFold` (`session/ProcessRows.tsx`, rendered from `session/Stream.tsx`): a fresh `row`, the whole `entries` array, and fresh `children` elements. It was not memoized at all.
- `ProcessRun`: fresh `row` and `thinking` map each chunk.
- `extractSessionAssets` (`sessionAssetsModel.ts`, called from `SessionAssets.tsx`): re-parsed every tool entry's output each time `entries` changed.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:38:09 +08:00
Mr0Bread 92d94a7ac4 perf(ui): prefetch only the lazy views a window is likely to open (#5464)
After start-up, the workbench window loaded the code of every lazy view in the background, one chunk at a time, whether or not the user ever opened it: 122 extra chunks, +2.1 MB of JS and +3.0 MB of JS heap, plus ~300 ms of task time in the main window. `lazyComponent` / `lazyWhen` now take `{ prefetch: true }`, and `prefetchLazyComponents` loads only the components that set it. Everything else loads when it is first rendered, as it always could. Only the main workbench window prefetches (`mountWindowRoot(..., { prefetchLazy: true })`); auxiliary windows never did.
Opted in (what most sessions open early, where a blank first frame would show): Terminal tool window, Agents tool window + task and new-task editors, Commit and Git tool windows, the Settings dialog shell (not its pages), Search Everywhere / Find in Files / Recent files / File structure overlays, the markdown preview editor, the project switcher popup. Left on demand: all database, debugger, plugins, notebook, logcat, remote/deployment, github, python-console, web, build-tools, templates views, all settings pages (they already preload on page reveal via `preloadBuiltinPage`), edit-configurations, merge/compare/local-history editors, Run and Find tool windows (their stripes only appear on use, so the view mounts as it appears).

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:37:47 +08:00
Mr0Bread 518a62ea6c perf(agents): stop rendering and revealing a kept-alive session while its tab is hidden (#5462)
A kept-alive agent session tab (up to 5 per pane) that sits behind another tab kept rendering every streamed chunk like a visible one: the whole conversation re-rendered, the composer re-scanned all tool output (`extractSessionAssets`), and the reply's smooth-text reveal kept running its ~60 Hz `requestAnimationFrame` repaint. Up to 4 hidden tabs paid this on every chunk of a running task.
Now a hidden session stops reading conversation entries from the store (`useAgentsWhileShown` in `SessionEditor.tsx`) and the reveal is not live while hidden (`reveal.ts`). Shown again, it takes the latest entries in one render and paints unseen text whole instead of pacing it in. Visible tabs and docked sessions are unchanged.
```text
chunk -> store.entries
  visible tab:  TaskSession -> Stream, SessionComposer      (as before)
  hidden tab:   TaskSession keeps the entries it had, nothing re-renders

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:37:31 +08:00
Mr0Bread d16a87cf58 perf(vcs): stop polling for git process exit (#5459)
Every cancellable git read (`run_cancellable`, `run_bounded`, saved-credential transport, and GnuPG via `capture_command`) waited for the process to exit by calling `try_wait` and then sleeping a fixed 20 ms. A command that finishes in a few milliseconds therefore cost about 10 ms more on average than the same command through `wait_with_output`, and every git call made while opening or refreshing the Git tool window pays it. The wait now blocks on the output readers' completion (a channel that disconnects when both pipes reach EOF), so it wakes the moment the child closes its pipes, then polls `try_wait` with a 0.1 ms backoff capped at 20 ms for the reaping. Cancellation and output-limit checks still run at least every 20 ms, as before.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:37:12 +08:00
LU XIANGRUIandwildcatDownstairs f9fd1257c7 feat(python): show and edit an interpreter's sys.path (#5432)
Settings → Python → All Interpreters gets **Show Paths for Selected Interpreter** (toolbar and context menu). The dialog lists the interpreter's own `sys.path` (queried from the interpreter on a blocking thread, cancellable, with a reload button) and lets you add and remove folders outside the project. Until now there was no way to see `sys.path` or to put such a folder on the import path short of setting `PYTHONPATH` by hand in every run configuration.
Added folders are saved per interpreter in the global settings layer (`languages.python.interpreterPaths`, keyed by the interpreter's executable, like the interpreter list itself), so they apply to every project that uses the interpreter, as in PyCharm. They follow the interpreter that is actually used: basedpyright / Pyright get them as `extraPaths` for the interpreter that server analyses with, and run, debug, tests and the Python Console get them on `PYTHONPATH` for the interpreter the launch names (else the one of the project or workspace member it runs in), so Run and Debug of the same file agree. They are listed under External Libraries unless they are inside or around the project's own folders, which stay editable.
A folder that no longer exists is marked **Missing**, one `PYTHONPATH` cannot hold (not absolute, or with its separator in the name) is marked **Invalid**; neither is passed on. Duplicates and folders already on `sys.path` are not added. Removing an interpreter from the list drops its folders.
Not in this PR: removing the interpreter's own entries (PyCharm's excluded paths); ty, pyrefly, pylsp and notebook kernels don't get the folders. Docker / Compose run targets are not rows of this list, so they have no paths dialog.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 01:34:36 +08:00
LU XIANGRUIandwildcatDownstairs e57a709d19 feat(python): create and detect Pipenv environments (#5449)
"Add Python Interpreter" has a new **Pipenv Environment** type. It runs `pipenv --python <base>` in the project, which writes a `Pipfile` (importing `requirements.txt` if there is one) when the project has none. With **Install packages from Pipfile** checked, it then runs `pipenv install --dev`. The result becomes the project interpreter. If the project already has a Pipenv environment, it is reused and `--python` is not passed, because pipenv replaces an environment built on another Python without asking. When the versions differ, nothing is changed and the dialog says so. The project's Pipenv environment is also detected: it is listed as `Python 3.13 (Pipenv: <project>)` with the Pipfile icon, and it is the project interpreter when none is configured (after a `.venv` or pixi environment in the project, before the mise/asdf pin).
Until now Pipenv was only a run wrapper (`pipenv run`). Its environments were listed as plain virtualenvs named after their folder (`shop-Kpos5yRM`) and were never tied to their project. Detection does not start pipenv, which takes about a second. It looks for the `Pipfile` the way pipenv does, in the opened folder or one above it, and computes the folder name pipenv gives that project's environment: the folder name, `-`, and 8 characters of the URL-safe base64 SHA-256 of the `Pipfile` path. It looks for that name in `WORKON_HOME`, `~/.virtualenvs` and `$XDG_DATA_HOME/virtualenvs`, after the project's own `.venv`. An environment found elsewhere in the list is labelled as Pipenv's only if its `.project` names a folder with a `Pipfile` and its name matches. `ide-sdk` now depends on `sha2` and `base64`; both were already in `Cargo.lock`.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 01:28:27 +08:00
l0ng-ai abab90ca60 fix(maven): refresh stale SNAPSHOT sources on dependency reload (#5490)
After a SNAPSHOT dependency was republished and the project reloaded, navigating into it still showed the old sources: SNAPSHOT file names never change, the cached sources jar was reused as long as it existed, and open library editors kept their text. A sources jar older than its binary jar is now stale and replaced atomically; Maven reload waits for jdtls to finish importing, refreshes stale cached SNAPSHOT sources before reattaching archives, and refreshes open library editors. First-time source downloads still follow the Maven setting.
2026-11-24 01:09:14 +08:00
LU XIANGRUIandwildcatDownstairs 9d94b00911 feat(python): add type annotations from the inferred types (#5357)
basedpyright shows inferred types as inlay hints, and each hint carries the `textEdits` that insert it, including the import it needs (`from typing import Any`). The IDE dropped those edits, so an inferred type could not become an annotation. Inlay hints now keep `textEdits` over IPC, and Alt+Enter in Python offers PyCharm's:
- **Add type annotation ': int'** on an unannotated `name = value` assignment in a function or at module level (not in class bodies, where it would turn a dataclass/NamedTuple attribute into a field, nor for `global`/`nonlocal` names);
- **Add return type annotation '-> str'** on a function header;
- **Add type hints for function 'f'** on a function header: the return type plus the types of defaulted parameters (`limit: int = 10`), taken from hover and kept only when they name builtins, which need no import.
Annotations Python evaluates (signatures, module variables) use `X | Y` or `list[X]` only when `requires-python` allows them (3.10 / 3.9) or the file has `from __future__ import annotations`; a local variable's annotation is never evaluated. The intention asks the server for the hints itself, so it works with type hints turned off in Settings; a variable the server shows no hint for falls back to its hover type under the same builtin rule.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 00:40:35 +08:00
LU XIANGRUIandwildcatDownstairs cc1cc4cce5 feat(python): convert %-formatting and str.format() to f-strings (#5356)
Alt+Enter on a Python `%`-format expression said "No intentions available". It now offers PyCharm's **Convert to f-string literal** and **Replace with str.format() call**; on a `str.format()` call it offers **Convert to f-string literal**. Neither basedpyright nor Ruff offers these (Ruff's UP031/UP032 only report when a project enables pyupgrade rules, and the fix is not a quick fix).
`%` conversions `s r a d i u f e g x o` with flags, widths and precisions map to the equivalent format specs (`%5s` → `{x!s:>5}`, `%-8.3e` → `{x:<8.3e}`); `%d` keeps its truncation as `{int(x)}` unless the value is an int literal or `len()`/`int()`/`ord()` (`%05d` % `len(a)` → `{len(a):05d}`); `%(key)s` works with a dict literal; `%%` and literal braces are escaped, and `\N{NAME}` escapes are kept as they are. `.format()` fields support auto and manual numbering, keywords, `.attr` / `[0]` accessors, `!r` and specs. The conversion is not offered when it could change behaviour or produce invalid code: bytes, `*`/`**` arguments, `%c`, `*` widths, a precision on an integer conversion, nested format specs, a wrong argument count, an argument that would be dropped or evaluated twice, an argument containing the string's quote, a backslash or `#` (f-strings before Python 3.12), or, for `.format()`, a key that is a Python keyword. As in PyCharm, a single `%` operand that is not a tuple literal is taken as one value.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 00:30:27 +08:00
wangfeiandhapput 2478f67066 fix(workbench): keep project tab tint on hover (#5477)
Follow-up to #4481: hovering a coloured project tab made the custom colour disappear. The hover rule layered the opaque `--bg-hover` surface on top of the tint (`linear-gradient(var(--bg-hover), var(--bg-hover)), var(--tab-tint-mix)`), so while the pointer was over the tab only the plain grey hover surface remained.
The hover rule now mixes the project colour into the hover surface instead, mirroring how the selected rule mixes into `--bg-island`:
```css
.item[data-tinted]:hover {
  background: color-mix(in srgb, var(--project-color) 12%, var(--bg-hover));
}

Co-authored-by: happut <[email protected]>
2026-11-24 00:10:02 +08:00
zhzhsxandzhzhsx dc2924db17 fix(terminal): send the final size to a newly started PTY (#5473)
A new project's first terminal can end up with the wrong size. While the shell is starting, the terminal may resize, for example when the font finishes loading. That new size never reaches the shell. Full-screen programs such as vim then draw at the old width and the text looks broken. This fix sends the current size once the shell is ready.

Co-authored-by: zhzhsx <[email protected]>
2026-11-24 00:09:43 +08:00
l0ng-ai 348f4c2a2e fix(keymap): support mouse wheel shortcuts (#5483) 2026-11-23 23:58:16 +08:00
l0ng-ai 431b87c717 fix(remote): use the correct filesystem for file dialogs (#5479)
In an SSH or WSL window, Export Test Results passed a path picked in the desktop's Save dialog to the project host. Project-side pickers (Export Test Results, Save As, patch and Git dialogs, Maven/Gradle linking, scopes, coverage and Java sources, database source files, deployment destinations, tool and plugin paths) now browse the project host, with overwrite confirmation kept; flows whose files belong to the desktop (keymap and color scheme import/export, database and ACP imports, Clone) read and write through the desktop process. Follow-up to #5439.
2026-11-23 23:22:47 +08:00
l0ng-ai 3a53d13315 fix(editor): refresh Java inheritance markers after Maven import (#5478)
Interface methods could show no "is implemented" marker: the gutter cached the empty implementation results jdtls gave before the Maven import put the implementations on the classpath, and nothing invalidated them. When jdtls reports the project status after an import (generated sources attached first), the backend now emits an inheritance refresh next to the semantic-token refresh, and the gutter drops its cached markers and asks again. Covers implemented/overridden markers on interfaces, abstract classes and concrete overrides.
2026-11-23 23:20:57 +08:00
Mr0Bread 23f591289c perf(ipc): send binary command arguments as base64 instead of number arrays (#5436)
Pasting an image into a terminal or a Markdown file, or saving bytes from the UI, sent the data as a JSON array of numbers (3.6x the size), which Tauri and the remote server parse into a serde_json::Value first (~50x the bytes in memory: a 20 MB image took ~2.2 GB peak heap and 640 ms). Binary command arguments (fs_create_file_bytes, term_store_image) now travel as base64 text (IpcBytes): the same 20 MB takes ~112 MB and 32 ms. Native image drops reuse the base64 they already have.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 22:32:58 +08:00
l0ng-ai 8684e95778 fix(vcs): title git HTTPS credential prompts Username / Password instead of SSH (#5474) 2026-11-23 22:27:28 +08:00
Bert Verhelstandbertyhell 9d9e3f1c4f fix(java): don't reuse a launch snapshot copied while another build rewrote the outputs (#5420)
A Java launch that delegates to Maven could snapshot a dependency module's target/classes while an external mvn was rewriting it, then reuse that incomplete snapshot on every later launch (NoClassDefFoundError until the cache was cleared). A snapshot is now reused only while the live module outputs still match it (paths, sizes and modification times of the output tree, read from metadata only); output directories that appear after capture also invalidate it.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 22:24:59 +08:00
Bert Verhelstandbertyhell 5eff75cab5 fix(remote): keep scratches and generated requests on the host that writes them (#5439)
In a remote (SSH/WSL) window, Generate Request in HTTP Client failed with Permission denied: the scratches folder was resolved on the desktop and its path sent to the remote host. Scratches and generated HTTP requests now live in the data directory of the host that writes them (created on demand, rechecked on later calls), and remote IPC routing is installed before session listeners run.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 22:24:23 +08:00
l0ng-ai aec1382e79 fix(agents): keep the prompt box free of scrollbars until it reaches its height limit (#5472)
After one exchange, a new session's empty prompt box showed a horizontal scrollbar and a vertical thumb (visible with always-on scrollbars): the CodeMirror scroller kept a fixed height slightly taller than its content and allowed horizontal overflow. The scroller now sizes to its wrapped text, never scrolls horizontally, and scrolls vertically only past its 280 px limit.
2026-11-23 22:02:22 +08:00
l0ng-ai 999d84b189 fix(run): resolve Java launches in attached projects (#5471)
Running or debugging a Java main class of a project attached to the window failed to compile (its Maven dependencies were missing): launch preparation used the primary project's root, build model, settings and cache. Run/Debug/test launches now resolve the owning attached project (innermost root containing the module) and use its build model, Maven reactor, settings, classpath and launch-snapshot cache; older saved configurations resolve the same way.
2026-11-23 22:01:15 +08:00
jiejie1133 9fda9b92c2 fix(editor): edit a repeated template variable from one caret (#5443)
After expanding Java `fori`, the three occurrences of `i` were all editing selections, so arrow keys moved three carets. The shared snippet engine now selects only the first occurrence of each variable and mirrors edits to the others, for every live template and language and for LSP snippets with repeated placeholders; the Java-specific handling is gone.

Co-authored-by: jiejie1133 <[email protected]>
2026-11-23 21:41:18 +08:00
fun90andfun90 261eb03009 fix(markdown): open preview links to another file at the linked heading (#5422)
Clicking a link to a heading in another file (e.g. [§5.2](b.md#52-状态机)) in the Markdown preview opened the file at the top. The destination now opens at the heading, in Preview Only and split mode, also when the file wasn't open yet (the preview scrolls once it has rendered). Markdown file-type aliases are honoured and a later link click wins over a slower earlier one.

Co-authored-by: fun90 <[email protected]>
2026-11-23 21:21:17 +08:00
l0ng-ai db8b553364 fix(editor): merge inheritance gutter markers by line and kind (#5470)
Lombok-generated members (@SuperBuilder, @Data) put one override/implemented marker per generated method on the annotation line, filling the gutter. Markers of the same kind on a line now collapse into one icon with a combined tooltip; clicking it opens the target chooser (a single target still opens directly). Applies to all four inheritance marker kinds.
2026-11-23 21:19:14 +08:00
langxpandkradme 2494b2efdf fix(libraries): reveal classes from unlisted classifier jars (#5414)
Select Opened File could not reveal a class opened from a dependency JAR that used a Maven classifier and was absent from External Libraries. The document knew its exact archive, but the Project view only searches registered archive roots.
External Libraries now adds the exact archive referenced by the active library document, labels it with its Maven coordinate when available, and removes the temporary entry once the build model lists the same archive.

Co-authored-by: kradme <[email protected]>
2026-11-23 21:13:35 +08:00
Muuandmuutot d78ce7ec66 fix(editor): offer contributed Copy Path links in the tab and library menus (#5400)
Copy Path/Reference… built a different submenu per entry point: the project view and the editor caret chooser list the contributed copy items (features/vcs: Path From Repository Root, GitHub Link), while the editor tab menu and the External Libraries menu hand-wrote theirs and silently dropped every contribution. Both hand-written submenus now append the same `copyPath` menu group, so all four entry points agree — and future contributions appear everywhere at once.

Co-authored-by: muutot <[email protected]>
2026-11-23 21:10:34 +08:00
Bert Verhelstandbertyhell 9df9499bf5 fix(project-view): open files on single click when preview tabs are enabled (#5419)
With **Settings › Editor › General › Editor Tabs › Enable preview tab** on, a single click on a file in the Project view now opens it in the preview tab, and the next single click reuses that tab. Before, the click did nothing. The cause was two switches that weren't connected. The Project view checked its own "Enable Preview Tab" view option, which was off by default and only reachable from the view's ⋮ menu. The Settings checkbox was a separate setting, `editor.tabs.previewTab`, which was only read when a preview tab was created.
IntelliJ IDEA documents these as two ways into one setting, so this PR makes them one. The Project view reads `editor.tabs.previewTab` for single click and for Autoscroll to Source. Its ⋮ › Behavior › Enable Preview Tab item and the `project.option.previewTab` action (the id is unchanged) now write that setting. The old view option is removed from the saved Project view options when they load.
What existing users will see:
- Defaults (Settings on, view option off): single click now opens a preview tab. This is the fix. The editor setting already defaulted to on, so users who never changed anything get single-click preview after this change.
- Both on: no change.
- Both off: no change.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 21:10:08 +08:00
aconeshanaandaconeshana d4b5581441 fix(ui): paste into a tree's speed search, not the view's Paste (#5401)
In the Project view, copy a keyword, press ⌘F, then ⌘V: the app reported "No files on the clipboard" and the search box stayed empty, instead of pasting the keyword the user had copied to search with.
A tree's speed search is not a text field — its query is built from printable keydowns. So `⌘V` never reached the query: the keymap dispatcher ran `project.paste` on the selected folder, and the paste event that followed bubbled to the Project view's clipboard fallback, which runs the same action again.
The shared `Tree` now claims `⌘V` while a search is active (as it already claims `⌫` since #3226) and takes the clipboard text into its query: pasted text is flattened onto one line and the search jumps to the nearest match. With the search closed, or with a clipboard that holds no text, the view's Paste runs exactly as before.
Every tree with a speed search gets this — the Project view, the Database view, the Services tree and the GitHub changes tree all render `src/ui/Tree.tsx`.

Co-authored-by: aconeshana <[email protected]>
2026-11-23 21:00:08 +08:00
Bert Verhelstandbertyhell d96060f08b fix(ui): scroll text fields while drag-selecting past their edges (#5429)
Drag-selecting in a long Find in Files query (or any text field) and moving the pointer past the field's left or right edge didn't scroll the text, so you couldn't select past what's visible. IntelliJ IDEA does scroll. WebKitGTK extends the selection in this case but never scrolls the field to follow it. Arrow keys do scroll. Now, while a drag that started in the field is past one of its edges, the field moves the selection end and the scroll position itself, faster the further out the pointer is. Once the pointer is back inside, WebKit's own selection takes over again. Both `Input` and `SearchField` get this.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:59:53 +08:00
Bert Verhelstandbertyhell 507258daec fix(editor): stop clipping Code Vision hints that are taller than 16px (#5418)
The Code Vision row above a declaration (usage count, author) cut off the top or bottom of its text, most visibly for Chinese labels like "10 个用法" / "无用法". The row was a fixed `height: 16px` with `overflow: hidden`, while its text is the editor font size minus 1px. At larger editor fonts, or with CJK fallback fonts that ink below the Latin metrics (Microsoft YaHei, Noto Sans CJK), the glyphs didn't fit.
The row now has `min-height: 16px`, and its items use `line-height: normal`, so the row grows to the ascent and descent of the fonts actually used. At the default font a Latin-only row is still exactly 16px. The line-end hint (Code Vision kinds set to "right") has the same 1em box with `overflow: hidden`. It keeps its size and position but now clips only horizontally.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:59:37 +08:00
Mr0Bread dae402b966 perf(vcs): make a git history page cost independent of the commit count (#5446)
A Git Log page costs a fixed ~15 ms in a repository with 248 refs (the 100k-commit fixture), even for a one-row page. Every page listed and peeled all refs twice (once for the decorations, once more for the view cache key via `log_refs`), at ~25 µs per ref. The decorations are now cached until `HEAD`, `packed-refs` or a directory under `refs/` changes, and the cache key uses a change counter instead of the full ref map. A warm page no longer reads any ref.
The cost scales with the number of refs, not commits: the audit's 10k/100k fixtures have 50/248 refs, which is why it looked proportional to the commit count. A repository with thousands of remote branches pays correspondingly more.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 20:43:54 +08:00
Bert Verhelstandbertyhell 39e803b8f9 fix(vcs): keep a filtered log narrow while older matches are still unloaded (#5421)
With a User filter on a merge-heavy history, the first page of the Git Log fanned the top merge out into dozens of dashed lanes, and the graph column pushed the commit subjects to the right. It went back to one line only after every match was loaded. The cause: `pruneFilteredEdges` (the #2670 fix) only judges a filtered connection when its target is on the loaded page. With the first 300 rows of the issue's repository, the merge kept 43 connections, 42 of them to rows that weren't loaded yet.
Now, while another kept connection of the commit already leads below the page, a filtered connection to an unloaded target waits until that target loads, and is then judged exactly like before. If no kept connection leads below the page, one filtered connection stays, so a row never looks like the end of its history. This is a heuristic: a connection that turns out to be needed (two unrelated side branches, both below the page) appears once its target loads. The sibling-branch test pins that behaviour. An exact answer on the first page would need the backend projection (`Visibility::parents`) to drop ancestors that another projected parent already reaches. This PR doesn't touch Rust; that could be a follow-up.
Go to Parent now pages until every unpruned connection of the commit is loaded, as it did before, so a merge still offers all its parents.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:43:44 +08:00
TWINKLE d6b56856d2 Fix/terminal ime caret (#5458)
Closes #4112 (its remaining half: #4347 stopped the terminal sliding sideways while composing, the
candidate window still opened at the far right of pi's input box).
xterm anchors the IME candidate window on its hidden helper textarea, and keeps that textarea on the
terminal cursor — on every render, on `compositionstart` and again on each `compositionupdate`. A
program that paints its own caret leaves the terminal cursor elsewhere: pi asks for a column past the
right edge of its input box (`ESC[21;411H` in a 206-column terminal, which xterm clamps) while it

Co-authored-by: H-TWINKLE <[email protected]>
2026-11-23 20:40:44 +08:00
Yann 8a84e8f473 fix(agents): preserve and display tool result images (#5447)
Claude Code can return an image from a tool call without including a Markdown image in its final reply. OpenIDEA discarded that image while normalizing and saving the tool result, so the conversation showed no preview.
Preserve inline tool images separately from truncated text and show them below the folded work summary. The existing image viewer opens the full preview; expanding the work does not duplicate it, and old conversations without an image field still load.

Co-authored-by: YannABC <[email protected]>
2026-11-23 20:40:35 +08:00
Bert Verhelstandbertyhell f31aa29f3e fix(agents): update the context meter when Claude Code compacts the conversation (#5441)
After a compaction the context meter kept the pre-compaction usage until the next request. compact_boundary now sets the usage to post_tokens; without it the driver asks Claude Code (get_context_usage).

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:03:15 +08:00
faysouandfaysou 639e4b3df9 fix(editor): keep completion types and usage captions visible in narrow popups (#5387)
The completion popup can clip a return type after the editor font loads. Its return-type column now uses the row’s existing gap. In Show Usages, same-named files can be hard to distinguish because the filename and directory share too little space. The filename column now gets 38% of a narrow row, with the existing 176 px cap.
| Popup | Before | After |
| ----- | ------ | ----- |
| Completion | ![Return type ends in an ellipsis](https://raw.githubusercontent.com/faysou/openidea/691de74a16586ccc65eb229315507ba0f5938933/completion-before.png) | ![RegionalSettlementResult fits](https://raw.githubusercontent.com/faysou/openidea/691de74a16586ccc65eb229315507ba0f5938933/completion-after.png) |
| Show Usages | ![The checkout directory is truncated](https://raw.githubusercontent.com/faysou/openidea/691de74a16586ccc65eb229315507ba0f5938933/usages-before.png) | ![Both billing and checkout are visible](https://raw.githubusercontent.com/faysou/openidea/691de74a16586ccc65eb229315507ba0f5938933/usages-after.png) |

Co-authored-by: faysou <[email protected]>
2026-11-23 20:02:54 +08:00
Bert Verhelstandbertyhell 01b9908898 fix(search): offer every project file type in the file mask menu (#5416)
The **File mask** menu in Find in Files now lists every language file type present in the project, most common first, after the recently used masks. Before, `refreshProjectMasks` kept only the 5 most common types, so in a project with six (rs, md, json, toml, yml, properties) the least common one, `*.properties`, could not be picked. The menu already scrolls and stays inside the window, so a long list stays usable.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:02:43 +08:00
Bert Verhelstandbertyhell 7f201ed87d fix(editor): stop linked tag editing while a tag is being deleted (#5434)
Backspacing through a closing tag such as `</div>` also emptied the opening tag, leaving `<>`. The first Backspace removes `>`. The parser still reads `</div` as the element's close tag, so every later Backspace in the name counted as a rename and was mirrored. Linked tag editing now only pairs two tags that both still end in `>`. A tag missing its `>` is being deleted, so nothing is mirrored into it or out of it. The same applies to an opening tag deleted before its children, in all the HTML-based modes and in JSX/TSX. XML does not use linked tags (`LINKED_TAG_LANGUAGES` in `prefs.ts`).

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:02:33 +08:00
Shohruh Ismoilovandshohruh-genius 85344b86b5 fix(templates): offer Svelte components in the New menu (#5440)
The New menu had no built-in template for `.svelte` files. Add **Svelte Component** for Vite and Node.js projects, including SvelteKit workspace members. The template accepts SvelteKit filenames such as `+page.svelte`.

Co-authored-by: shohruh-genius <[email protected]>
2026-11-23 20:02:23 +08:00
faysouandfaysou 12e85a7c1b test(vcs): check Git Log graph options as separate equivalence cases (#5424)
The Git Log graph-equivalence test compares layouts for eight option combinations, each with five fragment configurations. Running all 40 comparisons in one Vitest case exceeded the five-second timeout on shared Linux runners. Give each option combination its own test for histories with and without refs. Each case still compares the complete layout with the dense reference implementation for all five fragment configurations and the same 2,400 commits.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:02:13 +08:00
faysouandfaysou 861acabf77 test(search): open the action search from the toolbar (#5386)
The action-search test could time out before reaching its first search assertion when the runner delayed the second Shift press. Open Search Everywhere through the title-bar button for this test, then enter a query and run the matching action. The adjacent shortcut test exercises double Shift directly.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:02:04 +08:00
faysouandfaysou 96395c979f test(project): control the clock during diagonal submenu navigation (#5384)
The Project tree test moves the pointer diagonally toward the New submenu in ten steps. On a busy runner, the time spent delivering input and checking assertions can exceed the menu’s hover delay and close it mid-gesture. Use Playwright’s browser clock to advance 75 ms at each step and check that the submenu stays open through the final 350 ms pause.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:01:55 +08:00
Mr0Bread e9f768d8b5 perf(events): serialise an event once for all windows (#5445)
With auxiliary windows open (comparison, diff, etc. that share the project's documents), every backend event was serialised once per window, because `emit_to` serialises its payload on each call. For a large diagnostics event that is 2.3 MB (10k items) or 11.6 MB (50k items) of JSON built again for each window, on the thread that emits the event. `TauriSink` now serialises the event once and sends the same JSON string to each window with `emit_str_to`. The payload is the same `serde_json::to_string(&event)` that `emit_to` produced, so the frontend (`getCurrentWebviewWindow().listen` in `src/platform/ipc.ts`) receives exactly what it did before. Which windows get which events is unchanged.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 20:01:45 +08:00
Mr0Bread d15abe54e2 perf(vcs): read the restricted-mode scoped status with a pathspec (#5451)
In Restricted Mode, the refresh after a watcher batch (`status_paths`) ignored its paths and answered with the full gitoxide status, which walks the whole tree to report one saved file. In a 100k-file repository that took about 87 ms against about 15 ms for a trusted project. It now runs `git status` with the pathspec, as a trusted project does.
The audit (row S4) blamed the extra `git config --null --list` process. That process is not the cause: the full `status()` never runs it (it runs `gitoxide`), and the old restricted `status_paths` did not run it either. The cause is the early return to the full status in `Repo::status_paths`, left from #3267, when the scoped read was in-process and `git` was not allowed. #3280 moved the scoped read to `git`, with the filter overrides the restricted fallback already used, but the restricted bypass stayed.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 20:01:29 +08:00
faysouandfaysou b501f51526 test(run): compile the output counting reader only on Unix (#5407)
The Windows Clippy job fails because the test reader `Counted` is compiled on Windows, where its only caller is excluded. The flooding-process test uses `awk` and already requires Unix. Apply the same condition to the reader and its `Read` implementation. The cross-platform queue shutdown test keeps its own reader.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:01:20 +08:00
faysouandfaysou 50cd478773 test(vfs): allow watch events for an excluded directory itself (#5382)
The per-directory watcher skips the contents of excluded directories. A watch on the parent can still report the directory itself, which macOS did for `node_modules`. The regression test now accepts that event while continuing to reject events for descendants.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:01:10 +08:00
faysouandfaysou 2c63f0eb22 chore(deps): update cookie to 0.18.3 for RUSTSEC-2026-0594 (#5431)
Update the transitive `cookie` dependency from 0.18.2 to 0.18.3. Cargo Deny reports the older release for possible nonce reuse when encrypting private cookies across a fork. The patched crate obtains those nonces from the operating system. [RustSec advisory](https://rustsec.org/advisories/RUSTSEC-2026-0594.html)

Co-authored-by: faysou <[email protected]>
2026-11-23 20:01:00 +08:00
faysouandfaysou ed1730f273 fix(vcs): preserve the index timestamp when preparing a commit selection (#5383)
A commit preview or a commit of selected changes can omit a same-size edit made on the same filesystem clock tick as the Git index. Git uses the index timestamp to decide when it must inspect the file contents. The temporary copy now preserves that timestamp so Git detects the edit.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:00:51 +08:00
akshathayadav378-boopandakshathayadav378-boop d6d0cc7926 fix(vcs): use the Project view selection for Git file actions while it is the context (#5428)
Show History (and Add to VCS / the ignore actions) took the editor's file when the shortcut ran right after clicking a Project view row: the row publishes its selection on mousedown, but tree focus is a separate DOM event, so projectViewFocus was still false. File actions now use the Project view selection while the tree owns the context (its lead is set and the editor has no focus), the same rule External Tools use (shared projectViewContextLead helper).

Co-authored-by: akshathayadav378-boop <[email protected]>
2026-11-23 20:00:11 +08:00
l0ng-ai a21de32077 fix(editor): give the top and bottom breadcrumbs distinct keys (#5463)
The top and bottom breadcrumb bars are keyed separately, so Markdown and HTML tabs no longer log React's duplicate key error.
2026-11-23 19:38:19 +08:00
Bert Verhelstandbertyhell 546ff9f314 fix(run): resolve External Tools file macros against the Project view selection (#5415)
External Tools expanded $FilePath$ and the other file macros from the editor's file even while the Project view was the user's context. They now take the Project view's selected file while it is the context (no editor focus, not a virtual document); caret macros apply only when the editor shows that same file.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 19:35:44 +08:00
l0ng-ai a144208170 fix(debugger): keep a rerun session's tab in place while its adapter starts (#5460)
Rerun keeps the finished tab in place and selected until the new session appears, which then takes its slot and the selection at once.
2026-11-23 19:33:10 +08:00
l0ng-ai fda2d2ff69 fix(run): scroll configuration choosers to their last item in short windows (#5457)
The configuration choosers' list fills the viewport left by a window-capped popup, so its last items scroll into view in short windows.
2026-11-23 19:28:33 +08:00
l0ng-ai 0fdf37f1bf fix(vcs): list every repository's branches and tags in Go to Hash/Branch/Tag (#5455)
Go to Hash/Branch/Tag reads refs from the repositories it searches (shown log tab, else the filtered ones, else every root) instead of an empty Repository filter, which offered only HEAD.
2026-11-23 19:24:50 +08:00
l0ng-ai 5c592bbc86 fix(editor): move a whole switch case in languages with flat case labels (#5453)
Move Statement on a case label in Go, JavaScript and Java moves the whole branch (stacked labels through its last line) past the neighbouring branch instead of only the label line.
2026-11-23 19:22:35 +08:00
l0ng-ai 819ccb8bb5 docs: refresh WeChat group QR code 2026-11-23 19:18:28 +08:00
l0ng-ai ae893f059f fix(agents): keep unrelated chat rows stable during text selection (#5438) 2026-11-23 18:56:34 +08:00
l0ng-ai fb2f567d5b fix(agents): hide Jump to Latest when the reply end is visible (#5442) 2026-11-23 18:51:44 +08:00
l0ng-ai 22af0931dd fix(vcs): name each repository of a shared branch in the Branches pane tooltip (#5413)
In the Git Log Branches pane with several repositories, a branch every
repository has is listed once with no repository name. Hovering it now
lists each repository with the branch it tracks there.
2026-11-23 17:21:59 +08:00
l0ng-ai 4af81625b1 fix(agents): scroll the container under the pointer and keep fold headers in place (#5411)
The wheel now scrolls only the innermost scrollable container under the
pointer: a run of tool calls from its headers, a tool output from its text,
the conversation elsewhere. A nested container at its edge no longer hands
the rest of the gesture to the conversation, and a gesture stays with the
container it started in.

Opening or closing a section keeps its header where it was. Closing one near
the end leaves temporary room below the conversation that scrolling up or new
content takes back.
2026-11-23 17:16:29 +08:00
l0ng-ai f3d18c0eb8 fix(agents): clarify settings names and align the import dialog (#5403)
* fix(agents): align and shorten the Import Sessions dialog

* fix(agents): clarify settings page names
2026-11-23 16:35:39 +08:00
l0ng-ai e662c915a2 fix(agents): show the changes scope as compact tool window tabs (#5393)
The Whole Task / Last Turn switch in the agent Changes pane was a full-width
segmented pill. It now uses the compact Tabs strip that tool window sub-views
use elsewhere.
2026-11-23 15:45:07 +08:00
l0ng-ai f57a17ec14 fix(vcs): group stashes by repository (#5380) 2026-11-23 15:45:02 +08:00
l0ng-ai 0b8d9135aa fix(github): keep the review composer readable (#5375) 2026-11-23 15:44:50 +08:00
l0ng-ai 290ef6956e fix(diff): align original and modified line numbers (#5370)
Unified Diff shows original line numbers in the first column and modified line numbers in the second. Matching rows show both. Removed and inserted rows show the number for their own revision.

Line numbers stay beside the start of their rows when code wraps, and follow scrolling inside a large removed block. Matching rows keep their original numbers when empty lines are ignored. The column order also applies when the editable side is the Git index.
2026-11-23 15:44:15 +08:00
l0ng-ai 8a4b8f45b4 fix(agents): shorten task context menu labels (#5394) 2026-11-23 15:35:46 +08:00
l0ng-ai 31b265cb41 fix(vcs): align the New Worktree dialog (#5367)
- Align the repository, checkout, branch, name, location and setup fields in one label-and-control grid. Use the standard dialog type size for labels and keep the worktree path preview beneath the Location field.
- Let the `.worktreeinclude` edit action wrap below its checkbox in narrow windows. With setup expanded, the standard dialog is about 118 logical pixels shorter, and the setup field fits without scrolling in a 440 × 520 window.
2026-11-23 15:17:34 +08:00
l0ng-ai a6a05caa2e fix(editor): keep multiline find and replace compact (#5362)
Limit the inline Find and Replace fields to three visible lines each. Longer text scrolls inside the fields, leaving more of the matched code on screen.
2026-11-23 14:56:44 +08:00
Deng Liuanddengliu 4690463c53 feat(services): show Compose service resource usage and named volumes (#5330)
The Compose project dashboard listed only container chips, so resource usage meant opening each container, and the project's named volumes were only findable in the global Volumes group among anonymous hashes. It now shows a per-service table (status, CPU, memory, network and block I/O, PIDs) sampled with bounded concurrency and refreshed every 3 s without overlapping requests while the dashboard is visible (paused when the tool window or app is hidden; the container dashboard's stats use the same live sampling instead of a manual Refresh), plus a Volumes section with the project's named volumes that links to each Volume Overview and back.

Co-authored-by: dengliu <[email protected]>
2026-11-23 14:49:42 +08:00
Deng Liuanddengliu 8200ce8b5e feat(services): jump from Compose containers to their Compose file (#5348)
Docker Compose containers carry their Compose files and service name but had no way back to the source. Jump to Source (F4 / Cmd+Down, context menu, docker.jumpToSource) on a Compose container opens the Compose file at its service declaration and on a Compose project at the services section; the container dashboard's Command row has a button that lands on the service's command value (else entrypoint, across inline values, block scalars and sequences, later override files taking precedence), and the Compose project dashboard lists its Compose files as links. Missing or unreadable files show a notification.

Co-authored-by: dengliu <[email protected]>
2026-11-23 14:47:10 +08:00
Deng Liuanddengliu b524f738e5 fix(services): keep long Docker commands bounded and collapsible in dashboards (#5337)
Property rows in the Docker dashboards aligned items on their baseline; an inline-block value's baseline is its last line, so a wrapped multi-line command painted its earlier lines upward over the rows above it. Rows now align at start with a minmax(0, 1fr) value column, and container/image commands render as a single-line preview (newline markers, copy button, no auto-ellipsis tooltip via data-no-tooltip) that expands into a bounded scrollable block with Entrypoint and Command arguments shown separately.

Co-authored-by: dengliu <[email protected]>
2026-11-23 14:43:37 +08:00
l0ng-ai 1f871dc1c2 fix(search): keep multiline file search fields compact (#5358)
Find in Files and Replace in Files show up to three lines in each query field. Longer text scrolls within its field. Closer spacing between the search and replacement fields gives matches and the source preview more room in short windows.
2026-11-23 14:39:03 +08:00
langxpandkradme ceb3cef1af feat(vcs): scope Commit… to the selected project directory (#5304)
Git > Commit… from the Project view ignored the selection. It now passes the selected paths, and the commit interface (modal or not) opens with only the changes at or below them checked: tracked and unversioned files included, conflicts left out, the rest of the working tree still listed.

Co-authored-by: kradme <[email protected]>
2026-11-23 14:27:36 +08:00
Deng Liuanddengliu 735a0157c1 fix(editor): cap inline highlight backgrounds and frames at line height (#5285)
When the editor font's glyph box is taller than the line height (e.g. 18px font at 18px line height), Find matches, occurrence highlights, in-place rename spans, matched brackets, search results and plugin range marks painted the full inline box into the rows above and below. They now share a 1lh-capped background (and a 1px-framed variant), as selection marks already were, keeping background-color / outline fallbacks for Safari before 16.4.

Co-authored-by: dengliu <[email protected]>
2026-11-23 14:25:39 +08:00
Mr0Bread 82f26202ed perf(search): keep Find in Files cost linear while results stream in (#5239)
Every streamed file triggered a Find tool window update that rebuilt the whole result tree and its lookup tables, so a search matching thousands of files grew quadratically and froze the IDE. The session now publishes streamed results at most every 50 ms (the first file still at once), and the tool window builds its tree incrementally: only new files get nodes, merged into the sorted result; a list that is not an extension of the previous one is rebuilt.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 14:18:35 +08:00
l0ng-ai a90a9b20e3 fix(debugger): keep Memory instance fields readable (#5342)
The Memory Instances tree gives field values room beside long names. The panel title uses the workbench font. Field names and value previews that run out of space use ellipses and show the full text on hover, and the row's Show Referrers button stays in reach.
2026-11-23 14:17:51 +08:00
Deng Liuanddengliu aad701ba16 fix(editor): clear selection highlights when hiding kept-alive tabs (#5273)
WebKit skips clearing the selection highlight inside a subtree whose rendering is skipped, so a kept-alive tab (an Agent conversation) hidden with content-visibility kept a stale highlight after switching back. Hiding a kept tab now clears a selection inside it while keeping it rendered (invisibly) for one frame via a shared useSelectionVisibility hook, and the agent stream keeps data-selection independent of visibility so off-screen rows clear too.

Co-authored-by: dengliu <[email protected]>
2026-11-23 14:16:18 +08:00
Mr0Bread 46d4036038 perf(editor): keep typing and Enter fast in large TypeScript files (#5251)
Typing and Enter in a large TypeScript file got slower with its size. @lezer/common 1.5.6 gives each repeat group the look-ahead in effect where it ends, so groups above an edit stay reusable and an edit no longer re-parses the file up to the caret; decoratorRanges scans only subtrees not already known to hold no decorator; and Enter's one-line string check parses and highlights only the caret's line instead of the whole document.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 14:16:13 +08:00
LU XIANGRUIandwildcatDownstairs 19859b4ae2 fix(java): refresh semantic highlighting after a project import (#5319)
jdtls returns no semantic tokens for files outside any Java project (a failed Maven import) and sends no workspace/semanticTokens/refresh once a later import takes them in, so open editors stayed uncoloured until edited or reopened. On ProjectStatus the IDE now asks open editors to fetch semantic tokens again, after generated Maven sources are attached. Refs #5301.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-23 14:13:06 +08:00
Qingandqtvbwfn f3f05f8b15 fix(vue): keep the vtsls route on TypeScript 7 for Vue projects (#5368)
With a TypeScript 7 workspace the native server replaced vtsls before the Vue branch could inject @vue/typescript-plugin, so .vue files lost TypeScript support (Go to Declaration on the 'vue' import failed). The native swap now skips vtsls in a Vue project whose Vue language server is installed; typescript-language-server still takes the native route. Closes #4876.

Co-authored-by: qtvbwfn <[email protected]>
2026-11-23 14:13:02 +08:00
LU XIANGRUIandwildcatDownstairs b0417c83f4 fix(tools): find the Ruff the IDE installed when formatting (#5372)
The formatter lookup checked the project's node_modules and PATH but never a tool's managed virtualenv, so a Ruff installed from the tools list was reported as not installed by Reformat with Ruff. It now looks there before PATH, which also covers Black and Ruff-based Optimize Imports. Closes #5371.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-23 14:12:58 +08:00
l0ng-ai 4a5d90a91e fix(coverage): make report columns adjustable (#5331)
Make the Coverage table's Line and Branch columns adjustable. The divider next to Element gives space to the file tree, and the divider between the metrics redistributes space between them. Each column shows the full covered/total count when it has room. Compact columns keep the percentage visible and show the full count on hover.

Drag a divider or focus it and use the arrow keys. Double-click a divider to restore the default widths. The table remembers widths across reloads and fits them to smaller docks.
2026-11-23 13:52:09 +08:00
Mr0Bread 1e61b3b270 perf(search): search large files in context mode and non-UTF-8 encodings without reading them whole (#5254)
Project search read a non-UTF-8 file whole and decoded it as one String, and in the comments/strings modes read every file whole to find its comments, even ones far above what the parser takes. Non-UTF-8 files now stream through an incremental decoder (ide_vfs::decode_stream: a detection pass with the same result as decode_text, then 64 KiB chunks), and files too large for the parser are not read for comments at all. Results, binary detection, the match limit and cancellation are unchanged.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:47:56 +08:00
Mr0Bread 0809eb417c perf(vcs): keep Git Log graph layout cost per page linear in the loaded commits (#5243)
computeGraph kept its lanes in a dense array indexed by layout number, which grows with the log, and scanned every slot for each row, making each further page of Git Log quadratic in the loaded commits. Lanes are now kept sparsely so a row costs its live lanes, with identical output (checked against a reference implementation), and the graph is laid out again only when an option that shapes it changes.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:45:28 +08:00
Mr0Bread 86531ee1ba perf(run): bound the output queue of run and build processes (#5256)
The run and build runners passed every pipe chunk or line to their consumer through an unbounded channel, so a process printing faster than the console drained piled its whole output up in memory (hundreds of MB for a few million lines). Both queues are now bounded (128 x 16 KiB chunks for runs, 64 lines for builds): the reader waits, the pipe fills and the child blocks on its write, as on a terminal. Nothing is dropped, and a reader blocked on a full queue ends once the consumer is gone.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:45:25 +08:00
Mr0Bread 54f0373acf fix(project-tree): find removed directories without checking every loaded dir (#5235)
planRefresh and dropListings compared every loaded folder with every removed path or ignore-rule root. They now look up each folder and its ancestors in a set (insideAnyOf), with the same semantics as isSameOrInside.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:43:24 +08:00
Mr0Bread 137b1cc384 perf(code-insight): apply diagnostics events to the problems store without copying every file's map (#5234)
Each diagnostics event copied the whole problems map, so a storm of per-file events cost files^2 copies. The store now updates its data in place and publishes a new facade per change, so subscribers still see a new identity exactly when the content changed; the MCP problems report keeps its own copy to diff against, and profiledProblems builds its map without per-file copies.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:43:19 +08:00
Mr0Bread 6c9d432504 perf(host): run route scan, agent reads and plugin keychain calls off the main thread (#5233)
spring_route_sources (walks the project tree), agent_providers (reads the registry and custom agent files), agent_entries (serialises the whole conversation), plugin_secrets and plugin_set_secret (OS keychain) were sync commands that Tauri runs on the main thread. They are now async, all but agent_entries on the blocking pool, and blocking_commands.rs keeps them there.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:43:16 +08:00
Mr0Bread 2395c9544b fix(project-tree): apply one fs change with a single model build (#5241)
Each folder reloaded for an fs event copied the listings map and notified the store, so the mounted view rebuilt the whole tree model once per folder, and the reads were unbounded. One event now reads its folders at most eight at a time and applies all listings in one store update; a folder dropped while the batch was reading stays dropped.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:36:18 +08:00
Mr0Bread 4b55039e6e fix(editor): refresh usage counts only when a source file changed (#5242)
The usages code lens re-asked the language server for every visible declaration on every fsChanged event, even ones carrying only images or logs. It now recounts only when a changed path can be a file a language server analyses (by the language registry and Settings > File Types), and still recounts when in doubt: unloaded languages or paths without an extension.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:36:12 +08:00
Mr0Bread 7264194b0f fix(history): find removed files' snapshots without scanning every removed path (#5238)
LocalHistory::note_removed compared every snapshot entry with every removed path, stalling the watcher thread (and saves waiting on the history lock) for seconds on large deletions. Entries are now matched by looking up their path and its ancestors in a set of the removed paths.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:36:06 +08:00
Mr0Bread 9ebdf0d68f fix(index): remove a deleted subtree in one pass (#5232)
A removed folder arrives with every path below it in one watcher batch; each child that was already gone was looked up as a folder and triggered another full scan of the indexed paths under the write lock, so the cost was removed paths x indexed files. Removed paths that are not indexed files are now collected and everything below them is removed in a single scan.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:36:02 +08:00
LU XIANGRUIandwildcatDownstairs 0843dd8363 fix(agents): don't reference the same file twice with Send to Agent (#5349)
Send to Agent appended an @ mention for every target even when the message already held the same file and lines, leaving duplicate chips and file entries. Mentions already in the message are skipped (a different line range is still its own reference), the draft keeps one file entry per path, and the composer is still shown when nothing new was added. Part of #5296.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-23 13:34:40 +08:00
Deng Liuanddengliu 9935bfb7c6 fix(agents): coalesce change reads per task (#5346)
The 500 ms notification timer did not cover a change-list read already running, so slow reads overlapped and an older snapshot could land last. Refreshes for one task now share one active read and one trailing read; results from an old project, a removed task or an evicted cache are dropped, and other tasks refresh independently. Refs #5335.

Co-authored-by: dengliu <[email protected]>
2026-11-23 13:34:26 +08:00
Deng Liuanddengliu db08dbc4f5 fix(agents): refresh stale queue rows without error toasts (#5334)
A turn could take the next queued message before its row disappeared, so Send now / Edit / Remove on it failed with "already sent" once per click. The dequeue is now published as soon as the turn takes the message; a stale queue action returns OutOfSync after re-publishing the current queue, which the row ignores, and only the pending row is disabled. A missing task or other failure still shows an error.

Co-authored-by: dengliu <[email protected]>
2026-11-23 13:34:22 +08:00
Deng Liuanddengliu cfab86588b perf(agents): skip change diffs for unattributed sibling checkouts (#5344)
A flat change-list request with known attribution now diffs only the nested checkouts that own the task's paths (deleted files included), resolves the nested layout once, keeps the final attribution filter, and falls back to the full scan when attribution is unknown. A task with no touched paths reads nothing. Refs #5335.

Co-authored-by: dengliu <[email protected]>
2026-11-23 13:34:18 +08:00
Deng Liuanddengliu ba300ecbf9 fix(agents): bound concurrent change-list reads across tasks (#5343)
Flat, grouped and last-turn change-list reads now share four slots per agent manager, acquired before taking a blocking worker and held until the Git work ends even if the caller goes away. Mutations and other VCS work are not limited. Refs #5335.

Co-authored-by: dengliu <[email protected]>
2026-11-23 13:32:49 +08:00
Muuandmuutot 1e79ccaf41 fix(project): run workspace-member settings work off the IPC thread (#5360)
project_workspace_members and project_workspace_member_set ran synchronously on the main thread; each attached root's for_project() re-parses both settings layers and validates the merge against Settings, which overflowed the main thread's stack from a WebView2 callback in a debug build on Windows (STATUS_STACK_OVERFLOW on project open). Both now use desktop_body = spawn with thin desktop bodies, and blocking_commands.rs keeps them off the main thread.

Co-authored-by: muutot <[email protected]>
2026-11-23 13:31:23 +08:00
LU XIANGRUIandwildcatDownstairs 6815cb5f89 fix(debugger): suppress synthetic continued events superseded by a newer stop (#5226)
resume, step and step_in_target emitted a synthetic Continued after the DAP reply even when the adapter's next stopped event had already landed (php-debug/Xdebug on fast steps), leaving the Debug window showing running while paused. The reply now ends prior stops and emits Continued under the suspension lock only when a prior stop was ended and no newer stop superseded it; stopped and continued adapter events emit under the same lock so a synthetic Continued can never follow a newer Stopped.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-23 13:28:19 +08:00
l0ng-ai a79d551bd3 fix(vcs): anchor the Git Log path editor (#5317)
- Open the resizable text editor from its Git Log filter. It follows the visible Paths or More Filters control as the window narrows.
- Give paths a code-font editing area with soft wrapping. Keep the one-path-per-line hint and apply controls beneath it.
- Enter inserts a newline. The platform's primary modifier with Enter applies the filter, and Escape or clicking outside discards the draft.
2026-11-23 13:27:58 +08:00
langxpandkradme 0284b7091b fix(debugger): keep session tab order when restarting (#5318)
Debug tabs were ordered by the backend's increasing session id, so Rerun or a replaced finished tab jumped to the end. Each tab now has a stable local slot that a rerun, a prepared start, a pinned tab's rerun and a browser page inherit; a new session reuses a stopped tab by configuration id, then name, then the selected one. Child sessions are ordered by their root's slot so they stay next to their parent.

Co-authored-by: kradme <[email protected]>
2026-11-23 13:27:13 +08:00
Charlie.Weiandcharli117 93143ce872 test(ide-host): give the Maven import-roots poll a longer deadline (#5366)
The import_roots helper in maven_external polled the background jdtls Maven re-import for 5s, which a loaded CI runner can exceed. Raise the deadline to 15s.

Co-authored-by: charli117 <[email protected]>
2026-11-23 13:25:05 +08:00
Charlie.Weiandcharli117 6cbb27ed82 test(ide-lsp): wait for the retiring transport to close before asserting (#5365)
java_sharing_cancels_a_retiring_initialize_before_starting_its_replacement checked old.is_closed() once right after reconfigure() returned, racing the asynchronous close on a loaded runner. Wait for the close before releasing the initialize response; the ordering guarantee still holds because the gate stays shut until then.

Co-authored-by: charli117 <[email protected]>
2026-11-23 13:25:01 +08:00
Charlie.Weiandcharli117 74cf06505f test(ide-docker): wait for the log flush instead of a fixed sleep (#5363)
log_lines_arrive_in_order_as_few_batches slept 80ms and assumed the 30ms flusher had emitted the 1000-line burst by then; on a loaded runner the flusher is starved and the trailing line folds into the burst. Wait until every line of the burst has been flushed before sending the trailing one.

Co-authored-by: charli117 <[email protected]>
2026-11-23 13:22:45 +08:00
l0ng-ai d6d73e1072 test(search): measure the scope pattern field after the dialog settles (#5364)
The Scopes dialog relays out over a few frames after the viewport shrinks; wait until the pattern field's position is stable before measuring it.
2026-11-23 13:09:37 +08:00
l0ng-ai bbea793adf fix(debugger): align the Python table viewer (#5309)
- Keep the shape and paging controls above the table and put the full-width slice expression below it, above Close. The grid scrolls between the controls.
- Open at 700 × 500 when there is room. Give short tables the available width, use workbench typography and center the row and column headers.
- Update the title when a slice is submitted and show expression errors below the field.
2026-11-23 13:01:59 +08:00
l0ng-ai f1c556e2ec fix(editor): align the Find Usages source preview (#5305)
- Start with equal space for the results tree and source preview. Each orientation restores its saved split and starts at 50/50 when it has no saved split.
- Follow the editor's line height and size the preview gutter for the document's longest line number. Keep the selected line visible when the panel height or line metrics change.
2026-11-23 12:42:18 +08:00
l0ng-ai 2d99a79e69 fix(settings): align the Editor Tabs form (#5300)
- Align the tab placement and close button selectors in the Appearance form.
- Put the row and overflow choices on separate lines with the overflow options nested under the single-row choice. The two groups retain their own selections and support independent arrow-key navigation.
- Stack each set of closing policy choices below its heading, so the order stays consistent as the window narrows.
2026-11-23 12:24:08 +08:00
l0ng-ai ca778e2382 fix(search): improve structural template layout (#5298)
- Put the language picker in the Search template header and keep each label next to its template.
- Give both templates 150 px of editing space in a standard window. Tighten the editors on shorter screens and keep the dialog footer accessible.
- Use the configured editor font, size, and line height in both templates.
2026-11-23 12:08:57 +08:00
Deng Liuandl0ng-ai 414353a5bd ci: add Docker Compose setup for persistent self-hosted Actions runners (#5307)
* ci: add Docker Compose setup for persistent self-hosted Actions runners

* ci: wire Linux Rust CI to hardened self-hosted runners under scripts/

* ci: gate self-hosted runners behind a variable and use the jammy image

- Pin the Ubuntu 22.04 runner image; the untagged-distro image is 20.04 and
  cannot install libwebkit2gtk-4.1-dev.
- Route the Linux Rust job to self-hosted runners only while the
  SELFHOSTED_RUNNERS repository variable is 'true', so CI keeps working when
  no runner is online.
- On self-hosted runners, enable incremental compilation and clear the
  persistent target dir once it exceeds 40 GB.
- README: document the variable, passwordless sudo inside the container and
  the target dir shared between main and same-repo branches.

---------

Co-authored-by: l0ng-ai <[email protected]>
2026-11-23 11:54:56 +08:00
l0ng-ai 3080dc6100 fix(editor): balance the Edit Macros panes (#5293)
Edit Macros starts with equal widths for the macro list and recorded steps. The keyboard-resizable divider remembers its position. Rename and Delete sit in the toolbar above the macro list, and the dialog opens with focus on the list. Recorded steps use the UI font and wrap within their pane.
2026-11-23 11:45:46 +08:00
l0ng-ai 1bb9f8d07c fix(analysis): align controls with scope choices (#5292)
The shared analysis scope picker aligns directory and custom scope controls with their radio choices. At narrow widths each control sits directly below its choice. Controls stay visible when inactive, and switching the radio selection keeps both values.
2026-11-23 11:24:06 +08:00
l0ng-ai a539baec37 test(settings): measure Git Log checkboxes after the dialog settles (#5311)
The Git Log settings layout test read two checkbox positions one after the other while the Settings dialog was still opening, so it failed depending on timing. It now polls both positions together until they match.
2026-11-23 11:16:43 +08:00
l0ng-ai 7dff6e1852 fix(debugger): give Memory class filtering room (#5289)
The Debug Memory toolbar uses the available space for class search and places the Changed only filter in View Options at the right edge. The button shows when the filter is active. The search field shows a clear button when a query is present.
2026-11-23 11:07:14 +08:00
l0ng-ai fc7fa85850 fix(maven): give plugin names priority in the tree (#5288)
Maven plugin rows use the plugin prefix as the primary label and show the coordinates in muted text. The coordinates truncate independently in narrow docks and can be read in full from their tooltip.
2026-11-23 10:49:33 +08:00
l0ng-ai 7e5a2cf051 fix(vcs): group Git Log display settings (#5287)
Settings → Version Control → Log now groups the display and column checkboxes under titled separators. Both groups use the same checkbox alignment, row spacing, and UI font size, so the controls are easier to scan at narrow window widths.
2026-11-23 10:32:53 +08:00
l0ng-ai c4e08a9676 fix(gradle): keep task descriptions in row tooltips (#5286)
Gradle task rows give the available space beside the icon to the task name. The full description appears in the row tooltip, where assistive technology can also read it.
2026-11-23 10:06:57 +08:00
l0ng-ai 2c0b76c9e6 fix(editor): align the line separator menu (#5284)
- Give the line separator picker a standard menu heading. List Windows, Unix and macOS, and classic Mac OS from top to bottom.
- Use the localized platform names and escaped newline sequences in the menu. The status bar still shows the abbreviation and the menu checks the current format.
2026-11-23 09:48:46 +08:00
l0ng-ai 4d1f51c607 fix(editor): integrate usage access filters into the toolbars (#5283)
- Put read and write filters alongside the other actions in Show Usages and in the Find Usages tool window. Both results areas use the space previously occupied by a separate filter row.
- Keep the two buttons together as the popup narrows. The side toolbar can scroll when the tool window is short.
2026-11-23 09:26:05 +08:00
l0ng-ai 2215239ecb fix(editor): put the pin in the editor tab action slot (#5282)
- Put the pin in a pinned editor tab's action slot so the filename has more room. The pin follows the left or right placement and can unpin the tab directly.
- Use the same Unpin action in Hidden Editor Tabs. A modified pinned tab shows its unsaved marker beside the pin.
2026-11-23 09:23:25 +08:00
l0ng-ai 43eeb080be fix(run): expand multiline configuration fields in place (#5267)
Multiline run configuration fields now keep the Expand button inside the field. The larger editor opens next to the field so the configuration stays in view. It can be resized, scrolls long arguments horizontally, and applies edits through OK or Ctrl/⌘+Enter.
2026-11-23 09:16:39 +08:00
l0ng-ai 03a19d4284 fix(search): keep line numbers visible in text results (#5281)
- Give Search Everywhere's Text results a separate column for the line number. Long filenames truncate within the existing metadata width, leaving the same amount of space for the highlighted code snippet.
- Use tabular digits at the trailing edge and show the full relative path on hover.
2026-11-23 09:16:00 +08:00
l0ng-ai 3aeee3fcfc fix(settings): align the navigation tree spacing (#5280)
- Move the top-level disclosure arrows away from the sidebar edge and reduce each nested level from 20 px to 16 px.
- Keep leaf and expandable labels aligned at the same depth. The third-level result has 4 px more room in the 160 px sidebar shown below.
2026-11-23 09:15:52 +08:00
l0ng-ai 471003a8c5 fix(vcs): size annotation details to their content (#5279)
Git annotation details size themselves to the commit text, so short messages cover less of the editor. Long author details and messages wrap within the available width. The revision and its metadata share the tooltip's UI font, and the full revision remains clickable.
2026-11-23 09:15:44 +08:00
l0ng-ai c109773d2a fix(editor): keep completion controls on one row (#5278)
The completion footer keeps its shortcut hint and sorting control on one line. In narrow editor splits the hint shortens first, and hovering reveals its full text. The compact footer takes up less vertical space in the editor.
2026-11-23 09:15:36 +08:00
l0ng-ai ed6b67faed fix(run): keep configuration types reachable in short windows (#5277)
Add New Configuration keeps the title and search field above a scrollable list. The picker keeps its width while filtering with the standard 16 px icons and shows more types when the window has room. After filtering, Enter opens the configuration type highlighted in the list, including types under a group heading.
2026-11-23 09:15:28 +08:00
l0ng-ai ff7bfcaf1d fix(search): keep file context visible in Find previews (#5275)
The source preview in Find in Files and Replace in Files keeps the filename prominent and leaves the end of its containing path visible. The middle of a long directory shortens to fit, and hovering over the caption reveals the full project-relative path.
2026-11-23 09:15:20 +08:00
l0ng-ai 91330a82d0 fix(build): keep diagnostic names and elapsed time readable (#5274)
The Build tree shortens long directory hints first so there is room for the filename and diagnostic counts. The build duration uses smaller, tabular text at the trailing edge. Hovering over a file row reveals its full path.
2026-11-23 09:15:11 +08:00
l0ng-ai ce75c58a34 fix(workbench): give notification balloons room for their content (#5270)
Notification balloons reserve space for Dismiss in the title row. The body and action rows extend underneath it, giving paths and action labels more room to wrap in narrow windows. The cards use the standard UI text size and spacing.
2026-11-23 09:15:01 +08:00
l0ng-ai 03b9070b9b fix(vcs): show file names in staging diff headings (#5268)
The three-way staging diff displays the filename in the index heading. When a version has a different path, its heading shows that filename too. The headings use the standard workbench text size, and hovering over a filename heading reveals its full path.
2026-11-23 09:14:53 +08:00
l0ng-ai f6f610516c fix(vcs): clarify staging groups and row actions (#5266)
The Commit staging tree gives group headings more weight so the staged, unstaged, and unversioned sections are easy to scan. The inline Stage or Unstage action appears on the current selected row and on hover, so a multi-selection shows which row the inline action applies to.
2026-11-23 09:14:44 +08:00
l0ng-ai cf49a91b66 fix(vcs): group branches and tags in commit details (#5265)
Git Log commit details now show branches and tags in separate groups. Reference names use the same size as the surrounding metadata, and each group wraps within the details pane.
2026-11-23 09:14:35 +08:00
l0ng-ai e0a97e32f7 fix(terminal): give scrollback search a compact layout (#5264)
Size the floating terminal find bar to its controls. Keep the match count beside the previous and next buttons, and move the controls below the query in narrow docks so the full first row is available for typing.
2026-11-23 09:14:26 +08:00
l0ng-ai dd0eeeae29 fix(debugger): align compact editor value hints (#5262)
Use the standard bold UI font for compact debugger value hints. Put the variable icon and expand control beside the summary so wrapped values align with their first line. Size the hint to the available editor width, including when a dock reduces the space or the window is resized.
2026-11-23 09:14:18 +08:00
l0ng-ai 4bb22df1fb fix(run): show before-launch tasks as ordered tags (#5261)
Show before-launch tasks as compact tags numbered in execution order. Tags wrap within the configuration form, and each task has a remove button and a menu for moving it up or down. Shell commands stay editable in place.
2026-11-23 09:14:10 +08:00
l0ng-ai aee087597a fix(vcs): show readable commit message history previews (#5258)
Place commit message history just above the editor and use the same font settings as the draft. Show the beginning of the body in each row so messages with the same subject are distinguishable. Keep seven rows visible when space allows and scroll through the rest.
2026-11-23 09:14:02 +08:00
l0ng-ai 993a321dd0 fix(vcs): keep commit check actions visible while reading results (#5257)
Give commit check results their own scroll area. The status icon and retry action stay in place, and the results fit the space above the commit buttons. Use the standard 13 px UI type and a 4 px gap between results.
2026-11-23 09:13:53 +08:00
l0ng-ai 381e66aca5 fix(vcs): keep commit subjects readable in the Amend chooser (#5253)
The Amend chooser sizes to its contents within the window, up to about 520 px. Long subjects get more room and the full text on hover. The latest commit row gives its action label more weight and leaves the subject in secondary text. The list still shows five rows before scrolling.
2026-11-23 09:13:45 +08:00
l0ng-ai d7a05eea21 fix(vcs): align commit author and date fields (#5252)
Commit Options gives the author and date fields a shared label column when there is room. A narrow options pane puts the labels above the controls and moves the clear button below the date when needed. In the 650 px desktop window, the author input grew from 104 px to 157 px, and the date input grew from 133 px to 157 px. The native date control can still clip part of the time display at that width.
2026-11-23 09:13:37 +08:00
l0ng-ai c61ddbff3d fix(vcs): make Git Log commit choices easier to scan (#5250)
The Git Log commit chooser now gives its results the full dialog width and sizes the list to the number of candidates. Previously the list could be clipped inside a fixed-height area. Each row separates the subject from the hash, author and timestamp. The search field keeps keyboard focus while the arrow keys move the selection.
2026-11-23 09:13:30 +08:00
l0ng-ai 0c20d72cbf fix(project): group file rename options below the name field (#5247)
Project tree Rename places the name prompt directly above the input and keeps the two search options together below it. The options share one row when they fit and wrap at the dialog width. This gives the name and any validation message a clear place in the form.
2026-11-23 09:13:22 +08:00
l0ng-ai 021f334c0c fix(run): keep configuration names distinct in gutter menus (#5245)
Run and Debug menus keep the end of a long configuration name visible beside the shortcut. When the label runs out of room, the menu truncates the middle so names with the same prefix remain distinguishable. Hovering still shows the full name.
2026-11-23 09:13:13 +08:00
l0ng-ai c61264cdf9 fix(search): keep recent find and replace values readable (#5244)
The editor Find bar and the Find and Replace in Files dialog now share one history menu. The menu can grow up to 200 px wider than its field, within the window, and the text uses the space previously reserved for icons. The heading stays visible as the list scrolls. Multi-line entries show a line-break marker and restore the original text when selected.
2026-11-23 09:13:05 +08:00
l0ng-ai e4d6f50a0b fix(search): make Replace All details easier to review (#5236)
Replace All puts the affected count above separate, scrollable values for the search text and replacement. Both values stay available in full, and an empty replacement is labeled explicitly. The Replace in Files popup and the Find tool window use the same confirmation.
2026-11-23 09:12:56 +08:00
l0ng-ai 0435e0330e fix(search): keep scope names and patterns readable in the editor dialog (#5231)
The Scopes dialog in Find in Files keeps its list scrollable beside the Name and Pattern fields. At narrow widths the editor moves below the list, giving the pattern more room. Long names show an ellipsis and a tooltip, and the selected scope stays visible when a row is added.
2026-11-23 09:12:48 +08:00
l0ng-ai 13b5f9e575 fix(editor): keep image viewer controls and details readable (#5230)
The image viewer groups the image and zoom controls at the start of a compact toolbar. Its dimensions, file size, and zoom appear at the other end in the standard UI text size. In narrow splits the details wrap onto another row, leaving the SVG Open as Text action readable on one line.
2026-11-23 09:12:39 +08:00
l0ng-ai dde4b28abd fix(editor): keep color picker controls in view (#5228)
The editor color picker uses a shorter color field and a tighter control row. Numeric inputs use the UI text size, recent colors wrap with consistent spacing, and the action buttons stay visible when the popup has to scroll.
2026-11-23 09:12:30 +08:00
l0ng-ai 3817724637 fix(vcs): make files and actions easier to scan in local changes review (#5227)
The local changes review shows the filename first and uses smaller, muted text for its parent folder. This keeps filenames visible when directories are long. The warning and change preservation hint sit together above the file list. Force Checkout sits on the left, with Smart Checkout and cancellation on the right.
2026-11-23 09:12:22 +08:00
l0ng-ai 26b5856ce0 feat(workbench): let users move the More Tool Windows button (#5224)
Right-click **More Tool Windows** (`…`) and choose **Move to Right** or **Move to Left**. The workbench previously placed this button on the left unconditionally. It now starts on the left, remembers your choice across restarts, and opens the list toward the editor from either edge.
2026-11-23 09:12:13 +08:00
l0ng-ai 6aeb733f20 fix(run): make test report export paths easier to edit (#5223)
The test results export dialog puts HTML and XML on separate rows and gives the file name and folder separate fields. The file name is selected on open, so it can be replaced without retyping the directory. Pasting a full path and choosing a destination with Browse still work.
2026-11-23 09:12:05 +08:00
l0ng-ai 29fcec6ab8 fix(debugger): keep gutter breakpoint controls in view (#5221)
The gutter breakpoint popup puts the file and line in a fixed header and keeps the action buttons visible while the fields scroll. The popup gives the condition and hit-count fields more room. Long filenames shorten in the header while the line number stays visible. The same popup layout covers method breakpoints and field watchpoints.
2026-11-23 09:11:56 +08:00
l0ng-ai 5d6c76cdda fix(keymap): make shortcut recording and conflicts easier to read (#5220)
The shortcut recorder puts the action name and its category in the dialog body and uses a full-width first field. The optional second stroke stays beside its checkbox. Conflicting actions use two-line rows that keep the action name, category and binding readable in a narrow window.
2026-11-23 09:11:47 +08:00
l0ng-ai 844c2f3145 test(maven): wait for the background refresh of jdtls import roots (#5272)
external_maven_link_persists_reloads_and_unlink_keeps_files failed on the macOS runner: setting languages.java.maven.linkedProjects refreshes the language server's import roots on a blocking task, and the test read them right after build_model returned. It now waits up to 5 s for them to change.
2026-11-23 05:18:24 +08:00
Charlie.Weiandcharli117 76d67145f5 test(smoke): give the language-smoke closure tests a 20s timeout (#5240)
The two Language smoke workflow tests compute the repo-wide import closure and crate tree. On a CI runner running the whole suite they took longer than vitest's default 5 s and failed the Frontend job on main.

Co-authored-by: charli117 <[email protected]>
2026-11-23 01:13:43 +08:00
Charlie.Weiandcharli117 cf4273eeea chore(deps): bump url to 2.5.9 for RUSTSEC-2026-0592 (#5237)
url 2.5.8 overflows the stack in Url::origin() on nested blob: URLs (RUSTSEC-2026-0592), which failed Cargo deny on main. 2.5.9 fixes it; form_urlencoded moves to 1.2.3 with it. The rest of the lockfile stays as on main.

Co-authored-by: charli117 <[email protected]>
2026-11-23 01:13:33 +08:00
l0ng-ai 81dd5f0dd2 fix(vcs): keep Git Log path selection in a resizable tree (#5218)
The Git Log path chooser now uses a compact, resizable dialog with a framed file tree. Files and folders have icons and use the standard workbench text size. Long names shorten inside their rows and show the full name on hover. The tree and the checked paths list scroll independently, keeping both reachable in a short window.
2026-11-22 22:57:50 +08:00
l0ng-ai 36061abc91 fix(debugger): lay out inline evaluation and history together (#5216)
The Variables pane now keeps Add to Watches and the history arrow at the trailing edge of the evaluation field. The field uses the configured editor font family at up to the workbench text size, and its short placeholder fits narrow docks. The history menu matches the field width and uses the existing Evaluate history for single-line expressions.
2026-11-22 22:24:43 +08:00
l0ng-ai b8a11df800 fix(editor): keep tab title disambiguation out of the editor API (#5222)
src/editor/api.ts re-exported disambiguateTitles, which brought src/editor/core/model/tabTitles.ts into what the frontend language smoke loads without it being in that workflow's paths, so scripts/smoke-paths.test.ts failed on main. The Show Usages popup now imports it from its module, as EditorArea does.
2026-11-22 22:04:12 +08:00
l0ng-ai 401c542647 feat(vcs): improve Git workflows (#5174)
Improve OpenIDEA's Git workflows across commit and staging, branch and remote operations, merge and rebase, Git Log and signing, worktrees, stash and shelf, patch application, and clone settings. Adds a one-click stash for tracked changes across Git roots and lets users open a worktree branch's associated GitHub review from its context menu. Cloning now includes submodules by default (Settings › Version Control › Git, can be turned off).

Repository entry points added here run in each repository's execution scope, so they use the project's own git executable.
2026-11-22 21:57:30 +08:00
l0ng-ai a435be54e0 fix(editor): compact the line-number gutter (#5212)
Editor line numbers use a font 1 px smaller than the code and a more compact column. The gutter grows with the editor font and with longer line numbers. Sticky Lines uses the same number metrics, and a breakpoint sits at the trailing edge of the number column at the full editor font size.
2026-11-22 21:56:37 +08:00
l0ng-ai 4b58b2a5a5 fix(agents): clear the selection highlight on off-screen conversation rows (#5209)
Selecting new text in an agent conversation left the previous selection highlighted on messages that had been scrolled out of view, so it looked like several selections at once while copying only the new one. Rows that were laid out once skip rendering off screen (`content-visibility: auto`), and WebKit doesn't clear the selection highlight of skipped rows. While the conversation holds a selection, every row now renders (`data-selection` on the stream), until the frame after the selection is cleared, when WebKit applies the change; then off-screen rows skip rendering again.
2026-11-22 21:40:40 +08:00
l0ng-ai 39068cffb3 fix(editor): make Find Usages result rows easier to scan (#5207)
Find Usages now uses the result tree's font for both line numbers and snippets. Line numbers start at the same indent and take only the width of their digits, with a 4 px gap before the snippet. This brings short line numbers closer to their code and gives the snippet more room on narrow panes.
2026-11-22 21:31:46 +08:00
l0ng-ai bef9223913 fix(database): rename databases and schemas from the tree (#5219)
Rename… (db.rename, Shift+F6) did nothing on a database or schema node: canRename accepted only tables, columns, views and PostgreSQL indexes, and database nodes map to no schema object.

Databases of a server that creates them (PostgreSQL, SQL Server) now rename with ALTER DATABASE after the IDE closes its sessions on them; the connected database and read-only sources keep Rename disabled, as Drop does. Schemas rename with ALTER SCHEMA on PostgreSQL and Snowflake. Both use the rename dialog with its SQL preview and refresh the tree.

Fixes #5205
2026-11-22 21:25:44 +08:00
lifeir f2b06bc376 feat(run): npm tool window with the project's package.json scripts (#5217)
A new npm tool window on the right lists the scripts of every package.json in the project (root, workspace members, detected module roots and any other package.json the index knows outside node_modules), grouped by package. Double-click runs a script; the context menu offers Run / Debug through the same path as the package.json gutter, reusing a matching run configuration or creating a temporary one. The window appears only while the project has scripts and refreshes when a package.json changes or indexing finishes. The editor context menu on a package.json script line also offers Run / Debug for that script.

Co-authored-by: lifeir <[email protected]>
2026-11-22 21:10:59 +08:00
l0ng-ai 08d719e03d fix(search): keep action names and shortcuts readable (#5203)
Search Everywhere reserves room for action names alongside shortcuts and categories. Shortcut text is smaller and semibold. Very long key sequences and categories can shorten with an ellipsis, and hovering shows their full text.
2026-11-22 21:07:00 +08:00
ntbang0901 aa849b9cf4 fix(vcs): keep each project's git executable with its repositories (#5214)
Settings › Version Control › Git › Path to Git executable can be set per project, but the value lived in one process-wide variable that each trusted window overwrote before running git. Two windows running git at once could start a command of one project with the other's executable, and a relative value then resolved inside the wrong repository.

Each project's repositories now carry its executable on the same per-thread scope that already carries their trust. Work that opens repositories of its own (agent worktrees and snapshots, gh pull requests, plugin repository access, Create Git Repository…) runs with the project's value. The process-wide value is only the global settings' one, used for git without a project (clone, init without a project).

Co-authored-by: ntbang0901 <[email protected]>
2026-11-22 20:56:38 +08:00
l0ng-ai 0cc8f90708 fix(vcs): keep long Git Log filters compact (#5201)
Long Git Log filter values now end in an ellipsis, with the full value available on hover. A tighter width in compact commit panes keeps the active filter and its clear button visible at more window sizes.
2026-11-22 20:47:43 +08:00
LU XIANGRUIandwildcatDownstairs bc307fdea3 feat(lsp): lint CSS, SCSS and Less with Stylelint (#5208)
CSS, SCSS and Less files get Stylelint diagnostics from the Stylelint language server, installed on demand like the other tools. A project's Stylelint config is picked up as is, a Fix Stylelint Problems action applies the server's fixes, and the built-in CSS diagnostics step aside for rules Stylelint covers.

Closes #5156

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 20:44:18 +08:00
ntbang0901 407f1c5235 feat(debugger): toggle an exception breakpoint from a throw or catch (#5206)
Alt+Enter on a throw statement or a catch parameter offers to create, enable or disable a Java exception breakpoint for that exception type. The type is resolved by the new openidea.java.exceptionType command in the java-usages bundle (1.17.0), and intention providers can now be asynchronous.

Co-authored-by: ntbang0901 <[email protected]>
2026-11-22 20:43:54 +08:00
l0ng-ai ddf9cc3d70 fix(debugger): stabilize the inline variable editor (#5195)
Keep a debugger variable's icon, name and equals sign anchored when Set Value opens. The input fits the tree row, and an error uses a limited share of the value area so the field remains usable in a narrow pane.
2026-11-22 20:43:05 +08:00
l0ng-ai 6e4f536722 fix(search): keep Find in Files footer actions together (#5192)
Keep the shortcut hint beside Open in Find Window and keep Replace All beside the current selection action when the popup wraps. A separator and a smaller keyboard hint give the footer its own visual hierarchy. The popup handles its advertised shortcut when either search field has focus.
2026-11-22 20:42:54 +08:00
1294 changed files with 98029 additions and 15321 deletions

No files matched your search

Binary file not shown.

Before

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 169 KiB

+29 -3
View File
@@ -102,24 +102,44 @@ jobs:
name: Rust (${{ matrix.os }})
needs: changes
if: needs.changes.outputs.rust == 'true'
permissions:
contents: read
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
os: [macos-latest, ubuntu-22.04, windows-latest]
runs-on: ${{ matrix.os }}
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ matrix.os == 'ubuntu-22.04' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with: { node-version: 22, cache: pnpm }
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- uses: dtolnay/rust-toolchain@stable
with: { components: "clippy, rustfmt" }
# Only main saves the cache (saving takes minutes on Windows); PRs restore main's.
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
# (only main saves it because saving takes minutes on Windows; PRs restore main's).
- uses: Swatinem/rust-cache@v2
if: runner.environment != 'self-hosted'
with:
save-if: ${{ github.ref == 'refs/heads/main' }}
# The persistent target dir makes incremental builds pay off; cap its size so it can't fill the disk.
- name: Persistent Cargo target dir
if: runner.environment == 'self-hosted'
shell: bash
run: |
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
if [ "${size:-0}" -gt 40000 ]; then
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
rm -rf "$CARGO_TARGET_DIR"
fi
- uses: taiki-e/install-action@nextest
- name: Linux deps
if: runner.os == 'Linux'
@@ -135,6 +155,12 @@ jobs:
# Test fixtures write LF files; keep Git from converting them on checkout.
- run: git config --global core.autocrlf false
- run: cargo nextest run --workspace --no-fail-fast
- name: Remote backend with Docker Compose
if: runner.os == 'Linux'
run: |
docker pull busybox:latest
cargo nextest run -p ide-host --test remote_daemon --run-ignored only \
-E 'test(=compose_service_survives_disconnect_and_is_removed_on_stop)'
# nextest skips doctests; ide-command's are its compile-fail tests.
- if: runner.os == 'Linux'
run: cargo test --doc -p ide-command
+48 -13
View File
@@ -65,6 +65,8 @@ concurrency:
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
# Line tables keep test backtraces readable and the binaries the build job hands on small.
CARGO_PROFILE_DEV_DEBUG: line-tables-only
jobs:
# The languages a pull request can affect: a change to one language's fixture, definition or
@@ -132,10 +134,40 @@ jobs:
done < files.txt
echo "languages=$(emit "$langs")" | tee -a "$GITHUB_OUTPUT"
smoke:
name: Language smoke (${{ matrix.language }})
# Builds the smoke test binaries and openidea-server once for every language below.
build:
name: Build
needs: changes
if: needs.changes.outputs.languages != '[]'
# The tests find the fixtures through the checkout path compiled into them (CARGO_MANIFEST_DIR),
# which is the same on every GitHub-hosted runner.
runs-on: ubuntu-22.04
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
shared-key: language-smoke
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: |
set -euo pipefail
mkdir -p smoke-bin
cargo test --locked -p ide-host --test language_smoke --test project_smoke --no-run --message-format=json \
| jq -r 'select(.reason == "compiler-artifact" and .executable != null and .target.kind == ["test"]) | "\(.target.name) \(.executable)"' \
| while read -r name exe; do cp "$exe" "smoke-bin/$name"; done
cargo build --locked -p ide-host --bin openidea-server
cp target/debug/openidea-server smoke-bin/
ls -l smoke-bin
test -x smoke-bin/language_smoke && test -x smoke-bin/project_smoke
# A tar keeps the executable bits, which artifacts drop.
tar -cf smoke-bin.tar smoke-bin
- uses: actions/upload-artifact@v6
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
smoke:
name: Language smoke (${{ matrix.language }})
needs: [changes, build]
strategy:
fail-fast: false
matrix:
@@ -149,11 +181,11 @@ jobs:
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
- uses: dtolnay/rust-toolchain@stable
with: { components: "rust-analyzer, rustfmt" }
# One build cache for every language; main saves it.
- uses: Swatinem/rust-cache@v2
with:
shared-key: language-smoke
save-if: ${{ github.ref == 'refs/heads/main' && matrix.language == 'rust' }}
- uses: actions/download-artifact@v6
with: { name: smoke-bin }
- run: |
tar -xf smoke-bin.tar && rm smoke-bin.tar
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
- uses: pnpm/action-setup@v4
with: { version: 11 }
@@ -209,17 +241,20 @@ jobs:
- if: matrix.language == 'php'
run: npm install --global "intelephense@$INTELEPHENSE"
- run: cargo test --locked -p ide-host --test language_smoke --no-run
- run: cargo test --locked -p ide-host --test language_smoke -- --ignored --exact ${{ matrix.language }}
# The binaries from the build job, run from the crate directory as `cargo test` does.
- working-directory: crates/ide-host
run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }}
- if: matrix.language == 'java'
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
working-directory: crates/ide-host
run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
- if: matrix.language == 'kotlin'
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact gradle_sync
working-directory: crates/ide-host
run: ../../smoke-bin/project_smoke --ignored --exact gradle_sync
- if: matrix.language == 'python'
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact python_venv
working-directory: crates/ide-host
run: ../../smoke-bin/project_smoke --ignored --exact python_venv
- run: pnpm install --frozen-lockfile
- run: cargo build --locked -p ide-host --bin openidea-server
- run: pnpm smoke smoke/run.test.ts -t "^${{ matrix.language }}$"
- run: pnpm smoke smoke/debug.test.ts -t "^${{ matrix.language }}$"
# The IDE installs the debugger from GitHub releases: authenticated, against rate limits.
+2 -1
View File
@@ -79,8 +79,9 @@ Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
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:local [--build-only]` (or `mise run dogfood:local`) — 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.
- `pnpm dogfood:all <remote_name> [--restart | --no-restart]` (or `mise run dogfood:all <remote_name>`) — run `dogfood:local` and `dogfood:remote <remote_name>` in parallel.
- `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
+12 -28
View File
@@ -1104,9 +1104,9 @@ checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
[[package]]
name = "cookie"
version = "0.18.2"
version = "0.18.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"
checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a"
dependencies = [
"time",
"version_check",
@@ -2361,9 +2361,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
dependencies = [
"percent-encoding",
]
@@ -4180,8 +4180,6 @@ dependencies = [
"rayon",
"serde",
"specta",
"tracing",
"tree-sitter",
]
[[package]]
@@ -4191,7 +4189,6 @@ dependencies = [
"ide-core",
"serde",
"specta",
"tempfile",
"which",
]
@@ -4253,6 +4250,7 @@ dependencies = [
name = "ide-core"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"dunce",
"encoding_rs",
"libc",
@@ -4277,7 +4275,6 @@ dependencies = [
"serde_json",
"specta",
"tempfile",
"tracing",
]
[[package]]
@@ -4316,7 +4313,6 @@ dependencies = [
"base64 0.22.1",
"bb8",
"blake3",
"dirs 6.0.0",
"dunce",
"flate2",
"futures",
@@ -4382,7 +4378,6 @@ dependencies = [
"blake3",
"dunce",
"ed25519-dalek",
"ide-core",
"parking_lot",
"semver",
"serde",
@@ -4437,6 +4432,7 @@ version = "0.1.50"
dependencies = [
"criterion",
"ide-core",
"ide-heap",
"libc",
"memmap2",
"proptest",
@@ -4540,7 +4536,6 @@ dependencies = [
"specta",
"tempfile",
"tokio",
"tracing",
"uuid",
]
@@ -4553,6 +4548,7 @@ dependencies = [
"dunce",
"globset",
"ide-core",
"ide-index",
"ide-language",
"ignore",
"nucleo-matcher",
@@ -4583,7 +4579,6 @@ name = "ide-jsonrpc"
version = "0.1.50"
dependencies = [
"encoding_rs",
"futures",
"ide-core",
"parking_lot",
"serde",
@@ -4726,7 +4721,6 @@ dependencies = [
name = "ide-notebook"
version = "0.1.50"
dependencies = [
"futures",
"ide-core",
"ide-vfs",
"jupyter-protocol",
@@ -4739,7 +4733,6 @@ dependencies = [
"specta-typescript",
"tempfile",
"tokio",
"tracing",
"uuid",
"windows-sys 0.61.2",
"zeromq",
@@ -4759,7 +4752,6 @@ dependencies = [
"serde_json",
"specta",
"tempfile",
"thiserror 2.0.21",
"tokio",
"tracing",
"url",
@@ -4846,6 +4838,7 @@ dependencies = [
name = "ide-sdk"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
"dunce",
"flate2",
@@ -4857,6 +4850,7 @@ dependencies = [
"quick-xml 0.42.0",
"serde",
"serde_json",
"sha2 0.10.9",
"specta",
"tar",
"tempfile",
@@ -5012,6 +5006,7 @@ dependencies = [
"ide-core",
"ignore",
"libc",
"notify",
"redb",
"regex-lite",
"serde",
@@ -6705,14 +6700,11 @@ dependencies = [
"dunce",
"gtk",
"ide-agent",
"ide-analysis",
"ide-android",
"ide-build",
"ide-cli",
"ide-clipboard",
"ide-command",
"ide-core",
"ide-coverage",
"ide-dap",
"ide-db",
"ide-docker",
@@ -6722,24 +6714,16 @@ dependencies = [
"ide-github",
"ide-host",
"ide-http",
"ide-index",
"ide-jsonrpc",
"ide-language",
"ide-lsp",
"ide-mcp",
"ide-notebook",
"ide-plugin",
"ide-profiler",
"ide-remote",
"ide-run",
"ide-scaffold",
"ide-sdk",
"ide-search",
"ide-spell",
"ide-ssh",
"ide-syntax",
"ide-terminal",
"ide-text",
"ide-tools",
"ide-vcs",
"ide-vfs",
@@ -10826,9 +10810,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
version = "2.5.8"
version = "2.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
dependencies = [
"form_urlencoded",
"idna",
-2
View File
@@ -69,13 +69,11 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time"
tokio-util = { version = "0.7", features = ["rt"] }
parking_lot = "0.12"
rayon = "1"
dashmap = "6"
futures = "0.3"
tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "__rustls-tls"] }
# errors & diagnostics
thiserror = "2"
anyhow = "1"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
+1 -1
View File
@@ -68,7 +68,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
- WeChat group — scan to join:
<img src=".github/assets/wechat-group-3.png" alt="WeChat group QR code" width="200">
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
- Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup).
+1 -1
View File
@@ -68,7 +68,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
- WeChat grubu, katılmak için kodu okut:
<img src=".github/assets/wechat-group-3.png" alt="WeChat grubu QR kodu" width="200">
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
+1 -1
View File
@@ -66,7 +66,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
- 微信群,扫码加入:
<img src=".github/assets/wechat-group-3.png" alt="微信群二维码" width="200">
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
- 参与贡献:参见 [CONTRIBUTING.md](CONTRIBUTING.md) 和[贡献者文档](https://openidea.sh/zh/contribute/setup)。
+2 -1
View File
@@ -35,7 +35,8 @@ icon set, copied unmodified (some renamed) from JetBrains' open-source repositor
→ `maven/`); `plugins/gradle` (`icons/expui/gradle` → `toolwindows/gradle`,
`icons/expui/gradleLoadChanges` → `build/gradleLoadChanges`,
`icons/expui/gradle`, `icons/gradleSubproject` → `gradle/`);
`platform/external-system-impl` (`icons/newui/task` → `externalSystem/task`).
`platform/external-system-impl` (`icons/newui/task` → `externalSystem/task`);
`platform/dvcs-impl` (`icons/new/cherryPick` → `vcs/cherryPick`).
Copyright 2000-2026 JetBrains s.r.o. and contributors. Apache License 2.0 (below).
- [intellij-plugins](https://github.com/JetBrains/intellij-plugins) (each plugin
carries its own licence): `protobuf/protoeditor-core` (`newui/protoFile` →
+9 -6
View File
@@ -169,9 +169,12 @@ fn make_manager_at(root: &Path, models_file: &Path, catalogs: Arc<AgentCatalogs>
fn events(manager: &AgentManager) -> mpsc::UnboundedReceiver<AgentEvent> {
let (tx, rx) = mpsc::unbounded_channel();
manager.subscribe(Arc::new(move |event| {
let _ = tx.send(event);
}));
manager.subscribe_as(
"",
Arc::new(move |event| {
let _ = tx.send(event);
}),
);
rx
}
@@ -489,7 +492,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
set.reply.send(Err("Sign in required".into())).unwrap();
let error = switching.await.unwrap_err().to_string();
assert!(error.contains("Sign in required"), "{error}");
assert_eq!(manager.subscribe(Arc::new(|_| {})).remove(0).config, before_config);
assert_eq!(manager.subscribe_as("", Arc::new(|_| {})).remove(0).config, before_config);
assert!(harness.pending.try_recv().is_err());
manager.shutdown();
return;
@@ -498,7 +501,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
manager.set_config(&task.id, "model", "old".into()).await.unwrap();
set.reply.send(Ok(response(&["new", "old"], &["quick", "thorough"]))).unwrap();
switching.await.unwrap();
let task = manager.subscribe(Arc::new(|_| {})).remove(0);
let task = manager.subscribe_as("", Arc::new(|_| {})).remove(0);
assert_eq!(task.config.iter().find(|o| o.id == "model").unwrap().current.as_deref(), Some("old"));
assert_eq!(task.config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("low"));
assert!(harness.pending.try_recv().is_err());
@@ -529,7 +532,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
let effort = update.config.iter().find(|o| o.id == "effort").unwrap();
assert_eq!(effort.values.iter().map(|v| v.value.as_str()).collect::<Vec<_>>(), ["quick", "thorough"]);
}
let snapshot = |manager: &AgentManager| manager.subscribe(Arc::new(|_| {})).remove(0);
let snapshot = |manager: &AgentManager| manager.subscribe_as("", Arc::new(|_| {})).remove(0);
let current = snapshot(&manager);
assert_eq!(current.config.iter().find(|o| o.id == "model").unwrap().current.as_deref(), Some("new"));
assert_eq!(current.model.as_deref(), Some(if live { "new" } else { "old" }));
+103 -54
View File
@@ -38,7 +38,7 @@ pub use skill_installer::{
};
use conversation::{Conversation, SavedSubagent, Session};
use ide_core::{IdeError, IdeResult, IpcPath};
use ide_core::{IdeError, IdeResult, IpcPath, error::ErrorKind};
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
use ide_vcs::Repo;
use parking_lot::{Mutex, RwLock};
@@ -63,6 +63,9 @@ pub type NewTaskApprovalsHook = Arc<dyn Fn() -> ide_core::settings::NewTaskAppro
/// attached projects the user trusts.
pub type WorkspaceRootsHook = Arc<dyn Fn() -> Vec<PathBuf> + Send + Sync>;
/// Returns the project's git executable (`None`: the default), which the tasks' git runs.
pub type GitExecutableHook = Arc<dyn Fn() -> Option<PathBuf> + Send + Sync>;
/// Entry changes are batched for this long before they are sent.
const FLUSH_DELAY: Duration = Duration::from_millis(40);
/// Updates that arrive this late after `session/load` returns are still replayed history.
@@ -92,6 +95,8 @@ const MAX_EMBED: u64 = 256 * 1024;
const PROBE_TIMEOUT: Duration = Duration::from_secs(30);
/// How long deleting a task waits for its agent to exit before removing the worktree.
const EXIT_WAIT: Duration = Duration::from_secs(5);
/// Change lists can each open several Git pipes; leave room for interactive VCS operations.
const MAX_CHANGE_READS: usize = 4;
/// The agent tasks of one project.
pub struct AgentManager {
@@ -185,6 +190,8 @@ struct Shared {
security: RwLock<Option<SecurityHook>>,
new_task_approvals: RwLock<Option<NewTaskApprovalsHook>>,
workspace_roots: RwLock<Option<WorkspaceRootsHook>>,
git_executable: RwLock<Option<GitExecutableHook>>,
change_reads: Arc<tokio::sync::Semaphore>,
known: Arc<Mutex<HashMap<String, Known>>>,
providers: RwLock<Vec<provider::ProviderSpec>>,
/// Last probe of each provider.
@@ -599,6 +606,8 @@ impl AgentManager {
security: RwLock::new(None),
new_task_approvals: RwLock::new(None),
workspace_roots: RwLock::new(None),
git_executable: RwLock::new(None),
change_reads: Arc::new(tokio::sync::Semaphore::new(MAX_CHANGE_READS)),
known,
providers,
probes: Mutex::new(HashMap::new()),
@@ -638,12 +647,8 @@ impl AgentManager {
Self { shared, tasks: RwLock::new(tasks) }
}
/// Routes events to `sink` (replacing the previous subscriber); returns every task.
pub fn subscribe(&self, sink: AgentSink) -> Vec<AgentTask> {
self.subscribe_as("", sink)
}
/// Routes events to `sink` too, replacing only the sink `subscriber` (a view of the project) had.
/// Routes events to `sink`, replacing only the sink `subscriber` (a view of the project) had;
/// returns every task.
pub fn subscribe_as(&self, subscriber: &str, sink: AgentSink) -> Vec<AgentTask> {
self.shared.sinks.write().insert(subscriber.to_owned(), sink);
let mut tasks: Vec<AgentTask> = self.tasks.read().values().map(|t| t.state.lock().snapshot()).collect();
@@ -656,6 +661,15 @@ impl AgentManager {
self.shared.sinks.write().remove(subscriber);
}
pub fn has_live_work(&self) -> bool {
self.tasks.read().values().any(|task| {
let state = task.state.lock();
state.busy
|| !state.background_tasks.is_empty()
|| matches!(state.task.status, AgentStatus::Starting | AgentStatus::Running | AgentStatus::NeedsInput)
})
}
/// Sets the callback used to read the active command execution security policy.
pub fn set_security_hook(&self, hook: SecurityHook) {
*self.shared.security.write() = Some(hook);
@@ -671,6 +685,11 @@ impl AgentManager {
*self.shared.workspace_roots.write() = Some(hook);
}
/// Sets the callback that reads the project's git executable.
pub fn set_git_executable_hook(&self, hook: GitExecutableHook) {
*self.shared.git_executable.write() = Some(hook);
}
/// The agents (custom ones re-read), whether each is installed, and what they offered last time.
pub fn providers(&self) -> Vec<AgentProvider> {
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
@@ -983,14 +1002,15 @@ impl AgentManager {
}
let dir = self.shared.paths.worktrees_dir.clone();
let (t, b) = (title.clone(), req.base.clone());
let c = blocking(move || worktree::create(&root, &dir, &t, b.as_deref())).await?;
let c = vcs(&self.shared, move || worktree::create(&root, &dir, &t, b.as_deref())).await?;
(c.path, Some(c.branch), Some(c.base), Some(c.base_commit), BTreeMap::new())
}
Isolation::Local => {
let r = root.clone();
let (head, before) =
blocking(move || Ok((worktree::head_of(&r).ok(), worktree::snapshot(&r).unwrap_or_default())))
.await?;
let (head, before) = vcs(&self.shared, move || {
Ok((worktree::head_of(&r).ok(), worktree::snapshot(&r).unwrap_or_default()))
})
.await?;
let (base, commit) = head.unzip();
(root, None, base, commit, before)
}
@@ -1024,7 +1044,7 @@ impl AgentManager {
} else {
let name = format!("{id}.before");
let (dir, at, files) = (self.shared.paths.store_dir.join(&name), cwd.clone(), before.clone());
match blocking(move || worktree::save_before(&at, &files, &dir)).await {
match vcs(&self.shared, move || worktree::save_before(&at, &files, &dir)).await {
Ok(saved) => saved.then_some(name),
Err(e) => {
tracing::warn!("saving the changed files of agent task {id}: {e}");
@@ -1157,35 +1177,14 @@ impl AgentManager {
/// Drops a queued message.
pub fn unqueue(&self, id: &str, queued: &str) -> IdeResult<AgentQueued> {
let task = self.task(id)?;
let item = {
let mut s = task.state.lock();
let i =
s.task.queue.iter().position(|q| q.id == queued).ok_or_else(|| IdeError::not_found("already sent"))?;
s.task.queue.remove(i)
};
task.persist();
task.emit_task();
Ok(item)
self.task(id)?.take_queued(queued, false).map(|(item, _)| item)
}
/// Sends queued message `queued` now: into the running turn when the agent takes
/// messages mid-turn, else next, cancelling the current turn if there is one.
pub async fn send_queued_now(&self, id: &str, queued: &str) -> IdeResult<()> {
let task = self.task(id)?;
let (item, busy) = {
let mut s = task.state.lock();
let i =
s.task.queue.iter().position(|q| q.id == queued).ok_or_else(|| IdeError::not_found("already sent"))?;
let item = s.task.queue.remove(i);
let busy = s.busy;
if !busy {
s.busy = true;
}
(item, busy)
};
task.persist();
task.emit_task();
let (item, busy) = task.take_queued(queued, true)?;
if !busy {
self.shared.runtime.spawn(async move { task.run(item.prompt).await });
return Ok(());
@@ -1826,7 +1825,7 @@ impl AgentManager {
let _ = tokio::time::timeout(EXIT_WAIT, peer.exited()).await;
}
let worktrees = self.shared.paths.worktrees_dir.clone();
blocking(move || worktree::remove(&root, &worktrees, &cwd)).await?;
vcs(&self.shared, move || worktree::remove(&root, &worktrees, &cwd)).await?;
}
Ok(())
}
@@ -1836,7 +1835,7 @@ impl AgentManager {
let task = self.task(id)?;
let at = task.base();
let (before, touched) = task.attribution();
blocking(move || Ok(worktree::made_by_task(at.changes(&before)?, touched.as_deref()))).await
read_changes(&self.shared, move || at.changes(&before, touched.as_deref())).await
}
/// The task's uncommitted changes and, for a worktree task, the commits made since it
@@ -1845,7 +1844,7 @@ impl AgentManager {
let task = self.task(id)?;
let at = task.base();
let (before, touched) = task.attribution();
blocking(move || {
read_changes(&self.shared, move || {
let mut grouped = at.grouped_changes(&before)?;
grouped.uncommitted = worktree::made_by_task(grouped.uncommitted, touched.as_deref());
Ok(grouped)
@@ -1858,7 +1857,7 @@ impl AgentManager {
pub async fn turn_changes(&self, id: &str) -> IdeResult<Vec<AgentChange>> {
let (cwd, turn, dir) = self.task(id)?.last_turn();
let Some(turn) = turn else { return Ok(Vec::new()) };
blocking(move || {
read_changes(&self.shared, move || {
let changed = match &turn.changed {
Some(changed) => changed.clone(),
None => worktree::changed_in_turn(&cwd, &turn)?.1,
@@ -1875,10 +1874,10 @@ impl AgentManager {
if view == AgentChangesView::LastTurn {
let (cwd, turn, dir) = task.last_turn();
let Some(turn) = turn else { return Ok(None) };
return blocking(move || worktree::turn_text(&cwd, &path, &turn, &dir)).await;
return vcs(&self.shared, move || worktree::turn_text(&cwd, &path, &turn, &dir)).await;
}
let at = task.base();
blocking(move || {
vcs(&self.shared, move || {
let rev = match view {
AgentChangesView::Group => worktree::head_commit(at.cwd())?,
_ => at.rev()?,
@@ -1912,10 +1911,10 @@ impl AgentManager {
let s = task.state.lock();
(s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)), s.touched.clone())
};
let (restamped, restored) = blocking(move || {
let (restamped, restored) = vcs(&self.shared, move || {
let (changes, rev) = match view {
AgentChangesView::Group => (at.grouped_changes(&before)?.uncommitted, worktree::head_commit(at.cwd())?),
AgentChangesView::SinceStart | AgentChangesView::LastTurn => (at.changes(&before)?, at.rev()?),
AgentChangesView::SinceStart | AgentChangesView::LastTurn => (at.changes(&before, None)?, at.rev()?),
};
let changes = worktree::made_by_task(changes, touched.as_deref());
let sources = match rev.as_deref() {
@@ -1968,7 +1967,7 @@ impl AgentManager {
let s = task.state.lock();
(s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)))
};
let restamped = blocking(move || {
let restamped = vcs(&self.shared, move || {
let changed = match &turn.changed {
Some(changed) => changed.clone(),
None => worktree::changed_in_turn(&cwd, &turn)?.1,
@@ -2025,7 +2024,7 @@ impl AgentManager {
let Some(base) = base else {
return Err(IdeError::invalid("the task has no base revision to accept from"));
};
blocking(move || {
vcs(&self.shared, move || {
let wanted: Vec<AgentChange> = worktree::without_untouched(worktree::changes(&cwd, &base)?, &before)
.into_iter()
.filter(|c| rel_paths.as_ref().is_none_or(|p| p.contains(&c.rel_path)))
@@ -2280,7 +2279,7 @@ impl Task {
/// Records the checkout as a turn starts: what the turn's changes are compared with.
async fn checkout_before_turn(&self) {
let (cwd, previous, dir) = self.last_turn();
let turn = match blocking(move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await {
let turn = match vcs(&self.shared, move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await {
Ok(turn) => Some(Arc::new(turn)),
Err(e) => {
tracing::warn!("recording the checkout as a turn of agent task {} starts: {e}", self.id);
@@ -2297,7 +2296,9 @@ impl Task {
let (cwd, turn, _) = self.last_turn();
let Some(turn) = turn else { return };
let start = turn.clone();
let Ok((in_worktree, all)) = blocking(move || worktree::changed_in_turn(&cwd, &start)).await else { return };
let Ok((in_worktree, all)) = vcs(&self.shared, move || worktree::changed_in_turn(&cwd, &start)).await else {
return;
};
{
let mut s = self.state.lock();
if !in_worktree.is_empty()
@@ -2328,6 +2329,23 @@ impl Task {
self.shared.emit(AgentEvent::Task { task: Box::new(task) });
}
/// Takes the item and, for Send now, claims an idle turn under the same lock.
fn take_queued(&self, id: &str, for_send: bool) -> IdeResult<(AgentQueued, bool)> {
let mut s = self.state.lock();
let Some(index) = s.task.queue.iter().position(|item| item.id == id) else {
drop(s);
self.emit_task();
return Err(IdeError::new(ErrorKind::OutOfSync, "Message is no longer queued"));
};
let item = s.task.queue.remove(index);
let was_busy = s.busy;
s.busy |= for_send;
drop(s);
self.persist();
self.emit_task();
Ok((item, was_busy))
}
/// Shows (or clears) the agent's pending retry; emitted only when it changes.
fn set_retry(&self, retry: Option<AgentRetry>) {
{
@@ -2505,6 +2523,8 @@ impl Task {
/// the user stops one. The caller set `busy`.
async fn run(self: Arc<Self>, mut prompt: AgentPrompt) {
loop {
// The message shows before the checkout is recorded, which can take a while in a large repository.
self.show_prompt(&prompt);
self.checkout_before_turn().await;
let result = self.turn(&prompt).await;
self.cancel_pending.store(false, Ordering::Release);
@@ -2536,7 +2556,10 @@ impl Task {
self.push_entry(AgentEntry::Error { message: "The agent declined to continue.".into() });
}
match (next, result) {
(Some(queued), _) => prompt = queued.prompt,
(Some(queued), _) => {
self.emit_task();
prompt = queued.prompt;
}
(None, Ok(stop)) => {
self.set_status(AgentStatus::Ready, None);
if stop != "cancelled" {
@@ -2815,11 +2838,8 @@ impl Task {
Ok(())
}
/// Sends one prompt, starting the agent first if needed; returns the stop reason.
async fn turn(self: &Arc<Self>, prompt: &AgentPrompt) -> Result<String, Failure> {
self.turns.fetch_add(1, Ordering::AcqRel);
self.turn_started.store(false, Ordering::Release);
self.state.lock().task.resets_ms = None;
/// Adds the user's message to the conversation and shows the task starting.
fn show_prompt(self: &Arc<Self>, prompt: &AgentPrompt) {
let attachments = prompt
.files
.iter()
@@ -2837,6 +2857,13 @@ impl Task {
// Launching the agent can take a while (`npx` fetches its adapter on first use).
let starting = self.live.lock().as_ref().is_none_or(|l| l.peer.is_closed());
self.set_status(if starting { AgentStatus::Starting } else { AgentStatus::Running }, None);
}
/// Sends one prompt, starting the agent first if needed; returns the stop reason.
async fn turn(self: &Arc<Self>, prompt: &AgentPrompt) -> Result<String, Failure> {
self.turns.fetch_add(1, Ordering::AcqRel);
self.turn_started.store(false, Ordering::Release);
self.state.lock().task.resets_ms = None;
let mut live = self.ensure_session().await.map_err(Failure::from)?;
// Stopped while the agent started: the prompt is never sent.
if self.cancel_pending.load(Ordering::Acquire) {
@@ -4218,8 +4245,11 @@ fn file_uri(path: &Path) -> String {
out
}
/// The title of a task: the first line of the prompt that says something. A pasted Markdown
/// block opens with a code fence (```` ```text ````), which names no task.
fn title_of(prompt: &AgentPrompt) -> String {
let line = prompt.text.lines().map(str::trim).find(|l| !l.is_empty());
let is_fence = |l: &str| l.starts_with("```") || l.starts_with("~~~");
let line = prompt.text.lines().map(str::trim).find(|l| !l.is_empty() && !is_fence(l));
let line = match line {
Some(l) => l.to_owned(),
None => prompt.files.first().map(|f| file_name(&f.0)).unwrap_or_else(|| "Image".into()),
@@ -4251,6 +4281,25 @@ async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + '
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
/// [`blocking`] for work that runs git: the repositories it opens run the project's git.
async fn vcs<T: Send + 'static>(shared: &Shared, f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
let git = shared.git_executable.read().as_ref().and_then(|hook| hook());
blocking(move || ide_vcs::with_git_executable(git.as_deref(), f)).await
}
async fn read_changes<T: Send + 'static>(
shared: &Shared,
f: impl FnOnce() -> IdeResult<T> + Send + 'static,
) -> IdeResult<T> {
let permit = shared.change_reads.clone().acquire_owned().await.map_err(|e| IdeError::internal(e.to_string()))?;
vcs(shared, move || {
// Dropping the caller doesn't cancel a blocking job. Keep the slot with the work.
let _permit = permit;
f()
})
.await
}
#[cfg(test)]
mod replay;
#[cfg(test)]
+1 -98
View File
@@ -941,107 +941,10 @@ fn normalize_agents_list(agents: Vec<String>) -> Vec<String> {
out
}
/// Strips `//` line comments, `/* ... */` block comments, and trailing commas before `}` or `]`
/// outside JSON string literals so JSONC config files parse cleanly with `serde_json`.
pub(crate) fn strip_jsonc(input: &str) -> String {
let bytes = input.as_bytes();
let mut out = String::with_capacity(input.len());
let mut i = 0;
let mut in_str = false;
while i < bytes.len() {
if in_str {
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
if ch == '\\' && i < bytes.len() {
let next = input[i..].chars().next().unwrap();
out.push(next);
i += next.len_utf8();
} else if ch == '"' {
in_str = false;
}
continue;
}
if bytes[i] == b'"' {
in_str = true;
out.push('"');
i += 1;
continue;
}
if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'/' {
i += 2;
while i < bytes.len() && bytes[i] != b'\n' {
i += 1;
}
continue;
}
if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'*' {
i += 2;
while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
if bytes[i] == b'\n' {
out.push('\n');
i += 1;
} else {
let ch = input[i..].chars().next().unwrap();
i += ch.len_utf8();
}
}
i = (i + 2).min(bytes.len());
continue;
}
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
}
remove_trailing_commas(&out)
}
fn remove_trailing_commas(input: &str) -> String {
let bytes = input.as_bytes();
let mut out = String::with_capacity(input.len());
let mut i = 0;
let mut in_str = false;
while i < bytes.len() {
if in_str {
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
if ch == '\\' && i < bytes.len() {
let next = input[i..].chars().next().unwrap();
out.push(next);
i += next.len_utf8();
} else if ch == '"' {
in_str = false;
}
continue;
}
if bytes[i] == b'"' {
in_str = true;
out.push('"');
i += 1;
continue;
}
if bytes[i] == b',' {
let mut j = i + 1;
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
j += 1;
}
if j < bytes.len() && (bytes[j] == b'}' || bytes[j] == b']') {
i += 1;
continue;
}
}
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
}
out
}
fn parse_jsonc_value(raw: &str) -> Result<Value, String> {
let trimmed = raw.trim().trim_start_matches('\u{feff}');
serde_json::from_str::<Value>(trimmed)
.or_else(|_| serde_json::from_str::<Value>(&strip_jsonc(trimmed)))
.or_else(|_| serde_json::from_str::<Value>(&ide_core::jsonc::strip(trimmed)))
.map_err(|e| format!("Invalid JSON: {e}"))
}
+4 -1
View File
@@ -536,6 +536,9 @@ pub enum AgentEntry {
kind: String,
status: AgentToolStatus,
locations: Vec<IpcPath>,
/// Images returned by the tool, kept separately from its truncated text.
#[serde(default)]
images: Vec<AgentImage>,
/// Text the tool reported (command output…), truncated.
output: Option<String>,
diffs: Vec<AgentToolDiff>,
@@ -766,7 +769,7 @@ pub struct AgentModelCatalog {
pub error: Option<String>,
}
/// Streamed to the window that subscribed (`AgentManager::subscribe`).
/// Streamed to the window that subscribed (`AgentManager::subscribe_as`).
#[derive(Clone, Debug, Serialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum AgentEvent {
+30
View File
@@ -1007,11 +1007,16 @@ impl Session {
let mut updates = Vec::new();
let mut finished = None;
let mut read_title = false;
let mut refresh_usage = false;
{
let mut st = self.st.lock();
let st = &mut *st;
match kind {
"system" => match msg.get("subtype").and_then(Value::as_str) {
Some("compact_boundary") => {
refresh_usage = msg.pointer("/compact_metadata/post_tokens").is_none_or(Value::is_null);
updates.extend(st.tr.on_message(&msg));
}
Some("init") => {
st.terminal_only = strings(msg.get("terminal_slash_commands"));
}
@@ -1115,6 +1120,31 @@ impl Session {
if read_title {
self.read_title();
}
if refresh_usage {
self.refresh_usage();
}
}
/// Sends what the context holds after a compaction that didn't report it, as Claude Code
/// counts it (`get_context_usage`); until then the meter would show the count from before.
fn refresh_usage(self: &Arc<Self>) {
let me = self.clone();
tokio::spawn(async move {
let Some(proc) = me.st.lock().proc.clone() else { return };
let usage = match proc.control(json!({ "subtype": "get_context_usage" })).await {
Ok(usage) => usage,
Err(e) => {
tracing::debug!("reading claude context usage after compaction: {e}");
return;
}
};
let n = |k: &str| usage.get(k).and_then(Value::as_u64);
let (Some(used), Some(size)) = (n("totalTokens"), n("maxTokens").filter(|m| *m > 0)) else { return };
let update = me.st.lock().tr.on_context_usage(used, size);
if let Some(shim) = me.shim() {
shim.notify(vec![update]);
}
});
}
/// Sends the session's title once it has one: the one in its transcript, or else one
@@ -531,6 +531,38 @@ async fn sessions_without_a_title_get_one_generated() {
assert_eq!(request["request"]["persist"], true);
}
/// A compaction that doesn't report what the context holds now (no `post_tokens`): the
/// driver asks Claude Code, and the meter shows that instead of the count from before.
#[tokio::test(flavor = "multi_thread")]
async fn a_compaction_without_its_token_count_reads_the_context_usage() {
let mut processes = load_fixture("simple");
processes[0].extend([
Frame::Cli(json!({"type": "system", "subtype": "compact_boundary",
"compact_metadata": {"trigger": "manual", "pre_tokens": 120000}})),
Frame::Shim(json!({"type": "control_request", "request_id": "req_3",
"request": {"subtype": "get_context_usage"}})),
Frame::Cli(json!({"type": "control_response", "response": {"subtype": "success", "request_id": "req_3",
"response": {"categories": [], "totalTokens": 4200, "maxTokens": 200000, "model": "claude"}}})),
]);
let cli = replay_cli(processes);
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
let h =
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
let session = h.new_session().await;
h.prompt(&session, "Reply with exactly: hello there").await.unwrap();
let mut usage = Vec::new();
for _ in 0..100 {
usage = h.updates(&session, "usage_update");
if usage.last().is_some_and(|u| u["used"] == 4200) {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert!(cli.errors.lock().is_empty(), "{:?}", cli.errors.lock());
assert_eq!(usage.last().map(|u| (u["used"].clone(), u["size"].clone())), Some((json!(4200), json!(200000))));
}
#[tokio::test(flavor = "multi_thread")]
async fn replay_multi_turn() {
let r = replay("multi_turn").await;
@@ -1098,6 +1130,24 @@ fn streamed_text_is_not_sent_twice() {
assert_eq!(usage[0].update, json!({"sessionUpdate": "usage_update", "used": 15, "size": 1000}));
}
#[test]
fn a_compaction_replaces_the_context_usage() {
let mut t = Translator::new("s", PathBuf::from("/w"), true);
let assistant = json!({"type": "assistant", "parent_tool_use_id": null,
"message": {"id": "m1", "model": "x", "content": [], "usage": {"input_tokens": 900, "output_tokens": 50}}});
t.on_message(&assistant);
let result = json!({"modelUsage": {"x": {"contextWindow": 1000}}});
assert_eq!(t.on_result(&result)[0].update["used"], 950);
let boundary = |meta: Value| json!({"type": "system", "subtype": "compact_boundary", "compact_metadata": meta});
let out = t.on_message(&boundary(json!({"trigger": "manual", "pre_tokens": 950, "post_tokens": 120})));
assert_eq!(out[0].update, json!({"sessionUpdate": "usage_update", "used": 120, "size": 1000}));
// The `/compact` turn's result reports what compaction left, not the count from before.
assert_eq!(t.on_result(&result)[0].update["used"], 120);
// Without `post_tokens` nothing is known yet (the driver asks): the stale count stays out.
assert!(t.on_message(&boundary(json!({"trigger": "auto", "pre_tokens": 950}))).is_empty());
assert!(t.on_result(&result).is_empty());
}
#[test]
fn rate_limits_and_cost() {
let mut t = Translator::new("s", PathBuf::from("/w"), false);
@@ -144,6 +144,22 @@ pub(super) fn result_fields(name: &str, input: &Value, block: &Value, structured
content.push(text(&t));
}
}
if let Some(blocks) = block.get("content").and_then(Value::as_array) {
for block in blocks {
if block.get("type").and_then(Value::as_str) != Some("image") {
continue;
}
let Some(source) = block.get("source") else { continue };
if source.get("type").and_then(Value::as_str) != Some("base64") {
continue;
}
let data = source.get("data").and_then(Value::as_str).unwrap_or_default();
let mime = source.get("media_type").and_then(Value::as_str).unwrap_or_default();
if !data.is_empty() && mime.starts_with("image/") {
content.push(json!({"type": "content", "content": {"type": "image", "mimeType": mime, "data": data}}));
}
}
}
let mut out = json!({ "status": if failed { "failed" } else { "completed" } });
if !content.is_empty() {
out["content"] = Value::Array(content);
@@ -230,6 +246,43 @@ mod tests {
assert_eq!(call_fields("WebSearch", &json!({"query": "q"}), cwd)["kind"], "fetch");
}
#[test]
fn image_tool_results_keep_text_and_inline_images() {
let result = result_fields(
"Read",
&json!({"file_path": "/w/preview.png"}),
&json!({"content": [
{"type": "text", "text": "Preview ready"},
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
]}),
None,
);
assert_eq!(result["status"], "completed");
assert_eq!(
result["content"],
json!([
text("Preview ready"),
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": "aW1hZ2U="}}
])
);
}
#[test]
fn failed_shell_tool_images_keep_fallback_error_text() {
let result = result_fields(
"Bash",
&json!({}),
&json!({"is_error": true, "content": [
{"type": "text", "text": "Preview command failed"},
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
]}),
Some(&json!({"stdout": "", "stderr": ""})),
);
assert_eq!(result["status"], "failed");
assert_eq!(result["content"][0], text("Preview command failed"));
assert_eq!(result["content"][1]["content"]["type"], "image");
}
#[test]
fn results() {
let input = json!({"file_path": "/w/n.txt", "content": "two"});
@@ -458,6 +458,13 @@ impl Translator {
let last = self.children.get(&tool_use).map(|c| c.last_text.clone()).filter(|t| !t.is_empty());
self.finish_child(&tool_use, stop, last.or(summary))
}
// Compaction replaced the conversation with its summary: the context now holds
// `post_tokens`. Without it the stale count must not come back with the result;
// the driver asks Claude Code instead (`Session::refresh_usage`).
Some("compact_boundary") => {
self.used = msg.pointer("/compact_metadata/post_tokens").and_then(Value::as_u64);
self.usage_update().into_iter().collect()
}
// A turn's background tasks (`run_in_background`) outlive it: the task keeps
// the list and stays up while it isn't empty (see `Task::release_when_idle`).
Some("background_tasks_changed") => {
@@ -561,6 +568,16 @@ impl Translator {
self.usage_update().into_iter().collect()
}
/// The context usage Claude Code reports (`get_context_usage`), as a usage update.
pub fn on_context_usage(&mut self, used: u64, size: u64) -> Update {
self.used = Some(used);
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
if let Some(amount) = self.cost_usd {
update["cost"] = json!({ "amount": amount, "currency": "USD" });
}
Update { session: self.root.clone(), update }
}
fn usage_update(&self) -> Option<Update> {
let used = self.used?;
let size = self
+1 -1
View File
@@ -406,7 +406,7 @@ fn copilot_installed_plugin_roots(copilot_dir: &Path) -> Vec<(PathBuf, AgentSkil
};
if let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json"))
&& let Ok(root) = serde_json::from_str::<serde_json::Value>(&crate::mcp::strip_jsonc(&text))
&& let Ok(root) = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text))
&& let Some(installed) = root.get("installedPlugins").and_then(serde_json::Value::as_array)
{
for entry in installed {
+114 -15
View File
@@ -452,6 +452,57 @@ fn manager(dir: &Path, agent: Arc<FakeAgent>) -> AgentManager {
manager_at(dir, &dir.join("models.json"), agent)
}
#[tokio::test]
async fn change_reads_share_a_budget_until_the_blocking_work_finishes() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::default());
let submitted = Arc::new(AtomicU32::new(0));
mgr.set_git_executable_hook(Arc::new({
let submitted = submitted.clone();
move || {
submitted.fetch_add(1, Ordering::SeqCst);
None
}
}));
let (started, mut starts) = tokio::sync::mpsc::unbounded_channel();
let (finished, mut finishes) = tokio::sync::mpsc::unbounded_channel();
let mut releases = Vec::new();
let mut reads = Vec::new();
for job in 0..12 {
let (release, gate) = tokio::sync::oneshot::channel::<()>();
releases.push(release);
let (started, finished) = (started.clone(), finished.clone());
let mut read = Box::pin(read_changes(&mgr.shared, move || {
started.send(()).unwrap();
gate.blocking_recv().unwrap();
finished.send(()).unwrap();
Ok(())
}));
tokio::select! { biased; _ = &mut read => panic!("read finished before release"), _ = std::future::ready(()) => {} }
reads.push(read);
if job == 0 {
// Cancelling the requester cannot stop the blocking job or free its slot.
starts.recv().await.unwrap();
drop(reads.pop());
}
}
let admitted = submitted.load(Ordering::SeqCst);
for _ in 1..admitted {
starts.recv().await.unwrap();
}
for release in releases {
release.send(()).unwrap();
}
for read in reads {
read.await.unwrap();
}
for _ in 0..12 {
finishes.recv().await.unwrap();
}
eprintln!("change-read fixture: peak active {admitted}; completed 12/12");
assert_eq!(admitted, 4);
}
#[tokio::test]
async fn subscribers_do_not_replace_or_close_each_other() {
let tmp = tempfile::tempdir().unwrap();
@@ -1102,7 +1153,7 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
let mgr = manager(tmp.path(), agent.clone());
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
let sink = events.clone();
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
mgr.subscribe_as("", Arc::new(move |e| sink.lock().push(e)));
let task = mgr
.create(NewAgentTask {
@@ -1375,6 +1426,49 @@ async fn steers_through_session_steering() {
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn stale_queue_actions_refresh_the_queue_without_starting_another_turn() {
use ide_core::error::ErrorKind;
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { provider: "claude".into(), prompt: text("ask"), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.prompt(&task.id, text("again"), false).await.unwrap();
let handle = mgr.task(&task.id).unwrap();
let queued = handle.state.lock().task.queue[0].id.clone();
let permission = *handle.permissions.lock().keys().next().unwrap();
let (tx, mut updates) = tokio::sync::mpsc::unbounded_channel();
let weak = Arc::downgrade(&handle);
mgr.subscribe_as(
"",
Arc::new(move |event| {
if let AgentEvent::Task { task } = event
&& task.queue.is_empty()
&& let Some(handle) = weak.upgrade()
{
let _ = tx.send(handle.turns.load(Ordering::Acquire));
}
}),
);
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(updates.try_recv().unwrap(), 1, "publish the dequeue before starting the second turn");
while updates.try_recv().is_ok() {}
for error in
[mgr.unqueue(&task.id, &queued).unwrap_err(), mgr.send_queued_now(&task.id, &queued).await.unwrap_err()]
{
assert_eq!(error.kind, ErrorKind::OutOfSync);
assert_eq!(updates.try_recv().unwrap(), 2, "a stale action gets the current queue");
}
assert!(!handle.state.lock().busy);
assert_eq!(mgr.unqueue("missing-task", &queued).unwrap_err().kind, ErrorKind::NotFound);
}
#[tokio::test(flavor = "multi_thread")]
async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
let tmp = tempfile::tempdir().unwrap();
@@ -1640,6 +1734,8 @@ fn prompts_become_acp_content_blocks() {
assert_eq!(old["entries"][0]["attachments"], json!([]));
assert!(old["entries"][1].get("attachments").is_none());
assert_eq!(title_of(&AgentPrompt { files: p.files.clone(), ..AgentPrompt::default() }), "my file.rs");
let pasted = AgentPrompt { text: "```text\n\n ## Fix the tab title\n```".into(), ..AgentPrompt::default() };
assert_eq!(title_of(&pasted), "## Fix the tab title");
assert!(clean(text(" ")).is_none());
}
@@ -2947,7 +3043,7 @@ async fn reload_providers_updates_registry_install_clears_stale_probes_and_notif
let events = Arc::new(Mutex::new(Vec::new()));
let events_sink = events.clone();
mgr.subscribe(Arc::new(move |ev| events_sink.lock().push(ev)));
mgr.subscribe_as("", Arc::new(move |ev| events_sink.lock().push(ev)));
let toml = format!(
"name = \"GitHub Copilot\"\ncommand = {:?}\nargs = [\"--acp\", \"--stdio\"]\n",
@@ -3366,14 +3462,17 @@ async fn config_choice_shows_before_the_agent_answers() {
let mgr = manager(tempfile::tempdir().unwrap().path(), agent.clone());
let shown: Arc<Mutex<Option<std::time::Instant>>> = Arc::default();
let mark = shown.clone();
mgr.subscribe(Arc::new(move |e| {
if let AgentEvent::Task { task } = e
&& task.config.iter().any(|o| o.id == "fast" && o.current.as_deref() == Some("false"))
&& mark.lock().is_none()
{
*mark.lock() = Some(std::time::Instant::now());
}
}));
mgr.subscribe_as(
"",
Arc::new(move |e| {
if let AgentEvent::Task { task } = e
&& task.config.iter().any(|o| o.id == "fast" && o.current.as_deref() == Some("false"))
&& mark.lock().is_none()
{
*mark.lock() = Some(std::time::Instant::now());
}
}),
);
let task = mgr
.create(NewAgentTask {
project_root: None,
@@ -4217,7 +4316,7 @@ async fn attention_finished_not_cancelled() {
let mgr = manager(tmp.path(), agent.clone());
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
let sink = events.clone();
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
mgr.subscribe_as("", Arc::new(move |e| sink.lock().push(e)));
let done = mgr
.create(NewAgentTask {
@@ -4271,7 +4370,7 @@ async fn attention_failed() {
let mgr = manager(tmp.path(), agent);
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
let sink = events.clone();
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
mgr.subscribe_as("", Arc::new(move |e| sink.lock().push(e)));
let task = mgr
.create(NewAgentTask {
project_root: None,
@@ -4296,7 +4395,7 @@ async fn attention_input_not_auto_bypass() {
let mgr = manager(tmp.path(), agent);
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
let sink = events.clone();
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
mgr.subscribe_as("", Arc::new(move |e| sink.lock().push(e)));
let asked = mgr
.create(NewAgentTask {
@@ -4361,7 +4460,7 @@ async fn attention_not_emitted_on_restore() {
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
let sink = events.clone();
let tasks = restored.subscribe(Arc::new(move |e| sink.lock().push(e)));
let tasks = restored.subscribe_as("", Arc::new(move |e| sink.lock().push(e)));
assert!(tasks.iter().any(|t| t.id == task.id));
tokio::time::sleep(Duration::from_millis(50)).await;
assert!(attention_reasons(&events.lock()).is_empty(), "snapshot restore must not re-notify: {:?}", *events.lock());
@@ -4514,7 +4613,7 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl
// Persisted task file preserves `skill_overrides` across restart.
let restored_mgr = manager(root, Arc::new(FakeAgent::default()));
let restored = restored_mgr.subscribe(Arc::new(|_| {})).into_iter().find(|t| t.id == task.id).unwrap();
let restored = restored_mgr.subscribe_as("", Arc::new(|_| {})).into_iter().find(|t| t.id == task.id).unwrap();
assert_eq!(restored.skill_overrides.get("tdd"), Some(&AgentSkillMode::Off));
assert_eq!(restored.skill_overrides.get("noisy"), Some(&AgentSkillMode::Auto));
restored_mgr.shutdown();
+42 -3
View File
@@ -1,6 +1,6 @@
//! Folds ACP `session/update` notifications into a task's entries.
use crate::model::{AgentEntry, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
use crate::model::{AgentEntry, AgentImage, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
use ide_core::IpcPath;
use serde_json::Value;
use std::collections::HashMap;
@@ -84,6 +84,7 @@ impl Timeline {
status: tool_status(update.get("status")).unwrap_or(AgentToolStatus::Pending),
locations: locations(update.get("locations")),
output: None,
images: Vec::new(),
diffs: Vec::new(),
started_ms: Some(crate::now_ms()),
ended_ms: None,
@@ -150,7 +151,7 @@ impl Timeline {
}
fn merge_tool(&mut self, index: usize, update: &Value) {
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, ended_ms, .. } =
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
&mut self.entries[index]
else {
return;
@@ -173,10 +174,20 @@ impl Timeline {
let Some(content) = update.get("content").and_then(Value::as_array) else { return };
let mut text = String::new();
let mut new_diffs = Vec::new();
let mut new_images = Vec::new();
for item in content {
match item.get("type").and_then(Value::as_str) {
Some("content") => {
if let Some(t) = content_text(item.get("content")) {
let content = item.get("content");
if let Some(image) = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image"))
&& let (Some(data), Some(mime)) =
(image.get("data").and_then(Value::as_str), image.get("mimeType").and_then(Value::as_str))
&& !data.is_empty()
&& mime.starts_with("image/")
{
new_images.push(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
}
if let Some(t) = content_text(content) {
if !text.is_empty() {
text.push('\n');
}
@@ -203,6 +214,9 @@ impl Timeline {
if !new_diffs.is_empty() {
*diffs = new_diffs;
}
if !new_images.is_empty() {
*images = new_images;
}
}
/// Adds or updates the card of subagent `id` from its `subagent_update`; returns the
@@ -439,6 +453,31 @@ mod tests {
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
}
#[test]
fn tool_images_survive_updates_text_truncation_and_serialization() {
use base64::Engine;
let mut t = Timeline::default();
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "preview", "title": "Render", "kind": "execute"}));
let mut old = serde_json::to_value(&t.entries[0]).unwrap();
old.as_object_mut().unwrap().remove("images");
let legacy: AgentEntry = serde_json::from_value(old).unwrap();
assert!(matches!(legacy, AgentEntry::Tool { images, .. } if images.is_empty()));
let data = base64::engine::general_purpose::STANDARD.encode(vec![0; MAX_OUTPUT]);
let update = json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "content": [
{"type": "content", "content": {"type": "text", "text": "x".repeat(MAX_OUTPUT + 100)}},
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": data}}
]});
t.apply(&update);
t.apply(&update);
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "status": "completed"}));
let AgentEntry::Tool { images, output, status, .. } = &t.entries[0] else { panic!() };
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None }]);
assert!(output.as_ref().unwrap().len() < MAX_OUTPUT + 100);
assert_eq!(*status, AgentToolStatus::Completed);
let saved = serde_json::to_string(&t.entries[0]).unwrap();
assert_eq!(serde_json::from_str::<AgentEntry>(&saved).unwrap(), t.entries[0]);
}
#[test]
fn chunks_merge_into_one_message_until_another_entry_comes() {
let mut t = Timeline::default();
+103 -11
View File
@@ -65,7 +65,7 @@ impl TurnRepos {
/// The innermost repository holding `path`.
fn owner(&self, path: &Path) -> Option<&Repo> {
self.repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().as_os_str().len())
owning_repo(&self.repos, path)
}
/// `repo`'s `HEAD` as the turn `start` began.
@@ -78,6 +78,10 @@ fn root_key(root: &Path) -> String {
root.to_string_lossy().into_owned()
}
fn owning_repo<'a>(repos: &'a [Repo], path: &Path) -> Option<&'a Repo> {
repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().as_os_str().len())
}
/// `path` as a task in `base` names it, if it is not in a repository nested below `repo` (that
/// one lists it itself; to `repo` its folder is untracked).
fn nested_rel(base: &Path, repo: &Repo, roots: &[PathBuf], path: &Path) -> Option<String> {
@@ -91,11 +95,25 @@ fn nested_rel(base: &Path, repo: &Repo, roots: &[PathBuf], path: &Path) -> Optio
}
/// The uncommitted changes in every repository of the project, against each one's `HEAD`.
fn nested_changes(cwd: &Path) -> IdeResult<Vec<AgentChange>> {
let Some((base, repos)) = nested_repos(cwd)? else { return Ok(Vec::new()) };
fn nested_changes(base: &Path, repos: &[Repo], touched: Option<&BTreeSet<String>>) -> IdeResult<Vec<AgentChange>> {
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
// Match deletions too: find the owner by path components, not by opening the file.
// Display paths use slash separators and lossy Unicode (see nested_rel). If a checkout's
// name cannot round-trip from that representation, keep the full-read fallback.
let owners = touched
.filter(|_| {
roots.iter().all(|root| {
root.strip_prefix(base).is_ok_and(|rel| base.join(rel.to_string_lossy().replace('\\', "/")) == *root)
})
})
.map(|paths| {
paths.iter().filter_map(|rel| owning_repo(repos, &base.join(rel)).map(Repo::root)).collect::<BTreeSet<_>>()
});
let mut out: Vec<AgentChange> = Vec::new();
for repo in &repos {
for repo in repos {
if owners.as_ref().is_some_and(|owners| !owners.contains(repo.root())) {
continue;
}
let listed = match repo.head()?.1 {
Some(head) => changes(repo.root(), &head)?,
None => {
@@ -103,7 +121,7 @@ fn nested_changes(cwd: &Path) -> IdeResult<Vec<AgentChange>> {
}
};
for mut c in listed {
let Some(rel) = nested_rel(&base, repo, &roots, &c.path.0) else { continue };
let Some(rel) = nested_rel(base, repo, &roots, &c.path.0) else { continue };
if out.iter().any(|o| o.path == c.path) {
continue;
}
@@ -364,13 +382,30 @@ impl TaskBase {
}
/// The files the task changed, less those changed before it started and untouched since.
pub(crate) fn changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<Vec<AgentChange>> {
pub(crate) fn changes(
&self,
before: &BTreeMap<String, Stamp>,
touched: Option<&BTreeSet<String>>,
) -> IdeResult<Vec<AgentChange>> {
if touched.is_some_and(BTreeSet::is_empty) {
return Ok(Vec::new());
}
Ok(made_by_task(self.read_changes(before, touched)?, touched))
}
fn read_changes(
&self,
before: &BTreeMap<String, Stamp>,
touched: Option<&BTreeSet<String>>,
) -> IdeResult<Vec<AgentChange>> {
let (cwd, start) = match self {
Self::Worktree { cwd, base } => return Ok(without_untouched(changes(cwd, base)?, before)),
Self::Local { cwd, .. } if spans_repos(cwd) => {
return Ok(without_untouched(nested_changes(cwd)?, before));
Self::Local { cwd, start } => {
if let Some((base, repos)) = nested_repos(cwd)? {
return Ok(without_untouched(nested_changes(&base, &repos, touched)?, before));
}
(cwd, start.as_deref())
}
Self::Local { cwd, start } => (cwd, start.as_deref()),
};
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
// What is uncommitted, as the Commit tool window lists it: commits made since the task
@@ -429,7 +464,7 @@ impl TaskBase {
pub(crate) fn grouped_changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<AgentChanges> {
let cwd = self.cwd();
if spans_repos(cwd) {
return Ok(AgentChanges { uncommitted: self.changes(before)?, commits: Vec::new() });
return Ok(AgentChanges { uncommitted: self.changes(before, None)?, commits: Vec::new() });
}
let Some(repo) = discover(cwd)? else { return Ok(AgentChanges::default()) };
let head = repo.head()?.1;
@@ -1122,6 +1157,57 @@ mod tests {
assert!(ok, "git {args:?}");
}
#[cfg(unix)]
#[test]
fn attributed_changes_only_diff_the_owning_checkout() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
for n in 0..15 {
let repo = root.join(format!("repo{n:02}"));
std::fs::create_dir_all(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
git(&repo, &["add", "a.txt"]);
git(&repo, &["commit", "-q", "-m", "initial"]);
std::fs::write(repo.join("a.txt"), "two\n").unwrap();
}
// Count real Git diff processes, not walks to discover the topology.
let git = tmp.path().join("count-git");
let log = tmp.path().join("count-git.log");
std::fs::write(
&git,
"#!/bin/sh\nfor arg do\nif [ \"$arg\" = diff ]; then pwd >> \"$0.log\"; break; fi\ndone\nexec git \"$@\"\n",
)
.unwrap();
std::fs::set_permissions(&git, std::fs::Permissions::from_mode(0o700)).unwrap();
let at = TaskBase::Local { cwd: root, start: None };
let before = BTreeMap::new();
let one = BTreeSet::from(["repo07/a.txt".to_owned()]);
let read = |touched: Option<&BTreeSet<String>>| {
std::fs::write(&log, "").unwrap();
let start = std::time::Instant::now();
let changes = ide_vcs::with_git_executable(Some(&git), || at.changes(&before, touched).unwrap());
let elapsed = start.elapsed();
let calls = std::fs::read_to_string(&log).unwrap();
eprintln!("change read: touched={:?} elapsed={elapsed:?}", touched.map(BTreeSet::len));
(changes, calls.lines().count())
};
let (all, full_calls) = read(None);
let (selected, selected_calls) = read(Some(&one));
let (empty, empty_calls) = read(Some(&BTreeSet::new()));
assert_eq!(all.len(), 15);
assert_eq!(
serde_json::to_value(selected).unwrap(),
serde_json::to_value(made_by_task(all, Some(&one))).unwrap()
);
assert!(empty.is_empty());
eprintln!("git diff children: full {full_calls}, one touched {selected_calls}, none touched {empty_calls}");
assert!(selected_calls > 0);
assert_eq!(selected_calls * 15, full_calls);
assert_eq!(empty_calls, 0);
}
#[test]
fn a_project_with_nested_repositories_sees_changes_in_each_one() {
let tmp = tempfile::tempdir().unwrap();
@@ -1144,7 +1230,7 @@ mod tests {
std::fs::write(nested.join("b.txt"), "new\n").unwrap();
std::fs::write(deeper.join("a.txt"), "two\n").unwrap();
let at = TaskBase::Local { cwd: root.clone(), start: None };
let changed = at.changes(&before).unwrap();
let changed = at.changes(&before, None).unwrap();
let listed: Vec<(&str, &Path)> =
changed.iter().map(|c| (c.rel_path.as_str(), c.repo.as_ref().unwrap().0.as_path())).collect();
assert_eq!(
@@ -1168,6 +1254,12 @@ mod tests {
}
assert!(!nested.join("b.txt").exists());
assert!(root.join("mine.txt").exists(), "the user's own change stays");
// A deleted file cannot be canonicalized, but still belongs to its innermost repo.
std::fs::remove_file(deeper.join("a.txt")).unwrap();
let removed = at.changes(&before, Some(&BTreeSet::from(["libs/validation/pkg/sdk/a.txt".into()]))).unwrap();
assert_eq!(removed.len(), 1);
assert_eq!(removed[0].repo.as_ref().unwrap().0, deeper);
assert_eq!(removed[0].kind, ChangeKind::Deleted);
}
#[test]
-2
View File
@@ -10,8 +10,6 @@ ide-core.workspace = true
ide-language.workspace = true
serde.workspace = true
specta.workspace = true
tree-sitter.workspace = true
rayon.workspace = true
tracing.workspace = true
# Pinned: 0.40.2+ moves to tree-sitter 0.26, the workspace is on 0.25.
ast-grep-core = "=0.40.1"
-3
View File
@@ -10,6 +10,3 @@ ide-core.workspace = true
serde.workspace = true
specta.workspace = true
which = "8"
[dev-dependencies]
tempfile.workspace = true
-6
View File
@@ -91,12 +91,6 @@ fn executable() -> IdeResult<PathBuf> {
})
}
/// The directory holding adb, for command lines that expect `adb` on `PATH`.
pub fn platform_tools_dir() -> Option<&'static Path> {
static DIR: OnceLock<Option<PathBuf>> = OnceLock::new();
DIR.get_or_init(|| adb_executable().as_deref().and_then(Path::parent).map(Path::to_path_buf)).as_deref()
}
/// Connected devices, online ones first; starting the adb daemon when needed.
pub fn devices() -> IdeResult<Vec<AndroidDevice>> {
let adb = executable()?;
+216 -134
View File
@@ -1,101 +1,18 @@
//! Child processes of the `adb` CLI: bounded runs, and cancellable line streams
//! The `adb` CLI as a child process: bounded runs, and cancellable line streams
//! that are handed over in batches (logcat is far too chatty for one message a line).
use ide_core::process::terminate_tree;
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::io::Read;
use std::process::{Child, Command, Stdio};
use std::sync::mpsc;
pub(crate) use ide_core::cli_process::Output;
use ide_core::cli_process::{CarriageReturn, CliTool, Decoding, Poll, Stream, keep_stderr_line};
use ide_core::{CancellationToken, IdeResult};
use std::process::Command;
use std::time::{Duration, Instant};
/// How long a cancelled child gets to exit on `SIGTERM` (and flush) before `SIGKILL`.
const KILL_GRACE: Duration = Duration::from_millis(20);
pub(crate) struct Output {
pub stdout: String,
pub stderr: String,
pub success: bool,
}
fn prepare(cmd: &mut Command) {
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
ide_core::process::prepare(ide_core::process::own_group(cmd));
}
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run adb: {e}")))
}
fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<String> {
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = pipe.read_to_end(&mut buf);
ide_core::output_encoding::decode_tool_output(&buf)
})
}
const ADB: CliTool = CliTool::new("adb", Decoding::ToolOutput);
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
/// a non-zero exit is reported in [`Output::success`], not as an error.
pub(crate) fn run(mut cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
prepare(&mut cmd);
let mut child = spawn(&mut cmd)?;
let out = child.stdout.take().map(read_all);
let err = child.stderr.take().map(read_all);
let deadline = Instant::now() + timeout;
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_some_and(CancellationToken::is_cancelled) {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
if Instant::now() >= deadline {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::unavailable("adb did not respond in time"));
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(Output {
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
success: status.success(),
})
}
enum Event {
Line(bool, String),
Closed,
}
fn spawn_reader(mut pipe: impl Read + Send + 'static, tx: mpsc::Sender<Event>, stdout: bool) {
std::thread::spawn(move || {
let mut buf = [0u8; 8192];
let mut pending: Vec<u8> = Vec::new();
let flush = |pending: &mut Vec<u8>| {
if !pending.is_empty() {
let line = ide_core::output_encoding::decode_tool_output(pending);
pending.clear();
let _ = tx.send(Event::Line(stdout, line.trim_end().to_string()));
}
};
loop {
match pipe.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
for &b in &buf[..n] {
if b == b'\n' {
flush(&mut pending);
} else if b != b'\r' {
pending.push(b);
}
}
}
}
}
flush(&mut pending);
let _ = tx.send(Event::Closed);
});
pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
ADB.run(cmd, timeout, cancel)
}
fn flush<T>(batch: &mut Vec<T>, on_batch: &mut dyn FnMut(Vec<T>)) {
@@ -109,41 +26,22 @@ fn flush<T>(batch: &mut Vec<T>, on_batch: &mut dyn FnMut(Vec<T>)) {
/// old, so neither a quiet nor a steady stream holds lines back. Stderr is kept as a
/// tail for the error message. Returns whether the child exited successfully.
pub(crate) fn stream_batched<T>(
mut cmd: Command,
cmd: Command,
cancel: &CancellationToken,
idle: Duration,
max: usize,
mut parse: impl FnMut(&str) -> Option<T>,
on_batch: &mut dyn FnMut(Vec<T>),
) -> IdeResult<(bool, Vec<String>)> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
prepare(&mut cmd);
let mut child = spawn(&mut cmd)?;
let (tx, rx) = mpsc::channel::<Event>();
let mut open = 0;
if let Some(out) = child.stdout.take() {
spawn_reader(out, tx.clone(), true);
open += 1;
}
if let Some(err) = child.stderr.take() {
spawn_reader(err, tx.clone(), false);
open += 1;
}
drop(tx);
let mut lines = ADB.lines(cmd, cancel, CarriageReturn::Dropped)?;
let mut stderr_tail: Vec<String> = Vec::new();
let mut batch: Vec<T> = Vec::with_capacity(max);
// When the first line of the waiting batch arrived.
let mut since = Instant::now();
while open > 0 {
if cancel.is_cancelled() {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
loop {
let wait = if batch.is_empty() { idle } else { idle.saturating_sub(since.elapsed()) };
match rx.recv_timeout(wait) {
Ok(Event::Line(true, line)) => {
match lines.poll(cancel, wait)? {
Poll::Line(Stream::Stdout, line) => {
if let Some(item) = parse(&line) {
if batch.is_empty() {
since = Instant::now();
@@ -154,36 +52,25 @@ pub(crate) fn stream_batched<T>(
}
}
}
Ok(Event::Line(false, line)) => {
Poll::Line(Stream::Stderr, line) => {
if !line.trim().is_empty() {
stderr_tail.push(line);
if stderr_tail.len() > 20 {
stderr_tail.remove(0);
}
keep_stderr_line(&mut stderr_tail, line);
}
}
Ok(Event::Closed) => open -= 1,
Err(mpsc::RecvTimeoutError::Timeout) => flush(&mut batch, on_batch),
Err(mpsc::RecvTimeoutError::Disconnected) => break,
Poll::Closed => {}
Poll::Timeout => flush(&mut batch, on_batch),
Poll::Finished => break,
}
}
flush(&mut batch, on_batch);
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_cancelled() {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
std::thread::sleep(Duration::from_millis(10));
};
Ok((status.success(), stderr_tail))
Ok((lines.finish(cancel)?, stderr_tail))
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use ide_core::error::ErrorKind;
use ide_core::process::process_alive;
#[test]
fn a_steady_stream_is_handed_over_while_it_runs() {
@@ -203,4 +90,199 @@ mod tests {
assert_eq!(sizes.iter().sum::<usize>(), 20);
assert!(sizes.len() >= 3, "lines arriving every 20 ms waited for the end: {sizes:?}");
}
const LONG: Duration = Duration::from_secs(30);
fn sh(script: &str) -> Command {
let mut cmd = Command::new("sh");
cmd.args(["-c", script]);
cmd
}
/// A script that records its pid in `name`'s file, then runs `rest`.
fn recording_pid(name: &str, rest: &str) -> (Command, std::path::PathBuf) {
let file = std::env::temp_dir().join(format!("openidea-process-{}-{name}", std::process::id()));
let _ = std::fs::remove_file(&file);
(sh(&format!("echo $$ > '{0}.tmp' && mv '{0}.tmp' '{0}'; {rest}", file.display())), file)
}
fn recorded_pid(file: &std::path::Path) -> u32 {
let pid = std::fs::read_to_string(file).unwrap().trim().parse().unwrap();
let _ = std::fs::remove_file(file);
pid
}
/// Cancels `cancel` once the script has recorded its pid.
fn cancel_when_recorded(file: &std::path::Path, cancel: &CancellationToken) {
let (file, cancel) = (file.to_owned(), cancel.clone());
std::thread::spawn(move || {
while !file.exists() {
std::thread::sleep(Duration::from_millis(5));
}
cancel.cancel();
});
}
fn assert_gone(pid: u32) {
let deadline = Instant::now() + Duration::from_secs(5);
while process_alive(pid) {
assert!(Instant::now() < deadline, "process {pid} survived");
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn the_exit_status_is_reported_not_raised() {
assert!(run(sh("exit 0"), LONG, None).unwrap().success);
assert!(!run(sh("exit 3"), LONG, None).unwrap().success);
}
#[test]
fn both_streams_are_captured_separately_and_in_order() {
let out = run(sh("printf 'a\\nb\\nc\\n'; printf 'x\\ny\\n' >&2"), LONG, None).unwrap();
assert_eq!(out.stdout, "a\nb\nc\n");
assert_eq!(out.stderr, "x\ny\n");
assert!(out.success);
}
#[test]
fn invalid_utf8_is_replaced_in_collected_output() {
let out = run(sh("printf 'ok\\n\\377\\n'; printf 'a\\377b' >&2"), LONG, None).unwrap();
assert_eq!(out.stdout, "ok\n\u{FFFD}\n");
assert_eq!(out.stderr, "a\u{FFFD}b");
}
#[test]
fn stdin_is_closed() {
assert_eq!(run(sh("cat; echo done"), LONG, None).unwrap().stdout, "done\n");
}
#[test]
fn a_missing_program_is_unavailable() {
let err = run(Command::new("/nonexistent/openidea-adb"), LONG, None).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "could not run adb: No such file or directory (os error 2)");
}
#[test]
fn a_run_past_its_timeout_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("adb-timeout", "exec sleep 30");
let err = run(cmd, Duration::from_secs(1), None).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "adb did not respond in time");
assert_gone(recorded_pid(&file));
}
#[test]
fn a_cancelled_run_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("adb-cancel", "exec sleep 30");
let cancel = CancellationToken::new();
cancel_when_recorded(&file, &cancel);
let err = run(cmd, LONG, Some(&cancel)).err().unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
assert_gone(recorded_pid(&file));
}
/// Runs `script` batched by `max` lines (a long `idle`, so only `max` and the end flush),
/// parsing stdout lines unless they are `skip`.
fn batches(script: &str, max: usize) -> (bool, Vec<Vec<String>>, Vec<String>) {
let mut batches = Vec::new();
let (ok, tail) = stream_batched(
sh(script),
&CancellationToken::new(),
LONG,
max,
|line| (line != "skip").then(|| line.to_owned()),
&mut |batch| batches.push(batch),
)
.unwrap();
(ok, batches, tail)
}
#[test]
fn a_batch_is_handed_over_as_soon_as_max_lines_are_ready() {
let (ok, batches, _) = batches("printf '1\\n2\\n3\\n4\\n5\\n'", 2);
assert!(ok);
assert_eq!(batches, [vec!["1", "2"], vec!["3", "4"], vec!["5"]]);
}
#[test]
fn lines_the_parser_rejects_are_dropped() {
let (_, batches, _) = batches("printf '1\\nskip\\n2\\n'", 10);
assert_eq!(batches, [vec!["1", "2"]]);
}
#[test]
fn carriage_returns_are_dropped_not_split_on_and_line_ends_are_trimmed() {
let (_, batches, _) = batches("printf 'a\\r\\nb\\rc \\n\\n\\nd'", 10);
assert_eq!(batches, [vec!["a", "bc", "d"]]);
}
#[test]
fn a_stream_replaces_invalid_utf8() {
let (_, batches, _) = batches("printf 'a\\377b\\n'", 10);
assert_eq!(batches, [vec!["a\u{FFFD}b"]]);
}
#[test]
fn a_stream_reports_the_exit_status() {
assert!(batches("exit 0", 10).0);
assert!(!batches("exit 2", 10).0);
}
#[test]
fn stderr_is_not_parsed_and_its_last_twenty_non_blank_lines_are_kept() {
let (_, batches, tail) =
batches("echo ' ' >&2; i=1; while [ $i -le 25 ]; do echo e$i >&2; i=$((i+1)); done; echo out", 10);
assert_eq!(batches, [vec!["out"]]);
let expected: Vec<String> = (6..=25).map(|i| format!("e{i}")).collect();
assert_eq!(tail, expected);
}
#[test]
fn a_stream_cancelled_before_it_starts_does_not_spawn() {
let cancel = CancellationToken::new();
cancel.cancel();
let err = stream_batched(
Command::new("/nonexistent/openidea-adb"),
&cancel,
LONG,
10,
|line| Some(line.to_owned()),
&mut |_| {},
)
.err()
.unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
}
#[test]
fn a_stream_cancelled_while_running_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("adb-stream-cancel", "echo started; exec sleep 30");
let cancel = CancellationToken::new();
let err = stream_batched(cmd, &cancel, LONG, 1, |line| Some(line.to_owned()), &mut |_| cancel.cancel())
.err()
.unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
assert_gone(recorded_pid(&file));
}
#[test]
fn a_missing_program_cannot_be_streamed() {
let err = stream_batched(
Command::new("/nonexistent/openidea-adb"),
&CancellationToken::new(),
LONG,
10,
|line| Some(line.to_owned()),
&mut |_| {},
)
.err()
.unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "could not run adb: No such file or directory (os error 2)");
}
}
-2
View File
@@ -17,6 +17,4 @@ serde_json.workspace = true
specta.workspace = true
tracing.workspace = true
dirs.workspace = true
[dev-dependencies]
tempfile.workspace = true
+62 -14
View File
@@ -483,11 +483,6 @@ fn go_module_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
vec![s]
}
/// `pnpm` / `yarn` / `bun` / `npm`, from the lock file next to `package.json` or above it.
fn package_manager(dir: &Path) -> &'static str {
ide_core::project_roots::package_manager(dir)
}
fn has_build_script(dir: &Path) -> bool {
std::fs::read(dir.join("package.json"))
.ok()
@@ -525,7 +520,12 @@ fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
fn ts_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
let script = has_build_script(dir);
if script && (kind == BuildKind::Artifacts || !dir.join("tsconfig.json").is_file()) {
return vec![BuildStep::new(package_manager(dir), &["run", "build"], dir, Format::Tsc)];
return vec![BuildStep::new(
ide_core::project_roots::package_manager(dir),
&["run", "build"],
dir,
Format::Tsc,
)];
}
let local = dir.ancestors().map(|d| d.join("node_modules/.bin/tsc")).find(|p| p.is_file());
let program = local.map_or_else(|| "tsc".to_owned(), |p| p.to_string_lossy().into_owned());
@@ -1008,12 +1008,7 @@ pub fn build_for_launches(
if plan.system == BuildSystem::Maven
&& let Some(m) = &model.maven
{
maven_launch_projects(root, m, module, test)
.iter()
.flat_map(|p| {
launch_class_dirs(plan.system, &subdir(root, &p.dir), test && subdir(root, &p.dir) == module)
})
.collect()
maven_launch_output_dirs(root, m, module, test).into_iter().filter(|dir| dir.is_dir()).collect()
} else {
launch_class_dirs(plan.system, module, test)
}
@@ -1021,6 +1016,60 @@ pub fn build_for_launches(
Ok(modules.iter().map(|m| LaunchBuild { class_dirs: class_dirs(m), failure: failure.clone() }).collect())
}
/// Maven output directories for a launch, including directories that have yet to be created.
pub fn maven_launch_output_dirs(root: &Path, model: &maven::MavenModel, module: &Path, test: bool) -> Vec<PathBuf> {
maven_launch_projects(root, model, module, test)
.into_iter()
.flat_map(|p| {
let dir = subdir(root, &p.dir);
maven_output_dirs(&dir, test && dir == module)
})
.collect()
}
/// The class directories of a Maven launch that must hold classes after its build: those of
/// the launch projects with sources in a conventional JVM source root. One that is missing
/// or holds no class was caught mid-rewrite, e.g. cleaned by a concurrent `mvn` (#5404).
pub fn launch_required_class_dirs(root: &Path, model: &BuildModel, module: &Path, test: bool) -> Vec<PathBuf> {
fn has_sources(dir: &Path, depth: u32) -> bool {
let Ok(entries) = std::fs::read_dir(dir) else { return false };
entries.flatten().any(|e| {
let p = e.path();
if p.is_dir() {
depth > 0 && has_sources(&p, depth - 1)
} else {
// A package-info.java without annotations compiles to nothing.
p.file_name() != Some("package-info.java".as_ref())
&& p.extension().is_some_and(|x| x == "java" || x == "kt" || x == "groovy" || x == "scala")
}
})
}
let compiles = |dir: &Path, set: &str| {
["java", "kotlin", "groovy", "scala"].iter().any(|lang| has_sources(&dir.join("src").join(set).join(lang), 32))
};
let Some(m) = &model.maven else { return Vec::new() };
let mut dirs = Vec::new();
for p in maven_launch_projects(root, m, module, test) {
let dir = subdir(root, &p.dir);
if test && dir == module && compiles(&dir, "test") {
dirs.push(subdir(&dir, "target/test-classes"));
}
if compiles(&dir, "main") {
dirs.push(subdir(&dir, "target/classes"));
}
}
dirs
}
fn maven_output_dirs(module: &Path, test: bool) -> Vec<PathBuf> {
let mut dirs = Vec::new();
if test {
dirs.push(subdir(module, "target/test-classes"));
}
dirs.push(subdir(module, "target/classes"));
dirs
}
fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<PathBuf> {
let sets: &[&str] = if test { &["test", "main"] } else { &["main"] };
let dirs: Vec<PathBuf> = match system {
@@ -1031,8 +1080,7 @@ fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<Path
.map(|d| subdir(module, &format!("build/{d}/{s}")))
})
.collect(),
BuildSystem::Maven if test => vec![subdir(module, "target/test-classes"), subdir(module, "target/classes")],
BuildSystem::Maven => vec![subdir(module, "target/classes")],
BuildSystem::Maven => maven_output_dirs(module, test),
_ => Vec::new(),
};
dirs.into_iter().filter(|d| d.is_dir()).collect()
-34
View File
@@ -31,40 +31,6 @@ pub const LOCAL_REPO_TRACKING_ARG: &str = "-Daether.enhancedLocalRepository.trac
pub const LIFECYCLE: &[&str] =
&["clean", "validate", "compile", "test", "package", "verify", "install", "site", "deploy"];
/// Every phase of the clean, default and site lifecycles (Execute Maven Goal completion).
pub const ALL_PHASES: &[&str] = &[
"pre-clean",
"clean",
"post-clean",
"validate",
"initialize",
"generate-sources",
"process-sources",
"generate-resources",
"process-resources",
"compile",
"process-classes",
"generate-test-sources",
"process-test-sources",
"generate-test-resources",
"process-test-resources",
"test-compile",
"process-test-classes",
"test",
"prepare-package",
"package",
"pre-integration-test",
"integration-test",
"post-integration-test",
"verify",
"install",
"deploy",
"pre-site",
"site",
"post-site",
"site-deploy",
];
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MavenModel {
+263 -13
View File
@@ -3,7 +3,13 @@
use super::MavenProject;
use crate::process;
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::collections::HashSet;
use std::fs::{self, File};
use std::path::{Component, Path, PathBuf};
use std::time::SystemTime;
const DEPENDENCY_PLUGIN: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1";
const SOURCE_REFRESH_WORKERS: usize = 4;
#[derive(Debug, PartialEq, Eq)]
pub struct Artifact {
@@ -11,6 +17,29 @@ pub struct Artifact {
pub name: String,
pub version: String,
pub sources: PathBuf,
binary: PathBuf,
}
fn valid_part(part: &str) -> bool {
!part.is_empty()
&& part != "."
&& part != ".."
&& part.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
}
fn modified_file(path: &Path) -> Option<SystemTime> {
let metadata = fs::metadata(path).ok()?;
if metadata.is_file() { metadata.modified().ok() } else { None }
}
impl Artifact {
fn stale_binary(&self) -> Option<SystemTime> {
if !self.version.ends_with("-SNAPSHOT") {
return None;
}
let binary = modified_file(&self.binary)?;
(modified_file(&self.sources)? < binary).then_some(binary)
}
}
/// Resolve only jars inside the selected local repository, including custom repositories.
@@ -28,16 +57,14 @@ pub fn artifact(jar: &Path, repository: &Path) -> Option<Artifact> {
}
let n = parts.len();
let (name, version, file) = (parts[n - 3], parts[n - 2], parts[n - 1]);
let valid = |s: &str| {
!s.is_empty() && s != "." && s != ".." && s.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
};
if !parts[..n - 1].iter().all(|s| valid(s)) || file != format!("{name}-{version}.jar") {
if !parts[..n - 1].iter().all(|s| valid_part(s)) || file != format!("{name}-{version}.jar") {
return None;
}
Some(Artifact {
group: parts[..n - 3].join("."),
name: name.into(),
version: version.into(),
binary: jar.to_owned(),
sources: jar.with_file_name(format!("{name}-{version}-sources.jar")),
})
}
@@ -48,26 +75,58 @@ pub fn download(
artifact: &Artifact,
repository: &Path,
cancel: &CancellationToken,
) -> IdeResult<Option<PathBuf>> {
resolve(root, project, artifact, repository, &[], artifact.stale_binary(), cancel)
}
fn resolve(
root: &Path,
project: &MavenProject,
artifact: &Artifact,
repository: &Path,
profile_args: &[String],
stale: Option<SystemTime>,
cancel: &CancellationToken,
) -> IdeResult<Option<PathBuf>> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if artifact.sources.is_file() {
if stale.is_none() && artifact.sources.is_file() {
return Ok(Some(artifact.sources.clone()));
}
let mut args = vec!["-B".into(), "-N".into(), "-Dstyle.color=never".into()];
args.extend(project.options.clone());
args.extend([
format!("-Dmaven.repo.local={}", repository.display()),
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:get".into(),
format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version),
"-Dtransitive=false".into(),
]);
args.extend(project.options.iter().cloned());
args.extend(profile_args.iter().cloned());
args.push(format!("-Dmaven.repo.local={}", repository.display()));
let coordinate = format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version);
let stage = if let Some(binary) = stale {
// Keep the existing attachment readable while Maven resolves the timestamped snapshot.
// Disable Resolver's in-place copy to the base -SNAPSHOT filename.
let stage =
tempfile::Builder::new().prefix(".openidea-sources-").tempdir_in(artifact.sources.parent().unwrap())?;
args.extend([
"-U".into(),
"-Daether.artifactResolver.snapshotNormalization=false".into(),
format!("{DEPENDENCY_PLUGIN}:copy"),
coordinate,
"-Dmdep.useBaseVersion=true".into(),
format!("-DoutputDirectory={}", stage.path().display()),
]);
Some((stage, binary))
} else {
args.extend([format!("{DEPENDENCY_PLUGIN}:get"), coordinate, "-Dtransitive=false".into()]);
None
};
let output = process::run(&project.command, &args, &root.join(&project.dir), &project.env, cancel, |_, _| {})?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if artifact.sources.is_file() {
if let Some((stage, binary)) = stage {
let resolved = stage.path().join(artifact.sources.file_name().unwrap());
if output.success && resolved.is_file() {
return replace_stale_sources(artifact, &resolved, binary, cancel);
}
} else if artifact.sources.is_file() {
return Ok(Some(artifact.sources.clone()));
}
let coordinate = format!("{}:{}:jar:sources:{}", artifact.group, artifact.name, artifact.version);
@@ -83,6 +142,115 @@ pub fn download(
))
}
fn replace_stale_sources(
artifact: &Artifact,
resolved: &Path,
binary: SystemTime,
cancel: &CancellationToken,
) -> IdeResult<Option<PathBuf>> {
// Maven can fall back to a locally installed snapshot. Keep its timestamp if it returned
// the same bytes so a later reload can retry when newer sources are available.
let hash = |path| -> std::io::Result<_> { Ok(blake3::Hasher::new().update_reader(File::open(path)?)?.finalize()) };
if hash(resolved)? == hash(&artifact.sources)? {
return Ok(None);
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
match artifact.stale_binary() {
Some(current) if current == binary => {
File::options().write(true).open(resolved)?.set_modified(SystemTime::now().max(binary))?;
fs::rename(resolved, &artifact.sources)?;
Ok(Some(artifact.sources.clone()))
}
None if artifact.sources.is_file() => Ok(Some(artifact.sources.clone())),
_ => Ok(None),
}
}
/// Resolved Maven dependencies with an existing attachment. Binaries may still be
/// updating during import, so freshness is checked when the refresh runs.
pub fn cached_snapshots<'a>(
repository: &Path,
projects: impl Iterator<Item = (usize, &'a MavenProject)>,
) -> Vec<(usize, Artifact)> {
let mut seen = HashSet::new();
let mut candidates = Vec::new();
for (owner, project) in projects {
let mut dependencies: Vec<_> = project.dependencies.iter().collect();
while let Some(dep) = dependencies.pop() {
if !dep.resolved() {
continue;
}
dependencies.extend(&dep.children);
let Some(version) = dep.version.as_deref().filter(|v| v.ends_with("-SNAPSHOT") && valid_part(v)) else {
continue;
};
if dep.scope == "system"
|| dep.classifier.is_some()
|| !matches!(dep.kind.as_str(), "jar" | "bundle" | "maven-plugin" | "ejb")
|| !valid_part(&dep.artifact_id)
|| !dep.group_id.split('.').all(valid_part)
{
continue;
}
let name = &dep.artifact_id;
let jar = repository
.join(dep.group_id.replace('.', "/"))
.join(name)
.join(version)
.join(format!("{name}-{version}.jar"));
if let Some(artifact) = artifact(&jar, repository)
&& artifact.sources.is_file()
&& seen.insert(jar)
{
candidates.push((owner, artifact));
}
}
}
candidates
}
/// Refresh only previously attached snapshots. Maven subprocesses are bounded
/// and share the build reload's cancellation token.
pub fn refresh_snapshots(
root: &Path,
projects: &[MavenProject],
repository: &Path,
candidates: &[(usize, Artifact)],
profiles: &[String],
cancel: &CancellationToken,
) -> Vec<PathBuf> {
let profile_args = if profiles.is_empty() { vec![] } else { vec![format!("-P{}", profiles.join(","))] };
let profile_args = &profile_args;
let stale: Vec<_> = candidates.iter().filter(|(_, artifact)| artifact.stale_binary().is_some()).collect();
let batch_size = stale.len().div_ceil(SOURCE_REFRESH_WORKERS).max(1);
std::thread::scope(|scope| {
let workers: Vec<_> = stale
.chunks(batch_size)
.map(|batch| {
scope.spawn(move || {
let mut refreshed = Vec::new();
for (owner, artifact) in batch.iter().copied() {
if cancel.is_cancelled() {
break;
}
let Some(binary) = artifact.stale_binary() else { continue };
match resolve(root, &projects[*owner], artifact, repository, profile_args, Some(binary), cancel)
{
Ok(Some(_)) => refreshed.push(artifact.binary.clone()),
Ok(None) => {}
Err(e) => tracing::debug!(path = %artifact.sources.display(), "Maven sources refresh: {e}"),
}
}
refreshed
})
})
.collect();
workers.into_iter().flat_map(|worker| worker.join().expect("Maven sources worker")).collect()
})
}
#[cfg(test)]
mod tests {
use super::*;
@@ -121,4 +289,86 @@ mod tests {
assert_eq!(artifact(Path::new(path), repository), None, "{path}");
}
}
#[test]
fn selects_existing_snapshot_attachments_from_the_resolved_tree() {
use crate::maven::{MavenDependency, Omission};
let repo = tempfile::tempdir().unwrap();
let dependency = |name: &str, version: &str, cached: bool| {
if cached {
let dir = repo.path().join("example").join(name).join(version);
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join(format!("{name}-{version}-sources.jar")), b"cached").unwrap();
}
MavenDependency {
group_id: "example".into(),
artifact_id: name.into(),
version: Some(version.into()),
kind: "jar".into(),
..Default::default()
}
};
let transitive = dependency("transitive", "1-SNAPSHOT", true);
let direct = MavenDependency { children: vec![transitive.clone()], ..dependency("direct", "1-SNAPSHOT", true) };
let omitted =
MavenDependency { omitted: Some(Omission::Conflict), ..dependency("omitted", "1-SNAPSHOT", true) };
let projects = [
MavenProject {
dependencies: vec![
direct,
omitted,
dependency("missing", "1-SNAPSHOT", false),
dependency("release", "1", true),
],
..Default::default()
},
MavenProject { dependencies: vec![transitive], ..Default::default() },
];
let mut found: Vec<_> = cached_snapshots(repo.path(), projects.iter().enumerate())
.into_iter()
.map(|(owner, artifact)| (owner, artifact.name))
.collect();
found.sort();
assert_eq!(found, [(0, "direct".into()), (0, "transitive".into())]);
}
#[cfg(unix)]
#[test]
fn downloads_sources_again_when_the_snapshot_binary_is_newer() {
use std::fs::FileTimes;
use std::os::unix::fs::PermissionsExt;
use std::time::Duration;
let dir = tempfile::tempdir().unwrap();
let repository = dir.path().join("repository");
let jar = repository.join("example/lib/1-SNAPSHOT/lib-1-SNAPSHOT.jar");
fs::create_dir_all(jar.parent().unwrap()).unwrap();
fs::write(&jar, b"new binary").unwrap();
let artifact = artifact(&jar, &repository).unwrap();
fs::write(&artifact.sources, b"old sources").unwrap();
File::open(&artifact.sources)
.unwrap()
.set_times(FileTimes::new().set_modified(SystemTime::now() - Duration::from_secs(60)))
.unwrap();
let launcher = dir.path().join("mvn");
fs::write(
&launcher,
"#!/bin/sh\nfor arg do\n case \"$arg\" in\n -DoutputDirectory=*) out=\"${arg#*=}\" ;;\n esac\ndone\nprintf 'new sources' > \"$out/lib-1-SNAPSHOT-sources.jar\"\n",
)
.unwrap();
fs::set_permissions(&launcher, fs::Permissions::from_mode(0o755)).unwrap();
let cancel = CancellationToken::new();
cancel.cancel();
assert!(download(dir.path(), &MavenProject::default(), &artifact, &repository, &cancel).is_err());
assert_eq!(fs::read(&artifact.sources).unwrap(), b"old sources");
let project = MavenProject { command: launcher.to_string_lossy().into_owned(), ..Default::default() };
let cancel = CancellationToken::new();
let path = download(dir.path(), &project, &artifact, &repository, &cancel).unwrap().unwrap();
assert_eq!(fs::read(&path).unwrap(), b"new sources");
assert_eq!(
download(dir.path(), &MavenProject::default(), &artifact, &repository, &CancellationToken::new()).unwrap(),
Some(path)
);
}
}
+148 -9
View File
@@ -24,6 +24,21 @@ pub(crate) const MAX_LINE_BYTES: usize = 1024 * 1024;
/// `Output::text` stops growing past this while the pipes keep draining: a chatty build can
/// print far more than is ever parsed back out of the retained copy.
pub(crate) const MAX_TEXT_BYTES: usize = 32 * 1024 * 1024;
/// Lines the pipe readers may queue ahead of the consumer. A build printing faster than
/// `on_line` takes its lines waits on its full pipe, as it would on a terminal, instead of
/// the lines piling up in memory (a line is at most [`MAX_LINE_BYTES`] in [`run_bounded`]).
const LINE_QUEUE: usize = 64;
/// What [`pump_bounded`] reads from a pipe at a time.
const PUMP_CHUNK: usize = 64 * 1024;
/// One line of a child's output, with the stream it came from.
type Line = (Stream, String);
/// The queue from the pipe readers to the consumer: bounded, so the readers wait while the
/// consumer is behind.
fn line_queue() -> (mpsc::SyncSender<Line>, mpsc::Receiver<Line>) {
mpsc::sync_channel(LINE_QUEUE)
}
pub(crate) struct Output {
pub success: bool,
@@ -33,20 +48,20 @@ pub(crate) struct Output {
pub truncated: bool,
}
/// Bounded pump for callers that stream every line and only summarize errors: reads fixed
/// 64 KiB chunks, splits newline-free runs at a UTF-8 char boundary at the line cap, and
/// never grows one line buffer without bound.
fn pump_bounded(stream: Box<dyn Read + Send>, kind: Stream, tx: &mpsc::Sender<(Stream, String)>) {
/// Bounded pump for callers that stream every line and only summarize errors: reads
/// [`PUMP_CHUNK`] chunks, splits newline-free runs at a UTF-8 char boundary at the line cap,
/// and never grows one line buffer without bound.
fn pump_bounded(stream: Box<dyn Read + Send>, kind: Stream, tx: &mpsc::SyncSender<Line>) {
let mut reader = BufReader::new(stream);
// `terminated`: the buffer ends in the stream's newline. A segment cut from a
// newline-free run at the line cap must keep a trailing `\r` — it is data.
let send = |buf: &mut Vec<u8>, terminated: bool, tx: &mpsc::Sender<(Stream, String)>| {
let send = |buf: &mut Vec<u8>, terminated: bool, tx: &mpsc::SyncSender<Line>| {
let line = ide_core::output_encoding::decode_tool_output(buf);
let line = if terminated { line.trim_end_matches(['\n', '\r']).to_owned() } else { line };
buf.clear();
tx.send((kind, line)).is_ok()
};
let mut chunk = vec![0u8; 64 * 1024];
let mut chunk = vec![0u8; PUMP_CHUNK];
let mut line: Vec<u8> = Vec::with_capacity(256);
'read: loop {
let n = match reader.read(&mut chunk) {
@@ -179,8 +194,8 @@ fn run_with_env_capture(
}
let mut child =
command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {}: {e}", program.display())))?;
let (tx, rx) = mpsc::channel::<(Stream, String)>();
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::Sender<(Stream, String)>| {
let (tx, rx) = line_queue();
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::SyncSender<Line>| {
std::thread::spawn(move || {
if bounded {
pump_bounded(stream, kind, &tx);
@@ -212,7 +227,8 @@ fn run_with_env_capture(
// Retained copy of the output: the first half of the cap, then — once output overflows —
// a rolling tail instead of the middle. Error summaries read the end of the output, while
// listings parsed out of a successful run read from the start. The pipes keep draining
// either way: `on_line` still sees every line, so the child never blocks on a full pipe.
// either way: `on_line` still sees every line, and the child waits on its pipe only
// while `on_line` is behind, never because the retained copy is full.
let cap = MAX_TEXT_BYTES / 2;
let mut head = String::new();
let mut tail: std::collections::VecDeque<Vec<u8>> = Default::default();
@@ -295,6 +311,9 @@ fn run_with_env_capture(
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Instant;
#[test]
fn a_model_line_over_one_mebibyte_is_kept_whole_for_the_parsers() {
@@ -500,4 +519,124 @@ mod tests {
assert!(out.text.starts_with("pad\n"));
assert!(out.text.ends_with("FATAL: the real error\n"));
}
/// Numbered lines of `LINE_LEN` bytes each, counting the bytes taken: a pipe stand-in that
/// reports when it is dropped, which is when the pump owning it ends.
const LINE_LEN: usize = 100;
struct NumberedLines {
next: usize,
lines: usize,
taken: Arc<AtomicUsize>,
gone: mpsc::Sender<()>,
}
fn numbered(n: usize) -> String {
format!("{n:0width$}", width = LINE_LEN - 1)
}
impl Read for NumberedLines {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let mut n = 0;
while self.next < self.lines && n + LINE_LEN <= buf.len() {
buf[n..n + LINE_LEN - 1].copy_from_slice(numbered(self.next).as_bytes());
buf[n + LINE_LEN - 1] = b'\n';
self.next += 1;
n += LINE_LEN;
}
self.taken.fetch_add(n, Ordering::SeqCst);
Ok(n)
}
}
impl Drop for NumberedLines {
fn drop(&mut self) {
let _ = self.gone.send(());
}
}
#[test]
fn a_slow_consumer_holds_the_pump_back_instead_of_queueing_every_line() {
const LINES: usize = 50_000;
let taken = Arc::new(AtomicUsize::new(0));
let (gone, _) = mpsc::channel();
let pipe = NumberedLines { next: 0, lines: LINES, taken: taken.clone(), gone };
let (tx, rx) = line_queue();
let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx));
let (mut count, mut peak) = (0usize, 0usize);
loop {
match rx.recv_timeout(Duration::from_secs(60)) {
Ok((stream, line)) => {
assert_eq!(stream, Stream::Stdout);
assert_eq!(line, numbered(count), "a line arrived out of order or damaged");
// Read from the pipe but not yet handed over: the rest of the chunk the pump
// is cutting into lines, and the queue.
peak = peak.max(taken.load(Ordering::SeqCst) - count * LINE_LEN);
count += 1;
// A consumer that cannot keep up with the process.
if count.is_multiple_of(LINE_QUEUE) {
std::thread::sleep(Duration::from_millis(1));
}
}
Err(mpsc::RecvTimeoutError::Disconnected) => break,
Err(mpsc::RecvTimeoutError::Timeout) => panic!("the pump stalled"),
}
}
pump.join().unwrap();
assert_eq!(count, LINES);
let bound = PUMP_CHUNK + (LINE_QUEUE + 2) * LINE_LEN;
assert!(peak <= bound, "{peak} bytes read ahead of the consumer, more than {bound}");
}
#[test]
fn a_pump_blocked_on_a_full_queue_ends_when_the_consumer_is_gone() {
let taken = Arc::new(AtomicUsize::new(0));
let (gone_tx, gone) = mpsc::channel();
// Far more than the queue and a few chunks hold.
let pipe = NumberedLines { next: 0, lines: 100_000, taken: taken.clone(), gone: gone_tx };
let (tx, rx) = line_queue();
let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx));
// A consumer that takes nothing: the queue fills, with the pump inside its first chunk.
let deadline = Instant::now() + Duration::from_secs(30);
while taken.load(Ordering::SeqCst) == 0 {
assert!(Instant::now() < deadline, "the pump never read");
std::thread::sleep(Duration::from_millis(1));
}
// Time for a pump that does not wait to run ahead.
std::thread::sleep(Duration::from_millis(100));
assert!(taken.load(Ordering::SeqCst) <= PUMP_CHUNK, "the pump read past a full queue");
assert!(gone.try_recv().is_err(), "the pump ended while its consumer was still there");
drop(rx);
gone.recv_timeout(Duration::from_secs(30)).expect("the pump stayed blocked after the consumer was gone");
pump.join().unwrap();
}
#[test]
fn a_slow_on_line_still_sees_every_line_in_order_and_the_exit_status() {
if cfg!(windows) {
return;
}
let tmp = tempfile::tempdir().unwrap();
let args = ["-c".into(), "awk 'BEGIN{for(i=1;i<=300000;i++)print i}'; exit 4".into()];
for bounded in [false, true] {
let mut next = 1usize;
let on_line = |stream: Stream, line: &str| {
assert_eq!(stream, Stream::Stdout);
assert_eq!(line, next.to_string());
next += 1;
if next.is_multiple_of(1000) {
std::thread::sleep(Duration::from_millis(1));
}
};
let cancel = CancellationToken::new();
let out = if bounded {
run_bounded("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line)
} else {
run("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line)
}
.unwrap();
assert!(!out.success);
assert_eq!(next, 300_001, "lines were lost");
}
}
}
+1
View File
@@ -6,6 +6,7 @@ edition.workspace = true
license.workspace = true
[dependencies]
base64.workspace = true
dunce.workspace = true
encoding_rs.workspace = true
serde.workspace = true
+319
View File
@@ -0,0 +1,319 @@
//! Runs a tool's CLI (`docker`, `gh`, `adb`) as a child process: bounded runs that collect
//! its output, and cancellable streams that hand over its output line by line.
//!
//! Every child leads its own process group ([`own_group`]), so cancelling or timing out
//! reaches what it started in turn (`gh` → `git`, `docker` → CLI plugins such as compose).
//! They get [`KILL_GRACE`] to exit on `SIGTERM` and clean up (git removes its lock files)
//! before `SIGKILL`.
use crate::process::{own_group, prepare, terminate_tree};
use crate::{CancellationToken, IdeError, IdeResult};
use std::borrow::Cow;
use std::io::{Read, Write};
use std::process::{Child, Command, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};
/// How long a cancelled or timed-out child's process group gets to exit on `SIGTERM`
/// before `SIGKILL`.
const KILL_GRACE: Duration = Duration::from_millis(20);
/// How many of a streamed child's last non-blank stderr lines are kept for its error message.
const STDERR_TAIL: usize = 20;
/// How a tool's output bytes become text.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Decoding {
/// [`decode_tool_output`](crate::output_encoding::decode_tool_output): UTF-8, and on
/// Windows the system code page for what is not.
ToolOutput,
/// UTF-8, invalid bytes replaced by U+FFFD.
Utf8Lossy,
}
impl Decoding {
fn decode(self, bytes: &[u8]) -> Cow<'_, str> {
match self {
Decoding::ToolOutput => Cow::Owned(crate::output_encoding::decode_tool_output(bytes)),
Decoding::Utf8Lossy => String::from_utf8_lossy(bytes),
}
}
}
/// What a child's stdin is fed with, and how.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Input<'a> {
/// Written before the output is read, then closed: only for input small enough
/// (a password) to fit the pipe, as a full pipe blocks the caller.
Inline(&'a str),
/// Written by a thread of its own, then closed: a large body must not block on a full
/// pipe while the child is not reading yet.
Threaded(&'a str),
}
/// How a streamed child's `\r` is read.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CarriageReturn {
/// Ends a line like `\n`: progress output rewrites its line in place.
EndsLine,
/// Is dropped; only `\n` ends a line.
Dropped,
}
/// What a bounded run collected.
pub struct Output {
pub stdout: String,
pub stderr: String,
pub success: bool,
}
/// Which pipe a streamed line came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Stream {
Stdout,
Stderr,
}
/// One tool's CLI: its name for error messages and how its output is decoded.
#[derive(Clone, Copy, Debug)]
pub struct CliTool {
name: &'static str,
decoding: Decoding,
}
impl CliTool {
pub const fn new(name: &'static str, decoding: Decoding) -> Self {
Self { name, decoding }
}
fn spawn(self, cmd: &mut Command) -> IdeResult<Child> {
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run {}: {e}", self.name)))
}
/// Pipes stdout and stderr, closes stdin and starts the child in its own process group.
fn configure(cmd: &mut Command) {
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
prepare(own_group(cmd));
}
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
/// a non-zero exit is reported in [`Output::success`], not as an error.
pub fn run(self, cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
self.run_with_input(cmd, None, timeout, cancel)
}
/// [`run`](Self::run) with `input` written to the child's stdin and then closed.
pub fn run_with_input(
self,
mut cmd: Command,
input: Option<Input>,
timeout: Duration,
cancel: Option<&CancellationToken>,
) -> IdeResult<Output> {
Self::configure(&mut cmd);
if input.is_some() {
cmd.stdin(Stdio::piped());
}
let mut child = self.spawn(&mut cmd)?;
match (input, child.stdin.take()) {
(Some(Input::Inline(text)), Some(mut stdin)) => {
// Dropping `stdin` afterwards closes it, so the CLI sees EOF.
let _ = stdin.write_all(text.as_bytes());
}
(Some(Input::Threaded(text)), Some(mut stdin)) => {
let text = text.to_owned();
std::thread::spawn(move || {
let _ = stdin.write_all(text.as_bytes());
});
}
_ => {}
}
let decoding = self.decoding;
let out = child.stdout.take().map(|pipe| read_all(pipe, decoding));
let err = child.stderr.take().map(|pipe| read_all(pipe, decoding));
let deadline = Instant::now() + timeout;
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_some_and(CancellationToken::is_cancelled) {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
if Instant::now() >= deadline {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::unavailable(format!("{} did not respond in time", self.name)));
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(Output {
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
success: status.success(),
})
}
/// Runs `cmd`, handing every output line to `on_line` until it exits or `cancel`
/// fires. Returns whether it exited successfully plus the last stderr lines.
pub fn stream(
self,
cmd: Command,
cancel: &CancellationToken,
on_line: &mut dyn FnMut(Stream, String),
) -> IdeResult<(bool, Vec<String>)> {
let mut lines = self.lines(cmd, cancel, CarriageReturn::EndsLine)?;
let mut stderr_tail: Vec<String> = Vec::new();
loop {
match lines.poll(cancel, Duration::from_millis(50))? {
Poll::Line(stream, line) => {
if stream == Stream::Stderr && !line.trim().is_empty() {
keep_stderr_line(&mut stderr_tail, line.clone());
}
on_line(stream, line);
}
Poll::Closed | Poll::Timeout => {}
Poll::Finished => break,
}
}
Ok((lines.finish(cancel)?, stderr_tail))
}
/// Starts `cmd` with a reader thread per pipe, for a caller that drives the loop itself
/// (see [`Lines::poll`]). Fails when `cancel` has already fired, without starting it.
pub fn lines(self, mut cmd: Command, cancel: &CancellationToken, cr: CarriageReturn) -> IdeResult<Lines> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
Self::configure(&mut cmd);
let mut child = self.spawn(&mut cmd)?;
let (tx, rx) = mpsc::channel::<Event>();
let mut open = 0;
if let Some(out) = child.stdout.take() {
spawn_reader(out, tx.clone(), Stream::Stdout, self.decoding, cr);
open += 1;
}
if let Some(err) = child.stderr.take() {
spawn_reader(err, tx.clone(), Stream::Stderr, self.decoding, cr);
open += 1;
}
drop(tx);
Ok(Lines { child, rx, open })
}
}
/// Appends a stderr line to `tail`, which keeps only the last [`STDERR_TAIL`].
pub fn keep_stderr_line(tail: &mut Vec<String>, line: String) {
tail.push(line);
if tail.len() > STDERR_TAIL {
tail.remove(0);
}
}
fn read_all(mut pipe: impl Read + Send + 'static, decoding: Decoding) -> std::thread::JoinHandle<String> {
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = pipe.read_to_end(&mut buf);
decoding.decode(&buf).into_owned()
})
}
enum Event {
Line(Stream, String),
Closed,
}
fn spawn_reader(
mut pipe: impl Read + Send + 'static,
tx: mpsc::Sender<Event>,
stream: Stream,
decoding: Decoding,
cr: CarriageReturn,
) {
std::thread::spawn(move || {
let mut buf = [0u8; 8192];
let mut pending: Vec<u8> = Vec::new();
let flush = |pending: &mut Vec<u8>| {
if !pending.is_empty() {
let line = decoding.decode(pending).trim_end().to_string();
pending.clear();
let _ = tx.send(Event::Line(stream, line));
}
};
loop {
match pipe.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
for &b in &buf[..n] {
if b == b'\n' || (b == b'\r' && cr == CarriageReturn::EndsLine) {
flush(&mut pending);
} else if b != b'\r' {
pending.push(b);
}
}
}
}
}
flush(&mut pending);
let _ = tx.send(Event::Closed);
});
}
/// A running child whose output lines are read by threads: see [`CliTool::lines`].
pub struct Lines {
child: Child,
rx: mpsc::Receiver<Event>,
/// Pipes whose reader has not reported its end yet.
open: usize,
}
/// What [`Lines::poll`] saw.
pub enum Poll {
Line(Stream, String),
/// A pipe reached its end.
Closed,
/// Nothing arrived within the wait.
Timeout,
/// Every pipe is at its end.
Finished,
}
impl Lines {
/// Waits up to `wait` for the next line. Fails, after killing the child, when `cancel` has fired.
pub fn poll(&mut self, cancel: &CancellationToken, wait: Duration) -> IdeResult<Poll> {
if self.open == 0 {
return Ok(Poll::Finished);
}
if cancel.is_cancelled() {
terminate_tree(&mut self.child, KILL_GRACE);
return Err(IdeError::cancelled());
}
match self.rx.recv_timeout(wait) {
Ok(Event::Line(stream, line)) => Ok(Poll::Line(stream, line)),
Ok(Event::Closed) => {
self.open -= 1;
Ok(Poll::Closed)
}
Err(mpsc::RecvTimeoutError::Timeout) => Ok(Poll::Timeout),
Err(mpsc::RecvTimeoutError::Disconnected) => {
self.open = 0;
Ok(Poll::Finished)
}
}
}
/// Waits for the child to exit and returns whether it did so successfully. Fails, after
/// killing it, when `cancel` fires first.
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<bool> {
let status = loop {
if let Some(status) = self.child.try_wait()? {
break status;
}
if cancel.is_cancelled() {
terminate_tree(&mut self.child, KILL_GRACE);
return Err(IdeError::cancelled());
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(status.success())
}
}
+76 -2
View File
@@ -20,7 +20,72 @@ pub struct IdeError {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum ErrorData {
Tool { tool: String, missing: bool },
Tool {
tool: String,
missing: bool,
},
/// A non-fast-forward push from the current branch to its configured upstream.
PushRejected {
source: String,
upstream: String,
divergence: Option<Box<PushDivergence>>,
/// Other refs may already have been published in the same push.
#[specta(optional)]
report: Option<Box<PushReport>>,
},
/// Git updated some refs before a later ref or push URL failed.
PushPartiallyApplied {
report: Box<PushReport>,
},
/// A conflicted history replay left an amend commit ready to keep separately.
AmendConflict {
commit: String,
},
}
/// Git's reported result for each destination ref. A remote with several push URLs can
/// report more than one result for the same ref.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct PushReport {
pub remote: Option<String>,
pub refs: Vec<PushRefResult>,
}
impl PushReport {
pub fn new(remote: Option<String>) -> Self {
Self { remote, refs: Vec::new() }
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct PushRefResult {
pub reference: String,
pub status: PushRefStatus,
/// The number of commits between the tips Git reports for a fast-forward.
pub commits: Option<u32>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum PushRefStatus {
FastForward,
Forced,
Created,
UpToDate,
Deleted,
}
/// The two tips shown in the rejected-push dialog. A retry must use this lease
/// even if a fetch advances the remote-tracking branch while the dialog is open.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PushDivergence {
pub source: String,
pub remote: String,
pub target: String,
pub local_tip: String,
pub remote_tip: String,
pub remote_commits: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -30,7 +95,7 @@ pub enum ErrorKind {
AlreadyExists,
PermissionDenied,
InvalidInput,
/// Document version mismatch; the UI must resync the full text.
/// The requested state is stale; the UI must use the current snapshot.
OutOfSync,
Cancelled,
TimedOut,
@@ -115,4 +180,13 @@ mod tests {
serde_json::json!({"kind":"unavailable","message":"no server","data":null})
);
}
#[test]
fn older_tracked_push_rejections_need_no_report() {
let data: ErrorData = serde_json::from_str(
r#"{"type":"pushRejected","source":"main","upstream":"origin/main","divergence":null}"#,
)
.unwrap();
assert!(matches!(data, ErrorData::PushRejected { report: None, .. }));
}
}
+5 -2
View File
@@ -40,10 +40,11 @@ pub enum IdeEvent {
McpBackgroundProjectsChanged,
/// A window entered or left full screen, itself or as a member of a full-screen window group.
WindowFullscreenChanged,
/// This remote window's connection to its host ended on its own (network loss, the host or
/// its server went away); the window's project is unreachable until it reconnects.
/// This remote window's connection ended or another window took over the session.
RemoteConnectionLost {
host: String,
#[serde(default)]
taken_over: bool,
},
ProjectTrustChanged {
root: crate::IpcPath,
@@ -324,6 +325,8 @@ pub enum LspRefreshKind {
InlayHints,
SemanticTokens,
CodeLens,
/// An import or classpath update may have changed inheritance search results.
Inheritance,
/// The Dart server published a document's Flutter outline.
FlutterOutline,
}
@@ -71,6 +71,11 @@ pub struct SpellingSettings {
pub project_words: Vec<String>,
/// Custom dictionaries: plain word lists or Hunspell `.dic` files.
pub custom_dictionaries: Vec<String>,
/// Where "Save '…' to dictionary" writes: `project`, `application`, or a
/// `spelling.customDictionaries` entry verbatim; empty (the default) is
/// project when one is open, application otherwise.
#[specta(optional)]
pub default_dictionary: Option<String>,
}
/// Changes to one inspection; absent fields keep the inspection's defaults.
+122
View File
@@ -0,0 +1,122 @@
//! Binary arguments of IPC commands travel as base64 text: [`IpcBytes`] is a `Vec<u8>` that
//! serializes as a standard padded base64 string and is a plain `string` in the generated
//! bindings.
//!
//! A plain `Vec<u8>` is a JSON array of numbers, 3.6 times the size of the bytes, and parsing it
//! into a `serde_json::Value` (the remote protocol and Tauri both do) takes about 50 times the
//! bytes in memory: 20 MB become about 1 GB. Base64 is 1.33 times the size and one string.
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::ops::Deref;
/// A binary argument or result of an IPC command.
#[derive(Clone, Default, PartialEq, Eq, specta::Type)]
#[specta(transparent)]
pub struct IpcBytes(#[specta(type = String)] pub Vec<u8>);
impl IpcBytes {
pub fn into_vec(self) -> Vec<u8> {
self.0
}
}
impl fmt::Debug for IpcBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "IpcBytes({} bytes)", self.0.len())
}
}
impl Serialize for IpcBytes {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&STANDARD.encode(&self.0))
}
}
impl<'de> Deserialize<'de> for IpcBytes {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct Base64;
impl Visitor<'_> for Base64 {
type Value = IpcBytes;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a base64 string")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<IpcBytes, E> {
STANDARD.decode(v).map(IpcBytes).map_err(|e| E::custom(format!("invalid base64: {e}")))
}
}
d.deserialize_str(Base64)
}
}
impl Deref for IpcBytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.0
}
}
impl From<Vec<u8>> for IpcBytes {
fn from(bytes: Vec<u8>) -> Self {
Self(bytes)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{Value, json};
fn round_trip(bytes: Vec<u8>) {
let value = serde_json::to_value(IpcBytes(bytes.clone())).unwrap();
let text = value.as_str().expect("serializes as a string");
assert_eq!(text.len(), bytes.len().div_ceil(3) * 4);
assert_eq!(serde_json::from_value::<IpcBytes>(value).unwrap().into_vec(), bytes);
}
#[test]
fn round_trips_empty_every_byte_and_large_input() {
round_trip(Vec::new());
round_trip((0..=255).collect());
round_trip((0..=255).rev().cycle().take(5 * 1024 * 1024 + 1).collect());
}
#[test]
fn round_trips_through_a_json_document() {
let bytes: Vec<u8> = (0..=255).collect();
let text = serde_json::to_string(&json!({ "data": IpcBytes(bytes.clone()) })).unwrap();
#[derive(Deserialize)]
struct Args {
data: IpcBytes,
}
assert_eq!(serde_json::from_str::<Args>(&text).unwrap().data.into_vec(), bytes);
}
/// The old wire form of a `Vec<u8>`: 3.6 times the bytes. The string must stay near 4/3.
#[test]
fn serialized_form_is_a_string_about_a_third_larger_than_the_bytes() {
let bytes: Vec<u8> = (0..=255).cycle().take(1_000_000).collect();
let json = serde_json::to_string(&IpcBytes(bytes.clone())).unwrap();
assert!(json.starts_with('"') && json.ends_with('"'));
assert!(json.len() <= bytes.len().div_ceil(3) * 4 + 2, "{} bytes for {}", json.len(), bytes.len());
let as_array = serde_json::to_string(&bytes).unwrap();
assert!(json.len() * 2 < as_array.len(), "{} vs {}", json.len(), as_array.len());
}
#[test]
fn rejects_what_is_not_base64() {
for bad in [json!([1, 2, 3]), json!(7), Value::Null, json!("not base64!"), json!("QQ"), json!("QQ=a")] {
assert!(serde_json::from_value::<IpcBytes>(bad.clone()).is_err(), "{bad}");
}
}
#[test]
fn debug_does_not_print_the_bytes() {
assert_eq!(format!("{:?}", IpcBytes(vec![0; 3])), "IpcBytes(3 bytes)");
}
}
+54 -1
View File
@@ -40,6 +40,10 @@ pub fn strip(src: &str) -> String {
if prev == '*' && n == '/' {
break;
}
// Keep the comment's line breaks so parse errors report the original line.
if n == '\n' {
out.push('\n');
}
prev = n;
}
}
@@ -65,7 +69,7 @@ pub fn strip(src: &str) -> String {
in_str = true;
cleaned.push(c);
} else if c == ',' {
let next = bytes[i + 1..].iter().find(|ch| !ch.is_whitespace());
let next = bytes[i + 1..].iter().find(|ch| !ch.is_ascii_whitespace());
if !matches!(next, Some('}') | Some(']')) {
cleaned.push(c);
}
@@ -95,4 +99,53 @@ mod tests {
let v: serde_json::Value = serde_json::from_str(&strip("\u{feff}{ \"a\": 1 }")).unwrap();
assert_eq!(v["a"], 1);
}
#[test]
fn keeps_line_breaks_of_block_comments_so_errors_report_the_original_line() {
assert_eq!(strip("{\"a\"/*\n\n*/:x}"), "{\"a\"\n\n:x}");
let err = serde_json::from_str::<serde_json::Value>(&strip("{\"a\"/*\n\n*/:x}")).unwrap_err();
assert_eq!(err.line(), 3);
// A comment is whitespace, not a join: `1 2` stays invalid.
assert!(serde_json::from_str::<serde_json::Value>(&strip("1/*\n*/2")).is_err());
}
#[test]
fn line_comments_keep_their_line_break_and_may_end_the_input() {
assert_eq!(strip("{\"a\":1} // tail"), "{\"a\":1} ");
assert_eq!(strip("// a\r\n{\"a\":1}"), "\n{\"a\":1}");
assert_eq!(strip("[1, // c\n2]"), "[1, \n2]");
}
#[test]
fn unterminated_block_comment_drops_the_rest() {
assert_eq!(strip("{\"a\":1}/* open"), "{\"a\":1}");
assert_eq!(strip("/*"), "");
assert_eq!(strip("/*/ x"), "");
assert_eq!(strip("/**/{}"), "{}");
assert_eq!(strip("/***/{}"), "{}");
}
#[test]
fn comment_markers_inside_strings_survive_including_after_escapes() {
let src = "{\"a\":\"\\\\\",\"b\":\"//x\",\"c\":\"/*y*/\",\"d\":\"é,\u{1F600}\"} // é";
let v: serde_json::Value = serde_json::from_str(&strip(src)).unwrap();
assert_eq!(v, serde_json::json!({"a": "\\", "b": "//x", "c": "/*y*/", "d": "é,\u{1F600}"}));
}
#[test]
fn trailing_commas_are_dropped_across_whitespace_and_comments_only_before_a_closer() {
assert_eq!(strip("[1,2, ]"), "[1,2 ]");
assert_eq!(strip("[1,\r\n]"), "[1\r\n]");
assert_eq!(strip("[1,/*c*/]"), "[1]");
assert_eq!(strip("[1,//c\n]"), "[1\n]");
assert_eq!(strip("[1,/*c*/ ,]"), "[1, ]");
assert_eq!(strip("{\"a\":\"x,}\"}"), "{\"a\":\"x,}\"}");
assert_eq!(strip("[1,2]"), "[1,2]");
}
#[test]
fn only_json_whitespace_may_separate_a_trailing_comma_from_its_closer() {
// U+00A0 is not JSON whitespace: the comma stays and serde_json reports it.
assert_eq!(strip("[1,\u{a0}]"), "[1,\u{a0}]");
}
}
+4
View File
@@ -4,6 +4,7 @@
//! feature crates depend on `ide-core` and never on each other's internals.
//! All IPC-facing types derive `specta::Type`, which generates `src/bindings.ts`.
pub mod cli_process;
pub mod editor_settings;
pub mod error;
pub mod event;
@@ -12,6 +13,7 @@ pub mod ids;
pub mod ignored;
pub mod input;
pub mod inspection_settings;
pub mod ipc_bytes;
pub mod ipc_path;
pub mod java_runtime;
pub mod jsonc;
@@ -30,6 +32,7 @@ pub mod task;
pub mod text;
pub mod tool_path;
pub mod updates;
pub mod utf8;
pub mod version_managers;
pub mod workflow_settings;
pub mod wsl;
@@ -37,6 +40,7 @@ pub mod wsl;
pub use error::{IdeError, IdeResult};
pub use event::{EventSink, IdeEvent, NullSink, SharedSink};
pub use ids::*;
pub use ipc_bytes::IpcBytes;
pub use ipc_path::IpcPath;
pub use text::*;
pub use tokio_util::sync::CancellationToken;
+43
View File
@@ -5,6 +5,10 @@ use std::path::Path;
#[cfg(windows)]
use std::process::Stdio;
use std::process::{Child, Command};
pub const ASKPASS_PORT_ENV: &str = "OPENIDEA_ASKPASS_PORT";
/// The IDE's askpass helper may answer with saved credentials only.
pub const ASKPASS_SILENT_ENV: &str = "OPENIDEA_ASKPASS_SILENT";
use std::sync::{Arc, RwLock};
use std::time::Duration;
@@ -1330,6 +1334,45 @@ mod tests {
assert_eq!(cmd.get_envs().find(|(k, _)| *k == "PATH").and_then(|(_, v)| v), Some(OsStr::new("/custom")));
}
#[test]
fn unix_uses_the_name_as_is() {
assert_eq!(executable_names("kotlinc", false, Some(".BAT")), ["kotlinc"]);
}
#[test]
fn windows_appends_pathext_extensions() {
assert_eq!(
executable_names("kotlinc", true, None),
["kotlinc.com", "kotlinc.exe", "kotlinc.bat", "kotlinc.cmd"]
);
assert_eq!(executable_names("npx", true, Some(".EXE;.CMD;;")), ["npx.exe", "npx.cmd"]);
assert_eq!(executable_names("npx", true, Some(" ")), executable_names("npx", true, None));
// Already has an executable extension (any case): only that file.
assert_eq!(executable_names("rustc.EXE", true, None), ["rustc.EXE"]);
assert_eq!(executable_names("gradlew.bat", true, None), ["gradlew.bat"]);
// A dot that is not an executable extension (`clang++`, `python3.12`).
assert_eq!(executable_names("python3.12", true, Some(".EXE")), ["python3.12.exe"]);
}
#[test]
fn finds_batch_files_and_skips_extensionless_scripts_on_windows() {
let dir = tempfile::tempdir().unwrap();
let a = dir.path().join("a");
let b = dir.path().join("b");
std::fs::create_dir_all(&a).unwrap();
std::fs::create_dir_all(&b).unwrap();
// `node_modules/.bin` style: a POSIX script next to its `.cmd` shim.
std::fs::write(a.join("tsx"), "#!/bin/sh\n").unwrap();
std::fs::write(b.join("tsx.cmd"), "@echo off\n").unwrap();
std::fs::write(b.join("kotlinc.bat"), "@echo off\n").unwrap();
let search = std::env::join_paths([&a, &b]).unwrap();
assert_eq!(find_executable_in("tsx", &search, true, None), Some(b.join("tsx.cmd")));
assert_eq!(find_executable_in("kotlinc", &search, true, None), Some(b.join("kotlinc.bat")));
assert_eq!(find_executable_in("tsx", &search, false, None), Some(a.join("tsx")));
assert_eq!(find_executable_in("kotlinc", &search, false, None), None);
assert_eq!(find_executable_in("nope", &search, true, None), None);
}
#[test]
fn find_executable_finds_bare_names_on_the_given_path() {
let dir = tempfile::tempdir().unwrap();
+14
View File
@@ -4,6 +4,20 @@
use serde::{Deserialize, Serialize};
use specta::Type;
/// Tools › Remote Development. This is a user setting on the remote host.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct RemoteDevelopmentSettings {
/// Zero disables idle shutdown. Positive values from older configurations keep their meaning.
pub idle_timeout_minutes: u16,
}
impl Default for RemoteDevelopmentSettings {
fn default() -> Self {
Self { idle_timeout_minutes: 180 }
}
}
/// How an SSH connection authenticates.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+15 -1
View File
@@ -60,6 +60,7 @@ pub struct Settings {
pub spelling: SpellingSettings,
/// Tools › SSH Configurations.
pub ssh: SshSettings,
pub remote_development: RemoteDevelopmentSettings,
/// Build, Execution, Deployment › Deployment.
pub deployment: DeploymentSettings,
/// Build, Execution, Deployment › Run Targets.
@@ -578,6 +579,7 @@ impl Default for Settings {
inspections: InspectionSettings::default(),
spelling: SpellingSettings::default(),
ssh: SshSettings::default(),
remote_development: RemoteDevelopmentSettings::default(),
deployment: DeploymentSettings::default(),
run_targets: Vec::new(),
cmake: CMakeSettings::default(),
@@ -1208,6 +1210,7 @@ pub struct LanguagesSettings {
pub oxfmt: ExternalFormatterSettings,
pub biome: ExternalFormatterSettings,
pub ruff: ExternalFormatterSettings,
pub black: ExternalFormatterSettings,
pub java: JavaSettings,
pub ruby: RubySettings,
pub markdown: MarkdownSettings,
@@ -1235,6 +1238,10 @@ impl Default for LanguagesSettings {
languages: vec!["python".into()],
..ExternalFormatterSettings::default()
},
black: ExternalFormatterSettings {
languages: vec!["python".into()],
..ExternalFormatterSettings::default()
},
java: JavaSettings::default(),
ruby: RubySettings::default(),
markdown: MarkdownSettings::default(),
@@ -1304,6 +1311,7 @@ impl LanguagesSettings {
ExternalFormatter::Oxfmt => &self.oxfmt,
ExternalFormatter::Biome => &self.biome,
ExternalFormatter::Ruff => &self.ruff,
ExternalFormatter::Black => &self.black,
}
}
}
@@ -1316,6 +1324,7 @@ pub enum ExternalFormatter {
Oxfmt,
Biome,
Ruff,
Black,
}
impl ExternalFormatter {
@@ -1326,6 +1335,7 @@ impl ExternalFormatter {
Self::Oxfmt => "oxfmt",
Self::Biome => "biome",
Self::Ruff => "ruff",
Self::Black => "black",
}
}
}
@@ -1334,7 +1344,7 @@ impl ExternalFormatter {
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.
/// An external formatter (Prettier, oxfmt, Biome, Ruff, Black) and the languages it formats.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ExternalFormatterSettings {
@@ -1396,6 +1406,9 @@ pub struct PythonSettings {
pub hide_other_project_interpreters: bool,
/// Show each interpreter's path under its name on the interpreters page.
pub show_interpreter_paths: bool,
/// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
/// by interpreter executable; absolute or `~/`.
pub interpreter_paths: BTreeMap<String, Vec<String>>,
}
impl Default for PythonSettings {
@@ -1407,6 +1420,7 @@ impl Default for PythonSettings {
hidden_interpreters: Vec::new(),
hide_other_project_interpreters: false,
show_interpreter_paths: true,
interpreter_paths: BTreeMap::new(),
}
}
}
@@ -48,6 +48,7 @@ impl Utf8Decoder {
}
}
#[cfg(test)]
/// Convenience wrapper around [`Self::decode_into`].
pub fn decode(&mut self, bytes: &[u8]) -> String {
let mut out = String::new();
@@ -65,6 +66,7 @@ impl Utf8Decoder {
}
}
#[cfg(test)]
pub fn has_pending(&self) -> bool {
!self.pending.is_empty()
}
+90 -1
View File
@@ -11,6 +11,7 @@ use std::collections::BTreeMap;
pub struct VcsSettings {
/// Colour folders that contain changed files (project tree, tabs).
pub show_dirty_directories: bool,
pub create_changelists_automatically: bool,
/// Diffs the user opens show in an editor tab; off, in a separate window.
pub diff_as_editor_tab: bool,
/// Stop file history (Show History) after `history_limit` commits.
@@ -57,6 +58,7 @@ impl Default for VcsSettings {
Self {
// IDEA's VcsConfiguration.SHOW_DIRTY_RECURSIVELY is off by default.
show_dirty_directories: false,
create_changelists_automatically: false,
diff_as_editor_tab: true,
limit_history: true,
history_limit: 1000,
@@ -70,9 +72,66 @@ impl Default for VcsSettings {
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum EmptyCherryPickAction {
#[default]
Skip,
CreateEmpty,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum StashDiffTarget {
#[default]
Local,
Parent,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum GitSaveChangesPolicy {
#[default]
Shelve,
Stash,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum FetchTagsMode {
#[default]
Auto,
Sync,
Always,
Never,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum GitAnnotateMovement {
#[default]
None,
WithinFile,
AcrossFiles,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GitAnnotateSettings {
pub ignore_whitespace: bool,
pub movement: GitAnnotateMovement,
}
impl Default for GitAnnotateSettings {
fn default() -> Self {
Self { ignore_whitespace: true, movement: GitAnnotateMovement::None }
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GitSettings {
pub annotate: GitAnnotateSettings,
/// Show blame after the current editor line.
pub inline_blame: bool,
/// A click (or Enter / Space) on the inline blame label opens its commit; off, the
@@ -83,20 +142,29 @@ pub struct GitSettings {
pub sync_branch_operations: bool,
/// Path to the git executable; empty = auto-detect.
pub executable: String,
/// Clone all submodules along with the root repository.
pub clone_submodules: bool,
/// Default of Update Project: `merge` | `rebase`.
pub update_method: String,
/// Where Git operations keep local changes temporarily.
pub save_changes_policy: GitSaveChangesPolicy,
/// Push rejected (non-fast-forward): update the branch and push again.
pub auto_update_on_push_rejected: bool,
pub warn_crlf: bool,
pub warn_detached_head: bool,
/// Background check for incoming commits: `auto` | `always` | `never`.
/// Background check for incoming commits: `auto` | `always` | `check` | `never`.
pub incoming_check: String,
/// Minutes between background checks for incoming commits.
pub incoming_check_interval: u32,
/// How an explicit fetch or project update handles remote tags.
pub fetch_tags_mode: FetchTagsMode,
/// Branch name globs, `;`/`,`-separated; force push to them is prohibited.
pub protected_branches: String,
/// Initial state of Commit Options › Sign-off Commit.
pub sign_off: bool,
/// Add Git's origin line when cherry-picking commits from protected remote branches.
pub add_cherry_pick_origin: bool,
pub empty_cherry_pick: EmptyCherryPickAction,
/// Ask before committing files larger than `large_file_mb`.
pub warn_large_files: bool,
pub large_file_mb: u32,
@@ -108,6 +176,8 @@ pub struct GitSettings {
pub push_dialog_only_protected: bool,
/// Stashes and shelves share one tab.
pub combine_stash_and_shelf: bool,
/// What the stash browser compares its saved files against.
pub stash_diff_target: StashDiffTarget,
/// The non-modal Commit tool window works on the index: Staged / Unstaged groups,
/// stage and unstage instead of inclusion checkboxes, and no change lists.
pub staging_area: bool,
@@ -119,25 +189,32 @@ pub struct GitSettings {
impl Default for GitSettings {
fn default() -> Self {
Self {
annotate: GitAnnotateSettings::default(),
inline_blame: false,
inline_blame_clickable: true,
show_branch_in_project_view: false,
sync_branch_operations: true,
executable: String::new(),
clone_submodules: true,
update_method: "merge".into(),
save_changes_policy: GitSaveChangesPolicy::default(),
auto_update_on_push_rejected: false,
warn_crlf: true,
warn_detached_head: true,
incoming_check: "auto".into(),
incoming_check_interval: 15,
fetch_tags_mode: FetchTagsMode::Auto,
protected_branches: "master; main".into(),
sign_off: false,
add_cherry_pick_origin: true,
empty_cherry_pick: EmptyCherryPickAction::Skip,
warn_large_files: true,
large_file_mb: 50,
warn_bad_file_names: true,
show_push_dialog: true,
push_dialog_only_protected: false,
combine_stash_and_shelf: false,
stash_diff_target: StashDiffTarget::default(),
staging_area: false,
cli_status: false,
}
@@ -152,9 +229,11 @@ pub struct CommitSettings {
/// window and a Commit dialog.
pub non_modal: bool,
pub include_changes_by_default: bool,
pub commit_all_when_nothing_staged: bool,
/// Start with an empty message instead of the last one / the changelist's.
pub clear_initial_message: bool,
pub analyze_code: bool,
pub postpone_slow_checks: bool,
pub check_todo: bool,
pub reformat: bool,
pub optimize_imports: bool,
@@ -192,8 +271,10 @@ impl Default for CommitSettings {
Self {
non_modal: true,
include_changes_by_default: true,
commit_all_when_nothing_staged: true,
clear_initial_message: false,
analyze_code: true,
postpone_slow_checks: true,
check_todo: true,
reformat: false,
optimize_imports: false,
@@ -622,6 +703,14 @@ impl Default for AgentSecuritySettings {
mod tests {
use super::*;
#[test]
fn clone_submodules_defaults_on_and_can_be_disabled() {
let missing: GitSettings = serde_json::from_str("{}").unwrap();
let off: GitSettings = serde_json::from_str(r#"{"cloneSubmodules":false}"#).unwrap();
assert!(missing.clone_submodules);
assert!(!off.clone_submodules);
}
#[test]
fn git_settings_without_sync_key_execute_on_all_repositories() {
let missing: GitSettings = serde_json::from_str("{}").unwrap();
-1
View File
@@ -12,7 +12,6 @@ quick-xml = "0.42"
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
tracing.workspace = true
[dev-dependencies]
tempfile.workspace = true
+3 -9
View File
@@ -1752,9 +1752,7 @@ impl DebugManager {
let body = session.conn.request_timeout("continue", json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await?;
// DAP: a response without the flag continued every thread.
let all = body.get("allThreadsContinued").and_then(Value::as_bool).unwrap_or(true);
session.suspended.resumed(ticket, thread_id, all);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: all });
session.finish_resume(ticket, thread_id, all);
Ok(())
}
@@ -1801,9 +1799,7 @@ impl DebugManager {
let sent = session.conn.request_timeout(command, json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await;
step_settled(&session, sent)?;
// A step runs its thread; other threads stopped by their own events stay stopped.
session.suspended.resumed(ticket, thread_id, false);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: false });
session.finish_resume(ticket, thread_id, false);
Ok(())
}
@@ -1913,9 +1909,7 @@ impl DebugManager {
.request_timeout("stepIn", json!({ "threadId": thread_id, "targetId": target_id }), REQUEST_TIMEOUT)
.await;
step_settled(&session, sent)?;
session.suspended.resumed(ticket, thread_id, false);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: false });
session.finish_resume(ticket, thread_id, false);
Ok(())
}
+137 -16
View File
@@ -160,19 +160,36 @@ impl Stops {
}
/// Ends the stops taken by ticket `upto` of `thread`, or of every thread.
fn release(&mut self, thread: Option<i64>, every: bool, upto: u64) {
/// Returns whether any stop was removed.
fn release(&mut self, thread: Option<i64>, every: bool, upto: u64) -> bool {
let latest = self.latest();
let before = (self.all, self.threads.len());
if every || thread.is_none() || self.all.is_some_and(|t| t <= upto) {
self.all = self.all.filter(|&t| t > upto);
self.threads.retain(|&(_, t)| t > upto);
} else {
self.threads.retain(|&(id, t)| Some(id) != thread || t > upto);
}
let changed = (self.all, self.threads.len()) != before;
// Back on an earlier thread's stop, as the JDWP link moves to it with a new generation.
let now = self.latest();
if now.is_some() && now != latest {
self.ticket += 1;
}
changed
}
/// Whether a stop taken after `after` would be undone by a synthetic `continued` event for
/// `thread` (or for every thread when `every` is set).
fn superseded(&self, thread: i64, every: bool, after: u64) -> bool {
if self.all.is_some_and(|t| t > after) {
return true;
}
if every {
self.threads.iter().any(|&(_, t)| t > after)
} else {
self.threads.iter().any(|&(id, t)| id == thread && t > after)
}
}
}
@@ -197,12 +214,27 @@ impl Suspension {
}
}
/// A `continued` event; `all`: its `allThreadsContinued`.
pub fn continued(&self, thread: Option<i64>, all: bool) {
self.0.lock().release(thread, all, u64::MAX);
/// Runs `emit` under the suspension lock so a synthetic `continued` from a resume reply cannot
/// be emitted after a `stopped` event once that stop has been recorded.
pub fn emit_synced(&self, emit: impl FnOnce()) {
let _stops = self.0.lock();
emit();
}
/// Take before sending a resume-like request and pass to [`Self::resumed`].
/// A `continued` event; `all`: its `allThreadsContinued`. Runs `emit` under the same lock so
/// synthetic `continued` events from resume replies stay ordered against it.
pub fn continued_and_emit(&self, thread: Option<i64>, all: bool, emit: impl FnOnce()) {
let mut stops = self.0.lock();
stops.release(thread, all, u64::MAX);
emit();
}
#[cfg(test)]
pub fn continued(&self, thread: Option<i64>, all: bool) {
self.continued_and_emit(thread, all, || {});
}
/// Take before sending a resume-like request and pass to [`Self::resumed_and_emit`].
pub fn ticket(&self) -> u64 {
self.0.lock().ticket
}
@@ -215,8 +247,19 @@ impl Suspension {
}
/// After a successful resume-like request for `thread`; `all`: every thread ran.
/// Runs `emit` under the lock only when a prior stop was ended and no newer stop superseded it.
pub fn resumed_and_emit(&self, ticket: u64, thread: i64, all: bool, emit: impl FnOnce()) {
let mut stops = self.0.lock();
let superseded = stops.superseded(thread, all, ticket);
let released = stops.release(Some(thread), all, ticket);
if released && !superseded {
emit();
}
}
#[cfg(test)]
pub fn resumed(&self, ticket: u64, thread: i64, all: bool) {
self.0.lock().release(Some(thread), all, ticket);
self.resumed_and_emit(ticket, thread, all, || {});
}
}
@@ -316,6 +359,16 @@ impl Session {
self.owner.sink.emit(IdeEvent::Debug { session: self.id, event });
}
/// Completes a successful resume or step reply (`ticket` taken before the request): ends the
/// prior stops and emits a synthetic `continued` event unless an adapter event already ended
/// them or a newer `stopped` event superseded it.
pub(crate) fn finish_resume(&self, ticket: u64, thread_id: i64, all: bool) {
self.suspended.resumed_and_emit(ticket, thread_id, all, || {
self.emit(DebugEvent::Continued { thread_id, all_threads_continued: all });
});
crate::stream_trace::release_done(self);
}
/// `path` as sent to the adapter (resolved for [`RESOLVES_PATHS`] adapters).
pub fn adapter_path(&self, path: &Path) -> PathBuf {
if let Some(path) = self.kotlin_mirror.lock().as_ref().and_then(|m| m.adapter_path(path)) {
@@ -789,23 +842,26 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
reason = quirks.stop_reason(reason);
}
mgr.restore_breakpoints(s).await;
s.emit(DebugEvent::Stopped {
thread_id: int("threadId").unwrap_or(0),
reason,
description: str_("description").or_else(|| str_("text")),
all_threads_stopped: all,
s.suspended.emit_synced(|| {
s.emit(DebugEvent::Stopped {
thread_id: int("threadId").unwrap_or(0),
reason,
description: str_("description").or_else(|| str_("text")),
all_threads_stopped: all,
});
});
}
"continued" => {
let all = body.get("allThreadsContinued").and_then(Value::as_bool);
// DAP: an event without the flag continues its thread alone. The UI keeps treating
// it as all threads; the suspension, which holds only threads that stopped, need not.
s.suspended.continued(int("threadId"), all.unwrap_or(false));
crate::stream_trace::release_done(s);
s.emit(DebugEvent::Continued {
thread_id: int("threadId").unwrap_or(0),
all_threads_continued: all.unwrap_or(true),
s.suspended.continued_and_emit(int("threadId"), all.unwrap_or(false), || {
s.emit(DebugEvent::Continued {
thread_id: int("threadId").unwrap_or(0),
all_threads_continued: all.unwrap_or(true),
});
});
crate::stream_trace::release_done(s);
}
"output" => {
let category = str_("category").unwrap_or_else(|| "console".into());
@@ -1465,6 +1521,71 @@ mod tests {
assert!(!s.get());
}
#[test]
fn synthetic_continued_is_suppressed_when_a_newer_stop_or_continued_already_landed() {
let emit_if_resumed = |s: &Suspension, ticket, thread, all| {
let mut emitted = false;
s.resumed_and_emit(ticket, thread, all, || emitted = true);
emitted
};
// Normal step without an adapter `continued` event emits a synthetic one.
let s = Suspension::default();
s.stopped(Some(1), true);
assert!(emit_if_resumed(&s, s.ticket(), 1, false));
// Next `stopped` (all-threads or single-thread) overtakes the reply: no synthetic `continued`.
for next_all in [true, false] {
let s = Suspension::default();
s.stopped(Some(1), true);
let ticket = s.ticket();
s.stopped(Some(1), next_all);
assert!(!emit_if_resumed(&s, ticket, 1, false), "next_all={next_all}");
assert!(s.get());
}
// Adapter's own `continued` event already ended the stop: no duplicate synthetic `continued`.
let s = Suspension::default();
s.stopped(Some(1), true);
let ticket = s.ticket();
s.continued(Some(1), true);
assert!(!emit_if_resumed(&s, ticket, 1, true));
// Multi-thread: thread 7 steps while thread 9 stops alone -> thread 7 still emits `continued(all=false)`.
let s = two_threads_stopped();
let ticket = s.ticket();
s.stopped(Some(9), false);
assert!(emit_if_resumed(&s, ticket, 7, false));
assert!(s.get());
// Multi-thread: `continue(all=true)` while thread 9 stops alone -> suppressed so thread 9 stays paused.
let s = two_threads_stopped();
let ticket = s.ticket();
s.stopped(Some(9), false);
assert!(!emit_if_resumed(&s, ticket, 7, true));
assert!(s.get());
}
#[test]
fn concurrent_stop_and_resume_never_emit_continued_after_the_new_stop() {
for _ in 0..200 {
let s = std::sync::Arc::new(Suspension::default());
let log = std::sync::Arc::new(parking_lot::Mutex::new(Vec::<&'static str>::new()));
s.stopped(Some(1), true);
let ticket = s.ticket();
let s2 = s.clone();
let log2 = log.clone();
let stop = std::thread::spawn(move || {
s2.stopped(Some(1), false);
s2.emit_synced(|| log2.lock().push("stopped"));
});
s.resumed_and_emit(ticket, 1, false, || log.lock().push("continued"));
stop.join().unwrap();
let events = log.lock().clone();
assert!(events == ["continued", "stopped"] || events == ["stopped"], "unexpected order: {events:?}");
}
}
#[test]
fn kotlin_launch_starts_attach_listener_first() {
assert_eq!(
+107
View File
@@ -157,6 +157,11 @@ struct Script {
breakpoints_after_continue: usize,
/// The `reason` of the stop a `next` ends with (`step` when unset; kotlin-lsp says `breakpoint`).
step_reason: Option<&'static str>,
/// Send `stopped` before answering `next` / `stepIn` / `stepOut` / `continue` (like php-debug
/// when Xdebug finishes a step before the DAP reply is handled).
stop_before_reply: bool,
/// Send `continued` before answering `next` / `continue`.
continued_before_reply: bool,
/// Refuse `next`, then stop at a breakpoint (one the program hit meanwhile).
refuse_next: bool,
/// Send `invalidated { areas: ["variables"] }` right after the first `stopped` event.
@@ -213,6 +218,8 @@ impl Default for Script {
refuse_continue: false,
breakpoints_after_continue: 0,
step_reason: None,
stop_before_reply: false,
continued_before_reply: false,
refuse_next: false,
invalidated_after_stop: false,
stop_during_threads: false,
@@ -414,6 +421,19 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
tokio::time::sleep(Duration::from_millis(50)).await;
send!(json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1}}));
}
"next" if script.stop_before_reply => {
let reason = script.step_reason.unwrap_or("step");
send!(json!({"type": "event", "event": "stopped", "body": {"reason": reason, "threadId": 1}}));
tokio::time::sleep(Duration::from_millis(50)).await;
ok!(msg, Value::Null);
}
"next" if script.continued_before_reply => {
send!(
json!({"type": "event", "event": "continued", "body": {"threadId": 1, "allThreadsContinued": false}})
);
tokio::time::sleep(Duration::from_millis(50)).await;
ok!(msg, Value::Null);
}
"next" => {
ok!(msg, Value::Null);
let reason = script.step_reason.unwrap_or("step");
@@ -553,6 +573,20 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
"stepOut" if script.refuse_step_out => send!(
json!({"type": "response", "request_seq": msg["seq"], "command": "stepOut", "success": false, "message": "Thread is not suspended"})
),
"continue" if script.stop_before_reply => {
send!(
json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1, "allThreadsStopped": true}})
);
tokio::time::sleep(Duration::from_millis(50)).await;
ok!(msg, json!({"allThreadsContinued": true}));
}
"continue" if script.continued_before_reply => {
send!(
json!({"type": "event", "event": "continued", "body": {"threadId": 1, "allThreadsContinued": true}})
);
tokio::time::sleep(Duration::from_millis(50)).await;
ok!(msg, json!({"allThreadsContinued": true}));
}
"continue" if script.stop_after_continue => {
ok!(msg, json!({"allThreadsContinued": true}));
send!(
@@ -575,6 +609,11 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
send!(json!({"type": "event", "event": "stopped", "body": {"reason": reason, "threadId": thread}}));
}
}
"stepIn" | "stepOut" if script.stop_before_reply => {
send!(json!({"type": "event", "event": "stopped", "body": {"reason": "step", "threadId": 1}}));
tokio::time::sleep(Duration::from_millis(50)).await;
ok!(msg, Value::Null);
}
"stepIn" | "stepOut" | "pause" => ok!(msg, Value::Null),
"hotReload" => {
ok!(msg, Value::Null);
@@ -2789,6 +2828,74 @@ async fn step_of_one_thread_keeps_the_others_suspended() {
}
}
/// When an adapter emits the next `stopped` event before replying to `next` / `stepIn` / `stepOut`
/// / `continue` (as php-debug / Xdebug can on fast steps), no trailing synthetic `continued` may
/// overwrite the new stop.
#[tokio::test]
async fn stop_before_reply_does_not_emit_trailing_continued() {
let h = harness(Script { stop_before_reply: true, ..Script::default() });
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
let session = h.manager.session(id).unwrap();
let run_events = |from: usize| {
h.events
.lock()
.iter()
.skip(from)
.filter_map(|e| match e {
IdeEvent::Debug { event: DebugEvent::Stopped { reason, .. }, .. } => Some(format!("stopped:{reason}")),
IdeEvent::Debug { event: DebugEvent::Continued { .. }, .. } => Some("continued".into()),
_ => None,
})
.collect::<Vec<_>>()
};
for (label, expected) in [
("over", "stopped:step"),
("into", "stopped:step"),
("out", "stopped:step"),
("target", "stopped:step"),
("resume", "stopped:breakpoint"),
] {
let before = h.events.lock().len();
match label {
"over" => h.manager.step(id, 1, StepKind::Over).await.unwrap(),
"into" => h.manager.step(id, 1, StepKind::Into).await.unwrap(),
"out" => h.manager.step(id, 1, StepKind::Out).await.unwrap(),
"target" => h.manager.step_in_target(id, 1, 1).await.unwrap(),
"resume" => h.manager.resume(id, 1).await.unwrap(),
_ => unreachable!(),
}
assert!(session.suspended.get(), "{label}: session must remain suspended");
assert_eq!(run_events(before), [expected], "{label}: must not emit continued after stopped");
}
}
#[tokio::test]
async fn continued_event_before_reply_does_not_emit_duplicate_continued() {
for is_resume in [false, true] {
let h = harness(Script { continued_before_reply: true, ..Script::default() });
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
let before = h.events.lock().len();
if is_resume {
h.manager.resume(id, 1).await.unwrap();
} else {
h.manager.step(id, 1, StepKind::Over).await.unwrap();
}
let continued = h
.events
.lock()
.iter()
.skip(before)
.filter(|e| matches!(e, IdeEvent::Debug { event: DebugEvent::Continued { .. }, .. }))
.count();
assert_eq!(continued, 1, "is_resume={is_resume}: adapter continued event already reported it");
}
}
#[tokio::test]
async fn lazy_variables_are_resolved_when_the_adapter_declares_them_safe() {
let h = harness(Script::default());
-1
View File
@@ -27,7 +27,6 @@ tiberius.workspace = true
oracledb.workspace = true
bb8.workspace = true
tokio-util = { workspace = true, features = ["compat"] }
dirs.workspace = true
ide-ssh.workspace = true
ide-http.workspace = true
reqwest = { workspace = true, features = ["query"] }
-17
View File
@@ -46,23 +46,6 @@ pub fn databases(templates: bool) -> &'static str {
/// Databases of managed services that their users cannot use (hidden unless connected to).
pub const INTERNAL_DATABASES: &[&str] = &["rdsadmin", "azure_maintenance", "azure_sys", "cloudsqladmin"];
/// Oracle system accounts hidden unless `show_system` (see the Schemas tab).
pub const ORACLE_SYSTEM_SCHEMAS: &[&str] = &[
"CTXSYS",
"DBSFWUSER",
"DVSYS",
"GSMADMIN_INTERNAL",
"LBACSYS",
"MDDATA",
"MDSYS",
"OLAPSYS",
"OUTLN",
"SYS",
"SYSTEM",
"XDB",
"XS$NULL",
];
/// Databases available to this login; offline/restoring databases cannot be selected.
pub fn sqlserver_databases() -> &'static str {
"SELECT name FROM sys.databases WHERE state = 0 AND HAS_DBACCESS(name) = 1 ORDER BY name"
+28 -2
View File
@@ -143,6 +143,9 @@ pub struct DockerConnection {
pub id: String,
pub name: String,
pub endpoint: DockerEndpoint,
/// Whether the user explicitly disconnected this connection in Services.
#[serde(default)]
pub disconnected: bool,
}
/// A registry to log in to (Docker Hub, GHCR, a private one). The password is stored separately.
@@ -414,6 +417,7 @@ mod tests {
id: "c1".into(),
name: "Build box".into(),
endpoint: DockerEndpoint::Tcp { host: "build:2376".into(), tls_cert_dir: None },
disconnected: true,
}],
registries: vec![DockerRegistry {
id: "r1".into(),
@@ -435,12 +439,34 @@ mod tests {
assert!(load_settings(dir).connections.is_empty());
}
#[test]
fn connection_intent_defaults_to_connected_and_round_trips() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
std::fs::write(
dir.join(SETTINGS_FILE),
r#"{"connections":[{"id":"box","name":"Box","endpoint":{"kind":"ssh","config":"build"}}]}"#,
)
.unwrap();
let mut settings = load_settings(dir);
assert!(!settings.connections[0].disconnected);
for disconnected in [true, false] {
settings.connections[0].disconnected = disconnected;
save_settings(dir, &settings).unwrap();
assert_eq!(load_settings(dir), settings);
}
}
#[test]
fn load_drops_the_injected_default_connection() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
let injected =
|| DockerConnection { id: "default".into(), name: "Docker".into(), endpoint: DockerEndpoint::Default };
let injected = || DockerConnection {
id: "default".into(),
name: "Docker".into(),
endpoint: DockerEndpoint::Default,
disconnected: false,
};
let registry =
DockerRegistry { id: "r1".into(), name: "GHCR".into(), address: "ghcr.io".into(), username: "me".into() };
// Saved untouched by an older version (e.g. along with a registry): dropped on load.
+6 -1
View File
@@ -658,7 +658,12 @@ mod local_tests {
let batches = Mutex::new(Vec::<Vec<u32>>::new());
let result = batched(Duration::from_millis(30), &|b| batches.lock().unwrap().push(b), |line| {
(0..1000).for_each(line);
std::thread::sleep(Duration::from_millis(80));
// Wait for the flusher to emit the whole burst rather than assuming a fixed
// sleep outlasts its scheduling: a loaded runner can starve the thread
// past the quiet spell and fold the trailing line into the burst.
while batches.lock().unwrap().iter().map(Vec::len).sum::<usize>() < 1000 {
std::thread::sleep(Duration::from_millis(5));
}
line(1000);
"done"
});
+190 -154
View File
@@ -1,180 +1,216 @@
//! Child processes of the docker CLI: bounded runs and cancellable line streams.
//! The docker CLI as a child process: bounded runs and cancellable line streams.
use ide_core::process::terminate_tree;
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::io::Read;
use std::process::{Child, Command, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};
use ide_core::cli_process::{CliTool, Decoding, Input};
pub(crate) use ide_core::cli_process::{Output, Stream};
use ide_core::{CancellationToken, IdeResult};
use std::process::Command;
use std::time::Duration;
/// How long a cancelled or timed-out child's process group (CLI plugins such as compose)
/// gets to exit on `SIGTERM`, and clean up, before `SIGKILL`.
const KILL_GRACE: Duration = Duration::from_millis(20);
pub(crate) struct Output {
pub stdout: String,
pub stderr: String,
pub success: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Stream {
Stdout,
Stderr,
}
fn prepare(cmd: &mut Command) {
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
ide_core::process::prepare(ide_core::process::own_group(cmd));
}
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run docker: {e}")))
}
fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<String> {
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = pipe.read_to_end(&mut buf);
ide_core::output_encoding::decode_tool_output(&buf)
})
}
const DOCKER: CliTool = CliTool::new("docker", Decoding::ToolOutput);
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
/// a non-zero exit is reported in [`Output::success`], not as an error.
pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
run_with_input(cmd, timeout, cancel, None)
DOCKER.run(cmd, timeout, cancel)
}
/// [`run`] with `input` written to the child's stdin (e.g. `--password-stdin`).
pub(crate) fn run_with_input(
mut cmd: Command,
cmd: Command,
timeout: Duration,
cancel: Option<&CancellationToken>,
input: Option<&str>,
) -> IdeResult<Output> {
prepare(&mut cmd);
if input.is_some() {
cmd.stdin(Stdio::piped());
}
let mut child = spawn(&mut cmd)?;
if let (Some(text), Some(mut stdin)) = (input, child.stdin.take()) {
// Dropping `stdin` afterwards closes it, so the CLI sees EOF.
let _ = std::io::Write::write_all(&mut stdin, text.as_bytes());
}
let out = child.stdout.take().map(read_all);
let err = child.stderr.take().map(read_all);
let deadline = Instant::now() + timeout;
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_some_and(CancellationToken::is_cancelled) {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
if Instant::now() >= deadline {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::unavailable("docker did not respond in time"));
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(Output {
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
success: status.success(),
})
}
enum Event {
Line(Stream, String),
Closed,
}
fn spawn_reader(mut pipe: impl Read + Send + 'static, tx: mpsc::Sender<Event>, stream: Stream) {
std::thread::spawn(move || {
let mut buf = [0u8; 8192];
let mut pending: Vec<u8> = Vec::new();
let flush = |pending: &mut Vec<u8>| {
if !pending.is_empty() {
let line = ide_core::output_encoding::decode_tool_output(pending).trim_end().to_string();
pending.clear();
let _ = tx.send(Event::Line(stream, line));
}
};
loop {
match pipe.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
for &b in &buf[..n] {
// `\r` too: pull / build progress rewrites its line in place.
if b == b'\n' || b == b'\r' {
flush(&mut pending);
} else {
pending.push(b);
}
}
}
}
}
flush(&mut pending);
let _ = tx.send(Event::Closed);
});
DOCKER.run_with_input(cmd, input.map(Input::Inline), timeout, cancel)
}
/// Runs `cmd`, handing every output line to `on_line` until it exits or `cancel`
/// fires. Returns whether it exited successfully plus the last stderr lines.
pub(crate) fn stream(
mut cmd: Command,
cmd: Command,
cancel: &CancellationToken,
on_line: &mut dyn FnMut(Stream, String),
) -> IdeResult<(bool, Vec<String>)> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
prepare(&mut cmd);
let mut child = spawn(&mut cmd)?;
let (tx, rx) = mpsc::channel::<Event>();
let mut open = 0;
if let Some(out) = child.stdout.take() {
spawn_reader(out, tx.clone(), Stream::Stdout);
open += 1;
}
if let Some(err) = child.stderr.take() {
spawn_reader(err, tx.clone(), Stream::Stderr);
open += 1;
}
drop(tx);
let mut stderr_tail: Vec<String> = Vec::new();
while open > 0 {
if cancel.is_cancelled() {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
match rx.recv_timeout(Duration::from_millis(50)) {
Ok(Event::Line(stream, line)) => {
if stream == Stream::Stderr && !line.trim().is_empty() {
stderr_tail.push(line.clone());
if stderr_tail.len() > 20 {
stderr_tail.remove(0);
}
}
on_line(stream, line);
DOCKER.stream(cmd, cancel, on_line)
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use ide_core::error::ErrorKind;
use ide_core::process::process_alive;
use std::time::Instant;
const LONG: Duration = Duration::from_secs(30);
fn sh(script: &str) -> Command {
let mut cmd = Command::new("sh");
cmd.args(["-c", script]);
cmd
}
/// A script that records its pid in `name`'s file, then runs `rest`.
fn recording_pid(name: &str, rest: &str) -> (Command, std::path::PathBuf) {
let file = std::env::temp_dir().join(format!("openidea-process-{}-{name}", std::process::id()));
let _ = std::fs::remove_file(&file);
(sh(&format!("echo $$ > '{0}.tmp' && mv '{0}.tmp' '{0}'; {rest}", file.display())), file)
}
fn recorded_pid(file: &std::path::Path) -> u32 {
let pid = std::fs::read_to_string(file).unwrap().trim().parse().unwrap();
let _ = std::fs::remove_file(file);
pid
}
/// Cancels `cancel` once the script has recorded its pid.
fn cancel_when_recorded(file: &std::path::Path, cancel: &CancellationToken) {
let (file, cancel) = (file.to_owned(), cancel.clone());
std::thread::spawn(move || {
while !file.exists() {
std::thread::sleep(Duration::from_millis(5));
}
Ok(Event::Closed) => open -= 1,
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => break,
cancel.cancel();
});
}
fn assert_gone(pid: u32) {
let deadline = Instant::now() + Duration::from_secs(5);
while process_alive(pid) {
assert!(Instant::now() < deadline, "process {pid} survived");
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn the_exit_status_is_reported_not_raised() {
assert!(run(sh("exit 0"), LONG, None).unwrap().success);
assert!(!run(sh("exit 3"), LONG, None).unwrap().success);
}
#[test]
fn both_streams_are_captured_separately_and_in_order() {
let out = run(sh("printf 'a\\nb\\nc\\n'; printf 'x\\ny\\n' >&2"), LONG, None).unwrap();
assert_eq!(out.stdout, "a\nb\nc\n");
assert_eq!(out.stderr, "x\ny\n");
assert!(out.success);
}
#[test]
fn invalid_utf8_is_replaced_in_collected_output() {
let out = run(sh("printf 'ok\\n\\377\\n'; printf 'a\\377b' >&2"), LONG, None).unwrap();
assert_eq!(out.stdout, "ok\n\u{FFFD}\n");
assert_eq!(out.stderr, "a\u{FFFD}b");
}
#[test]
fn without_input_stdin_is_closed() {
assert_eq!(run(sh("cat; echo done"), LONG, None).unwrap().stdout, "done\n");
}
#[test]
fn input_reaches_the_child_stdin_and_is_then_closed() {
let out = run_with_input(sh("cat"), LONG, None, Some("secret\nmore")).unwrap();
assert_eq!(out.stdout, "secret\nmore");
assert!(out.success);
}
#[test]
fn a_missing_program_is_unavailable() {
let err = run(Command::new("/nonexistent/openidea-docker"), LONG, None).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "could not run docker: No such file or directory (os error 2)");
}
#[test]
fn a_run_past_its_timeout_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("docker-timeout", "exec sleep 30");
let err = run(cmd, Duration::from_secs(1), None).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "docker did not respond in time");
assert_gone(recorded_pid(&file));
}
#[test]
fn a_cancelled_run_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("docker-cancel", "exec sleep 30");
let cancel = CancellationToken::new();
cancel_when_recorded(&file, &cancel);
let err = run(cmd, LONG, Some(&cancel)).err().unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
assert_gone(recorded_pid(&file));
}
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_cancelled() {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
std::thread::sleep(Duration::from_millis(10));
};
Ok((status.success(), stderr_tail))
fn collect(script: &str) -> (bool, Vec<(Stream, String)>, Vec<String>) {
let mut lines = Vec::new();
let (ok, tail) = stream(sh(script), &CancellationToken::new(), &mut |s, l| lines.push((s, l))).unwrap();
(ok, lines, tail)
}
fn of(lines: &[(Stream, String)], which: Stream) -> Vec<&str> {
lines.iter().filter(|(s, _)| *s == which).map(|(_, l)| l.as_str()).collect()
}
#[test]
fn a_stream_splits_lines_at_lf_cr_and_crlf_and_trims_their_ends() {
let (ok, lines, _) = collect("printf 'a\\nb\\r\\nc\\rd \\n\\n\\ne'");
assert!(ok);
assert_eq!(of(&lines, Stream::Stdout), ["a", "b", "c", "d", "e"]);
assert!(of(&lines, Stream::Stderr).is_empty());
}
#[test]
fn a_stream_labels_each_line_with_its_pipe() {
let (_, lines, _) = collect("echo out1; echo err1 >&2; echo out2");
assert_eq!(of(&lines, Stream::Stdout), ["out1", "out2"]);
assert_eq!(of(&lines, Stream::Stderr), ["err1"]);
}
#[test]
fn a_stream_reports_the_exit_status() {
assert!(collect("exit 0").0);
assert!(!collect("exit 2").0);
}
#[test]
fn a_stream_replaces_invalid_utf8() {
let (_, lines, _) = collect("printf 'a\\377b\\n'");
assert_eq!(of(&lines, Stream::Stdout), ["a\u{FFFD}b"]);
}
#[test]
fn a_stream_keeps_the_last_twenty_non_blank_stderr_lines() {
let (_, lines, tail) = collect("echo ' ' >&2; i=1; while [ $i -le 25 ]; do echo e$i >&2; i=$((i+1)); done");
let expected: Vec<String> = (6..=25).map(|i| format!("e{i}")).collect();
assert_eq!(tail, expected);
assert_eq!(of(&lines, Stream::Stderr).len(), 26, "blank lines are still handed over");
}
#[test]
fn a_stream_cancelled_before_it_starts_does_not_spawn() {
let cancel = CancellationToken::new();
cancel.cancel();
let err = stream(Command::new("/nonexistent/openidea-docker"), &cancel, &mut |_, _| {}).err().unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
}
#[test]
fn a_stream_cancelled_while_running_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("docker-stream-cancel", "echo started; exec sleep 30");
let cancel = CancellationToken::new();
let err = stream(cmd, &cancel, &mut |_, _| cancel.cancel()).err().unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
assert_gone(recorded_pid(&file));
}
#[test]
fn a_missing_program_cannot_be_streamed() {
let err = stream(Command::new("/nonexistent/openidea-docker"), &CancellationToken::new(), &mut |_, _| {})
.err()
.unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "could not run docker: No such file or directory (os error 2)");
}
}
-1
View File
@@ -6,7 +6,6 @@ edition.workspace = true
license.workspace = true
[dependencies]
ide-core.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
-4
View File
@@ -382,10 +382,6 @@ impl Ledger {
}
grant.binaries.get(&key).cloned()
}
pub fn subjects(&self) -> impl Iterator<Item = (&Subject, &Grant)> {
self.grants.iter()
}
}
/// What a confirmation page shows: every capability with its risk, high risk first.
-4
View File
@@ -116,10 +116,6 @@ impl ExtensionRegistry {
Ok(())
}
pub fn point_ids(&self) -> Vec<&'static str> {
self.points.read().keys().copied().collect()
}
pub fn placement(&self, point: &str) -> Option<Placement> {
self.points.read().get(point).map(|p| p.placement())
}
+196 -158
View File
@@ -1,184 +1,222 @@
//! Child processes of the gh CLI: bounded runs and cancellable line streams.
//! The gh CLI as a child process: bounded runs and cancellable line streams.
use ide_core::process::terminate_tree;
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::io::Read;
use std::process::{Child, Command, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};
use ide_core::cli_process::{CliTool, Decoding, Input};
pub(crate) use ide_core::cli_process::{Output, Stream};
use ide_core::{CancellationToken, IdeResult};
use std::process::Command;
use std::time::Duration;
/// How long a cancelled or timed-out child's process group (gh spawns git and helpers)
/// gets to exit on `SIGTERM` before `SIGKILL`: git removes its lock files on `SIGTERM`.
const KILL_GRACE: Duration = Duration::from_millis(20);
pub(crate) struct Output {
pub stdout: String,
pub stderr: String,
pub success: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Stream {
Stdout,
Stderr,
}
fn prepare(cmd: &mut Command) {
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
ide_core::process::prepare(ide_core::process::own_group(cmd));
}
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run gh: {e}")))
}
fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<String> {
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = pipe.read_to_end(&mut buf);
String::from_utf8_lossy(&buf).into_owned()
})
}
const GH: CliTool = CliTool::new("gh", Decoding::Utf8Lossy);
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
/// a non-zero exit is reported in [`Output::success`], not as an error.
pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
run_with_input(cmd, None, timeout, cancel)
GH.run(cmd, timeout, cancel)
}
/// [`run`] with `input` written to the child's stdin (then closed).
pub(crate) fn run_with_input(
mut cmd: Command,
cmd: Command,
input: Option<&str>,
timeout: Duration,
cancel: Option<&CancellationToken>,
) -> IdeResult<Output> {
prepare(&mut cmd);
if input.is_some() {
cmd.stdin(Stdio::piped());
}
let mut child = spawn(&mut cmd)?;
if let (Some(input), Some(mut stdin)) = (input, child.stdin.take()) {
let input = input.to_owned();
// A writer thread: a large body must not block on a full pipe while gh is not reading yet.
std::thread::spawn(move || {
use std::io::Write;
let _ = stdin.write_all(input.as_bytes());
});
}
let out = child.stdout.take().map(read_all);
let err = child.stderr.take().map(read_all);
let deadline = Instant::now() + timeout;
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_some_and(CancellationToken::is_cancelled) {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
if Instant::now() >= deadline {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::unavailable("gh did not respond in time"));
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(Output {
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
success: status.success(),
})
}
enum Event {
Line(Stream, String),
Closed,
}
fn spawn_reader(mut pipe: impl Read + Send + 'static, tx: mpsc::Sender<Event>, stream: Stream) {
std::thread::spawn(move || {
let mut buf = [0u8; 8192];
let mut pending: Vec<u8> = Vec::new();
let flush = |pending: &mut Vec<u8>| {
if !pending.is_empty() {
let line = String::from_utf8_lossy(pending).trim_end().to_string();
pending.clear();
let _ = tx.send(Event::Line(stream, line));
}
};
loop {
match pipe.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
for &b in &buf[..n] {
// `\r` too: git progress rewrites its line in place.
if b == b'\n' || b == b'\r' {
flush(&mut pending);
} else {
pending.push(b);
}
}
}
}
}
flush(&mut pending);
let _ = tx.send(Event::Closed);
});
GH.run_with_input(cmd, input.map(Input::Threaded), timeout, cancel)
}
/// Runs `cmd`, handing every output line to `on_line` until it exits or `cancel`
/// fires. Returns whether it exited successfully plus the last stderr lines.
pub(crate) fn stream(
mut cmd: Command,
cmd: Command,
cancel: &CancellationToken,
on_line: &mut dyn FnMut(Stream, String),
) -> IdeResult<(bool, Vec<String>)> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
prepare(&mut cmd);
let mut child = spawn(&mut cmd)?;
let (tx, rx) = mpsc::channel::<Event>();
let mut open = 0;
if let Some(out) = child.stdout.take() {
spawn_reader(out, tx.clone(), Stream::Stdout);
open += 1;
}
if let Some(err) = child.stderr.take() {
spawn_reader(err, tx.clone(), Stream::Stderr);
open += 1;
}
drop(tx);
let mut stderr_tail: Vec<String> = Vec::new();
while open > 0 {
if cancel.is_cancelled() {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
match rx.recv_timeout(Duration::from_millis(50)) {
Ok(Event::Line(stream, line)) => {
if stream == Stream::Stderr && !line.trim().is_empty() {
stderr_tail.push(line.clone());
if stderr_tail.len() > 20 {
stderr_tail.remove(0);
}
}
on_line(stream, line);
GH.stream(cmd, cancel, on_line)
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use ide_core::error::ErrorKind;
use ide_core::process::process_alive;
use std::time::Instant;
const LONG: Duration = Duration::from_secs(30);
fn sh(script: &str) -> Command {
let mut cmd = Command::new("sh");
cmd.args(["-c", script]);
cmd
}
/// A script that records its pid in `name`'s file, then runs `rest`.
fn recording_pid(name: &str, rest: &str) -> (Command, std::path::PathBuf) {
let file = std::env::temp_dir().join(format!("openidea-process-{}-{name}", std::process::id()));
let _ = std::fs::remove_file(&file);
(sh(&format!("echo $$ > '{0}.tmp' && mv '{0}.tmp' '{0}'; {rest}", file.display())), file)
}
fn recorded_pid(file: &std::path::Path) -> u32 {
let pid = std::fs::read_to_string(file).unwrap().trim().parse().unwrap();
let _ = std::fs::remove_file(file);
pid
}
/// Cancels `cancel` once the script has recorded its pid.
fn cancel_when_recorded(file: &std::path::Path, cancel: &CancellationToken) {
let (file, cancel) = (file.to_owned(), cancel.clone());
std::thread::spawn(move || {
while !file.exists() {
std::thread::sleep(Duration::from_millis(5));
}
Ok(Event::Closed) => open -= 1,
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => break,
cancel.cancel();
});
}
fn assert_gone(pid: u32) {
let deadline = Instant::now() + Duration::from_secs(5);
while process_alive(pid) {
assert!(Instant::now() < deadline, "process {pid} survived");
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn the_exit_status_is_reported_not_raised() {
assert!(run(sh("exit 0"), LONG, None).unwrap().success);
assert!(!run(sh("exit 3"), LONG, None).unwrap().success);
}
#[test]
fn both_streams_are_captured_separately_and_in_order() {
let out = run(sh("printf 'a\\nb\\nc\\n'; printf 'x\\ny\\n' >&2"), LONG, None).unwrap();
assert_eq!(out.stdout, "a\nb\nc\n");
assert_eq!(out.stderr, "x\ny\n");
assert!(out.success);
}
#[test]
fn invalid_utf8_is_replaced_in_collected_output() {
let out = run(sh("printf 'ok\\n\\377\\n'; printf 'a\\377b' >&2"), LONG, None).unwrap();
assert_eq!(out.stdout, "ok\n\u{FFFD}\n");
assert_eq!(out.stderr, "a\u{FFFD}b");
}
#[test]
fn without_input_stdin_is_closed() {
assert_eq!(run(sh("cat; echo done"), LONG, None).unwrap().stdout, "done\n");
}
#[test]
fn input_reaches_the_child_stdin_and_is_then_closed() {
let out = run_with_input(sh("cat"), Some("secret\nmore"), LONG, None).unwrap();
assert_eq!(out.stdout, "secret\nmore");
assert!(out.success);
}
#[test]
fn a_body_larger_than_the_pipe_does_not_block_the_child_output() {
let body = "0123456789abcdef".repeat(64 * 1024);
let out = run_with_input(sh("cat"), Some(&body), LONG, None).unwrap();
assert_eq!(out.stdout.len(), body.len());
}
#[test]
fn a_missing_program_is_unavailable() {
let err = run(Command::new("/nonexistent/openidea-gh"), LONG, None).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "could not run gh: No such file or directory (os error 2)");
}
#[test]
fn a_run_past_its_timeout_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("gh-timeout", "exec sleep 30");
let err = run(cmd, Duration::from_secs(1), None).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "gh did not respond in time");
assert_gone(recorded_pid(&file));
}
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_cancelled() {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
std::thread::sleep(Duration::from_millis(10));
};
Ok((status.success(), stderr_tail))
#[test]
fn a_cancelled_run_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("gh-cancel", "exec sleep 30");
let cancel = CancellationToken::new();
cancel_when_recorded(&file, &cancel);
let err = run(cmd, LONG, Some(&cancel)).err().unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
assert_gone(recorded_pid(&file));
}
fn collect(script: &str) -> (bool, Vec<(Stream, String)>, Vec<String>) {
let mut lines = Vec::new();
let (ok, tail) = stream(sh(script), &CancellationToken::new(), &mut |s, l| lines.push((s, l))).unwrap();
(ok, lines, tail)
}
fn of(lines: &[(Stream, String)], which: Stream) -> Vec<&str> {
lines.iter().filter(|(s, _)| *s == which).map(|(_, l)| l.as_str()).collect()
}
#[test]
fn a_stream_splits_lines_at_lf_cr_and_crlf_and_trims_their_ends() {
let (ok, lines, _) = collect("printf 'a\\nb\\r\\nc\\rd \\n\\n\\ne'");
assert!(ok);
assert_eq!(of(&lines, Stream::Stdout), ["a", "b", "c", "d", "e"]);
assert!(of(&lines, Stream::Stderr).is_empty());
}
#[test]
fn a_stream_labels_each_line_with_its_pipe() {
let (_, lines, _) = collect("echo out1; echo err1 >&2; echo out2");
assert_eq!(of(&lines, Stream::Stdout), ["out1", "out2"]);
assert_eq!(of(&lines, Stream::Stderr), ["err1"]);
}
#[test]
fn a_stream_reports_the_exit_status() {
assert!(collect("exit 0").0);
assert!(!collect("exit 2").0);
}
#[test]
fn a_stream_replaces_invalid_utf8() {
let (_, lines, _) = collect("printf 'a\\377b\\n'");
assert_eq!(of(&lines, Stream::Stdout), ["a\u{FFFD}b"]);
}
#[test]
fn a_stream_keeps_the_last_twenty_non_blank_stderr_lines() {
let (_, lines, tail) = collect("echo ' ' >&2; i=1; while [ $i -le 25 ]; do echo e$i >&2; i=$((i+1)); done");
let expected: Vec<String> = (6..=25).map(|i| format!("e{i}")).collect();
assert_eq!(tail, expected);
assert_eq!(of(&lines, Stream::Stderr).len(), 26, "blank lines are still handed over");
}
#[test]
fn a_stream_cancelled_before_it_starts_does_not_spawn() {
let cancel = CancellationToken::new();
cancel.cancel();
let err = stream(Command::new("/nonexistent/openidea-gh"), &cancel, &mut |_, _| {}).err().unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
}
#[test]
fn a_stream_cancelled_while_running_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("gh-stream-cancel", "echo started; exec sleep 30");
let cancel = CancellationToken::new();
let err = stream(cmd, &cancel, &mut |_, _| cancel.cancel()).err().unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
assert_gone(recorded_pid(&file));
}
#[test]
fn a_missing_program_cannot_be_streamed() {
let err =
stream(Command::new("/nonexistent/openidea-gh"), &CancellationToken::new(), &mut |_, _| {}).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "could not run gh: No such file or directory (os error 2)");
}
}
+6
View File
@@ -18,7 +18,13 @@ uuid.workspace = true
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[features]
# `testing`: the `.hprof` fixture builders, for tests and benches of this crate and of crates built on it.
testing = []
[dev-dependencies]
# Self dev-dependency: turns `testing` on for this crate's benches, so a plain `cargo bench -p ide-heap` builds them.
ide-heap = { workspace = true, features = ["testing"] }
criterion = { version = "0.5", default-features = false }
proptest.workspace = true
tempfile.workspace = true
+1 -1
View File
@@ -20,7 +20,7 @@ mod strings;
#[cfg(test)]
mod test_index;
/// Fixture builders shared by this crate's tests and by dependants' tests and benches; not API.
#[doc(hidden)]
#[cfg(any(test, feature = "testing"))]
pub mod testing;
pub use analysis::{AnalyzeOptions, analyze};
+1
View File
@@ -78,6 +78,7 @@ zip.workspace = true
quick-xml = "0.42"
[dev-dependencies]
ide-heap = { workspace = true, features = ["testing"] }
ide-ssh = { workspace = true, features = ["testing"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "io-util", "test-util"] }
criterion = { version = "0.5", default-features = false }
+1 -1
View File
@@ -33,7 +33,7 @@ impl AgentSecrets {
)
}
pub fn with_store(store: SecretFile, local: PathBuf) -> Self {
fn with_store(store: SecretFile, local: PathBuf) -> Self {
Self { store, local, lock: Mutex::new(()) }
}
+138 -39
View File
@@ -1,5 +1,6 @@
//! `openidea-server --stdio`: the IDE backend for remote development, serving
//! one desktop client over stdin / stdout (started by the client over SSH).
//! `openidea-server`: the IDE backend for remote development, either serving one
//! desktop client over stdin / stdout (`--stdio`) or running as a persistent
//! per-project daemon (`--attach <project>`).
use ide_host::catalogue::TrustClass;
use ide_host::plugins::remote::{RemotePluginLanguages, SYNC_COMMAND};
@@ -10,6 +11,12 @@ use ide_language::LanguageRegistry;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
enum Mode {
Stdio,
#[cfg(unix)]
Daemon(PathBuf, ide_host::daemon::BuildId),
}
fn main() {
let raw_args: Vec<String> = std::env::args().collect();
if let Some(project) = ide_mcp::stdio_request(&raw_args) {
@@ -35,18 +42,48 @@ fn main() {
};
std::process::exit(code);
}
if !args.iter().any(|a| a == "--stdio") {
eprintln!(
"usage: openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <port> | --version"
);
std::process::exit(2);
let base = server_home();
#[cfg(unix)]
if args.first().is_some_and(|a| a == "--attach") {
let Some(project_path) = args.get(1).filter(|p| !p.is_empty()) else {
eprintln!("usage: openidea-server --attach <project-path>");
std::process::exit(2);
};
let home = dirs::home_dir().unwrap_or_default();
let code =
match ide_host::daemon::attach(&base, &home, project_path, std::io::stdin(), std::io::stdout().lock()) {
Ok(()) => 0,
Err(e) => {
eprintln!("{e}");
1
}
};
std::process::exit(code);
}
let mode = match args.as_slice() {
#[cfg(unix)]
[flag, sock, build] if flag == "--daemon" => {
let Ok(build) = build.as_bytes().try_into() else {
eprintln!("invalid daemon build identifier");
std::process::exit(2);
};
Mode::Daemon(PathBuf::from(sock), build)
}
#[cfg(not(unix))]
[flag, _] if flag == "--attach" => Mode::Stdio,
_ if args.iter().any(|a| a == "--stdio") => Mode::Stdio,
_ => {
eprintln!(
"usage: openidea-server --stdio | --attach <project-path> | --mcp-stdio [--project <path>] | --connect <host> <port> | --version"
);
std::process::exit(2);
}
};
// stdout carries the protocol: logs go to stderr.
tracing_subscriber::fmt()
.with_writer(std::io::stderr)
.with_env_filter(tracing_subscriber::EnvFilter::try_from_env("OPENIDEA_LOG").unwrap_or_else(|_| "info".into()))
.init();
let base = server_home();
// An SSH exec channel gets a minimal environment: take the login shell's, read
// afresh on every start, plus the IDE-managed tools. Before any other thread starts.
ide_host::shell_env::inherit_login_shell_env("openidea-server");
@@ -55,7 +92,7 @@ fn main() {
ide_dap::adapter::set_tools_root(ide_tools::tools_dir(&data_dir));
ide_sdk::java::add_jdk_root(&ide_tools::jdk::jdks_dir(&data_dir));
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().expect("tokio runtime");
let code = runtime.block_on(run(base));
let code = runtime.block_on(run(base, mode));
std::process::exit(code);
}
@@ -64,7 +101,7 @@ fn server_home() -> PathBuf {
std::env::var_os("OPENIDEA_SERVER_HOME").map(PathBuf::from).unwrap_or_else(|| home.join(".openidea"))
}
async fn run(base: PathBuf) -> i32 {
async fn run(base: PathBuf, mode: Mode) -> i32 {
let (config_dir, data_dir) = (base.join("config"), base.join("data"));
for dir in [&config_dir, &data_dir] {
if let Err(e) = std::fs::create_dir_all(dir) {
@@ -82,40 +119,103 @@ async fn run(base: PathBuf) -> i32 {
// The desktop's plugin languages (`plugin_sync_languages`); programs pinned on this machine.
let plugin_languages = RemotePluginLanguages::new(Some(&data_dir));
languages.attach_plugins(plugin_languages.store().clone());
let peer = Arc::new(OnceLock::new());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
// A stable path for `--mcp-stdio` client configurations across server upgrades.
match mode {
Mode::Stdio => {
let peer = Arc::new(OnceLock::new());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
start_mcp(&host, &base);
let plugins = start_plugins(&plugins_data, &host, peer.clone());
inherit_trust(&host);
tracing::info!("openidea-server {} ready", env!("CARGO_PKG_VERSION"));
let dispatcher = build_dispatcher(&plugins, plugin_languages);
rpc::serve(host.clone(), dispatcher, peer, tokio::io::stdin(), tokio::io::stdout()).await;
shutdown_all(&host, plugins.as_ref()).await;
0
}
#[cfg(unix)]
Mode::Daemon(socket, build) => {
let peer = Arc::new(rpc::PeerSlot::default());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
start_mcp(&host, &base);
let plugins = start_plugins(&plugins_data, &host, peer.clone());
inherit_trust(&host);
tracing::info!("openidea-server {} daemon ready at {}", env!("CARGO_PKG_VERSION"), socket.display());
let dispatcher = build_dispatcher(&plugins, plugin_languages);
let result = ide_host::daemon::serve(
&socket,
build,
host.clone(),
dispatcher,
peer,
shutdown_all(&host, plugins.as_ref()),
)
.await;
match result {
Ok(()) => 0,
Err(e) => {
eprintln!("daemon error: {e}");
1
}
}
}
}
}
fn start_mcp(host: &Arc<Host>, base: &std::path::Path) {
host.mcp.set_stdio_link(base.join("bin").join("openidea-server"));
host.mcp_background.serve_none();
host.mcp.apply(&host);
// The desktop's code plugins run here, next to the project (`plugin_sync_packages`).
let plugins = match RemotePlugins::start(&plugins_data, &host, peer.clone()) {
host.mcp.apply(host);
}
fn start_plugins<P: rpc::PeerHandle>(
plugins_data: &std::path::Path,
host: &Arc<Host>,
peer: Arc<P>,
) -> Option<Arc<RemotePlugins>> {
match RemotePlugins::start(plugins_data, host, peer) {
Ok(p) => Some(p),
Err(e) => {
tracing::warn!("plugins are unavailable: {e}");
None
}
};
}
}
fn inherit_trust(host: &Host) {
if let Some(root) = std::env::var_os(ide_host::trust::TRUSTED_ROOT_ENV)
&& let Err(e) = host.trust.inherit(std::path::Path::new(&root))
{
tracing::warn!("cannot trust {}: {e}", root.to_string_lossy());
}
tracing::info!("openidea-server {} ready", env!("CARGO_PKG_VERSION"));
}
fn build_dispatcher(plugins: &Option<Arc<RemotePlugins>>, plugin_languages: Arc<RemotePluginLanguages>) -> Dispatcher {
let mut dispatcher = Dispatcher::standard();
if let Some(plugins) = &plugins {
if let Some(plugins) = plugins {
plugins.register(&mut dispatcher);
}
dispatcher.add(SYNC_COMMAND, TrustClass::Trusted, move |c| {
@@ -126,14 +226,13 @@ async fn run(base: PathBuf) -> i32 {
Ok(report)
}
});
rpc::serve(host.clone(), dispatcher, peer, tokio::io::stdin(), tokio::io::stdout()).await;
host.mcp.stop(&host);
if let Some(plugins) = &plugins {
dispatcher
}
async fn shutdown_all(host: &Host, plugins: Option<&Arc<RemotePlugins>>) {
host.mcp.stop(host);
if let Some(plugins) = plugins {
plugins.host().shutdown();
}
// `process::exit` skips destructors: nothing started for the client may outlive it.
if tokio::time::timeout(std::time::Duration::from_secs(10), host.shutdown()).await.is_err() {
tracing::warn!("language servers did not shut down in time");
}
0
host.shutdown().await;
}
+482
View File
@@ -0,0 +1,482 @@
//! Persistent per-project `openidea-server` daemon over a local Unix domain socket.
//!
//! * `openidea-server --attach <project_path>` connects to the daemon for `<project_path>`
//! (spawning it detached in a new session if none is listening) and bridges its own
//! stdin / stdout to the Unix socket. Closing the desktop window ends the SSH / WSL /
//! `docker exec` attach relay while the daemon — and its index, language servers,
//! terminals, runs and agent sessions — keeps running.
//! * `openidea-server --daemon <socket_path> <build>` is the process `--attach` starts.
use crate::Host;
use crate::rpc::{self, Dispatcher, PeerSlot, RemoteIdlePolicy};
use ide_core::CancellationToken;
use rustix::fs::{FlockOperation, flock};
use std::fs::{File, OpenOptions};
use std::future::{Future, pending};
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::net::Shutdown;
use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt};
use std::os::unix::net::UnixStream;
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Arc, mpsc};
use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::signal::unix::{SignalKind, signal};
/// Keep socket paths well below macOS (104) and Linux (108) `sun_path` limits.
const MAX_SUN_PATH: usize = 96;
const STARTUP_TIMEOUT: Duration = Duration::from_secs(15);
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(3);
const EOF_DRAIN: Duration = Duration::from_secs(2);
const EMPTY_IDLE_EXIT: Duration = Duration::from_secs(30);
const IDLE_ENV: &str = "OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS";
pub type BuildId = [u8; 16];
const ATTACHED: u8 = b'A';
const RETIRING: u8 = b'R';
const BUSY: u8 = b'B';
pub struct DaemonPaths {
pub key: String,
pub socket: PathBuf,
pub lock: PathBuf,
pub log: PathBuf,
}
/// Resolves `raw_path` (`~`, `~/…`, symlinks) the same way `open_project` does so
/// `~/repo` and `/home/user/repo` attach to the same daemon.
pub fn normalize_project_path(raw_path: &str, home: &Path) -> PathBuf {
let trimmed = raw_path.trim();
let expanded = if trimmed.is_empty() || trimmed == "~" {
home.to_path_buf()
} else if let Some(rest) = trimmed.strip_prefix("~/") {
home.join(rest)
} else {
PathBuf::from(trimmed)
};
let canonical = dunce::canonicalize(&expanded).unwrap_or(expanded);
let text = canonical.to_string_lossy();
if text.len() > 1 && text.ends_with('/') { PathBuf::from(text.trim_end_matches('/')) } else { canonical }
}
/// Deterministic socket, lock and log paths for a project and server home, across builds.
pub fn paths_for(base: &Path, home: &Path, raw_project_path: &str) -> io::Result<DaemonPaths> {
let project = normalize_project_path(raw_project_path, home);
std::fs::create_dir_all(base)?;
let base_canon = dunce::canonicalize(base).unwrap_or_else(|_| base.to_path_buf());
let mut hasher = blake3::Hasher::new();
hasher.update(project.as_os_str().as_encoded_bytes());
hasher.update(&[0]);
hasher.update(base_canon.as_os_str().as_encoded_bytes());
let key = hasher.finalize().to_hex()[..16].to_owned();
let sock_name = format!("s-{key}.sock");
let lock_name = format!("s-{key}.lock");
let preferred_dir = base.join("run");
let run_dir = if preferred_dir.join(&sock_name).as_os_str().len() <= MAX_SUN_PATH {
ensure_private_dir(&preferred_dir)?;
preferred_dir
} else {
let uid = rustix::process::geteuid().as_raw();
let fallback = PathBuf::from(format!("/tmp/openidea-{uid}"));
ensure_private_dir(&fallback)?;
fallback
};
let log_dir = base.join("logs");
std::fs::create_dir_all(&log_dir)?;
Ok(DaemonPaths {
socket: run_dir.join(sock_name),
lock: run_dir.join(lock_name),
log: log_dir.join(format!("server-{key}.log")),
key,
})
}
fn ensure_private_dir(dir: &Path) -> io::Result<()> {
if !dir.exists() {
let mut builder = std::fs::DirBuilder::new();
builder.recursive(true).mode(0o700);
builder.create(dir)?;
}
let meta = std::fs::symlink_metadata(dir)?;
if meta.file_type().is_symlink() || !meta.is_dir() {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("{} is not a private directory", dir.display()),
));
}
let uid = rustix::process::geteuid().as_raw();
if meta.uid() != uid {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("{} is owned by uid {}, expected {uid}", dir.display(), meta.uid()),
));
}
if meta.mode() & 0o077 != 0 {
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
}
Ok(())
}
/// Connects to the daemon for `project_path` (spawning it if needed) and bridges
/// `input` / `output` to its Unix socket.
pub fn attach(
base: &Path,
home: &Path,
project_path: &str,
input: impl Read + Send + 'static,
output: impl Write,
) -> Result<(), String> {
let exe = std::env::current_exe().map_err(|e| format!("cannot locate openidea-server: {e}"))?;
let paths = paths_for(base, home, project_path).map_err(|e| format!("cannot prepare runtime dir: {e}"))?;
let mut hasher = blake3::Hasher::new();
hasher
.update_reader(File::open(&exe).map_err(|e| format!("cannot open openidea-server: {e}"))?)
.map_err(|e| format!("cannot identify openidea-server build: {e}"))?;
let hex = hasher.finalize().to_hex();
let build = &hex.as_str()[..16];
let stream = connect_or_spawn(&exe, &paths, build)?;
bridge(stream, input, output).map_err(|e| format!("daemon relay failed: {e}"))
}
fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str) -> Result<UnixStream, String> {
let lock_file = OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.mode(0o600)
.open(&paths.lock)
.map_err(|e| format!("cannot open {}: {e}", paths.lock.display()))?;
flock(&lock_file, FlockOperation::LockExclusive)
.map_err(|e| format!("cannot lock {}: {e}", paths.lock.display()))?;
if let Some(stream) = existing_daemon(paths, build)? {
return Ok(stream);
}
match std::fs::remove_file(&paths.socket) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(format!("cannot remove stale socket {}: {e}", paths.socket.display())),
}
let mut log_file = OpenOptions::new()
.create(true)
.append(true)
.read(true)
.mode(0o600)
.open(&paths.log)
.map_err(|e| format!("cannot open {}: {e}", paths.log.display()))?;
let log_offset = log_file.metadata().map(|m| m.len()).unwrap_or(0);
let stderr_file = log_file.try_clone().map_err(|e| format!("cannot clone log handle: {e}"))?;
let mut cmd = Command::new(exe);
cmd.arg("--daemon")
.arg(&paths.socket)
.arg(build)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::from(stderr_file));
// SAFETY: `setsid` is an async-signal-safe POSIX call that detaches the daemon into
// a new session without a controlling terminal, outliving the SSH / WSL / docker exec call.
unsafe {
cmd.pre_exec(|| {
let _ = rustix::process::setsid();
Ok(())
});
}
let mut child = cmd.spawn().map_err(|e| format!("cannot spawn openidea-server daemon: {e}"))?;
let deadline = Instant::now() + STARTUP_TIMEOUT;
loop {
if let Some(stream) = existing_daemon(paths, build)? {
return Ok(stream);
}
if let Ok(Some(status)) = child.try_wait() {
let tail = read_log_tail(&mut log_file, log_offset);
let detail = if tail.is_empty() { format!("exited with {status}") } else { tail };
return Err(format!("openidea-server daemon failed to start: {detail}"));
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
let tail = read_log_tail(&mut log_file, log_offset);
let detail = if tail.is_empty() { "timed out waiting for socket".to_owned() } else { tail };
return Err(format!("openidea-server daemon did not start: {detail}"));
}
std::thread::sleep(Duration::from_millis(15));
}
}
fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result<Option<UnixStream>, String> {
let exchange = |mut stream: UnixStream| -> io::Result<Option<UnixStream>> {
stream.set_read_timeout(Some(HANDSHAKE_TIMEOUT))?;
stream.set_write_timeout(Some(HANDSHAKE_TIMEOUT))?;
stream.write_all(build.as_bytes())?;
let mut reply = [0];
stream.read_exact(&mut reply)?;
match reply[0] {
ATTACHED => {
stream.set_read_timeout(None)?;
stream.set_write_timeout(None)?;
Ok(Some(stream))
}
RETIRING => {
// This stream stays open until project cleanup and socket removal finish.
stream.set_read_timeout(Some(rpc::SHUTDOWN_TIMEOUT))?;
if stream.read(&mut reply)? == 0 {
Ok(None)
} else {
Err(io::Error::other("unexpected response from stopping daemon"))
}
}
BUSY => Err(io::Error::other(
"Another build of OpenIDEA still has this project open, is running tasks, or has unsaved changes. \
Reconnect with that build, then stop the remote backend before upgrading.",
)),
_ => Err(io::Error::other("unrecognized remote backend response")),
}
};
let stream = match UnixStream::connect(&paths.socket) {
Ok(stream) => stream,
Err(e) if matches!(e.kind(), io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused) => return Ok(None),
Err(e) => return Err(format!("cannot connect to remote backend at {}: {e}", paths.socket.display())),
};
exchange(stream).map_err(|e| format!("cannot attach to {}: {e}", paths.socket.display()))
}
fn read_log_tail(file: &mut File, offset: u64) -> String {
if file.seek(SeekFrom::Start(offset)).is_err() {
return String::new();
}
let mut text = String::new();
let _ = file.read_to_string(&mut text);
text.trim().to_owned()
}
/// Copies `input` to `stream` and `stream` to `output`, returning promptly when either
/// side closes.
pub fn bridge(
mut from_daemon: UnixStream,
mut input: impl Read + Send + 'static,
mut output: impl Write,
) -> io::Result<()> {
from_daemon.set_read_timeout(Some(Duration::from_millis(100)))?;
let mut to_daemon = from_daemon.try_clone()?;
let (eof_tx, eof_rx) = mpsc::channel();
std::thread::spawn(move || {
let mut buf = [0u8; 16 * 1024];
loop {
match input.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
if to_daemon.write_all(&buf[..n]).is_err() {
break;
}
}
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
Err(_) => break,
}
}
let _ = to_daemon.shutdown(Shutdown::Write);
let _ = eof_tx.send(Instant::now());
});
let mut buf = [0u8; 16 * 1024];
let mut input_closed: Option<Instant> = None;
loop {
if let Ok(at) = eof_rx.try_recv() {
input_closed = Some(at);
}
if input_closed.is_some_and(|at| at.elapsed() >= EOF_DRAIN) {
break;
}
match from_daemon.read(&mut buf) {
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => continue,
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
Ok(0) | Err(_) => break,
Ok(n) => {
if output.write_all(&buf[..n]).and_then(|()| output.flush()).is_err() {
break;
}
}
}
}
let _ = from_daemon.shutdown(Shutdown::Both);
Ok(())
}
/// The socket remains bound until cleanup finishes, so an attach can't start a
/// replacement while the previous backend is still stopping its processes.
pub async fn serve(
socket_path: &Path,
build: BuildId,
host: Arc<Host>,
dispatcher: Dispatcher,
slot: Arc<PeerSlot>,
cleanup: impl Future<Output = ()>,
) -> io::Result<()> {
let start = || {
if let Some(parent) = socket_path.parent() {
ensure_private_dir(parent)?;
}
let terminate = signal(SignalKind::terminate())?;
let listener = tokio::net::UnixListener::bind(socket_path)?;
if let Err(e) = std::fs::set_permissions(socket_path, std::fs::Permissions::from_mode(0o600)) {
let _ = std::fs::remove_file(socket_path);
return Err(e);
}
Ok((listener, terminate))
};
let (listener, mut terminate) = match start() {
Ok(started) => started,
Err(e) => {
cleanup.await;
return Err(e);
}
};
let shutdown = CancellationToken::new();
let idle_policy = RemoteIdlePolicy { override_seconds: idle_override() };
let mut check = tokio::time::interval(Duration::from_secs(idle_policy.override_seconds.unwrap_or(5).min(5)));
let mut idle = None;
let mut retiring = None;
let mut active: Option<ide_jsonrpc::Peer> = None;
let result = loop {
tokio::select! {
_ = shutdown.cancelled() => break Ok(()),
_ = terminate.recv() => break Ok(()),
_ = async {
match &active {
Some(peer) => { peer.closed().await; }
None => pending().await,
}
} => {
active = None;
slot.remove();
host.client_disconnected();
idle = None;
}
accepted = listener.accept() => {
let mut stream = match accepted {
Ok((stream, _)) => stream,
Err(e) => break Err(e),
};
let mut requested_build = [0; 16];
if !matches!(
tokio::time::timeout(HANDSHAKE_TIMEOUT, stream.read_exact(&mut requested_build)).await,
Ok(Ok(_))
) {
continue;
}
if active.as_ref().is_some_and(ide_jsonrpc::Peer::is_closed) {
active = None;
slot.remove();
host.client_disconnected();
idle = None;
}
if shutdown.is_cancelled() {
break Ok(());
}
if requested_build != build {
let busy = active.is_some() || has_live_work(&host);
if busy {
let _ = stream.write_u8(BUSY).await;
} else if stream.write_u8(RETIRING).await.is_ok() {
retiring = Some(stream);
break Ok(());
}
continue;
}
if stream.write_u8(ATTACHED).await.is_err() {
continue;
}
if let Some(old) = slot.remove() {
// Await an acknowledgement before tearing down the old transport.
let _ = tokio::time::timeout(
Duration::from_millis(750),
old.request::<_, ()>(rpc::SESSION_REPLACED, (), None),
).await;
old.kill();
host.client_disconnected();
}
let (reader, writer) = stream.into_split();
active = Some(rpc::connect_persistent(
host.clone(), dispatcher.clone(), slot.clone(), shutdown.clone(), idle_policy, reader, writer,
));
idle = None;
}
_ = check.tick() => {
if active.is_some() || has_live_work(&host) {
idle = None;
} else {
if idle.is_none() {
let since = Instant::now();
let timeout = match disconnected_timeout(&host, idle_policy).await {
Ok(timeout) => timeout,
Err(e) => break Err(e),
};
idle = Some((since, timeout));
}
if let Some((since, Some(timeout))) = idle && since.elapsed() >= timeout {
tracing::info!("idle openidea-server daemon exiting");
break Ok(());
}
}
}
}
};
shutdown.cancel();
slot.remove();
if let Some(peer) = &active {
let _ = tokio::time::timeout(HANDSHAKE_TIMEOUT, peer.flush()).await;
host.client_disconnected();
}
cleanup.await;
if let Err(e) = std::fs::remove_file(socket_path) {
tracing::warn!("cannot remove remote backend socket {}: {e}", socket_path.display());
}
if let Some(active) = active {
active.kill();
}
drop(retiring);
result
}
fn idle_override() -> Option<u64> {
if let Some(value) = std::env::var_os(IDLE_ENV) {
if let Some(seconds) = value.to_str().and_then(|s| s.parse::<u64>().ok()).filter(|&n| n > 0) {
return Some(seconds);
}
tracing::warn!("{IDLE_ENV} must be a positive number of seconds; using the host setting");
}
None
}
async fn disconnected_timeout(host: &Arc<Host>, policy: RemoteIdlePolicy) -> io::Result<Option<Duration>> {
let override_timeout = policy.override_seconds.map(Duration::from_secs);
if host.projects().is_empty() {
return Ok(Some(override_timeout.unwrap_or(EMPTY_IDLE_EXIT).min(EMPTY_IDLE_EXIT)));
}
if let Some(timeout) = override_timeout {
return Ok(Some(timeout));
}
let minutes = crate::ops::project::remote_idle_timeout_minutes(host).await.map_err(io::Error::other)?;
Ok((minutes != 0).then(|| Duration::from_secs(u64::from(minutes) * 60)))
}
/// Keeps a disconnected daemon alive: expiring would end this work, or lose the unsaved
/// edits a dropped connection left behind.
fn has_live_work(host: &Host) -> bool {
!host.terminals.list().is_empty()
|| host.processes.has_live_runs()
|| !host.debugger.sessions(None).is_empty()
|| host
.projects()
.iter()
.any(|project| project.agents.has_live_work() || project.documents.has_unsaved_changes())
}
-3
View File
@@ -66,9 +66,6 @@ impl EventSink for RecordingSink {
}
}
/// A sink whose diagnostics are recorded; the store outlives every project.
pub type RecordSinkFactory = Box<dyn Fn(&str) -> SharedSink + Send + Sync>;
/// Wraps a sink factory so every sink it creates records diagnostics.
pub fn recording_sink_factory(store: Arc<DiagnosticsStore>, inner: crate::SinkFactory) -> crate::SinkFactory {
Box::new(move |window| {
+34 -18
View File
@@ -21,7 +21,7 @@ use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
use std::time::{Duration, Instant};
type Changes = Vec<(OsString, Option<OsString>)>;
@@ -355,20 +355,34 @@ fn run_post_start(cmd: &LifecycleCommand, root: &Path, sink: &SharedSink, cancel
/// Runs `argv` in `root` with the children's environment, its stdout and stderr line by line
/// to `on_line`; `Err` says how it failed.
fn run_one(argv: &[String], root: &Path, cancel: &CancellationToken, on_line: &dyn Fn(String)) -> Result<(), String> {
let (program, args) = argv.split_first().ok_or("empty command")?;
let mut command = Command::new(program);
command.args(args);
run_command(command, root, cancel, None, on_line)
}
pub(crate) fn run_command(
mut command: Command,
root: &Path,
cancel: &CancellationToken,
timeout: Option<Duration>,
mut on_line: impl FnMut(String),
) -> Result<(), String> {
if cancel.is_cancelled() {
return Err("cancelled".into());
}
let (program, args) = argv.split_first().ok_or("empty command")?;
let mut child = ide_core::process::prepare(&mut Command::new(program))
.args(args)
let program = command.get_program().to_string_lossy().into_owned();
command
.current_dir(root)
.envs(ide_core::process::shell_env())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.stderr(Stdio::piped());
let mut child = ide_core::process::prepare(ide_core::process::own_group(&mut command))
.spawn()
.map_err(|e| format!("cannot start {program}: {e}"))?;
let (tx, rx) = std::sync::mpsc::channel::<String>();
let started = Instant::now();
let (tx, rx) = std::sync::mpsc::sync_channel::<String>(64);
let pipes: [Option<Box<dyn Read + Send>>; 2] = [
child.stdout.take().map(|p| Box::new(p) as Box<dyn Read + Send>),
child.stderr.take().map(|p| Box::new(p) as Box<dyn Read + Send>),
@@ -386,29 +400,31 @@ fn run_one(argv: &[String], root: &Path, cancel: &CancellationToken, on_line: &d
}
drop(tx);
let status = loop {
if cancel.is_cancelled() {
ide_core::process::kill_tree(&mut child);
return Err("cancelled".into());
}
if timeout.is_some_and(|duration| started.elapsed() >= duration) {
ide_core::process::kill_tree(&mut child);
return Err("timed out".into());
}
match rx.recv_timeout(Duration::from_millis(50)) {
Ok(line) => on_line(line),
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break child.wait(),
}
if cancel.is_cancelled() {
let _ = child.kill();
let _ = child.wait();
return Err("cancelled".into());
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => std::thread::sleep(Duration::from_millis(50)),
}
// A process it started in the background may keep the pipes open: the command is done.
if let Ok(Some(status)) = child.try_wait() {
let deadline = std::time::Instant::now() + Duration::from_secs(1);
if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
let deadline = Instant::now() + Duration::from_secs(1);
while let Ok(line) = rx.recv_timeout(Duration::from_millis(100)) {
on_line(line);
if std::time::Instant::now() > deadline {
if Instant::now() > deadline {
break;
}
}
break Ok(status);
break status;
}
}
.map_err(|e| e.to_string())?;
};
match status.code() {
Some(0) => Ok(()),
Some(code) => Err(format!("exited with code {code}")),
+487 -43
View File
@@ -3,11 +3,13 @@
use crate::Host;
use ide_core::event::NotifyLevel;
use ide_core::settings::{BIOME_LANGUAGES, ExternalFormatter, LanguagesSettings, Settings};
use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, LanguageId, Pos, Range, TextEdit};
use ide_core::{
CancellationToken, ChangeSet, DocId, IdeError, IdeEvent, IdeResult, IpcPath, LanguageId, Pos, Range, TextEdit,
};
use ide_language::{LanguageConfig, PhpAlignment, Syntax};
use ide_lsp::types::FormatOptions;
use ide_tools::{Tools, formatter};
use std::path::Path;
use std::path::{Path, PathBuf};
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).
@@ -29,18 +31,131 @@ fn biome_formats(file: &Path) -> bool {
}
}
/// The `pyproject.toml` Black reads for `file`, in the project root Black finds: the nearest folder
/// with `.git`, `.hg`, or a `pyproject.toml` that has `[tool.black]` (one without it is skipped).
/// `None` when that root has no `pyproject.toml`: Black then reads the user's configuration.
fn black_pyproject(file: &Path) -> Option<PathBuf> {
let mut dirs = file.parent()?.ancestors();
let root = dirs
.find(|d| {
d.join(".git").exists()
|| d.join(".hg").is_dir()
|| ide_sdk::apply::toml_has_table(&d.join("pyproject.toml"), "tool.black")
})
.or_else(|| file.parent()?.ancestors().last())?;
Some(root.join("pyproject.toml")).filter(|p| p.is_file())
}
/// Black formats files whose project configures it (`[tool.black]`).
fn black_configured(file: &Path) -> bool {
black_pyproject(file).is_some_and(|p| ide_sdk::apply::toml_has_table(&p, "tool.black"))
}
/// The single user configuration directory the formatter searches.
fn user_config_dir(tool: &str, cwd: &Path) -> Option<PathBuf> {
if cfg!(windows) {
return if tool == "black" { dirs::home_dir() } else { dirs::config_dir() };
}
let xdg = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from);
xdg_user_config_dir(tool, cwd, xdg.as_deref(), dirs::home_dir().as_deref())
}
fn xdg_user_config_dir(tool: &str, cwd: &Path, xdg: Option<&Path>, home: Option<&Path>) -> Option<PathBuf> {
if let Some(dir) = xdg.filter(|dir| tool == "black" || dir.is_absolute()) {
if let Ok(relative) = dir.strip_prefix("~") {
return home.map(|home| home.join(relative));
}
return Some(cwd.join(dir));
}
home.map(|home| home.join(".config"))
}
fn user_configured(tool: &str, dir: Option<&Path>) -> bool {
let Some(dir) = dir else { return false };
let names: &[&str] = match tool {
"ruff" => &["ruff/.ruff.toml", "ruff/ruff.toml", "ruff/pyproject.toml"],
"black" if cfg!(windows) => &[".black"],
"black" => &["black"],
_ => &[],
};
names.iter().any(|name| dir.join(name).is_file())
}
/// Whether Ruff finds a configuration of the project for `file`: `ruff.toml`, `.ruff.toml` or a
/// `pyproject.toml` with `[tool.ruff]` in its folder or above.
fn ruff_project_configured(file: &Path) -> bool {
file.parent().into_iter().flat_map(Path::ancestors).any(|dir| {
dir.join("ruff.toml").is_file()
|| dir.join(".ruff.toml").is_file()
|| ide_sdk::apply::toml_has_table(&dir.join("pyproject.toml"), "tool.ruff")
})
}
/// The indentation and line length for `tool`, unless a configuration of the project or the user
/// decides them (or the Ruff configuration directory is set): the file's `.editorconfig`, then
/// what was set on the Code Style › Python page, as the editor indents.
fn python_style_for(
tool: &str,
file: &Path,
configured: bool,
settings: &Settings,
editorconfig: Option<&ide_workspace::editorconfig::EditorConfigProps>,
user_dir: Option<&Path>,
) -> formatter::PythonStyle {
let has_config = configured
|| match tool {
"ruff" => ruff_project_configured(file) || user_configured("ruff", user_dir),
// Black reads the user's configuration only when its project root has no pyproject.toml.
"black" => match black_pyproject(file) {
Some(pyproject) => ide_sdk::apply::toml_has_table(&pyproject, "tool.black"),
None => user_configured("black", user_dir),
},
_ => true,
};
if has_config {
return formatter::PythonStyle::default();
}
// Only what was set: the global hard wrap (120) is not Ruff's or Black's default (88).
let page = settings.editor.code_style.languages.get("python");
let ec = editorconfig;
formatter::PythonStyle {
line_length: ec.and_then(|e| e.max_line_length).or(page.and_then(|s| s.hard_wrap_at)),
indent_width: ec.and_then(|e| e.indent_size.or(e.tab_width)).or(page.and_then(|s| s.indent.or(s.tab_size))),
use_tabs: ec
.and_then(|e| e.indent_style)
.map(|style| style == ide_workspace::editorconfig::IndentStyle::Tab)
.or(page.and_then(|s| s.use_tab)),
}
}
/// `tool` installed in the environment of the interpreter nearest to `near` (`svc/.venv/bin/ruff` or
/// `svc/.venv/bin/black`), or in `Scripts` for conda and pixi environments on Windows.
fn interpreter_tool(root: &Path, near: Option<&Path>, settings: &Settings, tool: &str) -> Option<PathBuf> {
let python = ide_sdk::apply::python_interpreter_near(root, near, settings)?;
let dir = python.parent()?;
let exe = if cfg!(windows) { format!("{tool}.exe") } else { tool.to_owned() };
[dir.join(&exe), dir.join("Scripts").join(&exe)].into_iter().find(|p| p.is_file())
}
/// Formatters print nothing for a file their configuration excludes (Black's `force-exclude`):
/// that output must not replace the file.
fn excluded_output(text: &str, formatted: &str) -> bool {
formatted.is_empty() && !text.trim().is_empty()
}
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,
Some("ruff") => matches!(tool, ExternalFormatter::Ruff | ExternalFormatter::Black),
_ => false,
}
}
/// The external formatter of a file, for a language with an external formatter.
/// `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
/// `forced` names the tool (Reformat with Prettier, oxfmt, Biome, Ruff, or Black). Ruff is
/// the base formatter for Python, replaced by Black when configured or selected; 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(
@@ -49,7 +164,7 @@ fn external_tool(
file: &Path,
settings: &LanguagesSettings,
) -> IdeResult<Option<ExternalFormatter>> {
use ExternalFormatter::{Biome, Oxfmt, Prettier, Ruff};
use ExternalFormatter::{Biome, Black, Oxfmt, Prettier, Ruff};
let Some(language) = language.filter(|l| l.formatter.is_some()) else {
return match forced {
Some(tool) => Err(IdeError::invalid(format!(
@@ -73,7 +188,11 @@ fn external_tool(
}
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == language.id.as_str());
if language.formatter.as_ref().is_some_and(|f| f.tool == "ruff") {
return Ok(enabled(Ruff).then_some(Ruff));
return Ok(if enabled(Black) && (settings.black.prefer || black_configured(file)) {
Some(Black)
} else {
enabled(Ruff).then_some(Ruff)
});
}
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);
@@ -173,10 +292,58 @@ pub async fn format(
) -> IdeResult<Vec<TextEdit>> {
let project = host.project(window)?;
let snap = project.documents.snapshot(doc)?;
let source = FormatSource {
path: snap.path,
language: snap.language,
text: snap.text,
doc: Some(doc),
version: snap.version,
read_only: snap.read_only,
};
format_source(host, window, &project, source, range, options).await
}
/// Format a separate snapshot using the file's language, settings and formatter.
pub async fn format_text(
host: &Host,
window: &str,
path: PathBuf,
text: String,
options: FormatOptions,
) -> IdeResult<Vec<TextEdit>> {
let project = host.project(window)?;
if !path.is_absolute() || path.file_name().is_none() {
return Err(IdeError::invalid("formatting requires a file path"));
}
if text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD {
return Ok(Vec::new());
}
let language = project.documents.language_of(&path, text.lines().next()).language;
let source = FormatSource { path: path.into(), language, text, doc: None, version: 0, read_only: false };
format_source(host, window, &project, source, None, options).await
}
struct FormatSource {
path: IpcPath,
language: LanguageId,
text: String,
doc: Option<DocId>,
version: u32,
read_only: bool,
}
async fn format_source(
host: &Host,
window: &str,
project: &crate::Project,
snap: FormatSource,
range: Option<Range>,
options: FormatOptions,
) -> IdeResult<Vec<TextEdit>> {
let settings = project.settings.effective();
let alignment = php_alignment(&settings, &snap.language);
let original = alignment.any().then(|| (snap.language.clone(), snap.text.clone()));
let Some(edits) = provider_edits(host, window, &project, snap, settings, range, options).await? else {
let Some(edits) = provider_edits(host, window, project, snap, settings, range, options).await? else {
return Ok(Vec::new());
};
let Some((language, text)) = original else {
@@ -257,12 +424,12 @@ async fn provider_edits(
host: &Host,
window: &str,
project: &crate::Project,
snap: ide_workspace::documents::DocumentInfo,
snap: FormatSource,
settings: Settings,
range: Option<Range>,
options: FormatOptions,
) -> IdeResult<Option<Vec<TextEdit>>> {
let doc = snap.id;
let doc = snap.doc;
let language = project.languages.get(&snap.language);
if options.tool.is_none()
&& let Some(id) = settings.languages.plugin_formatters.get(snap.language.as_str()).filter(|s| !s.is_empty())
@@ -326,10 +493,15 @@ async fn provider_edits(
return Ok(Some(edits));
}
let mut selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?;
// Black is selected only when configured or preferred: the Ruff server's formatting doesn't replace it.
if let Some(tool) = selected
&& options.tool.is_none()
&& tool != ExternalFormatter::Black
&& !settings.languages.formatter(tool).prefer
&& project.lsp.can_format(doc).await?
&& match doc {
Some(doc) => project.lsp.can_format(doc).await?,
None => project.lsp.can_format_text(&snap.path, &snap.language).await,
}
{
selected = None;
}
@@ -337,14 +509,20 @@ async fn provider_edits(
if options.on_save && !settings.editor.format_on_save {
return Ok(None);
}
let edits = project.lsp.format(doc, range, options).await?;
let edits = match doc {
Some(doc) => project.lsp.format(doc, range, options).await?,
None => project.lsp.format_text(&snap.path, &snap.language, &snap.text, options).await?,
};
let text = snap.text;
return tokio::task::spawn_blocking(move || Some(minimal_edits(&text, edits)))
.await
.map_err(|e| IdeError::internal(e.to_string()));
};
let tool_settings = settings.languages.formatter(selected);
if options.on_save && !tool_settings.run_on_save {
// Black takes over from the language server in its projects, so Format on save runs it too.
let runs_on_save =
tool_settings.run_on_save || (selected == ExternalFormatter::Black && settings.editor.format_on_save);
if options.on_save && !runs_on_save {
return Ok(None);
}
host.require_trust(window)?;
@@ -354,12 +532,21 @@ async fn provider_edits(
let config = language.and_then(|l| l.formatter).expect("external_tool selects languages with a formatter");
let tool = selected.name();
let name = formatter::display_name(tool);
let custom = ide_sdk::apply::setting_path(&project.root, &tool_settings.path);
let mut custom = ide_sdk::apply::setting_path(&project.root, &tool_settings.path);
if custom.is_none() && matches!(selected, ExternalFormatter::Ruff | ExternalFormatter::Black) {
let (root, near, settings) =
(project.root.clone(), snap.path.parent().map(Path::to_path_buf), settings.clone());
custom = tokio::task::spawn_blocking(move || interpreter_tool(&root, near.as_deref(), &settings, tool))
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
}
let tools = Tools::new(&host.local_data_dir);
let whole_selection = range.is_some() && !formatter::supports_range(tool, &config);
let unsupported_range = range.is_some() && !formatter::supports_range(tool, &config);
let project_root = project.root.clone();
let configuration_directory = settings.languages.ruff.configuration_directory.clone();
let edits: IdeResult<Vec<TextEdit>> = tokio::task::spawn_blocking(move || {
let style_settings = settings.clone();
let documents = project.documents.clone();
let result: IdeResult<(Vec<TextEdit>, bool, bool)> = tokio::task::spawn_blocking(move || {
let text = ide_text::Document::new(&snap.text);
let range = range.map(|range| format_range(&text, range));
let config_file = if tool == "ruff" {
@@ -367,47 +554,133 @@ async fn provider_edits(
} else {
None
};
let mut command = tools.formatter_command(tool, &snap.path, custom.as_deref())?;
let dir = snap.path.parent().ok_or_else(|| IdeError::invalid(format!("{name}: file has no directory")))?;
command.current_dir(dir);
command.args(formatter::arguments(
tool,
&config,
&snap.path,
options.tab_size,
options.insert_spaces,
range,
config_file.as_deref(),
));
let formatted = formatter::run(tool, command, &snap.text, &Default::default())?;
Ok(text
.diff(&formatted)
.changes
.into_iter()
.map(|c| TextEdit {
range: Range::new(text.offset_to_pos(c.from), text.offset_to_pos(c.to)),
new_text: c.insert,
})
.collect())
let style = if matches!(selected, ExternalFormatter::Ruff | ExternalFormatter::Black) {
let editorconfig = style_settings
.editor
.code_style
.editorconfig
.then(|| documents.editorconfig().resolve(&snap.path))
.flatten();
python_style_for(
tool,
&snap.path,
config_file.is_some(),
&style_settings,
editorconfig.as_ref(),
user_config_dir(tool, dir).as_deref(),
)
} else {
formatter::PythonStyle::default()
};
let run = |range| {
let mut command = tools.formatter_command(tool, &snap.path, custom.as_deref())?;
command.current_dir(dir);
let args = formatter::arguments(
tool,
&config,
&snap.path,
options.tab_size,
options.insert_spaces,
range,
config_file.as_deref(),
);
command.args(formatter::with_python_style(tool, args, style));
formatter::run(tool, command, &snap.text, &Default::default())
};
let mut old_black = false;
let formatted = match run(range) {
// Black before 23.11 has no `--line-ranges`: format the whole file instead.
Err(e) if tool == "black" && range.is_some() && e.message.contains("--line-ranges") => {
old_black = true;
run(None)?
}
result => result?,
};
if excluded_output(&snap.text, &formatted) {
return Ok((Vec::new(), false, true));
}
let edits = diff_edits(&text, &formatted);
Ok((edits, old_black, false))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
if edits.is_ok() && whole_selection {
let (edits, old_black, excluded) = match result {
Ok((edits, old_black, excluded)) => (Ok(edits), old_black, excluded),
Err(e) => (Err(e), false, false),
};
// Notification titles are translated, and the catalog has "Black" as the colour.
let title = if selected == ExternalFormatter::Black { "Black formatter" } else { name };
if excluded && !options.on_save {
project.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Info,
title: name.into(),
body: Some(format!(
"{name} does not support selection formatting for this language; formatted the whole file"
)),
title: title.into(),
body: Some(format!("{name} left the file unchanged: its configuration excludes it")),
});
}
let whole_selection = if old_black {
Some("This Black cannot format a selection (Black 23.11 or later can); formatted the whole file".to_owned())
} else {
(edits.is_ok() && unsupported_range).then(|| {
format!("{name} does not support selection formatting for this language; formatted the whole file")
})
};
if let Some(body) = whole_selection {
project.sink.emit(IdeEvent::Notify { level: NotifyLevel::Info, title: title.into(), body: Some(body) });
}
edits.map(Some).map_err(|e| e.with_tool(tool))
}
/// The edits that turn `text` into `formatted`, one per changed region.
fn diff_edits(text: &ide_text::Document, formatted: &str) -> Vec<TextEdit> {
text.diff(formatted)
.changes
.into_iter()
.map(|c| TextEdit {
range: Range::new(text.offset_to_pos(c.from), text.offset_to_pos(c.to)),
new_text: c.insert,
})
.collect()
}
/// Optimize Imports for a Python document no language server organizes (the Ruff server starts
/// only below a Ruff configuration): Ruff's CLI removes the unused imports and sorts the rest, with
/// the project's Ruff settings when there are any. `None` for other documents and untrusted projects.
pub async fn python_import_edits(
host: &Host,
window: &str,
doc: DocId,
cancel: CancellationToken,
) -> IdeResult<Option<(ide_core::IpcPath, Vec<TextEdit>)>> {
let project = host.project(window)?;
let snap = project.documents.snapshot(doc)?;
if snap.language.as_str() != "python" || snap.read_only || project.require_trust().is_err() {
return Ok(None);
}
let settings = project.settings.effective();
let custom = ide_sdk::apply::setting_path(&project.root, &settings.languages.ruff.path);
let configured = settings.languages.ruff.configuration_directory.clone();
let root = project.root.clone();
let tools = Tools::new(&host.local_data_dir);
tokio::task::spawn_blocking(move || {
let config_file = ide_sdk::apply::ruff_configuration(&root, &configured)?;
let custom = custom.or_else(|| interpreter_tool(&root, snap.path.parent(), &settings, "ruff"));
let mut command = tools.formatter_command("ruff", &snap.path, custom.as_deref())?;
if let Some(dir) = snap.path.parent() {
command.current_dir(dir);
}
command.args(formatter::ruff_organize_imports_arguments(&snap.path, config_file.as_deref()));
let fixed = formatter::run("ruff", command, &snap.text, &cancel)?;
Ok(Some((snap.path, diff_edits(&ide_text::Document::new(&snap.text), &fixed))))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
#[cfg(test)]
mod tests {
use super::*;
use ExternalFormatter::{Biome, Oxfmt, Prettier, Ruff};
use ExternalFormatter::{Biome, Black, Oxfmt, Prettier, Ruff};
use ide_core::LanguageId;
use ide_language::LanguageRegistry;
@@ -452,6 +725,177 @@ mod tests {
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");
assert_eq!(tool(Some(Black), "python", file, &settings).unwrap(), Some(Black));
let black = tool(Some(Black), "typescript", Path::new("/project/app.ts"), &settings).unwrap_err();
assert_eq!(black.message, "Black cannot format TypeScript files");
}
#[test]
#[cfg(not(windows))]
fn an_xdg_override_hides_fallback_python_formatter_configs() {
let dir = tempfile::tempdir().unwrap();
let cwd = dir.path();
let home = cwd.join("home");
let fallback = home.join(".config");
let xdg = cwd.join("config override");
for (tool, name) in [("ruff", "ruff/ruff.toml"), ("black", "black")] {
let config = fallback.join(name);
std::fs::create_dir_all(config.parent().unwrap()).unwrap();
std::fs::write(config, "").unwrap();
let probe = |xdg| xdg_user_config_dir(tool, cwd, xdg, Some(&home));
assert!(user_configured(tool, probe(None).as_deref()), "{tool} should find its default config");
assert!(!user_configured(tool, probe(Some(&xdg)).as_deref()), "{tool} should skip its default config");
let config = xdg.join(name);
std::fs::create_dir_all(config.parent().unwrap()).unwrap();
std::fs::write(config, "").unwrap();
assert!(user_configured(tool, probe(Some(&xdg)).as_deref()), "{tool} should find its XDG config");
}
let relative = Some(Path::new("config override"));
assert_eq!(xdg_user_config_dir("ruff", cwd, relative, Some(&home)), Some(fallback));
assert_eq!(xdg_user_config_dir("black", cwd, relative, Some(&home)), Some(xdg));
assert_eq!(xdg_user_config_dir("black", cwd, Some(Path::new("~/alt")), Some(&home)), Some(home.join("alt")));
}
#[test]
fn code_style_reaches_ruff_and_black_only_without_their_configuration() {
use ide_workspace::editorconfig::{EditorConfigProps, IndentStyle};
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("repo");
let user = dir.path().join("user config");
std::fs::create_dir_all(root.join("app/src")).unwrap();
std::fs::create_dir_all(root.join(".git")).unwrap();
std::fs::create_dir_all(user.join("ruff")).unwrap();
let file = root.join("app/src/main.py");
let mut settings = Settings::default();
let style = |tool, settings: &Settings, editorconfig: Option<&EditorConfigProps>| {
python_style_for(tool, &file, false, settings, editorconfig, Some(&user))
};
let none = formatter::PythonStyle::default();
// Nothing set: the tools keep their defaults.
assert_eq!(style("ruff", &settings, None), none);
let page = ide_core::editor_settings::LanguageCodeStyle {
hard_wrap_at: Some(100),
tab_size: Some(2),
..Default::default()
};
settings.editor.code_style.languages.insert("python".into(), page);
let set = formatter::PythonStyle { line_length: Some(100), indent_width: Some(2), use_tabs: None };
assert_eq!(style("ruff", &settings, None), set);
assert_eq!(style("black", &settings, None), set);
assert_eq!(python_style_for("ruff", &file, true, &settings, None, Some(&user)), none);
// The file's .editorconfig wins over the page, as in the editor.
let editorconfig =
EditorConfigProps { indent_size: Some(4), indent_style: Some(IndentStyle::Space), ..Default::default() };
let indented = formatter::PythonStyle { line_length: Some(100), indent_width: Some(4), use_tabs: Some(false) };
assert_eq!(style("ruff", &settings, Some(&editorconfig)), indented);
// The user's configurations: Ruff's always counts, Black's only when the project root
// (here the repository) has no pyproject.toml.
let (black_config, ignored_black_config) =
if cfg!(windows) { (".black", "black") } else { ("black", ".black") };
std::fs::write(user.join(ignored_black_config), "[tool.black]\n").unwrap();
assert_eq!(style("black", &settings, None), set);
std::fs::write(user.join(black_config), "[tool.black]\n").unwrap();
assert_eq!(style("black", &settings, None), none);
std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"repo\"\n").unwrap();
assert_eq!(style("black", &settings, None), set);
std::fs::write(user.join("ruff/ruff.toml"), "").unwrap();
assert_eq!(style("ruff", &settings, None), none);
std::fs::remove_file(user.join("ruff/ruff.toml")).unwrap();
// The project's configurations.
std::fs::write(root.join("app/pyproject.toml"), "[project]\nname = \"app\"\n").unwrap();
assert_eq!(style("ruff", &settings, None), set);
std::fs::write(root.join("pyproject.toml"), "[tool.black]\n").unwrap();
assert_eq!(style("black", &settings, None), none);
assert_eq!(style("ruff", &settings, None), set);
std::fs::write(root.join(".ruff.toml"), "").unwrap();
assert_eq!(style("ruff", &settings, None), none);
}
#[test]
fn empty_output_for_a_file_with_code_is_an_exclusion_not_an_empty_file() {
assert!(excluded_output("x = 1\n", ""));
assert!(!excluded_output("\n\n", ""));
assert!(!excluded_output("x = 1\n", "x = 1\n"));
}
#[test]
fn ruff_comes_from_the_environment_of_the_files_own_project() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let bin = root.join(if cfg!(windows) { "svc/.venv/Scripts" } else { "svc/.venv/bin" });
std::fs::create_dir_all(&bin).unwrap();
let exe = |name: &str| if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() };
std::fs::write(bin.join(exe("python")), "").unwrap();
std::fs::write(root.join("svc/.venv/pyvenv.cfg"), "").unwrap();
let settings = Settings::default();
let near = root.join("svc/src");
assert_eq!(interpreter_tool(root, Some(&near), &settings, "ruff"), None);
std::fs::write(bin.join(exe("ruff")), "").unwrap();
assert_eq!(interpreter_tool(root, Some(&near), &settings, "ruff"), Some(bin.join(exe("ruff"))));
}
#[test]
fn black_comes_from_the_environment_of_the_files_own_project() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let bin = root.join(if cfg!(windows) { "svc/.venv/Scripts" } else { "svc/.venv/bin" });
std::fs::create_dir_all(&bin).unwrap();
let exe = |name: &str| if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() };
std::fs::write(bin.join(exe("python")), "").unwrap();
std::fs::write(root.join("svc/.venv/pyvenv.cfg"), "").unwrap();
std::fs::write(root.join("svc/pyproject.toml"), "[tool.black]\n").unwrap();
let settings = Settings::default();
assert_eq!(interpreter_tool(root, Some(&root.join("svc/src")), &settings, "black"), None);
std::fs::write(bin.join(exe("black")), "").unwrap();
assert_eq!(
interpreter_tool(root, Some(&root.join("svc/src")), &settings, "black"),
Some(bin.join(exe("black")))
);
}
#[test]
fn black_config_or_preference_selects_black_for_python() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::create_dir_all(root.join("svc/src")).unwrap();
std::fs::create_dir_all(root.join("api")).unwrap();
let (svc, api) = (root.join("svc/src/main.py"), root.join("api/main.py"));
let mut settings = LanguagesSettings::default();
std::fs::write(root.join("svc/pyproject.toml"), "[tool.ruff]\nline-length = 100\n").unwrap();
assert_eq!(tool(None, "python", &svc, &settings).unwrap(), Some(Ruff));
std::fs::write(root.join("svc/pyproject.toml"), "[tool.black]\nline-length = 100\n").unwrap();
assert_eq!(tool(None, "python", &svc, &settings).unwrap(), Some(Black));
assert_eq!(tool(None, "python", &api, &settings).unwrap(), Some(Ruff));
settings.black.prefer = true;
assert_eq!(tool(None, "python", &api, &settings).unwrap(), Some(Black));
settings.black.languages.clear();
assert_eq!(tool(None, "python", &svc, &settings).unwrap(), Some(Ruff));
}
#[test]
fn black_finds_its_configuration_like_black_does() {
let dir = tempfile::tempdir().unwrap();
let repo = dir.path().join("repo");
std::fs::create_dir_all(repo.join(".git")).unwrap();
std::fs::create_dir_all(repo.join("pkg/src")).unwrap();
let file = repo.join("pkg/src/m.py");
assert_eq!(black_pyproject(&file), None);
// A pyproject without [tool.black] is passed over, up to the repository root.
std::fs::write(repo.join("pkg/pyproject.toml"), "[project]\nname = \"pkg\"\n").unwrap();
std::fs::write(repo.join("pyproject.toml"), "[tool.black]\nline-length = 100\n").unwrap();
assert_eq!(black_pyproject(&file), Some(repo.join("pyproject.toml")));
assert!(black_configured(&file));
// The repository root's pyproject is Black's even without [tool.black]; nothing above counts.
std::fs::write(repo.join("pyproject.toml"), "[project]\nname = \"repo\"\n").unwrap();
std::fs::write(dir.path().join("pyproject.toml"), "[tool.black]\n").unwrap();
assert_eq!(black_pyproject(&file), Some(repo.join("pyproject.toml")));
assert!(!black_configured(&file));
std::fs::write(repo.join("pkg/pyproject.toml"), "[tool.black]\n").unwrap();
assert_eq!(black_pyproject(&file), Some(repo.join("pkg/pyproject.toml")));
}
#[test]
+75 -22
View File
@@ -5,6 +5,8 @@
pub mod agent_secrets;
pub mod catalogue;
#[cfg(unix)]
pub mod daemon;
pub mod data_dirs;
pub mod diagnostics_store;
mod direnv;
@@ -25,7 +27,7 @@ pub mod rpc;
pub mod shell_env;
pub mod trust;
pub use project::{Project, apply_git_executable, history_retention};
pub use project::{Project, history_retention};
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId, SharedSink};
use ide_language::{LanguageRegistry, Syntax};
@@ -34,7 +36,7 @@ use ide_terminal::TerminalManager;
use ide_workspace::SettingsStore;
use parking_lot::{Mutex, RwLock};
use std::collections::HashMap;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};
/// Event sink for one window (by label).
@@ -58,6 +60,27 @@ pub struct HostConfig {
pub project_environment: bool,
}
#[cfg(test)]
impl HostConfig {
/// A host under `base` for unit tests: `config`, `data` and `data` again for the machine-local
/// directory, built-in languages, no grammars, a sink that drops events, the window as its own
/// owner, the current tokio runtime and no project environment. Override fields with
/// `HostConfig { sink_for: .., ..HostConfig::for_test(base) }`. Call it inside a runtime.
pub(crate) fn for_test(base: &Path) -> Self {
Self {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}
}
}
pub struct Host {
pub(crate) mcp_executable: Arc<RwLock<Option<PathBuf>>>,
pub mcp: mcp::McpService,
@@ -92,6 +115,7 @@ pub struct Host {
/// The window that owns each open heap snapshot; its project's close closes them.
pub(crate) heap_windows: Mutex<HashMap<ide_heap::HeapSnapshotId, String>>,
pub(crate) heap_requests: ops::heap::HeapRequests,
pub(crate) rebase_editors: Arc<ops::vcs::RebaseEditors>,
/// SSH connections of Settings › SSH Configurations.
pub ssh: Arc<ide_ssh::SshManager>,
/// SFTP deployment, remote file editing and runs on run targets.
@@ -190,6 +214,7 @@ impl Host {
heap: Arc::new(ide_heap::HeapRegistry::new(ide_heap::snapshots_root(&local_data_dir))),
heap_windows: Mutex::default(),
heap_requests: Default::default(),
rebase_editors: Default::default(),
languages,
syntax,
config_dir,
@@ -207,6 +232,7 @@ impl Host {
};
host.apply_proxy();
host.apply_added_jdks();
host.apply_git_executable();
// Before any project starts jdtls; the deleting itself can take a while.
let unused =
ide_sdk::jdtls_workspaces::take_unused(&host.local_data_dir, ide_sdk::jdtls_workspaces::UNUSED_FOR);
@@ -502,6 +528,25 @@ impl Host {
}
}
/// Cleans up per-connection client state when a remote window disconnects from a
/// persistent daemon, leaving the project, index, language servers, terminals,
/// runs and agent sessions running.
pub fn client_disconnected(&self) {
let windows: Vec<String> = self.projects.read().keys().cloned().collect();
for window in &windows {
self.mcp_reports.forget_window(window);
self.mcp_requests.forget_window(window);
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
self.cancel_request(request);
}
}
self.terminals.detach_output();
self.processes.detach_output();
for project in self.projects() {
project.documents.release_client_refs();
}
}
/// Stops what this host started: heap snapshots, notebook kernels, language servers, agents,
/// runs and terminals.
/// For a process that exits without dropping the host (the remote server).
@@ -509,7 +554,6 @@ impl Host {
// A capture's dump may hold secrets from the debuggee's memory: delete it before exiting.
ops::heap::shutdown(self).await;
self.environment.shutdown();
self.processes.kill_all();
self.terminals.kill_all();
let projects: Vec<_> = self.projects.write().drain().map(|(_, p)| p).collect();
for project in &projects {
@@ -529,22 +573,33 @@ impl Host {
project.notebooks.stop_admission();
project.agents.shutdown();
}
let stop_processes = async {
for project in &projects {
self.debugger.stop_under(&project.root).await;
}
self.processes.shutdown().await;
};
// Kernel cleanup owns its interrupt/termination/reaping deadlines. An
// outer LSP timeout must never abort it before owned children are reaped.
for project in &projects {
if let Some(bridge) = &project.kotlin_bridge {
bridge.shutdown().await;
let stop_kernels = async {
for project in &projects {
if let Some(bridge) = &project.kotlin_bridge {
bridge.shutdown().await;
}
project.notebooks.shutdown().await;
}
project.notebooks.shutdown().await;
}
};
let stop_language_servers = async {
for project in &projects {
project.lsp.shutdown_all().await;
}
};
if tokio::time::timeout(std::time::Duration::from_secs(10), stop_language_servers).await.is_err() {
tracing::warn!("language servers did not shut down in time");
}
let stop_lsp = async {
if tokio::time::timeout(std::time::Duration::from_secs(10), stop_language_servers).await.is_err() {
tracing::warn!("language servers did not shut down in time");
}
};
tokio::join!(stop_processes, stop_kernels, stop_lsp);
}
// ---- cancellable requests: the UI allocates ids, `cancel_request` cancels ----
@@ -598,6 +653,14 @@ impl Host {
let homes = self.global_settings.effective().languages.java.added_jdks;
ide_sdk::java::set_added_jdks(homes.into_iter().map(PathBuf::from));
}
/// Global Settings › Version Control › Git › Path to Git executable, for git started outside
/// a project's repositories (clone, init, agents, gh, plugins). A project's own value stays
/// with its repositories ([`Project::repos`]).
pub fn apply_git_executable(&self) {
let exe = self.global_settings.read_effective(|s| s.vcs.git.executable.trim().to_owned());
ide_vcs::set_default_git_executable((!exe.is_empty()).then(|| Path::new(&exe)));
}
}
#[cfg(test)]
@@ -611,17 +674,7 @@ mod tests {
let root = base.join("project");
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.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 host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
let project = Arc::downgrade(&host.open_project("main", &root).unwrap());
host.close_project_detached("main");
assert!(host.project("main").is_err());
+1 -7
View File
@@ -42,15 +42,9 @@ impl Fixture {
}
let syntax: Arc<std::sync::OnceLock<Arc<ide_language::Syntax>>> = Arc::default();
let host = Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: syntax.clone(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
..HostConfig::for_test(&base)
}));
let fixture = Self { host, base, syntax, _tmp: tmp };
fixture.set("enabled", json!(true));
+10 -1
View File
@@ -10,6 +10,7 @@
use super::diff::{ChangedFileText, MAX_DIFF_LINES, build_unified_diff};
use super::{edits_for, open_document, requested_files, whole_range};
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
use crate::ops::lsp::RUFF_ORGANIZE_IMPORTS;
use ide_core::{DocId, IdeError, IdeResult};
use std::path::Path;
@@ -157,7 +158,7 @@ async fn format(call: &Call, doc: DocId, info: &ide_workspace::DocumentInfo) ->
.await
}
/// Runs the `source.organizeImports` code action of the document's language server.
/// Runs the document's `source.organizeImports` code action, including the host's Ruff fallback.
/// Nothing offered: nothing to do, unless the server says it has no such action at all.
pub(super) async fn organize_imports(call: &Call, doc: DocId, path: &Path) -> IdeResult<()> {
let host = call.host();
@@ -173,12 +174,20 @@ pub(super) async fn organize_imports(call: &Call, doc: DocId, path: &Path) -> Id
}
};
let organizes = |kind: &str| kind == ORGANIZE_IMPORTS || kind.starts_with("source.organizeImports.");
let ruff_unavailable = query
.actions
.iter()
.find(|a| a.kind.as_deref() == Some(RUFF_ORGANIZE_IMPORTS))
.and_then(|a| a.disabled_reason.clone());
let action = query
.actions
.into_iter()
.filter(|a| a.disabled_reason.is_none() && a.kind.as_deref().is_some_and(organizes))
.max_by_key(|a| a.is_preferred);
let Some(action) = action else {
if let Some(reason) = ruff_unavailable {
return Err(IdeError::unavailable(reason));
}
let offered = query.advertised_kinds.is_none_or(|kinds| kinds.iter().any(|k| k == "source" || organizes(k)));
return if offered {
Ok(())
+2 -1
View File
@@ -488,7 +488,7 @@ async fn find_java_module(call: &Call, main: &str) -> IdeResult<Option<String>>
/// (compile errors are added to `errors`). Other configurations are returned as they are.
async fn resolve_jvm_application(
call: &Call,
config: RunConfig,
mut config: RunConfig,
errors: &mut BuildErrors,
) -> IdeResult<Result<RunConfig, String>> {
if !JVM_APPLICATION_KINDS.contains(&config.kind.as_str()) {
@@ -544,6 +544,7 @@ async fn resolve_jvm_application(
(Some(exec), "java") => exec.clone(),
_ => config.command.clone(),
};
config.extras.module = Some(module);
Ok(Ok(RunConfig { command, args, ..config }))
}
+2 -7
View File
@@ -102,9 +102,7 @@ This is useful to detect all repositories in a multi-repository project.
In OpenIDEA each root also tells its current `branch` (absent when HEAD is detached), `headCommit` and a merge, \
rebase or cherry-pick in progress (`operationInProgress`).",
|call| async move {
let host = call.host();
let window = call.window.clone();
let roots = call.host.blocking(move || crate::ops::vcs::vcs_roots(&host, &window)).await?;
let roots = crate::ops::vcs::vcs_roots(&call.host(), &call.window).await?;
let list: Vec<Value> = roots
.into_iter()
.map(|r| {
@@ -257,10 +255,7 @@ By default all Git repositories are returned.",
let include_ignored = call.flag("includeIgnored", false)?;
let page = Page::of(&call, STATUS_DEFAULT_LIMIT)?;
let host = call.host();
let h = host.clone();
let w = call.window.clone();
let repos: Vec<(PathBuf, Option<String>)> = host
.blocking(move || crate::ops::vcs::vcs_roots(&h, &w))
let repos: Vec<(PathBuf, Option<String>)> = crate::ops::vcs::vcs_roots(&host, &call.window)
.await?
.into_iter()
.map(|r| (r.root.into_path_buf(), r.head))
+19 -6
View File
@@ -43,12 +43,19 @@ pub fn agent_unsubscribe(host: &Host, window: &str, subscriber: String) -> IdeRe
Ok(())
}
/// Reads the ACP registry's install state for every provider from disk, so it runs on the
/// blocking pool.
#[command(trust = trusted)]
pub fn agent_providers(host: &Host, window: &str) -> IdeResult<Vec<AgentProvider>> {
pub async fn agent_providers(host: &Host, window: &str) -> IdeResult<Vec<AgentProvider>> {
host.require_trust(window)?;
let mut providers = host.project(window)?.agents.providers();
ide_agent::registry::mark_updates(&registry_paths(host), &mut providers);
Ok(providers)
let agents = host.project(window)?.agents.clone();
let paths = registry_paths(host);
host.blocking(move || {
let mut providers = agents.providers();
ide_agent::registry::mark_updates(&paths, &mut providers);
Ok(providers)
})
.await
}
/// Hermes Agent profiles on this machine (`default` first); empty without Hermes.
@@ -249,9 +256,15 @@ pub async fn agent_commands(
host.project(window)?.agents.commands(&provider, task.as_deref()).await
}
/// Entries of `task`'s conversation, or of its subagent `subagent`'s.
/// Entries of `task`'s conversation, or of its subagent `subagent`'s. Async so a long
/// conversation is cloned and serialised off the main thread.
#[command(trust = always)]
pub fn agent_entries(host: &Host, window: &str, task: String, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
pub async fn agent_entries(
host: &Host,
window: &str,
task: String,
subagent: Option<String>,
) -> IdeResult<Vec<AgentEntry>> {
host.project(window)?.agents.entries(&task, subagent)
}
+148 -70
View File
@@ -1,6 +1,6 @@
//! Maven / Gradle tool windows (the build model and its background sync) and
//! Build › Build Project (compiling with the project's build system).
mod workspace;
pub(super) mod workspace;
use super::dependencies::{MavenCentralArtifacts, MavenCentralGroups, MavenCentralVersions};
use crate::ops::Channel;
@@ -9,13 +9,16 @@ use ide_command::command;
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
use ide_build::maven::completion::{PomCompletion, PomCompletionOption};
use ide_build::maven::sources;
use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions};
use ide_build::pom_edit::{ArtifactKey, Exclusion};
use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress};
use ide_core::settings::Settings;
use ide_core::{DocId, FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit};
use std::collections::HashMap;
use std::path::Path;
use ide_core::{
CancellationToken, DocId, FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit,
};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
@@ -181,7 +184,7 @@ fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings)
/// `model` building with the Maven profiles of the last sync (`-P`), as Maven runs from
/// the tool window do.
fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
pub(super) fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
let profiles = ide_build::maven_profiles(cache);
if let (Some(m), false) = (&mut model.maven, profiles.is_empty()) {
for p in &mut m.projects {
@@ -281,6 +284,35 @@ pub async fn gradle_unlink_projects(host: &Host, window: &str, paths: Vec<String
set_gradle_projects(host, window, paths, false).await
}
struct MavenSourceRefresh {
root: PathBuf,
repository: PathBuf,
candidates: Vec<(usize, sources::Artifact)>,
}
fn cached_maven_sources(
model: &BuildModel,
scopes: Vec<workspace::Scope>,
window_root: &Path,
build_dir: Option<&str>,
) -> Vec<MavenSourceRefresh> {
let Some(maven) = &model.maven else { return Vec::new() };
scopes
.into_iter()
.filter(|scope| workspace::selected(scope, window_root, BuildTool::Maven, build_dir))
.filter_map(|scope| {
let repository = ide_sdk::apply::maven_local_repository(&scope.root, &scope.settings)
.or_else(ide_build::maven::default_local_repo)?;
let projects = maven.projects.iter().enumerate().filter(|(_, project)| {
Path::new(project.project_root.as_deref().unwrap_or_default()) == scope.root
|| (project.project_root.is_none() && scope.root == window_root)
});
let candidates = sources::cached_snapshots(&repository, projects);
(!candidates.is_empty()).then_some(MavenSourceRefresh { root: scope.root, repository, candidates })
})
.collect()
}
/// Runs Maven (`help:effective-pom dependency:tree`) or Gradle (`tasks --all`) in the
/// background, reporting progress on `on_progress`; cancellable with `cancel_request(request)`.
/// Returns the refreshed model; a failed build is reported in its `syncError`.
@@ -377,72 +409,122 @@ pub async fn build_sync(
let scopes = workspace::scopes(&p, &config)?;
let model = workspace::load_scopes(&p.root, &scopes);
let updates = workspace::update_files(&p.root, &scopes, &model, tool);
Ok::<_, IdeError>((model, profiles_changed, offline_changed, updates))
let snapshots = if tool == BuildTool::Maven && !offline {
cached_maven_sources(&model, scopes, &p.root, build_dir.as_deref())
} else {
Vec::new()
};
Ok::<_, IdeError>((model, profiles_changed || offline_changed, updates, snapshots))
})
.await
.map_err(join_err);
host.end_request(request);
let (model, profiles_changed, offline_changed, updates) = result??;
if completion_token.is_cancelled() {
return Err(IdeError::cancelled());
}
// Gradle may report project folders outside the project (`includeFlat`), and a Maven
// reactor may have gained or dropped modules beside it: index and list them.
project.refresh_index_scope();
let p = project.clone();
tokio::task::spawn_blocking(move || p.refresh_repositories());
// New source folders and dependency versions: the Project view and External Libraries reload.
project.sink.emit(ide_core::IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
if tool == BuildTool::Maven
&& model.maven.is_some()
&& let Some(bridge) = &project.kotlin_bridge
{
bridge.configure_maven(offline, bridge_profiles);
}
// jdtls re-imports on pom changes but misses artifacts added to ~/.m2
// meanwhile ("missing artifact" stays until Invalidate Caches); asking it
// to update the project configurations re-resolves them (#436). The same
// holds for Gradle: it reuses its cached classpath on restart, so a
// dependency added to `build.gradle` stays unresolved until told to sync.
let lsp = project.lsp.clone();
let documents = project.documents.clone();
tokio::spawn(async move {
if profiles_changed || offline_changed {
// jdtls takes the profiles and offline mode from its Maven settings (see `ide_sdk::maven_profiles`).
lsp.reconfigure().await;
let result = async {
let (mut model, reconfigure, updates, snapshots) = result??;
if completion_token.is_cancelled() {
return Err(IdeError::cancelled());
}
let first = updates.first().cloned();
for file in updates {
let uri = ide_lsp::path_to_uri_string(&file);
if let Err(e) = lsp.java_update_project_configs(&file, vec![uri]).await {
tracing::debug!("java/projectConfigurationsUpdate: {e}");
}
}
let changed = {
let lsp = lsp.clone();
tokio::task::spawn_blocking(move || lsp.changed_library_archives()).await.unwrap_or_default()
};
if let Some(file) = first
&& let Err(e) = lsp.java_refresh_archives(&file, &changed).await
// A reactor or Gradle build may have changed its external project folders.
project.refresh_index_scope();
let p = project.clone();
tokio::task::spawn_blocking(move || p.refresh_repositories());
project.sink.emit(IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
if tool == BuildTool::Maven
&& model.maven.is_some()
&& let Some(bridge) = &project.kotlin_bridge
{
tracing::debug!("openidea.java.refreshArchives: {e}");
bridge.configure_maven(offline, bridge_profiles.clone());
}
refresh_library_classes(&lsp, &documents).await;
});
Ok(model)
let lsp = project.lsp.clone();
let documents = project.documents.clone();
if snapshots.is_empty() {
tokio::spawn(async move {
update_java_projects(&lsp, &updates, reconfigure, None).await;
refresh_library_archives(&lsp, &documents, &updates, Vec::new()).await;
});
} else {
// JDT LS resolves the binary jars while importing Maven projects.
update_java_projects(&lsp, &updates, reconfigure, Some(&completion_token)).await;
let cancel = completion_token.clone();
let (updated, refreshed) = tokio::task::spawn_blocking(move || {
let mut refreshed = Vec::new();
if let Some(maven) = &model.maven {
for batch in snapshots {
if cancel.is_cancelled() {
break;
}
refreshed.extend(sources::refresh_snapshots(
&batch.root,
&maven.projects,
&batch.repository,
&batch.candidates,
&bridge_profiles,
&cancel,
));
}
}
(model, refreshed)
})
.await
.map_err(join_err)?;
model = updated;
tokio::spawn(async move {
refresh_library_archives(&lsp, &documents, &updates, refreshed).await;
});
}
if completion_token.is_cancelled() {
return Err(IdeError::cancelled());
}
Ok(model)
}
.await;
host.end_request(request);
result
}
/// Open library classes whose jar was replaced in place (a SNAPSHOT installed
/// again keeps its path) show the new contents, like a reopened one.
async fn refresh_library_classes(lsp: &Arc<ide_lsp::LspManager>, documents: &Arc<ide_workspace::Documents>) {
async fn update_java_projects(
lsp: &ide_lsp::LspManager,
updates: &[PathBuf],
reconfigure: bool,
wait: Option<&CancellationToken>,
) {
if reconfigure {
// jdtls takes the profiles and offline mode from its Maven settings.
lsp.reconfigure().await;
}
// JDT LS caches its classpath and re-imports on build-file changes. Ask it to
// re-resolve dependencies even when the build files stayed the same (#436).
if let Err(e) = lsp.java_update_project_configs(updates, wait).await {
tracing::debug!("Updating Java project configurations: {e}");
}
}
/// Re-read open library classes whose binary or attached sources changed in place.
async fn refresh_library_archives(
lsp: &Arc<ide_lsp::LspManager>,
documents: &Arc<ide_workspace::Documents>,
updates: &[PathBuf],
refreshed: Vec<PathBuf>,
) {
let changed = {
let lsp = lsp.clone();
tokio::task::spawn_blocking(move || lsp.changed_library_archives()).await.unwrap_or_default()
};
let archives: HashSet<_> = changed.into_iter().chain(refreshed).collect();
if let Err(e) = lsp.java_refresh_archives(updates, &archives).await {
tracing::debug!("openidea.java.refreshArchives: {e}");
}
let changed = {
let (lsp, documents) = (lsp.clone(), documents.clone());
tokio::task::spawn_blocking(move || {
lsp.invalidate_library_archives(&archives);
documents
.open_documents()
.into_iter()
.filter_map(|doc| Some((doc, documents.virtual_uri(doc).ok().flatten()?)))
.filter(|(_, uri)| lsp.library_class_changed(uri))
.filter(|(_, uri)| {
lsp.library_class_changed(uri)
|| ide_lsp::LspManager::library_archive(uri).is_some_and(|archive| archives.contains(&archive))
})
.collect::<Vec<_>>()
})
.await
@@ -952,16 +1034,18 @@ pub async fn build_run(
items: Vec::new(),
});
}
let mut launch_caches = Vec::new();
let plan = if let Some(id) = cmake {
launch_caches.push(cache.clone());
let configs = super::run::project_configs(&root, &settings, &config_dir)?;
cmake_plan(&root, kind, &configs, &id)?
} else if let Some(workspace) = ide_workspace::workspace::Workspace::load(&root)? {
let mut combined: Option<compile::BuildPlan> = None;
for member in workspace.projects.iter().filter(|p| file.as_ref().is_none_or(|f| f.starts_with(p))) {
let settings = ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective();
let member_cache =
if member == &root { cache.clone() } else { cache.join(crate::project::project_key(member)) };
let member_cache = workspace::cache_at(&root, &cache, member);
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
launch_caches.push(member_cache);
let plan = prepare_plan(
compile::plan(
member,
@@ -985,6 +1069,7 @@ pub async fn build_run(
plan
} else {
let model = with_profiles(load(&root, &cache, &settings), &cache);
launch_caches.push(cache.clone());
match compile::plan(
&root,
&model,
@@ -1007,7 +1092,9 @@ pub async fn build_run(
});
if kind == BuildKind::Rebuild {
// The clean removed outputs that earlier launch snapshots still hold.
launch_project.java_launch_snapshots.lock().forget_reusable_snapshots();
for cache in launch_caches {
launch_project.java_launches.for_cache(&cache).snapshots.lock().forget_reusable_snapshots();
}
}
let result = result?;
if result.success && single && kind == BuildKind::Build {
@@ -1359,17 +1446,8 @@ mod maven_completion_tests {
let path = root.join("pom.xml");
std::fs::write(&path, text).unwrap();
let host = Host::new(crate::HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.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 host =
Host::new(crate::HostConfig { local_data_dir: base.join("local"), ..crate::HostConfig::for_test(&base) });
let project = host.open_project("main", &root).unwrap();
let info = project.documents.open(&path).unwrap();
+23 -6
View File
@@ -1,12 +1,33 @@
use super::*;
use std::path::PathBuf;
pub(super) struct Scope {
pub(in crate::ops) struct Scope {
pub root: PathBuf,
pub cache: PathBuf,
pub settings: Settings,
}
pub(in crate::ops) fn scope_for(project: &Project, path: &Path) -> IdeResult<Scope> {
let workspace = ide_workspace::workspace::Workspace::load(&project.root)?;
let root = workspace
.as_ref()
.and_then(|w| w.projects.iter().filter(|p| path.starts_with(p)).max_by_key(|p| p.components().count()))
.unwrap_or(&project.root);
Ok(Scope {
cache: cache_at(&project.root, &project.build_cache_dir(), root),
settings: if root == &project.root {
project.settings.effective()
} else {
project.settings.for_project(root).effective()
},
root: root.clone(),
})
}
pub(super) fn cache_at(window_root: &Path, cache: &Path, root: &Path) -> PathBuf {
if root == window_root { cache.to_owned() } else { cache.join(crate::project::project_key(root)) }
}
pub(super) fn scopes(project: &Project, config: &Path) -> IdeResult<Vec<Scope>> {
scopes_at(&project.root, &project.build_cache_dir(), config, project.settings.effective())
}
@@ -19,11 +40,7 @@ fn scopes_at(root: &Path, cache: &Path, config: &Path, settings: Settings) -> Id
.into_iter()
.filter(|p| p.is_dir())
.map(|root| Scope {
cache: if root == window_root {
cache.to_owned()
} else {
cache.join(crate::project::project_key(&root))
},
cache: cache_at(window_root, cache, &root),
settings: ide_workspace::SettingsStore::load(config, Some(&root)).effective(),
root,
})
+1 -12
View File
@@ -646,7 +646,6 @@ mod tests {
use super::*;
use crate::HostConfig;
use ide_db::DbDriver;
use std::sync::Arc;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_reporting_error_stops_the_batch_and_releases_the_request() {
@@ -654,17 +653,7 @@ mod tests {
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir(&root).unwrap();
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.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 host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
let window = "main";
host.open_project(window, &root).unwrap();
host.set_project_trust(&root, true, false).await.unwrap();
+9 -1
View File
@@ -44,7 +44,15 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
&& config.request == "launch"
&& let Ok(project) = host.project(window)
{
super::python::prepare_debug(&mut config, &super::python::paths(&project))?;
let python = super::python::debug_python(&config);
let paths = super::python::with_user_paths(
super::python::paths(&project),
&host.config_dir,
&project,
python.as_deref(),
config.cwd.as_deref(),
);
super::python::prepare_debug(&mut config, &paths)?;
}
let label = window;
let (sink, flush_output) = output::coalescing_sink(host.window_sink(label));
@@ -31,18 +31,11 @@ impl Fixture {
let events = Arc::new(Mutex::new(Vec::new()));
let captured = events.clone();
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(move |_| {
let events = captured.clone();
Arc::new(move |event| events.lock().push(event))
}),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
..HostConfig::for_test(&base)
});
let missing = base.join("missing").join("kotlin-debug-adapter");
host.global_settings
+34 -36
View File
@@ -4,7 +4,7 @@ use ide_command::command;
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, RequestId};
use ide_workspace::dependencies::{
DependencyVersionSource, DependencyVersions, PythonRequirements, UnsatisfiedRequirement, cargo, go, maven, npm,
python,
pypi, python,
};
use std::collections::BTreeMap;
use std::hash::{DefaultHasher, Hash, Hasher};
@@ -301,11 +301,39 @@ pub async fn python_requirements(
result
}
/// A project on pypi.org by its exact name; `None` when PyPI has no such project.
#[command(trust = outside_restricted)]
pub async fn pypi_package(
host: &Host,
window: &str,
name: String,
request: RequestId,
) -> IdeResult<Option<pypi::PypiPackage>> {
let url = pypi::project_url(name.trim()).ok_or_else(|| IdeError::invalid("not a package name"))?;
let cancel = host.begin_project_read_request(window, request);
let result = host
.blocking(move || {
let search_path = std::env::var_os("PATH").unwrap_or_default();
let text = ide_tools::Http::new(&search_path)?.https_only().get_text_limited_or_empty_on_404(
&url,
16 * 1024 * 1024,
&cancel,
)?;
// The helper's body for a 404.
if text == "[]" {
return Ok(None);
}
pypi::parse_project(&text).map(Some).ok_or_else(|| IdeError::internal("invalid PyPI response"))
})
.await;
host.end_request(request);
result
}
#[cfg(test)]
mod tests {
use super::*;
use crate::HostConfig;
use std::sync::Arc;
struct Source;
impl DependencyVersionSource for Source {
@@ -326,17 +354,7 @@ mod tests {
let text = "# 中文 😀\n[dependencies]\ntokio = { version = \"0.2\", features = [\"full\"] }\nserde = \"1.0.100\"\nlocal = { path = \"../x\", version = \"0.2\" }\n";
let path = root.join("Cargo.toml");
std::fs::write(&path, text).unwrap();
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.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 host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
let project = host.open_project("main", &root).unwrap();
let info = project.documents.open(&path).unwrap();
for package in ["tokio", "serde"] {
@@ -382,17 +400,7 @@ mod tests {
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 host = Host::new(HostConfig { local_data_dir: base_dir.join("local"), ..HostConfig::for_test(&base_dir) });
let project = host.open_project("main", &root).unwrap();
let info = project.documents.open(&path).unwrap();
// Restricted Mode never runs the interpreter.
@@ -432,17 +440,7 @@ mod tests {
let text = "{\n \"devDependencies\": { \"@types/node\": \"^20\" }\n}\n";
let path = root.join("package.json");
std::fs::write(&path, text).unwrap();
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.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 host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
let project = host.open_project("main", &root).unwrap();
let info = project.documents.open(&path).unwrap();
host.dependency_versions.versions(&CachedNpm, "@types/node", &CancellationToken::new()).unwrap();
@@ -458,4 +456,4 @@ mod tests {
}
}
ide_command::domain!(dependencies: dependency_versions, python_requirements);
ide_command::domain!(dependencies: dependency_versions, python_requirements, pypi_package);
+25 -1
View File
@@ -1,6 +1,6 @@
use crate::Host;
use ide_command::command;
use ide_core::{DocId, IdeError, IdeResult, OutlineItem, Range};
use ide_core::{DocId, IdeError, IdeResult, OutlineItem, Range, TextEdit};
use ide_language::{FoldRange, SyntaxHighlights};
use ide_text::LineEnding;
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, HistoryEntry};
@@ -195,6 +195,29 @@ pub async fn doc_python_facts(host: &Host, window: &str, doc: DocId) -> IdeResul
blocking(move || Ok(syntax.python_facts(&snap.language, &snap.text))).await
}
/// Rearrange Code: the edits that put the document's class members in arrangement order (Python
/// for now); none when they already are or the language has no arrangement.
#[command(trust = always)]
pub async fn doc_rearrange(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<TextEdit>> {
let project = host.project(window)?;
let syntax = host.syntax();
let snap = project.documents.text_snapshot(doc)?;
blocking(move || {
let Some(rearranged) = syntax.rearranged(&snap.language, &snap.text) else { return Ok(Vec::new()) };
let text = ide_text::Document::new(&snap.text);
Ok(text
.diff(&rearranged)
.changes
.into_iter()
.map(|c| TextEdit {
range: Range::new(text.offset_to_pos(c.from), text.offset_to_pos(c.to)),
new_text: c.insert,
})
.collect())
})
.await
}
/// Extend Selection (⌥↑): syntax ranges around `offset`, innermost first.
/// Large documents fall back to word / line / document ranges.
#[command(trust = always)]
@@ -244,6 +267,7 @@ ide_command::domain!(
doc_open_virtual,
doc_outline,
doc_python_facts,
doc_rearrange,
doc_selection_ranges,
doc_set_bom,
doc_set_encoding,
+24 -8
View File
@@ -28,18 +28,11 @@ impl Fixture {
let events = Arc::new(Mutex::new(Vec::new()));
let captured = events.clone();
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(move |_| {
let events = captured.clone();
Arc::new(move |event| events.lock().push(event))
}),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
..HostConfig::for_test(&base)
});
let project = host.open_project("main", &root).unwrap();
Self { _temp: temp, host, project, events, path, outside }
@@ -205,3 +198,26 @@ async fn synchronization_only_changes_the_calling_windows_documents() {
assert_eq!(f.project.documents.snapshot(original.id).unwrap().text, "external change in shared file\n");
assert_eq!(other.documents.snapshot(other_doc.id).unwrap().text, other_doc.text);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn rearrange_returns_utf16_edits_that_put_methods_in_order() {
let f = Fixture::new();
let path = f.project.root.join("board.py");
let text = "class Board:\n def 移动(self):\n return '→'\n\n def __init__(self):\n self.名前 = 1 # 初始化\n";
std::fs::write(&path, text).unwrap();
let doc = f.open(&path).await.id;
let edits = doc_rearrange(&f.host, "main", doc).await.unwrap();
let mut rearranged = ide_text::Document::new(text);
rearranged.apply_edits(&edits).unwrap();
assert_eq!(
rearranged.text(),
"class Board:\n def __init__(self):\n self.名前 = 1 # 初始化\n\n def 移动(self):\n return '→'\n"
);
// Already in order, or broken: nothing to do.
std::fs::write(&path, rearranged.text()).unwrap();
f.sync().await;
assert!(doc_rearrange(&f.host, "main", doc).await.unwrap().is_empty());
std::fs::write(&path, "class A:\n def b(self\n def __init__(self): ...\n").unwrap();
f.sync().await;
assert!(doc_rearrange(&f.host, "main", doc).await.unwrap().is_empty());
}
+12 -2
View File
@@ -1,7 +1,7 @@
use super::Channel;
use crate::{Host, Project};
use ide_command::command;
use ide_core::{IdeError, IdeResult, RequestId};
use ide_core::{IdeError, IdeResult, IpcBytes, RequestId};
use ide_vfs::FileEntry;
use ide_workspace::DeletionUndo;
use std::path::{Path, PathBuf};
@@ -209,7 +209,7 @@ pub fn fs_create_file(host: &Host, window: &str, path: PathBuf) -> IdeResult<()>
}
#[command(trust = always)]
pub async fn fs_create_file_bytes(host: &Host, window: &str, path: PathBuf, data: Vec<u8>) -> IdeResult<()> {
pub async fn fs_create_file_bytes(host: &Host, window: &str, path: PathBuf, data: IpcBytes) -> IdeResult<()> {
let project = host.project(window).ok();
host.blocking(move || {
ide_vfs::create_file_bytes(&path, &data)?;
@@ -228,6 +228,15 @@ pub fn fs_create_dir(path: PathBuf) -> IdeResult<()> {
ide_vfs::create_dir(&path)
}
/// The scratch files' folder of this host (`<data dir>/scratches`), created. A remote window
/// keeps its scratches on the server, where its file commands run.
#[command(trust = always)]
pub fn fs_scratches_dir(host: &Host) -> IdeResult<ide_core::IpcPath> {
let dir = host.data_dir.join("scratches");
std::fs::create_dir_all(&dir)?;
Ok(dir.into())
}
/// Toggle Read-only Attribute: sets the writable bit (and the open document's
/// state). Returns whether the file is read-only now.
#[command(trust = always)]
@@ -383,6 +392,7 @@ ide_command::domain!(
fs_read_dir,
fs_read_text,
fs_rename,
fs_scratches_dir,
fs_set_writable,
fs_synchronize_directories,
fs_undo_delete,
+1 -11
View File
@@ -26,17 +26,7 @@ impl Fixture {
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.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 host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
host.open_project(WINDOW, &root).unwrap();
host.set_project_trust(&root, true, false).await.unwrap();
Self { host, base, root, _temp: temp }
+57 -62
View File
@@ -4,7 +4,7 @@ pub(crate) mod cache;
use crate::Host;
use ide_command::command;
use super::build::load;
use super::build::{load, with_profiles, workspace};
use ide_build::BuildModel;
use ide_build::compile;
use ide_core::error::ErrorKind;
@@ -46,37 +46,44 @@ pub(crate) async fn resolve_launch(
) -> IdeResult<JavaLaunchInfo> {
let started = std::time::Instant::now();
let project = host.project(window)?;
let module = project.root.join(module);
let module = ide_core::project_roots::resolve(&project.root, &module);
let scope = {
let (project, module) = (project.clone(), module.clone());
tokio::task::spawn_blocking(move || workspace::scope_for(&project, &module))
.await
.map_err(|e| IdeError::internal(e.to_string()))??
};
if !project.lsp.java_served_by_jdtls(&module) {
return resolve_launch_without_jdtls(host, &project, module, test, policy, cancel).await;
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel).await;
}
let waiting = project.java_launches_waiting.add(module.clone(), test, policy);
let settings = project.settings.effective();
let scope = std::sync::Arc::new(scope);
let launches = project.java_launches.for_cache(&scope.cache);
let waiting = launches.waiting.add(module.clone(), test, policy);
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
let build = policy != BuildPolicy::NoBuild;
let full = policy == BuildPolicy::Rebuild;
let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, external, mut delegated, prefer_maven, is_maven) = {
let project = project.clone();
let settings = settings.clone();
let (model, external, mut delegated, is_maven) = {
let scope = scope.clone();
let launches = launches.clone();
let module = module.clone();
tokio::task::spawn_blocking(move || {
project.java_launch_snapshots.lock().initialize();
let model = load(&project.root, &project.build_cache_dir(), &settings);
let non_java = build && compile::launch_has_non_java_sources(&project.root, &model, &module, test);
let is_maven =
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
let prefer_maven = settings.languages.java.maven.delegate_build;
launches.snapshots.lock().initialize();
let root = &scope.root;
let model = load_launch_model(&scope);
let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test);
let is_maven = is_maven_module(root, &model, &module);
let delegated = build
&& delegates_to_external_build(
is_maven,
policy,
non_java,
cache::has_record(&project.root, &project.build_cache_dir(), &module),
cache::has_record(root, &scope.cache, &module),
prefer_maven,
);
let external = non_java || delegated;
(model, external, delegated, prefer_maven, is_maven)
(model, external, delegated, is_maven)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -101,7 +108,7 @@ pub(crate) async fn resolve_launch(
}
let model = std::sync::Arc::new(model);
let members = if delegated {
build_members(&project, &model, &module, test, prefer_maven, &waiting, cancel).await?
build_members(&project, &scope, &model, &module, test, &waiting, cancel).await?
} else {
Vec::new()
};
@@ -110,7 +117,8 @@ pub(crate) async fn resolve_launch(
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
let _external_build = external_build;
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
// Module outputs the launch runs from a snapshot of: the originals must not come back.
let mut snapshotted = Vec::new();
// The modules of the launches sharing this build also share its classpath probe.
@@ -118,8 +126,8 @@ pub(crate) async fn resolve_launch(
std::iter::once(module.clone()).chain(members.iter().map(|m| m.module.clone())).collect();
let built = if delegated {
let rebuild_on_jdt_errors = rebuild_on_jdt_errors(policy, prefer_maven, info.error_count);
let outputs = project.java_launch_snapshots.lock().build(
&project.root,
let outputs = launches.snapshots.lock().build(
root,
&model,
&module,
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members },
@@ -132,7 +140,7 @@ pub(crate) async fn resolve_launch(
snapshotted = outputs.originals;
copies
} else if external {
let built = compile::build_for_launch(&project.root, &model, &module, test, build_kind, &cancel)?;
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel)?;
if let Some(failure) = built.failure {
if policy != BuildPolicy::MakeAndContinueOnErrors {
return Err(IdeError::internal(failure));
@@ -149,24 +157,15 @@ pub(crate) async fn resolve_launch(
// m2e runs inside jdtls on the server JDK and can resolve a different
// Maven profile/classifier than the module build. Ask the same Maven
// process that built the module for its runtime/test dependencies.
let maven_cp = compile::module_classpaths(
&project.root,
&model,
&probed,
test,
local_repo,
&project.build_cache_dir(),
&cancel,
);
let maven_cp = compile::module_classpaths(root, &model, &probed, test, local_repo, cache, &cancel);
merge_maven_launch_classpath(&mut class_paths, &mut info, maven_cp, &snapshotted)?;
} else {
append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths));
}
info.class_paths = class_paths;
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
if build && !delegated {
let cache_dir = project.build_cache_dir();
match compile::process_launch_resources(&project.root, &model, &cache_dir, &info.class_paths, &cancel) {
match compile::process_launch_resources(root, &model, cache, &info.class_paths, &cancel) {
Ok(tasks) if !tasks.is_empty() => tracing::info!(?tasks, "Processed launch resources with Gradle"),
Ok(_) => {}
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
@@ -177,7 +176,7 @@ pub(crate) async fn resolve_launch(
}
}
let compile_ms = started.elapsed().as_millis() - lsp_ms;
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
@@ -194,28 +193,36 @@ pub(crate) async fn resolve_launch(
.map_err(|e| IdeError::internal(e.to_string()))?
}
fn load_launch_model(scope: &workspace::Scope) -> BuildModel {
with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache)
}
fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module))
}
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
/// build tool compiles it, and the classpath comes from that server, else from Maven.
async fn resolve_launch_without_jdtls(
host: &Host,
project: &std::sync::Arc<crate::Project>,
module: PathBuf,
scope: workspace::Scope,
test: bool,
policy: BuildPolicy,
cancel: &CancellationToken,
) -> IdeResult<JavaLaunchInfo> {
let started = std::time::Instant::now();
let settings = project.settings.effective();
let scope = std::sync::Arc::new(scope);
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, built) = {
let (root, cache, settings, module, cancel) =
(project.root.clone(), project.build_cache_dir(), settings.clone(), module.clone(), cancel.clone());
let (scope, module, cancel) = (scope.clone(), module.clone(), cancel.clone());
tokio::task::spawn_blocking(move || {
let model = load(&root, &cache, &settings);
let model = load_launch_model(&scope);
let built = if policy == BuildPolicy::NoBuild {
None
} else {
Some(compile::build_for_launch(&root, &model, &module, test, kind, &cancel))
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel))
};
(model, built)
})
@@ -249,9 +256,9 @@ async fn resolve_launch_without_jdtls(
let build_ms = started.elapsed().as_millis();
let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?;
let data_dir = host.local_data_dir.clone();
let project = project.clone();
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
match from_server {
Some(server) => {
info.project_root = server.classpath.project_root;
@@ -260,26 +267,14 @@ async fn resolve_launch_without_jdtls(
append_unique_class_paths(&mut class_paths, server.classpath.class_paths);
}
None => {
let is_maven = model
.maven
.as_ref()
.is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
if !is_maven {
if !is_maven_module(root, &model, &module) {
return Err(IdeError::unavailable(
"Cannot resolve the classpath: the Java language server does not report it \
(java-analyzer/projectClasspath), and the module is not a Maven project",
));
}
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
let classpath = compile::module_classpath(
&project.root,
&model,
&module,
test,
local_repo,
&project.build_cache_dir(),
&cancel,
)?;
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
let classpath = compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?;
append_unique_class_paths(
&mut class_paths,
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
@@ -287,8 +282,8 @@ async fn resolve_launch_without_jdtls(
}
}
info.class_paths = class_paths;
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
@@ -445,10 +440,10 @@ fn apply_library_classpath(
/// whether its JDT errors call for a clean rebuild (as its own launch would decide).
async fn build_members(
project: &std::sync::Arc<crate::Project>,
scope: &std::sync::Arc<workspace::Scope>,
model: &std::sync::Arc<BuildModel>,
module: &Path,
test: bool,
prefer_maven: bool,
waiting: &cache::WaitingGuard,
cancel: &CancellationToken,
) -> IdeResult<Vec<cache::Member>> {
@@ -456,10 +451,11 @@ async fn build_members(
if others.is_empty() {
return Ok(Vec::new());
}
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
let joining = {
let (project, model, module) = (project.clone(), model.clone(), module.to_path_buf());
let (scope, model, module) = (scope.clone(), model.clone(), module.to_path_buf());
tokio::task::spawn_blocking(move || {
joining_launches(&project.root, &project.build_cache_dir(), &model, &module, test, others, prefer_maven)
joining_launches(&scope.root, &scope.cache, &model, &module, test, others, prefer_maven)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -500,8 +496,7 @@ fn joining_launches(
others
.into_iter()
.filter(|o| {
let is_maven =
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == o.module));
let is_maven = is_maven_module(root, model, &o.module);
o.test == test
&& matches!(o.policy, BuildPolicy::Automatic | BuildPolicy::Make)
&& compile::launch_reactor(root, model, &o.module).as_ref() == Some(&reactor)
+291 -8
View File
@@ -6,14 +6,20 @@ use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::SystemTime;
#[derive(Debug, Serialize, Deserialize)]
pub(super) struct Outputs {
fingerprint: Option<LaunchFingerprint>,
pub snapshot: PathBuf,
pub originals: Vec<PathBuf>,
/// Live output and snapshot metadata at publication. Older records may hold an
/// incomplete copy and are rebuilt once (#5404).
#[serde(default)]
output_stamps: Option<Vec<OutputStamp>>,
#[serde(skip)]
pub failure: Option<String>,
/// Whether this result replaces jdtls diagnostics with a clean Maven build or a
@@ -23,12 +29,93 @@ pub(super) struct Outputs {
}
impl Outputs {
fn reusable(&self, fingerprint: &Option<LaunchFingerprint>, snapshots: &Path) -> bool {
fn reusable(
&self,
fingerprint: &Option<LaunchFingerprint>,
snapshots: &Path,
output_dirs: impl Iterator<Item = PathBuf>,
cancel: &CancellationToken,
) -> bool {
fingerprint.is_some()
&& self.fingerprint == *fingerprint
&& self.snapshot.parent() == Some(snapshots)
&& !self.originals.is_empty()
&& (0..self.originals.len()).all(|i| self.snapshot.join(i.to_string()).is_dir())
&& self.output_stamps.as_ref().is_some_and(|stamps| {
stamps.len() == self.originals.len()
&& output_dirs.eq(self.originals.iter().cloned())
&& self.originals.iter().zip(stamps).enumerate().all(|(i, (dir, stamp))| {
Contents::scan(dir, cancel).is_some_and(|live| live.stamp() == stamp.live)
&& Contents::scan(&self.snapshot.join(i.to_string()), cancel)
.is_some_and(|copy| copy.class_stamp() == stamp.snapshot_classes)
})
})
}
}
#[derive(Debug, Serialize, Deserialize)]
struct OutputStamp {
live: u64,
// A launched app may write non-class files under its snapshot classpath root.
snapshot_classes: u64,
}
/// Relative paths, sizes and mtimes are enough to detect ordinary compiler rewrites
/// without reading class or resource bytes.
#[derive(Debug, PartialEq, Eq)]
struct Contents(Vec<(PathBuf, u64, SystemTime)>);
impl Contents {
fn scan(root: &Path, cancel: &CancellationToken) -> Option<Self> {
if !fs::metadata(root).ok()?.is_dir() {
return None;
}
let mut files = Vec::new();
let mut pending = vec![root.to_path_buf()];
while let Some(dir) = pending.pop() {
if cancel.is_cancelled() {
return None;
}
for entry in fs::read_dir(dir).ok()? {
let entry = entry.ok()?;
let meta = entry.metadata().ok()?;
let path = entry.path();
if meta.is_dir() {
pending.push(path);
} else {
files.push((path.strip_prefix(root).ok()?.to_path_buf(), meta.len(), meta.modified().ok()?));
}
}
}
files.sort_unstable_by(|a, b| a.0.cmp(&b.0));
Some(Self(files))
}
fn stamp(&self) -> u64 {
let mut hasher = DefaultHasher::new();
self.0.hash(&mut hasher);
hasher.finish()
}
fn classes(&self) -> impl Iterator<Item = &(PathBuf, u64, SystemTime)> {
self.0.iter().filter(|(path, _, _)| path.extension().is_some_and(|ext| ext == "class"))
}
fn class_stamp(&self) -> u64 {
let mut hasher = DefaultHasher::new();
for file in self.classes() {
file.hash(&mut hasher);
}
hasher.finish()
}
fn matches_copy(&self, copy: &Self) -> bool {
// Copying preserves relative paths and sizes. Each tree has its own mtimes.
self.0.len() == copy.0.len()
&& self
.0
.iter()
.zip(&copy.0)
.all(|((path, len, _), (copied, copied_len, _))| path == copied && len == copied_len)
}
}
@@ -64,6 +151,30 @@ pub(super) struct Member {
pub rebuild_on_jdt_errors: bool,
}
/// Launches share a build only within the same workspace project's cache.
#[derive(Default)]
pub(crate) struct Sessions(Mutex<HashMap<PathBuf, Arc<Launches>>>);
pub(in crate::ops) struct Launches {
pub waiting: Waiting,
pub snapshots: Mutex<Session>,
}
impl Sessions {
pub(in crate::ops) fn for_cache(&self, cache: &Path) -> Arc<Launches> {
self.0
.lock()
.entry(cache.to_owned())
.or_insert_with(|| {
Arc::new(Launches {
waiting: Waiting::default(),
snapshots: Mutex::new(Session::new(cache.to_owned())),
})
})
.clone()
}
}
/// Java launches from their start until their build: one launch's Maven run also builds
/// the modules of launches still waiting (configurations started together, #3971).
#[derive(Default)]
@@ -256,13 +367,23 @@ impl Session {
}
if let Some(outputs) = previous.as_ref()
&& policy != BuildPolicy::Rebuild
&& outputs.reusable(&before, &snapshots)
&& let Some(maven) = &model.maven
&& outputs.reusable(
&before,
&snapshots,
compile::maven_launch_output_dirs(root, maven, module, test).into_iter().filter(|dir| dir.is_dir()),
cancel,
)
&& !cancel.is_cancelled()
{
tracing::info!(module = %module.display(), test, "Reusing Maven launch snapshot");
let mut outputs = previous.unwrap();
outputs.authoritative = true;
return Ok(Ok(outputs));
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
// Retain a non-reusable record even on failure, so removing the final mixed
// source still delegates to Maven to clean its old classes on the next launch.
fs::create_dir_all(record.parent().unwrap())?;
@@ -293,6 +414,7 @@ impl Session {
let snapshot = tempfile::Builder::new().prefix("launch-").tempdir_in(&snapshots)?.keep();
// Retain every new snapshot even if copying or publishing its record fails.
self.unreferenced.push(snapshot.clone());
let scanned: Vec<_> = originals.iter().map(|dir| Contents::scan(dir, cancel)).collect();
for (i, source) in originals.iter().enumerate() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
@@ -303,8 +425,43 @@ impl Session {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut outputs = Outputs { fingerprint: None, snapshot, originals, failure, authoritative };
if outputs.failure.is_none() && pending.before.is_some() && pending.before == after {
// The fingerprint covers build inputs only. Another build (an external `mvn`) can
// rewrite the outputs meanwhile without changing them (#5404): record the snapshot
// only if the outputs held still through the copy and hold every module's classes.
let copied: Option<Vec<Contents>> =
(0..originals.len()).map(|i| Contents::scan(&snapshot.join(i.to_string()), cancel)).collect();
let output_stamps: Option<Vec<OutputStamp>> = copied.as_ref().and_then(|copied| {
originals
.iter()
.zip(&scanned)
.zip(copied)
.map(|((dir, before), copy)| {
let before = before.as_ref()?;
let live = Contents::scan(dir, cancel)?;
(live == *before && before.matches_copy(copy))
.then(|| OutputStamp { live: live.stamp(), snapshot_classes: copy.class_stamp() })
})
.collect()
});
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let consistent = output_stamps.is_some();
let complete = copied.as_ref().is_some_and(|copied| {
compile::launch_required_class_dirs(root, model, &pending.module, test).iter().all(|dir| {
originals.iter().position(|o| o == dir).is_some_and(|i| copied[i].classes().next().is_some())
})
});
if failure.is_none() && !(consistent && complete) {
tracing::warn!(
module = %pending.module.display(),
consistent,
complete,
"Maven outputs changed or lacked classes while copying the launch snapshot; it will not be reused"
);
}
let mut outputs = Outputs { fingerprint: None, snapshot, originals, output_stamps, failure, authoritative };
if outputs.failure.is_none() && pending.before.is_some() && pending.before == after && consistent && complete {
outputs.fingerprint = pending.before;
write_record(&pending.record, &outputs)?;
self.unreferenced.retain(|path| path != &outputs.snapshot);
@@ -698,7 +855,7 @@ mod tests {
assert!(reused.authoritative);
assert_eq!(fs::read_to_string(root.join("calls")).unwrap().lines().count(), 1);
fs::write(root.join("src/main/kotlin/Main.kt"), "updated").unwrap();
fs::write(root.join("target/classes/Main.class"), "JDT stub").unwrap();
let rebuilt = session
.build(
root,
@@ -711,6 +868,7 @@ mod tests {
.unwrap();
assert_ne!(rebuilt.snapshot, first.snapshot);
assert!(rebuilt.authoritative);
assert_eq!(fs::read_to_string(rebuilt.snapshot.join("0/Main.class")).unwrap(), "first");
let calls = fs::read_to_string(root.join("calls")).unwrap();
assert_eq!(calls.lines().count(), 2);
assert!(calls.lines().last().unwrap().contains("clean"));
@@ -732,8 +890,6 @@ mod tests {
let second = build().unwrap();
assert_eq!(snapshot, second.snapshot);
assert_eq!(fs::read_to_string(root.join("calls")).unwrap().lines().count(), 1);
fs::write(root.join("target/classes/Main.class"), "JDT stub").unwrap();
assert_eq!(snapshot, build().unwrap().snapshot);
assert_eq!(fs::read_to_string(snapshot.join("0/Main.class")).unwrap(), "first");
fs::write(root.join("src/main/kotlin/Main.kt"), "updated").unwrap();
let updated = build().unwrap();
@@ -869,6 +1025,7 @@ mod tests {
fingerprint: None,
snapshot: retained.clone(),
originals: Vec::new(),
output_stamps: None,
failure: None,
authoritative: false,
};
@@ -929,6 +1086,132 @@ mod tests {
drop(session);
assert!(!outputs.snapshot.exists());
}
/// An external `mvn` removes a dependency module's classes (`clean`) while this launch
/// builds and copies the outputs, and compiles them again only after the copy (#5404).
/// The sources never change, so only the copied outputs can tell the snapshot is broken.
fn assert_outputs_cleaned_by_an_external_build_are_not_reused(clean: &str) {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = reactor_fixture(root);
let script = root.join("mvnw");
let mut text = fs::read_to_string(&script).unwrap();
text.push_str("echo resource > lib/target/classes/app.yml\n");
text.push_str(&format!("if [ -f external-build ]; then {clean}; fi\n"));
fs::write(&script, text).unwrap();
let cancel = CancellationToken::new();
let mut session = Session::new(root.join("cache"));
let a = root.join("a");
fs::write(root.join("external-build"), "").unwrap();
let first = session.build(root, &model, &a, BuildOptions::default(), None, &cancel).unwrap();
assert!(!first.snapshot.join("1/Main.class").exists());
// The external build finished: the classes are complete again, sources unchanged.
fs::remove_file(root.join("external-build")).unwrap();
fs::create_dir_all(root.join("lib/target/classes")).unwrap();
fs::write(root.join("lib/target/classes/Main.class"), "lib").unwrap();
let second = session.build(root, &model, &a, BuildOptions::default(), None, &cancel).unwrap();
assert_ne!(second.snapshot, first.snapshot, "the incomplete snapshot must not be reused");
assert_eq!(fs::read_to_string(second.snapshot.join("1/Main.class")).unwrap(), "lib");
assert_eq!(calls(root).len(), 2);
let third = session.build(root, &model, &a, BuildOptions::default(), None, &cancel).unwrap();
assert_eq!(third.snapshot, second.snapshot, "a complete snapshot is reused");
assert_eq!(calls(root).len(), 2);
}
#[test]
fn a_snapshot_of_classes_cleaned_by_an_external_build_is_not_reused() {
assert_outputs_cleaned_by_an_external_build_are_not_reused("rm lib/target/classes/Main.class");
}
#[test]
fn a_snapshot_missing_an_output_directory_removed_by_an_external_build_is_not_reused() {
assert_outputs_cleaned_by_an_external_build_are_not_reused("rm -r lib/target/classes");
}
#[test]
fn a_partially_recompiled_dependency_snapshot_is_not_reused() {
assert_outputs_cleaned_by_an_external_build_are_not_reused(
"echo other > lib/target/classes/Other.class; rm lib/target/classes/Main.class",
);
}
#[test]
fn a_new_output_directory_invalidates_a_test_launch_snapshot() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root);
let cancel = CancellationToken::new();
let mut session = Session::new(root.join("cache"));
let mut build =
|| session.build(root, &model, root, BuildOptions { test: true, ..Default::default() }, None, &cancel);
let first = build().unwrap();
assert_eq!(first.originals, [root.join("target/classes")]);
fs::create_dir_all(root.join("target/test-classes")).unwrap();
fs::write(root.join("target/test-classes/GeneratedTest.class"), "test").unwrap();
let second = build().unwrap();
assert_ne!(first.snapshot, second.snapshot);
assert!(second.snapshot.join("0/GeneratedTest.class").is_file());
assert_eq!(second.snapshot, build().unwrap().snapshot);
assert_eq!(calls(root).len(), 2);
}
#[test]
fn a_record_without_output_stamps_is_rebuilt_once() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root);
let cancel = CancellationToken::new();
let mut session = Session::new(root.join("cache"));
let first = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
// A count-only record may still hold a partial copy.
let record = root.join("cache/java-launch/records/main.json");
let mut json: serde_json::Value = serde_json::from_slice(&fs::read(&record).unwrap()).unwrap();
json.as_object_mut().unwrap().remove("output_stamps").unwrap();
json["contents"] = serde_json::json!([{ "files": 1, "bytes": 5, "classes": 1 }]);
fs::write(&record, serde_json::to_vec(&json).unwrap()).unwrap();
let rebuilt = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_ne!(rebuilt.snapshot, first.snapshot);
let reused = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_eq!(reused.snapshot, rebuilt.snapshot);
// A file the launched app wrote under its classpath root keeps the snapshot.
fs::write(reused.snapshot.join("0/app.log"), "log").unwrap();
let kept = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_eq!(kept.snapshot, reused.snapshot);
// A snapshot that lost a class since it was recorded is rebuilt.
fs::remove_file(reused.snapshot.join("0/Main.class")).unwrap();
let again = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_ne!(again.snapshot, reused.snapshot);
assert_eq!(calls(root).len(), 3);
}
#[test]
fn contents_tell_a_rewritten_output_from_its_copy() {
let dir = tempfile::tempdir().unwrap();
let classes = dir.path().join("classes");
let cancel = CancellationToken::new();
let scan = |path: &Path| Contents::scan(path, &cancel);
fs::create_dir_all(classes.join("pkg")).unwrap();
fs::write(classes.join("pkg/A.class"), "a").unwrap();
fs::write(classes.join("app.yml"), "yml").unwrap();
let class = fs::File::options().write(true).open(classes.join("pkg/A.class")).unwrap();
let resource = fs::File::options().write(true).open(classes.join("app.yml")).unwrap();
let before = SystemTime::now();
resource.set_modified(before + std::time::Duration::from_secs(10)).unwrap();
let contents = scan(&classes).unwrap();
ide_vfs::copy(&classes, &dir.path().join("copy")).unwrap();
assert!(contents.matches_copy(&scan(&dir.path().join("copy")).unwrap()));
// A rewrite can preserve both the class file's size and the tree's newest mtime.
class.set_modified(before + std::time::Duration::from_secs(1)).unwrap();
let rewritten = scan(&classes).unwrap();
assert!(contents.matches_copy(&rewritten));
assert_ne!(rewritten.stamp(), contents.stamp());
fs::rename(classes.join("pkg/A.class"), classes.join("pkg/B.class")).unwrap();
let renamed = scan(&classes).unwrap();
assert!(!rewritten.matches_copy(&renamed));
assert_ne!(renamed.stamp(), rewritten.stamp());
assert!(scan(&dir.path().join("missing")).is_none());
}
#[test]
fn deleting_the_last_mixed_source_keeps_maven_delegation_after_failure() {
let dir = tempfile::tempdir().unwrap();
+293 -6
View File
@@ -3,7 +3,9 @@ use crate::Host;
use crate::plugins::{ProviderKind, editor_providers_for as editor_providers};
use ide_command::command;
use ide_core::error::ErrorKind;
use ide_core::{DocId, IdeError, IdeResult, Location, Pos, Range, RequestId, ServerId, TextEdit, WorkspaceEdit};
use ide_core::{
CancellationToken, DocId, IdeError, IdeResult, Location, Pos, Range, RequestId, ServerId, TextEdit, WorkspaceEdit,
};
use ide_lsp::types::*;
use ide_plugin::ProviderDocument;
use std::path::Path;
@@ -150,7 +152,7 @@ fn merge_language_highlights(
server
}
/// Items from plugins carry no server: commands don't apply, and a code
/// Items from plugins (and the host's own Ruff Optimize Imports) carry no server: commands don't apply, and a code
/// action is resolved by the plugin named in its `data` ([`PluginActionRef`]).
const PLUGIN_SERVER: ServerId = ServerId(0);
@@ -909,6 +911,7 @@ pub async fn lsp_code_actions(
let target = position_document(host, window, doc, range.start).await?;
let range = project.lsp.injected_request_range(target, range);
let result = project.lsp.code_actions(target, range, only.clone()).await;
let result = with_ruff_organize_imports(host, window, doc, &only, result, CancellationToken::new()).await;
let plugin_actions = match plugin_providers(host, window, doc, ProviderKind::CodeActions) {
Some((plugins, d)) => plugin_call(move || plugins.provide_code_actions(&d, range)).await.unwrap_or_default(),
None => Vec::new(),
@@ -931,6 +934,76 @@ pub async fn lsp_code_actions(
prepare_actions(project, doc, version, actions).await
}
const ORGANIZE_IMPORTS: &str = "source.organizeImports";
pub(crate) const RUFF_ORGANIZE_IMPORTS: &str = "source.organizeImports.ruff";
/// `result` and, when organize imports is asked for and no server offers it, Ruff's Optimize
/// Imports for a Python file: for the editor and for the MCP tools alike.
async fn with_ruff_organize_imports(
host: &Host,
window: &str,
doc: DocId,
only: &[String],
result: IdeResult<Vec<CodeAction>>,
cancel: CancellationToken,
) -> IdeResult<Vec<CodeAction>> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if !only.iter().any(|k| k == ORGANIZE_IMPORTS) || result.as_ref().is_ok_and(|a| a.iter().any(organizes_imports)) {
return result;
}
// A missing provider permits a fallback. Stale, invalid and cancelled requests must still fail.
if result.as_ref().is_err_and(|e| !matches!(e.kind, ErrorKind::NotFound | ErrorKind::Unavailable)) {
return result;
}
match ruff_organize_imports(host, window, doc, cancel).await? {
Some(action) => {
let mut actions = result.unwrap_or_default();
actions.push(action);
Ok(actions)
}
None => result,
}
}
fn organizes_imports(action: &CodeAction) -> bool {
action.kind.as_deref().is_some_and(|k| k == ORGANIZE_IMPORTS || k.starts_with("source.organizeImports."))
}
/// Optimize Imports with Ruff's CLI for a Python file no language server organizes; a missing Ruff
/// is a disabled action that says so. Like a plugin's, the action carries its edit and is applied as is.
async fn ruff_organize_imports(
host: &Host,
window: &str,
doc: DocId,
cancel: CancellationToken,
) -> IdeResult<Option<CodeAction>> {
let (edit, disabled_reason) = match crate::formatter::python_import_edits(host, window, doc, cancel).await {
Ok(None) => return Ok(None),
Ok(Some((path, edits))) => {
let files = vec![ide_core::FileEdit::Edit { path, edits, version: None }];
(Some(WorkspaceEdit { files, preconditions: Vec::new() }), None)
}
Err(e) if matches!(e.data, Some(ide_core::error::ErrorData::Tool { missing: true, .. })) => {
(None, Some("Install Ruff to optimize imports in Python files".to_owned()))
}
Err(e) => return Err(e),
};
Ok(Some(CodeAction {
title: "Optimize Imports (Ruff)".into(),
diagnostics: Vec::new(),
original_diagnostics: None,
kind: Some(RUFF_ORGANIZE_IMPORTS.into()),
is_preferred: true,
disabled_reason,
edit,
command: None,
data: None,
server: PLUGIN_SERVER,
}))
}
/// Where a plugin's code action may change or open files: the project root and its content
/// roots (a group's members, extra Project Structure folders), never git's own files.
fn plugin_edit_roots(project: &crate::Project) -> Vec<std::path::PathBuf> {
@@ -1063,11 +1136,19 @@ pub async fn lsp_code_action_query(
let version = blocking(move || documents.version(doc)).await?;
let (target, cancel) = begin_position_request(host, window, request, doc, range.start).await?;
let range = project.lsp.injected_request_range(target, range);
let result = project.lsp.code_action_query(target, range, only, cancel).await;
let result = async {
let result = project.lsp.code_action_query(target, range, only.clone(), cancel.clone()).await;
let (actions, advertised_kinds) = match result {
Ok(query) => (Ok(query.actions), query.advertised_kinds),
Err(e) => (Err(e), None),
};
let actions = with_ruff_organize_imports(host, window, doc, &only, actions, cancel).await?;
let actions = prepare_actions(project, doc, version, actions).await?;
Ok(CodeActionQuery { actions, advertised_kinds })
}
.await;
host.end_request(request);
let mut result = result?;
result.actions = prepare_actions(project, doc, version, result.actions).await?;
Ok(result)
result
}
/// Resolves a code action's edit without applying it (intention preview).
@@ -1176,6 +1257,22 @@ pub async fn lsp_prepare_rename(host: &Host, window: &str, doc: DocId, pos: Pos)
host.project(window)?.lsp.prepare_rename(doc, pos).await
}
/// The Throwable class the caret at `pos` names, for the exception breakpoint intention.
#[command(trust = trusted)]
pub async fn lsp_exception_class_at(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
pos: Pos,
) -> IdeResult<Option<ExceptionClassRef>> {
let project = host.project(window)?;
let cancel = host.begin_request(request);
let result = project.lsp.exception_class_at(doc, pos, cancel).await;
host.end_request(request);
result
}
/// The class at `pos` and the members Pull Members Up / Push Members Down can move.
#[command(trust = trusted)]
pub async fn lsp_hierarchy_members(
@@ -1590,6 +1687,62 @@ pub async fn lsp_format(
crate::formatter::format(host, window, doc, range, options).await
}
#[command(trust = trusted)]
pub async fn lsp_format_text(
host: &Host,
window: &str,
path: std::path::PathBuf,
text: String,
options: FormatOptions,
) -> IdeResult<Vec<TextEdit>> {
crate::formatter::format_text(host, window, path, text, options).await
}
#[command(trust = trusted)]
pub async fn lsp_source_action_text(
host: &Host,
window: &str,
path: std::path::PathBuf,
text: String,
kind: String,
request: RequestId,
) -> IdeResult<Vec<TextEdit>> {
let project = host.project(window)?;
if !path.is_absolute() || path.file_name().is_none() {
return Err(IdeError::invalid("a text snapshot requires a file path"));
}
if text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD {
return Ok(Vec::new());
}
let language = project.documents.language_of(&path, text.lines().next()).language;
let cancel = host.begin_project_read_request(window, request);
let result = project.lsp.source_action_text(&path, &language, &text, &kind, &cancel).await;
host.end_request(request);
result
}
#[command(trust = trusted)]
pub async fn lsp_snapshot_diagnostics(
host: &Host,
window: &str,
path: std::path::PathBuf,
text: String,
request: RequestId,
) -> IdeResult<Vec<ide_core::Diagnostic>> {
let project = host.project(window)?;
if !path.is_absolute() || path.file_name().is_none() {
return Err(IdeError::invalid("a text snapshot requires a file path"));
}
if text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD {
return Ok(Vec::new());
}
let language = project.documents.language_of(&path, text.lines().next()).language;
let cancel = host.begin_project_read_request(window, request);
let result = project.lsp.snapshot_diagnostics(&path, &language, &text, &cancel).await;
host.end_request(request);
result
}
#[command(trust = trusted)]
pub async fn lsp_inlay_hints(host: &Host, window: &str, doc: DocId, range: Range) -> IdeResult<Vec<InlayHint>> {
let lsp = host.project(window)?.lsp.clone();
@@ -1681,6 +1834,23 @@ pub async fn lsp_document_links(host: &Host, window: &str, doc: DocId) -> IdeRes
Ok(out)
}
/// Colors in a document from its language servers (Tailwind classes, CSS values…).
#[command(trust = trusted)]
pub async fn lsp_document_colors(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<DocumentColor>> {
host.project(window)?.lsp.document_colors(doc).await
}
/// How the server that reported `color` writes it with new components.
#[command(trust = trusted)]
pub async fn lsp_color_presentations(
host: &Host,
window: &str,
doc: DocId,
color: DocumentColor,
) -> IdeResult<Vec<ColorPresentation>> {
host.project(window)?.lsp.color_presentations(doc, color).await
}
#[command(trust = trusted)]
pub async fn lsp_call_hierarchy(
host: &Host,
@@ -2054,6 +2224,117 @@ pub fn plugin_formatters() -> IdeResult<Vec<crate::plugins::language_features::F
#[cfg(test)]
mod tests {
#[cfg(unix)]
#[tokio::test]
async fn python_optimize_imports_without_a_server_runs_ruff_on_the_unsaved_text() {
use super::*;
use std::os::unix::fs::PermissionsExt;
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir(&root).unwrap();
let file = root.join("main.py");
std::fs::write(&file, "import os\n").unwrap();
std::fs::write(root.join("notes.txt"), "import sys\n").unwrap();
// A stand-in Ruff that checks its arguments and removes the unused import.
let ruff = base.join("ruff");
std::fs::write(
&ruff,
"#!/bin/sh\n[ \"$1 $2 $3 $4 $5\" = \"check --extend-select I --fixable I,F401\" ] || exit 2\nsed '/^import sys$/d'\n",
)
.unwrap();
std::fs::set_permissions(&ruff, std::fs::Permissions::from_mode(0o755)).unwrap();
let host = crate::Host::new(crate::HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: std::sync::Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: std::sync::Arc::default(),
sink_for: Box::new(|_| std::sync::Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
project
.settings
.set(
ide_workspace::settings::SettingsScope::Project,
"languages.ruff.path",
ruff.to_string_lossy().into_owned().into(),
)
.unwrap();
let doc = project.documents.open(&file).unwrap().id;
project
.documents
.apply_edits(
doc,
&[TextEdit { range: Range::new(Pos::default(), Pos::default()), new_text: "import sys\n".into() }],
)
.unwrap();
let cancel = CancellationToken::new();
let only = [ORGANIZE_IMPORTS.to_owned()];
// A server that offers organize imports keeps the request to itself.
let server = CodeAction { kind: Some(ORGANIZE_IMPORTS.into()), ..action_stub() };
let kept =
with_ruff_organize_imports(&host, "main", doc, &only, Ok(vec![server]), cancel.clone()).await.unwrap();
assert_eq!(kept.len(), 1);
assert_eq!(kept[0].server, ServerId(7));
// No server: the Ruff action, for the editor and the MCP tools alike.
let no_server = Err(ide_core::IdeError::unavailable("no server"));
let mut actions =
with_ruff_organize_imports(&host, "main", doc, &only, no_server, cancel.clone()).await.unwrap();
assert_eq!(actions.len(), 1);
let action = actions.remove(0);
assert_eq!(action.kind.as_deref(), Some("source.organizeImports.ruff"));
assert!(organizes_imports(&action) && action.disabled_reason.is_none());
let Some(ide_core::FileEdit::Edit { edits, .. }) = action.edit.unwrap().files.into_iter().next() else {
panic!("no edit")
};
// "import sys\nimport os\n" loses "sys\nimport " and keeps "import os\n".
assert_eq!(edits, [TextEdit { range: Range::new(Pos::new(0, 7), Pos::new(1, 7)), new_text: String::new() }]);
assert_eq!(std::fs::read_to_string(file).unwrap(), "import os\n");
let imports_only = root.join("imports_only.py");
std::fs::write(&imports_only, "import sys\n").unwrap();
let imports_only = project.documents.open(&imports_only).unwrap().id;
let (_, edits) =
crate::formatter::python_import_edits(&host, "main", imports_only, cancel.clone()).await.unwrap().unwrap();
assert_eq!(edits, [TextEdit { range: Range::new(Pos::default(), Pos::new(1, 0)), new_text: String::new() }]);
let text = project.documents.open(&root.join("notes.txt")).unwrap().id;
assert!(ruff_organize_imports(&host, "main", text, cancel.clone()).await.unwrap().is_none());
assert!(
with_ruff_organize_imports(&host, "main", doc, &[], Ok(Vec::new()), cancel.clone())
.await
.unwrap()
.is_empty()
);
for kind in [ErrorKind::Cancelled, ErrorKind::OutOfSync, ErrorKind::InvalidInput] {
let error = IdeError::new(kind, "must propagate");
let result = with_ruff_organize_imports(&host, "main", doc, &only, Err(error), cancel.clone()).await;
assert_eq!(result.unwrap_err().kind, kind);
}
cancel.cancel();
let result = with_ruff_organize_imports(&host, "main", doc, &only, Ok(Vec::new()), cancel).await;
assert_eq!(result.unwrap_err().kind, ErrorKind::Cancelled);
}
#[cfg(unix)]
fn action_stub() -> CodeAction {
CodeAction {
title: String::new(),
diagnostics: Vec::new(),
original_diagnostics: None,
kind: None,
is_preferred: false,
disabled_reason: None,
edit: None,
command: None,
data: None,
server: ServerId(7),
}
}
#[test]
fn language_features_merge_without_overwriting_lsp_ranges_or_masking_errors() {
use super::*;
@@ -2783,14 +3064,20 @@ ide_command::domain!(
lsp_code_action_query,
lsp_code_actions,
lsp_code_lens,
lsp_color_presentations,
lsp_completion,
lsp_document_colors,
lsp_document_highlights,
lsp_document_links,
lsp_exception_class_at,
lsp_execute_code_action,
lsp_execute_command,
lsp_extract_interface,
lsp_extract_interface_info,
lsp_format,
lsp_format_text,
lsp_snapshot_diagnostics,
lsp_source_action_text,
lsp_goto,
lsp_goto_implementation,
lsp_hierarchy_members,
+1
View File
@@ -27,6 +27,7 @@ pub mod nav;
pub mod notebook;
pub mod project;
mod python;
pub mod python_stubs;
pub mod refactor;
pub mod routes;
pub mod run;
+49
View File
@@ -1,4 +1,7 @@
use super::doc::blocking;
use super::python_stubs::{
PythonStubLinks, counterpart_candidates, match_declarations, module_name, site_packages, stub_path,
};
use crate::Host;
use crate::Project;
use ide_command::command;
@@ -383,6 +386,51 @@ pub async fn web_unresolved_references(host: &Host, window: &str, doc: DocId) ->
.await
}
/// The stub (`.pyi`) of a Python document, or the implementation of a stub, and the
/// functions and classes declared in both: PyCharm's stub gutter markers.
#[command(trust = always)]
pub async fn nav_python_stubs(host: &Host, window: &str, doc: DocId) -> IdeResult<PythonStubLinks> {
let project = host.project(window)?;
let syntax = host.syntax();
blocking(move || {
let snap = project.documents.snapshot(doc)?;
if snap.large {
return Ok(PythonStubLinks::default());
}
let path = PathBuf::from(snap.path.clone());
// Modules are found in the project's Python roots and its virtualenv's site-packages.
let mut search = super::python::paths(&project);
let settings = project.settings.effective();
if let Some(venv) =
ide_sdk::apply::python_interpreter(&project.root, &settings).and_then(|p| ide_sdk::venv_of(&p))
{
search.extend(site_packages(&venv));
}
let module = module_name(&path, &search);
let candidates = counterpart_candidates(&path, &stub_path(&project.root), module.as_deref(), &search);
let watched = candidates.iter().cloned().map(IpcPath::from).collect();
let Some(counterpart) = candidates.into_iter().find(|p| project.documents.text_of(p).is_some() || p.is_file())
else {
return Ok(PythonStubLinks { candidates: watched, ..Default::default() });
};
// A counterpart too large to parse still opens; it just gets no markers.
let other = match project.documents.text_of(&counterpart) {
Some(text) => Some(text).filter(|t| t.len() as u64 <= ide_vfs::LARGE_FILE_THRESHOLD),
None => std::fs::metadata(&counterpart)
.is_ok_and(|m| m.len() <= ide_vfs::LARGE_FILE_THRESHOLD)
.then(|| project.text_of(&counterpart))
.transpose()?,
};
let links = other
.map(|other| {
match_declarations(&syntax.outline(&snap.language, &snap.text), &syntax.outline(&snap.language, &other))
})
.unwrap_or_default();
Ok(PythonStubLinks { counterpart: Some(IpcPath::from(counterpart)), links, candidates: watched })
})
.await
}
ide_command::domain!(
nav:
find_dirs,
@@ -396,6 +444,7 @@ ide_command::domain!(
mark_recent,
nav_index_definitions,
nav_inheritance,
nav_python_stubs,
nav_resolve_module,
path_completions,
recent_files,
+19 -2
View File
@@ -87,6 +87,15 @@ pub fn settings_get_global(host: &Host) -> Settings {
host.with_proxy_password(host.global_settings.effective())
}
/// Read the same host-wide value for the close dialog and the idle timer: another project's
/// daemon may have edited the file since this host loaded its settings.
#[command(trust = always)]
pub async fn remote_idle_timeout_minutes(host: &Arc<Host>) -> IdeResult<u16> {
let h = host.clone();
host.blocking(move || Ok(h.global_settings.layer(SettingsScope::Global).remote_development.idle_timeout_minutes))
.await
}
/// The removed built-in theme id a settings file of this window still names, if any:
/// `settings_get` reports the built-in that stands in for it, so the notice about
/// a theme that moved to a plugin can address the installs it concerns.
@@ -140,7 +149,10 @@ pub struct WorkspaceMember {
}
/// The workspace projects outside the window's project folder, for Mark Directory as there.
#[command(trust = always)]
/// Each member's `for_project().layer(Project)` re-parses both settings layers and validates the
/// merged tree against `Settings`; that stack-hungry work must not run on the IPC (main) thread,
/// whose 1 MiB stack overflows on project open (STATUS_STACK_OVERFLOW).
#[command(trust = always, desktop_body = spawn)]
pub fn project_workspace_members(host: &Host, window: &str) -> IdeResult<Vec<WorkspaceMember>> {
let project = host.project(window)?;
Ok(project
@@ -156,7 +168,8 @@ pub fn project_workspace_members(host: &Host, window: &str) -> IdeResult<Vec<Wor
/// Sets a `projectStructure.*` key in the settings of `root`, a project attached to the window's
/// project (Mark Directory as there). Every open window holding that project follows.
#[command(trust = always)]
/// Like `project_workspace_members`, its `for_project` settings re-parse runs off the IPC thread.
#[command(trust = always, desktop_body = spawn)]
pub fn project_workspace_member_set(
host: &Arc<Host>,
window: &str,
@@ -391,6 +404,9 @@ pub fn set_settings(
if key == "languages" || key == "languages.java" || key.starts_with("languages.java.addedJdks") {
host.apply_added_jdks();
}
if key == "vcs" || key == "vcs.git" || key == "vcs.git.executable" {
host.apply_git_executable();
}
if is_proxy {
host.apply_proxy();
}
@@ -474,6 +490,7 @@ ide_command::domain!(
project_trust_status,
project_workspace_member_set,
project_workspace_members,
remote_idle_timeout_minutes,
settings_get,
settings_get_global,
settings_removed_theme,
+34 -1
View File
@@ -3,7 +3,7 @@ use ide_core::IdeResult;
use ide_dap::LaunchConfig;
use ide_workspace::roots::RootKind;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
pub(super) fn paths(project: &Project) -> Vec<PathBuf> {
let mut paths = vec![project.root.clone()];
@@ -19,6 +19,39 @@ pub(super) fn paths(project: &Project) -> Vec<PathBuf> {
paths
}
/// `paths` plus the folders added to the paths of the interpreter a launch uses (All
/// Interpreters › Show Paths): `command` when it names a Python executable, else the
/// interpreter of the project or workspace member at `near`. Run, Debug and the console
/// resolve it the same way, so the same file imports the same modules in each.
pub(super) fn with_user_paths(
mut paths: Vec<PathBuf>,
config_dir: &Path,
project: &Project,
command: Option<&str>,
near: Option<&Path>,
) -> Vec<PathBuf> {
let named = command
.filter(|c| ide_sdk::apply::is_python_command(c))
.map(PathBuf::from)
.filter(|p| p.is_absolute() && p.is_file())
.map(|p| ide_core::project_roots::resolve(&project.root, &p));
let python = named.or_else(|| super::sdk::effective_python(config_dir, project, near));
if let Some(python) = python {
for path in ide_sdk::apply::interpreter_user_paths(&python, &project.settings.effective()) {
if !paths.contains(&path) {
paths.push(path);
}
}
}
paths
}
/// The interpreter a debugpy launch names (`"python": "<executable>"`), if it names one.
pub(super) fn debug_python(config: &LaunchConfig) -> Option<String> {
let extra: serde_json::Value = serde_json::from_str(config.extra_json.as_deref()?).ok()?;
extra.get("python")?.as_str().map(str::to_owned)
}
pub(super) fn prepare_debug(config: &mut LaunchConfig, paths: &[PathBuf]) -> IdeResult<()> {
// Adapter-specific env takes precedence over the common launch fields in DAP.
let mut extra: Option<serde_json::Value> = config.extra_json.as_deref().and_then(|s| serde_json::from_str(s).ok());
+230
View File
@@ -0,0 +1,230 @@
//! `.py` ↔ `.pyi` pairing for the stub gutter markers and Navigate › Stub / Implementation:
//! which file holds a module's stub (or implementation), and which declarations match.
use ide_core::{OutlineItem, Range, SymbolKind};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
/// A declaration of the document and its counterpart in the other file.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct StubLink {
/// Qualified name, `Class.method`.
pub name: String,
/// The declaration's identifier in the document.
pub range: Range,
/// The declaration's whole extent in the document.
pub extent: Range,
/// The counterpart's identifier in `PythonStubLinks::counterpart`.
pub target: Range,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PythonStubLinks {
/// The stub of a `.py` document, the implementation of a `.pyi` one.
pub counterpart: Option<ide_core::IpcPath>,
pub links: Vec<StubLink>,
/// Every place the counterpart was looked for: a change to one of them may change the answer.
pub candidates: Vec<ide_core::IpcPath>,
}
/// The stub folder basedpyright reads: `stubPath` from `pyrightconfig.json` or the
/// `[tool.basedpyright]` / `[tool.pyright]` table of `pyproject.toml`, else `typings`.
pub(crate) fn stub_path(root: &Path) -> PathBuf {
let json = || {
let text = std::fs::read_to_string(root.join("pyrightconfig.json")).ok()?;
serde_json::from_str::<serde_json::Value>(&text).ok()?.get("stubPath")?.as_str().map(str::to_owned)
};
let toml = || {
let text = std::fs::read_to_string(root.join("pyproject.toml")).ok()?;
let tool = text.parse::<toml::Table>().ok()?.remove("tool")?;
["basedpyright", "pyright"].iter().find_map(|t| tool.get(t)?.get("stubPath")?.as_str().map(str::to_owned))
};
root.join(json().or_else(toml).unwrap_or_else(|| "typings".to_owned()))
}
/// The `site-packages` folders of a virtualenv (`lib/python3.x/site-packages`, `Lib/site-packages`).
pub(crate) fn site_packages(venv: &Path) -> Vec<PathBuf> {
let mut out = vec![venv.join("Lib").join("site-packages")];
if let Ok(entries) = std::fs::read_dir(venv.join("lib")) {
out.extend(entries.flatten().map(|e| e.path().join("site-packages")));
}
out.retain(|p| p.is_dir());
out
}
/// The dotted module of a Python file, from the innermost `search` folder holding it
/// (`src/a/b.py` → `a.b`, `site-packages/a/__init__.py` → `a`).
pub(crate) fn module_name(path: &Path, search: &[PathBuf]) -> Option<String> {
let base = search.iter().filter(|b| path.starts_with(b)).max_by_key(|b| b.components().count())?;
let rel = path.strip_prefix(base).ok()?.with_extension("");
let rel = if rel.file_name()? == "__init__" { rel.parent()?.to_path_buf() } else { rel };
let parts: Vec<&str> = rel.iter().map(|c| c.to_str()).collect::<Option<_>>()?;
let valid = |s: &str| {
s.chars().next().is_some_and(|c| !c.is_ascii_digit()) && s.chars().all(|c| c == '_' || c.is_alphanumeric())
};
(!parts.is_empty() && parts.iter().all(|p| valid(p))).then(|| parts.join("."))
}
/// Where the counterpart of `path` may be, nearest first: beside it, in a PEP 561
/// `<package>-stubs` folder beside its package (or `<module>-stubs/__init__.pyi` for a
/// single module), and in the `stubs` folder, which mirrors module paths (`module` names a
/// `.py` file's module, `search` lists the folders modules are found in).
pub(crate) fn counterpart_candidates(
path: &Path,
stubs: &Path,
module: Option<&str>,
search: &[PathBuf],
) -> Vec<PathBuf> {
let stub = match path.extension().and_then(|e| e.to_str()) {
Some("pyi") => true,
Some("py") => false,
_ => return Vec::new(),
};
let other = if stub { "py" } else { "pyi" };
let mut out = vec![path.with_extension(other)];
// `a/pkg-stubs/m.pyi` ↔ `a/pkg/m.py`.
for dir in path.ancestors().skip(1) {
let (Some(parent), Some(name)) = (dir.parent(), dir.file_name().and_then(|n| n.to_str())) else { break };
let renamed = match (stub, name.strip_suffix("-stubs")) {
(true, Some(package)) => package.to_owned(),
(false, None) => format!("{name}-stubs"),
_ => continue,
};
if let Ok(rest) = path.strip_prefix(dir) {
out.push(parent.join(renamed).join(rest).with_extension(other));
}
}
// `a/six.py` ↔ `a/six-stubs/__init__.pyi`.
if let (Some(dir), Some(name)) = (path.parent(), path.file_stem().and_then(|n| n.to_str())) {
if !stub {
out.push(dir.join(format!("{name}-stubs")).join("__init__.pyi"));
} else if let (true, Some(package), Some(parent)) = (
name == "__init__",
dir.file_name().and_then(|n| n.to_str()).and_then(|n| n.strip_suffix("-stubs")),
dir.parent(),
) {
out.push(parent.join(package).with_extension("py"));
}
}
// `typings/a/b.pyi` ↔ the module `a.b`: `a/b.py` or `a/b/__init__.py` in a search folder.
let modules = |rel: &Path, base: &Path, ext: &str| {
[base.join(rel).with_extension(ext), base.join(rel).join("__init__").with_extension(ext)]
};
let module = if stub { module_name(path, &[stubs.to_path_buf()]) } else { module.map(str::to_owned) };
if let Some(module) = module {
let rel: PathBuf = module.split('.').collect();
if stub {
out.extend(search.iter().flat_map(|base| modules(&rel, base, "py")));
} else {
out.extend(modules(&rel, stubs, "pyi"));
}
}
let mut seen = std::collections::HashSet::new();
out.retain(|p| p != path && seen.insert(p.clone()));
out
}
/// The declarations of `doc` (functions and classes, recursing into classes) whose
/// qualified name `other` declares too; an overloaded name targets its first declaration.
pub(crate) fn match_declarations(doc: &[OutlineItem], other: &[OutlineItem]) -> Vec<StubLink> {
let mut targets: HashMap<String, Range> = HashMap::new();
walk(other, "", &mut |name, item| {
targets.entry(name).or_insert(item.selection_range);
});
let mut links = Vec::new();
walk(doc, "", &mut |name, item| {
if let Some(target) = targets.get(&name) {
links.push(StubLink { name, range: item.selection_range, extent: item.range, target: *target });
}
});
links
}
fn walk(items: &[OutlineItem], prefix: &str, f: &mut impl FnMut(String, &OutlineItem)) {
for item in items {
let class = item.kind == SymbolKind::Class;
if !class && !matches!(item.kind, SymbolKind::Function | SymbolKind::Method | SymbolKind::Constructor) {
continue;
}
let name = if prefix.is_empty() { item.name.clone() } else { format!("{prefix}.{}", item.name) };
f(name.clone(), item);
if class {
walk(&item.children, &name, f);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::LanguageId;
use ide_language::Syntax;
fn outline(text: &str) -> Vec<OutlineItem> {
Syntax::new().outline(&LanguageId::new("python"), text)
}
#[test]
fn candidates_cover_siblings_stub_packages_and_typings() {
let typings = Path::new("/p/typings");
let site = PathBuf::from("/p/.venv/lib/python3.12/site-packages");
let search = [PathBuf::from("/p"), PathBuf::from("/p/src"), site.clone()];
let module = |p: &str| module_name(Path::new(p), &search);
assert_eq!(module("/p/src/pkg/m.py").as_deref(), Some("pkg.m"));
assert_eq!(module("/p/.venv/lib/python3.12/site-packages/requests/__init__.py").as_deref(), Some("requests"));
assert_eq!(module("/elsewhere/x.py"), None);
let py = counterpart_candidates(Path::new("/p/src/pkg/m.py"), typings, Some("pkg.m"), &search);
assert_eq!(py[0], Path::new("/p/src/pkg/m.pyi"));
assert!(py.contains(&PathBuf::from("/p/src/pkg-stubs/m.pyi")));
assert!(py.contains(&PathBuf::from("/p/src/pkg/m-stubs/__init__.pyi")));
assert!(py.contains(&PathBuf::from("/p/typings/pkg/m.pyi")));
assert!(py.contains(&PathBuf::from("/p/typings/pkg/m/__init__.pyi")));
let stub = counterpart_candidates(Path::new("/lib/pkg-stubs/sub/m.pyi"), typings, None, &search);
assert_eq!(stub[0], Path::new("/lib/pkg-stubs/sub/m.py"));
assert!(stub.contains(&PathBuf::from("/lib/pkg/sub/m.py")));
assert!(!stub.iter().any(|p| p.to_string_lossy().contains("-stubs-stubs")));
// PEP 561 stubs of a single module: `six-stubs/__init__.pyi` ↔ `six.py`.
let six = counterpart_candidates(&site.join("six-stubs/__init__.pyi"), typings, None, &search);
assert!(six.contains(&site.join("six.py")));
// `typings/` stubs of an installed package resolve into site-packages.
let typed = counterpart_candidates(Path::new("/p/typings/requests/api.pyi"), typings, None, &search);
assert!(typed.contains(&site.join("requests/api.py")));
let installed = site.join("requests/api.py");
let back = counterpart_candidates(&installed, typings, module_name(&installed, &search).as_deref(), &search);
assert!(back.contains(&PathBuf::from("/p/typings/requests/api.pyi")));
let package = counterpart_candidates(Path::new("/p/typings/pkg/__init__.pyi"), typings, None, &search);
assert!(package.contains(&PathBuf::from("/p/src/pkg.py")));
assert!(package.contains(&PathBuf::from("/p/src/pkg/__init__.py")));
assert!(counterpart_candidates(Path::new("/p/a.txt"), typings, None, &search).is_empty());
}
#[test]
fn stub_path_follows_the_pyright_settings() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(stub_path(dir.path()), dir.path().join("typings"));
std::fs::write(dir.path().join("pyproject.toml"), "[tool.basedpyright]\nstubPath = \"stubs\"\n").unwrap();
assert_eq!(stub_path(dir.path()), dir.path().join("stubs"));
std::fs::write(dir.path().join("pyrightconfig.json"), r#"{"stubPath": "types"}"#).unwrap();
assert_eq!(stub_path(dir.path()), dir.path().join("types"));
}
#[test]
fn declarations_match_by_qualified_name() {
let py = "def f(a):\n def inner(): pass\n return a\n\nclass C:\n def __init__(self): pass\n def m(self): pass\n def extra(self): pass\n\ndef g(): pass\nX = 1\n";
let pyi = "from typing import overload\n@overload\ndef f(a: int) -> int: ...\n@overload\ndef f(a: str) -> str: ...\nclass C:\n def __init__(self) -> None: ...\n def m(self) -> None: ...\ndef inner() -> None: ...\nX: int\n";
let links = match_declarations(&outline(py), &outline(pyi));
let names: Vec<(&str, u32, u32)> =
links.iter().map(|l| (l.name.as_str(), l.range.start.line, l.target.start.line)).collect();
assert_eq!(names, [("f", 0, 2), ("C", 4, 5), ("C.__init__", 5, 6), ("C.m", 6, 7)]);
}
}
+17 -13
View File
@@ -67,20 +67,24 @@ fn scan_roots(root: &Path, content_roots: Vec<PathBuf>) -> Vec<PathBuf> {
roots
}
/// Every mapping source of the project, for the request-path index.
pub fn spring_route_sources(host: &Host, window: &str) -> IdeResult<Vec<RouteSource>> {
/// Every mapping source of the project, for the request-path index. Walks the whole tree,
/// so it runs on the blocking pool.
pub async fn spring_route_sources(host: &Host, window: &str) -> IdeResult<Vec<RouteSource>> {
let project = host.project(window)?;
let mut out = Vec::new();
for root in scan_roots(&project.root, project.content_roots()) {
out.extend(sources_in(&root, &project.search_excludes_in(&root)));
}
out.sort_by(|a, b| a.path.cmp(&b.path));
out.dedup_by(|a, b| a.path == b.path);
match out.len() {
0 => tracing::warn!("spring routes: no mapping source under {:?}", project.root),
n => tracing::info!("spring routes: {n} mapping sources under {:?}", project.root),
}
Ok(out)
host.blocking(move || {
let mut out = Vec::new();
for root in scan_roots(&project.root, project.content_roots()) {
out.extend(sources_in(&root, &project.search_excludes_in(&root)));
}
out.sort_by(|a, b| a.path.cmp(&b.path));
out.dedup_by(|a, b| a.path == b.path);
match out.len() {
0 => tracing::warn!("spring routes: no mapping source under {:?}", project.root),
n => tracing::info!("spring routes: {n} mapping sources under {:?}", project.root),
}
Ok(out)
})
.await
}
#[cfg(test)]
+42 -11
View File
@@ -3,7 +3,7 @@ use crate::Host;
use ide_command::command;
use ide_core::remote_settings::RunTargetKind;
use ide_core::{IdeError, IdeResult, RunId};
use ide_run::{OutputChunk, RunConfig, RunInfo, StartOptions};
use ide_run::{OutputChunk, RunAttach, RunConfig, RunInfo, StartOptions};
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
@@ -242,7 +242,10 @@ fn settings_only(
.cloned()
});
if workspace.as_ref().is_some_and(|w| w.is_container(&project.root)) || member.is_some() {
if config.extras.module.is_none() && !matches!(config.kind.as_str(), "application" | "spring-boot") {
let jvm = matches!(config.kind.as_str(), "application" | "spring-boot");
if jvm && member.is_some() && config.cwd.is_none() {
config.cwd = Some(owner.into());
} else if config.extras.module.is_none() && !jvm {
config.extras.module = config.cwd.as_deref().map(ide_core::ipc_path::to_ipc);
}
ide_run::scope::rebase(config, &project.root, None);
@@ -485,14 +488,17 @@ async fn start_inner(
}
// A Python configuration pointing at a missing interpreter fails in the depth of
// process spawn otherwise; name the cause and the fix like PyCharm's "Invalid SDK".
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test")
&& !Path::new(&config.command).is_file()
&& Path::new(&config.command).components().count() > 1
{
return Err(IdeError::invalid(format!(
"The configured Python interpreter does not exist: {}\nSelect a working interpreter in Settings › Languages & Frameworks › Python Interpreter.",
config.command
)));
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "django-test");
if is_python && Path::new(&config.command).components().count() > 1 {
let cwd = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
let executable = ide_core::project_roots::resolve(&cwd, Path::new(&config.command));
if !executable.is_file() {
return Err(IdeError::invalid(format!(
"The configured Python interpreter does not exist: {}\nSelect a working interpreter in Settings › Languages & Frameworks › Python Interpreter.",
config.command
)));
}
config.command = ide_core::ipc_path::to_ipc(&executable);
}
if config.kind == "tomcat" {
if host.processes.list().iter().any(|r| r.running && r.config_id == config.id) {
@@ -515,10 +521,21 @@ async fn start_inner(
})
.await?;
}
let mut python_paths = if *root != project.root { vec![root.clone()] } else { super::python::paths(&project) };
if is_python {
let near = ide_run::scope::owner(&project.root, &config);
python_paths = super::python::with_user_paths(
python_paths,
&host.config_dir,
&project,
Some(&config.command),
Some(&near),
);
}
let encoding = settings.console.encoding;
let options = StartOptions {
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
python_paths: if *root != project.root { vec![root.clone()] } else { super::python::paths(&project) },
python_paths,
ruby_reporter: ruby_reporter_dir(host, &config),
};
project.require_trust()?;
@@ -627,6 +644,19 @@ pub fn run_list(host: &Host) -> Vec<RunInfo> {
runs
}
/// Reattaches to a running process `id` on this host, returning its buffered output
/// and configuration while streaming subsequent chunks to `on_output`.
#[command(trust = always)]
pub async fn run_attach(host: &Host, window: &str, id: RunId, on_output: Channel<OutputChunk>) -> IdeResult<RunAttach> {
host.processes.reattach(
id,
host.window_sink(window),
Box::new(move |chunk| {
let _ = on_output.send(chunk);
}),
)
}
pub mod commands;
pub(crate) mod container;
pub use commands::*;
@@ -799,6 +829,7 @@ mod ownership_tests {
ide_command::domain!(
run:
run_apply_settings,
run_attach,
run_close_stdin,
run_configs,
run_list,
+151 -27
View File
@@ -120,6 +120,49 @@ pub async fn sdk_python_interpreter(host: &Host, window: &str, path: PathBuf) ->
.map_err(join_err)?
}
/// `sys.path` of the interpreter `python`, for All Interpreters › Show Paths.
#[command(trust = outside_restricted)]
pub async fn sdk_python_sys_path(
host: &Host,
window: &str,
python: PathBuf,
request: RequestId,
) -> IdeResult<Vec<ide_core::IpcPath>> {
host.require_trust_if_project(window)?;
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
let paths = ide_sdk::libraries::python_sys_path(&python, &cancel);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let paths = paths.ok_or_else(|| {
IdeError::invalid(format!(
"Cannot read sys.path of {}: the interpreter failed or did not answer in time",
python.display()
))
})?;
Ok(paths.iter().map(|p| p.as_path().into()).collect())
})
.await
.map_err(join_err);
host.end_request(request);
result?
}
/// For each folder added to an interpreter's paths, why it stays off the import path
/// (`None`: it is used). The folders may not be saved yet.
#[command(trust = outside_restricted)]
pub async fn sdk_python_user_path_problems(
host: &Host,
window: &str,
paths: Vec<String>,
) -> IdeResult<Vec<Option<ide_sdk::apply::UserPathProblem>>> {
host.require_trust_if_project(window)?;
tokio::task::spawn_blocking(move || paths.iter().map(|p| ide_sdk::apply::user_path(p).err()).collect())
.await
.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,
@@ -336,7 +379,21 @@ pub async fn sdk_locate_tools(
.map_err(join_err)
}
/// Creates a Python environment with `tool` (`venv` / `uv` / `poetry`); output streams through `on_output`.
/// The environments the window's project defines for Hatch, `default` first (hatch must be on PATH).
#[command(trust = outside_restricted)]
pub async fn sdk_python_hatch_envs(host: &Host, window: &str, request: RequestId) -> IdeResult<Vec<String>> {
host.require_trust_if_project(window)?;
let root = host.project(window)?.root.clone();
let cancel = host.begin_project_request(window, request);
let result =
tokio::task::spawn_blocking(move || ide_sdk::python::hatch_envs(&root, &cancel)).await.map_err(join_err);
host.end_request(request);
result?
}
/// Creates a Python environment and streams its output through `on_output`.
/// With Pipenv, `install_packages` also installs the packages declared in the project's `Pipfile`.
#[allow(clippy::too_many_arguments)]
#[command(trust = outside_restricted)]
pub async fn sdk_python_create_venv(
host: &Host,
@@ -344,13 +401,14 @@ pub async fn sdk_python_create_venv(
tool: ide_sdk::python::VenvTool,
base: PathBuf,
location: PathBuf,
install_packages: bool,
request: RequestId,
on_output: Channel<String>,
) -> IdeResult<Sdk> {
host.require_trust_if_project(window)?;
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
ide_sdk::python::create_venv(tool, &base, &location, &cancel, &|line| {
ide_sdk::python::create_venv(tool, &base, &location, install_packages, &cancel, &|line| {
let _ = on_output.send(line);
})
})
@@ -365,12 +423,34 @@ pub async fn sdk_python_packages(
host: &Host,
window: &str,
python: PathBuf,
outdated: bool,
request: RequestId,
) -> IdeResult<Vec<PythonPackage>> {
host.require_trust_if_project(window)?;
let cancel = host.begin_project_request(window, request);
let result =
tokio::task::spawn_blocking(move || ide_sdk::python::list_packages(&python, &cancel)).await.map_err(join_err);
let result = tokio::task::spawn_blocking(move || ide_sdk::python::list_packages(&python, outdated, &cancel))
.await
.map_err(join_err);
host.end_request(request);
result?
}
/// A package index other than PyPI that installing from `python` uses; `None` for PyPI.
#[command(trust = outside_restricted)]
pub async fn sdk_python_package_index(
host: &Host,
window: &str,
python: PathBuf,
request: RequestId,
) -> IdeResult<Option<String>> {
host.require_trust_if_project(window)?;
let project_root = host.project(window).ok().map(|p| p.root.clone());
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
ide_sdk::python::configured_index(&python, project_root.as_deref(), &cancel)
})
.await
.map_err(join_err);
host.end_request(request);
result?
}
@@ -423,7 +503,6 @@ mod tests {
use super::*;
use crate::HostConfig;
use std::path::Path;
use std::sync::Arc;
fn fake_venv(root: &Path, name: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
@@ -436,23 +515,74 @@ mod tests {
python
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_launch_takes_the_user_paths_of_the_interpreter_it_uses() {
use crate::ops::python::{debug_python, with_user_paths};
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let (root, bare, own) = (base.join("project"), base.join("bare"), base.join("own"));
let (for_main, for_own) = (base.join("for-main"), base.join("for-own"));
for dir in [&root, &bare, &own, &for_main, &for_own] {
std::fs::create_dir(dir).unwrap();
}
let (main_python, own_python) = (fake_venv(&root, ".venv"), fake_venv(&own, ".venv"));
ide_workspace::workspace::Workspace::attach(&root, "ws", vec![root.clone(), bare.clone(), own.clone()])
.unwrap();
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let project = host.project("main").unwrap();
let text = |p: &Path| p.to_string_lossy().into_owned();
project
.settings
.set(
ide_workspace::SettingsScope::Global,
"languages.python.interpreterPaths",
serde_json::json!({ text(&main_python): [text(&for_main)], text(&own_python): [text(&for_own)] }),
)
.unwrap();
let paths = |command: Option<&str>, near: &Path| {
with_user_paths(Vec::new(), &host.config_dir, &project, command, Some(near))
};
// A member without a Python of its own runs on the primary project's interpreter;
// a member with its own virtualenv on that one.
assert_eq!(paths(None, &root), std::slice::from_ref(&for_main));
assert_eq!(paths(None, &bare), std::slice::from_ref(&for_main));
assert_eq!(paths(None, &own), std::slice::from_ref(&for_own));
// The interpreter a launch names wins over where it runs; a manager's command does not name one.
assert_eq!(paths(Some(&text(&own_python)), &bare), std::slice::from_ref(&for_own));
assert_eq!(paths(Some("uv"), &own), std::slice::from_ref(&for_own));
assert_eq!(paths(Some("python3"), &bare), std::slice::from_ref(&for_main));
// What is already on the path is neither repeated nor dropped.
let kept = with_user_paths(vec![root.clone(), for_main.clone()], &host.config_dir, &project, None, Some(&root));
assert_eq!(kept, [root.clone(), for_main]);
// Debug resolves a relative command against its working directory before sending it.
let debug_interpreter = bare.join("..").join(own_python.strip_prefix(&base).unwrap());
let mut launch = ide_dap::LaunchConfig {
name: "Python".into(),
adapter: "debugpy".into(),
request: "launch".into(),
program: None,
args: vec![],
cwd: Some(bare.as_path().into()),
env: Default::default(),
extra_json: Some(serde_json::json!({ "python": text(&debug_interpreter) }).to_string()),
};
assert_eq!(debug_python(&launch), Some(text(&debug_interpreter)));
assert_eq!(paths(debug_python(&launch).as_deref(), &bare), [for_own]);
launch.extra_json = Some(serde_json::json!({ "python": ["uv", "run", "python"] }).to_string());
assert_eq!(debug_python(&launch), None);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_hand_picked_venv_is_resolved_like_a_detected_interpreter() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir(&root).unwrap();
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.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 host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
@@ -506,17 +636,7 @@ mod tests {
]);
std::fs::write(config.join("recent.json"), serde_json::to_vec(&recent).unwrap()).unwrap();
let host = Host::new(HostConfig {
config_dir: config,
data_dir: base.join("data"),
local_data_dir: base.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 host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
@@ -545,8 +665,12 @@ ide_command::domain!(
sdk_project_libraries,
sdk_python_create_venv,
sdk_python_effective,
sdk_python_hatch_envs,
sdk_python_interpreter,
sdk_python_packages,
sdk_python_package_index,
sdk_python_pip,
sdk_python_project_interpreters,
sdk_python_sys_path,
sdk_python_user_path_problems,
);
+7 -2
View File
@@ -111,7 +111,7 @@ pub(crate) fn search_project(
};
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
let defaults = project.documents.file_defaults();
let decode = |path: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, defaults.fallback_for(path));
let fallback = |path: &Path| defaults.fallback_for(path).map(str::to_owned);
let mut total = SearchSummary::default();
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
let mut remaining = query.clone();
@@ -139,7 +139,7 @@ pub(crate) fn search_project(
&remaining,
Some(&filter),
Some(&literals),
ide_search::TextSource { overlay: &|p| project.documents.search_text_of(p), decode: &decode },
ide_search::TextSource { overlay: &|p| project.documents.search_text_of(p), fallback: &fallback },
cancel,
&|mut file| {
if let Some(prefix) = &prefix {
@@ -188,6 +188,11 @@ pub(crate) fn rebase_masks(masks: &[String], prefix: &str) -> Vec<String> {
#[cfg(test)]
mod tests {
#[test]
fn search_leaves_unread_the_texts_the_parser_does_not_take() {
assert_eq!(ide_search::MAX_LITERALS_TEXT_BYTES, ide_language::MAX_PARSE_BYTES);
}
#[test]
fn masks_follow_the_root_they_search() {
let masks = vec![".wt/a/src/**, src/**".into(), "*.rs".into(), "!.wt/a/out/**".into(), "**/build/**".into()];
+110 -5
View File
@@ -20,13 +20,18 @@ fn dictionary_paths(settings: &SpellingSettings, root: &Path) -> Vec<PathBuf> {
.iter()
.map(|p| p.trim())
.filter(|p| !p.is_empty())
.map(|p| match p.strip_prefix("~/") {
Some(rest) => dirs::home_dir().unwrap_or_default().join(rest),
None => root.join(p),
})
.map(|p| resolve_dictionary(p, root))
.collect()
}
/// One `spelling.customDictionaries` entry resolved: `~/…` from home, relative from the project root.
fn resolve_dictionary(text: &str, root: &Path) -> PathBuf {
match text.strip_prefix("~/") {
Some(rest) => dirs::home_dir().unwrap_or_default().join(rest),
None => root.join(text),
}
}
fn speller(project: &Project) -> Speller {
let s = project.settings.effective().spelling;
let words = s.ide_words.iter().chain(&s.project_words);
@@ -116,4 +121,104 @@ pub async fn spell_suggest(host: &Host, window: &str, word: String) -> IdeResult
.await
}
ide_command::domain!(spell: spell_check, spell_suggest);
/// Appends `word` to the custom dictionary `dictionary` (a
/// `spelling.customDictionaries` entry: `~/…` from home, relative from the
/// project root) and reports which file was written, creating it when missing.
/// A Hunspell `.dic` with a `.aff` beside it keeps its word count line current;
/// the speller picks the change up through its own mtime cache.
#[command(trust = always)]
pub async fn spell_save_to_dictionary(
host: &Host,
window: &str,
dictionary: String,
word: String,
) -> IdeResult<String> {
let project = host.project(window)?;
blocking(move || {
let entry = dictionary.trim();
if entry.is_empty()
|| !project.settings.read_effective(|s| s.spelling.custom_dictionaries.iter().any(|p| p.trim() == entry))
{
return Err(IdeError::invalid("Select a configured custom dictionary"));
}
let w = word.trim();
// One word per line: no whitespace, no line breaks; digits and hyphens
// may appear, but at least one letter (a number list checks nothing).
if w.starts_with('#')
|| w.contains('/')
|| w.chars().any(|c| c.is_whitespace() || c.is_control())
|| !w.chars().any(|c| c.is_alphabetic())
{
return Err(IdeError::invalid(format!("'{word}' is not a word a dictionary can list")));
}
let path = resolve_dictionary(entry, &project.root);
// Serialize the read/modify/write across projects that share a dictionary.
static SAVES: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
let _save = SAVES.lock();
let mut text = match std::fs::metadata(&path) {
Ok(m) if !m.is_file() || m.permissions().readonly() => {
return Err(IdeError::invalid(format!("{} is not a writable dictionary file", path.display())));
}
Ok(_) => std::fs::read_to_string(&path)?,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => return Err(e.into()),
};
let hunspell = ide_spell::affix_file(&path).is_some();
let already_listed = if hunspell {
text.lines().any(|line| line.trim() == w)
} else {
ide_spell::parse_word_list(&text).contains(&w.to_lowercase())
};
if already_listed {
return Ok(String::new());
}
let newline = if text.contains("\r\n") { "\r\n" } else { "\n" };
if hunspell {
let body = text.strip_prefix('\u{feff}').unwrap_or(&text);
let start = text.len() - body.len()
+ body
.split_inclusive('\n')
.take_while(|line| line.trim_start().starts_with('#'))
.map(str::len)
.sum::<usize>();
let header = text[start..].lines().next().unwrap_or_default();
if let Some(count) = header.trim().parse::<usize>().ok().and_then(|n| n.checked_add(1)) {
text.replace_range(start..start + header.len(), &count.to_string());
} else if text.is_empty() {
text.push_str("1\n");
}
}
if !text.is_empty() && !text.ends_with('\n') {
text.push_str(newline);
}
text.push_str(w);
text.push_str(newline);
// A dictionary file may name folders that do not exist yet (a fresh
// project layout): create them, then write.
if let Some(dir) = path.parent()
&& !dir.is_dir()
{
std::fs::create_dir_all(dir)?;
}
ide_vfs::write_atomic_strict(&path, text.as_bytes())?;
Ok(path.to_string_lossy().into_owned())
})
.await
}
ide_command::domain!(spell: spell_check, spell_suggest, spell_save_to_dictionary);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn resolves_home_dictionaries() {
if let Some(home) = dirs::home_dir() {
assert_eq!(
resolve_dictionary("~/words/personal.txt", Path::new("project")),
home.join("words/personal.txt")
);
}
}
}
+2 -11
View File
@@ -272,17 +272,8 @@ impl Fixture {
std::fs::create_dir_all(root.join("src")).unwrap();
let source = root.join("src/Chains.java");
std::fs::write(&source, SOURCE).unwrap();
let host = Host::new(crate::HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.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 host =
Host::new(crate::HostConfig { local_data_dir: base.join("local"), ..crate::HostConfig::for_test(&base) });
host.open_project(WINDOW, &root).unwrap();
host.set_project_trust(&root, true, false).await.unwrap();
Self { host, source, _temp: temp }
+41 -18
View File
@@ -1,15 +1,15 @@
use super::{Channel, Emit};
use crate::Host;
use ide_command::command;
use ide_core::{IdeResult, TerminalId};
use ide_terminal::{TerminalInfo, TerminalOptions};
use ide_core::{IdeResult, IpcBytes, TerminalId};
use ide_terminal::{TerminalAttach, TerminalInfo, TerminalOptions, TerminalSessionInfo};
mod images;
const MAX_IMAGE_BYTES: usize = 20 * 1024 * 1024;
#[command(trust = always)]
pub async fn term_store_image(host: &Host, id: TerminalId, data: Vec<u8>, mime: String) -> IdeResult<String> {
pub async fn term_store_image(host: &Host, id: TerminalId, data: IpcBytes, mime: String) -> IdeResult<String> {
if data.len() > MAX_IMAGE_BYTES {
return Err(ide_core::IdeError::invalid("image is too large to paste (limit 20 MB)"));
}
@@ -53,6 +53,7 @@ pub async fn term_spawn(
Box::new(move |chunk| {
let _ = on_output.send(chunk);
}),
None,
)?;
if let Some(line) = activation {
let _ = host.terminals.write(info.id, &format!(" {line}\r"));
@@ -160,6 +161,36 @@ pub fn term_kill(host: &Host, id: TerminalId) -> IdeResult<()> {
host.terminals.kill(id)
}
/// Live terminal sessions of this window, for reattaching after a reconnect.
#[command(trust = always)]
pub async fn term_list(host: &Host, window: &str) -> Vec<TerminalSessionInfo> {
host.terminals.list_key(host.owner_window(window))
}
/// Reattaches to an existing terminal session `id`, returning its buffered output
/// and streaming subsequent chunks to `on_output`.
#[command(trust = always)]
pub async fn term_attach(
host: &Host,
window: &str,
id: TerminalId,
cols: u16,
rows: u16,
on_output: Channel<String>,
) -> IdeResult<TerminalAttach> {
let key = host.owner_window(window);
host.terminals.reattach(
id,
key,
cols,
rows,
host.window_sink(window),
Box::new(move |chunk| {
let _ = on_output.send(chunk);
}),
)
}
/// Whether the session is running a command (closing its tab asks first). A
/// `tcgetpgrp` or one process snapshot: async only to stay off the main thread.
#[command(trust = always)]
@@ -183,28 +214,18 @@ pub fn term_available_shells() -> Vec<String> {
mod tests {
use super::*;
use crate::HostConfig;
use ide_core::{NullSink, error::ErrorKind};
use std::sync::Arc;
use ide_core::error::ErrorKind;
#[tokio::test]
async fn image_size_limit_is_checked_before_storage() {
let root = tempfile::tempdir().unwrap();
let host = Host::new(HostConfig {
config_dir: root.path().join("config"),
data_dir: root.path().join("data"),
local_data_dir: root.path().join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let host = Host::new(HostConfig::for_test(root.path()));
let id = TerminalId::next();
let error = term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES + 1], "image/png".into()).await.unwrap_err();
let error =
term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES + 1].into(), "image/png".into()).await.unwrap_err();
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert_eq!(error.message, "image is too large to paste (limit 20 MB)");
let error = term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES], "image/png".into()).await.unwrap_err();
let error = term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES].into(), "image/png".into()).await.unwrap_err();
assert_eq!(error.message, "terminal session not found");
assert!(!host.data_dir.join("terminal-images").exists());
}
@@ -212,10 +233,12 @@ mod tests {
ide_command::domain!(
term:
term_attach,
term_available_shells,
term_default_shell,
term_is_busy,
term_kill,
term_list,
term_resize,
term_spawn,
term_store_image,
+20 -8
View File
@@ -1,4 +1,4 @@
use crate::{Host, apply_git_executable};
use crate::Host;
use ide_command::command;
use ide_core::IdeResult;
use ide_vcs::FileStatus;
@@ -9,9 +9,6 @@ pub async fn vcs_status(host: &Host, window: &str) -> IdeResult<Vec<FileStatus>>
let project = host.project(window)?;
host.blocking(move || {
let settings = project.settings.effective();
if project.is_trusted() {
apply_git_executable(&settings);
}
let repos = project.repos();
if repos.is_empty() {
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
@@ -25,6 +22,21 @@ pub async fn vcs_status(host: &Host, window: &str) -> IdeResult<Vec<FileStatus>>
.await
}
#[command(trust = always)]
pub async fn vcs_ignored_files(host: &Host, window: &str) -> IdeResult<Vec<FileStatus>> {
let project = host.project(window)?;
host.blocking(move || {
let settings = project.settings.effective();
let repos = project.repos();
let ignored = settings.ignored_names();
for repo in repos.all() {
repo.set_ignored_names(ignored.clone());
}
repos.ignored_files()
})
.await
}
/// Changes of `paths` only: the dirty-scope refresh after a watcher batch.
#[command(trust = always)]
pub async fn vcs_status_paths(host: &Host, window: &str, paths: Vec<std::path::PathBuf>) -> IdeResult<Vec<FileStatus>> {
@@ -32,9 +44,6 @@ pub async fn vcs_status_paths(host: &Host, window: &str, paths: Vec<std::path::P
let project = host.project(window)?;
host.blocking(move || {
let settings = project.settings.effective();
if project.is_trusted() {
apply_git_executable(&settings);
}
let repos = project.repos();
if repos.is_empty() {
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
@@ -49,7 +58,10 @@ pub async fn vcs_status_paths(host: &Host, window: &str, paths: Vec<std::path::P
}
pub mod commands;
mod rebase_editor;
mod worktree_setup;
pub use commands::*;
pub(crate) use rebase_editor::RebaseEditors;
/// Refuses (with `refusal`) to remove or move the worktree that holds the open project.
fn check_worktree_away_from_project(
@@ -90,4 +102,4 @@ fn check_worktree_away_from_project(
Ok(())
}
ide_command::domain!(vcs: vcs_status, vcs_status_paths);
ide_command::domain!(vcs: vcs_status, vcs_status_paths, vcs_ignored_files);
File diff suppressed because it is too large. Load diff
Loaded 100 of 1294 files, more files were not shown because too many files have changed in this diff. Show more