Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 32bfbc3a78 fix(theme): switch themes without flicker, preview them at once, drop the built-in One themes
Switching a theme with several windows open flickered for seconds: the plugin theme is shared by every window, and each window put back the theme its own settings named whenever it changed, before those settings caught up. Windows now act on the plugin theme only when their own selection changes, and applying the theme already shown keeps its stylesheet instead of replacing it.

Theme previews in the gear menu, Quick Switch and Settings waited 500 ms, and on themes written with hsl() or color-mix() the terminal took up to a second to read its colours: each token was resolved through a new element inserted under the root, restyling the whole page every time. Previews now show at once, and token colours resolve through one element kept for it.

The built-in One Light and One Dark themes are removed in favour of the One Dark Pro plugin; settings naming them read as Islands Light and Islands Dark.
2026-11-12 22:41:36 +08:00
l0ng-ai 405343b7b7 fix(code-insight): show a language server busy only once it stays busy (#2953)
jdtls reports a $/progress task on almost every edit, save, search and diagnostics publish, most lasting 0-20 ms, so the status bar's language-server dot kept switching to busy and back. A running server now shows busy only after it has been busy for 500 ms, the delay background tasks already use. Other statuses and the switch back to running still show at once; only the status bar display is delayed.
2026-11-12 21:47:39 +08:00
Muuтаmuutot cc29842e6b fix(python): workspace members inherit the project interpreter, and a deleted one falls back (#2920)
A workspace member attached to a project resolved its Python interpreter only from its own settings and folder, so a member with no Python of its own ran on the PATH python while the status widget named the primary project's interpreter. Members now inherit the primary project's interpreter when they have none (explicit setting, then virtualenv or pin, as a module without its own SDK inherits the project SDK), sdk_python_effective answers with the same chain, and the status widget asks about the open file's member.

A configured interpreter whose executable was deleted is skipped during resolution, so runs fall back to the project virtualenv or the inherited interpreter. Settings mark it Invalid (decided from what the backend resolves, so working custom paths are not flagged), the status widget warns when nothing resolves, and starting a Python configuration on a missing path names the cause.

Co-authored-by: muutot <[email protected]>
2026-11-12 21:45:37 +08:00
l0ng-ai de0f738bb2 fix(editor): keep Enter for new lines in a completion's snippet (#2967)
Completing an XML tag inserts the server's snippet <tag>$1</tag>$0. Enter moved to the next snippet field in every snippet, so it jumped to the end of the line instead of splitting the tag. Enter now moves between fields only in live templates and Emmet; in a completion's snippet Tab does and Enter inserts a line break.

Closes #2951
2026-11-12 21:25:54 +08:00
l0ng-ai d781df542a fix(lsp): answer Java usages without waiting for jdtls' background work (#2945)
A usages search that found nothing waited up to 10 s for every $/progress task to end before asking again, and jdtls reports background work (builds, validation) for long stretches, so Show Usages on a method nothing calls could take 10 s. jdtls' searches wait for its index themselves, so after ServiceReady an empty answer is final: it is neither waited on nor flagged as incomplete. Before ServiceReady, and for other servers, running progress still counts as indexing.

Refs #2770
2026-11-12 21:12:54 +08:00
SunZhiQiang abfc4cbade feat(agents): review a task's commits in the Changes pane (#2960)
A worktree task's Changes pane only listed the cumulative diff since the task started, so work the agent committed was mixed into the current changes. It now groups the task's work: uncommitted files compared with HEAD, and each commit made since the task started with the files it changed against its first parent. Double-clicking a commit or one of its files opens the parent-to-commit diff; commit files are history and are not rolled back. Rollback in this view restores files to HEAD. Accept still brings over the task's whole work, committed or not. View Options > Group By > Commit switches back to the flat since-start list; tasks in the project's own checkout keep that list.

Co-authored-by: panda-student <[email protected]>
2026-11-12 21:10:33 +08:00
arookieofcтаa-rookie-of-C-language 646e5f8364 fix(vcs): explain a mode-only change in the diff viewer (#2864)
A chmod-only change is a real modification: git status lists it and a commit records the new mode, so status keeps reporting it (core.fileMode=false still hides it). The diff viewer used to show "Contents are identical" with no explanation; when both texts are equal but the git modes differ it now says "File mode changed: 100644 → 100755". The modes come from a new vcs_file_mode command (index/tree entry mode for revisions, worktree permissions for the working copy).

Closes #2853

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-12 21:01:13 +08:00
Mr0Bread a3b48b78fd fix(editor): keep narrow editor groups usable with vertical tabs (#2962)
With tabs placed left or right, the tab column was sized to its longest label (140–260 px) and never shrank, so in a narrow split group a long file name left the editor almost no room. The column is now capped at 40% of its group; long labels truncate and keep the full path in the tooltip. Top and bottom placement are unchanged.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-12 20:55:15 +08:00
Ernstjan FreriksтаEjaYF 5e4fa861bb fix(agents): move the caret with Home and End in the agent composer on macOS (#2943)
WebKit maps Home / End in a text box to scrolling and leaves the caret where it is, so they did nothing in the agent composer on macOS. The composer now moves the caret to the start or end of the visual line (Shift extends the selection); with ⌘, Ctrl or Alt the keys keep their native behaviour, and other platforms are unchanged.

Co-authored-by: EjaYF <[email protected]>
2026-11-12 20:55:06 +08:00
hwlLL0703 068ce8e721 feat(maven): import external Maven modules from Project Structure (#2922)
A Maven project outside the opened root can be linked explicitly: Add Maven Projects accepts an external pom.xml, and Project Structure › Modules › Import Module from Existing Sources (also on the project root's context menu) imports a directory with a pom.xml. The linked project becomes an extra project-tree root and an independent Maven project with its own working directory and wrapper; links are stored as canonical paths, survive reloads and reopening, and unlinking removes only the association. The opened project's jdtls gets the external directory as an extra workspace folder, keeping automatic discovery under the opened root. Neither POM is edited.

Merged with main's aggregation fix: a project an aggregator lists later becomes its module only when the aggregator lies inside the opened root and is not on the same chain, so a linked sibling does not take over the opened project.

Closes #2884

Co-authored-by: hwlLL0703 <[email protected]>
2026-11-12 20:52:00 +08:00
l0ng-ai e5cc1ed712 fix(http-client): show the request in the tool window while it is sent (#2966)
The HTTP Client tool window opened only once a response arrived, so slow requests looked unanswered. It now opens as the request is sent, and the response pane shows the request line, a progress indicator and Stop Request until the response replaces it.

Fixes #2937
2026-11-12 20:40:59 +08:00
l0ng-ai abe6285629 feat(app): resizable New Project dialog (#2965)
The New Project dialog gets a resize grip and remembers its size; the template list and settings pane grow with it. It opens at the same default size as before.

Part of #2903
2026-11-12 20:36:00 +08:00
l0ng-ai 66a829c24c fix(maven): an aggregator in a subfolder holds the root POM it lists as ../ (#2963)
The root POM was found first as a top-level project and skipped when parent/pom.xml listed it again as <module>../</module>, and module paths kept their '..', so the Maven tool window showed the root module beside the aggregator. Module paths are normalised and a project an aggregator lists later becomes its module.

Fixes #2877
2026-11-12 20:32:00 +08:00
l0ng-ai 04f3f9434f fix(remote): serve Open in Browser and the built-in preview from the remote host (#2961)
In a remote window the built-in web server ran on the client and read the local file system, so URLs for remote files were 404s. The server now lives in the host: openidea-server answers web_url with its own server on the remote loopback, and the client forwards that port over the SSH or dev container connection and returns the forwarded URL. The Host check accepts any port with 127.0.0.1 / localhost, since the forwarded port can differ.

Fixes #2915
2026-11-12 20:18:11 +08:00
l0ng-ai 4330034403 perf(remote): list the deployment tree concurrently and report sync phases (#2959)
Sync before run listed the remote project one folder after another and checked each external classpath entry in turn, a round trip each, silently. Folders are now listed 16 at a time and classpath entries checked the same way; the run console reports the comparing / checking phases and the elapsed time. The walk still visits every folder, so results are unchanged.

Part of #2873
2026-11-12 20:05:43 +08:00
l0ng-ai de8afe31d2 fix(remote): finish SSH runs whose channel outlives the process (#2957)
A remote run finished only when its SSH channel closed, so a channel that outlived the process (a child holding the inherited stdout, or a server that never closes it) left the run, and Stop / Rerun, hanging. The exit status now ends the process once the channel has been quiet for a second, and Stop finishes the run locally when the channel still reports nothing 3 s after KILL.

Fixes #2872
2026-11-12 20:02:25 +08:00
l0ng-ai 579e5eee9b feat(languages): add Prisma (#2955)
Prisma schema files get highlighting, structure view and folding from the bundled tree-sitter-prisma-io grammar, a file icon, and code insight from @prisma/language-server (installable from the IDE). The language definition provides the `prisma` settings section the server reads before each validation; without it the server crashed.

Closes #2926
2026-11-12 20:00:13 +08:00
l0ng-ai 099ede3478 fix(vcs): Commit… from Local Changes includes the selected files and focuses the message (#2952)
With the modal commit interface, Commit… (⌘K) and Commit and Push… invoked from Local Changes include just the selected files, and the commit message field takes focus. Invoked elsewhere, the dialog starts with the default inclusion instead of the previous dialog's leftovers.

Fixes #2923
2026-11-12 19:33:15 +08:00
l0ng-ai fb269afdfa fix(lsp): run every server's fix-all on save, and give ESLint its codeActionOnSave setting (#2950)
Run code cleanup applied one source.fixAll action, so in TypeScript files vtsls's won and ESLint's was dropped; fix-all now runs once per server that offers it, each asked again after the previous edit. ESLint rejected every fix-all request because the built-in settings lacked codeActionOnSave; all language files attaching eslint now send { mode = "all", rules = [] }. Failed save actions are logged.

Fixes #2927
Fixes #2928
2026-11-12 19:23:59 +08:00
Alexanderтаformiat 435b00d893 feat(search): colour Find in Files preview matches with the editor's search result colour (#2949)
Matches in the Find in Files and Search Everywhere preview use the editor scheme's search result background (IntelliJ's SEARCH_RESULT_ATTRIBUTES, new token --bg-search-result with values for every built-in theme) instead of the lists' SearchMatch yellow, as a background only so syntax colours stay readable. SEARCH_RESULT_ATTRIBUTES now imports into the new token; --bg-search-match keeps coming from SearchMatch.

Closes #2858

Co-authored-by: formiat <[email protected]>
2026-11-12 19:20:34 +08:00
jiejie1133 14fe542617 fix(editor): leave the caret after a completion snippet without fields (#2939)
CodeMirror leaves the caret before an inserted snippet that has no fields, so accepting a field like `val` at `root.` put the caret before it. LSP snippets without tab stops, choices or unresolved variables now get a final ${0} stop; SQL functions without parameters had the same problem and get one too. Snippets with fields keep their selection.

Closes #2936

Co-authored-by: jiejie1133 <[email protected]>
2026-11-12 19:19:37 +08:00
persicaTaoтаpersicaTao 513762147a fix(db): do not require TLS when SQL Server SSL is disabled (#2938)
Tiberius defaults to EncryptionLevel::Required with rustls, and trust_cert only skips certificate checks, so a SQL Server data source with SSL = Disable still negotiated TLS and timed out against a server without encryption (or one rustls can't speak TLS with). Disable now selects NotSupported; Prefer still trusts the certificate, Require and Verify keep validated TLS.

Closes #2917

Co-authored-by: persicaTao <[email protected]>
2026-11-12 19:18:49 +08:00
l0ng-ai 489f55f52c fix(vcs): don't commit a file that was added to the index and then deleted (#2947)
A file added to the index and then deleted from disk is listed nowhere in the Commit view, but it stayed in the index copy the commit is made from, so committing other files committed it too. Such staged entries are now excluded like unchecked staged files.

Fixes #2908
2026-11-12 19:15:23 +08:00
l0ng-ai 55fcbf281a fix(editor): keep hover documentation inside its popup near the window edge (#2946)
Near the window edge CodeMirror caps the hover tooltip's height, but the documentation section kept its own 380px maximum and ran past the popup's border. The tooltip is now a flex column whose sections shrink and scroll within it.

Fixes #2910
2026-11-12 19:13:31 +08:00
Clarence f8aa003b47 feat(editor): render documentation comments (#2934)
Javadoc, KDoc, JSDoc, rustdoc and other /** and /// comments can be drawn in place as formatted documentation and switched back to source: globally (Settings › Editor › General › Appearance › Render documentation comments, off by default), per file (View › Active Editor › Render Documentation Comments, gutter menu, editor.toggleRenderedDocs) and per comment (gutter icon on hover, editor.toggleRenderedView at the caret). Comments are rescanned only once typing pauses and the Markdown renderer loads on first use.

Co-authored-by: Clarence404 <[email protected]>
2026-11-12 19:05:25 +08:00
Qingтаqtvbwfn e27b7f2502 feat(services): show a running-services badge on the window button (#2891)
The Services tool window's stripe button shows how many listed services are running: one per configuration (a run and its attached debugger count once), leaving out types not added, Docker kinds and hidden configurations; hidden at zero. The run provider keeps the count in a shared store, so the Services feature renders it without importing the run feature.

Co-authored-by: qtvbwfn <[email protected]>
2026-11-12 19:03:45 +08:00
langxpтаkradme bc00302ef8 fix(debugger): echo the Java launch command in the debug console (#2930)
Java Debug launches through java-debug in jdtls, which bypasses the Run process that echoes its command line. Debug now prints the equivalent java … -cp … Main … command after the build and classpath resolution, so Debug and Run output stay comparable.

Co-authored-by: kradme <[email protected]>
2026-11-12 19:03:38 +08:00
Mansur Akhmadiтаmansur-akhmadi 2e044c4a2b feat(vcs): show each repository's branch on its node in the Commit tool window (#2911)
With several Git repositories, each repository node in the Commit tool window now shows its current branch as a dimmed hint after the name (the short HEAD commit when detached), with the branch widget's branch / commit icon, from the heads the VCS store already loads.

Closes #2912

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-12 19:03:18 +08:00
l0ng-ai b1959e8fb5 fix(java): state the installed jdtls' JDK requirement in the language server JDK settings (#2876)
Settings said the language server JDK needs "jdtls 21+", but recent jdtls bundles an Eclipse platform that needs JDK 25, so a JDK 21 chosen there was rejected at launch. The requirement is now read from the installed jdtls (new jdtls_required_java command, the same bundle scan as the launch check): the hint states it, flags a too-old selection, the JDK picker marks too-old JDKs, and Download JDK preselects that version.
2026-11-12 19:03:00 +08:00
Qingтаqtvbwfn ce67c7e129 feat(run): colour console log lines by level (#2924)
Run and Debug consoles can colour whole lines by detected log level (ERROR, WARN, INFO, DEBUG, TRACE), reusing the log editor mode's level vocabulary; ANSI colours the program prints win. Settings › Build, Execution, Deployment › Console has the toggle and one colour per level (scheme tokens by default). Off by default, since IDEA's console doesn't colour lines by level.

Co-authored-by: qtvbwfn <[email protected]>
2026-11-12 19:01:01 +08:00
l0ng-ai 3cc94e340b fix(editor): move through the completion lookup with ⌃N / ⌃P on macOS (#2944)
On macOS ⌃N / ⌃P are line down / up in text, so with the lookup open they moved the caret instead of the selection. With a lookup open they now move its selection, as ↓ / ↑ do.

Fixes #2905
2026-11-12 18:58:15 +08:00
arookieofcтаa-rookie-of-C-language 51793e02c5 fix(debugger): use the same console font as the Run window (#2865)
The debug console used the UI mono font and size instead of the console font the Run window resolves from Tools › Terminal › Font (or Editor › Font). Both consoles now take family, size and row height from a shared useConsoleFont() hook, the debug console re-measures its rows when the size changes, and its evaluate input uses the same font.

Closes #2844

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-12 18:57:51 +08:00
l0ng-ai 1e0ce64b0c fix(plugins): don't block Find Usages on a failed plugin index batch (#2941)
A plugin indexer batch that failed left its paths dirty forever, so every later Find Usages and rename failed with "Plugin indexes are still updating". Failed paths are now retried before the next usages or refactoring; usages go ahead with a "may be incomplete" note while an index is not up to date, and refactoring refuses with a message that says the index failed.

Fixes #2913
2026-11-12 18:37:36 +08:00
HL-slcтаHL-slc 6e7b39023c fix(vcs): show changes in submodules whose git dir path exceeds MAX_PATH on Windows (#2902)
gitoxide checks ownership of a submodule's unnormalized `<worktree>/../../.git/modules/…` path with GetNamedSecurityInfoW, which rejects paths past 260 characters, so deep submodules were skipped and the parent's status fell back to git. The app manifest now declares longPathAware, so Win32 path APIs accept long paths where the system enables them.

Co-authored-by: HL-slc <[email protected]>
2026-11-12 18:28:04 +08:00
aconeshanaтаaconeshana c5d319c298 fix(run): keep a blank output line free of a zero-width space (#2906)
A blank console row rendered a U+200B text node to keep its height, and selections and Copy took that node as content. Blank rows now get their height from the row box (minHeight = rowHeight) and render no text.

Closes #2878

Co-authored-by: aconeshana <[email protected]>
2026-11-12 18:24:19 +08:00
arookieofc 0780171704 test(i18n): whitelist Bun product names in own-script locales (#2931) 2026-11-12 18:11:08 +08:00
l0ng-ai 0324a81ce4 fix(ssh): update russh to 0.65 (RUSTSEC-2026-0495) (#2935)
The advisory covers russh's SSH agent server, which signed with confirm-constrained keys without asking; OpenIDEA only uses the agent client, so it was not affected, but cargo deny fails on main. 0.65 passes the verified key to the server's auth_publickey; the test SSH server follows.
2026-11-12 18:05:33 +08:00
l0ng-ai 7c51662e9e chore: v0.1.43 2026-11-12 17:52:04 +08:00
l0ng-ai 6b91fb396a fix(ui): stop selection stripes and flashes in reading panes
Repaint the pane when its selection changes, so a shrinking selection
leaves no stripe between blocks, and clamp a double or triple click
selection to the pane before it is painted into the next field.
2026-11-12 17:49:58 +08:00
l0ng-ai 4792647d06 fix(ui): keep the text selection a context menu was opened on 2026-11-12 17:49:57 +08:00
l0ng-ai 0262812d9b fix(search): find scratch files in Search Everywhere's Files results 2026-11-12 17:09:52 +08:00
l0ng-ai 33957ed34f fix(ui): show full labels in the commit panel, console preview and install hints (#2916)
- Commit panel: the action row wraps at narrow widths, so "Commit and Push…"
  moves to its own line instead of being cut to "Commit ..."; its tooltip
  names the action as well as the shortcut.
- Console Colors preview: four short lines, so the bright colors no longer
  run past the preview's right edge.
- Language server and debugger install hints are plain text: drop the
  Markdown backticks that showed up literally.
- Appearance: "Accent color", matching the rest of the UI.
2026-11-12 16:13:56 +08:00
l0ng-ai de9c8db74e fix(agents): edit composer references as ordinary text 2026-11-12 15:49:09 +08:00
l0ng-ai e1f41093ec fix(agents): delete a reference being typed character by character in the composer
Backspace, Delete and the arrow keys treated any @path or /command under the caret
as one tag, so backspacing while typing a path removed the whole path. The tag being
typed (or a folder entered with Tab) now edits character by character; a completed
reference still deletes as a unit.
2026-11-12 15:23:02 +08:00
l0ng-ai 53d5d66520 fix(agent): roll back renames to their old path (#2909)
Rolling back a task's rename restored only the new path, so the file at its old
path stayed gone. Rollback now also restores the rename source.

A case-only rename on a case-insensitive disk lost the file entirely: revision
lookups used the index's spelling of the path, which no longer matches the
revision's tree, so the old file read as absent. Revision lookups now try the
path as given first and fall back to the index's spelling.
2026-11-12 15:00:56 +08:00
l0ng-ai 0eb68afd40 fix(deploy): don't download or delete through links that leave the mapped folder (#2907)
Download from Server and Sync with Deployed wrote remote files to their mapped
local paths without checking for symbolic links, so a linked folder or file in
the project sent the download, or a local delete, outside the mapped folder.
Both now refuse a path that resolves outside its mapping.
2026-11-12 14:54:15 +08:00
l0ng-ai de2a631c17 fix: FTP download temp files, CRLF and case-only renames in Accept, IPv6 loopback WebSockets (#2901)
FTP downloads use an exclusively created random temporary file and keep the replaced file's permissions; Accept Changes treats a CRLF checkout of the committed text as unchanged and applies case-only renames; ws://[::1] counts as loopback.
2026-11-12 13:49:53 +08:00
l0ng-ai 59755adec4 chore(plugins): rebuild checked-in components for the current SDK and WIT (#2900)
The WebSocket and document-subscription APIs changed wit/ and the SDK, so the checked-in components no longer matched their source fingerprints; this rebuilds all 43.
2026-11-12 13:38:11 +08:00
l0ng-ai 5c7de8b6d7 perf(editor): find the token before < directly in Kotlin and C# (#2899)
Deciding whether < starts a generic list in Kotlin/C# walked every token from the file start and sliced the text to the caret on each keystroke (quadratic); it now resolves the token before the caret's spaces directly.
2026-11-12 13:30:18 +08:00
l0ng-ai ab41d9aa71 fix(agents): accept worktree changes at repository paths, renames included (#2898)
Accept Changes joined repository-relative paths to the task's project root, so a project in a repository folder got doubled paths and skipped modifications; paths now map from the checkout's repository root. A rename also removes the old path.
2026-11-12 13:29:09 +08:00
l0ng-ai 4ecd04af79 fix(settings): leave registry agent installs in place when moving local data (#2896)
Moving the local data directory moved agents/tools, but registry agent files name their executables by absolute path (and uv installs aren't relocatable), so installed agents stopped starting. They stay behind like other non-relocatable tool installs.
2026-11-12 13:25:42 +08:00
l0ng-ai d09156ca8a fix(deployment): don't download through symbolic links out of the chosen folder (#2895)
Download to… checked local paths lexically, so a link already in the chosen folder sent files elsewhere. Folders and files are now written only when their closest existing ancestor resolves inside the folder and the path itself is not a link.
2026-11-12 13:23:52 +08:00
l0ng-ai 1946dbd87c fix(deployment): keep local files on a failed FTP download and don't hang on mkdir (#2894)
An FTP download truncated the local file before the transfer finished, so a failed one left it empty or partial; it now downloads to a sibling temporary file and replaces the destination after the server confirmed the transfer. mkdir_all held the connection lock through its match arms, so a failed MKD deadlocked in is_dir.
2026-11-12 13:22:31 +08:00
l0ng-ai 10d53e9956 fix(vcs): don't run repository filters in the restricted git status fallback (#2893)
When gitoxide can't read a directory, status asks git (#2800); that run lacked the Restricted Mode guards, so an untrusted repository's clean/process filters or a submodule's could run. It now empties the filters (failing closed) and passes --ignore-submodules=dirty in Restricted Mode.
2026-11-12 13:20:31 +08:00
l0ng-ai 780052d204 fix(plugins): keep command edits undoable and accept WebSocket URLs (#2892)
text-editor.apply-edits and the background editor.apply-edits-at share the versioned document write; since #2610 it marked every edit as a workspace edit, which the editor leaves out of Undo. Only edits without a window are marked now. websocket-connect derived its grant with the HTTP URL check that rejects ws:// and wss://; WebSocket URLs now need the grant of their https/http counterpart.
2026-11-12 13:18:36 +08:00
l0ng-ai 80a693c1bf fix(navigation): say it is finding the target until the target shows (#2870)
Go to Declaration / Implementation kept "Finding navigation target…" only while the server was asked, so a quick answer followed by the chooser's row preparation showed nothing for up to ~100 ms, and Go to Implementation dropped the hint when its first results arrived. The hint now lasts until the editor reaches the target or the chooser opens.
2026-11-12 13:03:25 +08:00
morf-bls 7097fb46dd feat(debugger): debug Bun files with bun-dap (#2478)
Run File configurations for TypeScript/JavaScript run with Bun now debug through bun-dap, a DAP adapter for Bun registered as a built-in debugger (TCP, installed by the user). Adds a Bun run configuration type (run/test, script, arguments, working directory) with its icon; the bun-dap launch takes the program and its arguments from the `bun run <file> …` command line. Bun configurations using js-debug still explain why they can't be debugged.

Co-authored-by: morf-bls <[email protected]>
2026-11-12 12:56:52 +08:00
Lucas 39d798e8c1 feat(plugins): versioned document subscriptions and background document edits (#2610)
Plugins can subscribe to committed local edits of open project documents with subscribe-paths("document-changed", globs) and receive versioned UTF-16 replacements. editor.document-at and editor.apply-edits-at read and edit an explicitly named open project document from background events; stale versions are rejected without changing the editor, and these edits are non-undoable and not re-emitted as local changes.

document-changed is delivered only for named paths and only to plugins granted project.read and editor.read. Also delivers websocket-ready events to plugins from the frontend runtime. API 1.6.

Co-authored-by: SorPuti <[email protected]>
2026-11-12 12:40:15 +08:00
HL-slcтаHL-slc 30a0b1d9fd fix(lsp): decode semantic tokens with negative deltas instead of shifting the rest of the file (#2890)
JDT LS emits the tokens of a generic class header with a bounded type parameter and a superclass on the next line out of order and duplicated (eclipse-jdtls/eclipse.jdt.ls#3975), giving negative deltaLine/deltaStart. They were read as unsigned with unwrap_or(0), so every later token landed one line off. Deltas are now decoded as signed, tokens before the document start are dropped, and the result is sorted and de-duplicated.

Co-authored-by: HL-slc <[email protected]>
2026-11-12 12:30:10 +08:00
Clarence 41f54ceba9 fix(editor): colour a JavaDoc's text as a doc comment, as IntelliJ does (#2885)
In Java, JavaScript, TypeScript and PHP the Lezer grammars have one node for /* */ and /** */ alike, so a doc comment's text took the plain comment colour. The doc comment tag highlighter, which already finds these comments, now also marks each one with the doc comment style (tags nest inside and keep their colours); plain comments are unchanged.

Co-authored-by: Clarence404 <[email protected]>
2026-11-12 12:27:50 +08:00
l0ng-ai d90b2b7bbe fix(editor): show usage counts that came back incomplete for a moment (#2857)
Servers call an empty references answer incomplete while any of their progress runs, and jdtls reports progress for a few milliseconds around many requests with no settle afterwards, so a usage lens whose count came back incomplete could stay hidden. An incomplete count is now asked again on the next passes, up to three times, before waiting for the server to settle as before. Java lens evals: 4 of 36 runs lost a lens before, 0 of 36 after.
2026-11-12 12:21:27 +08:00
l0ng-ai b2d506a929 test(evals): measure Java code intelligence as the user sees it (#2758)
pnpm eval drives the production workbench in Chromium against a release openidea-server and real jdtls, judging each scenario (navigation, usages, implementations, gutter markers, lenses, diagnostics, completion, docs, rename) on time to feedback, first and complete result, and checking results against evals/java/golden/. Supporting changes: data-* hooks in the usages popup, hints and rows; a shared in-page Tauri shim for smoke tests and evals; a shared perf bundle builder; language-server versions in .github/tool-versions.env shared with Language smoke; the eval agent skill.
2026-11-12 12:17:07 +08:00
l0ng-ai 81e3717d66 fix(services): keep rows of one image's tags apart in the Docker tree (#2842)
docker images lists every tag of one image on its own row with the same id, and image nodes were keyed by id alone, so the virtualized tree got duplicate keys: rows of one image's tags overlapped, and collapsing Images left them over Networks and Volumes. Image keys now include the reference, and identical rows are dropped.
2026-11-12 12:12:02 +08:00
l0ng-ai 018b12f24f feat(services): group run configurations by their folders (#2887)
Services listed a configuration type's configurations as one flat list. It now shows the type's run configuration folders (from Run/Debug Configurations) as groups before the loose configurations; a folder shows its running count, and Run All / Restart All / Stop All on it act on its configurations.
2026-11-12 11:53:17 +08:00
l0ng-ai 76b5d63c95 feat(templates): Java .var introduces a variable of the expression's type (#2886)
Java's .var postfix template always produced var name = expr;. It now runs Introduce Variable on the expression, as IDEA does by default: the statement is ended with ';', the expression selected and the language server declares the variable with its type, followed by the occurrences chooser and in-place rename. Without Introduce Variable the var template is used as before.
2026-11-12 11:52:31 +08:00
l0ng-ai 6fc6042a78 fix(plugins): link installed plugins to their marketplace homepage (#2883)
An installed plugin whose manifest has no homepage showed no link, so there was nowhere to report its bugs. Its details now fall back to the marketplace entry's homepage, which the registry fills with the plugin's source repository.
2026-11-12 11:31:02 +08:00
l0ng-ai d01dc30f4f fix(vcs): status and git operations after a case-only rename on case-insensitive disks (#2881)
With core.ignorecase (Windows, macOS), a directory renamed by case only keeps its old spelling in the index, so status reported modified files under a path the tree, tabs and editors (which use the disk's names) never matched, and the change gutter looked up HEAD:<disk spelling>, treating the whole file as added. Status now reports tracked files' paths as the disk spells them (relPath keeps the index spelling), and paths from the IDE are mapped back to the index spelling (ASCII folding, like git) before git commands and blob lookups — stage, rollback, history, annotate and the gutter included.
2026-11-12 11:29:33 +08:00
l0ng-ai b8bad81497 fix(http-client): Select All and Copy in the response pane (#2871)
Select All in a reading pane (useSelectionBoundary) selected the whole window, so Copy afterwards copied nothing useful from the HTTP Client response. Reading panes now handle primary+A and the Edit menu's Select All by selecting only their own text (editable fields keep their own); the response pane is focusable and uses the selection boundary.
2026-11-12 11:14:54 +08:00
l0ng-ai 63bb5d4976 test: fix two main failures (theme template tokens, maximized update notifications) (#2869)
The Python color tokens from the Python color page were missing from the Harbor Night template and plugins/themes.md; the maximized-notifications update tests maximized a side with no tool window, which #2830 treats as stale.
2026-11-12 10:59:01 +08:00
Alexanderтаformiat 49a2e084a8 fix(search): keep Find in Files preview matches readable over syntax colours (#2863)
The preview's match decorations had default precedence, so the syntax highlighter's Prec.high token spans nested inside them and kept their colour on the search highlight (1.14:1 contrast in Dark). Matches are now Prec.highest, as find in an editor tab already is, so they nest inside the token span and take --fg-search-match. Part of #2858.

Co-authored-by: formiat <[email protected]>
2026-11-12 10:55:00 +08:00
l0ng-ai 42a65aba23 fix(terminal): keep IME-committed spaces as ASCII spaces (#2866)
xterm reads IME commits from its hidden textarea, styled white-space: nowrap; WebKit stores a trailing space typed there as U+00A0, so a space committed by the IME (Fcitx5 on Linux) reached the shell as a non-breaking space. The helper textarea now uses white-space: pre in both the integrated and embedded terminals. Fixes #2834.
2026-11-12 10:51:57 +08:00
l0ng-ai a812a03405 feat(agents): close the agent task tab in focus, or close it and start a new task (#2862)
Close Agent Task (agents.closeTask) closes the active agent task tab, leaving other tabs alone; the task keeps running in the Agents tool window. Close and New Agent Task (agents.closeAndNewTask) then opens the New Task page unless closing was cancelled. No default shortcut. Closes #2521.
2026-11-12 10:33:49 +08:00
l0ng-ai 17204bbdca chore(bindings): regenerate after the recent-project branch doc change (#2860)
#2851 changed the doc comment on RecentProject::branch, which is part of the generated src/bindings.ts.
2026-11-12 10:29:20 +08:00
arookieofcтаa-rookie-of-C-language feef7db39d feat(keymap): export the current keymap as JSON (#2852)
Settings › Keymap's gear menu gets Export Keymap as JSON…: the selected keymap's name, the preset it is based on and every configurable action's resolved bindings, so the full mapping can be read or diffed outside the IDE. Written with the fs commands like the color scheme export; strings in the en/zh catalog. Part of #287.

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-12 10:24:35 +08:00
Gabriel Gondim c54253fba2 fix(welcome): show the live git branch on recent projects (#2851)
The welcome screen showed the branch stored when a project was last opened, so a checkout made later (in or outside the IDE) stayed stale. recent_projects now reads each project's HEAD when the list is built (linked worktrees via the .git file's gitdir; a detached HEAD shows the short commit), off the async runtime, and keeps the stored value when HEAD can't be read.

Co-authored-by: GGVidal <[email protected]>
2026-11-12 10:19:57 +08:00
Deng Liuтаdengliu ac54a064ef fix(plugins): scale Wasm fuel budget proportionally for background tasks (#2850)
A call that starts a tasks progress handle gets the background wall-clock budget (60 s, renewed on report), but its Wasm fuel stayed at the per-call foreground budget, so long background work trapped with OutOfFuel. Background calls now get fuel scaled by background/timeout, refilled when tasks.begin, task.report and task.is-cancelled return (fuel is only reloaded by compiled code across host calls); every new call is re-armed with the normal budget, and OutOfFuel reports the budget that was active.

Co-authored-by: dengliu <[email protected]>
2026-11-12 10:14:09 +08:00
l0ng-ai 04dd202fab test(plugins): match the process output test to the 16 MiB stdout limit (#2855)
The process output test still expected both streams to be cut at MAX_OUTPUT after #2838 raised it from 4 to 16 MiB while the test wrote 5 MiB. stdout within the limit now comes back whole; stderr beyond it is truncated.
2026-11-12 10:11:52 +08:00
Lucas 43b5c69ecd feat(plugins): add bounded background WebSockets (API 1.6) (#2544)
Plugins get a host-owned WebSocket resource (net.websocket-connect → websocket with id/send/drain/close; dropping it closes the transport). The connection is bound to the project it was opened for, needs the endpoint's net:<host> grant, uses WSS outside loopback with the shared rustls config, and is capped at eight per plugin. Request headers (secret placeholders expanded) go with the handshake, except the ones the handshake owns; an empty subprotocol requests none; the handshake is bounded by the call's I/O budget. Incoming frames queue in a bounded FIFO, signalled by the websocket-ready event. Checked-in components are rebuilt for API 1.6.

Co-authored-by: SorPuti <[email protected]>
2026-11-12 10:09:15 +08:00
Gabriel Gondim 597d94bb42 fix(ui): close open popups when a modal dialog opens (#2845)
Popups stack above dialogs (--z-popup > --z-dialog), so a dialog opened from a popup rendered underneath it: Delete from the Agent sessions popup's context menu left the confirmation half hidden. Opening a modal dialog now closes the open popups that would cover it, the way they close when the window loses focus; popups that stay open on deactivation and popups the dialog is rendered inside are kept. Covers every dialog opened from a popup, not just the agent task menu.

Co-authored-by: GGVidal <[email protected]>
2026-11-12 09:54:43 +08:00
l0ng-ai ffbd80e857 fix(editor): compute implementation gutter icons for the whole file (#2848)
Each pass asked the language server about at most 60 declarations in and near the viewport, so a method further down got its implemented/overriding icon only after scrolling to it and waiting for the next debounced pass. A pass now asks the viewport first, then the rest of the file in batches nearest first. Refs #2770.
2026-11-12 09:50:02 +08:00
Deng Liuтаdengliu f4ff2feefa fix(plugins): raise process stdout limit to 16 MiB and surface truncation (#2838)
process.run kept at most 4 MiB of stdout and silently dropped the rest while reporting success, so large structured output (kubectl -o json, cargo metadata) reached plugins cut off mid-document. The limit is now 16 MiB, as for file reads, and stdout beyond it fails the call with an explicit error instead of returning truncated output. stderr is still truncated without failing.

Co-authored-by: dengliu <[email protected]>
2026-11-12 09:31:52 +08:00
l0ng-ai a7af19d6b9 fix(lsp): don't start a second jdtls for module-folder queries or a new workspace layout (#2837)
Root markers skipped the path itself, so a module folder whose own folder holds the build file (what Run/Debug's classpath and launch queries pass) resolved to the enclosing root, and with per-module jdtls a query started a second instance; a directory now counts as its own ancestor. A reconfigure that switches the jdtls workspace layout restarted the instance it had just created, because its settings were compared before the start recorded them; servers created in the same pass are skipped.
2026-11-12 09:17:23 +08:00
l0ng-ai a2dd7e3939 fix(ci): ignore the Django parser terms in knip and fix two flaky tests (#2835)
knip now ignores the generated Django parser terms like the other template parsers'. The progress-replacement test started its barrier task while the released search could still be measuring indexing, so it sometimes saw Indexing; the barrier now starts after the search. The local download test passes '/'-separated remote paths, as the local file system lists them on Windows.
2026-11-12 08:58:45 +08:00
l0ng-ai 3ed5157e03 fix(agents): don't show +0 −0 for binary files in a task's changes (#2833)
git has no line counts for binary files, so a task's changes list showed +0 −0 for each binary the task produced. The list now shows only non-zero counts, as the run summaries in the same view do.
2026-11-12 08:50:07 +08:00
Deng Liuтаdengliu 68a9bf37e3 fix(workbench): clear orphaned maximized state when a tool window unregisters (#2830)
When a maximized tool window unregistered (its plugin was disabled, uninstalled or crashed), the layout kept its side maximized with nothing left to show there, which hid the editor and every other tool window and left the workbench blank; Hide Active Tool Window and Maximize did nothing. Unregistration now clears a maximized side that has no registered visible window, along with a stale focused or last-active window (focus returns to the editor), and visibility, context keys and Hide Active Tool Window ignore such a stale maximized side.

Co-authored-by: dengliu <[email protected]>
2026-11-12 08:48:02 +08:00
Deng Liuтаdengliu 96711ff85a fix(plugins): unwind host process/net timeouts as guest errors instead of trapping (#2831)
process.run, process.run-command and net.fetch were given the call's whole remaining wall-clock budget, so a subprocess or request that timed out returned to Wasm already past the deadline and the next epoch check trapped the instance. Three slow external calls then counted as three crashes and disabled the plugin. Blocking host I/O now gets the budget minus a 250 ms unwind window, and a failed I/O call near the deadline gets one 250 ms extension per call so the guest can handle the error. Pure Wasm loops still trap at the deadline.

Co-authored-by: dengliu <[email protected]>
2026-11-12 08:46:55 +08:00
l0ng-ai 29bbaf3b78 fix(problems): show the active notebook's diagnostics in the File tab (#2829)
The File tab followed only the active text editor, so with a notebook active it said no file was open; notebook diagnostics are also stored per cell document. It now follows the active tab's path for other editor kinds and collects the notebook's cell documents (percent-encoded and Windows drive paths included).
2026-11-12 07:42:57 +08:00
Gabriel Gondim b30657ec50 feat(java): Delegate IDE build/run actions to Maven (#2828)
jdtls builds launches with ECJ, which rejects some code javac accepts (for example a generic method call used as an if condition), so such a Maven project could not be run from the IDE. Settings › Build, Execution, Deployment › Maven › Delegate IDE build/run actions to Maven makes Automatic and Build (Make) launches of Maven modules compile with Maven, as Rebuild already did. Classes JDT wrote for sources with errors look up to date to Maven's incremental compiler, so a delegated launch JDT reports errors for recompiles everything and javac's result decides whether it starts. Editor diagnostics still come from jdtls. Off by default.

Co-authored-by: GGVidal <[email protected]>
2026-11-12 07:39:30 +08:00
rohitkumardandaтаrohitdanda fd5f4b8639 feat(notebook): completion, hover, diagnostics and navigation in notebook cells (#2824)
Notebook cells had no language server support. Servers that advertise notebookDocumentSync (basedpyright, Ruff) now receive the notebook through LSP 3.17 notebookDocument/didOpen, didChange and didClose, with one vscode-notebook-cell document per cell, so names defined in one cell resolve in the others. Cell editors get completion, hover, diagnostics and go to declaration; a location in another cell scrolls to and selects it in that cell, and cell diagnostics show under the notebook in Problems.

Co-authored-by: rohitdanda <[email protected]>
2026-11-12 07:28:31 +08:00
Bruno Belloni 0567bb88bf feat(database): pick up data sources edited on disk without reopening the project (#2826)
Edits to .openidea/data-sources.toml and the global data-sources.toml made outside the IDE (git pull, branch switch, a text editor) were only read when the project opened. A notify watcher on the project root, .openidea and the global data directory now reloads both files after a short settle delay, closes connections whose source changed or was removed, and emits DbSourcesChanged so the Database tool window refreshes. Saves from the IDE update the on-disk snapshot so they don't echo back as external changes.

Co-authored-by: brunobelloni <[email protected]>
2026-11-12 07:23:39 +08:00
Vadim LazukтаInf1mum a7e968e869 docs(java): note the ECJ vs javac divergence for generic calls in boolean conditions (#2825)
jdtls' bundled ECJ rejects a generic method call used directly as an if/while/for/do or ternary condition (Type mismatch: cannot convert from Object to boolean) where javac infers boolean; no ECJ release accepts it. Document the case and the workaround (assign to a boolean first) in the Java limitations, en and zh. Refs #2624.

Co-authored-by: Inf1mum <[email protected]>
2026-11-12 05:56:01 +08:00
l0ng-ai e9a464cfef test(agents): give the Claude command discovery test's waits a 10 s bound (#2823)
The test waited 2 s for its Python stub agent to start and to exit. Under a
parallel test run the interpreter's start-up alone can take longer, so the test
failed now and then. Both are polls for a condition, so a longer bound costs
nothing when it passes.
2026-11-12 05:03:21 +08:00
l0ng-ai c23696c51f test(e2e): wait for the start-up splash in the workbench fixture (#2822)
The splash covers the page and swallows raw mouse presses until it has faded
out. Only one spec waited for it, so the tool window resize test sometimes
pressed on the splash instead of the gap (3 of 15 runs locally). The workbench
fixture now waits for it to be removed.
2026-11-12 05:01:51 +08:00
l0ng-ai 3e6e9ed255 fix(markdown): redraw a Mermaid diagram's full-screen view when the diagram is redrawn (#2821)
The full-screen view kept a copy of the diagram as it was when opened, so a theme
change (or an edit) redrew the inline diagram but left the open view in the old
colours. The view now replaces its copy in place whenever its block is redrawn,
keeping the current pan and zoom; Download saves the newest drawing.
2026-11-12 04:56:46 +08:00
633 змінених файлів з 17100 додано та 1543 видалено

No files matched your search

+83
Переглянути файл
@@ -0,0 +1,83 @@
---
name: eval
description: Run the code-intelligence evals (`pnpm eval`), pick the worst failing scenario, diagnose it from the attached timeline, fix it, prove the fix with before / after numbers measured on this machine without regressing other scenarios, and open one PR. Use for "跑 eval", "优化 Java 代码智能", "eval 失败了", an issue labelled `eval`, or any change to Java navigation / usages / gutter markers that needs numbers.
---
# Eval loop: measure → fix → prove
`pnpm eval` drives the production workbench in Chromium against a release `openidea-server`
with real language servers (Java / jdtls for now) and judges every scenario on what the user
sees: time to feedback, to the first result, to the final one, and the results themselves vs
`evals/<language>/golden/`. One machine, before and after: numbers from different machines or
from the nightly host don't judge a fix.
## 0. Preconditions
- `jdtls` on PATH and `JAVA_HOME` pointing at a JDK of the pinned `JAVA` version (projects
compile against it, and the JDK scenarios' results are in its sources; jdtls itself runs on
a newer installed JDK when it needs one). Pinned versions: `.github/tool-versions.env`. A
mismatch prints a warning and the report records both: say so in the PR when it applies.
- First run builds `cargo build --release -p ide-host --bin openidea-server` and the perf
bundle; later iterations of a frontend-only change can use `--no-build` after a
`pnpm exec vite build --mode perf --outDir target/eval/dist`, a backend-only one after the
cargo build alone.
- Run evals one at a time on this machine, with nothing heavy (builds, other evals) beside them.
## 1. Baseline on the base commit
```sh
git switch --detach origin/main # or the fix branch's merge base
pnpm eval --save-baseline # target/eval/baseline.json, this machine only
```
Read `target/eval/report.json`. Each verdict has `status`, `failures` (`kind`: `error`,
`timeout`, `degraded`, `correctness`, `budget`, `golden`), `regressions`, `repro` (the command
that reruns it) and, for failures, `diagnostics`: every command sent to the server in the
slowest run's window (`cmd`, `start`, `ms`, `ok`, `bytes`, `items`), background tasks, server
status changes and the server's log tail.
## 2. Pick one problem
Worst first: wrong or missing results and silent degradation, then timeouts, then the
feedback budget (100 ms), then the slowest `completeMs`. One problem per PR. Say which
scenario and metric, with its value vs budget.
## 3. Diagnose from the timeline
- Commands in the window ordered by `start`: what ran, what waited on what, what's serial
that could overlap, which request returned many `items`/`bytes`, which failed.
- `feedbackMs` far above 16 ms with a fast `firstResultMs`: the UI shows nothing while it
waits (a hint or popup that only appears after a delay).
- A task still running across the window: background work competing with the request.
- For the frontend side rerun with `--trace` and open `target/eval/traces/<id>@<cond>.json`
in Chrome's Performance panel.
- Name the cause at class level (as in `issue-fix`): it usually affects sibling scenarios.
## 4. Fix, then rerun that scenario until it passes
```sh
pnpm eval --only <scenario> --condition <warm|cold> # the verdict's `repro`
```
Correctness is enforced, so a faster answer that drops, truncates or serves stale results
fails. Don't trade a budget miss for a degraded answer.
## 5. Full suite, then PR
```sh
pnpm eval # vs the baseline from step 1: no new failures or regressions
```
PR per `issue-fix` §6, plus in **How it was verified** the before / after table from
`target/eval/report.md` (both on this machine, commits named) and the tool versions line.
## Guard rails
- Goldens (`evals/*/golden/`) and budgets (`evals/budgets.json`) are human-owned. Don't edit
them, and don't run `--update-golden`, to make a scenario pass. When a golden looks wrong
(a tool bump, a deliberate behaviour change), stop and say so: a PR that touches them gets
`needs-decision`.
- Don't weaken a scenario's checks or timeouts in `evals/<language>/scenarios.ts` to pass.
Adding a scenario (for a case the sweep or a user found) is fine; record its golden with
`--update-golden --only <id>` and ask a person to review the file.
- A flaky timing (passes on rerun) is not a regression: rerun once before acting on one.
+1
Переглянути файл
@@ -0,0 +1 @@
../../.agents/skills/eval
+14
Переглянути файл
@@ -0,0 +1,14 @@
# Language server and tool versions for Language smoke (.github/workflows/language-smoke.yml)
# and the code-intelligence evals (pnpm eval). Pinned so a release can't fail an unrelated
# PR or move a golden result; bump them deliberately (and re-record goldens: pnpm eval --update-golden).
VTSLS=0.3.0
TYPESCRIPT=6.0.3
BASEDPYRIGHT=1.40.2
RUFF=0.17.3
GOPLS=v0.24.0
JDTLS=1.63.0-202610191322
KOTLIN_LSP=263.7084.0
GRADLE=8.14.3
INTELEPHENSE=1.18.5
# The JDK projects compile against (JAVA_HOME): library navigation opens its sources.
JAVA=21
+4 -11
Переглянути файл
@@ -24,6 +24,7 @@ on:
- "package.json"
- "pnpm-lock.yaml"
- ".github/workflows/language-smoke.yml"
- ".github/tool-versions.env"
pull_request:
branches: [main]
types: [opened, synchronize, reopened]
@@ -38,16 +39,6 @@ concurrency:
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
# Pinned so a server release can't fail an unrelated PR; bump them deliberately.
VTSLS: 0.3.0
TYPESCRIPT: 6.0.3
BASEDPYRIGHT: 1.40.2
RUFF: 0.17.3
GOPLS: v0.24.0
JDTLS: 1.63.0-202610191322
KOTLIN_LSP: 263.7084.0
GRADLE: 8.14.3
INTELEPHENSE: 1.18.5
jobs:
smoke:
@@ -61,6 +52,8 @@ jobs:
timeout-minutes: 40
steps:
- uses: actions/checkout@v4
# Tool versions, shared with the evals (pnpm eval).
- 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.
@@ -96,7 +89,7 @@ jobs:
- if: matrix.language == 'java' || matrix.language == 'kotlin'
uses: actions/setup-java@v4
with: { distribution: temurin, java-version: "21" }
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
- if: matrix.language == 'java'
run: |
mkdir -p "$RUNNER_TEMP/jdtls"
+1
Переглянути файл
@@ -40,6 +40,7 @@ CLAUDE.local.md
.claude/skills/*
!.claude/skills/verify
!.claude/skills/issue-fix
!.claude/skills/eval
# Local reference screenshots
pycharm-screenshots/
+1
Переглянути файл
@@ -9,6 +9,7 @@
"dist",
"target",
"src/bindings.ts",
"evals/*/golden",
"src/editor/core/cm/angular/parser*.ts",
"src/editor/core/cm/jsp/parser*.ts",
"src/editor/core/cm/astro/parser*.ts",
+11 -3
Переглянути файл
@@ -24,8 +24,8 @@ Visual style: dark, low-contrast greys, one cool accent
Plugin docs: `plugins/README.md`, `plugins/themes.md`.
- `java/` — JDT LS extension bundles (`java-usages`, `kotlin-bridge`) and the patched
Lombok agent, embedded into the app by `ide-sdk` / `ide-tools`.
- `e2e/` — Playwright UI tests (`pnpm e2e`). `fixtures/` — sample projects per language
for manual and automated testing.
- `e2e/` — Playwright UI tests (`pnpm e2e`). `evals/` — code-intelligence evals (`pnpm eval`).
`fixtures/` — sample projects per language for manual and automated testing.
- `docs/` — the Mintlify documentation site (`docs.json` navigation, `en/` and `zh/` pages);
preview with `npx mint dev` in `docs/`.
@@ -59,9 +59,12 @@ Unclear product decisions → `needs-decision` and stop.
## Skills
Do not use Impeccable or its related skills in this repository, including globally installed copies.
Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
`verify` drives the running app through Tauri MCP and captures screenshot evidence;
`issue-fix` takes an issue from reproduction to one PR.
`issue-fix` takes an issue from reproduction to one PR;
`eval` takes a failing code-intelligence eval to a fix with before / after numbers.
## Commands
@@ -81,6 +84,11 @@ Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
`pnpm gen:bindings`.
- `pnpm perf` (UI interaction latency / frames / leaks), `pnpm perf:rust` (criterion
benches vs budgets). Budgets: `perf/budgets.json`.
- `pnpm eval [--only <id>] [--runs n] [--save-baseline]` — Java code intelligence (navigation,
usages, gutter markers) in the production workbench against a release `openidea-server` and
jdtls: time to feedback / first result / complete, results vs `evals/<language>/golden/`.
Report: `target/eval/report.json`. Goldens and `evals/budgets.json` are changed by people only.
Tool versions: `.github/tool-versions.env` (shared with Language smoke).
- `pnpm release:prepare <version>` — the release commit's changes: app version everywhere,
`Cargo.lock`, and the plugin API snapshot when `wit/` moved to a new version.
Створено
+66 -47
Переглянути файл
@@ -2637,7 +2637,6 @@ version = "1.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "337d46834ee672ab3e48caca2cb0c78cc174fb12b3a68d0d88f99a0519a5e36e"
dependencies = [
"generic-array 0.14.7",
"rustversion",
"typenum",
]
@@ -4145,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"dunce",
"encoding_rs",
@@ -4169,7 +4168,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4183,7 +4182,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"ide-core",
"serde",
@@ -4194,7 +4193,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"blake3",
"chardetng",
@@ -4212,7 +4211,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4226,7 +4225,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4236,7 +4235,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"dunce",
"encoding_rs",
@@ -4253,7 +4252,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"ide-core",
"ide-run",
@@ -4267,7 +4266,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"futures",
"ide-core",
@@ -4293,7 +4292,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"bb8",
"blake3",
@@ -4303,6 +4302,7 @@ dependencies = [
"ide-core",
"ide-http",
"ide-ssh",
"notify",
"oracledb",
"parking_lot",
"reqwest",
@@ -4323,7 +4323,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"ide-core",
"serde",
@@ -4336,7 +4336,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4357,7 +4357,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4369,7 +4369,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4382,7 +4382,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"criterion",
"ide-core",
@@ -4400,7 +4400,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4443,6 +4443,7 @@ dependencies = [
"ide-tools",
"ide-vcs",
"ide-vfs",
"ide-web",
"ide-workspace",
"ignore",
"jsonschema",
@@ -4459,6 +4460,7 @@ dependencies = [
"specta-typescript",
"tempfile",
"tokio",
"tokio-tungstenite",
"toml 0.9.12+spec-1.1.0",
"tracing",
"tracing-subscriber",
@@ -4469,7 +4471,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"ide-core",
"ide-vfs",
@@ -4488,7 +4490,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"blake3",
"criterion",
@@ -4510,7 +4512,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4522,7 +4524,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"encoding_rs",
"futures",
@@ -4539,7 +4541,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"libc",
"tempfile",
@@ -4548,7 +4550,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"futures",
"serde",
@@ -4559,7 +4561,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"blake3",
"criterion",
@@ -4600,6 +4602,7 @@ dependencies = [
"tree-sitter-nix",
"tree-sitter-ocaml",
"tree-sitter-php",
"tree-sitter-prisma-io",
"tree-sitter-proto",
"tree-sitter-python",
"tree-sitter-ruby",
@@ -4615,7 +4618,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"dunce",
"encoding_rs",
@@ -4643,7 +4646,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"bytes",
"dunce",
@@ -4662,7 +4665,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"futures",
"ide-core",
@@ -4685,7 +4688,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"blake3",
"dunce",
@@ -4708,7 +4711,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4722,9 +4725,10 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"dunce",
"futures",
"globset",
"ide-core",
"ide-run",
@@ -4741,7 +4745,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"dunce",
"encoding_rs",
@@ -4765,7 +4769,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"ide-core",
"ide-tools",
@@ -4781,7 +4785,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"dunce",
"ide-core",
@@ -4802,7 +4806,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"criterion",
"encoding_rs",
@@ -4823,7 +4827,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"ide-core",
"parking_lot",
@@ -4836,7 +4840,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4861,7 +4865,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"ide-core",
"ide-language",
@@ -4876,7 +4880,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"ide-core",
"libc",
@@ -4889,7 +4893,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"criterion",
"ide-core",
@@ -4902,7 +4906,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"flate2",
"hex",
@@ -4923,7 +4927,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"blake3",
"dunce",
@@ -4944,7 +4948,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"chardetng",
"dunce",
@@ -4968,7 +4972,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -4984,7 +4988,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"blake3",
"dunce",
@@ -6585,7 +6589,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.42"
version = "0.1.43"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -7710,9 +7714,9 @@ dependencies = [
[[package]]
name = "russh"
version = "0.64.1"
version = "0.65.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba61e87b9ec9a39a59a6bbed4c0b8ff7fb07073405b24a767a1f2c8560ac8f58"
checksum = "94be3d86c71b9ed220a675c405e35c7a02565a009bf8da2e9cc13a700320a5c5"
dependencies = [
"aes",
"bitflags 2.13.2",
@@ -9867,7 +9871,10 @@ checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857"
dependencies = [
"futures-util",
"log",
"rustls",
"rustls-pki-types",
"tokio",
"tokio-rustls",
"tungstenite",
]
@@ -10433,6 +10440,16 @@ dependencies = [
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-prisma-io"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c35912d65a6adb07f781db46d843bf0464935e267da6ed192705516adafc7c24"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-proto"
version = "0.6.0"
@@ -10561,6 +10578,8 @@ dependencies = [
"httparse",
"log",
"rand 0.9.5",
"rustls",
"rustls-pki-types",
"sha1 0.10.7",
"thiserror 2.0.21",
"utf-8",
+2 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.42"
version = "0.1.43"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
@@ -68,6 +68,7 @@ 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"
+33 -9
Переглянути файл
@@ -1343,6 +1343,15 @@ impl AgentManager {
blocking(move || at.changes(&before)).await
}
/// The task's uncommitted changes and, for a worktree task, the commits made since it
/// started (newest first). Both are read against the same `HEAD`.
pub async fn grouped_changes(&self, id: &str) -> IdeResult<AgentChanges> {
let task = self.task(id)?;
let at = task.base();
let before = task.state.lock().before.clone();
blocking(move || at.grouped_changes(&before)).await
}
/// Content of `path` (in the task's directory) when the task started.
pub async fn base_text(&self, id: &str, path: PathBuf) -> IdeResult<Option<String>> {
let at = self.task(id)?.base();
@@ -1353,9 +1362,14 @@ impl AgentManager {
.await
}
/// Rollback: puts the task's changed files among `rel_paths` (all with `None`) back as they
/// were when it started (files the user had changed then, as the user left them).
pub async fn rollback_changes(&self, id: &str, rel_paths: Option<Vec<String>>) -> IdeResult<()> {
/// Rollback: puts the task's changed files among `rel_paths` (all with `None`) back as
/// `view` compares them: as they were when it started, or as they are in `HEAD`.
pub async fn rollback_changes(
&self,
id: &str,
rel_paths: Option<Vec<String>>,
view: AgentChangesView,
) -> IdeResult<()> {
let task = self.task(id)?;
if task.state.lock().busy {
return Err(IdeError::invalid("the agent is working: stop it before rolling back its changes"));
@@ -1366,14 +1380,24 @@ impl AgentManager {
(s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)))
};
let restamped = blocking(move || {
let changes = at.changes(&before)?;
let rev = at.rev()?;
let (changes, rev) = match view {
AgentChangesView::Group => (at.grouped_changes(&before)?.uncommitted, worktree::head_commit(at.cwd())?),
AgentChangesView::SinceStart => (at.changes(&before)?, at.rev()?),
};
let sources = match rev.as_deref() {
Some(rev) => worktree::rename_sources(at.cwd(), rev)?,
None => Default::default(),
};
let mut restamped = Vec::new();
for change in changes.iter().filter(|c| rel_paths.as_ref().is_none_or(|p| p.contains(&c.rel_path))) {
worktree::restore(at.cwd(), rev.as_deref(), change, &before, saved.as_deref())?;
// Back to the user's own edits: not a change of the task any more.
if before.contains_key(&change.rel_path) {
restamped.push((change.rel_path.clone(), worktree::stamp(&change.path.0)));
// A rename goes back to its old path too; the new one is taken away first, so a
// case-only rename on a case-insensitive disk ends as the old file.
for change in std::iter::once(change).chain(sources.get(&change.rel_path)) {
worktree::restore(at.cwd(), rev.as_deref(), change, &before, saved.as_deref())?;
// Back to the user's own edits: not a change of the task any more.
if before.contains_key(&change.rel_path) {
restamped.push((change.rel_path.clone(), worktree::stamp(&change.path.0)));
}
}
}
Ok(restamped)
+40 -1
Переглянути файл
@@ -484,7 +484,8 @@ pub struct NewAgentTask {
pub base: Option<String>,
}
/// A file the task changed, relative to [`AgentTask::base_commit`].
/// A file the task changed: against [`AgentTask::base_commit`], or against `HEAD` in the
/// grouped view.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentChange {
@@ -493,6 +494,44 @@ pub struct AgentChange {
pub kind: ide_vcs::ChangeKind,
pub added: u32,
pub removed: u32,
/// Path before a rename; the left side of its diff reads this path.
pub old_path: Option<String>,
}
/// A commit made while the task ran, with the files it changed against its first parent.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentCommit {
pub id: String,
pub short_id: String,
pub summary: String,
pub message: String,
pub time_ms: f64,
/// First parent, or `None` for a root commit.
pub parent: Option<String>,
pub files: Vec<AgentChange>,
}
/// Which comparison a rollback of the task's changes uses.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentChangesView {
/// Everything since the commit the task started from.
#[default]
SinceStart,
/// The uncommitted files against `HEAD`; commits made since the start stay.
Group,
}
/// A task's uncommitted files and the commits made since it started.
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentChanges {
/// Files changed against `HEAD`, less those changed before the task started and untouched since.
pub uncommitted: Vec<AgentChange>,
/// Commits from the task's start (exclusive) to `HEAD` (inclusive), newest first. Empty
/// for tasks working in the project's own checkout.
pub commits: Vec<AgentCommit>,
}
/// Streamed to the window that subscribed (`AgentManager::subscribe`).
+57 -9
Переглянути файл
@@ -492,7 +492,7 @@ for line in sys.stdin:
}
let concurrent = async {
if outcome == "session_report" {
tokio::time::timeout(Duration::from_secs(2), async {
tokio::time::timeout(Duration::from_secs(10), async {
while !root.join("initialized").exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
@@ -564,7 +564,7 @@ for line in sys.stdin:
};
assert_eq!(subtypes, expected, "{outcome}");
let pid = std::fs::read_to_string(root.join("pid")).unwrap();
tokio::time::timeout(Duration::from_secs(2), async {
tokio::time::timeout(Duration::from_secs(10), async {
while std::process::Command::new("kill").args(["-0", pid.trim()]).output().unwrap().status.success() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
@@ -2853,14 +2853,14 @@ async fn rolling_back_restores_the_start_of_the_task_and_keeps_the_users_own_edi
}
assert_eq!(changed(&mgr, &task.id).await, ["mine.txt", "new.txt", "other.txt"]);
mgr.rollback_changes(&task.id, Some(vec!["other.txt".into()])).await.unwrap();
mgr.rollback_changes(&task.id, Some(vec!["other.txt".into()]), AgentChangesView::SinceStart).await.unwrap();
assert_eq!(read("other.txt"), "base\n");
assert_eq!(changed(&mgr, &task.id).await, ["mine.txt", "new.txt"]);
// After a restart, from the saved copy.
mgr.shutdown();
let mgr = manager(&dir, Arc::new(FakeAgent::default()));
mgr.rollback_changes(&task.id, None).await.unwrap();
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
assert_eq!(read("mine.txt"), "my edit\n", "the user's edit stays");
assert!(!dir.join("new.txt").exists());
assert!(changed(&mgr, &task.id).await.is_empty());
@@ -2973,7 +2973,7 @@ async fn work_uncommitted_by_a_reset_during_a_local_task_is_not_rolled_back() {
let base = mgr.base_text(&task.id, repo.dir.join("a.txt")).await.unwrap();
assert_eq!(base.map(|b| b.replace("\r\n", "\n")).as_deref(), Some("base\n"), "{eol:?}");
mgr.rollback_changes(&task.id, None).await.unwrap();
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
assert_eq!(repo.read("a.txt"), "base\n", "{eol:?}");
assert_eq!(repo.read("mine.txt"), "my work\n", "{eol:?}: the user's work survives the rollback");
assert!(changed(&mgr, &task.id).await.is_empty(), "{eol:?}");
@@ -2996,7 +2996,7 @@ async fn files_a_mixed_reset_during_a_local_task_leaves_behind_are_not_rolled_ba
repo.git(&["reset", "-q", "HEAD~1"]);
assert_eq!(changed(&mgr, &task.id).await, ["a.txt"], "{eol:?}");
mgr.rollback_changes(&task.id, None).await.unwrap();
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
assert_eq!(repo.read("a.txt"), "base\n", "{eol:?}");
assert_eq!(repo.read("mine.txt"), "my work\n", "{eol:?}");
assert_eq!(repo.read("mine-new.txt"), "my new file\n", "{eol:?}");
@@ -3023,7 +3023,7 @@ async fn a_branch_switched_to_during_a_local_task_is_left_alone() {
repo.git(&["checkout", "-q", "feature"]);
assert_eq!(changed(&mgr, &task.id).await, ["a.txt"], "{eol:?}");
mgr.rollback_changes(&task.id, None).await.unwrap();
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
assert_eq!(repo.read("a.txt"), "base\n", "{eol:?}");
assert_eq!(repo.read("other.txt"), "feature\n", "{eol:?}");
assert_eq!(repo.read("only-feature.txt"), "feature\n", "{eol:?}");
@@ -3048,13 +3048,61 @@ async fn commits_made_during_a_local_task_are_kept_by_its_rollback() {
repo.write("a.txt", "agent\nagain\n");
assert_eq!(changed(&mgr, &task.id).await, ["a.txt", "b.txt"], "{eol:?}");
mgr.rollback_changes(&task.id, None).await.unwrap();
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
assert_eq!(repo.read("a.txt"), "agent\n", "{eol:?}: back to the commit, not to before it");
assert!(!repo.dir.join("b.txt").exists(), "{eol:?}");
assert!(changed(&mgr, &task.id).await.is_empty(), "{eol:?}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn rolling_back_a_rename_brings_the_old_file_back() {
for eol in EOLS {
let repo = Checkout::new(eol);
repo.write("Old.java", "class Old {}\n");
repo.write("Case.java", "class Case {}\n");
repo.commit("init");
let (mgr, task) = repo.task().await;
repo.git(&["mv", "Old.java", "New.java"]);
repo.git(&["mv", "Case.java", "CASE.java"]);
// Renames list their new path only.
let listed = changed(&mgr, &task.id).await;
assert_eq!(listed, ["CASE.java", "New.java"], "{eol:?}");
mgr.rollback_changes(&task.id, Some(listed), AgentChangesView::SinceStart).await.unwrap();
assert_eq!(repo.read("Old.java"), "class Old {}\n", "{eol:?}");
assert!(!repo.dir.join("New.java").exists(), "{eol:?}");
assert_eq!(repo.read("Case.java"), "class Case {}\n", "{eol:?}");
let names: Vec<String> = std::fs::read_dir(&repo.dir)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.filter(|n| n.ends_with(".java"))
.collect();
assert!(!names.contains(&"CASE.java".to_owned()), "{eol:?}: {names:?}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn the_group_view_rolls_back_only_uncommitted_files() {
for eol in EOLS {
let repo = Checkout::new(eol);
repo.write("a.txt", "base\n");
repo.commit("init");
let (mgr, task) = repo.task().await;
repo.write("a.txt", "agent\n");
repo.commit("agent work");
repo.write("a.txt", "agent\nagain\n");
let grouped = mgr.grouped_changes(&task.id).await.unwrap();
assert_eq!(grouped.uncommitted.iter().map(|c| c.rel_path.as_str()).collect::<Vec<_>>(), ["a.txt"], "{eol:?}");
assert!(grouped.commits.is_empty(), "{eol:?}: local tasks have no commits to group");
mgr.rollback_changes(&task.id, None, AgentChangesView::Group).await.unwrap();
assert_eq!(repo.read("a.txt"), "agent\n", "{eol:?}: back to the commit, not to the start");
assert!(mgr.grouped_changes(&task.id).await.unwrap().uncommitted.is_empty(), "{eol:?}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_local_task_in_a_repository_without_commits_lists_and_rolls_back_its_changes() {
for eol in EOLS {
@@ -3065,7 +3113,7 @@ async fn a_local_task_in_a_repository_without_commits_lists_and_rolls_back_its_c
assert_eq!(changed(&mgr, &task.id).await, ["new.txt"], "{eol:?}");
assert_eq!(mgr.base_text(&task.id, repo.dir.join("new.txt")).await.unwrap(), None, "{eol:?}");
mgr.rollback_changes(&task.id, None).await.unwrap();
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
assert!(!repo.dir.join("new.txt").exists(), "{eol:?}");
assert_eq!(repo.read("mine.txt"), "mine\n", "{eol:?}");
assert!(changed(&mgr, &task.id).await.is_empty(), "{eol:?}");
+321 -28
Переглянути файл
@@ -1,8 +1,8 @@
//! Task worktrees and the changes made in them.
use crate::model::AgentChange;
use crate::model::{AgentChange, AgentChanges, AgentCommit};
use ide_core::{IdeError, IdeResult, IpcPath};
use ide_vcs::{ChangeKind, Repo};
use ide_vcs::{ChangeKind, LogQuery, Repo};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::{Duration, UNIX_EPOCH};
@@ -35,6 +35,14 @@ pub(crate) fn head_of(path: &Path) -> IdeResult<(String, String)> {
Ok((info.head.unwrap_or_else(|| commit.clone()), commit))
}
/// `HEAD`'s commit in `cwd`, `None` outside a repository or before its first commit.
pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
match discover(cwd)? {
Some(repo) => Ok(repo.head()?.1),
None => Ok(None),
}
}
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, base: Option<&str>) -> IdeResult<Created> {
let repo = repo_at(project_root)?;
@@ -111,7 +119,14 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
.into_iter()
.map(|f| {
let (added, removed) = stat(&f.path);
AgentChange { path: IpcPath(root.join(&f.path)), rel_path: f.path, kind: f.kind, added, removed }
AgentChange {
path: IpcPath(root.join(&f.path)),
rel_path: f.path,
kind: f.kind,
added,
removed,
old_path: f.old_path,
}
})
.collect();
let tracked: std::collections::HashSet<String> = out.iter().map(|c| c.rel_path.clone()).collect();
@@ -124,9 +139,90 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
Ok(out)
}
/// Files renamed since `rev`, by their new repository-relative path: the old path, as a deletion
/// to roll back along with the rename.
pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String, AgentChange>> {
let Some(repo) = discover(cwd)? else { return Ok(BTreeMap::new()) };
let root = repo.root().to_path_buf();
Ok(repo
.diff_with_worktree(rev)?
.into_iter()
.filter_map(|f| {
let old = f.old_path.filter(|old| *old != f.path)?;
let source = AgentChange {
path: IpcPath(root.join(&old)),
rel_path: old,
kind: ChangeKind::Deleted,
added: 0,
removed: 0,
old_path: None,
};
Some((f.path, source))
})
.collect())
}
fn added(path: IpcPath, rel_path: String) -> AgentChange {
let added = std::fs::read_to_string(&*path).map_or(0, |t| t.lines().count() as u32);
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0 }
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0, old_path: None }
}
/// The commits from `base` (exclusive) to `head` (inclusive) in `cwd`, newest first, each
/// with the files it changed against its first parent and their line counts.
pub(crate) fn commits(cwd: &Path, base: &str, head: &str) -> IdeResult<Vec<AgentCommit>> {
if base == head {
return Ok(Vec::new());
}
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
let root = repo.root().to_path_buf();
let query = LogQuery { range: Some(format!("{base}..{head}")), ..LogQuery::default() };
let mut out = Vec::new();
for commit in repo.log(&query)? {
let parent = commit.parents.first().cloned();
// A root commit has no parent to count lines against; its files still show.
let stats: std::collections::HashMap<String, (u32, u32)> = match &parent {
Some(parent) => repo
.diff_numstat(parent, &commit.id, &[])?
.into_iter()
.map(|s| (s.path, (s.added, s.removed)))
.collect(),
None => std::collections::HashMap::new(),
};
let mut files: Vec<AgentChange> = repo
.commit_files(&commit.id)?
.into_iter()
.map(|f| {
let (added, removed) = stats.get(&f.path).copied().unwrap_or((0, 0));
AgentChange {
path: IpcPath(root.join(&f.path)),
rel_path: f.path,
kind: f.kind,
added,
removed,
old_path: f.old_path,
}
})
.collect();
files.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
out.push(AgentCommit {
id: commit.id,
short_id: commit.short_id,
summary: commit.summary,
message: commit.message,
time_ms: commit.time_ms,
parent,
files,
});
}
Ok(out)
}
/// Whether two paths name one file (a case-insensitive disk resolving both spellings).
fn same_file(a: &Path, b: &Path) -> bool {
match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
(Ok(a), Ok(b)) => a == b,
_ => false,
}
}
fn crlf_to_lf(bytes: &[u8]) -> Vec<u8> {
@@ -213,6 +309,34 @@ impl TaskBase {
.collect())
}
/// The task's uncommitted changes and, for a worktree task, the commits made since it
/// started (newest first). Both read the same `HEAD`, so a commit landing between the two
/// reads cannot put a file in both lists.
pub(crate) fn grouped_changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<AgentChanges> {
let cwd = self.cwd();
let Some(repo) = discover(cwd)? else { return Ok(AgentChanges::default()) };
let head = repo.head()?.1;
let uncommitted = match &head {
Some(head) => without_untouched(changes(cwd, head)?, before),
None => {
// No commits yet: every file is new, as in `changes` for a local task.
let mut all: Vec<AgentChange> = repo
.status()?
.into_iter()
.filter(|s| s.path.is_file())
.map(|s| added(s.path, s.rel_path))
.collect();
all.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
without_untouched(all, before)
}
};
let commits = match (self, &head) {
(Self::Worktree { cwd, base }, Some(head)) => commits(cwd, base, head)?,
_ => Vec::new(),
};
Ok(AgentChanges { uncommitted, commits })
}
/// The revision the task's changed files go back to on rollback, and are compared with:
/// the commit the task started from, or the current `HEAD` once the user committed on top
/// of it, so those commits stay. `None` while the repository has no commits.
@@ -245,34 +369,70 @@ pub(crate) fn accept(
changes: &[AgentChange],
) -> IdeResult<crate::AgentAcceptOutcome> {
let repo = repo_at(cwd)?;
let mut accepted = Vec::with_capacity(changes.len());
let mut skipped = Vec::new();
for change in changes {
let local = root.join(&change.rel_path);
let base_bytes = repo.file_bytes_at(&change.path.0, Some(base))?;
let current = std::fs::read(&change.path.0).ok();
// Change paths are repository-relative, and the task's project may be a folder inside it.
let local_root = discover(root)?.map_or_else(|| root.to_path_buf(), |r| r.root().to_path_buf());
let renamed_from: BTreeMap<String, String> =
repo.diff_with_worktree(base)?.into_iter().filter_map(|f| Some((f.path, f.old_path?))).collect();
// Brings one path of the checkout to the task's version, unless the checkout changed it itself.
let apply = |rel: &str| -> IdeResult<bool> {
let local = local_root.join(rel);
let in_task = repo.root().join(rel);
let base_bytes = repo.file_bytes_at(&in_task, Some(base))?;
let current = std::fs::read(&in_task).ok();
let local_bytes = std::fs::read(&local).ok();
if local_bytes == current {
accepted.push(change.rel_path.clone());
} else if local_bytes == base_bytes {
match current {
Some(bytes) => {
if let Some(parent) = local.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&local, bytes)?;
return Ok(true);
}
// The checkout may hold the committed LF text with CRLF line ends (`core.autocrlf`).
let unchanged = match (&local_bytes, &base_bytes) {
(Some(now), Some(at_base)) => now == at_base || crlf_to_lf(now) == *at_base,
(now, at_base) => now == at_base,
};
if !unchanged {
return Ok(false);
}
match current {
Some(bytes) => {
if let Some(parent) = local.parent() {
std::fs::create_dir_all(parent)?;
}
None => match std::fs::remove_file(&local) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()),
_ => {}
},
std::fs::write(&local, bytes)?;
}
accepted.push(change.rel_path.clone());
} else {
skipped.push(crate::AgentAcceptSkipped {
path: change.rel_path.clone(),
reason: "the checkout has changes of its own to it; accept it by hand".to_owned(),
});
None => match std::fs::remove_file(&local) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()),
_ => {}
},
}
Ok(true)
};
let mut accepted = Vec::with_capacity(changes.len());
let mut skipped = Vec::new();
let skip = |path: &str| crate::AgentAcceptSkipped {
path: path.to_owned(),
reason: "the checkout has changes of its own to it; accept it by hand".to_owned(),
};
for change in changes {
// A case-only rename on a case-insensitive disk: both names reach the same file, so
// rename it in place before bringing it to the task's version.
if let Some(old) = renamed_from.get(&change.rel_path)
&& old != &change.rel_path
&& old.to_lowercase() == change.rel_path.to_lowercase()
&& local_root.join(old).exists()
&& same_file(&local_root.join(old), &local_root.join(&change.rel_path))
{
std::fs::rename(local_root.join(old), local_root.join(&change.rel_path))?;
}
if !apply(&change.rel_path)? {
skipped.push(skip(&change.rel_path));
continue;
}
accepted.push(change.rel_path.clone());
// A rename also takes the file away from its old path (unless only its case changed).
if let Some(old) = renamed_from.get(&change.rel_path)
&& old.to_lowercase() != change.rel_path.to_lowercase()
&& !apply(old)?
{
skipped.push(skip(old));
}
}
Ok(crate::AgentAcceptOutcome { accepted, skipped })
@@ -532,6 +692,88 @@ mod tests {
assert!(!created.path.exists());
}
#[test]
fn commits_since_the_base_are_listed_with_their_files() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
let created = create(&repo, &tmp.path().join("wt"), "Edit A", None).unwrap();
assert!(commits(&created.path, &created.base_commit, &created.base_commit).unwrap().is_empty());
std::fs::write(created.path.join("a.txt"), "one\ntwo\n").unwrap();
git(&created.path, &["add", "."]);
git(&created.path, &["commit", "-q", "-m", "change a"]);
std::fs::write(created.path.join("b.txt"), "b\n").unwrap();
git(&created.path, &["add", "."]);
git(&created.path, &["commit", "-q", "-m", "add b"]);
let head = head_of(&created.path).unwrap().1;
let log = commits(&created.path, &created.base_commit, &head).unwrap();
assert_eq!(log.iter().map(|c| c.summary.as_str()).collect::<Vec<_>>(), ["add b", "change a"]);
assert_eq!(log[0].files.iter().map(|f| f.rel_path.as_str()).collect::<Vec<_>>(), ["b.txt"]);
assert_eq!((log[0].files[0].added, log[0].files[0].removed), (1, 0));
assert_eq!(log[1].files.iter().map(|f| f.rel_path.as_str()).collect::<Vec<_>>(), ["a.txt"]);
assert_eq!((log[1].files[0].added, log[1].files[0].removed), (1, 0));
assert!(log.iter().all(|c| c.parent.is_some() && !c.message.is_empty()));
// Nothing is uncommitted after the commits; editing a committed file brings it back.
let at = TaskBase::Worktree { cwd: created.path.clone(), base: created.base_commit.clone() };
let grouped = at.grouped_changes(&BTreeMap::new()).unwrap();
assert!(grouped.uncommitted.is_empty());
assert_eq!(grouped.commits.len(), 2);
std::fs::write(created.path.join("a.txt"), "one\ntwo\nthree\n").unwrap();
let grouped = at.grouped_changes(&BTreeMap::new()).unwrap();
assert_eq!(grouped.uncommitted.iter().map(|c| c.rel_path.as_str()).collect::<Vec<_>>(), ["a.txt"]);
assert_eq!(grouped.commits.len(), 2);
}
#[test]
fn a_rename_in_a_commit_keeps_its_old_path() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("a.txt"), "one\ntwo\nthree\nfour\nfive\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
let base = head_of(&repo).unwrap().1;
std::fs::rename(repo.join("a.txt"), repo.join("b.txt")).unwrap();
std::fs::write(repo.join("b.txt"), "one\ntwo\nthree\nfour\nFIVE\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "rename a"]);
let head = head_of(&repo).unwrap().1;
let log = commits(&repo, &base, &head).unwrap();
assert_eq!(log.len(), 1);
assert_eq!(log[0].files.len(), 1);
assert_eq!(log[0].files[0].rel_path, "b.txt");
assert_eq!(log[0].files[0].old_path.as_deref(), Some("a.txt"));
assert_eq!(log[0].files[0].kind, ChangeKind::Renamed);
}
#[test]
fn a_local_task_has_no_commits() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
std::fs::write(repo.join("a.txt"), "one\ntwo\n").unwrap();
let at = TaskBase::Local { cwd: repo.clone(), start: None };
let grouped = at.grouped_changes(&BTreeMap::new()).unwrap();
assert!(grouped.commits.is_empty());
assert_eq!(grouped.uncommitted.iter().map(|c| c.rel_path.as_str()).collect::<Vec<_>>(), ["a.txt"]);
}
#[test]
fn a_broken_worktree_registration_still_leaves_a_deletable_folder() {
let tmp = tempfile::tempdir().unwrap();
@@ -580,6 +822,57 @@ mod tests {
without_untouched(changes(cwd, base).unwrap(), &BTreeMap::new())
}
#[test]
fn accept_moves_a_renamed_file_and_maps_paths_from_a_project_folder() {
let (_tmp, repo, created) = accept_repo();
std::fs::create_dir(created.path.join("app")).unwrap();
git(&created.path, &["mv", "a.txt", "app/moved.txt"]);
std::fs::write(created.path.join("app/new.txt"), "n\n").unwrap();
git(&created.path, &["add", "."]);
git(&created.path, &["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "move"]);
// The task's project is the repository's `app` folder.
let project = repo.join("app");
std::fs::create_dir(&project).unwrap();
let changes = listed(&created.path, &created.base_commit);
let outcome = accept(&project, &created.path, &created.base_commit, &changes).unwrap();
assert!(outcome.skipped.is_empty(), "{:?}", outcome.skipped);
assert_eq!(std::fs::read_to_string(repo.join("app/moved.txt")).unwrap(), "one\ntwo\n");
assert_eq!(std::fs::read_to_string(repo.join("app/new.txt")).unwrap(), "n\n");
assert!(!repo.join("a.txt").exists(), "the rename's old path is gone");
assert!(!repo.join("app/app").exists());
}
#[test]
fn accept_treats_a_crlf_checkout_of_the_base_as_unchanged() {
let (_tmp, repo, created) = accept_repo();
// The checkout holds the committed text with CRLF line ends, as core.autocrlf leaves it.
std::fs::write(repo.join("a.txt"), "one\r\ntwo\r\n").unwrap();
std::fs::write(created.path.join("a.txt"), "one\nTWO\n").unwrap();
git(&created.path, &["mv", "gone.txt", "kept.txt"]);
std::fs::write(repo.join("gone.txt"), "bye\r\n").unwrap();
let changes = listed(&created.path, &created.base_commit);
let outcome = accept(&repo, &created.path, &created.base_commit, &changes).unwrap();
assert!(outcome.skipped.is_empty(), "{:?}", outcome.skipped);
assert_eq!(std::fs::read_to_string(repo.join("a.txt")).unwrap(), "one\nTWO\n");
assert!(repo.join("kept.txt").exists() && !repo.join("gone.txt").exists());
}
#[test]
fn accept_applies_a_case_only_rename() {
let (_tmp, repo, created) = accept_repo();
git(&created.path, &["mv", "a.txt", "A.txt"]);
let changes = listed(&created.path, &created.base_commit);
let outcome = accept(&repo, &created.path, &created.base_commit, &changes).unwrap();
assert!(outcome.skipped.is_empty(), "{:?}", outcome.skipped);
let names: Vec<_> = std::fs::read_dir(&repo)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.filter(|n| n.eq_ignore_ascii_case("a.txt"))
.collect();
assert_eq!(names, ["A.txt"]);
}
#[test]
fn accept_copies_new_modified_and_deleted_files_into_the_checkout() {
let (_tmp, repo, created) = accept_repo();
+1 -1
Переглянути файл
@@ -204,7 +204,7 @@ pub fn parse_settings(text: &str) -> Settings {
}
/// `a/b/../c` → `a/c`, without touching the filesystem.
fn normalize(p: &Path) -> PathBuf {
pub(crate) fn normalize(p: &Path) -> PathBuf {
let mut out = PathBuf::new();
for c in p.components() {
match c {
+8
Переглянути файл
@@ -122,6 +122,14 @@ pub fn gradle_external_roots(
gradle::external_roots(root, dirs.iter().map(String::as_str))
}
/// Directories of Maven POMs linked from outside `root`, outermost only.
/// Reads just those explicit paths (no POM parse and no directory walk).
pub fn maven_external_roots(root: &Path, linked: &[String]) -> Vec<PathBuf> {
let dirs = maven::external_pom_dirs(root, linked);
let owned: Vec<String> = dirs.iter().map(|dir| dir.to_string_lossy().into_owned()).collect();
gradle::external_roots(root, owned.iter().map(String::as_str))
}
/// Source, resource and build folders of the last Gradle sync, absolute.
pub fn gradle_source_roots(
root: &Path,
+337 -31
Переглянути файл
@@ -106,7 +106,9 @@ pub struct MavenProject {
pub profiles: Vec<String>,
/// Java feature version the project compiles for (`maven.compiler.release`, `java.version`…).
pub java_version: Option<u32>,
/// Maven launcher: the nearest `mvnw` up to the project root (absolute), else `mvn`.
/// Maven launcher: the nearest `mvnw` (absolute), else `mvn`. Inside the opened
/// project the search stops at its root; outside it, the search stops before
/// that root so a linked project keeps its own wrapper.
pub command: String,
/// Options before the goals (`-s`, `-Dmaven.repo.local=`); filled in by the shell from settings.
pub options: Vec<String>,
@@ -1032,10 +1034,6 @@ pub(crate) fn plugin(
const MAX_PROJECTS: usize = 1000;
fn rel_path(root: &Path, p: &Path) -> String {
p.strip_prefix(root).unwrap_or(p).to_string_lossy().replace('\\', "/")
}
/// The POMs that are not modules of another one: the root `pom.xml`, else the
/// shallowest `pom.xml` of each branch (a folder holding several builds). An
/// aggregate POM directly inside `src/` counts too (issue #1001: `src/pom.xml`
@@ -1049,18 +1047,29 @@ pub fn is_maven_project(root: &Path) -> bool {
!top_level_poms(root).is_empty()
}
/// The `mvnw` nearest to `dir`, looking up to `root`.
/// The `mvnw` nearest to `dir`. Inside `root` the walk stops at `root`. Outside it,
/// the walk stops before entering `root` or any ancestor of `root`: a sibling project
/// keeps its own wrapper, and the search does not continue to the filesystem root.
fn wrapper(root: &Path, dir: &Path) -> String {
let name = if cfg!(windows) { "mvnw.cmd" } else { "mvnw" };
let mut cur = Some(dir);
let root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
let dir = dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
let external = !dir.starts_with(&root);
let mut cur = Some(dir.as_path());
while let Some(d) = cur {
if d.join(name).is_file() {
return d.join(name).to_string_lossy().into_owned();
}
if d == root {
if !external && d == root {
break;
}
cur = d.parent();
let Some(parent) = d.parent() else { break };
// `parent` inside the opened project, or an ancestor of it (the common parent,
// then the filesystem root). Stop before inspecting those.
if external && (parent.starts_with(&root) || root.starts_with(parent)) {
break;
}
cur = Some(parent);
}
if cfg!(windows) { "mvn.cmd".into() } else { "mvn".into() }
}
@@ -1104,24 +1113,118 @@ pub(crate) fn load_with(root: &Path, local_repo: Option<PathBuf>, profiles: &[St
load_with_linked(root, local_repo, profiles, &[])
}
/// The POMs of `linked` (project-relative, from Settings) that exist inside `root`.
/// The `pom.xml` files `linked` names. Each entry is used as written (project-relative,
/// `../sibling/pom.xml`, or absolute) and canonicalized; a path that is not an existing
/// `pom.xml` is skipped. Nothing here lists a directory or walks parents looking for builds.
fn linked_poms(root: &Path, linked: &[String]) -> Vec<PathBuf> {
let base = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
let mut out: Vec<PathBuf> = Vec::new();
for pom in linked {
let pom = normalized_pom(pom);
if pom.is_empty() || pom.starts_with("../") || pom == ".." {
continue;
}
let path = root.join(&pom);
let inside = dunce::canonicalize(&path).is_ok_and(|p| p.starts_with(&base));
if path.is_file() && inside && !out.contains(&path) {
let Some(path) = dunce::canonicalize(base.join(pom.trim())).ok() else { continue };
if is_pom_file(&path) && !out.contains(&path) {
out.push(path);
}
}
out
}
fn is_pom_file(path: &Path) -> bool {
path.is_file()
&& path
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| if cfg!(windows) { name.eq_ignore_ascii_case("pom.xml") } else { name == "pom.xml" })
}
/// Identity of `path` (both canonical) within `root`: project-relative inside it,
/// otherwise the absolute path with forward slashes.
fn project_rel(root: &Path, path: &Path) -> String {
path.strip_prefix(root).unwrap_or(path).to_string_lossy().replace('\\', "/")
}
/// Canonical `pom.xml` paths named by `linked`, keyed by the spelling to store and to
/// show so unlink removes the same entry settings hold. The first spelling wins.
fn linked_identities(root: &Path, linked: &[String]) -> HashMap<PathBuf, String> {
let mut out = HashMap::new();
for entry in linked {
let entry = entry.trim();
if entry.is_empty() {
continue;
}
let Some(path) = dunce::canonicalize(root.join(entry)).ok() else { continue };
if is_pom_file(&path) {
out.entry(path).or_insert_with(|| entry.replace('\\', "/"));
}
}
out
}
/// Stable, deduplicated form of `poms` for `languages.java.maven.linkedProjects`.
/// An existing `pom.xml` inside `root` is project-relative; one outside it is the
/// canonical absolute path. Spellings of the same file (`../B/pom.xml`, an absolute
/// path, a symlink) collapse to one entry. A path that exists and is not a `pom.xml`
/// is dropped. A `pom.xml` that cannot be resolved yet is kept, so a link is not
/// discarded while its volume is offline. No directory is scanned.
pub fn normalize_linked_poms(root: &Path, poms: &[String]) -> Vec<String> {
let Some(root) = dunce::canonicalize(root).ok() else {
let mut out = Vec::new();
for pom in poms {
let pom = normalized_pom(pom);
if !pom.is_empty() && pom_name_ok(&pom) && !out.contains(&pom) {
out.push(pom);
}
}
return out;
};
let mut out = Vec::new();
let mut seen = HashSet::new();
for pom in poms {
let pom = pom.trim();
if pom.is_empty() {
continue;
}
let key = match dunce::canonicalize(root.join(pom)) {
Ok(path) if is_pom_file(&path) => project_rel(&root, &path),
Ok(_) => continue,
Err(_) => {
let fallback = normalized_pom(pom);
let joined = root.join(pom);
if !pom_name_ok(&fallback) || (joined.exists() && !is_pom_file(&joined)) {
continue;
}
fallback
}
};
if key.is_empty() || !seen.insert(key.clone()) {
continue;
}
out.push(key);
}
out
}
fn pom_name_ok(path: &str) -> bool {
let name = path.rsplit('/').next().unwrap_or(path);
if cfg!(windows) { name.eq_ignore_ascii_case("pom.xml") } else { name == "pom.xml" }
}
/// Directories of linked `pom.xml` files that sit outside `root` (the opened project
/// stays the root). Callers keep the outermost directory only. Modules a POM declares
/// outside its own directory are not included: a linked file cannot widen the indexed
/// tree to an arbitrary path.
pub fn external_pom_dirs(root: &Path, linked: &[String]) -> Vec<PathBuf> {
let base = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
let mut out = Vec::new();
for pom in linked_poms(root, linked) {
let Some(dir) = pom.parent() else { continue };
if dir.starts_with(&base) || out.iter().any(|have| have == dir) {
continue;
}
out.push(dir.to_path_buf());
}
out
}
/// Whether `root` holds a Maven build or the settings link one inside it.
pub fn has_projects(root: &Path, settings: &ide_core::settings::MavenSettings) -> bool {
is_maven_project(root) || !linked_poms(root, &settings.linked_projects).is_empty()
@@ -1130,7 +1233,9 @@ pub fn has_projects(root: &Path, settings: &ide_core::settings::MavenSettings) -
/// The model with the chosen `profiles` (`-P` entries; `!id` deactivates: their modules,
/// dependencies and properties are part of the model, those turned off are not) and the
/// `linked` POMs (Add Maven Projects): builds that no reactor lists, shown as independent
/// top-level projects. A linked POM that turns out to be a module of the root reactor stays that module.
/// top-level projects, including a `pom.xml` outside the opened root. A linked POM that
/// turns out to be a module of the root reactor stays that module. The same canonical file
/// is loaded once, so a cycle or a second spelling does not duplicate it or edit either POM.
pub fn load_with_linked(
root: &Path,
local_repo: Option<PathBuf>,
@@ -1139,7 +1244,10 @@ pub fn load_with_linked(
) -> MavenModel {
let mut resolver = Resolver::new(local_repo, profiles);
let mut model = MavenModel::default();
let mut seen: HashSet<PathBuf> = HashSet::new();
// Canonical POM → its project, for a module listed again by a later aggregator.
let mut seen: HashMap<PathBuf, Option<usize>> = HashMap::new();
let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
let linked_ids = linked_identities(&canonical_root, linked);
let mut tops = top_level_poms(root);
for pom in linked_poms(root, linked) {
if !tops.contains(&pom) {
@@ -1147,17 +1255,31 @@ pub fn load_with_linked(
}
}
// (pom, aggregated); the root reactor and its modules come before linked POMs.
let mut stack: Vec<(PathBuf, bool)> = tops.into_iter().rev().map(|p| (p, false)).collect();
while let Some((path, aggregated)) = stack.pop() {
// (pom, listed by): a module carries the top-level project its chain started from and
// whether the aggregator listing it lies inside the opened root.
let mut stack: Vec<(PathBuf, Option<(usize, bool)>)> = tops.into_iter().rev().map(|p| (p, None)).collect();
while let Some((path, listed_by)) = stack.pop() {
let aggregated = listed_by.is_some();
if model.projects.len() >= MAX_PROJECTS {
break;
}
let canonical = dunce::canonicalize(&path).unwrap_or_else(|_| path.clone());
if !seen.insert(canonical) {
if let Some(known) = seen.get(&canonical) {
// Found as a top-level POM first, then listed by an aggregator elsewhere
// (`<module>../</module>` of `parent/pom.xml`): it is that aggregator's module.
// Not when the chain leads back to where it started (a cycle), and not for an
// aggregator outside the opened root: a linked sibling does not take it over.
if let (Some(known), Some((origin, true))) = (*known, listed_by)
&& known != origin
{
model.projects[known].aggregated = true;
}
continue;
}
seen.insert(canonical.clone(), None);
let Some(pom) = resolver.pom(&path) else { continue };
let dir = path.parent().unwrap_or(root).to_path_buf();
let dir_canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
let ctx = resolver.context(&path, 0);
let props = resolver.properties_for(&pom, &ctx, &dir);
let i = |s: &str| interpolate(s, &props);
@@ -1168,7 +1290,7 @@ pub fn load_with_linked(
}
let mut modules: Vec<PathBuf> = Vec::new();
for m in module_names {
let mut mp = dir.join(i(&m));
let mut mp = crate::gradle::normalize(&dir.join(i(&m)));
if mp.is_dir() || mp.extension().is_none_or(|e| e != "xml") {
mp.push("pom.xml");
}
@@ -1232,28 +1354,39 @@ pub fn load_with_linked(
}
}
let artifact_id = i(&pom.artifact_id);
let module_ids: Vec<String> = modules
.iter()
.map(|m| {
let canonical = dunce::canonicalize(m).unwrap_or_else(|_| m.clone());
linked_ids.get(&canonical).cloned().unwrap_or_else(|| project_rel(&canonical_root, &canonical))
})
.collect();
model.projects.push(MavenProject {
project_root: None,
pom: rel_path(root, &path),
dir: rel_path(root, &dir),
pom: linked_ids.get(&canonical).cloned().unwrap_or_else(|| project_rel(&canonical_root, &canonical)),
dir: project_rel(&canonical_root, &dir_canon),
group_id: i(props.get("project.groupId").map(String::as_str).unwrap_or_default()),
version: i(props.get("project.version").map(String::as_str).unwrap_or_default()),
display_name: pom.name.as_deref().map(i).filter(|n| !n.is_empty()).unwrap_or_else(|| artifact_id.clone()),
artifact_id,
packaging,
parent: pom.parent.as_ref().map(|p| format!("{}:{}:{}", p.group_id, p.artifact_id, i(&p.version))),
modules: modules.iter().map(|m| rel_path(root, m)).collect(),
modules: module_ids,
aggregated,
plugins,
dependencies,
profiles: ctx.profiles.iter().map(|(id, _)| id.clone()).collect(),
java_version: jv,
command: wrapper(root, &dir),
command: wrapper(&canonical_root, &dir_canon),
options: Vec::new(),
env: BTreeMap::new(),
});
let index = model.projects.len() - 1;
seen.insert(canonical, Some(index));
let origin = listed_by.map_or(index, |(origin, _)| origin);
let inside = dir_canon.starts_with(&canonical_root);
for m in modules.into_iter().rev() {
stack.push((m, true));
stack.push((m, Some((origin, inside))));
}
}
model
@@ -1341,17 +1474,27 @@ impl UnlinkedProjects {
fn normalized_pom(pom: &str) -> String {
let pom = pom.replace('\\', "/");
let mut parts = Vec::new();
let unc = pom.starts_with("//");
let absolute = pom.starts_with('/');
let mut parts: Vec<&str> = Vec::new();
for part in pom.split('/') {
match part {
"" | "." => {}
".." if parts.last().is_some_and(|p| *p != "..") => {
// Keep a drive letter (`C:`) and a leading `..` that has nothing to climb.
".." if parts.last().is_some_and(|p| *p != ".." && !p.ends_with(':')) => {
parts.pop();
}
part => parts.push(part),
}
}
parts.join("/")
let joined = parts.join("/");
if unc {
format!("//{joined}")
} else if absolute {
format!("/{joined}")
} else {
joined
}
}
/// Every POM of the model (for change detection).
@@ -2147,6 +2290,169 @@ mod tests {
assert_eq!(top(&load_linked(deep.path(), &settings)), [("a/b/c/tool".into(), false)]);
}
/// A sibling Maven project is linked beside the opened root. Its reactor, including a
/// module that points back at the opened project, is read once. Neither POM is rewritten,
/// and only the linked project's directory is an extra content root — not the common
/// parent and not a module that lives outside that directory.
#[test]
fn external_sibling_keeps_its_directory_and_does_not_edit_poms() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let a = base.join("A");
let b = base.join("B");
let c = base.join("C");
std::fs::create_dir_all(a.join("core")).unwrap();
std::fs::create_dir_all(b.join("mod")).unwrap();
std::fs::create_dir_all(&c).unwrap();
let a_pom = "<project><groupId>demo</groupId><artifactId>a</artifactId><version>1</version><packaging>pom</packaging><modules><module>core</module></modules></project>";
let b_pom = "<project><groupId>demo</groupId><artifactId>b</artifactId><version>1</version><packaging>pom</packaging><modules><module>mod</module><module>../A</module><module>../C</module><module>.</module></modules></project>";
let c_pom = "<project><groupId>demo</groupId><artifactId>c</artifactId><version>1</version><modules><module>../B</module></modules></project>";
std::fs::write(a.join("pom.xml"), a_pom).unwrap();
std::fs::write(a.join("core/pom.xml"), "<project><artifactId>core</artifactId></project>").unwrap();
std::fs::write(b.join("pom.xml"), b_pom).unwrap();
std::fs::write(b.join("mod/pom.xml"), "<project><artifactId>bmod</artifactId></project>").unwrap();
std::fs::write(c.join("pom.xml"), c_pom).unwrap();
let wrapper = if cfg!(windows) { "mvnw.cmd" } else { "mvnw" };
std::fs::write(a.join(wrapper), "#!/bin/sh\n").unwrap();
std::fs::write(b.join(wrapper), "#!/bin/sh\n").unwrap();
std::fs::write(base.join(wrapper), "#!/bin/sh\n").unwrap();
let discovered = load_with_linked(&a, None, &[], &[]);
assert_eq!(discovered.projects.iter().map(|p| p.artifact_id.as_str()).collect::<Vec<_>>(), ["a", "core"]);
let stored = vec!["../B/pom.xml".into()];
let linked = load_with_linked(&a, None, &[], &stored);
let b_project = linked.projects.iter().find(|p| p.artifact_id == "b").unwrap();
assert!(!b_project.aggregated);
assert_eq!(b_project.pom, "../B/pom.xml");
assert_eq!(dunce::canonicalize(a.join(&b_project.dir)).unwrap(), b);
assert_eq!(dunce::canonicalize(&b_project.command).unwrap(), dunce::canonicalize(b.join(wrapper)).unwrap());
let a_project = linked.projects.iter().find(|p| p.artifact_id == "a").unwrap();
assert!(!a_project.aggregated);
assert_eq!(a_project.modules, ["core/pom.xml"]);
assert_eq!(dunce::canonicalize(&a_project.command).unwrap(), dunce::canonicalize(a.join(wrapper)).unwrap());
assert_eq!(linked.projects.iter().filter(|p| p.artifact_id == "a").count(), 1);
assert_eq!(linked.projects.iter().filter(|p| p.artifact_id == "b").count(), 1);
assert!(linked.projects.iter().any(|p| p.artifact_id == "c" && p.aggregated));
assert!(linked.projects.iter().any(|p| p.artifact_id == "bmod" && p.aggregated));
let again = load_with_linked(&a, None, &[], &stored);
assert_eq!(
again.projects.iter().map(|p| &p.pom).collect::<Vec<_>>(),
linked.projects.iter().map(|p| &p.pom).collect::<Vec<_>>()
);
let absolute = b.join("pom.xml").to_string_lossy().replace('\\', "/");
let via_a = a.join("../B/pom.xml").to_string_lossy().replace('\\', "/");
let normalized = normalize_linked_poms(
&a,
&[
"../B/pom.xml".into(),
absolute,
via_a,
a.join("pom.xml").to_string_lossy().into_owned(),
b.to_string_lossy().into_owned(),
"stub/pom.xml".into(),
"notes.xml".into(),
],
);
assert_eq!(normalized.len(), 3, "{normalized:?}");
assert_eq!(normalized[0], dunce::canonicalize(b.join("pom.xml")).unwrap().to_string_lossy().replace('\\', "/"));
assert_eq!(normalized[1], "pom.xml");
assert_eq!(normalized[2], "stub/pom.xml");
assert_eq!(crate::maven_external_roots(&a, &normalized), vec![b.clone()]);
assert_eq!(crate::maven_external_roots(&a, &stored), vec![b.clone()]);
let removed = load_with_linked(&a, None, &[], &[]);
assert!(removed.projects.iter().all(|p| p.artifact_id != "b"));
assert_eq!(std::fs::read_to_string(a.join("pom.xml")).unwrap(), a_pom);
assert_eq!(std::fs::read_to_string(b.join("pom.xml")).unwrap(), b_pom);
assert_eq!(std::fs::read_to_string(c.join("pom.xml")).unwrap(), c_pom);
assert!(b.join("mod/pom.xml").is_file());
}
/// The launcher recorded on an external project is that project's wrapper, and
/// running it uses the external directory as the working directory.
#[cfg(unix)]
#[test]
fn external_project_wrapper_runs_in_its_own_directory() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let a = base.join("A");
let b = base.join("B");
std::fs::create_dir_all(b.join("src/main/java")).unwrap();
std::fs::create_dir_all(&a).unwrap();
std::fs::write(a.join("pom.xml"), "<project><artifactId>a</artifactId></project>").unwrap();
std::fs::write(
b.join("pom.xml"),
"<project><artifactId>b</artifactId><build><sourceDirectory>src/main/java</sourceDirectory></build></project>",
)
.unwrap();
std::fs::write(b.join("src/main/java/B.java"), "class B {}").unwrap();
let script = b.join("mvnw");
std::fs::write(&script, "#!/bin/sh\npwd > \"$1\"\nprintf 'BUILD SUCCESS\\n'\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let model = load_with_linked(&a, None, &[], &["../B/pom.xml".into()]);
let project = model.projects.iter().find(|p| p.artifact_id == "b").unwrap();
let cwd = a.join(&project.dir);
assert_eq!(dunce::canonicalize(&cwd).unwrap(), b);
let marker = tmp.path().join("cwd");
let out = crate::process::run(
&project.command,
&[marker.to_string_lossy().into_owned()],
&cwd,
&std::collections::BTreeMap::new(),
&ide_core::CancellationToken::new(),
|_, _| {},
)
.unwrap();
assert!(out.success, "{}", out.text);
let recorded = dunce::canonicalize(std::fs::read_to_string(&marker).unwrap().trim()).unwrap();
assert_eq!(recorded, b);
}
/// #2877: an aggregator in a subfolder lists the root POM as `../`; linked, it holds every
/// module, the root one included, under the same POM paths the projects have.
#[test]
fn an_aggregator_in_a_subfolder_holds_the_root_pom() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let child = |id: &str, rel: &str| {
format!(
"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1.0</version><relativePath>{rel}</relativePath></parent><artifactId>{id}</artifactId></project>"
)
};
write(root, "pom.xml", &child("app", "parent/pom.xml"));
write(
root,
"parent/pom.xml",
"<project><groupId>demo</groupId><artifactId>parent</artifactId><version>1.0</version><packaging>pom</packaging><modules><module>../</module><module>../infra</module></modules></project>",
);
write(root, "infra/pom.xml", &child("infra", "../parent/pom.xml"));
let model = load_with_linked(root, None, &[], &["parent/pom.xml".into()]);
let tops: Vec<&str> = model.projects.iter().filter(|p| !p.aggregated).map(|p| p.artifact_id.as_str()).collect();
assert_eq!(tops, ["parent"]);
let parent = model.projects.iter().find(|p| p.artifact_id == "parent").unwrap();
assert_eq!(parent.modules, ["pom.xml", "infra/pom.xml"]);
for pom in &parent.modules {
assert!(model.projects.iter().any(|p| &p.pom == pom), "{pom}");
}
// A cycle (the root lists the aggregator, which lists the root) keeps the root on top.
write(
root,
"pom.xml",
"<project><groupId>demo</groupId><artifactId>app</artifactId><version>1.0</version><packaging>pom</packaging><modules><module>parent</module></modules></project>",
);
let model = load_with_linked(root, None, &[], &[]);
let tops: Vec<&str> = model.projects.iter().filter(|p| !p.aggregated).map(|p| p.artifact_id.as_str()).collect();
assert_eq!(tops, ["app"]);
}
#[test]
fn chosen_profiles_bring_their_modules_and_dependencies() {
let tmp = tempfile::tempdir().unwrap();
+5
Переглянути файл
@@ -78,6 +78,10 @@ pub struct EditorAppearanceSettings {
/// Right margin and visual guides from Code Style.
pub hard_wrap_guides: bool,
pub intention_bulb: bool,
/// Draw doc comments (Javadoc, KDoc, JSDoc, rustdoc) as rendered documentation
/// instead of their source, as IDEA's option of the same name. View › Active
/// Editor › Render Documentation Comments overrides this for one editor.
pub render_doc_comments: bool,
/// Distraction Free Mode: width of the centred text column, in characters.
pub distraction_free_width: u32,
}
@@ -100,6 +104,7 @@ impl Default for EditorAppearanceSettings {
rainbow_indent_guides: false,
hard_wrap_guides: true,
intention_bulb: true,
render_doc_comments: false,
distraction_free_width: 80,
}
}
+40 -2
Переглянути файл
@@ -194,6 +194,19 @@ where
Ok(serde_json::from_value(serde_json::Value::deserialize(d)?).unwrap_or_default())
}
/// A theme id, with the built-in themes that were removed read as the Islands theme of their kind.
fn theme_id<'de, D>(d: D) -> Result<String, D::Error>
where
D: serde::Deserializer<'de>,
{
let id = String::deserialize(d)?;
Ok(match id.as_str() {
"one-light" => "light".into(),
"one-dark" => "dark".into(),
_ => id,
})
}
/// [`AgentSettings::defaults`], keeping only the text values of each agent's table.
fn agent_defaults<'de, D>(d: D) -> Result<BTreeMap<String, BTreeMap<String, String>>, D::Error>
where
@@ -557,13 +570,19 @@ pub enum NavigationBarPosition {
pub struct AppearanceSettings {
/// A built-in theme id (`light`, `dark`, `dark-hc`, …), `system` (legacy
/// "Sync with OS"), or a plugin's theme: `plugin:<plugin-id>/<theme-id>`.
#[serde(deserialize_with = "theme_id")]
#[specta(type = String)]
pub theme: String,
pub accent: String,
pub ui_font_size: f32,
pub locale: String,
/// Follow the OS light/dark mode with the preferred themes below.
pub sync_with_os: bool,
#[serde(deserialize_with = "theme_id")]
#[specta(type = String)]
pub preferred_light_theme: String,
#[serde(deserialize_with = "theme_id")]
#[specta(type = String)]
pub preferred_dark_theme: String,
/// A plugin's file icon theme (`<plugin-id>/<theme-id>`); empty = the built-in icons.
pub file_icon_theme: String,
@@ -1182,7 +1201,9 @@ pub struct MavenSettings {
pub runner_jre: String,
/// Project-relative root POMs removed from the Maven project model.
pub unlinked_projects: Vec<String>,
/// Project-relative POMs outside the root reactor added as independent top-level projects.
/// POMs added as independent top-level projects. Inside the opened project the path is
/// project-relative (`tools/pom.xml`); outside it, the canonical absolute path. Linking
/// does not edit either POM.
pub linked_projects: Vec<String>,
/// Maven home (or its `mvn` executable); empty = the project's `mvnw`, else `mvn` on `PATH`.
pub home: String,
@@ -1203,6 +1224,8 @@ pub struct MavenSettings {
pub threads: String,
/// Active Maven profiles (`-P`), comma-separated; empty leaves profiles to the POM/settings.
pub active_profiles: String,
/// Delegate IDE build/run actions to Maven: launches build with Maven (`javac`) instead of jdtls (ECJ).
pub delegate_build: bool,
}
impl MavenSettings {
@@ -1420,6 +1443,19 @@ impl Settings {
mod tests {
use super::*;
#[test]
fn removed_one_themes_read_as_islands_themes() {
let settings: Settings = serde_json::from_str(
r#"{"appearance":{"theme":"one-dark","preferredLightTheme":"one-light","preferredDarkTheme":"one-dark"}}"#,
)
.unwrap();
let a = settings.appearance;
assert_eq!((a.theme.as_str(), a.preferred_light_theme.as_str()), ("dark", "light"));
assert_eq!(a.preferred_dark_theme, "dark");
let kept: Settings = serde_json::from_str(r#"{"appearance":{"theme":"solarized-dark"}}"#).unwrap();
assert_eq!(kept.appearance.theme, "solarized-dark");
}
#[test]
fn window_close_settings_default_off_and_round_trip() {
for old in [r#"{}"#, r#"{"general":{"confirmExit":false}}"#] {
@@ -1707,10 +1743,12 @@ mod maven_linkage_tests {
fn maven_runner_jre_defaults_and_round_trips() {
let old: MavenSettings = serde_json::from_str(r#"{"home":"/opt/maven"}"#).unwrap();
assert!(old.runner_jre.is_empty());
assert!(!old.delegate_build);
assert!(MavenSettings::default().runner_jre.is_empty());
let settings = MavenSettings { runner_jre: "/opt/jdk-21".into(), ..old };
let settings = MavenSettings { runner_jre: "/opt/jdk-21".into(), delegate_build: true, ..old };
let encoded = serde_json::to_string(&settings).unwrap();
assert!(encoded.contains(r#""runnerJre":"/opt/jdk-21""#));
assert!(encoded.contains(r#""delegateBuild":true"#));
assert_eq!(serde_json::from_str::<MavenSettings>(&encoded).unwrap(), settings);
}
+30
Переглянути файл
@@ -192,6 +192,33 @@ pub struct IssueLink {
pub link: String,
}
/// Per-level colours for console log lines: a line whose level is detected
/// (`ERROR`, `WARN`, …) takes the level's colour; ANSI colours the program
/// prints itself win over it. Values are CSS colours, usually scheme tokens.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct LogLevelColors {
pub enabled: bool,
pub error: String,
pub warn: String,
pub info: String,
pub debug: String,
pub trace: String,
}
impl Default for LogLevelColors {
fn default() -> Self {
Self {
enabled: false,
error: "var(--ansi-red)".into(),
warn: "var(--ansi-yellow)".into(),
info: "var(--ansi-green)".into(),
debug: "var(--ansi-cyan)".into(),
trace: "var(--ansi-magenta)".into(),
}
}
}
/// Build, Execution, Deployment › Console.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -203,6 +230,8 @@ pub struct ConsoleSettings {
pub encoding: String,
/// Consecutive lines containing any of these are folded.
pub fold_patterns: Vec<String>,
/// Log lines take the colour of their level (Run/Debug consoles).
pub log_colors: LogLevelColors,
}
impl Default for ConsoleSettings {
@@ -219,6 +248,7 @@ impl Default for ConsoleSettings {
"at node:internal/".into(),
"<frozen importlib._bootstrap".into(),
],
log_colors: LogLevelColors::default(),
}
}
}
+12 -3
Переглянути файл
@@ -105,9 +105,12 @@ fn builtin(adapter: &str) -> Option<DebuggerConfig> {
"stdio",
"Install netcoredbg (.NET debugger) in Settings › Languages & Frameworks › Language Servers",
),
"lldb-dap" => {
cfg("lldb-dap", &[], "stdio", "Install LLVM's lldb-dap (brew install llvm; on macOS `xcrun -f lldb-dap`)")
}
"lldb-dap" => cfg(
"lldb-dap",
&[],
"stdio",
"Install LLVM's lldb-dap (brew install llvm), or on macOS use the one found by xcrun -f lldb-dap",
),
// GDB's own DAP interpreter, stdio transport. The DAP support it needs shipped in GDB 14
// (`prepare_gdb` refuses older ones with the required version in the message).
"gdb" => cfg(
@@ -124,6 +127,12 @@ fn builtin(adapter: &str) -> Option<DebuggerConfig> {
"tcp",
"Install Microsoft java-debug (Settings › Languages & Frameworks › Language Servers)",
),
"bun-dap" => cfg(
"bun-dap",
&["${port}", "127.0.0.1"],
"tcp",
"To install bun-dap: git clone https://github.com/morf-bls/bun-dap, run bun install && bun run build, then place dist/bun-dap in your PATH",
),
_ => return None,
})
}
+1
Переглянути файл
@@ -17,6 +17,7 @@ blake3.workspace = true
tokio.workspace = true
tracing.workspace = true
parking_lot.workspace = true
notify.workspace = true
futures.workspace = true
sqlx.workspace = true
tiberius.workspace = true
+38 -3
Переглянути файл
@@ -283,6 +283,16 @@ fn mssql_pool_err(e: bb8::RunError<tiberius::error::Error>) -> IdeError {
}
}
/// Tiberius requires TLS when a TLS backend is enabled. `trust_cert` only skips
/// certificate checks, so Disable has to turn encryption off.
fn apply_sqlserver_ssl(config: &mut tiberius::Config, ssl: DbSslMode) {
match ssl {
DbSslMode::Disable => config.encryption(tiberius::EncryptionLevel::NotSupported),
DbSslMode::Prefer => config.trust_cert(),
DbSslMode::Require | DbSslMode::VerifyCa | DbSslMode::VerifyFull => {}
}
}
const DAYS_1900_01_01: i64 = 693_595;
/// Formats a proleptic Gregorian date given days since `0001-01-01`.
@@ -876,9 +886,7 @@ impl Pool {
if !source.database.is_empty() {
config.database(&source.database);
}
if matches!(source.ssl, DbSslMode::Disable | DbSslMode::Prefer) {
config.trust_cert();
}
apply_sqlserver_ssl(&mut config, source.ssl);
let manager = MssqlConnectionManager(config);
let pool = bb8::Pool::builder()
.max_size(MAX)
@@ -1331,6 +1339,33 @@ mod tests {
use super::*;
use crate::source::{DbOptions, DbProperty};
fn sqlserver_debug(ssl: DbSslMode) -> String {
let mut config = tiberius::Config::new();
apply_sqlserver_ssl(&mut config, ssl);
format!("{config:?}")
}
#[test]
fn sqlserver_disable_does_not_require_tls() {
let debug = sqlserver_debug(DbSslMode::Disable);
assert!(debug.contains("encryption: NotSupported"), "{debug}");
assert!(debug.contains("bypass: false"), "{debug}");
}
#[test]
fn sqlserver_prefer_trusts_the_server_certificate() {
let debug = sqlserver_debug(DbSslMode::Prefer);
assert!(debug.contains("encryption: Required"), "{debug}");
assert!(debug.contains("bypass: true"), "{debug}");
}
#[test]
fn sqlserver_require_keeps_validated_tls() {
let debug = sqlserver_debug(DbSslMode::Require);
assert!(debug.contains("encryption: Required"), "{debug}");
assert!(debug.contains("bypass: false"), "{debug}");
}
#[test]
fn discarded_sqlserver_connections_are_broken() {
let manager = MssqlConnectionManager(tiberius::Config::new());
+42
Переглянути файл
@@ -12,6 +12,8 @@ pub mod secrets;
pub mod source;
pub mod split;
pub mod sql;
mod watch;
pub use watch::SourcesWatch;
pub use conn::{Held, Pool, QueryResult, ResultColumn};
pub use history::HistoryEntry;
@@ -235,6 +237,9 @@ pub struct DbManager {
/// Manual-commit data sources, each with the connection of its open
/// transaction (taken by the first statement after a commit / rollback).
sessions: Mutex<HashMap<String, Session>>,
/// The data sources as last read from disk, for [`DbManager::reconcile_sources`]
/// (`None` until [`DbManager::watch_sources`]).
on_disk: Mutex<Option<Vec<DataSource>>>,
}
type Session = Arc<tokio::sync::Mutex<Option<Held>>>;
@@ -362,6 +367,7 @@ impl DbManager {
tunnel_open: tokio::sync::Mutex::new(()),
ssh,
session_passwords: Mutex::default(),
on_disk: Mutex::default(),
sessions: Mutex::default(),
}
}
@@ -474,9 +480,45 @@ impl DbManager {
}
}
}
// Our own write is not reported as an edit on disk.
if let Some(known) = self.on_disk.lock().as_mut() {
*known = self.sources().unwrap_or(sources);
}
Ok(())
}
/// Watches the data source files (the project's and the global one) for edits made
/// outside the IDE; `on_change` runs on a background thread once they settle, and
/// should call [`DbManager::reconcile_sources`]. Stops when the result is dropped.
pub fn watch_sources(&self, on_change: Box<dyn Fn() + Send>) -> IdeResult<SourcesWatch> {
*self.on_disk.lock() = Some(self.sources().unwrap_or_default());
SourcesWatch::start(&self.root, self.global.as_ref().map(|(dir, _)| dir.as_path()), on_change)
}
/// Re-reads the data sources after their files changed on disk: connections of
/// removed or changed sources close, as on [`DbManager::save_sources`] (saved
/// passwords stay, the source may come back). Returns whether the list the tree
/// shows changed, or the files no longer parse (the tree reports the error).
pub async fn reconcile_sources(&self) -> bool {
let now = match self.sources() {
Ok(now) => now,
Err(e) => {
tracing::warn!("data sources: {}", e.message);
return true;
}
};
let before = self.on_disk.lock().replace(now.clone()).unwrap_or_default();
if before == now {
return false;
}
for o in &before {
if now.iter().find(|s| s.id == o.id) != Some(o) {
self.disconnect_source(&o.id).await;
}
}
true
}
/// Remembers `password` for the session, and in the saved passwords when
/// the data source saves passwords (`None` forgets it).
pub async fn set_password(&self, id: &str, password: Option<String>, save: bool) -> IdeResult<()> {
+1 -1
Переглянути файл
@@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::Path;
const FILE: &str = "data-sources.toml";
pub(crate) const FILE: &str = "data-sources.toml";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+151
Переглянути файл
@@ -0,0 +1,151 @@
//! Data source files edited outside the Database tool window (by hand, by a coding
//! agent, by `git checkout`) are picked up while the project is open, as IDEA does
//! for `dataSources.xml`. The project file tree's watcher is no help here: it never
//! reports a modification inside a gitignored `.openidea/`.
use crate::source::FILE;
use ide_core::{IdeError, IdeResult, project_dir};
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use parking_lot::Mutex;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Weak, mpsc};
use std::time::Duration;
/// How long a burst of writes (an editor's save, an agent's rewrite) settles before
/// the files are read.
const SETTLE: Duration = Duration::from_millis(200);
/// Watches `<root>/.openidea/data-sources.toml` and `<global>/data-sources.toml`;
/// stops when dropped.
pub struct SourcesWatch {
_watcher: Arc<Mutex<RecommendedWatcher>>,
}
impl SourcesWatch {
/// Calls `on_change` once a burst of changes to either file settled, on a
/// background thread.
pub fn start(root: &Path, global: Option<&Path>, on_change: Box<dyn Fn() + Send>) -> IdeResult<Self> {
let config: PathBuf = root.join(project_dir::DIR);
let (tx, rx) = mpsc::channel::<()>();
let relevant = {
let config = config.clone();
move |p: &Path| p.file_name().is_some_and(|n| n == FILE) || p == config
};
let watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
if let Ok(e) = res
&& e.paths.iter().any(|p| relevant(p))
{
let _ = tx.send(());
}
})
.map_err(|e| IdeError::internal(format!("data sources watcher: {e}")))?;
let watcher = Arc::new(Mutex::new(watcher));
{
let mut w = watcher.lock();
// The root (not recursively) sees `.openidea/` itself appear or go.
w.watch(root, RecursiveMode::NonRecursive)
.map_err(|e| IdeError::internal(format!("data sources watcher: {e}")))?;
if let Some(dir) = global.filter(|d| d.is_dir())
&& let Err(e) = w.watch(dir, RecursiveMode::NonRecursive)
{
tracing::warn!("global data sources watcher: {e}");
}
}
let mut watching = watch_config(&watcher, &config, false);
let weak: Weak<Mutex<RecommendedWatcher>> = Arc::downgrade(&watcher);
std::thread::Builder::new().name("openidea-db-sources-watch".into()).spawn(move || {
while rx.recv().is_ok() {
// Wait until the writes stop.
loop {
match rx.recv_timeout(SETTLE) {
Ok(()) => {}
Err(mpsc::RecvTimeoutError::Timeout) => break,
Err(mpsc::RecvTimeoutError::Disconnected) => return,
}
}
let Some(watcher) = weak.upgrade() else { return };
watching = watch_config(&watcher, &config, watching);
drop(watcher);
on_change();
}
})?;
Ok(Self { _watcher: watcher })
}
}
/// Watches `.openidea/` once it exists (again: a removed folder loses its watch);
/// returns whether it is watched.
fn watch_config(watcher: &Mutex<RecommendedWatcher>, config: &Path, watching: bool) -> bool {
if !config.is_dir() {
return false;
}
if watching {
return true;
}
match watcher.lock().watch(config, RecursiveMode::NonRecursive) {
Ok(()) => true,
Err(e) => {
tracing::warn!("data sources watcher {}: {e}", config.display());
false
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Instant;
fn wait_for(count: &AtomicUsize, at_least: usize) -> bool {
let deadline = Instant::now() + Duration::from_secs(10);
while Instant::now() < deadline {
if count.load(Ordering::SeqCst) >= at_least {
return true;
}
std::thread::sleep(Duration::from_millis(20));
}
false
}
fn counting() -> (Arc<AtomicUsize>, Box<dyn Fn() + Send>) {
let count = Arc::new(AtomicUsize::new(0));
let c = count.clone();
(count, Box::new(move || _ = c.fetch_add(1, Ordering::SeqCst)))
}
#[test]
fn reports_project_and_global_files_and_a_config_folder_created_later() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let (project, global) = (root.join("p"), root.join("app"));
std::fs::create_dir_all(&project).unwrap();
std::fs::create_dir_all(&global).unwrap();
let (count, on_change) = counting();
let _watch = SourcesWatch::start(&project, Some(&global), on_change).unwrap();
// No `.openidea/` yet: it is created, then the file written into it.
std::fs::create_dir_all(project.join(".openidea")).unwrap();
assert!(wait_for(&count, 1));
let seen = count.load(Ordering::SeqCst);
std::fs::write(project.join(".openidea/data-sources.toml"), "").unwrap();
assert!(wait_for(&count, seen + 1), "project file");
let seen = count.load(Ordering::SeqCst);
std::fs::write(global.join("data-sources.toml"), "").unwrap();
assert!(wait_for(&count, seen + 1), "global file");
}
#[test]
fn ignores_other_files() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
std::fs::create_dir_all(root.join(".openidea")).unwrap();
let (count, on_change) = counting();
let _watch = SourcesWatch::start(&root, None, on_change).unwrap();
std::fs::write(root.join(".openidea/settings.toml"), "").unwrap();
std::fs::write(root.join("main.py"), "").unwrap();
std::thread::sleep(SETTLE * 3);
assert_eq!(count.load(Ordering::SeqCst), 0);
}
}
+28
Переглянути файл
@@ -342,3 +342,31 @@ async fn applies_driver_properties_and_the_startup_script_on_connect() -> IdeRes
assert_eq!(db.schemas("s1").await?, vec!["main"]);
Ok(())
}
#[tokio::test]
async fn data_sources_edited_on_disk_close_their_connections() -> IdeResult<()> {
let (tmp, db) = setup().await;
std::fs::File::create(tmp.path().join("other.db")).unwrap();
let (tx, rx) = std::sync::mpsc::channel();
let _watch = db.watch_sources(Box::new(move || _ = tx.send(())))?;
db.pool("s1").await?;
assert_eq!(db.connected(), vec!["s1"]);
// Our own save is no edit on disk.
let mut sources = db.sources()?;
sources[0].name = "renamed".into();
db.save_sources(sources.clone()).await?;
assert!(!db.reconcile_sources().await);
// Edited outside the IDE (by hand, by an agent): the watcher reports it, and the
// connection made with the old settings closes.
db.pool("s1").await?;
sources[0].file = Some("other.db".into());
ide_db::source::save(tmp.path(), &sources)?;
rx.recv_timeout(std::time::Duration::from_secs(10)).expect("the watcher reports the edit");
assert!(db.reconcile_sources().await);
assert!(db.connected().is_empty());
assert_eq!(db.sources()?[0].file.as_ref().map(|f| f.0.clone()), Some("other.db".into()));
assert!(!db.reconcile_sources().await);
Ok(())
}
+29 -2
Переглянути файл
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
pub const MANIFEST_FILE: &str = "plugin.toml";
/// The plugin API (engine) version this host implements.
pub const ENGINE_VERSION: &str = "1.5.0";
pub const ENGINE_VERSION: &str = "1.6.0";
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
pub const LEGACY_API: &str = "0.1";
/// Marketplace categories, in the order they are shown.
@@ -151,6 +151,8 @@ impl ActivationEvent {
/// Workbench event kinds (`on-event:<kind>`, WIT `events.event-kind`).
/// `scheduled` comes from `on-schedule` instead.
pub const EVENT_KINDS: &[&str] = &[
"document-changed",
"websocket-ready",
"run-exited",
"terminal-exited",
"content-tab-action",
@@ -366,6 +368,10 @@ impl Manifest {
}
let mut seen = BTreeSet::new();
for event in &self.activation {
if matches!(event, ActivationEvent::Event(kind) if matches!(kind.as_str(), "document-changed" | "websocket-ready"))
{
self.needs_api(&format!("`{event}`"), 6)?;
}
if matches!(event, ActivationEvent::Event(kind) if matches!(kind.as_str(), "file-closed" | "settings-changed" | "input-mode-changed" | "run-exited" | "terminal-exited" | "content-tab-action"))
{
self.needs_api(&format!("`{event}`"), 4)?;
@@ -582,6 +588,8 @@ mod tests {
ActivationEvent::parse("on-event:files-changed"),
Ok(ActivationEvent::Event("files-changed".into()))
);
assert!(ActivationEvent::parse("on-event:document-changed").is_ok());
assert!(ActivationEvent::parse("on-event:websocket-ready").is_ok());
let err = ActivationEvent::parse("on-event:keystroke").unwrap_err();
assert!(err.contains("unknown event kind") && err.contains("action-performed"), "{err}");
assert!(ActivationEvent::parse("on-event:scheduled").is_err(), "declared with on-schedule");
@@ -860,7 +868,7 @@ mod commands_api_tests {
mod net_ask_api_tests {
use super::*;
#[test]
fn net_ask_requires_api_1_5() {
fn api_1_5_declarations_require_api_1_5() {
for declaration in ["[capabilities]\nrequired = [\"net:ask\"]", "[capabilities]\noptional = [\"net:ask\"]"] {
for engine in ["^1.4", "^1.5"] {
let manifest = format!(
@@ -875,4 +883,23 @@ mod net_ask_api_tests {
}
}
}
#[test]
fn realtime_events_require_api_1_6() {
for declaration in
["activation = [\"on-event:document-changed\"]", "activation = [\"on-event:websocket-ready\"]"]
{
for engine in ["^1.5", "^1.6"] {
let manifest = format!(
"id = 'test'\nname = 'Test'\nversion = '0.1.0'\nwasm = 'plugin.wasm'\nengines.openidea = '{engine}'\n{declaration}\n"
);
let parsed = Manifest::parse(&manifest);
if engine == "^1.6" {
parsed.unwrap();
} else {
assert!(parsed.unwrap_err().contains("new in plugin API 1.6"), "{engine}");
}
}
}
}
}
+2
Переглянути файл
@@ -14,6 +14,7 @@ encoding_rs.workspace = true
ide-core.workspace = true
ide-mcp.workspace = true
futures.workspace = true
tokio-tungstenite.workspace = true
ide-text.workspace = true
ide-vfs.workspace = true
regex-syntax.workspace = true
@@ -45,6 +46,7 @@ globset.workspace = true
ide-db.workspace = true
ide-ssh.workspace = true
ide-remote.workspace = true
ide-web.workspace = true
ide-jsonrpc.workspace = true
ide-agent.workspace = true
ide-notebook.workspace = true
+9 -8
Переглянути файл
@@ -176,14 +176,13 @@ fn apply_custom_migration_in(path: &Path, local: &Path) {
/// Entries of a local-data tree that move to a newly chosen directory.
/// Non-relocatable tool installs (virtual environments with absolute interpreter
/// paths) stay behind and are reinstalled on demand, as in `migrate_entries`.
/// paths) stay behind and are reinstalled on demand, as in `migrate_entries`;
/// so do registry agents, whose saved commands are absolute paths into `agents/tools`.
fn custom_entries(root: &Path) -> Vec<PathBuf> {
let mut entries = local_entries(root);
for extra in ["logs", "agents/tools"] {
let entry = PathBuf::from(extra);
if !entries.contains(&entry) {
entries.push(entry);
}
let logs = PathBuf::from("logs");
if !entries.contains(&logs) {
entries.push(logs);
}
entries
}
@@ -884,11 +883,13 @@ mod tests {
}
#[test]
fn custom_entries_cover_logs_and_agent_tools() {
fn custom_entries_cover_logs_and_keep_agent_installs() {
let tmp = tempfile::tempdir().unwrap();
let entries = custom_entries(tmp.path());
for expected in ["logs", "agents/tools", "index", "cache", "lsp", "agents/registry.json"] {
for expected in ["logs", "index", "cache", "lsp", "agents/registry.json"] {
assert!(entries.contains(&PathBuf::from(expected)), "{entries:?}");
}
// Registry agent files name their executables by absolute path.
assert!(!entries.iter().any(|e| e.starts_with("agents/tools")), "{entries:?}");
}
}
+4
Переглянути файл
@@ -84,6 +84,9 @@ pub struct Host {
pub remote: Arc<ide_remote::RemoteService>,
/// What child processes get beyond this process's environment (Reload Environment, `remoteEnv`).
pub environment: environment::Environment,
/// The built-in web server (Open In › Browser, the editor's browser bar). On a remote host the
/// client forwards its ports.
pub web: ide_web::WebServer,
/// The HTTP proxy's saved password (see `proxy.rs`).
proxy_password: ide_ssh::secrets::SecretFile,
/// The proxy password when it could not be saved (no credential store).
@@ -140,6 +143,7 @@ impl Host {
remote: Arc::new(ide_remote::RemoteService::new(ssh.clone(), data_dir.join("remote"))),
ssh,
environment: environment::Environment::new(project_environment, local_data_dir.clone()),
web: ide_web::WebServer::new(),
global_settings,
dependency_versions: Arc::new(ide_workspace::dependencies::VersionCache::new(
data_dir.join("cache/dependency-versions"),
+83 -4
Переглянути файл
@@ -84,6 +84,14 @@ pub struct NotebookService {
registry: Arc<Mutex<Registry>>,
kernels: Arc<KernelManager>,
sink: SharedSink,
observer: parking_lot::RwLock<Option<Arc<dyn NotebookObserver>>>,
}
/// Learns each open notebook's contents after every change of them, and when it closes (the
/// language servers' copy of its code cells).
pub trait NotebookObserver: Send + Sync {
fn changed(&self, path: &Path, snapshot: &NotebookSnapshot);
fn closed(&self, path: &Path);
}
impl NotebookService {
@@ -121,7 +129,23 @@ impl NotebookService {
}
}),
);
Arc::new(Self { registry, kernels: Arc::new(kernels), sink })
Arc::new(Self { registry, kernels: Arc::new(kernels), sink, observer: Default::default() })
}
pub fn set_observer(&self, observer: Arc<dyn NotebookObserver>) {
*self.observer.write() = Some(observer);
}
/// Called with the document's state locked, so observers see its changes in order.
fn changed(&self, path: &Path, snapshot: &NotebookSnapshot) {
if let Some(observer) = self.observer.read().clone() {
observer.changed(path, snapshot);
}
}
/// The file of an open notebook.
pub fn path_of(&self, id: &str) -> IdeResult<PathBuf> {
Ok(self.resolve(id)?.path.clone())
}
pub fn open(&self, path: &Path) -> IdeResult<NotebookSnapshot> {
@@ -136,6 +160,7 @@ impl NotebookService {
}
let document = NotebookDocument::load(&path)?;
let initial = document.snapshot();
self.changed(&path, &initial);
let id = initial.id.clone();
registry.paths.insert(path.clone(), id.clone());
registry.documents.insert(
@@ -173,7 +198,9 @@ impl NotebookService {
let document = self.resolve(id)?;
let mut state = document.state.lock();
mutable(&state)?;
state.document.edit(version, edit)
let snapshot = state.document.edit(version, edit)?;
self.changed(&document.path, &snapshot);
Ok(snapshot)
}
pub fn save(&self, id: &str) -> IdeResult<NotebookSnapshot> {
@@ -190,7 +217,9 @@ impl NotebookService {
if state.active.is_some() {
return Err(IdeError::unavailable("stop notebook execution before undo or redo"));
}
if redo { state.document.redo() } else { state.document.undo() }
let snapshot = if redo { state.document.redo() } else { state.document.undo() }?;
self.changed(&document.path, &snapshot);
Ok(snapshot)
}
pub async fn interrupt(&self, id: &str) -> IdeResult<()> {
@@ -238,7 +267,10 @@ impl NotebookService {
snapshot(&document)
} else {
self.kernels.shutdown_kernel(&document.path).await?;
document.state.lock().document.reload()
let mut state = document.state.lock();
let snapshot = state.document.reload()?;
self.changed(&document.path, &snapshot);
Ok(snapshot)
}
}
.await;
@@ -284,6 +316,10 @@ impl NotebookService {
let mut registry = self.registry.lock();
registry.documents.remove(id);
registry.paths.remove(&document.path);
drop(registry);
if let Some(observer) = self.observer.read().clone() {
observer.closed(&document.path);
}
Ok(())
}
@@ -572,6 +608,49 @@ mod tests {
KernelOutput { kind: kind.into(), content, msg_id: "actual-parent-request".into() }
}
#[tokio::test]
async fn the_observer_follows_every_change_of_an_open_notebook_and_its_close() {
#[derive(Default)]
struct Seen(Mutex<Vec<String>>);
impl NotebookObserver for Seen {
fn changed(&self, path: &Path, snapshot: &NotebookSnapshot) {
let sources: Vec<&str> = snapshot.cells.iter().map(|c| c.source.as_str()).collect();
let name = path.file_name().unwrap().to_string_lossy();
self.0.lock().push(format!("{name}: {}", sources.join(" | ")));
}
fn closed(&self, path: &Path) {
self.0.lock().push(format!("closed {}", path.file_name().unwrap().to_string_lossy()));
}
}
let (dir, service, initial) = fixture();
let seen = Arc::new(Seen::default());
service.set_observer(seen.clone());
service.close(&initial.id).await.unwrap();
let opened = service.open(&dir.path().join("session.ipynb")).unwrap();
assert_eq!(
service.path_of(&opened.id).unwrap(),
dunce::canonicalize(dir.path().join("session.ipynb")).unwrap()
);
let edit = NotebookEdit::SetSource { cell: "second".into(), source: "print(x + 1)".into() };
let edited = service.edit(&opened.id, opened.version, edit).unwrap();
service.undo(&opened.id, false).unwrap();
// A second view of the open notebook changes nothing.
service.open(&dir.path().join("session.ipynb")).unwrap();
assert!(edited.version > opened.version);
service.close(&opened.id).await.unwrap();
assert_eq!(
*seen.0.lock(),
[
"closed session.ipynb",
"session.ipynb: x = 1 | print(x) | notes",
"session.ipynb: x = 1 | print(x + 1) | notes",
"session.ipynb: x = 1 | print(x) | notes",
"closed session.ipynb",
]
);
service.shutdown().await;
}
#[tokio::test]
async fn canonical_split_opens_share_incarnation_but_reopen_and_projects_do_not() {
let (dir, service, initial) = fixture();
+20 -7
Переглянути файл
@@ -5,9 +5,9 @@ use crate::Host;
use crate::rpc::Dispatcher;
use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentCommand, AgentEntry, AgentEvent, AgentProbe, AgentPrompt,
AgentProvider, AgentQueued, AgentTask, CustomAgentInput, ExternalSession, McpScope, McpServer, McpServerInput,
NewAgentTask,
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCommand, AgentEntry,
AgentEvent, AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentTask, CustomAgentInput, ExternalSession,
McpScope, McpServer, McpServerInput, NewAgentTask,
};
use ide_core::error::ErrorKind;
use ide_core::{IdeError, IdeEvent, IdeResult, IpcPath, RequestId, SharedSink, TaskId};
@@ -304,16 +304,28 @@ pub async fn changes(host: &Host, window: &str, task: String) -> IdeResult<Vec<A
host.project(window)?.agents.changes(&task).await
}
/// The task's uncommitted changes and the commits made since it started.
pub async fn grouped_changes(host: &Host, window: &str, task: String) -> IdeResult<AgentChanges> {
host.require_trust(window)?;
host.project(window)?.agents.grouped_changes(&task).await
}
/// Content of `path` when the task started (left side of its diff).
pub async fn base_text(host: &Host, window: &str, task: String, path: IpcPath) -> IdeResult<Option<String>> {
host.require_trust(window)?;
host.project(window)?.agents.base_text(&task, path.into_path_buf()).await
}
/// Rollback: the task's changed files among `paths` (all without) back as they were when it started.
pub async fn rollback_changes(host: &Host, window: &str, task: String, paths: Option<Vec<String>>) -> IdeResult<()> {
/// Rollback: the task's changed files among `paths` (all without) back as `view` compares them.
pub async fn rollback_changes(
host: &Host,
window: &str,
task: String,
paths: Option<Vec<String>>,
view: Option<AgentChangesView>,
) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.rollback_changes(&task, paths).await
host.project(window)?.agents.rollback_changes(&task, paths, view.unwrap_or_default()).await
}
/// Accept: copies a worktree task's changed files among `paths` (all without) into the
@@ -476,9 +488,10 @@ pub(crate) fn register(d: &mut Dispatcher) {
|c| async move { delete(&c.host, &c.window, c.arg("task")?, c.arg("removeWorktree")?).await },
);
d.add("agent_changes", |c| async move { changes(&c.host, &c.window, c.arg("task")?).await });
d.add("agent_grouped_changes", |c| async move { grouped_changes(&c.host, &c.window, c.arg("task")?).await });
d.add("agent_base_text", |c| async move { base_text(&c.host, &c.window, c.arg("task")?, c.arg("path")?).await });
d.add("agent_rollback_changes", |c| async move {
rollback_changes(&c.host, &c.window, c.arg("task")?, c.arg("paths")?).await
rollback_changes(&c.host, &c.window, c.arg("task")?, c.arg("paths")?, c.arg("view")?).await
});
d.add("agent_accept_changes", |c| async move {
accept_changes(&c.host, &c.window, c.arg("task")?, c.arg("paths")?).await
+46 -10
Переглянути файл
@@ -48,7 +48,7 @@ async fn resolve_launch(
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, delegated) = {
let (model, external, delegated, prefer_maven) = {
let project = project.clone();
let settings = settings.clone();
let module = module.clone();
@@ -58,15 +58,17 @@ async fn resolve_launch(
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;
let delegated = build
&& delegates_to_external_build(
is_maven,
policy,
non_java,
cache::has_record(&project.root, &project.build_cache_dir(), &module),
prefer_maven,
);
let external = non_java || delegated;
(model, external, delegated)
(model, external, delegated, prefer_maven)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -79,6 +81,7 @@ async fn resolve_launch(
tokio::task::spawn_blocking(move || {
let _external_build = external_build;
let built = if delegated {
let policy = delegated_policy(policy, prefer_maven, info.error_count);
let outputs = project.java_launch_snapshots.lock().build(
&project.root,
&model,
@@ -169,6 +172,17 @@ async fn resolve_launch(
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// With Settings › Maven › Delegate IDE build/run actions to Maven, javac's verdict replaces
/// JDT's. Classes JDT wrote for sources with errors look up to date to Maven's incremental
/// compiler, so a launch JDT reports errors for recompiles everything.
fn delegated_policy(policy: BuildPolicy, prefer_maven: bool, jdt_errors: u32) -> BuildPolicy {
if prefer_maven && jdt_errors > 0 && matches!(policy, BuildPolicy::Automatic | BuildPolicy::Make) {
BuildPolicy::Rebuild
} else {
policy
}
}
fn apply_external_build_result(info: &mut JavaLaunchInfo, failure: Option<String>, clean: bool) {
info.build = Some(if let Some(failure) = failure {
info.hints.push(failure);
@@ -241,8 +255,15 @@ fn apply_library_classpath(
/// Whether a launch should be built by the project's build system instead of jdtls.
/// A Rebuild has to clean the output; jdtls' full build only recompiles sources, so
/// Maven modules always delegate for it, even when every source is Java.
fn delegates_to_external_build(is_maven: bool, policy: BuildPolicy, non_java: bool, has_record: bool) -> bool {
is_maven && (policy == BuildPolicy::Rebuild || non_java || has_record)
/// `prefer_maven` is Settings › Maven › Delegate IDE build/run actions to Maven.
fn delegates_to_external_build(
is_maven: bool,
policy: BuildPolicy,
non_java: bool,
has_record: bool,
prefer_maven: bool,
) -> bool {
is_maven && (prefer_maven || policy == BuildPolicy::Rebuild || non_java || has_record)
}
fn same_entry(a: &str, b: &str, windows: bool) -> bool {
@@ -321,14 +342,29 @@ pub(crate) fn register(d: &mut Dispatcher) {
mod tests {
use super::*;
#[test]
fn delegated_launches_with_jdt_errors_recompile_with_maven() {
assert_eq!(delegated_policy(BuildPolicy::Make, true, 1), BuildPolicy::Rebuild);
assert_eq!(delegated_policy(BuildPolicy::Automatic, true, 2), BuildPolicy::Rebuild);
assert_eq!(delegated_policy(BuildPolicy::Make, true, 0), BuildPolicy::Make);
assert_eq!(delegated_policy(BuildPolicy::Make, false, 1), BuildPolicy::Make);
assert_eq!(
delegated_policy(BuildPolicy::MakeAndContinueOnErrors, true, 1),
BuildPolicy::MakeAndContinueOnErrors
);
}
#[test]
fn rebuild_delegates_maven_builds_to_the_build_system() {
assert!(delegates_to_external_build(true, BuildPolicy::Rebuild, false, false));
assert!(delegates_to_external_build(true, BuildPolicy::Automatic, true, false));
assert!(delegates_to_external_build(true, BuildPolicy::Make, false, true));
assert!(!delegates_to_external_build(true, BuildPolicy::Automatic, false, false));
assert!(!delegates_to_external_build(true, BuildPolicy::Make, false, false));
assert!(!delegates_to_external_build(false, BuildPolicy::Rebuild, false, false));
assert!(delegates_to_external_build(true, BuildPolicy::Rebuild, false, false, false));
assert!(delegates_to_external_build(true, BuildPolicy::Automatic, true, false, false));
assert!(delegates_to_external_build(true, BuildPolicy::Make, false, true, false));
assert!(!delegates_to_external_build(true, BuildPolicy::Automatic, false, false, false));
assert!(!delegates_to_external_build(true, BuildPolicy::Make, false, false, false));
assert!(!delegates_to_external_build(false, BuildPolicy::Rebuild, false, false, false));
assert!(delegates_to_external_build(true, BuildPolicy::Automatic, false, false, true));
assert!(delegates_to_external_build(true, BuildPolicy::Make, false, false, true));
assert!(!delegates_to_external_build(false, BuildPolicy::Automatic, false, false, true));
}
#[test]
+6 -4
Переглянути файл
@@ -314,10 +314,12 @@ pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: Got
&& let Some(plugins) = crate::plugins::editor_plugin_host()
{
let project = host.project(window)?;
let (path, version) = project.documents.identity(doc)?;
if let Some(found) = plugins.navigation_at(&project.root, &path, version, pos, Some(window), |p| {
project.documents.by_path(p).and_then(|id| project.documents.version(id).ok())
}) {
// A notebook cell is a language-server document only: no plugin navigates in it.
if let Ok((path, version)) = project.documents.identity(doc)
&& let Some(found) = plugins.navigation_at(&project.root, &path, version, pos, Some(window), |p| {
project.documents.by_path(p).and_then(|id| project.documents.version(id).ok())
})
{
return Ok(found.targets);
}
}
+1
Переглянути файл
@@ -35,6 +35,7 @@ pub mod syntax;
pub mod term;
pub mod tools;
pub mod vcs;
pub mod web;
use crate::Host;
use ide_core::{IdeError, IdeResult};
+8
Переглянути файл
@@ -19,6 +19,13 @@ pub fn get(host: &Host, window: &str, id: String) -> IdeResult<NotebookSnapshot>
host.project(window)?.notebooks.get(&id)
}
/// The language-server documents of the notebook's code cells (empty when no server syncs notebooks).
pub fn cell_docs(host: &Host, window: &str, id: String) -> IdeResult<Vec<ide_lsp::NotebookCellDoc>> {
let project = host.project(window)?;
let path = project.notebooks.path_of(&id)?;
Ok(project.lsp.notebook_cells(&path))
}
pub async fn edit(
host: &Host,
window: &str,
@@ -132,6 +139,7 @@ impl Drop for RequestGuard<'_> {
pub(crate) fn register(d: &mut Dispatcher) {
d.add("notebook_open", |c| async move { open(&c.host, &c.window, c.arg("path")?).await });
d.add("notebook_get", |c| async move { get(&c.host, &c.window, c.arg("id")?) });
d.add("notebook_cell_docs", |c| async move { cell_docs(&c.host, &c.window, c.arg("id")?) });
d.add("notebook_edit", |c| async move {
edit(&c.host, &c.window, c.arg("id")?, c.arg("version")?, c.arg("edit")?).await
});
+12 -1
Переглянути файл
@@ -164,10 +164,21 @@ pub fn set_settings(
// A LightEdit window has no project layer: its values are global.
let project_scope = matches!(scope, SettingsScope::Project) && current.as_ref().is_some_and(|p| !p.light);
let is_proxy = key == "proxy" || key.starts_with("proxy.");
let Some(value) = host.take_proxy_password(key, value)? else {
let Some(mut value) = host.take_proxy_password(key, value)? else {
host.apply_proxy();
return Ok(SettingsApplied { settings: settings(host, window), project_scope, roots_changed: None });
};
// One canonical spelling per linked POM, including a project outside the opened root.
if project_scope
&& key == "languages.java.maven.linkedProjects"
&& let Some(project) = current.as_ref()
&& let Some(list) = value.as_array()
{
let poms: Vec<String> = list.iter().filter_map(|item| item.as_str().map(str::to_owned)).collect();
if poms.len() == list.len() {
value = serde_json::json!(ide_build::maven::normalize_linked_poms(&project.root, &poms));
}
}
let settings = match &current {
Some(p) if project_scope => p.settings.set(scope, key, value)?,
Some(p) => {
+48 -8
Переглянути файл
@@ -3,6 +3,7 @@ use crate::Host;
use ide_core::remote_settings::RunTargetKind;
use ide_core::{IdeError, IdeResult, RunId};
use ide_run::{OutputChunk, RunConfig, RunInfo, StartOptions};
use std::path::Path;
use std::time::Duration;
/// Detected configs followed by user-defined ones (user ids win on conflict).
@@ -138,11 +139,24 @@ pub fn save_configs(
ide_run::save_user_configs_with_removals(&project.root, &configs, removed_detected_ids)
}
/// The project `config` runs in (a workspace member, by its working directory) and its settings.
/// The project `config` runs in (a workspace member, by its working directory) and its
/// settings, with the primary project as the inherited fallback: a member with no Python
/// of its own runs on the primary project's interpreter (see `apply_to_run_configs_in`).
fn settings_for(
host: &Host,
project: &crate::project::Project,
config: &mut RunConfig,
) -> IdeResult<(std::path::PathBuf, ide_core::settings::Settings, Option<std::path::PathBuf>)> {
let (root, settings) = settings_only(host, project, config)?;
let fallback = (root != project.root).then_some(project.root.clone());
Ok((root, settings, fallback))
}
/// [`settings_for`] without the fallback, for callers that only rebase or read settings.
fn settings_only(
host: &Host,
project: &crate::project::Project,
config: &mut RunConfig,
) -> IdeResult<(std::path::PathBuf, ide_core::settings::Settings)> {
let workspace = ide_workspace::workspace::Workspace::load(&project.root)?;
let owner = ide_run::scope::owner(&project.root, config);
@@ -180,8 +194,8 @@ pub fn without_derived(host: &Host, window: &str, configs: Vec<RunConfig>) -> Id
if c.kind == "gradle" {
return Ok(c);
}
let (root, settings) = settings_for(host, &project, &mut c)?;
Ok(ide_sdk::apply::without_derived(&c, &root, &settings))
let (root, settings, fallback) = settings_for(host, &project, &mut c)?;
Ok(ide_sdk::apply::without_derived_in(&c, &root, fallback.as_deref(), &settings))
})
.collect()
}
@@ -194,8 +208,13 @@ pub fn apply_settings(host: &Host, window: &str, configs: Vec<RunConfig>) -> Ide
.into_iter()
.map(|mut c| {
if c.kind != "gradle" {
let (root, settings) = settings_for(host, &project, &mut c)?;
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut c), &root, &settings);
let (root, settings, fallback) = settings_for(host, &project, &mut c)?;
ide_sdk::apply::apply_to_run_configs_in(
std::slice::from_mut(&mut c),
&root,
fallback.as_deref(),
&settings,
);
}
Ok(c)
})
@@ -329,7 +348,7 @@ async fn start_inner(
return host.remote.run(&settings, &project.root, &config, sink.clone(), Box::new(move |c| out(c))).await;
}
let mut config = config;
let (root, settings) = settings_for(host, &project, &mut config)?;
let (root, settings, fallback) = settings_for(host, &project, &mut config)?;
let root = &root;
// Configurations made in the UI name bare tools (`godot`) that may live outside PATH.
// Maven re-applies too: a config listed before a settings change (daemon toggle,
@@ -338,17 +357,38 @@ async fn start_inner(
if config.kind == "maven" {
ide_sdk::apply::prepare_maven_run(&mut config, root, &settings);
} else if matches!(config.kind.as_str(), "gradle" | "tomcat" | "junit") {
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
ide_sdk::apply::apply_to_run_configs_in(
std::slice::from_mut(&mut config),
root,
fallback.as_deref(),
&settings,
);
} else {
ide_sdk::apply::resolve_run_command(&mut config, root, &settings);
}
if config.kind == "go" {
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
ide_sdk::apply::apply_to_run_configs_in(
std::slice::from_mut(&mut config),
root,
fallback.as_deref(),
&settings,
);
ide_sdk::go::apply_to_run(&mut config, &settings.languages.go.build_tags);
}
if config.command == ide_sdk::godot::COMMAND {
return Err(IdeError::unavailable(ide_sdk::godot::NOT_FOUND));
}
// 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
)));
}
if config.kind == "tomcat" {
if host.processes.list().iter().any(|r| r.running && r.config_id == config.id) {
return Err(IdeError::invalid("This Tomcat configuration is already running"));
+8 -1
Переглянути файл
@@ -69,7 +69,14 @@ pub fn sdk_python_effective(host: &Host, window: &str, near: Option<PathBuf>) ->
}
None => (project.root.clone(), project.settings.effective()),
};
Ok(ide_sdk::apply::python_interpreter_near(&root, near.as_deref(), &settings).map(Into::into))
// A member with no Python of its own falls back to the primary project's
// (the same chain run configurations use), so every answer names one interpreter.
let interpreter = ide_sdk::apply::python_interpreter_near(&root, near.as_deref(), &settings).or_else(|| {
(root != project.root)
.then(|| ide_sdk::apply::python_interpreter(&project.root, &project.settings.effective()))
.flatten()
});
Ok(interpreter.map(Into::into))
}
/// The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`.
+18
Переглянути файл
@@ -161,6 +161,23 @@ pub async fn jdk_download(
Ok(sdk)
}
/// The Java version the jdtls this window launches needs; `None` while it isn't
/// installed or doesn't tell.
pub async fn jdtls_required_java(host: &Host, window: &str) -> IdeResult<Option<u32>> {
let settings = match host.project(window) {
Ok(project) => project.settings.effective(),
Err(_) => host.global_settings.effective(),
};
let Some(mut cfg) =
languages(host, window).into_iter().flat_map(|l| l.language_servers).find(|s| s.name == "jdtls")
else {
return Ok(None);
};
ide_sdk::apply::server_launch_overrides(&mut cfg, &settings);
ide_sdk::apply::server_protocol_overrides(&mut cfg, &settings);
tokio::task::spawn_blocking(move || ide_sdk::java::jdtls_required_java(&cfg)).await.map_err(join_err)
}
/// Commands of this module the remote server answers.
pub(crate) fn register(d: &mut Dispatcher) {
d.add("tools_list", |c| async move { tools_list(&c.host, &c.window).await });
@@ -173,6 +190,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
jdk_download_releases(&c.host, &c.window, c.arg("vendor")?, c.arg("request")?).await
});
d.add("jdk_download_location", |c| async move { jdk_download_location(&c.host, &c.window) });
d.add("jdtls_required_java", |c| async move { jdtls_required_java(&c.host, &c.window).await });
d.add("jdk_download", |c| async move {
jdk_download(
&c.host,
+20
Переглянути файл
@@ -373,6 +373,25 @@ pub async fn vcs_file_at(host: &Host, window: &str, path: PathBuf, rev: Option<S
.await
}
/// The file's git mode at `rev` (`100644`, `100755`, `120000`…); `"WT"` reads the
/// worktree's. `None` when the path is absent on that side. The diff viewer shows
/// "File mode changed" when the texts compare equal but the modes differ.
pub async fn vcs_file_mode(host: &Host, window: &str, path: PathBuf, rev: Option<String>) -> IdeResult<Option<String>> {
let project = host.project(window).ok();
let external = host.external_logs.read().get(host.owner_window(window)).and_then(|rs| {
rs.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
});
blocking(move || {
if let Some(project) = project {
return project.with_log_repo_of(&path, |r| r.file_mode_at(&path, rev.as_deref()));
}
external
.ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?
.file_mode_at(&path, rev.as_deref())
})
.await
}
pub async fn vcs_blame(
host: &Host,
window: &str,
@@ -1392,6 +1411,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("vcs_branch_info", |c| async move { vcs_branch_info(&c.host, &c.window, c.arg("repo")?).await });
d.add("vcs_line_hunks", |c| async move { vcs_line_hunks(&c.host, &c.window, c.arg("path")?).await });
d.add("vcs_file_at", |c| async move { vcs_file_at(&c.host, &c.window, c.arg("path")?, c.arg("rev")?).await });
d.add("vcs_file_mode", |c| async move { vcs_file_mode(&c.host, &c.window, c.arg("path")?, c.arg("rev")?).await });
d.add("vcs_blame", |c| async move {
vcs_blame(&c.host, &c.window, c.arg("path")?, c.arg("text")?, c.arg("revision")?).await
});
+11
Переглянути файл
@@ -0,0 +1,11 @@
//! The built-in web server's URLs.
use crate::Host;
use ide_core::IdeResult;
use std::path::Path;
/// The URL serving `file`, under the window's project when it holds the file.
pub async fn url(host: &Host, window: &str, file: &Path) -> IdeResult<String> {
let root = host.project(window).ok().map(|p| p.root.clone());
host.web.url_for(root.as_deref(), file).await
}
+86 -20
Переглянути файл
@@ -111,8 +111,9 @@ pub trait PluginWorkspace: Send + Sync {
/// Version and text of the open document at `path`.
fn document(&self, path: &Path) -> Option<(u64, String)>;
/// Applies `edits` to the open document at `path` if it is still at
/// `version`, as one change (one undo step in the editor).
fn apply_edits(&self, path: &Path, version: u64, edits: &[TextEdit]) -> Result<u64, HostError>;
/// `version`, as one change: one undo step in the editor, or none for a
/// `background` caller (a plugin event rather than a command).
fn apply_edits(&self, path: &Path, version: u64, edits: &[TextEdit], background: bool) -> Result<u64, HostError>;
/// Code from the project may run (git hooks and config on fetch).
fn trusted(&self, root: &Path) -> bool;
/// Root of the project open in `window`.
@@ -180,7 +181,7 @@ impl SecretStore for FileSecretStore {
/// Largest response body a plugin receives.
const MAX_RESPONSE: usize = 8 << 20;
/// Largest stdout / stderr kept from a process.
const MAX_OUTPUT: usize = 4 << 20;
const MAX_OUTPUT: usize = 16 << 20;
/// Most processes one plugin keeps running at once.
const MAX_PROCESSES: usize = 8;
/// Most output one stream of a handle holds until the plugin reads it.
@@ -488,6 +489,7 @@ type SettingSnapshots = BTreeMap<(Option<String>, String), BTreeMap<String, Stri
/// State shared by the host and every plugin's [`PluginApi`].
pub(super) struct Shared {
pub sink: Arc<dyn PluginEventSink>,
pub websockets: super::websocket::WebSocketHub,
pub workspace: RwLock<Option<Arc<dyn PluginWorkspace>>>,
/// `<plugins>/.data`: one directory per plugin id.
pub data_dir: PathBuf,
@@ -565,7 +567,8 @@ impl Shared {
ui,
registry,
locale: RwLock::new("en".into()),
sink,
sink: sink.clone(),
websockets: super::websocket::WebSocketHub::new(sink.clone()),
workspace: RwLock::new(None),
secrets: RwLock::new(Arc::new(FileSecretStore { dir: data_dir.clone() })),
pins,
@@ -775,6 +778,7 @@ impl Shared {
self.kill_processes(plugin);
self.connections.clear(plugin);
self.websockets.disconnect_plugin(plugin);
self.setting_snapshots.lock().retain(|(_, p), _| p != plugin);
let channels: Vec<_> = {
let mut output = self.output.lock();
@@ -2048,13 +2052,14 @@ impl HostApi for PluginApi {
fn apply_edits(
&self,
_client: Option<&str>,
client: Option<&str>,
path: &Path,
version: u64,
edits: Vec<TextEdit>,
) -> Result<u64, HostError> {
let workspace = self.shared.workspace().ok_or_else(|| HostError::NotFound("no project is open".into()))?;
workspace.apply_edits(path, version, &edits)
// Edits from a window's command are undoable; `editor.apply-edits-at` from a background event isn't.
workspace.apply_edits(path, version, &edits, client.is_none())
}
fn storage_get(&self, key: &str) -> Result<Option<String>, HostError> {
@@ -2275,6 +2280,49 @@ impl HostApi for PluginApi {
})
}
fn websocket_connect(
&self,
root: &Path,
request: ide_plugin::WebSocketRequest,
timeout: Duration,
) -> Result<u64, HostError> {
let secrets = self.shared.secrets.read().clone();
let plugin = self.id().to_owned();
let headers = request
.headers
.into_iter()
.map(|(name, value)| {
let value = fill_secrets(&value, |name| secrets.get(&plugin, name))?;
Ok((name, value))
})
.collect::<Result<Vec<_>, HostError>>()?;
net_runtime()
.block_on(self.shared.websockets.connect(
&plugin,
&to_ipc(root),
&request.url,
&headers,
&request.subprotocol,
timeout,
))
.map_err(|error| match error {
super::websocket::ConnectError::Invalid(message) => HostError::Invalid(message),
super::websocket::ConnectError::Failed(message) => HostError::Failed(message),
})
}
fn websocket_send(&self, connection: u64, bytes: Vec<u8>) -> Result<(), HostError> {
self.shared.websockets.send(self.id(), connection, bytes).map_err(HostError::Failed)
}
fn websocket_drain(&self, connection: u64, limit: usize) -> Result<ide_plugin::WebSocketBatch, HostError> {
self.shared.websockets.drain(self.id(), connection, limit).map_err(HostError::Invalid)
}
fn websocket_close(&self, connection: u64) {
let _ = self.shared.websockets.disconnect(self.id(), connection);
}
/// The `net:ask` answer: a host the user allowed with "always" is
/// remembered in the ledger (no dialog again, background included); a new
/// host is asked about in `client`'s window when there is one. Dismissal
@@ -2443,9 +2491,14 @@ impl HostApi for PluginApi {
let read = |pipe: Option<Box<dyn Read + Send>>| {
std::thread::spawn(move || {
let mut out = Vec::new();
let mut overflow = false;
if let Some(p) = pipe {
let mut p = p;
let _ = p.by_ref().take(MAX_OUTPUT as u64).read_to_end(&mut out);
let _ = p.by_ref().take((MAX_OUTPUT + 1) as u64).read_to_end(&mut out);
if out.len() > MAX_OUTPUT {
overflow = true;
out.truncate(MAX_OUTPUT);
}
let _ = std::io::copy(&mut p, &mut std::io::sink());
}
let mut text = String::from_utf8_lossy(&out).into_owned();
@@ -2454,7 +2507,7 @@ impl HostApi for PluginApi {
end -= 1;
}
text.truncate(end);
text
(text, overflow)
})
};
let stdout = read(child.stdout.take().map(|p| Box::new(p) as Box<dyn Read + Send>));
@@ -2474,11 +2527,18 @@ impl HostApi for PluginApi {
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(ProcessOutput {
status: status.code(),
stdout: stdout.join().unwrap_or_default(),
stderr: stderr.join().unwrap_or_default(),
})
let (stdout, stdout_overflow) = stdout.join().unwrap_or_default();
let (stderr, _) = stderr.join().unwrap_or_default();
if stdout_overflow {
tracing::warn!(
plugin = %self.id(),
program = %cmd.program,
limit_mib = MAX_OUTPUT >> 20,
"process stdout exceeded limit"
);
return Err(HostError::Failed(format!("{} stdout exceeded {} MiB limit", cmd.program, MAX_OUTPUT >> 20)));
}
Ok(ProcessOutput { status: status.code(), stdout, stderr })
}
fn subscribe(&self, kind: EventKind) {
@@ -3208,11 +3268,16 @@ impl PluginWorkspace for HostWorkspace {
Some((u64::from(snap.version), snap.text))
}
fn apply_edits(&self, path: &Path, version: u64, edits: &[TextEdit]) -> Result<u64, HostError> {
fn apply_edits(&self, path: &Path, version: u64, edits: &[TextEdit], background: bool) -> Result<u64, HostError> {
let (project, doc) =
self.open_document(path).ok_or_else(|| HostError::NotFound(format!("{} is not open", path.display())))?;
let version = u32::try_from(version).map_err(|_| HostError::Stale)?;
match project.documents.apply_edits_at(doc, version, edits) {
let applied = if background {
project.documents.apply_background_edits_at(doc, version, edits)
} else {
project.documents.apply_edits_at(doc, version, edits)
};
match applied {
Ok(Some(v)) => Ok(u64::from(v)),
Ok(None) => Err(HostError::Stale),
Err(e) if e.kind == ide_core::error::ErrorKind::InvalidInput => Err(HostError::Invalid(e.message)),
@@ -3542,7 +3607,7 @@ mod tests {
fn document(&self, _: &Path) -> Option<(u64, String)> {
None
}
fn apply_edits(&self, _: &Path, _: u64, _: &[TextEdit]) -> Result<u64, HostError> {
fn apply_edits(&self, _: &Path, _: u64, _: &[TextEdit], _: bool) -> Result<u64, HostError> {
Err(HostError::Stale)
}
fn trusted(&self, _: &Path) -> bool {
@@ -3606,7 +3671,7 @@ mod tests {
fn document(&self, _: &Path) -> Option<(u64, String)> {
None
}
fn apply_edits(&self, _: &Path, _: u64, _: &[TextEdit]) -> Result<u64, HostError> {
fn apply_edits(&self, _: &Path, _: u64, _: &[TextEdit], _: bool) -> Result<u64, HostError> {
Err(HostError::Stale)
}
fn trusted(&self, _: &Path) -> bool {
@@ -3807,10 +3872,11 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
let api = shell_api(tmp.path());
let token = CancellationToken::new();
let cmd = shell("head -c 5242880 /dev/zero; head -c 5242880 /dev/zero >&2");
// stdout within the limit comes back whole; stderr beyond it is truncated (stdout beyond it fails).
let cmd = shell(&format!("head -c 5242880 /dev/zero; head -c {} /dev/zero >&2", MAX_OUTPUT + (1 << 20)));
let out = api.run_process(cmd.clone(), None, None, &token, Duration::from_secs(5)).unwrap();
assert_eq!(out.status, Some(0));
assert_eq!((out.stdout.len(), out.stderr.len()), (MAX_OUTPUT, MAX_OUTPUT));
assert_eq!((out.stdout.len(), out.stderr.len()), (5 << 20, MAX_OUTPUT));
let id = api.start_process(cmd, None, None).unwrap();
let out = api.wait_process(id, MAX_PENDING, Duration::from_secs(5), &token).unwrap();
assert_eq!(out.status, Some(0));
@@ -4066,7 +4132,7 @@ mod workbench_tests {
fn document(&self, _: &Path) -> Option<(u64, String)> {
self.text.clone().map(|s| (1, s))
}
fn apply_edits(&self, _: &Path, _: u64, _: &[TextEdit]) -> Result<u64, HostError> {
fn apply_edits(&self, _: &Path, _: u64, _: &[TextEdit], _: bool) -> Result<u64, HostError> {
Err(HostError::Stale)
}
fn trusted(&self, _: &Path) -> bool {
+1 -1
Переглянути файл
@@ -262,7 +262,7 @@ mod tests {
fn project_of(&self, _: &str) -> Option<PathBuf> {
None
}
fn apply_edits(&self, _: &Path, _: u64, _: &[ide_core::TextEdit]) -> Result<u64, HostError> {
fn apply_edits(&self, _: &Path, _: u64, _: &[ide_core::TextEdit], _: bool) -> Result<u64, HostError> {
unreachable!()
}
fn publish_diagnostics(&self, _: &str, _: &Path, _: Vec<ide_core::Diagnostic>) -> Result<(), HostError> {
+29 -6
Переглянути файл
@@ -1,6 +1,7 @@
//! Project-relative event filters, kept with runtime subscriptions across idle reclaim.
use super::{LoadedPlugin, PluginHost};
use globset::{GlobBuilder, GlobMatcher};
use ide_extension::Capability;
use ide_plugin::{EventKind, HostError, WorkbenchEvent};
use std::{
collections::{BTreeSet, HashMap},
@@ -21,9 +22,9 @@ pub(super) struct PathFilter {
impl PathFilter {
pub fn new(kind: &str, globs: Vec<String>) -> Result<Self, HostError> {
if !matches!(kind, "file-opened" | "file-saved" | "files-changed") {
if !matches!(kind, "file-opened" | "file-saved" | "files-changed" | "document-changed") {
return Err(HostError::Invalid(
"subscribe-paths supports file-opened, file-saved and files-changed".into(),
"subscribe-paths supports file-opened, file-saved, files-changed and document-changed".into(),
));
}
if globs.len() > 64 {
@@ -95,13 +96,15 @@ impl PluginHost {
events: &[WorkbenchEvent],
subs: &Subscriptions,
) -> Vec<WorkbenchEvent> {
let Some(filters) = subs.paths.get(plugin.id()) else { return events.to_vec() };
let filters = subs.paths.get(plugin.id());
let workspace = shared.workspace();
events
.iter()
.filter_map(|event| {
if let WorkbenchEvent::FilesChanged(batch) = event {
let Some(filter) = filters.get(event.kind().name()) else { return Some(event.clone()) };
let Some(filter) = filters.and_then(|filters| filters.get(event.kind().name())) else {
return Some(event.clone());
};
let root = workspace.as_ref()?.project_of(client?)?;
if plugin.dev_root.as_deref().is_some_and(|r| r != root) {
return None;
@@ -126,9 +129,9 @@ impl PluginHost {
}
let path = match event {
WorkbenchEvent::FileOpened(path) | WorkbenchEvent::FileSaved(path) => Path::new(path),
WorkbenchEvent::DocumentChanged(change) => Path::new(&change.path),
_ => return Some(event.clone()),
};
let Some(filter) = filters.get(event.kind().name()) else { return Some(event.clone()) };
if !path.is_absolute() {
return None;
}
@@ -147,7 +150,26 @@ impl PluginHost {
if plugin.dev_root.as_deref().is_some_and(|r| r != root) {
return None;
}
filter.matches(&root, path).then(|| event.clone())
if let WorkbenchEvent::DocumentChanged(change) = event {
// Typed text: only for plugins that may read editors, and only for paths they named.
let filter = filters.and_then(|filters| filters.get(event.kind().name()))?;
let granted = &plugin.meta.lock().granted;
if !granted.contains(&Capability::ProjectRead)
|| !granted.contains(&Capability::EditorRead)
|| !filter.matches(&root, path)
{
return None;
}
let real = ide_plugin::resolve_real(path);
let relative = real.strip_prefix(ide_plugin::resolve_real(&root)).ok()?;
let mut change = change.clone();
change.path = relative.to_string_lossy().replace('\\', "/");
return Some(WorkbenchEvent::DocumentChanged(change));
}
filters
.and_then(|filters| filters.get(event.kind().name()))
.is_none_or(|filter| filter.matches(&root, path))
.then(|| event.clone())
})
.collect()
}
@@ -167,6 +189,7 @@ mod tests {
assert!(PathFilter::new("file-saved", vec!["./".repeat(513)]).is_err());
assert!(PathFilter::new("file-saved", vec![]).is_ok());
assert!(PathFilter::new("files-changed", vec![]).is_ok());
assert!(PathFilter::new("document-changed", vec!["src/**/*.rs".into()]).is_ok());
}
#[test]
+7 -1
Переглянути файл
@@ -507,7 +507,13 @@ mod tests {
fn document(&self, _: &Path) -> Option<(u64, String)> {
None
}
fn apply_edits(&self, _: &Path, _: u64, _: &[ide_core::TextEdit]) -> Result<u64, ide_plugin::HostError> {
fn apply_edits(
&self,
_: &Path,
_: u64,
_: &[ide_core::TextEdit],
_: bool,
) -> Result<u64, ide_plugin::HostError> {
unreachable!()
}
fn trusted(&self, _: &Path) -> bool {
+3
Переглянути файл
@@ -41,6 +41,7 @@ pub mod language_features;
mod market;
mod mcp;
pub mod navigation;
mod network_inbox;
mod points;
mod providers;
pub mod remote;
@@ -54,6 +55,7 @@ mod types;
pub mod ui_points;
pub mod views;
pub mod web;
mod websocket;
pub use api::{FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
pub(crate) use hover::merge as merge_hover;
@@ -1921,6 +1923,7 @@ impl PluginHost {
for p in plugins {
let wanted: Vec<WorkbenchEvent> = events
.iter()
.filter(|event| !matches!(event, WorkbenchEvent::WebsocketReady(ready) if ready.plugin_id != p.id()))
.filter(|e| Self::wants(&p, e.kind(), subs.kinds.get(p.id())))
.filter(|e| {
!matches!(e, WorkbenchEvent::FilesChanged(_))
+203
Переглянути файл
@@ -0,0 +1,203 @@
//! Bounded inbox for the proposed background network API.
//!
//! Experimental transport-independent primitive. This module does not expose
//! sockets to plugins. Overflow closes the inbox: silently dropping a document
//! update would make a collaboration session appear healthy while diverging.
use std::collections::VecDeque;
use std::sync::Mutex;
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Push {
/// The caller must schedule one plugin wake-up after releasing this lock.
Wake,
Queued,
/// This message was refused and the caller must schedule a wake-up.
OverflowWake,
/// This message was refused; a wake-up is already pending.
OverflowQueued,
Closed,
}
#[derive(Debug, PartialEq, Eq)]
pub(super) struct Batch {
pub messages: Vec<Vec<u8>>,
pub closed: bool,
pub more: bool,
}
#[derive(Default)]
struct State {
messages: VecDeque<Box<[u8]>>,
bytes: usize,
closed: bool,
notified: bool,
}
pub(super) struct Inbox {
state: Mutex<State>,
max_messages: usize,
max_bytes: usize,
max_frame: usize,
}
impl Inbox {
pub fn new(max_messages: usize, max_bytes: usize, max_frame: usize) -> Self {
assert!(max_messages > 0 && max_bytes > 0 && max_frame > 0);
Self { state: Mutex::new(State::default()), max_messages, max_bytes, max_frame }
}
pub fn push(&self, message: Vec<u8>) -> Push {
let mut state = self.state.lock().unwrap();
if state.closed {
return Push::Closed;
}
let overflow = message.len() > self.max_frame
|| state.messages.len() >= self.max_messages
|| message.len() > self.max_bytes.saturating_sub(state.bytes);
if overflow {
state.closed = true;
} else {
state.bytes += message.len();
state.messages.push_back(message.into_boxed_slice());
}
let wake = !state.notified;
state.notified = true;
match (overflow, wake) {
(false, true) => Push::Wake,
(false, false) => Push::Queued,
(true, true) => Push::OverflowWake,
(true, false) => Push::OverflowQueued,
}
}
/// Returns whether the caller must schedule a wake-up. Idempotent.
pub fn close(&self) -> bool {
let mut state = self.state.lock().unwrap();
if state.closed {
return false;
}
state.closed = true;
let wake = !state.notified;
state.notified = true;
wake
}
/// A partial drain retains the notification; the consumer must continue
/// draining when `more` is true. An empty drain rearms the next wake-up.
pub fn drain(&self, limit: usize) -> Batch {
assert!(limit > 0);
let mut state = self.state.lock().unwrap();
let count = limit.min(state.messages.len());
let messages: Vec<Vec<u8>> = state.messages.drain(..count).map(|message| message.into_vec()).collect();
state.bytes -= messages.iter().map(Vec::len).sum::<usize>();
let more = !state.messages.is_empty();
state.notified = more;
Batch { messages, closed: state.closed, more }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn coalesces_and_rearms_wakeups() {
let inbox = Inbox::new(4, 16, 8);
assert_eq!(inbox.push(vec![1]), Push::Wake);
assert_eq!(inbox.push(vec![2]), Push::Queued);
assert!(inbox.drain(1).more);
assert_eq!(inbox.push(vec![3]), Push::Queued);
assert_eq!(inbox.drain(4).messages, vec![vec![2], vec![3]]);
assert_eq!(inbox.push(vec![4]), Push::Wake);
}
#[test]
fn overflow_preserves_accepted_messages_and_reports_close() {
for (messages, bytes, frame) in [(1, 8, 8), (4, 1, 8), (4, 8, 1)] {
let inbox = Inbox::new(messages, bytes, frame);
assert_eq!(inbox.push(vec![1]), Push::Wake);
assert_eq!(inbox.push(vec![2, 3]), Push::OverflowQueued);
let batch = inbox.drain(4);
assert_eq!(batch.messages, vec![vec![1]]);
assert!(batch.closed);
assert_eq!(inbox.push(vec![]), Push::Closed);
}
}
#[test]
fn accepted_frame_does_not_retain_excess_capacity() {
let inbox = Inbox::new(2, 8, 8);
let mut frame = Vec::with_capacity(1024 * 1024);
frame.push(42);
assert_eq!(inbox.push(frame), Push::Wake);
let state = inbox.state.lock().unwrap();
assert_eq!(state.bytes, 1);
assert_eq!(state.messages[0].len(), 1);
assert_eq!(std::mem::size_of_val(&*state.messages[0]), 1);
}
#[test]
fn close_during_partial_drain_remains_visible_without_duplicate_wakeup() {
let inbox = Inbox::new(3, 12, 4);
assert_eq!(inbox.push(vec![1]), Push::Wake);
assert_eq!(inbox.push(vec![2]), Push::Queued);
let first = inbox.drain(1);
assert_eq!(first.messages, vec![vec![1]]);
assert!(first.more);
assert!(!inbox.close());
let second = inbox.drain(1);
assert_eq!(second.messages, vec![vec![2]]);
assert!(second.closed);
assert!(!second.more);
assert_eq!(inbox.push(vec![3]), Push::Closed);
}
#[test]
fn draining_releases_byte_budget_for_later_messages() {
let inbox = Inbox::new(2, 4, 4);
assert_eq!(inbox.push(vec![1, 2, 3, 4]), Push::Wake);
assert_eq!(inbox.drain(1).messages, vec![vec![1, 2, 3, 4]]);
assert_eq!(inbox.push(vec![5, 6, 7, 8]), Push::Wake);
assert_eq!(inbox.drain(1).messages, vec![vec![5, 6, 7, 8]]);
}
#[test]
fn oversized_first_message_requests_wakeup_and_reports_refusal() {
let inbox = Inbox::new(2, 8, 1);
assert_eq!(inbox.push(vec![1, 2]), Push::OverflowWake);
let batch = inbox.drain(2);
assert!(batch.closed);
assert!(batch.messages.is_empty());
}
#[test]
fn close_wakes_once_even_without_messages() {
let inbox = Inbox::new(4, 16, 8);
assert!(inbox.close());
assert!(!inbox.close());
assert!(inbox.drain(4).closed);
assert_eq!(inbox.push(vec![1]), Push::Closed);
}
#[test]
fn concurrent_producers_remain_bounded_and_fifo_per_producer() {
let inbox = std::sync::Arc::new(Inbox::new(400, 800, 2));
std::thread::scope(|scope| {
for producer in 0..4u8 {
let inbox = inbox.clone();
scope.spawn(move || {
for index in 0..100u8 {
assert_ne!(inbox.push(vec![producer, index]), Push::Closed);
}
});
}
});
let batch = inbox.drain(400);
assert_eq!(batch.messages.len(), 400);
assert!(!batch.closed);
for producer in 0..4u8 {
let sequence: Vec<_> = batch.messages.iter().filter(|m| m[0] == producer).map(|m| m[1]).collect();
assert_eq!(sequence, (0..100u8).collect::<Vec<_>>());
}
}
}
+1
Переглянути файл
@@ -155,6 +155,7 @@ pub fn forwarded(event: &PluginEvent) -> bool {
| PluginEvent::TaskProgress { .. }
| PluginEvent::TaskEnded { .. }
| PluginEvent::SubscriptionsChanged
| PluginEvent::WebsocketReady { .. }
| PluginEvent::ViewChanged { .. }
| PluginEvent::ViewMessage { .. }
| PluginEvent::OpenTerminal { .. }
+3
Переглянути файл
@@ -275,6 +275,9 @@ pub enum PluginEvent {
/// The kinds of workbench events plugins want changed: re-fetch
/// `plugin_event_kinds` (the UI reports only those).
SubscriptionsChanged,
/// A background WebSocket has messages ready for its owning plugin.
#[serde(rename_all = "camelCase")]
WebsocketReady { plugin_id: String, connection: u64 },
#[serde(rename_all = "camelCase")]
ThemeChanged { theme: Option<ActiveTheme> },
/// A plugin needs capabilities the user has not granted yet (first use
+531
Переглянути файл
@@ -0,0 +1,531 @@
//! Host-owned background WebSocket connections for plugins.
use super::{
PluginEvent, PluginEventSink,
network_inbox::{Inbox, Push},
};
use futures::{SinkExt, StreamExt};
use ide_plugin::WebSocketBatch;
use parking_lot::Mutex;
use std::{
collections::HashMap,
sync::{
Arc, Weak,
atomic::{AtomicU64, Ordering},
},
time::Duration,
};
use tokio::sync::{Notify, watch};
use tokio_tungstenite::{
Connector, connect_async_tls_with_config,
tungstenite::{
Message,
client::IntoClientRequest,
http::{HeaderName, HeaderValue},
protocol::WebSocketConfig,
},
};
const MAX_MESSAGES: usize = 256;
const MAX_BYTES: usize = 8 << 20;
const MAX_FRAME: usize = 1 << 20;
const DRAIN_BATCH: usize = 32;
const CLOSED_HANDLE_TTL: Duration = Duration::from_secs(60);
const MAX_CONNECTIONS_PER_PLUGIN: usize = 8;
pub type ConnectionId = u64;
#[derive(Debug, PartialEq, Eq)]
pub enum ConnectError {
Invalid(String),
Failed(String),
}
struct Connection {
plugin: String,
outgoing: Arc<Inbox>,
incoming: Arc<Inbox>,
wake: Notify,
stop: watch::Sender<bool>,
}
struct Inner {
next: AtomicU64,
connections: Mutex<HashMap<ConnectionId, Arc<Connection>>>,
pending: Mutex<HashMap<String, usize>>,
sink: Option<Arc<dyn PluginEventSink>>,
}
#[derive(Clone)]
pub struct WebSocketHub(Arc<Inner>);
impl Default for WebSocketHub {
fn default() -> Self {
Self(Arc::new(Inner {
next: AtomicU64::new(1),
connections: Mutex::new(HashMap::new()),
pending: Mutex::new(HashMap::new()),
sink: None,
}))
}
}
impl WebSocketHub {
pub fn new(sink: Arc<dyn PluginEventSink>) -> Self {
Self(Arc::new(Inner {
next: AtomicU64::new(1),
connections: Mutex::new(HashMap::new()),
pending: Mutex::new(HashMap::new()),
sink: Some(sink),
}))
}
pub async fn connect(
&self,
plugin: &str,
_project: &str,
url: &str,
headers: &[(String, String)],
subprotocol: &str,
timeout: Duration,
) -> Result<ConnectionId, ConnectError> {
validate_url(url).map_err(ConnectError::Invalid)?;
if subprotocol.len() > 256 {
return Err(ConnectError::Invalid("WebSocket subprotocol is too long".into()));
}
if timeout.is_zero() {
return Err(ConnectError::Failed("WebSocket connection timed out".into()));
}
self.reserve(plugin)?;
let result = async {
let mut request =
url.into_client_request().map_err(|_| ConnectError::Invalid("invalid WebSocket URL".into()))?;
for (name, value) in headers {
if protected_header(name) {
return Err(ConnectError::Invalid(format!(
"WebSocket header {name:?} is managed by the handshake"
)));
}
let name: HeaderName =
name.parse().map_err(|_| ConnectError::Invalid("invalid WebSocket header name".into()))?;
let value = HeaderValue::from_str(value)
.map_err(|_| ConnectError::Invalid("invalid WebSocket header value".into()))?;
request.headers_mut().append(name, value);
}
if !subprotocol.is_empty() {
request.headers_mut().insert(
"sec-websocket-protocol",
subprotocol.parse().map_err(|_| ConnectError::Invalid("invalid WebSocket subprotocol".into()))?,
);
}
let config = WebSocketConfig::default()
.read_buffer_size(16 << 10)
.write_buffer_size(16 << 10)
.max_write_buffer_size(2 << 20)
.max_message_size(Some(MAX_FRAME))
.max_frame_size(Some(MAX_FRAME));
let tls = ide_http::client::tls_config()
.map(Arc::new)
.map(Connector::Rustls)
.map_err(|error| ConnectError::Failed(error.message))?;
let (socket, response) =
tokio::time::timeout(timeout, connect_async_tls_with_config(request, Some(config), false, Some(tls)))
.await
.map_err(|_| ConnectError::Failed("WebSocket connection timed out".into()))?
.map_err(|_| ConnectError::Failed("WebSocket connection failed".into()))?;
if !subprotocol.is_empty()
&& response.headers().get("sec-websocket-protocol").and_then(|value| value.to_str().ok())
!= Some(subprotocol)
{
return Err(ConnectError::Failed("WebSocket server did not accept the required subprotocol".into()));
}
let id = self.0.next.fetch_add(1, Ordering::Relaxed);
let (stop, stopped) = watch::channel(false);
let connection = Arc::new(Connection {
plugin: plugin.to_owned(),
outgoing: Arc::new(Inbox::new(MAX_MESSAGES, MAX_BYTES, MAX_FRAME)),
incoming: Arc::new(Inbox::new(MAX_MESSAGES, MAX_BYTES, MAX_FRAME)),
wake: Notify::new(),
stop,
});
self.0.connections.lock().insert(id, connection.clone());
tokio::spawn(run_socket(id, socket, connection, Arc::downgrade(&self.0), stopped));
Ok(id)
}
.await;
self.release(plugin);
result
}
pub fn send(&self, plugin: &str, connection: ConnectionId, bytes: Vec<u8>) -> Result<(), String> {
let connection = self.connection(plugin, connection)?;
match connection.outgoing.push(bytes) {
Push::Wake => {
connection.wake.notify_one();
Ok(())
}
Push::Queued => Ok(()),
Push::OverflowWake => {
connection.wake.notify_one();
Err("WebSocket send queue is full; message was rejected".into())
}
Push::OverflowQueued => Err("WebSocket send queue is full; message was rejected".into()),
Push::Closed => Err("WebSocket connection is closed; message was rejected".into()),
}
}
pub fn drain(&self, plugin: &str, connection: ConnectionId, limit: usize) -> Result<WebSocketBatch, String> {
if limit == 0 || limit > DRAIN_BATCH {
return Err("invalid drain limit".into());
}
let connection_state = self.connection(plugin, connection)?;
let batch = connection_state.incoming.drain(limit);
if batch.more {
self.emit_ready(connection, plugin);
}
if batch.closed && !batch.more {
self.0.connections.lock().remove(&connection);
}
Ok(WebSocketBatch { messages: batch.messages, closed: batch.closed })
}
pub fn disconnect(&self, plugin: &str, id: ConnectionId) -> Result<(), String> {
let connection = self
.0
.connections
.lock()
.get(&id)
.filter(|connection| connection.plugin == plugin)
.cloned()
.ok_or_else(|| "unknown WebSocket connection".to_owned())?;
connection.outgoing.close();
let _ = connection.stop.send(true);
connection.wake.notify_one();
self.0.connections.lock().remove(&id);
Ok(())
}
pub fn disconnect_plugin(&self, plugin: &str) {
let removed: Vec<_> = {
let mut connections = self.0.connections.lock();
let ids: Vec<_> =
connections.iter().filter(|(_, connection)| connection.plugin == plugin).map(|(id, _)| *id).collect();
ids.into_iter().filter_map(|id| connections.remove(&id)).collect()
};
for connection in removed {
connection.outgoing.close();
let _ = connection.stop.send(true);
connection.wake.notify_one();
}
}
fn connection(&self, plugin: &str, id: ConnectionId) -> Result<Arc<Connection>, String> {
self.0
.connections
.lock()
.get(&id)
.filter(|connection| connection.plugin == plugin)
.cloned()
.ok_or_else(|| "unknown WebSocket connection".into())
}
fn reserve(&self, plugin: &str) -> Result<(), ConnectError> {
let open = self.0.connections.lock().values().filter(|connection| connection.plugin == plugin).count();
let mut pending = self.0.pending.lock();
if open + pending.get(plugin).copied().unwrap_or_default() >= MAX_CONNECTIONS_PER_PLUGIN {
return Err(ConnectError::Invalid("at most 8 WebSocket connections per plugin".into()));
}
*pending.entry(plugin.to_owned()).or_default() += 1;
Ok(())
}
fn release(&self, plugin: &str) {
let mut pending = self.0.pending.lock();
if let Some(count) = pending.get_mut(plugin) {
*count -= 1;
if *count == 0 {
pending.remove(plugin);
}
}
}
fn emit_ready(&self, connection: ConnectionId, plugin: &str) {
if let Some(sink) = &self.0.sink {
sink.emit(None, PluginEvent::WebsocketReady { plugin_id: plugin.to_owned(), connection });
}
}
}
fn validate_url(url: &str) -> Result<(), String> {
let parsed = reqwest::Url::parse(url).map_err(|_| "invalid WebSocket URL")?;
// `host_str` keeps an IPv6 address in brackets.
let loopback = parsed.host_str().is_some_and(|host| {
let host = host.trim_start_matches('[').trim_end_matches(']');
host.eq_ignore_ascii_case("localhost") || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
});
if parsed.scheme() != "wss" && !(parsed.scheme() == "ws" && loopback) {
return Err("WebSocket requires WSS outside loopback".into());
}
if !parsed.username().is_empty() || parsed.password().is_some() || parsed.fragment().is_some() {
return Err("WebSocket URLs may not carry credentials or a fragment".into());
}
Ok(())
}
fn protected_header(name: &str) -> bool {
name.eq_ignore_ascii_case("host")
|| name.eq_ignore_ascii_case("connection")
|| name.eq_ignore_ascii_case("upgrade")
|| name.get(.."sec-websocket-".len()).is_some_and(|prefix| prefix.eq_ignore_ascii_case("sec-websocket-"))
}
async fn run_socket<S>(
id: ConnectionId,
socket: tokio_tungstenite::WebSocketStream<S>,
connection: Arc<Connection>,
inner: Weak<Inner>,
mut stopped: watch::Receiver<bool>,
) where
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
{
let (mut writer, mut reader) = socket.split();
loop {
tokio::select! {
_ = connection.wake.notified() => {
let batch = connection.outgoing.drain(DRAIN_BATCH);
let mut failed = false;
for bytes in batch.messages {
if writer.send(Message::Binary(bytes.into())).await.is_err() {
failed = true;
break;
}
}
if failed || batch.closed { break; }
if batch.more { connection.wake.notify_one(); }
}
changed = stopped.changed() => {
if changed.is_err() || *stopped.borrow() {
let mut failed = false;
loop {
let batch = connection.outgoing.drain(DRAIN_BATCH);
for bytes in batch.messages {
if writer.send(Message::Binary(bytes.into())).await.is_err() {
failed = true;
break;
}
}
if failed || !batch.more { break; }
}
break;
}
}
message = reader.next() => match message {
Some(Ok(Message::Binary(bytes))) => {
let pushed = connection.incoming.push(bytes.to_vec());
if matches!(pushed, Push::Wake | Push::OverflowWake)
&& let Some(inner) = inner.upgrade()
&& let Some(sink) = &inner.sink
{
sink.emit(None, PluginEvent::WebsocketReady { plugin_id: connection.plugin.clone(), connection: id });
}
if matches!(pushed, Push::OverflowWake | Push::OverflowQueued | Push::Closed) { break; }
}
Some(Ok(Message::Ping(bytes))) => if writer.send(Message::Pong(bytes)).await.is_err() { break; },
Some(Ok(Message::Close(_))) | Some(Err(_)) | None => break,
_ => {}
}
}
}
let _ = writer.close().await;
connection.outgoing.close();
let wake = connection.incoming.close();
if let Some(inner) = inner.upgrade() {
if wake && let Some(sink) = &inner.sink {
sink.emit(None, PluginEvent::WebsocketReady { plugin_id: connection.plugin.clone(), connection: id });
}
let retained = connection.clone();
tokio::spawn(async move {
tokio::time::sleep(CLOSED_HANDLE_TTL).await;
let mut connections = inner.connections.lock();
if connections.get(&id).is_some_and(|current| Arc::ptr_eq(current, &retained)) {
connections.remove(&id);
}
});
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::net::TcpListener;
use tokio_tungstenite::{
accept_hdr_async,
tungstenite::handshake::server::{ErrorResponse, Request, Response},
};
#[allow(clippy::result_large_err)] // Required by tungstenite's callback signature.
fn accept_test_protocol(request: &Request, mut response: Response) -> Result<Response, ErrorResponse> {
assert_eq!(request.headers()["authorization"], "Bearer test");
assert_eq!(request.headers()["sec-websocket-protocol"], "openidea.test.v1");
response.headers_mut().insert("sec-websocket-protocol", "openidea.test.v1".parse().unwrap());
Ok(response)
}
async fn server() -> (String, tokio::task::JoinHandle<Vec<Vec<u8>>>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("ws://{}/socket", listener.local_addr().unwrap());
let task = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let socket = accept_hdr_async(stream, accept_test_protocol).await.unwrap();
let (_, mut reader) = socket.split();
let mut messages = Vec::new();
while let Ok(Some(message)) = tokio::time::timeout(Duration::from_secs(2), reader.next()).await {
match message.unwrap() {
Message::Binary(bytes) => messages.push(bytes.to_vec()),
Message::Close(_) => break,
_ => {}
}
}
messages
});
(url, task)
}
#[tokio::test]
async fn outbound_message_reaches_the_websocket_server() {
let (url, server) = server().await;
let hub = WebSocketHub::default();
let connection = hub
.connect(
"plugin",
"/project",
&url,
&[("authorization".into(), "Bearer test".into())],
"openidea.test.v1",
Duration::from_secs(1),
)
.await
.unwrap();
hub.send("plugin", connection, b"message".to_vec()).unwrap();
hub.disconnect("plugin", connection).unwrap();
assert_eq!(server.await.unwrap(), [b"message"]);
}
#[tokio::test]
async fn inbound_messages_can_be_drained_and_disconnect_cleans_the_handle() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("ws://{}/socket", listener.local_addr().unwrap());
let server = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let mut socket = accept_hdr_async(stream, accept_test_protocol).await.unwrap();
socket.send(Message::Binary(vec![1, 2, 3].into())).await.unwrap();
socket.close(None).await.unwrap();
});
let hub = WebSocketHub::default();
let connection = hub
.connect(
"plugin",
"/project",
&url,
&[("authorization".into(), "Bearer test".into())],
"openidea.test.v1",
Duration::from_secs(1),
)
.await
.unwrap();
server.await.unwrap();
tokio::time::sleep(Duration::from_millis(20)).await;
assert_eq!(
hub.drain("plugin", connection, 1).unwrap(),
WebSocketBatch { messages: vec![vec![1, 2, 3]], closed: true }
);
assert!(hub.drain("plugin", connection, 1).is_err());
}
#[test]
fn send_rejects_full_queues_without_reporting_success() {
let hub = WebSocketHub::default();
let (stop, _) = watch::channel(false);
let connection = Arc::new(Connection {
plugin: "plugin".into(),
outgoing: Arc::new(Inbox::new(1, MAX_BYTES, MAX_FRAME)),
incoming: Arc::new(Inbox::new(1, MAX_BYTES, MAX_FRAME)),
wake: Notify::new(),
stop,
});
hub.0.connections.lock().insert(1, connection.clone());
assert!(hub.send("other-plugin", 1, b"cross-plugin".to_vec()).is_err());
assert!(hub.drain("other-plugin", 1, 1).is_err());
assert!(hub.send("plugin", 1, b"first".to_vec()).is_ok());
assert!(hub.send("plugin", 1, b"second".to_vec()).unwrap_err().contains("rejected"));
assert_eq!(connection.outgoing.drain(1).messages, [b"first"]);
}
#[test]
fn websocket_urls_require_tls_and_keep_credentials_out_of_the_url() {
assert!(validate_url("wss://relay.example/socket").is_ok());
assert!(validate_url("wss://relay.example/socket?channel=main&token=opaque").is_ok());
assert!(validate_url("ws://127.0.0.1:9000/socket").is_ok());
assert!(validate_url("ws://[::1]:9000/socket").is_ok());
assert!(validate_url("ws://localhost:9000/socket").is_ok());
assert!(validate_url("ws://relay.example/socket").unwrap_err().contains("WSS"));
assert!(validate_url("wss://[email protected]/socket").is_err());
assert!(validate_url("wss://relay.example/socket#fragment").is_err());
assert!(protected_header("Host"));
assert!(protected_header("Connection"));
assert!(protected_header("Upgrade"));
assert!(protected_header("Sec-WebSocket-Key"));
assert!(!protected_header("Cookie"));
assert!(!protected_header("X-API-Key"));
}
#[tokio::test]
#[allow(clippy::result_large_err)] // Required by tungstenite's callback signature.
async fn optional_subprotocol_and_custom_headers_reach_the_handshake() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("ws://{}/socket?channel=main", listener.local_addr().unwrap());
let server = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let mut socket = accept_hdr_async(stream, |request: &Request, response: Response| {
assert_eq!(request.headers()["cookie"], "session=test");
assert_eq!(request.headers()["x-api-key"], "key");
assert!(request.headers().get("sec-websocket-protocol").is_none());
Ok(response)
})
.await
.unwrap();
socket.close(None).await.unwrap();
});
let hub = WebSocketHub::default();
let connection = hub
.connect(
"plugin",
"/project",
&url,
&[("cookie".into(), "session=test".into()), ("x-api-key".into(), "key".into())],
"",
Duration::from_secs(1),
)
.await
.unwrap();
hub.disconnect("plugin", connection).unwrap();
server.await.unwrap();
}
#[test]
fn connection_limit_is_enforced_before_connecting() {
let hub = WebSocketHub::default();
for _ in 0..MAX_CONNECTIONS_PER_PLUGIN {
hub.reserve("plugin").unwrap();
}
assert_eq!(
hub.reserve("plugin"),
Err(ConnectError::Invalid("at most 8 WebSocket connections per plugin".into()))
);
for _ in 0..MAX_CONNECTIONS_PER_PLUGIN {
hub.release("plugin");
}
}
}
+82 -3
Переглянути файл
@@ -69,6 +69,8 @@ pub struct Project {
/// watchers for (a virtualenv elsewhere, a path dependency).
lsp_watchers: Mutex<Vec<(PathBuf, Watcher)>>,
pub(crate) _scratch_watcher: Option<Watcher>,
/// Picks up data sources edited on disk outside the Database tool window.
_db_sources_watch: Option<ide_db::SourcesWatch>,
/// A LightEdit window's loose files ([`Host::open_light`]): global settings only,
/// nothing indexed, no language servers, repositories or project services.
pub light: bool,
@@ -140,6 +142,10 @@ impl Host {
crate::plugins::injections::configure_lsp(&lsp);
lsp.set_execution_allowed(trusted.load(Ordering::Acquire));
lsp.set_content_roots(extra_roots.clone());
lsp.set_jdtls_import_roots(ide_build::maven_external_roots(
&root,
&settings.effective().languages.java.maven.linked_projects,
));
let settings = Arc::new(settings);
{
let settings = settings.clone();
@@ -536,10 +542,12 @@ impl Host {
tracing::info!("opened {} in window {window} in {} ms {laps:?}", root.display(), started.elapsed().as_millis());
let (db, http_history, agents) = self.project_services(&root, &project_key, &settings);
let db_sources_watch = db_sources_watch(&db, &sink, &self.runtime);
let notebooks = crate::notebook::NotebookService::new(
self.local_data_dir.join("notebook-runtime").join(uuid::Uuid::new_v4().to_string()),
sink.clone(),
);
notebooks.set_observer(Arc::new(NotebookLspObserver(lsp.clone())));
ide_agent::registry::maintain(crate::ops::agent::registry_paths(self));
let plugin_diagnostics =
crate::plugins::diagnostics::Diagnostics::new(sink.clone(), self.runtime.clone(), &documents, &root);
@@ -576,6 +584,7 @@ impl Host {
content_watchers: Mutex::new(content_watchers),
lsp_watchers: Mutex::new(Vec::new()),
_scratch_watcher: scratch_watcher,
_db_sources_watch: db_sources_watch,
files_events_active,
light: false,
});
@@ -738,6 +747,7 @@ impl Host {
content_watchers: Mutex::new(Vec::new()),
lsp_watchers: Mutex::new(Vec::new()),
_scratch_watcher: None,
_db_sources_watch: None,
files_events_active: Arc::new(AtomicBool::new(false)),
light: true,
root: dir,
@@ -790,6 +800,28 @@ fn documents(sink: &SharedSink, languages: &Arc<LanguageRegistry>, root: Option<
)
}
/// Data sources edited on disk outside the Database tool window (by hand, by a coding
/// agent): connections made with the old settings close and the tree re-reads them,
/// without reopening the project.
fn db_sources_watch(
db: &Arc<ide_db::DbManager>,
sink: &SharedSink,
runtime: &tokio::runtime::Handle,
) -> Option<ide_db::SourcesWatch> {
let (weak, sink, runtime) = (Arc::downgrade(db), sink.clone(), runtime.clone());
db.watch_sources(Box::new(move || {
let Some(db) = weak.upgrade() else { return };
let sink = sink.clone();
runtime.spawn(async move {
if db.reconcile_sources().await {
sink.emit(IdeEvent::DbSourcesChanged);
}
});
}))
.inspect_err(|e| tracing::warn!("{}", e.message))
.ok()
}
fn light_watcher(
dir: &Path,
sink: &SharedSink,
@@ -1092,6 +1124,10 @@ impl Project {
}
let (roots, excludes) = (self.content_roots(), self.exclude_globs());
self.lsp.set_content_roots(roots.clone());
self.lsp.set_jdtls_import_roots(ide_build::maven_external_roots(
&self.root,
&self.settings.effective().languages.java.maven.linked_projects,
));
self.index.set_scope(index_roots(&self.root, roots.clone()), excludes.clone());
self.watcher.set_excludes(&excludes);
let mut watchers = self.content_watchers.lock();
@@ -1211,8 +1247,9 @@ pub(crate) fn workspace_member_roots(root: &Path) -> Vec<PathBuf> {
.unwrap_or_default()
}
/// Workspace members in manifest order, or extra Project Structure directories and the
/// Gradle project folders outside the project as of the last sync (`build_cache`).
/// Workspace members in manifest order, or extra Project Structure directories, Gradle
/// project folders outside the project, and directories of Maven POMs linked from
/// outside it (`build_cache` is the Gradle sync cache).
fn content_roots(settings: &ide_core::settings::Settings, root: &Path, build_cache: &Path) -> Vec<PathBuf> {
if let Ok(Some(workspace)) = ide_workspace::workspace::Workspace::load(root) {
if workspace.is_container(root) {
@@ -1304,7 +1341,10 @@ fn extra_content_roots(settings: &ide_core::settings::Settings, root: &Path, bui
.iter()
.chain(settings.project_structure.dependencies.iter())
.map(|r| PathBuf::from(r.trim()));
for p in user.chain(ide_build::gradle_external_roots(root, build_cache, &settings.languages.java.gradle)) {
for p in user
.chain(ide_build::gradle_external_roots(root, build_cache, &settings.languages.java.gradle))
.chain(ide_build::maven_external_roots(root, &settings.languages.java.maven.linked_projects))
{
if p.is_absolute() && p.is_dir() && !p.starts_with(root) && !out.contains(&p) {
out.push(p);
}
@@ -1578,6 +1618,25 @@ impl DocumentObserver for LspObserver {
}
}
/// Feeds the code cells of open notebooks to the Python language servers that sync notebooks.
struct NotebookLspObserver(Arc<LspManager>);
impl crate::notebook::NotebookObserver for NotebookLspObserver {
fn changed(&self, path: &Path, snapshot: &ide_notebook::NotebookSnapshot) {
let cells: Vec<ide_lsp::NotebookCell> = snapshot
.cells
.iter()
.filter(|c| c.cell_type == "code")
.map(|c| ide_lsp::NotebookCell { id: c.id.clone(), source: c.source.clone() })
.collect();
// Notebooks run Python kernels only.
self.0.sync_notebook(path, &LanguageId::new("python"), &cells);
}
fn closed(&self, path: &Path) {
self.0.close_notebook(path);
}
}
/// Feeds document edits into the per-project syntax tree cache.
struct SyntaxObserver(Arc<SyntaxCache>);
@@ -1721,6 +1780,26 @@ mod maven_linkage_tests {
assert_eq!(super::jdtls_maven_import(root, &settings).1, None);
}
#[test]
fn external_maven_link_is_a_content_root_and_not_its_sibling_module() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let a = base.join("A");
let b = base.join("B");
let c = base.join("C");
for dir in [&a, &b, &c] {
std::fs::create_dir_all(dir).unwrap();
std::fs::write(dir.join("pom.xml"), "<project/>").unwrap();
}
let mut settings = ide_core::settings::Settings::default();
settings.languages.java.maven.linked_projects = vec!["../B/pom.xml".into()];
assert_eq!(super::content_roots(&settings, &a, &base.join("cache")), vec![b]);
// External links must not replace jdtls's scan of the opened root with a build-file list.
assert_eq!(super::jdtls_maven_import(&a, &settings), (Vec::new(), None));
settings.languages.java.maven.linked_projects.clear();
assert!(super::content_roots(&settings, &a, &base.join("cache")).is_empty());
}
#[test]
fn unlinked_roots_remain_plain_files() {
let tmp = tempfile::tempdir().unwrap();
+1
Переглянути файл
@@ -265,6 +265,7 @@ impl Dispatcher {
ops::run::start_request(&c.host, &c.window, c.arg("config")?, on_output, c.arg("request")?).await
})
.add("run_stop", |c| async move { ops::run::stop(&c.host, &c.window, c.arg("id")?) })
.add("web_url", |c| async move { ops::web::url(&c.host, &c.window, &c.arg::<PathBuf>("path")?).await })
.add("run_stdin", |c| async move { ops::run::stdin(&c.host, c.arg("id")?, &c.arg::<String>("data")?) })
.add("run_resize", |c| async move { ops::run::resize(&c.host, c.arg("id")?, c.arg("cols")?, c.arg("rows")?) })
.add("run_close_stdin", |c| async move { ops::run::close_stdin(&c.host, c.arg("id")?) })
+1
Переглянути файл
@@ -254,6 +254,7 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
| "jdk_download_releases"
| "jdk_download_location"
| "jdk_download"
| "jdtls_required_java"
| "run_system_env"
| "run_gradle_jvm_args_script"
| "proxy_check_connection"
+71
Переглянути файл
@@ -0,0 +1,71 @@
use ide_core::NullSink;
use ide_host::{Host, HostConfig, ops};
use ide_workspace::settings::SettingsScope;
use std::sync::Arc;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn external_maven_link_persists_reloads_and_unlink_keeps_files() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("A");
let sibling = base.join("B");
std::fs::create_dir_all(root.join("core")).unwrap();
std::fs::create_dir_all(&sibling).unwrap();
let a_pom = "<project><artifactId>a</artifactId><packaging>pom</packaging><modules><module>core</module></modules></project>";
let b_pom = "<project><artifactId>b</artifactId></project>";
std::fs::write(root.join("pom.xml"), a_pom).unwrap();
std::fs::write(root.join("core/pom.xml"), "<project><artifactId>core</artifactId></project>").unwrap();
std::fs::write(sibling.join("pom.xml"), b_pom).unwrap();
let config = base.join("config");
let host = Host::new(HostConfig {
config_dir: config.clone(),
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(NullSink)),
owner: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.open_project("main", &root).unwrap();
host.set_project_trust(&root, true, false).await.unwrap();
let written =
serde_json::to_string(&vec!["../B/pom.xml".to_owned(), sibling.join("pom.xml").to_string_lossy().into_owned()])
.unwrap();
ops::project::set_settings(&host, "main", SettingsScope::Project, "languages.java.maven.linkedProjects", &written)
.unwrap();
let saved =
|| ide_workspace::SettingsStore::load(&config, Some(&root)).effective().languages.java.maven.linked_projects;
let canonical = dunce::canonicalize(sibling.join("pom.xml")).unwrap().to_string_lossy().replace('\\', "/");
assert_eq!(saved(), vec![canonical.clone()]);
let model = ops::build::build_model(&host, "main").await.unwrap();
let projects = &model.maven.unwrap().projects;
assert_eq!(projects.iter().filter(|p| p.artifact_id == "a").count(), 1);
let b = projects.iter().find(|p| p.artifact_id == "b").unwrap();
assert!(!b.aggregated);
assert_eq!(b.pom, canonical);
assert_eq!(dunce::canonicalize(root.join(&b.dir)).unwrap(), sibling);
assert_eq!(host.project("main").unwrap().content_roots(), vec![sibling.clone()]);
assert_eq!(host.project("main").unwrap().lsp.jdtls_import_roots(), vec![sibling.clone()]);
let reloaded = ops::build::build_model(&host, "main").await.unwrap();
assert_eq!(
reloaded.maven.unwrap().projects.iter().map(|p| p.pom.clone()).collect::<Vec<_>>(),
projects.iter().map(|p| p.pom.clone()).collect::<Vec<_>>()
);
assert_eq!(saved(), vec![canonical]);
ops::project::set_settings(&host, "main", SettingsScope::Project, "languages.java.maven.linkedProjects", "[]")
.unwrap();
let gone = ops::build::build_model(&host, "main").await.unwrap();
assert!(gone.maven.unwrap().projects.iter().all(|p| p.artifact_id != "b"));
assert!(host.project("main").unwrap().content_roots().is_empty());
assert!(host.project("main").unwrap().lsp.jdtls_import_roots().is_empty());
assert_eq!(saved(), Vec::<String>::new());
assert_eq!(std::fs::read_to_string(root.join("pom.xml")).unwrap(), a_pom);
assert_eq!(std::fs::read_to_string(sibling.join("pom.xml")).unwrap(), b_pom);
host.shutdown().await;
}
+1 -1
Переглянути файл
@@ -39,7 +39,7 @@ impl PluginWorkspace for Workspace {
fn document(&self, _: &Path) -> Option<(u64, String)> {
None
}
fn apply_edits(&self, _: &Path, _: u64, _: &[ide_core::TextEdit]) -> Result<u64, HostError> {
fn apply_edits(&self, _: &Path, _: u64, _: &[ide_core::TextEdit], _: bool) -> Result<u64, HostError> {
Err(HostError::NotFound("not open".into()))
}
fn trusted(&self, _: &Path) -> bool {
+112 -6
Переглянути файл
@@ -154,9 +154,20 @@ impl PluginWorkspace for TestWorkspace {
let snap = self.documents.snapshot(self.documents.by_path(path)?).ok()?;
Some((u64::from(snap.version), snap.text))
}
fn apply_edits(&self, path: &Path, version: u64, edits: &[ide_core::TextEdit]) -> Result<u64, HostError> {
fn apply_edits(
&self,
path: &Path,
version: u64,
edits: &[ide_core::TextEdit],
background: bool,
) -> Result<u64, HostError> {
let doc = self.documents.by_path(path).ok_or_else(|| HostError::NotFound("not open".into()))?;
match self.documents.apply_edits_at(doc, version as u32, edits) {
let applied = if background {
self.documents.apply_background_edits_at(doc, version as u32, edits)
} else {
self.documents.apply_edits_at(doc, version as u32, edits)
};
match applied {
Ok(Some(v)) => Ok(u64::from(v)),
Ok(None) => Err(HostError::Stale),
Err(e) => Err(HostError::Failed(e.message)),
@@ -455,10 +466,10 @@ fn edits_are_refused_when_the_document_changed() {
range: ide_core::Range::new(ide_core::Pos::new(0, 0), ide_core::Pos::new(0, 3)),
new_text: "ONE".into(),
};
assert_eq!(f.workspace.apply_edits(&editor.path, doc.0, std::slice::from_ref(&edit)), Err(HostError::Stale));
assert_eq!(f.workspace.apply_edits(&editor.path, doc.0, std::slice::from_ref(&edit), false), Err(HostError::Stale));
assert_eq!(f.workspace.text("src/notes.txt"), "typed one two three\nfour five\n");
let now = f.workspace.document(&editor.path).unwrap().0;
assert_eq!(f.workspace.apply_edits(&editor.path, now, &[edit]), Ok(now + 1));
assert_eq!(f.workspace.apply_edits(&editor.path, now, &[edit], false), Ok(now + 1));
assert_eq!(f.workspace.text("src/notes.txt"), "ONEed one two three\nfour five\n");
let _ = (
std::any::type_name::<Runtime>(),
@@ -808,6 +819,28 @@ fn a_reporting_task_outlives_its_background_budget() {
assert_eq!((info.status, info.stats.crashes, info.stats.errors), (PluginStatus::Active, 0, 0), "{info:?}");
}
#[test]
fn background_tasks_scale_and_renew_cpu_fuel_budget() {
let f = fixture(Limits {
fuel: 3_500,
timeout: Duration::from_millis(500),
background: Duration::from_millis(5_000),
..Limits::default()
});
f.install(&misbehave_pkg());
if f.host.set_capability("misbehave", "process:git", true).is_err() {
return;
}
// Warm up activation in its own call so `patient` starts with a fresh 3_500-fuel budget.
assert_eq!(f.run("misbehave", "echo", Some("warm")).unwrap().as_deref(), Some("warm"));
let out = f.run("misbehave", "patient", None).expect("background task succeeds").expect("output");
assert_eq!(out, "still here");
let err = f.run("misbehave", "spin", None).unwrap_err();
assert!(err.contains("exceeded its CPU budget (3500 fuel per call)"), "{err}");
}
#[test]
fn private_directory_is_owned_persistent_and_removed_on_uninstall() {
let f = fixture(Limits {
@@ -4807,8 +4840,14 @@ impl PluginWorkspace for EndpointWorkspace {
fn project_of(&self, _: &str) -> Option<PathBuf> {
self.roots.lock().first().cloned()
}
fn apply_edits(&self, path: &Path, version: u64, edits: &[ide_core::TextEdit]) -> Result<u64, HostError> {
self.inner.apply_edits(path, version, edits)
fn apply_edits(
&self,
path: &Path,
version: u64,
edits: &[ide_core::TextEdit],
background: bool,
) -> Result<u64, HostError> {
self.inner.apply_edits(path, version, edits, background)
}
fn publish_diagnostics(
&self,
@@ -6648,6 +6687,73 @@ fn project_write_cannot_replace_the_git_file_of_a_linked_worktree() {
}
}
#[cfg(unix)]
#[test]
fn process_timeout_returns_guest_error_without_disabling_plugin() {
use std::os::unix::fs::PermissionsExt;
let f = fixture(Limits {
timeout: Duration::from_millis(120),
max_failures: 3,
restart_backoff: Duration::ZERO,
..Limits::default()
});
let package = f._tmp.path().join("api14-slow-proc");
copy_dir(&sample("api14"), &package);
let manifest = package.join("plugin.toml");
let text =
std::fs::read_to_string(&manifest).unwrap().replace("optional = [", "optional = [\"process:api14-tool\", ");
std::fs::write(manifest, text).unwrap();
f.install(&package);
let slow = f._tmp.path().join("slow-tool");
std::fs::write(&slow, "#!/bin/sh\nsleep 5\n").unwrap();
std::fs::set_permissions(&slow, std::fs::Permissions::from_mode(0o755)).unwrap();
let slow = slow.canonicalize().unwrap();
f.host.choose_program("api14", "process:api14-tool", Some(&f.project), Some(&slow)).unwrap();
// Even past `max_failures` (3), external subprocess timeouts unwind as guest errors
// instead of poisoning the Wasm instance and disabling the plugin for the session.
for _ in 0..4 {
let err = f.run("api14", "process-run", None).unwrap_err();
assert!(err.contains("api14-tool timed out"), "{err}");
}
let info = f.host.info_of("api14").unwrap();
assert_eq!(info.status, PluginStatus::Active);
assert_eq!(info.stats.crashes, 0);
}
#[cfg(unix)]
#[test]
fn process_stdout_accepts_large_payloads_and_reports_overflow_explicitly() {
use std::os::unix::fs::PermissionsExt;
let f = fixture(Limits { timeout: Duration::from_secs(10), ..Limits::default() });
let package = f._tmp.path().join("api14-large-proc");
copy_dir(&sample("api14"), &package);
let manifest = package.join("plugin.toml");
let text =
std::fs::read_to_string(&manifest).unwrap().replace("optional = [", "optional = [\"process:api14-tool\", ");
std::fs::write(manifest, text).unwrap();
f.install(&package);
let medium_bytes = 5 * 1024 * 1024;
let medium = f._tmp.path().join("medium-tool");
std::fs::write(&medium, "#!/bin/sh\ndd if=/dev/zero bs=1048576 count=5 2>/dev/null | tr '\\0' 'x'\n").unwrap();
std::fs::set_permissions(&medium, std::fs::Permissions::from_mode(0o755)).unwrap();
let medium = medium.canonicalize().unwrap();
f.host.choose_program("api14", "process:api14-tool", Some(&f.project), Some(&medium)).unwrap();
let out = f.run("api14", "process-run", None).unwrap().unwrap();
assert_eq!(out.len(), medium_bytes);
let huge = f._tmp.path().join("huge-tool");
std::fs::write(&huge, "#!/bin/sh\ndd if=/dev/zero bs=1048576 count=17 2>/dev/null | tr '\\0' 'x'\n").unwrap();
std::fs::set_permissions(&huge, std::fs::Permissions::from_mode(0o755)).unwrap();
let huge = huge.canonicalize().unwrap();
f.host.choose_program("api14", "process:api14-tool", Some(&f.project), Some(&huge)).unwrap();
let err = f.run("api14", "process-run", None).unwrap_err();
assert!(err.contains("stdout exceeded 16 MiB limit"), "{err}");
assert_eq!(f.host.info_of("api14").unwrap().stats.crashes, 0);
}
/// A link already in the project is written through, so it is judged by where it points.
#[cfg(unix)]
#[test]
+6
Переглянути файл
@@ -126,6 +126,12 @@ async fn serves_projects_files_documents_search_and_runs() {
let current = invoke(&peer, "project_current", json!({})).await.unwrap();
assert_eq!(current["name"], "demo");
// The built-in web server runs where the project is; the client forwards its port.
let root = std::path::PathBuf::from(opened["root"].as_str().unwrap());
let url = invoke(&peer, "web_url", json!({ "path": root.join("src/main.py") })).await.unwrap();
let url = url.as_str().unwrap();
assert!(url.starts_with("http://127.0.0.1:") && url.ends_with("/demo/src/main.py"), "{url}");
let entries = invoke(&peer, "fs_read_dir", json!({ "path": project })).await.unwrap();
assert!(entries.as_array().unwrap().iter().any(|e| e["name"] == "src"), "{entries}");
+1
Переглянути файл
@@ -53,6 +53,7 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project(
"jdk_download_releases",
"jdk_download_location",
"jdk_download",
"jdtls_required_java",
"scaffold_catalog",
"scaffold_options",
"scaffold_requirements",
+50
Переглянути файл
@@ -105,6 +105,56 @@ async fn linked_projects_share_navigation_but_keep_files_repositories_and_run_di
host.close_project("main");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn python_effective_interpreter_falls_back_to_the_primary_project() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let primary = base.join("primary");
let venv_python =
if cfg!(windows) { primary.join(".venv/Scripts/python.exe") } else { primary.join(".venv/bin/python") };
std::fs::create_dir_all(venv_python.parent().unwrap()).unwrap();
std::fs::write(primary.join(".venv/pyvenv.cfg"), "home = /usr/bin\n").unwrap();
std::fs::write(&venv_python, "").unwrap();
let member = base.join("attached");
std::fs::create_dir_all(member.join("src")).unwrap();
// The primary project with an attached folder (the "attach" flow, not a container workspace).
Workspace::attach(&primary, "Primary", vec![primary.clone(), member.clone()]).unwrap();
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(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&primary, true, false).unwrap();
host.trust.decide(&member, true, false).unwrap();
host.open_project("main", &primary).unwrap();
let python = |near: Option<&std::path::Path>| {
ops::sdk::sdk_python_effective(&host, "main", near.map(|p| p.to_path_buf())).unwrap().map(|p| p.into_path_buf())
};
// The primary project's own virtualenv, and the bare member inheriting it.
assert_eq!(python(Some(&primary)), Some(venv_python.clone()));
assert_eq!(python(Some(&member.join("src"))), Some(venv_python.clone()));
// The member's own settings win: an explicit interpreter configured for it
// (its file is created here — a missing one would be skipped as invalid).
let configured = member.join("selected").join(if cfg!(windows) { "python.exe" } else { "python" });
std::fs::create_dir_all(configured.parent().unwrap()).unwrap();
std::fs::write(&configured, "").unwrap();
ide_workspace::SettingsStore::load(&base.join("config"), Some(&member))
.set(
ide_workspace::SettingsScope::Project,
"languages.python.interpreter",
serde_json::to_value(configured.to_string_lossy().into_owned()).unwrap(),
)
.unwrap();
assert_eq!(python(Some(&member.join("src"))), Some(configured));
host.close_project("main");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn php_language_level_follows_the_member_of_the_file() {
use ide_sdk::php::{PhpLanguageLevel, PhpLevelSource};
+12 -6
Переглянути файл
@@ -29,17 +29,23 @@ pub fn build(proxy: &ProxySettings) -> IdeResult<reqwest::Client> {
build_with_redirect(proxy, reqwest::redirect::Policy::default())
}
/// A client with an explicit redirect policy, for callers enforcing network grants.
pub fn build_with_redirect(proxy: &ProxySettings, redirect: reqwest::redirect::Policy) -> IdeResult<reqwest::Client> {
/// The backend's TLS configuration: ring with the operating system's trust store.
pub fn tls_config() -> IdeResult<rustls::ClientConfig> {
use rustls_platform_verifier::BuilderVerifierExt;
let fail = |e: String| IdeError::internal(format!("HTTP client: {e}"));
let fail = |e: String| IdeError::internal(format!("TLS client: {e}"));
let provider = Arc::new(rustls::crypto::ring::default_provider());
let tls = rustls::ClientConfig::builder_with_provider(provider)
rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.map_err(|e| fail(e.to_string()))?
.with_platform_verifier()
.map_err(|e| fail(e.to_string()))?
.with_no_client_auth();
.map_err(|e| fail(e.to_string()))
.map(|builder| builder.with_no_client_auth())
}
/// A client with an explicit redirect policy, for callers enforcing network grants.
pub fn build_with_redirect(proxy: &ProxySettings, redirect: reqwest::redirect::Policy) -> IdeResult<reqwest::Client> {
let fail = |e: String| IdeError::internal(format!("HTTP client: {e}"));
let tls = tls_config()?;
// `localhost` is tried on IPv4 first: local servers (Ollama, dev servers)
// usually listen there, and on Windows a refused `::1` costs ~2 s before
// the system resolver's order falls back. Ports come from the URL.
+1
Переглянути файл
@@ -55,6 +55,7 @@ tree-sitter-xml = "0.7.0"
tree-sitter-haskell = "0.24.1"
tree-sitter-dart = "0.2.0"
tree-sitter-graphql = "0.3.0"
tree-sitter-prisma-io = "1.6.0"
tree-sitter-gdscript = "6.1.0"
[dev-dependencies]
+40
Переглянути файл
@@ -0,0 +1,40 @@
; Prisma schema highlighting (our captures, not the grammar crate's). Later patterns win.
(identifier) @variable
(developer_comment) @comment
(comment) @comment.doc
(number) @number
(string) @string
[(true) (false) (null)] @keyword
(variable) @property
(column_declaration . (identifier) @property)
(type_expression . (identifier) @variable.parameter)
(enumeral (identifier) @constant)
(column_type (identifier) @type)
(column_type (call_expression (identifier) @type))
(call_expression (identifier) @function)
(model_declaration (identifier) @type)
(view_declaration (identifier) @type)
(type_declaration (identifier) @type)
(type_declaration (type_declaration_type) @type)
(enum_declaration (identifier) @type)
(datasource_declaration (identifier) @type)
(generator_declaration (identifier) @type)
(attribute (identifier) @attribute)
(attribute (call_expression (identifier) @attribute))
(attribute (member_expression (identifier) @attribute (property_identifier) @attribute))
(attribute (call_expression (member_expression (identifier) @attribute (property_identifier) @attribute)))
(block_attribute_declaration (identifier) @attribute)
(block_attribute_declaration (call_expression (identifier) @attribute))
["@" "@@"] @attribute
["datasource" "enum" "generator" "model" "type" "view"] @keyword
["(" ")" "[" "]" "{" "}"] @punctuation.bracket
["," ":" "."] @punctuation.delimiter
(maybe) @operator
"=" @operator
+8
Переглянути файл
@@ -0,0 +1,8 @@
(model_declaration (identifier) @name) @def.class
(view_declaration (identifier) @name) @def.class
(type_declaration . (identifier) @name (statement_block)) @def.struct
(enum_declaration (identifier) @name) @def.enum
(enumeral (identifier) @name) @def.enum_member
(datasource_declaration (identifier) @name) @outline.module
(generator_declaration (identifier) @name) @outline.module
(column_declaration . (identifier) @name) @def.field
+17 -2
Переглянути файл
@@ -5,10 +5,11 @@
use std::path::{Path, PathBuf};
/// The outermost ancestor of `file` containing a root marker, within
/// `project_root` (any ancestor without one: loose files).
/// `project_root` (any ancestor without one: loose files). A directory counts
/// as its own ancestor: a module folder is served like the files in it.
pub fn marked_root(project_root: Option<&Path>, file: &Path, markers: &[String]) -> Option<PathBuf> {
let mut best = None;
for dir in file.ancestors().skip(1) {
for dir in file.ancestors().skip(usize::from(!file.is_dir())) {
if project_root.is_some_and(|root| !dir.starts_with(root)) {
break;
}
@@ -112,6 +113,20 @@ mod tests {
assert_eq!(marked_root(Some(root), &root.join("apps/api/main.ts"), &markers), None);
}
#[test]
fn a_marked_directory_is_its_own_root() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let module = root.join("first");
std::fs::create_dir_all(module.join("src")).unwrap();
std::fs::write(module.join("pom.xml"), "").unwrap();
let markers = vec!["pom.xml".to_string()];
assert_eq!(marked_root(Some(root), &module.join("src/Main.java"), &markers), Some(module.clone()));
assert_eq!(marked_root(Some(root), &module, &markers), Some(module.clone()));
assert_eq!(marked_root(Some(root), &module.join("src"), &markers), Some(module));
assert_eq!(marked_root(Some(root), &root.join("second"), &markers), None);
}
#[test]
fn markers_above_the_project_root_only_count_without_one() {
let tmp = tempfile::tempdir().unwrap();
+2
Переглянути файл
@@ -67,6 +67,7 @@ const BUILTIN: &[(&str, &str)] = &[
("php", include_str!("../../../languages/php.toml")),
("plaintext", include_str!("../../../languages/plaintext.toml")),
("powershell", include_str!("../../../languages/powershell.toml")),
("prisma", include_str!("../../../languages/prisma.toml")),
("properties", include_str!("../../../languages/properties.toml")),
("proto", include_str!("../../../languages/proto.toml")),
("python", include_str!("../../../languages/python.toml")),
@@ -1026,6 +1027,7 @@ mod tests {
("CMakeLists.txt", "cmake"),
("api.proto", "proto"),
("schema.graphql", "graphql"),
("schema.prisma", "prisma"),
("main.tf", "terraform"),
("prod.tfvars", "terraform-vars"),
("job.nomad", "hcl"),
+10
Переглянути файл
@@ -430,6 +430,16 @@ pub(crate) static SPECS: &[Spec] = &[
imports: NONE,
constructors: NONE,
},
Spec {
name: "prisma",
language: tree_sitter_prisma_io::LANGUAGE,
outline: outline!("prisma"),
highlights: Some(Highlights { query: highlights!("prisma"), first_wins: false }),
fold_nodes: NONE,
fold_bodies: NONE,
imports: NONE,
constructors: NONE,
},
Spec {
name: "make",
language: tree_sitter_make::LANGUAGE,
+22
Переглянути файл
@@ -501,6 +501,28 @@ mod tests {
("NEWHOPE", K::Constant),
],
),
(
"prisma",
"// hi\n/// Doc\nmodel User {\n id Int @id @default(autoincrement())\n email String? @db.VarChar(255)\n role Role\n @@index([email])\n}\nenum Role { ADMIN }\ndatasource db {\n provider = \"postgresql\"\n}\n",
&[
("// hi", K::Comment),
("/// Doc", K::DocComment),
("model", K::Keyword),
("User", K::Type),
("id", K::Property),
("Int", K::Type),
("@id", K::Attribute),
("@default", K::Attribute),
("autoincrement", K::FunctionCall),
("VarChar", K::Attribute),
("255", K::Number),
("Role", K::Type),
("@@index", K::Attribute),
("ADMIN", K::Constant),
("provider", K::Property),
("\"postgresql\"", K::String),
],
),
(
"hcl",
"# hi\nresource \"aws_instance\" \"web\" {\n ami = var.ami\n count = 2\n tags = { Name = \"web-${var.env}\" }\n name = upper(\"x\")\n}\n",
+11
Переглянути файл
@@ -886,6 +886,17 @@ fn outline_more_languages() {
Function GetUser
",
);
check_outline(
"prisma",
"datasource db {\n provider = \"sqlite\"\n}\nmodel User {\n id Int @id\n @@map(\"users\")\n}\nenum Role {\n ADMIN\n}\n",
"
Module db
Class User
Field id
Enum Role
EnumMember ADMIN
",
);
check_outline(
"nix",
"{ pkgs, ... }:\nlet\n foo = 1;\n bar = x: x;\nin { inherit foo; }\n",
+51 -1
Переглянути файл
@@ -163,7 +163,9 @@ pub fn client_capabilities() -> Value {
"typeHierarchy": { "dynamicRegistration": false }
},
// rust-analyzer: report when the project has loaded (`quiescent`).
"experimental": { "serverStatusNotification": true }
"experimental": { "serverStatusNotification": true },
// Jupyter notebooks: code cells are synced with `notebookDocument/*` (see `notebook.rs`).
"notebookDocument": { "synchronization": { "dynamicRegistration": false, "executionSummarySupport": false } }
})
}
@@ -426,6 +428,34 @@ impl ServerCaps {
.unwrap_or_default()
}
/// Whether `notebookDocumentSync` takes Jupyter notebooks (`file:`) with cells of `language`:
/// a selector that names no notebook, or `jupyter-notebook` / `*`, and no cell languages or
/// `language` among them.
pub fn syncs_notebooks(&self, language: &str) -> bool {
let Some(selectors) = self.raw.pointer("/notebookDocumentSync/notebookSelector").and_then(Value::as_array)
else {
return false;
};
selectors.iter().any(|s| {
let notebook = match s.get("notebook") {
None | Some(Value::Null) => true,
Some(Value::String(kind)) => kind == "jupyter-notebook" || kind == "*",
Some(filter) => {
filter
.get("notebookType")
.and_then(Value::as_str)
.is_none_or(|t| t == "jupyter-notebook" || t == "*")
&& filter.get("scheme").and_then(Value::as_str).is_none_or(|s| s == "file")
}
};
let cells = match s.get("cells").and_then(Value::as_array) {
None => true,
Some(cells) => cells.iter().any(|c| c.get("language").and_then(Value::as_str) == Some(language)),
};
notebook && cells && (s.get("notebook").is_some() || s.get("cells").is_some())
})
}
/// `workspace.fileOperations.<op>` registration options (`op`: `willRename`, `didRename`).
pub fn file_operation(&self, op: &str) -> Option<&Value> {
self.raw.pointer(&format!("/workspace/fileOperations/{op}")).filter(|v| v.is_object())
@@ -668,6 +698,26 @@ mod tests {
assert_eq!(c.code_action_kinds(), Some(vec!["refactor.inline".into()]));
}
#[test]
fn notebook_sync_selectors() {
let syncs = |selector: Value| {
ServerCaps::parse(json!({ "notebookDocumentSync": { "notebookSelector": [selector] } }))
.syncs_notebooks("python")
};
// basedpyright
assert!(syncs(json!({
"notebook": { "scheme": "file", "notebookType": "jupyter-notebook" }, "cells": [{ "language": "python" }]
})));
// Ruff: any notebook with Python cells.
assert!(syncs(json!({ "cells": [{ "language": "python" }] })));
assert!(syncs(json!({ "notebook": "*" })));
assert!(!syncs(json!({ "notebook": "interactive" })));
assert!(!syncs(json!({ "notebook": { "notebookType": "jupyter-notebook", "scheme": "untitled" } })));
assert!(!syncs(json!({ "cells": [{ "language": "r" }] })));
assert!(!syncs(json!({})));
assert!(!ServerCaps::parse(json!({ "textDocumentSync": 2 })).syncs_notebooks("python"));
}
#[test]
fn language_definitions_use_known_feature_names() {
for lang in ide_language::LanguageRegistry::load(None).unwrap().all() {
+37 -8
Переглянути файл
@@ -966,10 +966,12 @@ pub fn inlay_hint(conv: &Conv, path: &Path, h: lsp::InlayHint) -> InlayHint {
}
}
/// Decodes relative semantic token data into absolute UTF-16 quintuples.
pub fn decode_semantic_tokens(data: &[u32], enc: Encoding, text: Option<&DocText>) -> Vec<u32> {
let mut out = Vec::with_capacity(data.len());
let (mut line, mut start) = (0u32, 0u32);
/// Decodes relative semantic token data into absolute UTF-16 quintuples, sorted by position.
/// Deltas are read as signed because some servers (JDT LS) emit tokens out of order; tokens that
/// land before the document start are dropped and exact duplicates removed.
pub fn decode_semantic_tokens(data: &[i64], enc: Encoding, text: Option<&DocText>) -> Vec<u32> {
let mut out: Vec<[u32; 5]> = Vec::with_capacity(data.len() / 5);
let (mut line, mut start) = (0i64, 0i64);
for &[dl, ds, len, ty, mods] in data.as_chunks::<5>().0 {
if dl == 0 {
start = start.saturating_add(ds);
@@ -977,16 +979,21 @@ pub fn decode_semantic_tokens(data: &[u32], enc: Encoding, text: Option<&DocText
line = line.saturating_add(dl);
start = ds;
}
let (Ok(line), Ok(start), Ok(len)) = (u32::try_from(line), u32::try_from(start), u32::try_from(len)) else {
continue;
};
let (col, len16) = match (enc, text) {
(Encoding::Utf16, _) | (_, None) => (start, len),
(_, Some(t)) => {
let (a, b) = convert_offsets(t.line(line as usize), start as usize, (start + len) as usize, enc);
let (a, b) = convert_offsets(t.line(line as usize), start as usize, start as usize + len as usize, enc);
(a, b - a)
}
};
out.extend_from_slice(&[line, col, len16, ty, mods]);
out.push([line, col, len16, ty as u32, mods as u32]);
}
out
out.sort_by_key(|t| (t[0], t[1]));
out.dedup();
out.into_flattened()
}
pub fn code_lens(conv: &Conv, path: &Path, l: lsp::CodeLens) -> CodeLens {
@@ -1473,7 +1480,7 @@ mod tests {
#[test]
fn semantic_token_decoding() {
let data = [1, 2, 3, 0, 1, 0, 5, 2, 1, 0, 2, 0, 4, 2, 3];
let data: [i64; 15] = [1, 2, 3, 0, 1, 0, 5, 2, 1, 0, 2, 0, 4, 2, 3];
let out = decode_semantic_tokens(&data, Encoding::Utf16, None);
assert_eq!(out, vec![1, 2, 3, 0, 1, 1, 7, 2, 1, 0, 3, 0, 4, 2, 3]);
// UTF-8 server: "😀ab" token "ab" at byte 4 len 2 → utf16 col 2 len 2.
@@ -1481,6 +1488,28 @@ mod tests {
assert_eq!(decode_semantic_tokens(&[0, 4, 2, 0, 0], Encoding::Utf8, Some(&text)), vec![0, 2, 2, 0, 0]);
}
#[test]
fn semantic_tokens_out_of_order() {
// JDT LS for `public class Repro<T extends Number> extends\n ArrayList<T> {`: the bound's
// `extends` comes after `Number`, the superclass is emitted twice and the line goes backwards.
let data: [i64; 95] = [
0, 8, 4, 0, 0, 2, 7, 4, 0, 4096, 0, 5, 4, 0, 4096, 0, 5, 9, 1, 5184, 2, 0, 6, 11, 0, 0, 7, 5, 11, 0, 0, 6,
5, 1, 1104, 0, 6, 1, 6, 16, 0, 10, 6, 1, 65, 0, -8, 7, 11, 0, 1, 8, 9, 1, 1088, 0, 10, 1, 6, 2048, -1, 37,
7, 11, 0, 1, 8, 9, 1, 1088, 0, 10, 1, 6, 2048, 1, 4, 7, 11, 0, 0, 12, 5, 8, 144, 2, 9, 1, 7, 1040, 1, 8, 5,
8, 128,
];
let out = decode_semantic_tokens(&data, Encoding::Utf16, None);
let positions: Vec<(u32, u32)> = out.chunks(5).map(|t| (t[0], t[1])).collect();
#[rustfmt::skip]
assert_eq!(positions, [
(0, 8), (2, 7), (2, 12), (2, 17),
(4, 0), (4, 7), (4, 13), (4, 19), (4, 21), (4, 29), (4, 37),
(5, 8), (5, 18), (6, 4), (6, 16), (8, 9), (9, 8),
]);
// A token that would start before the document is dropped rather than wrapped.
assert_eq!(decode_semantic_tokens(&[0, -1, 2, 0, 0, 0, 5, 1, 0, 0], Encoding::Utf16, None), [0, 4, 1, 0, 0]);
}
#[test]
fn diagnostics_mapping() {
let conv = Conv::utf16();
+9 -1
Переглянути файл
@@ -10,6 +10,7 @@ use ide_core::{IdeEvent, TaskId};
use ide_jsonrpc::{Handler, codes};
use lsp_types as lsp;
use serde_json::{Value, json};
use std::path::PathBuf;
use std::sync::{Arc, Weak};
use std::time::Duration;
@@ -229,7 +230,11 @@ impl ClientHandler {
return;
}
};
let Some(path) = uri_to_path(params.uri.as_str()) else { return };
let Some(path) = uri_to_path(params.uri.as_str())
.or_else(|| crate::notebook::is_cell_uri(params.uri.as_str()).then(|| PathBuf::from(params.uri.as_str())))
else {
return;
};
if self.server.name == "jdtls"
&& let Some(failure) = crate::jdtls::build_plan_failure(&path, &self.server.root, &params.diagnostics)
{
@@ -425,6 +430,9 @@ impl Handler for ClientHandler {
crate::kotlin_lsp::record_import_state(&self.server, self.generation, &params)
}
"language/status" if self.server.name == "jdtls" && params["type"] == "ServiceReady" => {
if self.server.running_gen(self.generation).is_some() {
self.server.set_java_ready();
}
mgr.java_import_ready(self.server.clone(), self.generation);
}
"language/status" if self.server.name == "jdtls" && params["type"] == "ProjectStatus" => {
+100 -15
Переглянути файл
@@ -25,6 +25,7 @@ mod kotlin_lsp;
mod launch;
mod library_source;
mod loading;
mod notebook;
mod pull;
mod scope;
mod server;
@@ -42,6 +43,7 @@ pub use inspect::{FileInspection, InspectHost, InspectOptions};
pub use jdtls::jvm_inspect::JdtJvmInspector;
pub use kotlin_lsp::{KotlinDebugServer, KotlinDebugUnavailable};
pub use launch::{LaunchError, Launcher, ProcessLauncher};
pub use notebook::{NotebookCell, NotebookCellDoc, cell_uri};
pub use scope::{CandidateFiles, CandidateFn, CandidateQuery, MAX_CANDIDATES};
pub use uri::{is_virtual_uri, path_to_uri_string, uri_target, uri_to_path};
@@ -115,6 +117,8 @@ struct DocState {
servers: Vec<Attached>,
/// Open YAML document whose filename does not match a Compose glob and whose content is Compose.
compose_detected: bool,
/// The notebook a code cell belongs to: synced through `notebookDocument/*`, not as a file.
notebook: Option<PathBuf>,
}
impl DocState {
@@ -197,6 +201,10 @@ pub struct LspManager {
me: Weak<LspManager>,
project_root: PathBuf,
content_roots: RwLock<Vec<PathBuf>>,
/// Maven projects linked from outside `project_root`. jdtls scans them as extra
/// workspace folders; `projectConfigurations` stays unset so the opened root is
/// still discovered automatically.
jdtls_import_roots: RwLock<Vec<PathBuf>>,
languages: Arc<LanguageRegistry>,
sink: SharedSink,
launcher: Arc<dyn Launcher>,
@@ -229,6 +237,8 @@ pub struct LspManager {
/// Contents fetched for virtual URIs.
virtual_docs: Mutex<HashMap<String, VirtualDocument>>,
injections: injections::State,
/// Open notebooks by path. Locked before `docs` when both are.
notebooks: Mutex<HashMap<PathBuf, notebook::NotebookState>>,
}
/// Fetched virtual documents kept before the cache is reset.
@@ -438,6 +448,7 @@ impl LspManager {
me: me.clone(),
project_root,
content_roots: RwLock::new(Vec::new()),
jdtls_import_roots: RwLock::new(Vec::new()),
languages,
sink: {
let me = me.clone();
@@ -476,6 +487,7 @@ impl LspManager {
virtual_origins: Mutex::new(HashMap::new()),
virtual_docs: Mutex::new(HashMap::new()),
injections: injections::State::default(),
notebooks: Mutex::new(HashMap::new()),
})
}
@@ -496,6 +508,28 @@ impl LspManager {
}
}
/// Directories of Maven projects linked from outside the opened root. The jdtls
/// rooted at the opened project scans them together with that root. An empty list
/// leaves discovery as the single `rootUri` scan.
pub fn set_jdtls_import_roots(&self, mut roots: Vec<PathBuf>) {
roots.retain(|root| root.is_absolute() && root.is_dir() && !root.starts_with(&self.project_root));
roots.sort();
roots.dedup();
let changed = {
let mut current = self.jdtls_import_roots.write();
let changed = *current != roots;
*current = roots;
changed
};
if changed && let Some(me) = self.me.upgrade() {
me.reconfigure_soon();
}
}
pub fn jdtls_import_roots(&self) -> Vec<PathBuf> {
self.jdtls_import_roots.read().clone()
}
/// Shares JDT LS within this manager; callers reconfigure after the hook's value changes.
pub fn set_jdtls_shared_hook(&self, hook: Box<JdtlsSharedFn>) {
*self.jdtls_shared_hook.write() = Some(Arc::from(hook));
@@ -530,10 +564,29 @@ impl LspManager {
if state.shared {
return state.roots.clone();
}
// The opened project's server also scans linked external Maven projects.
// Other in-root builds keep their own server and their own root.
if server.root == self.project_root {
return self.project_and_import_roots();
}
}
vec![server.root.clone()]
}
fn project_and_import_roots(&self) -> Vec<PathBuf> {
let mut roots = vec![self.project_root.clone()];
for root in self.jdtls_import_roots.read().iter() {
if root.is_absolute() && root.is_dir() && !roots.contains(root) {
roots.push(root.clone());
}
}
roots
}
fn imports_external_java(&self, config: &LanguageServerConfig, path: &Path) -> bool {
is_local_jdtls(config) && self.jdtls_import_roots.read().iter().any(|root| path.starts_with(root))
}
fn project_root_for(&self, path: &Path) -> PathBuf {
self.content_roots
.read()
@@ -550,7 +603,9 @@ impl LspManager {
let mut servers = self.servers.lock();
let project = self.project_root_for(path);
let sketch = (cfg.name == arduino::SERVER).then(|| arduino::sketch_root(&project, path)).flatten();
let root = if shared.as_ref().is_some_and(|state| state.shared) {
let root = if shared.as_ref().is_some_and(|state| state.shared) || self.imports_external_java(cfg, path) {
// One server for the opened root and a linked external Maven project, so
// Java completion and navigation see the import jdtls made of both.
self.project_root.clone()
} else {
sketch.or_else(|| launch::find_root(&project, path, &cfg.root_markers)).unwrap_or_else(|| {
@@ -614,8 +669,13 @@ impl LspManager {
/// enabled in settings.
fn attach_fallbacks(&self) {
let _gate = self.injections.gate.lock();
let open: Vec<(DocId, LanguageId, PathBuf)> =
self.docs.lock().iter().map(|(id, d)| (*id, d.language.clone(), d.path.clone())).collect();
let open: Vec<(DocId, LanguageId, PathBuf)> = self
.docs
.lock()
.iter()
.filter(|(_, d)| d.notebook.is_none())
.map(|(id, d)| (*id, d.language.clone(), d.path.clone()))
.collect();
let wanted: Vec<(DocId, Vec<Arc<Server>>)> =
open.into_iter().map(|(id, language, path)| (id, self.servers_for(&language, &path))).collect();
let mut start = Vec::new();
@@ -648,6 +708,11 @@ impl LspManager {
for (doc, server) in opened {
self.schedule_pull(doc, Some(&server), Duration::ZERO);
}
for server in self.attach_notebook_servers() {
if !start.iter().any(|s| s.id == server.id) {
start.push(server);
}
}
for server in &start {
self.ensure_started(server);
}
@@ -756,7 +821,7 @@ impl LspManager {
Err(LaunchError::Missing) => {
let cfg = server.effective_config();
let message =
cfg.install_hint.clone().unwrap_or_else(|| format!("`{}` was not found on PATH", cfg.command));
cfg.install_hint.clone().unwrap_or_else(|| format!("{} was not found on PATH", cfg.command));
if server.fail_start(
generation,
Conn::Missing,
@@ -867,7 +932,7 @@ impl LspManager {
false
} else {
let open_close = run.caps.read().open_close;
for (id, d) in docs.iter_mut() {
for (id, d) in docs.iter_mut().filter(|(_, d)| d.notebook.is_none()) {
let params = d.did_open_params();
for a in
d.servers.iter_mut().filter(|a| a.server.id == server.id && a.opened_gen != Some(generation))
@@ -889,6 +954,7 @@ impl LspManager {
for doc in reopened {
self.schedule_pull(doc, Some(&server), Duration::ZERO);
}
self.reopen_notebooks(&server, &run);
self.check_clang_tidy(&server).await;
self.check_vue_navigation(&server).await;
server.refresh_busy_status(&self.sink);
@@ -935,13 +1001,15 @@ impl LspManager {
}
init_options["settings"] = handler::all_settings(&cfg);
let shared = is_local_jdtls(&server.config) && self.jdtls_workspace_state().shared;
if shared {
init_options["workspaceFolders"] = json!(
self.server_workspace_roots(server)
.iter()
.map(|root| uri::path_to_uri_string(root))
.collect::<Vec<_>>()
);
// jdtls imports `initializationOptions.workspaceFolders` by scanning each
// directory. It ignores the LSP workspace folder list for that first import,
// and a `projectConfigurations` list replaces the scan. Extra Maven projects
// are therefore folders here, not an explicit build-file list, so projects
// under the opened root are still discovered.
let folders: Vec<String> =
self.server_workspace_roots(server).iter().map(|root| uri::path_to_uri_string(root)).collect();
if shared || folders.len() > 1 {
init_options["workspaceFolders"] = json!(folders);
}
let triggers: Vec<_> = self
.docs
@@ -1083,6 +1151,7 @@ impl LspManager {
text: Arc::new(DocText::new(text)),
servers: servers.iter().map(|s| Attached { server: s.clone(), opened_gen: None }).collect(),
compose_detected,
notebook: None,
};
let compose_added = {
let mut docs = self.docs.lock();
@@ -1214,7 +1283,7 @@ impl LspManager {
return;
}
let docs = self.docs.lock();
for d in docs.values() {
for d in docs.values().filter(|d| d.notebook.is_none()) {
if !d.servers.iter().any(|a| a.server.id == server.id && a.opened_gen == Some(generation)) {
continue;
}
@@ -1288,13 +1357,23 @@ impl LspManager {
fn snapshot(&self, doc: DocId) -> IdeResult<DocSnap> {
let docs = self.docs.lock();
let d = docs.get(&doc).ok_or_else(|| IdeError::not_found(format!("{doc} is not open")))?;
// A cell is asked only of the servers its notebook is open on (those that sync notebooks).
let servers = d
.servers
.iter()
.filter(|a| {
d.notebook.is_none()
|| a.opened_gen.is_some_and(|g| a.server.running().is_some_and(|run| run.generation == g))
})
.map(|a| a.server.clone())
.collect();
Ok(DocSnap {
version: d.version,
path: d.path.clone(),
uri: d.uri.clone(),
language: d.language.clone(),
text: d.text.clone(),
servers: d.servers.iter().map(|a| a.server.clone()).collect(),
servers,
})
}
@@ -2822,7 +2901,7 @@ impl LspManager {
let params = json!({ "textDocument": snap.ident() });
let r: Option<Value> = self.call(t, "textDocument/semanticTokens/full", params, None, DEFAULT_TIMEOUT).await?;
let Some(data) = r.as_ref().and_then(|v| v.get("data")).and_then(Value::as_array) else { return Ok(None) };
let data: Vec<u32> = data.iter().map(|n| n.as_u64().unwrap_or(0) as u32).collect();
let data: Vec<i64> = data.iter().map(|n| n.as_i64().unwrap_or(0)).collect();
let (enc, legend) = {
let caps = t.caps();
(caps.encoding, caps.semantic_legend.clone().unwrap_or_default())
@@ -3490,11 +3569,17 @@ impl LspManager {
join_all(servers.iter().map(|s| self.stop_instance(s, true))).await;
return;
}
let existing: Vec<ide_core::ServerId> = self.servers.lock().iter().map(|s| s.id).collect();
self.reconfigure_jdtls_workspace().await;
self.stop_unlisted().await;
let Some(me) = self.me.upgrade() else { return };
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
for s in servers {
// Created in this pass (the jdtls of a new workspace layout): it starts with the
// current configuration, though it may not have recorded it yet.
if !existing.contains(&s.id) {
continue;
}
// The settings hook may run tools (`npm root -g`), as when the server starts.
let next = match tokio::task::spawn_blocking({
let (me, s) = (me.clone(), s.clone());
+382
Переглянути файл
@@ -0,0 +1,382 @@
//! Jupyter notebooks on servers that sync them with LSP 3.17 `notebookDocument/*` (basedpyright,
//! Ruff). Each code cell is a document of its own, `vscode-notebook-cell:<notebook path>#<cell id>`,
//! kept in `docs` under a [`DocId`]: completion, hover and the other requests address a cell like
//! any open file. Only opening, changing and closing go through the notebook methods; a change in
//! the cells' order closes and reopens the notebook.
use crate::server::{Running, Server};
use crate::text::DocText;
use crate::{Attached, DocState, LspManager, uri};
use ide_core::{DocId, LanguageId, ServerId};
use lsp_types as lsp;
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
use serde::Serialize;
use serde_json::{Value, json};
use specta::Type;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Arc;
const CELL_SCHEME: &str = "vscode-notebook-cell";
const NOTEBOOK_TYPE: &str = "jupyter-notebook";
/// `NotebookCellKind.Code`.
const CODE_CELL: u32 = 2;
/// Escaped in a cell id: nbformat ids are `[a-zA-Z0-9-_]`, older notebooks may have others.
const FRAGMENT: &AsciiSet = &NON_ALPHANUMERIC.remove(b'-').remove(b'_');
/// A code cell as the notebook holds it.
pub struct NotebookCell {
pub id: String,
pub source: String,
}
/// The document the language servers know a code cell by.
#[derive(Clone, Debug, PartialEq, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct NotebookCellDoc {
pub cell: String,
pub doc: DocId,
/// Also the `path` of the cell's diagnostics and of locations in it.
pub uri: String,
}
pub(crate) struct NotebookState {
uri: lsp::Uri,
language: LanguageId,
version: i32,
/// Code cells in notebook order.
cells: Vec<(String, DocId)>,
servers: Vec<Arc<Server>>,
/// Servers it is open on, by instance generation.
opened: Vec<(ServerId, u64)>,
}
/// The URI of cell `cell` of the notebook at `path`: the notebook's `file:` URI with the cell
/// scheme and the cell id as fragment (as VS Code names cells; basedpyright expects the scheme).
pub fn cell_uri(path: &Path, cell: &str) -> String {
let file = uri::path_to_uri_string(path);
let rest = file.strip_prefix("file://").unwrap_or(&file);
// `file:///C:/a` → `…:/C:/a`; a share (`file://server/s/a`) keeps its authority.
let authority = if rest.starts_with('/') { "" } else { "//" };
format!("{CELL_SCHEME}:{authority}{rest}#{}", utf8_percent_encode(cell, FRAGMENT))
}
pub(crate) fn is_cell_uri(uri: &str) -> bool {
uri.strip_prefix(CELL_SCHEME).is_some_and(|rest| rest.starts_with(':'))
}
fn parse_uri(s: &str) -> Option<lsp::Uri> {
lsp::Uri::from_str(s).inspect_err(|e| tracing::debug!("not a valid URI {s}: {e}")).ok()
}
impl NotebookState {
fn opened_on(&self, server: ServerId, generation: u64) -> bool {
self.opened.contains(&(server, generation))
}
/// The servers it is open on whose instance is still the one it was opened on.
fn open_targets(&self) -> Vec<(Arc<Server>, Running)> {
self.servers
.iter()
.filter_map(|s| {
let run = s.running()?;
self.opened_on(s.id, run.generation).then(|| (s.clone(), run))
})
.collect()
}
}
impl LspManager {
/// Opens the notebook at `path` on its language's servers that sync notebooks, or brings
/// them up to date with `cells` (its code cells, in order).
pub fn sync_notebook(&self, path: &Path, language: &LanguageId, cells: &[NotebookCell]) {
let mut notebooks = self.notebooks.lock();
let mut changed = Vec::new();
let start = match notebooks.get_mut(path) {
None => {
let Some(notebook_uri) = parse_uri(&uri::path_to_uri_string(path)) else { return };
let servers = self.servers_for(language, path);
let mut state = NotebookState {
uri: notebook_uri,
language: language.clone(),
version: 1,
cells: Vec::new(),
servers: servers.clone(),
opened: Vec::new(),
};
self.set_cells(path, &mut state, cells);
self.open_notebook(&mut state, None);
notebooks.insert(path.to_owned(), state);
servers
}
Some(state) => {
let same_cells =
state.cells.len() == cells.len() && state.cells.iter().zip(cells).all(|((id, _), c)| *id == c.id);
if same_cells {
changed = self.change_cells(state, cells);
} else {
self.close_notebook_on_servers(state);
state.version += 1;
self.set_cells(path, state, cells);
self.open_notebook(state, None);
}
Vec::new()
}
};
drop(notebooks);
for server in &start {
self.ensure_started(server);
}
for doc in changed {
self.schedule_pull(doc, None, crate::pull::AFTER_EDIT);
}
}
/// Closes the notebook at `path` on its servers and forgets its cells.
pub fn close_notebook(&self, path: &Path) {
let Some(mut state) = self.notebooks.lock().remove(path) else { return };
self.close_notebook_on_servers(&mut state);
let removed: Vec<DocId> = state.cells.iter().map(|(_, doc)| *doc).collect();
self.remove_cells(&state.servers, &removed);
}
/// The documents of the notebook's code cells, in notebook order; empty when it isn't open.
pub fn notebook_cells(&self, path: &Path) -> Vec<NotebookCellDoc> {
let notebooks = self.notebooks.lock();
let Some(state) = notebooks.get(path) else { return Vec::new() };
let docs = self.docs.lock();
state
.cells
.iter()
.filter_map(|(cell, doc)| {
Some(NotebookCellDoc { cell: cell.clone(), doc: *doc, uri: docs.get(doc)?.uri.as_str().to_owned() })
})
.collect()
}
/// Opens the notebooks of `server`'s language on its instance that just became ready.
pub(crate) fn reopen_notebooks(&self, server: &Arc<Server>, run: &Running) {
let mut pull = Vec::new();
{
let mut notebooks = self.notebooks.lock();
for state in notebooks.values_mut() {
if state.servers.iter().any(|s| s.id == server.id) && !state.opened_on(server.id, run.generation) {
self.open_notebook(state, Some(server));
pull.extend(state.cells.iter().map(|(_, doc)| *doc));
}
}
}
for doc in pull {
self.schedule_pull(doc, Some(server), std::time::Duration::ZERO);
}
}
/// Adds servers of the notebooks' languages that were not wanted when they opened (a
/// fallback for a missing server, one enabled in settings) and returns them to be started.
pub(crate) fn attach_notebook_servers(&self) -> Vec<Arc<Server>> {
let mut start = Vec::new();
let mut notebooks = self.notebooks.lock();
for (path, state) in notebooks.iter_mut() {
let added: Vec<Arc<Server>> = self
.servers_for(&state.language, path)
.into_iter()
.filter(|s| !state.servers.iter().any(|known| known.id == s.id))
.collect();
if added.is_empty() {
continue;
}
{
let mut docs = self.docs.lock();
for (_, doc) in &state.cells {
if let Some(d) = docs.get_mut(doc) {
d.servers.extend(added.iter().map(|s| Attached { server: s.clone(), opened_gen: None }));
}
}
}
state.servers.extend(added.iter().cloned());
for server in &added {
self.open_notebook(state, Some(server));
}
start.extend(added);
}
start
}
/// Replaces the cell documents with `cells`: kept cells keep their [`DocId`].
fn set_cells(&self, path: &Path, state: &mut NotebookState, cells: &[NotebookCell]) {
let mut docs = self.docs.lock();
let previous = std::mem::take(&mut state.cells);
for cell in cells {
let kept = previous.iter().find(|(id, _)| *id == cell.id).map(|(_, doc)| *doc);
if let Some(doc) = kept
&& let Some(d) = docs.get_mut(&doc)
{
if d.text.as_str() != cell.source {
Arc::make_mut(&mut d.text).set(&cell.source);
}
d.version += 1;
state.cells.push((cell.id.clone(), doc));
continue;
}
let uri_string = cell_uri(path, &cell.id);
let Some(cell_uri) = parse_uri(&uri_string) else { continue };
let doc = DocId::next();
let key = PathBuf::from(&uri_string);
docs.insert(
doc,
DocState {
canonical: key.clone(),
path: key,
uri: cell_uri,
language: state.language.clone(),
version: 1,
text: Arc::new(DocText::new(&cell.source)),
servers: state.servers.iter().map(|s| Attached { server: s.clone(), opened_gen: None }).collect(),
compose_detected: false,
notebook: Some(path.to_owned()),
},
);
state.cells.push((cell.id.clone(), doc));
}
drop(docs);
let removed: Vec<DocId> = previous
.into_iter()
.filter(|(_, doc)| !state.cells.iter().any(|(_, d)| d == doc))
.map(|(_, d)| d)
.collect();
self.remove_cells(&state.servers, &removed);
}
/// Sends the cells whose text differs from `cells` as one change; returns their documents.
fn change_cells(&self, state: &mut NotebookState, cells: &[NotebookCell]) -> Vec<DocId> {
let mut docs = self.docs.lock();
let mut changed = Vec::new();
let mut content = Vec::new();
for ((_, doc), cell) in state.cells.iter().zip(cells) {
let Some(d) = docs.get_mut(doc) else { continue };
if d.text.as_str() == cell.source {
continue;
}
Arc::make_mut(&mut d.text).set(&cell.source);
d.version += 1;
content.push(json!({
"document": { "uri": d.uri, "version": d.version },
"changes": [{ "text": cell.source }],
}));
changed.push(*doc);
}
drop(docs);
if content.is_empty() {
return changed;
}
state.version += 1;
let params = json!({
"notebookDocument": { "uri": state.uri, "version": state.version },
"change": { "cells": { "textContent": content } },
});
for (server, run) in state.open_targets() {
if let Err(e) = run.peer.notify("notebookDocument/didChange", params.clone()) {
tracing::debug!("{}: notebookDocument/didChange: {e}", server.name);
}
}
changed
}
/// Opens the notebook on its running servers that sync notebooks (`only`: on that one).
fn open_notebook(&self, state: &mut NotebookState, only: Option<&Arc<Server>>) {
let mut docs = self.docs.lock();
let mut cells = Vec::new();
let mut texts = Vec::new();
for (_, doc) in &state.cells {
let Some(d) = docs.get(doc) else { continue };
cells.push(json!({ "kind": CODE_CELL, "document": d.uri }));
texts.push(json!({
"uri": d.uri,
"languageId": d.language.as_str(),
"version": d.version,
"text": d.text.as_str(),
}));
}
let params = json!({
"notebookDocument": { "uri": state.uri, "notebookType": NOTEBOOK_TYPE, "version": state.version, "cells": cells },
"cellTextDocuments": texts,
});
let servers: Vec<Arc<Server>> =
state.servers.iter().filter(|s| only.is_none_or(|o| o.id == s.id)).cloned().collect();
for server in servers {
let Some(run) = server.running() else { continue };
if state.opened_on(server.id, run.generation) || !run.caps.read().syncs_notebooks(state.language.as_str()) {
continue;
}
if let Err(e) = run.peer.notify("notebookDocument/didOpen", params.clone()) {
tracing::debug!("{}: notebookDocument/didOpen: {e}", server.name);
continue;
}
state.opened.retain(|(id, _)| *id != server.id);
state.opened.push((server.id, run.generation));
for (_, doc) in &state.cells {
if let Some(a) = docs.get_mut(doc).and_then(|d| d.servers.iter_mut().find(|a| a.server.id == server.id))
{
a.opened_gen = Some(run.generation);
}
}
}
}
fn close_notebook_on_servers(&self, state: &mut NotebookState) {
let cells: Vec<Value> = {
let docs = self.docs.lock();
state.cells.iter().filter_map(|(_, doc)| docs.get(doc)).map(|d| json!({ "uri": d.uri })).collect()
};
let params = json!({ "notebookDocument": { "uri": state.uri }, "cellTextDocuments": cells });
for (server, run) in state.open_targets() {
if let Err(e) = run.peer.notify("notebookDocument/didClose", params.clone()) {
tracing::debug!("{}: notebookDocument/didClose: {e}", server.name);
}
}
state.opened.clear();
let mut docs = self.docs.lock();
for (_, doc) in &state.cells {
if let Some(d) = docs.get_mut(doc) {
d.servers.iter_mut().for_each(|a| a.opened_gen = None);
}
}
}
/// Forgets cell documents and clears what their servers reported about them: a server need
/// not clear the diagnostics of a cell that left the notebook.
fn remove_cells(&self, servers: &[Arc<Server>], removed: &[DocId]) {
let gone: Vec<DocState> = {
let mut docs = self.docs.lock();
removed.iter().filter_map(|doc| docs.remove(doc)).collect()
};
for d in gone {
for server in servers {
let run = server.running();
self.forget_pulled(server, &d.path, run.as_ref());
let enc = run.as_ref().map(|r| r.caps.read().encoding).unwrap_or_default();
let shown = server.set_diagnostics(d.path.clone(), Vec::new());
self.emit_diagnostics(server, d.path.clone(), shown, enc);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cell_uris_name_the_notebook_file_and_the_cell() {
let root = if cfg!(windows) { PathBuf::from(r"C:\work\my nb") } else { PathBuf::from("/work/my nb") };
let expected = if cfg!(windows) {
"vscode-notebook-cell:/C:/work/my%20nb/a.ipynb#f3-x_1%2E"
} else {
"vscode-notebook-cell:/work/my%20nb/a.ipynb#f3-x_1%2E"
};
let uri = cell_uri(&root.join("a.ipynb"), "f3-x_1.");
assert_eq!(uri, expected);
assert!(is_cell_uri(&uri) && parse_uri(&uri).is_some());
assert!(!is_cell_uri("file:///a.ipynb") && !is_cell_uri("vscode-notebook-cellx:/a"));
}
}
+4 -4
Переглянути файл
@@ -80,7 +80,7 @@ pub(crate) struct Widened<R> {
impl<R> Widened<R> {
/// An answer from the server's analysis scope alone; `empty`: it found nothing.
pub fn only(first: R, empty: bool, server: &Server) -> Self {
let incomplete = (empty && server.is_busy()).then_some(ReferencesIncomplete::Indexing);
let incomplete = (empty && server.indexing()).then_some(ReferencesIncomplete::Indexing);
Self { first, second: None, incomplete }
}
}
@@ -130,7 +130,7 @@ impl LspManager {
F: Fn() -> Fut,
Fut: Future<Output = IdeResult<R>>,
{
let busy = t.server.is_busy();
let indexing = t.server.indexing();
// gopls searches the view of the file asked about; files opened for it only get views of
// their own (see `go_scope`).
let word = search_word(snap, pos).filter(|_| t.caps().open_close && snap.language.as_str() != "go");
@@ -143,7 +143,7 @@ impl LspManager {
};
let (first, candidates) = futures::join!(query(), candidates);
let mut first = first?;
if busy && covered(&first).is_empty() && t.server.wait_idle(INDEX_WAIT, cancel).await {
if indexing && covered(&first).is_empty() && t.server.wait_indexed(INDEX_WAIT, cancel).await {
first = query().await?;
}
if cancel.is_cancelled() {
@@ -151,7 +151,7 @@ impl LspManager {
}
// Servers report analysis progress often; only "nothing found" while it lasts is suspect.
let mut incomplete =
(t.server.is_busy() && covered(&first).is_empty()).then_some(ReferencesIncomplete::Indexing);
(t.server.indexing() && covered(&first).is_empty()).then_some(ReferencesIncomplete::Indexing);
let Some(candidates) = candidates else { return Ok(Widened { first, second: None, incomplete }) };
if candidates.limit_hit {
incomplete = incomplete.or(Some(ReferencesIncomplete::TooManyFiles));
+28 -8
Переглянути файл
@@ -127,7 +127,7 @@ pub struct Server {
published: Mutex<HashMap<PathBuf, Instant>>,
/// Woken on every `publishDiagnostics` (Inspect Code waits on it).
pub published_notify: Notify,
/// Woken when the last `$/progress` task ends.
/// Woken when an empty answer stops being suspect (see [`Server::indexing`]).
idle_notify: Notify,
/// `experimental/serverStatus` (rust-analyzer): `None` until the server sends
/// one, then whether it is still loading the project.
@@ -148,6 +148,8 @@ pub struct Server {
/// The instance whose just registered external project is loading, until an open file's
/// diagnostics arrive (0: none).
pub external_loading: std::sync::atomic::AtomicU64,
/// jdtls sent `ServiceReady` on this instance: the project is imported.
java_ready: std::sync::atomic::AtomicBool,
/// kotlin-lsp's project import as the current instance last reported it.
pub(crate) import_state: watch::Sender<Option<crate::kotlin_lsp::ImportState>>,
}
@@ -195,6 +197,7 @@ impl Server {
external_diagnostics: std::sync::atomic::AtomicBool::new(false),
external_refresh_queued: std::sync::atomic::AtomicBool::new(false),
external_loading: std::sync::atomic::AtomicU64::new(0),
java_ready: std::sync::atomic::AtomicBool::new(false),
import_state: watch::channel(None).0,
}
}
@@ -596,6 +599,22 @@ impl Server {
self.phase_ended();
}
/// Whether an empty search answer may only mean the server has not indexed the project
/// yet. jdtls' searches wait for its index themselves, and the progress it reports once
/// the project is imported is background work (builds, validation): only the import counts.
pub fn indexing(&self) -> bool {
if self.name == "jdtls" {
return self.is_busy() && !self.java_ready.load(std::sync::atomic::Ordering::Acquire);
}
self.is_busy()
}
/// Records jdtls' `ServiceReady`.
pub fn set_java_ready(&self) {
self.java_ready.store(true, std::sync::atomic::Ordering::Release);
self.phase_ended();
}
/// Whether progress token `token` is still running on this instance.
pub fn has_progress(&self, token: &str) -> bool {
self.progress.lock().contains_key(token)
@@ -613,7 +632,7 @@ impl Server {
fn phase_ended(&self) {
self.phase_notify.notify_waiters();
if !self.is_busy() {
if !self.indexing() {
self.idle_notify.notify_waiters();
}
}
@@ -623,17 +642,17 @@ impl Server {
self.phase_notify.notified()
}
/// Waits until no `$/progress` task is active; false on timeout or cancellation.
pub async fn wait_idle(&self, timeout: Duration, cancel: &CancellationToken) -> bool {
/// Waits until [`Server::indexing`] ends; false on timeout or cancellation.
pub async fn wait_indexed(&self, timeout: Duration, cancel: &CancellationToken) -> bool {
let deadline = tokio::time::Instant::now() + timeout;
loop {
let notified = self.idle_notify.notified();
if !self.is_busy() || self.running().is_none() {
return !self.is_busy();
if !self.indexing() || self.running().is_none() {
return !self.indexing();
}
tokio::select! {
() = notified => {}
() = tokio::time::sleep_until(deadline) => return !self.is_busy(),
() = tokio::time::sleep_until(deadline) => return !self.indexing(),
() = cancel.cancelled() => return false,
}
}
@@ -723,6 +742,7 @@ impl Server {
pub fn take_progress(&self) -> Vec<(TaskId, String)> {
*self.loading.lock() = None;
self.external_loading.store(0, std::sync::atomic::Ordering::Release);
self.java_ready.store(false, std::sync::atomic::Ordering::Release);
self.progress.lock().drain().map(|(_, p)| (p.task, p.title)).collect()
}
@@ -957,7 +977,7 @@ mod tests {
stalled: true,
},
);
assert!(!s.is_busy(), "a stuck task must not hold wait_idle or ReferencesIncomplete::Indexing");
assert!(!s.is_busy(), "a stuck task must not hold wait_indexed or ReferencesIncomplete::Indexing");
s.progress.lock().get_mut("p").unwrap().stalled = false;
assert!(s.is_busy(), "a reporting task keeps the server busy");
}
+213 -4
Переглянути файл
@@ -687,6 +687,8 @@ async fn java_classpath_waits_for_a_config_restart_that_is_reaping_startup() {
assert!(result.unwrap_err().message.contains("restart configuration error"));
} else {
assert!(result.is_ok(), "a configuration restart is transient: {result:?}");
// The module folder resolves to the instance serving its files, not a second one.
assert_eq!(h.mgr.servers().len(), 1);
assert_eq!(state.launches.load(Ordering::SeqCst), 2);
assert_eq!(h.mgr.servers()[0].id != old, shared);
}
@@ -757,6 +759,40 @@ async fn java_classpath_does_not_retry_permanently_unavailable_servers() {
}
}
#[tokio::test(flavor = "multi_thread")]
async fn external_maven_import_joins_the_opened_root_without_replacing_discovery() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let external = tempfile::tempdir().unwrap();
let external = dunce::canonicalize(external.path()).unwrap();
std::fs::write(external.join("pom.xml"), "<project><artifactId>b</artifactId></project>").unwrap();
let outside = external.join("src/Main.java");
std::fs::create_dir_all(outside.parent().unwrap()).unwrap();
std::fs::write(&outside, "class External {}").unwrap();
let inside = h.root.join("src/App.java");
std::fs::create_dir_all(inside.parent().unwrap()).unwrap();
std::fs::write(&inside, "class App {}").unwrap();
// An in-root build with its own marker keeps a separate server.
let nested = h.root.join("nested");
std::fs::create_dir_all(&nested).unwrap();
std::fs::write(nested.join("mock.toml"), "").unwrap();
let nested_file = nested.join("Nested.java");
std::fs::write(&nested_file, "class Nested {}").unwrap();
h.mgr.set_jdtls_import_roots(vec![external.clone()]);
h.mgr.did_open(DocId::next(), &inside, &h.lang, 1, "class App {}");
h.mgr.did_open(DocId::next(), &outside, &h.lang, 1, "class External {}");
h.mgr.did_open(DocId::next(), &nested_file, &h.lang, 1, "class Nested {}");
let state = h.launcher.state("jdtls");
eventually(|| state.requested("initialize").len() == 2).await;
let inits = state.requested("initialize");
let project = inits.iter().find(|init| init["rootUri"] == uri_of(&h.root)).unwrap();
assert_eq!(project["initializationOptions"]["workspaceFolders"], json!([uri_of(&h.root), uri_of(&external)]));
assert!(project["initializationOptions"].get("projectConfigurations").is_none());
assert!(state.requested("initialize").iter().any(|init| init["rootUri"] == uri_of(&nested)));
assert_eq!(h.mgr.servers().len(), 2);
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn shared_java_external_roots_reach_initialization_queries_and_watches() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
@@ -1916,16 +1952,17 @@ async fn replacing_progress_keeps_cancellation_reports_and_indexing_on_the_new_t
for _ in 0..2 {
peer.notify("$/progress", json!({ "token": 7, "value": { "kind": "end" } })).unwrap();
}
// A later task is a barrier for both end notifications.
h.wait_status("mock", ServerStatus::Ready).await;
let refs = tokio::time::timeout(Duration::from_secs(5), search).await.unwrap().unwrap().unwrap();
assert_eq!(refs.incomplete, None);
// A later task is a barrier for both end notifications. It starts only after the search
// finished: one that is still running would see the barrier as indexing.
peer.notify("$/progress", json!({ "token": "barrier", "value": { "kind": "begin", "title": "Barrier" } })).unwrap();
peer.notify("$/progress", json!({ "token": "barrier", "value": { "kind": "end" } })).unwrap();
eventually(|| {
h.events.lock().iter().any(|e| matches!(e, IdeEvent::Task { title, done: true, .. } if title == "Barrier"))
})
.await;
h.wait_status("mock", ServerStatus::Ready).await;
let refs = tokio::time::timeout(Duration::from_secs(5), search).await.unwrap().unwrap().unwrap();
assert_eq!(refs.incomplete, None);
assert!(!ide_core::task::cancel(new));
let events = h.events.lock();
for id in [old, new] {
@@ -4922,6 +4959,39 @@ async fn scoped_java_usages_search_the_sources_unless_libraries_are_asked_for()
assert!(seen.lock().is_empty());
}
/// jdtls' searches wait for its index themselves, and it reports background work (builds,
/// validation) for long stretches: a method nothing calls is answered at once meanwhile.
#[tokio::test(flavor = "multi_thread")]
async fn java_usages_of_an_unused_method_do_not_wait_for_background_work() {
let mut caps = incremental_caps();
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.usages"]});
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
let s = h.launcher.state("jdtls");
s.respond("workspace/executeCommand", json!([]));
let (doc, _) = h.open("a.java", "void unused() {}");
h.wait_status("jdtls", ServerStatus::Ready).await;
s.peer()
.notify("$/progress", json!({ "token": "build", "value": { "kind": "begin", "title": "Building" } }))
.unwrap();
h.wait_status("jdtls", ServerStatus::Busy).await;
// Until the project is imported, finding nothing may only mean it is not indexed yet.
let refs = h.mgr.references(doc, Pos::new(0, 6), true, false, Default::default()).await.unwrap();
assert_eq!(refs.incomplete, Some(ReferencesIncomplete::Indexing));
s.peer().notify("language/status", json!({"type": "ServiceReady", "message": "ServiceReady"})).unwrap();
for _ in 0..200 {
let refs = h.mgr.references(doc, Pos::new(0, 6), true, false, Default::default()).await.unwrap();
if refs.incomplete.is_none() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let started = std::time::Instant::now();
let refs = h.mgr.references(doc, Pos::new(0, 6), true, true, Default::default()).await.unwrap();
assert!(started.elapsed() < Duration::from_secs(2), "waited {:?}", started.elapsed());
assert!(refs.locations.is_empty());
assert_eq!(refs.incomplete, None);
}
/// A library method's usages in the sources are shown before the dependencies and the JDK
/// are searched, which takes seconds; scope widening searches the sources alone again.
#[tokio::test(flavor = "multi_thread")]
@@ -6781,3 +6851,142 @@ async fn gomod_files_are_served_by_gopls() {
assert_eq!(items[0].message, "missing requirement");
mgr.shutdown_all().await;
}
// ------------------------------------------------------------------ notebooks
fn notebook_caps() -> Value {
let mut caps = incremental_caps();
caps["notebookDocumentSync"] = json!({
"notebookSelector": [{
"notebook": { "scheme": "file", "notebookType": "jupyter-notebook" },
"cells": [{ "language": "python" }]
}]
});
caps
}
fn cells(cells: &[(&str, &str)]) -> Vec<ide_lsp::NotebookCell> {
cells.iter().map(|(id, source)| ide_lsp::NotebookCell { id: (*id).into(), source: (*source).into() }).collect()
}
fn cell_texts(open: &Value) -> Vec<(String, String)> {
open["cellTextDocuments"]
.as_array()
.unwrap()
.iter()
.map(|c| (c["uri"].as_str().unwrap().to_owned(), c["text"].as_str().unwrap().to_owned()))
.collect()
}
#[tokio::test(flavor = "multi_thread")]
async fn notebook_cells_are_documents_of_the_servers_that_sync_notebooks() {
let h = harness_for("python", "py", &[("nb", notebook_caps()), ("plain", incremental_caps())], &[]);
let path = h.root.join("analysis.ipynb");
let python = LanguageId::new("python");
h.mgr.sync_notebook(&path, &python, &cells(&[("a", "import os\n"), ("b", "os.pa")]));
h.wait_status("nb", ServerStatus::Ready).await;
h.wait_status("plain", ServerStatus::Ready).await;
let (nb, plain) = (h.launcher.state("nb"), h.launcher.state("plain"));
eventually(|| !nb.notified("notebookDocument/didOpen").is_empty()).await;
let docs = h.mgr.notebook_cells(&path);
assert_eq!(docs.iter().map(|d| d.cell.as_str()).collect::<Vec<_>>(), ["a", "b"]);
assert_eq!(docs[0].uri, ide_lsp::cell_uri(&path, "a"));
let open = &nb.notified("notebookDocument/didOpen")[0];
assert_eq!(open["notebookDocument"]["uri"], uri_of(&path));
assert_eq!(open["notebookDocument"]["notebookType"], "jupyter-notebook");
assert_eq!(open["notebookDocument"]["cells"][1], json!({ "kind": 2, "document": docs[1].uri }));
assert_eq!(
cell_texts(open),
[(docs[0].uri.clone(), "import os\n".to_owned()), (docs[1].uri.clone(), "os.pa".to_owned())]
);
assert!(plain.notified("notebookDocument/didOpen").is_empty() && plain.notified("textDocument/didOpen").is_empty());
// Requests address a cell like a file, and go only to the server it is open on.
nb.respond("textDocument/completion", json!({ "isIncomplete": false, "items": [{ "label": "path" }] }));
plain.respond("textDocument/completion", json!({ "isIncomplete": false, "items": [{ "label": "wrong" }] }));
let list = h.mgr.completion(docs[1].doc, Pos::new(0, 5), None, Default::default()).await.unwrap();
assert_eq!(list.items.iter().map(|i| i.label.as_str()).collect::<Vec<_>>(), ["path"]);
assert_eq!(nb.requested("textDocument/completion")[0]["textDocument"]["uri"], docs[1].uri);
assert!(plain.requested("textDocument/completion").is_empty());
// Its diagnostics are reported under the cell's URI.
nb.peer()
.notify(
"textDocument/publishDiagnostics",
json!({ "uri": docs[1].uri, "diagnostics": [{
"range": {"start":{"line":0,"character":3},"end":{"line":0,"character":5}}, "message": "no attribute pa"
}] }),
)
.unwrap();
let cell_path = PathBuf::from(&docs[1].uri);
eventually(|| {
h.events
.lock()
.iter()
.any(|e| matches!(e, IdeEvent::Diagnostics { path, items, .. } if path.0 == cell_path && items.len() == 1))
})
.await;
h.mgr.close_notebook(&path);
eventually(|| !nb.notified("notebookDocument/didClose").is_empty()).await;
assert_eq!(nb.notified("notebookDocument/didClose")[0]["cellTextDocuments"].as_array().unwrap().len(), 2);
assert!(h.mgr.notebook_cells(&path).is_empty());
assert!(h.mgr.completion(docs[1].doc, Pos::new(0, 5), None, Default::default()).await.is_err());
let last = h
.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::Diagnostics { path, items, source } if path.0 == cell_path && source == "nb" => Some(items.len()),
_ => None,
})
.next_back();
assert_eq!(last, Some(0), "a closed notebook's diagnostics are cleared");
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn notebook_edits_change_cell_text_and_reorders_reopen_it() {
let h = harness_for("python", "py", &[("nb", notebook_caps())], &[]);
let path = h.root.join("n.ipynb");
let python = LanguageId::new("python");
h.mgr.sync_notebook(&path, &python, &cells(&[("a", "x = 1\n"), ("b", "print(x)\n")]));
h.wait_status("nb", ServerStatus::Ready).await;
let nb = h.launcher.state("nb");
eventually(|| nb.notified("notebookDocument/didOpen").len() == 1).await;
let before = h.mgr.notebook_cells(&path);
// Typing in one cell sends only that cell's text.
h.mgr.sync_notebook(&path, &python, &cells(&[("a", "x = 1\n"), ("b", "print(x + 1)\n")]));
h.mgr.sync_notebook(&path, &python, &cells(&[("a", "x = 1\n"), ("b", "print(x + 1)\n")]));
eventually(|| !nb.notified("notebookDocument/didChange").is_empty()).await;
let changes = nb.notified("notebookDocument/didChange");
assert_eq!(changes.len(), 1, "an unchanged notebook sends nothing");
let content = &changes[0]["change"]["cells"]["textContent"];
assert_eq!(content.as_array().unwrap().len(), 1);
assert_eq!(content[0]["document"]["uri"], before[1].uri);
assert_eq!(content[0]["changes"], json!([{ "text": "print(x + 1)\n" }]));
assert_eq!(changes[0]["notebookDocument"]["version"], 2);
// Inserting and moving cells reopens the notebook; kept cells keep their documents.
h.mgr.sync_notebook(&path, &python, &cells(&[("c", "import math\n"), ("b", "print(x + 1)\n"), ("a", "x = 1\n")]));
eventually(|| nb.notified("notebookDocument/didOpen").len() == 2).await;
assert_eq!(nb.notified("notebookDocument/didClose").len(), 1);
let after = h.mgr.notebook_cells(&path);
assert_eq!(after.iter().map(|d| d.cell.as_str()).collect::<Vec<_>>(), ["c", "b", "a"]);
assert_eq!((after[1].doc, after[2].doc), (before[1].doc, before[0].doc));
let reopened = &nb.notified("notebookDocument/didOpen")[1];
assert_eq!(
cell_texts(reopened).into_iter().map(|(_, t)| t).collect::<Vec<_>>(),
["import math\n", "print(x + 1)\n", "x = 1\n"]
);
// A restarted server gets the notebook again.
let launches = nb.launches.load(Ordering::SeqCst);
let server = h.mgr.servers()[0].id;
h.mgr.restart(server).await.unwrap();
eventually(|| nb.launches.load(Ordering::SeqCst) > launches && nb.notified("notebookDocument/didOpen").len() == 3)
.await;
h.mgr.shutdown_all().await;
}
+96
Переглянути файл
@@ -920,3 +920,99 @@ async fn angular_language_server_end_to_end() {
}
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// A notebook's code cells on basedpyright and Ruff (LSP 3.17 notebook sync): names flow from
/// earlier cells, IPython magics parse, and locations and diagnostics name the cells.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires ruff and basedpyright on PATH"]
async fn basedpyright_and_ruff_serve_notebook_cells() {
use ide_lsp::{NotebookCell, cell_uri};
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let root = dunce::simplified(&root).to_path_buf();
std::fs::write(root.join("pyproject.toml"), "[tool.ruff.lint]\nselect = [\"F\"]\n").unwrap();
let path = root.join("analysis.ipynb");
std::fs::write(&path, "{}").unwrap();
let mut python = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("python")).unwrap();
python.language_servers.retain(|server| matches!(server.name.as_str(), "basedpyright" | "ruff"));
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![python]));
let cell = |id: &str, source: &str| NotebookCell { id: id.into(), source: source.into() };
let first = "import os\nimport sys\n\ndef area(r: float) -> float:\n return 3.14 * r * r\n";
let second = "%matplotlib inline\nsize: int = area(2)\nos.pa";
mgr.sync_notebook(&path, &LanguageId::new("python"), &[cell("first", first), cell("second", second)]);
for name in ["basedpyright", "ruff"] {
retry(name, Duration::from_secs(60), || {
let status = last_status(&events, name);
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &status {
panic!("{name} failed: {msg:?}");
}
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
})
.await;
}
let docs = mgr.notebook_cells(&path);
let b = docs[1].doc;
let (a_uri, b_uri) = (cell_uri(&path, "first"), cell_uri(&path, "second"));
assert_eq!((docs[0].uri.as_str(), docs[1].uri.as_str()), (a_uri.as_str(), b_uri.as_str()));
// `os`, imported in the first cell, completes in the second.
let labels = retry("completion in a cell", Duration::from_secs(30), || {
let mgr = mgr.clone();
async move {
let list = mgr.completion(b, Pos::new(2, 5), Some(".".into()), Default::default()).await.ok()?;
let labels: Vec<String> = list.items.into_iter().map(|i| i.label).collect();
labels.iter().any(|l| l == "path").then_some(labels)
}
})
.await;
assert!(labels.iter().any(|l| l == "path"), "{labels:?}");
let hover = mgr.hover(b, Pos::new(1, 13), Default::default()).await.unwrap().expect("hover on `area`");
assert!(
hover.contents.value.contains("area") && hover.contents.value.contains("float"),
"{}",
hover.contents.value
);
let defs = mgr.goto(b, Pos::new(1, 13), GotoKind::Definition).await.unwrap();
assert_eq!(defs.len(), 1, "{defs:?}");
assert_eq!((defs[0].path.to_path_buf(), defs[0].range.start.line), (std::path::PathBuf::from(&a_uri), 3));
let diagnostics = |source: &'static str, uri: String| {
let events = events.clone();
move || {
let items = events.lock().iter().rev().find_map(|e| match e {
IdeEvent::Diagnostics { path, source: s, items } if s == source && path.0 == Path::new(&uri) => {
Some(items.clone())
}
_ => None,
});
async move { items.filter(|items| !items.is_empty()) }
}
};
// `float` is not assignable to `int`; the magic on line 0 is no error.
let typed =
retry("basedpyright cell diagnostics", Duration::from_secs(30), diagnostics("basedpyright", b_uri)).await;
assert!(typed.iter().any(|d| d.range.start.line == 1), "{typed:?}");
assert!(typed.iter().all(|d| d.range.start.line != 0), "{typed:?}");
// F401: `sys` is unused.
let linted = retry("ruff cell diagnostics", Duration::from_secs(30), diagnostics("ruff", a_uri)).await;
assert!(linted.iter().any(|d| d.code.as_deref() == Some("F401") && d.range.start.line == 1), "{linted:?}");
// An edit reaches both servers: the error is fixed.
let fixed = "%matplotlib inline\nsize: float = area(2)\nos.path";
mgr.sync_notebook(&path, &LanguageId::new("python"), &[cell("first", first), cell("second", fixed)]);
retry("diagnostics after the fix", Duration::from_secs(30), || {
let uri = cell_uri(&path, "second");
let clear = events.lock().iter().rev().find_map(|e| match e {
IdeEvent::Diagnostics { path, source, items } if source == "basedpyright" && path.0 == Path::new(&uri) => {
Some(items.is_empty())
}
_ => None,
});
async move { (clear == Some(true)).then_some(()) }
})
.await;
mgr.close_notebook(&path);
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
+86 -6
Переглянути файл
@@ -55,7 +55,7 @@ use views_bindings::exports::openidea::plugin::view_provider as wit_view;
use views_bindings::openidea::plugin::view_types as wit_vt;
/// The API version of the world above, `major.minor` of [`host_api`].
pub const API_VERSION: &str = "1.5";
pub const API_VERSION: &str = "1.6";
const EPOCH_TICK: Duration = Duration::from_millis(10);
pub(crate) const MAX_TEXT: usize = 1 << 20;
pub(crate) const MAX_TITLE: usize = 256;
@@ -432,6 +432,27 @@ pub trait HostApi: Send + Sync {
fn publish_diagnostics(&self, path: &Path, items: Vec<ide_core::Diagnostic>) -> Result<(), HostError>;
/// Performs `request` (its host is granted), filling in secret placeholders.
fn fetch(&self, request: HttpRequest, cancel: &CancellationToken) -> Result<HttpResponse, HostError>;
fn websocket_connect(
&self,
root: &Path,
request: crate::WebSocketRequest,
timeout: Duration,
) -> Result<u64, HostError> {
let _ = (root, request, timeout);
Err(HostError::Invalid("background WebSockets are unavailable on this host".into()))
}
fn websocket_send(&self, connection: u64, bytes: Vec<u8>) -> Result<(), HostError> {
let _ = (connection, bytes);
Err(HostError::Invalid("background WebSockets are unavailable on this host".into()))
}
fn websocket_drain(&self, connection: u64, limit: usize) -> Result<crate::WebSocketBatch, HostError> {
let _ = (connection, limit);
Err(HostError::Invalid("background WebSockets are unavailable on this host".into()))
}
fn websocket_close(&self, connection: u64) {
let _ = connection;
}
/// The `net:ask` answer for a request to HTTPS host `host` of this plugin
/// (`subject`): `Some(true)` allowed and remembered (a host the user
/// already allowed connects without asking again, also in the background),
@@ -606,6 +627,10 @@ impl PluginEngine {
let mut linker = Linker::new(&engine);
wasmtime_wasi::p2::add_to_linker_sync(&mut linker).map_err(|e| e.to_string())?;
bindings::Plugin::add_to_linker::<_, HasSelf<_>>(&mut linker, |s| s).map_err(|e| e.to_string())?;
// Cranelift caches fuel in a JIT local across `new_epoch` yields and only
// reloads `VMStoreContext::fuel_consumed` across host import calls, so
// `tasks` host calls refill `StoreContextMut::set_fuel` directly on return.
bind_task_fuel_refill(&mut linker).map_err(|e| e.to_string())?;
let weak = engine.weak();
std::thread::Builder::new()
@@ -799,7 +824,7 @@ impl CallCancel {
self.token.lock().clone()
}
fn is_set(&self) -> bool {
pub(crate) fn is_set(&self) -> bool {
self.flag.load(Ordering::Acquire)
}
@@ -835,6 +860,10 @@ pub struct StoreData {
/// Tasks begun by the running call and not ended yet.
pub(crate) open_tasks: Vec<u64>,
pub(crate) last_report: Option<Instant>,
/// One-shot unwind window after a blocking host I/O call times out.
pub(crate) host_io_grace_used: bool,
/// Fuel budget active for the running call (scales when a background task begins).
pub(crate) active_fuel: u64,
}
impl WasiView for StoreData {
@@ -987,6 +1016,14 @@ const MAX_BATCH: usize = 1000;
fn event_to_wit(e: WorkbenchEvent) -> wit_events::Event {
match e {
WorkbenchEvent::DocumentChanged(value) => wit_events::Event::Other(wit_types::Extension {
kind: "document-changed".into(),
data: serde_json::to_string(&value).expect("document change serializes"),
}),
WorkbenchEvent::WebsocketReady(value) => wit_events::Event::Other(wit_types::Extension {
kind: "websocket-ready".into(),
data: serde_json::to_string(&value).expect("WebSocket ready event serializes"),
}),
WorkbenchEvent::RunExited(value) => wit_events::Event::Other(wit_types::Extension {
kind: "run-exited".into(),
data: serde_json::to_string(&value).unwrap(),
@@ -1067,6 +1104,8 @@ impl Runtime {
action_prompt_client: None,
open_tasks: Vec::new(),
last_report: None,
host_io_grace_used: false,
active_fuel: setup.limits.fuel,
};
let mut store = Store::new(&engine.engine, data);
store.limiter(|d| &mut d.store_limits);
@@ -1083,7 +1122,7 @@ impl Runtime {
});
arm(&mut store, &setup.limits, setup.limits.timeout).map_err(|e| e.to_string())?;
let api_hint = |e: wasmtime::Error| {
let msg = describe_trap(&e, &setup.limits);
let msg = describe_trap(&e, &setup.limits, setup.limits.fuel);
if msg.contains("openidea:plugin/") { link_error(&msg) } else { msg }
};
let pre = engine.linker.instantiate_pre(component).map_err(api_hint)?;
@@ -1868,10 +1907,11 @@ impl Runtime {
if !stderr.trim().is_empty() {
tracing::info!(plugin = %data.plugin_id, "stderr: {}", stderr.trim_end());
}
let active_fuel = data.active_fuel;
match result {
Ok(r) => Ok(r),
Err(e) => {
let mut msg = describe_trap(&e, &self.limits);
let mut msg = describe_trap(&e, &self.limits, active_fuel);
// Typically the panic message: "panicked at src/lib.rs:1:2:\nboom".
let detail: Vec<&str> =
stderr.lines().filter(|l| !l.trim().is_empty() && !l.starts_with("note:")).collect();
@@ -1923,15 +1963,55 @@ fn arm(store: &mut Store<StoreData>, limits: &Limits, timeout: Duration) -> wasm
data.deadline = now + timeout;
data.timeout = timeout;
data.last_report = None;
data.host_io_grace_used = false;
data.active_fuel = limits.fuel;
data.cancel.reset();
// The callback above runs every tick and decides.
store.set_epoch_deadline(1);
Ok(())
}
fn describe_trap(e: &wasmtime::Error, limits: &Limits) -> String {
fn bind_task_fuel_refill(linker: &mut Linker<StoreData>) -> wasmtime::Result<()> {
use crate::wit_host::TaskRes;
use crate::wit_host::bindings::openidea::plugin::tasks::{Host, HostTask};
use wasmtime::StoreContextMut;
use wasmtime::component::Resource;
linker.allow_shadowing(true);
let tasks_iface = format!("openidea:plugin/tasks@{}", ide_extension::ENGINE_VERSION);
let mut inst = linker.instance(&tasks_iface)?;
inst.func_wrap("begin", |mut caller: StoreContextMut<'_, StoreData>, (title, cancellable): (String, bool)| {
let task = Host::begin(caller.data_mut(), title, cancellable)?;
let fuel = caller.data().active_fuel;
caller.set_fuel(fuel)?;
Ok((task,))
})?;
inst.func_wrap(
"[method]task.report",
|mut caller: StoreContextMut<'_, StoreData>,
(this, done, total, message): (Resource<TaskRes>, u32, Option<u32>, Option<String>)| {
HostTask::report(caller.data_mut(), this, done, total, message)?;
let fuel = caller.data().active_fuel;
caller.set_fuel(fuel)?;
Ok(())
},
)?;
inst.func_wrap(
"[method]task.is-cancelled",
|mut caller: StoreContextMut<'_, StoreData>, (this,): (Resource<TaskRes>,)| {
let cancelled = HostTask::is_cancelled(caller.data_mut(), this)?;
let fuel = caller.data().active_fuel;
caller.set_fuel(fuel)?;
Ok((cancelled,))
},
)?;
linker.allow_shadowing(false);
Ok(())
}
fn describe_trap(e: &wasmtime::Error, limits: &Limits, active_fuel: u64) -> String {
match e.downcast_ref::<wasmtime::Trap>() {
Some(wasmtime::Trap::OutOfFuel) => format!("exceeded its CPU budget ({} fuel per call)", limits.fuel),
Some(wasmtime::Trap::OutOfFuel) => format!("exceeded its CPU budget ({active_fuel} fuel per call)"),
Some(wasmtime::Trap::Interrupt) => CANCELLED.to_owned(),
Some(wasmtime::Trap::UnreachableCodeReached) => "crashed (panic / unreachable)".to_owned(),
Some(trap) => format!("trapped: {trap}"),
+73 -1
Переглянути файл
@@ -104,6 +104,8 @@ pub enum Prompt {
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "kebab-case")]
pub enum EventKind {
DocumentChanged,
WebsocketReady,
FileClosed,
SettingsChanged,
InputModeChanged,
@@ -121,7 +123,9 @@ pub enum EventKind {
}
impl EventKind {
pub const ALL: [Self; 14] = [
pub const ALL: [Self; 16] = [
Self::DocumentChanged,
Self::WebsocketReady,
Self::FileClosed,
Self::SettingsChanged,
Self::InputModeChanged,
@@ -140,6 +144,8 @@ impl EventKind {
pub fn name(self) -> &'static str {
match self {
Self::DocumentChanged => "document-changed",
Self::WebsocketReady => "websocket-ready",
Self::FileClosed => "file-closed",
Self::SettingsChanged => "settings-changed",
Self::InputModeChanged => "input-mode-changed",
@@ -227,10 +233,53 @@ pub struct InputMode {
pub sub: Option<String>,
}
/// One UTF-16 replacement in a locally edited editor document.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct DocumentTextChange {
pub from: u32,
pub to: u32,
pub insert: String,
}
/// Local changes accepted by the editor's shared document model.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DocumentChanged {
pub path: String,
pub base_version: u64,
pub version: u64,
pub changes: Vec<DocumentTextChange>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct WebsocketReady {
pub plugin_id: String,
pub connection: u64,
}
/// A host-owned background WebSocket request.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WebSocketRequest {
pub url: String,
pub headers: Vec<(String, String)>,
pub subprotocol: String,
}
/// Frames received from a host-owned WebSocket and its transport state.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct WebSocketBatch {
pub messages: Vec<Vec<u8>>,
pub closed: bool,
}
/// A workbench event delivered to plugins.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", tag = "kind", content = "value")]
pub enum WorkbenchEvent {
DocumentChanged(DocumentChanged),
WebsocketReady(WebsocketReady),
RunExited(crate::RunExited),
TerminalExited(crate::TerminalExited),
ContentTabAction(crate::ContentTabAction),
@@ -251,6 +300,8 @@ pub enum WorkbenchEvent {
impl WorkbenchEvent {
pub fn kind(&self) -> EventKind {
match self {
Self::DocumentChanged(_) => EventKind::DocumentChanged,
Self::WebsocketReady(_) => EventKind::WebsocketReady,
Self::RunExited(_) => EventKind::RunExited,
Self::TerminalExited(_) => EventKind::TerminalExited,
Self::ContentTabAction(_) => EventKind::ContentTabAction,
@@ -476,6 +527,18 @@ pub fn net_capability(url: &str) -> Result<ide_extension::Capability, String> {
}
}
/// The grant a WebSocket URL requires: the same as its `https`/`http` counterpart.
pub fn websocket_capability(url: &str) -> Result<ide_extension::Capability, String> {
let mut parsed = url::Url::parse(url).map_err(|e| format!("invalid URL: {e}"))?;
let scheme = match parsed.scheme() {
"wss" => "https",
"ws" => "http",
other => return Err(format!("unsupported WebSocket scheme {other:?}")),
};
parsed.set_scheme(scheme).map_err(|()| "invalid WebSocket URL".to_owned())?;
net_capability(parsed.as_str())
}
#[cfg(test)]
mod tests {
#[test]
@@ -510,6 +573,15 @@ mod tests {
assert_eq!(net_host(url).unwrap(), host);
}
assert_ne!(net_host("https://аpi.example/").unwrap(), net_host("https://api.example/").unwrap());
assert_eq!(
websocket_capability("wss://Collab.example.com/socket?room=1").unwrap(),
ide_extension::Capability::Net("collab.example.com".into())
);
assert_eq!(
websocket_capability("ws://localhost:9000/").unwrap(),
ide_extension::Capability::Net("localhost".into())
);
assert!(websocket_capability("https://example.com/").is_err());
assert!(net_host("file:///etc/passwd").is_err());
assert!(net_host("example.com").is_err());
assert!(net_host("https://*.example.com/").is_err());
+187 -8
Переглянути файл
@@ -26,6 +26,7 @@ pub(crate) mod bindings {
"openidea:plugin/tasks.task": super::TaskRes,
"openidea:plugin/process.child": super::ChildRes,
"openidea:plugin/ipc.connection": super::ConnectionRes,
"openidea:plugin/net.websocket": super::WebSocketRes,
"openidea:plugin/auth.loopback": super::LoopbackRes,
},
});
@@ -162,6 +163,19 @@ pub struct ChildRes {
host: std::sync::Arc<dyn crate::HostApi>,
}
/// A project-bound background WebSocket owned by this plugin instance.
/// Releasing the component resource closes the underlying transport.
pub struct WebSocketRes {
id: u64,
host: std::sync::Arc<dyn crate::HostApi>,
}
impl Drop for WebSocketRes {
fn drop(&mut self) {
self.host.websocket_close(self.id);
}
}
impl Drop for ChildRes {
fn drop(&mut self) {
self.host.release_process(self.id);
@@ -183,6 +197,8 @@ pub struct TaskRes {
const MAX_EDITS: usize = 10_000;
const MAX_DIAGNOSTICS: usize = 5_000;
const MAX_REQUEST_BODY: usize = 8 << 20;
/// Upper bound for a WebSocket handshake; the call's remaining time can make it shorter.
const WEBSOCKET_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
const MAX_FIND: u32 = 10_000;
const MAX_STATUS_TEXT: usize = 128;
const MAX_PICK_ITEMS: usize = 5000;
@@ -822,6 +838,52 @@ impl workspace::HostProject for StoreData {
}
impl editor::Host for StoreData {
fn document_at(&mut self, project: Resource<ProjectRes>, path: String) -> Fallible<editor::Document> {
if let Err(error) = self.require(Capability::ProjectRead).and_then(|_| self.require(Capability::EditorRead)) {
return Ok(Err(error));
}
let root = self.table.get(&project)?.root.clone();
let path = match self.resolve_in_project(&root, &path) {
Ok(path) => path,
Err(error) => return Ok(Err(wit::Error::Invalid(error))),
};
Ok(match self.host.document(&path) {
Some((version, text)) => Ok(editor::Document { version, text }),
None => Err(wit::Error::NotFound(format!("{} is not open", path.display()))),
})
}
fn apply_edits_at(
&mut self,
project: Resource<ProjectRes>,
path: String,
version: u64,
edits: Vec<wit::TextEdit>,
) -> Fallible<u64> {
if let Err(error) = self.require(Capability::ProjectRead).and_then(|_| self.require(Capability::EditorWrite)) {
return Ok(Err(error));
}
if edits.len() > MAX_EDITS {
return Ok(Err(wit::Error::Invalid(format!("more than {MAX_EDITS} edits"))));
}
if edits.iter().map(|edit| edit.text.len()).sum::<usize>() > crate::runtime::MAX_TEXT * 8 {
return Ok(Err(wit::Error::Invalid("edits too large".into())));
}
let root = self.table.get(&project)?.root.clone();
let path = match self.resolve_in_project(&root, &path) {
Ok(path) => path,
Err(error) => return Ok(Err(wit::Error::Invalid(error))),
};
let edits = edits
.into_iter()
.map(|edit| ide_core::TextEdit {
range: ide_core::Range::new(pos(edit.range.start), pos(edit.range.end)),
new_text: edit.text,
})
.collect();
Ok(self.host.apply_edits(None, &path, version, edits).map_err(to_wit))
}
fn open_editors(&mut self) -> Fallible<Vec<editor::OpenEditor>> {
if let Err(e) = self.require(Capability::EditorRead).and_then(|_| self.require_window()) {
return Ok(Err(e));
@@ -857,6 +919,7 @@ impl editor::Host for StoreData {
fn core_range(r: wit::Range) -> ide_core::Range {
ide_core::Range::new(pos(r.start), pos(r.end))
}
impl StoreData {
/// A `project` resource's path: inside the resource's root, or — for a
/// project window group — inside any of its member roots (as the editor and
@@ -1196,6 +1259,11 @@ impl events::Host for StoreData {
{
return Ok(Err(to_wit(e)));
}
if kind == EventKind::DocumentChanged {
return Ok(Err(wit::Error::Invalid(
"document-changed is delivered only for paths named with subscribe-paths".into(),
)));
}
if let Some(cap) = kind.capability()
&& let Err(e) = self.require(cap)
{
@@ -1209,6 +1277,14 @@ impl events::Host for StoreData {
if let Err(e) = self.require(Capability::Events) {
return Ok(Err(e));
}
if kind == EventKind::DocumentChanged.name() {
if let Err(e) = self.host.require_api(&kind, 6) {
return Ok(Err(to_wit(e)));
}
if let Err(e) = self.require(Capability::ProjectRead).and_then(|_| self.require(Capability::EditorRead)) {
return Ok(Err(e));
}
}
Ok(self.host.subscribe_paths(&kind, globs).map_err(to_wit))
}
@@ -1267,6 +1343,11 @@ impl tasks::HostTask for StoreData {
}
}
/// Headroom reserved before `StoreData::deadline` so a timed-out host subprocess
/// or HTTP request can unwind as a recoverable `wit::Error` in guest code instead
/// of immediately tripping the Wasm epoch trap on re-entry.
const HOST_IO_UNWIND_GRACE: Duration = Duration::from_millis(250);
impl StoreData {
/// Lets the running call reach `from` plus the background budget (the
/// longer of it and what was left), so a task that keeps saying it is alive
@@ -1277,6 +1358,8 @@ impl StoreData {
self.deadline = extended;
self.timeout = self.limits.background;
}
let scale = (self.limits.background.as_millis() / self.limits.timeout.as_millis().max(1)).max(1) as u64;
self.active_fuel = self.limits.fuel.saturating_mul(scale);
}
/// What is left of the running call's wall-clock budget (host operations
@@ -1284,6 +1367,28 @@ impl StoreData {
fn remaining(&self) -> Duration {
self.deadline.saturating_duration_since(Instant::now())
}
/// Budget handed to a blocking host I/O call (`process.run`, `net.fetch`),
/// leaving room before `self.deadline` when possible so a timed-out I/O call
/// returns `Err` to the guest instead of trapping the Wasm instance.
fn io_timeout(&self) -> Duration {
let rem = self.remaining();
if !self.host_io_grace_used && rem > HOST_IO_UNWIND_GRACE * 2 { rem - HOST_IO_UNWIND_GRACE } else { rem }
}
/// Grants at most one short unwind window per call when a blocking host I/O
/// call failed at or near `self.deadline` without caller cancellation. An
/// error well before the deadline leaves the window for a later call.
fn grant_io_error_grace(&mut self) {
if self.host_io_grace_used || self.cancel.is_set() {
return;
}
let min_deadline = Instant::now() + HOST_IO_UNWIND_GRACE;
if min_deadline > self.deadline {
self.deadline = min_deadline;
self.host_io_grace_used = true;
}
}
}
impl diagnostics::Host for StoreData {
@@ -1371,13 +1476,15 @@ impl net::Host for StoreData {
url: req.url,
headers: req.headers.into_iter().map(|h| (h.name, h.value)).collect(),
body: req.body,
timeout: wanted.min(self.remaining()),
timeout: wanted.min(self.io_timeout()),
grants,
};
let token = self.cancel.token();
Ok(self
.host
.fetch(request, &token)
let outcome = self.host.fetch(request, &token);
if outcome.is_err() {
self.grant_io_error_grace();
}
Ok(outcome
.map(|r| net::Response {
status: r.status,
headers: r.headers.into_iter().map(|(name, value)| net::Header { name, value }).collect(),
@@ -1385,6 +1492,70 @@ impl net::Host for StoreData {
})
.map_err(to_wit))
}
fn websocket_connect(
&mut self,
project: Resource<ProjectRes>,
req: net::WebsocketRequest,
) -> Fallible<Resource<WebSocketRes>> {
let capability = match crate::types::websocket_capability(&req.url) {
Ok(capability) => capability,
Err(error) => return Ok(Err(wit::Error::Invalid(error))),
};
if let Err(error) = self.require(capability) {
return Ok(Err(error));
}
if req.headers.iter().any(|header| header.value.contains("{{secret:"))
&& let Err(error) = self.require(Capability::Secrets)
{
return Ok(Err(error));
}
let request = crate::WebSocketRequest {
url: req.url,
headers: req.headers.into_iter().map(|header| (header.name, header.value)).collect(),
subprotocol: req.subprotocol,
};
let root = self.table.get(&project)?.root.clone();
let timeout = WEBSOCKET_HANDSHAKE_TIMEOUT.min(self.io_timeout());
match self.host.websocket_connect(&root, request, timeout) {
Ok(id) => self.push(WebSocketRes { id, host: self.host.clone() }).map(Ok),
Err(error) => {
self.grant_io_error_grace();
Ok(Err(to_wit(error)))
}
}
}
}
impl net::HostWebsocket for StoreData {
fn id(&mut self, this: Resource<WebSocketRes>) -> wasmtime::Result<u64> {
Ok(self.table.get(&this)?.id)
}
fn send(&mut self, this: Resource<WebSocketRes>, bytes: Vec<u8>) -> Fallible<()> {
let id = self.table.get(&this)?.id;
Ok(self.host.websocket_send(id, bytes).map_err(to_wit))
}
fn drain(&mut self, this: Resource<WebSocketRes>, limit: u32) -> Fallible<net::WebsocketBatch> {
let id = self.table.get(&this)?.id;
Ok(self
.host
.websocket_drain(id, limit as usize)
.map(|batch| net::WebsocketBatch { messages: batch.messages, closed: batch.closed })
.map_err(to_wit))
}
fn close(&mut self, this: Resource<WebSocketRes>) -> Fallible<()> {
let id = self.table.get(&this)?.id;
self.host.websocket_close(id);
Ok(Ok(()))
}
fn drop(&mut self, this: Resource<WebSocketRes>) -> wasmtime::Result<()> {
self.table.delete(this)?;
Ok(())
}
}
impl secrets::Host for StoreData {
@@ -1466,8 +1637,12 @@ impl process::Host for StoreData {
};
let cwd = self.cwd_of(cwd)?;
let token = self.cancel.token();
let timeout = self.remaining();
Ok(self.host.run_process(cmd, cwd.as_deref(), stdin, &token, timeout).map(to_output).map_err(to_wit))
let timeout = self.io_timeout();
let outcome = self.host.run_process(cmd, cwd.as_deref(), stdin, &token, timeout);
if outcome.is_err() {
self.grant_io_error_grace();
}
Ok(outcome.map(to_output).map_err(to_wit))
}
fn run_command(
@@ -1482,8 +1657,12 @@ impl process::Host for StoreData {
};
let cwd = self.cwd_of(cwd)?;
let token = self.cancel.token();
let timeout = self.remaining();
Ok(self.host.run_process(cmd, cwd.as_deref(), stdin, &token, timeout).map(to_output).map_err(to_wit))
let timeout = self.io_timeout();
let outcome = self.host.run_process(cmd, cwd.as_deref(), stdin, &token, timeout);
if outcome.is_err() {
self.grant_io_error_grace();
}
Ok(outcome.map(to_output).map_err(to_wit))
}
fn start(&mut self, cmd: process::Command, cwd: Option<Resource<ProjectRes>>) -> Fallible<Resource<ChildRes>> {
+5 -5
Переглянути файл
@@ -91,15 +91,15 @@ fn the_sdk_carries_the_hosts_wit() {
#[test]
fn the_version_check_runs_compatible_components_and_explains_the_rest() {
let host = v("1.5.0");
for ok in ["1.0.0", "1.3.0", "1.4.7", "1.5.0", "1.0.0-rc.1"] {
let host = v("1.6.0");
for ok in ["1.0.0", "1.3.0", "1.4.7", "1.5.0", "1.6.0", "1.0.0-rc.1"] {
assert_eq!(check_api(&v(ok), &host), Ok(()), "{ok}");
}
let newer = check_api(&v("1.6.0"), &host).unwrap_err();
assert!(newer.contains("1.6") && newer.contains("update OpenIDEA"), "{newer}");
let newer = check_api(&v("1.7.0"), &host).unwrap_err();
assert!(newer.contains("1.7") && newer.contains("update OpenIDEA"), "{newer}");
assert!(check_api(&v("2.0.0"), &host).unwrap_err().contains("update OpenIDEA"));
let older = check_api(&v("0.2.0"), &host).unwrap_err();
assert!(older.contains("rebuild it with the 1.5 SDK"), "{older}");
assert!(older.contains("rebuild it with the 1.6 SDK"), "{older}");
// 0.x: every minor is its own API.
assert_eq!(check_api(&v("0.2.0"), &v("0.2.5")), Ok(()));
assert!(check_api(&v("0.1.0"), &v("0.2.0")).is_err());
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
eb7d608bf1e7379620ef7d9ce5289dd9b927f137af2aafdd0861a84d60d677a2
005d9da29eb7d713a97ff872051e408f653030434d837835843298553c9e12e0
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
195cb4025508e7af6e6fb63d81660c4a977327fa3d101a2a77e5f448f43518f8
6359ef4271f38374889412bd926d9aa735f59a8ce047ffcb06c47976444196cf
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
49491ad2d57592cca2451b0abde5f88a3aedd3f5d36ceaf8259c3254f59c5023
6f560f3d0d7737150d2dfa09c3b801bd3b4c3a52cef9893ed8fc045809fe33e1
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b24383f6e05ec531ef8db368b79af710433bc3782438f5a9e3578ebb730a1ce2
4024af2d55d7fe4e8c456efd7e0c497ade4b2c5959e9108ff218f4a669e920f4
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ef01f199e668063b2c444e4ccf169d5b5407e567dbe8ff583cfdfc111b2438cf
4ca977f53a18e9e8f869d34e027a15abece9e97b9331e23d4f71af721b104611
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
a4dbe2a261e00809b64039ce9c89db681b186788db8a92b7456eca84b33c5945
3d12a00f81e0db1b0902c2ddebfd6454a056f15b97add80b22a0333722568dc8
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
3c9db6ffeaa9b782970c7a7a132878f862b0b5b18e9d11ad56649ee28317e3ca
95d89e411216f50d0b34bee110c6bfc9b8fbcb2ffaae2e912c3609f7bf678b2c
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ac1dceb016b7963f44e876784ea62f776e90dd63fc6f660a5dad3dfbd7433b1c
dd4b6c5153892a4f3facb3f23cb1d92da39a3977985b8abf4eaa9558decfa4a9
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
11dc1a74c0650b493ed6ec88b5d15e08421ab08c5f2320099dabd5df1bdc5096
325bc15cd28933d9687bc3c316008f921f48a4a69d7528c6b367fa0ff22489b8
Loaded 100 of 633 files, more files were not shown because too many files have changed in this diff. Show more