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

..
Автор SHA1 Повідомлення Дата
l0ng-ai ce4be5bebe fix(welcome): flatten recent project lists across hosts 2026-12-02 18:04:20 +08:00
l0ng-ai 9443517d1c docs: restore AGENTS.md and add PR evidence rules with a pr skill (#7498)
Restore AGENTS.md (CLAUDE.md links to it) and the verify skill, and add a pr skill covering scope, checks to run, the evidence each kind of change needs and a UX consistency review against DESIGN.md and PRODUCT.md.

The PR template lists evidence by change type, and the PR check also asks for screenshots or a recording when a PR changes UI files under src/, unless the description says "No visible change".
2026-12-02 17:50:30 +08:00
l0ng-ai 29f6131f9d fix(plugins): keep plugin gutter markers while their file is reindexed (#7499)
An edit invalidated the file's indexed markers and the host has none for the new version until it is indexed again, so the gutter icon area emptied, collapsed and shifted the code sideways after every Enter or line copy. Markers now stay, mapped through the edits, until the reindex settles; editors no longer re-place a kept entry at its old lines; plugin line markers likewise stay until the new ones arrive.

Fixes #7422
2026-12-02 17:50:27 +08:00
Isaac Gallartтаigallart 4027b8341f fix(run): keep configuration fields aligned when resizing on Linux (#7470)
Fixes #7469. On Linux, WebKitGTK shifts the tracks of the scrolling options subgrid as the Run/Debug Configurations dialog resizes, moving fields away from the Name column. There the header and the options now share a fixed 150px label column instead of a subgrid; macOS and Windows keep the subgrid whose label column fits the longest label, and narrow panes keep the stacked layout.

Co-authored-by: igallart <[email protected]>
2026-12-02 17:41:13 +08:00
l0ng-ai ddc483fd2a feat(java): end a completed break or continue with a semicolon (#7493)
Fixes #7358. Completing break or continue in Java inserted the bare keyword. As in IDEA's keyword completion, it now ends with a semicolon, or with a space inside a labeled statement where the keyword can name the label; nothing is added when the line already continues. return is left alone.
2026-12-02 17:36:08 +08:00
l0ng-ai 23d81a2b3d feat(tools): show language server updates in the status bar (#7492)
Fixes #7365. Newer versions of the IDE-installed language servers were only visible in Settings > Language Servers. features/tools now looks for updates a minute after startup, at most once a day (the last result is stored and shown meanwhile in every window, and installing drops it), and publishes them through workbench/contributions. The status bar's Language Servers widget marks that an update exists and gives the server's popup row an Update button.
2026-12-02 17:34:26 +08:00
l0ng-ai 74f61a3540 fix(macos): avoid flashing when switching grouped project tabs (#7209)
Switching to an occluded or detached tab in a native window tab group now syncs its frame, re-attaches its web view and waits for one presentation commit (at most 80 ms) with occlusion detection off before swapping windows, so the incoming tab paints complete on its first visible frame. Rapid switches cancel a superseded wait and restore its web view. Tab switches and hiding AppKit's tab bar run without implicit animation, the tab bar is hidden before the window is ordered front, and a mouse click blurs the clicked project tab so the outgoing window does not keep its hover controls.
2026-12-02 17:19:13 +08:00
Muuтаmuutot c287ce0ee3 fix(python): indent @property inside the class body in the color scheme sample (#7460)
The Python sample in Editor > Color Scheme > Python showed @property at column 0 while the def alias it decorates was indented inside class Foo. The decorator line now has the same four-space indent.

Co-authored-by: muutot <[email protected]>
2026-12-02 17:18:57 +08:00
wangfeiтаhapput 607e4e095d fix(editor): show navigation link for bound click modifiers on hover (#7446)
Cmd+Alt-click (Ctrl+Alt elsewhere) is bound to Go to Implementation in the IntelliJ keymap, but the hover affordance only recognised Cmd/Ctrl alone, so the symbol kept plain text and the I-beam cursor. The navigation modifier tracker now also holds for any modifiers the active keymap binds to a navigation left-click (declaration, implementation, type declaration, super method); the LSP link hover and the plain hover popups follow it, and rebinding or removing the mouse binding removes the affordance.

Co-authored-by: happut <[email protected]>
2026-12-02 17:18:31 +08:00
LU XIANGRUIтаwildcatDownstairs e7da5e0937 fix(lsp): keep escaped brackets in hover docs from rendering as math (#7455)
Fixes #7454. basedpyright escapes literal brackets in hover Markdown (str(bytes_or_buffer\[, encoding\[, errors\]\]) -> str), which the \[...\] rule read as display math. mathExtension gets a strictBrackets option, used only by the LSP hover parser: there a single-line \[...\] is math only when padded with whitespace and not nested. Agents chat, Markdown files and notebooks keep rendering unpadded \[x^2\].

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 17:16:44 +08:00
audichuang ae4a90b23a fix(app): keep a window waiting for its peers to close from taking edits it would lose (#7428)
When Quit or closing several project tabs closes windows in parallel, a window with nothing to ask about waits at windowReadyToClose for the others; while a peer showed its Unsaved Changes prompt, the waiting window still took input, and an edit made there closed unasked. The waiting window now blurs its focused element, goes inert and suspends keyboard dispatch while it waits; it is given back with focus restored when the close is cancelled or the wait fails.

Co-authored-by: audichuang <[email protected]>
2026-12-02 17:12:10 +08:00
l0ng-ai 04006f2ea7 fix(agents): close open session view when archiving a task (#7440)
Archiving a task closes its session and Changes tabs, returns a docked Agents tool window to the task list, and clears lastTask / lastComposer so Send to Agent and layout switches do not target the read-only task. Closing a detached window of an archived task keeps its draft without reopening it. Reopening an already archived task from the Archived group still shows it.
2026-12-02 17:06:27 +08:00
l0ng-ai 7f20fc0c54 ci(smoke): run every language when lineNumberOptions.ts changes (#7484)
src/editor/api.ts now imports src/editor/core/cm/lineNumberOptions.ts, which the frontend smoke loads, so add it to the Language smoke paths and the Changes step pattern.
2026-12-02 17:06:20 +08:00
LU XIANGRUIтаwildcatDownstairs a8db175c25 feat(svn): shelf, working copy information, menu name and stripe position (#7478)
Subversion requests from #7433:

- Shelve, Shelve Silently, Unshelve and the Shelf tab work in Subversion working copies. Shelve saves `svn diff --git --show-copies-as-adds` of the selection and rolls the files back, refusing when the files changed since the patch was taken; Unshelve applies it with `svn patch` and reports rejected or skipped files as conflicts. Unversioned or conflicted files, binary files an older svn cannot put in a patch, non-UTF-8 text and selections across working copies are refused before anything is reverted. Stash stays Git-only.
- A Subversion Working Copies Information tab lists every working copy with its URL, repository root, revision, depth and format, with Show Log, Update Project, Cleanup and Relocate for each.
- The version control menu is named SVN for a Subversion project and VCS for a project with several systems.
- The version control tool window button is last in the bottom stripe group.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 16:57:05 +08:00
LU XIANGRUIтаwildcatDownstairs 8aacedf5ad fix(svn): bugs reported in #7433 (#7464)
Fixes five Subversion bugs from #7433:

- Revision details, changed files and annotation summaries ask the working copy's own URL first and the repository root only for revisions it does not list, so a server that authorizes by path no longer refuses them (E170013 / E175013). The branch list asks trunk, branches and tags one by one when the project folder cannot be listed.
- Shelving around Update Project is limited to Git repositories, so updating Subversion working copies no longer reports "not a git repository of the project".
- A double click on a working copy's tree or property conflict keeps it selected in the Conflicts dialog instead of opening the merge editor.
- The diff of a working copy's folder compares its properties instead of failing with W195007.
- The Log's User filter and author tooltip show an author without an email by name alone.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 16:44:42 +08:00
LU XIANGRUIтаwildcatDownstairs 1425bfe8ae feat(xcode): build in the background for code insight before the first build (#7339)
Opening an Xcode project with no build log builds its first scheme once in the background, so xcode-build-server has compiler arguments and sourcekit-lsp gives cross-target insight before the first Run. The build is cancellable, waits for Xcode's own build database, restarts sourcekit-lsp when it ends, and foreground builds cancel and reap it first. Xcode process execution lives in ide-run.

Closes #7337

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 16:32:55 +08:00
Glitched Polygons GmbH 75ec6c51a3 feat(csharp): Razor / cshtml / ASP.NET Core MVC support (#7256)
Razor (.cshtml/.razor) gets syntax highlighting, Roslyn's built-in Razor support with the HTML parts projected to the HTML language server (ordered open/close, a reserved projection URI, scoped capability registrations), and MVC navigation between controller actions and their views, including explicit View("...") names, subfolders and areas.

Closes #615

Co-authored-by: GlitchedPolygons <[email protected]>
2026-12-02 16:32:46 +08:00
l0ng-ai b20e7c0817 feat(agents): place image attachments inline in prompts (#7477)
Pasting, dropping or choosing an image in the agent composer inserts an [Image #n] label at the caret with a hover preview; deleting the label removes the attachment (undo restores it), and the prompt is sent as text and image blocks in label order (Copilot gets numbered references plus attachments).

Fixes #7336
2026-12-02 16:31:38 +08:00
LU XIANGRUIтаwildcatDownstairs adf5701e16 fix(svn): data loss and mixed-project Git fixes from a second review of #7131 (#7266)
Fixes from a second review of the built-in Subversion support: rollback keeps moved and needs-lock files intact, a failed commit staging step undoes only the schedules it made, mixed Git/SVN Commit All no longer pulls in unstaged Git edits, status refreshes keep failed roots' rows without resurrecting cleaned ones, BASE image sizes follow copy history, logins say whether the user asked, Windows passwords are sent in the console code page, and background Log refreshes share one SVN branch lookup so a cancelled login is not re-prompted.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 15:48:23 +08:00
Yohann CATHERINEтаyohannlog 5debc5297b feat(cmake): CLion-style profiles, presets and toolchains (#7262)
CMake gets CLion-style profiles (build type, generator, build directory, CMake options, environment), CMake presets as profiles, and toolchains (compilers, build tool, debugger, environment script). Only the active profile is detected; target ids have their own namespace, configurations from the older per-profile ids are migrated with their suppressions and before-launch references, the toolchain's build program is passed only to a compatible generator, and a profile switch refreshes the derived executable and build arguments while keeping user edits.

Co-authored-by: yohannlog <[email protected]>
2026-12-02 15:35:21 +08:00
l0ng-ai 5db70297cb fix(i18n): translate the Search Everywhere category actions (#7457)
#7405 added the Search Everywhere: {title} action title without zh / zh-TW text, which failed the source-text catalog test.
2026-12-02 15:34:13 +08:00
LU XIANGRUIтаwildcatDownstairs 0f78b845e6 docs(csharp): document Project view .NET entry points and Unity Editor attach (#7414)
Documents the .NET solution and project entry points in the Project view and attaching to the Unity Editor.

Closes #7410

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 14:51:15 +08:00
王斌 c319656529 feat(search): give every plugin search category its own action (#7405)
Each plugin-contributed Search Everywhere category gets a Navigate action (Search Everywhere: <category>) that opens that tab, so a keymap can bind it directly. The actions follow the categories as plugins are enabled or disabled; no default shortcuts.

Closes #7369

Co-authored-by: kitter960324 <[email protected]>
2026-12-02 14:51:05 +08:00
王斌 4ebc769042 feat(vcs): expand and collapse all in the Branches panel (#7407)
The Git Log Branches panel gets Expand All / Collapse All buttons and the ⌘+ / ⌘- (Ctrl+= / Ctrl+-) shortcuts while the tree has focus. Collapse All keeps the selected rows' ancestors open; the tree's identity (repository, grouping, reload) restores the default expansion.

Closes #7335

Co-authored-by: kitter960324 <[email protected]>
2026-12-02 14:50:54 +08:00
LU XIANGRUIтаwildcatDownstairs 300424658a fix(vcs): keep a deleted new file deleted after Pull, checkout, merge (#7343)
A new file staged and then deleted came back after Pull, checkout or merge: preserving local changes stashed and restored it. The deletions are now recorded and reapplied after the restore, across every batch of Git path queries; pre-existing empty folders are recreated, and a restore Git blocks keeps its marker and deletion record for the retry.

Closes #7333

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 14:47:00 +08:00
Onur Ugur 44ccaaef26 fix(editor): keep column 0 on paste after clearing auto-indent in YAML (#7415)
Fixes #7388. pasteReindentFilter fell back to the previous line's indent whenever the caret was at column 0 and the language had no indent opinion, so a line whose auto-indent the user had just deleted was treated like a clicked blank line (#4474). A state field now records a blank line whose indentation the user removed (kept across Enter from it, cleared when the caret leaves or the line gets text), and the paste keeps column 0 there. In YAML, an explicit indent is also kept when the language computes 0 because a root key follows.

Co-authored-by: OnurrUgur <[email protected]>
2026-12-02 14:39:45 +08:00
王斌 befb4792ce fix(editor): colour a module's top-level bindings as variables, not globals (#7409)
Fixes #7047. tsserver marks only function- and block-scoped bindings local, so every top-level const, let, function and import of a JS/TS file got cm-sem-global. A file with an import or export statement is an ES module, whose top-level bindings WebStorm colours as variables; only a script's top-level bindings keep the global classes. The module check is cached per syntax tree.

Co-authored-by: kitter960324 <[email protected]>
2026-12-02 14:37:53 +08:00
zhzhsxтаzhzhsx 34741f56c4 fix(diff): align the deleted lines with the new ones in the unified view (#7404)
In the unified diff viewer a deleted block started 3.5px right of the added lines: @codemirror/merge insets .cm-deletedChunk by 6px while the viewer's lines use LINE_INSET (2.5px). The block now uses LINE_INSET, which also fixes the base lines on the merge editor's sides.

Co-authored-by: zhzhsx <[email protected]>
2026-12-02 14:37:23 +08:00
Kim Myeong Su 2907832e37 fix(editor): keep a Space the Korean IME commits as a composition (#7411)
Fixes #7386. macOS Korean 2-Set commits a Space typed after Hangul as a one-character composition, and typedImeCommit (#6608) removed it as a Pinyin syllable space, in the editor and the terminal. Only spaces between non-space characters now count as syllable separators, so ni hao still becomes nihao and a lone Space is kept.

Co-authored-by: kmsdoit <[email protected]>
2026-12-02 14:33:17 +08:00
薛纪克таxuejike ff4e916561 fix(agents): retry opening a session while the agent finishes starting (#7350)
Opening a saved session while the agent was still starting failed with an internal error. The session open is now retried while the agent reports warming up, within a 30 s window that also bounds each attempt; a timeout or warm-up failure keeps the saved session id so Try again reopens the same conversation, and an auth request during any attempt runs the advertised authentication once.

Closes #7348

Co-authored-by: xuejike <[email protected]>
2026-12-02 14:32:35 +08:00
LU XIANGRUIтаwildcatDownstairs 2f799aede9 fix(editor): match WebStorm's JS/TS inlay hint defaults and cut long hints (#7338)
JS/TS inlay hints default as in WebStorm: inferred types for variables and fields, enum values, and parameter names for literal and anonymous-function arguments. The Editor toggle now reaches the typescript-language-server fallback too. Long hints are cut with the full label in the tooltip, which also refreshes when the server changes it.

Closes #7326

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 14:32:27 +08:00
l0ng-ai f853ccf544 fix(i18n): translate Bundle Identifier in the Xcode project wizard (#7425)
The Xcode project wizard (#7394) added zh entries equal to their English source, failing src/platform/i18n.test.ts on main. Bundle Identifier is translated; iOS and macOS join the kept-as-written list.
2026-12-02 14:32:11 +08:00
王斌 8b4de98664 fix(search): keep the arrows in the File Structure filter for text editing (#7416)
Fixes #4174. The filter field's keydown handler treated ←/→ as tree navigation even with a query, so the caret never moved and the selected symbol collapsed. With a query the arrows now move the caret; with an empty query they still expand and collapse the tree, as IDEA's speed search does until something is typed. The tree keeps its own ←/→ handling when it has focus.

Co-authored-by: kitter960324 <[email protected]>
2026-12-02 14:29:12 +08:00
l0ng-ai a36516d463 refactor(database): take plugin table menu entries from a workbench registry (#7423)
The Database tree imported pluginDatabaseTableMenuItems from features/plugins directly (from #7372). The table context type and a provider registry now live in workbench/contributions; features/plugins registers its provider.
2026-12-02 14:28:15 +08:00
葛俊таgejun123456 b7c2d4eacb feat(plugins): expose database table menus and read-only schema (#7372)
Plugin API 1.20 adds wit/database.wit with describe-table behind the database.schema capability: a read-only view of a connected source's table (columns, keys, indexes) through DbManager::connected_table_details. Plugins can contribute database.table.context menu entries (needs_api 20) that receive the non-secret table identity and the when keys databaseDriver, databaseObjectKind, databaseSchema, databaseTable and databaseSelectionCount.

Co-authored-by: gejun123456 <[email protected]>
2026-12-02 14:25:35 +08:00
LU XIANGRUIтаwildcatDownstairs abc5b2b2c6 feat(new-project): Xcode project templates for iOS, macOS and multiplatform apps (#7394)
File > New Project could only create SwiftPM packages. A new Xcode Project entry (Swift group; also found by iOS, macOS, App, SwiftUI or Xcode) opens a chooser modelled on Xcode's template sheet: platform tabs (Multiplatform, iOS, macOS), a filter and template tiles under Application and Framework & Library, then an options page (Product Name, Team, Organization Identifier, read-only Bundle Identifier preview, Interface, Language, Testing System). The App and Framework templates are generator definitions that write a minimal Xcode 16 project with synchronized folders and a shared scheme, so no XcodeGen or Tuist is needed and the existing scheme, simulator, run and test support takes over when it opens. The entry shows the installed Xcode's own icon, rendered at runtime, or a bundled glyph without Xcode.

Scaffold gains {{#if field=value}} blocks, c99 / bundle filters, generator platforms / section / name-pattern and readonly / remember fields. Template tree tests skip the generator's tool requirements so they run without Xcode.

Closes #7393

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 14:05:01 +08:00
l0ng-ai cb10ba7207 fix(build): copy Maven resources whose content changed without a newer mtime (#7413)
The resources step ran maven-resources-plugin, which copies a file only when it is newer than the copy, then recorded the source stamps as processed, so content replaced without a newer mtime stayed stale for good. It now passes -Dmaven.resources.overwrite=true.

Fixes #7340
2026-12-02 13:59:52 +08:00
l0ng-ai 0fe39535d6 test(trust): check SDK lookups against the restricted project window (#7412)
#7389 lets SDK commands run without a project window, so the assertion that a missing window is refused no longer held. Assert that the restricted project's own window still refuses them.
2026-12-02 13:58:59 +08:00
LU XIANGRUIтаwildcatDownstairs 0c9ffe1e41 fix(settings): let the Maven home path be typed or pasted (#7385)
Settings > Build Tools > Maven > Maven home path was a plain dropdown of detected installations plus Browse. It is now an editable combo box, as in IntelliJ IDEA: a typed or pasted path is saved on Enter, blur or paste (trimmed; empty means Auto), Escape undoes an unsaved edit, the arrow, Up and Down open the list of Auto and the detected homes. The saved path is checked the way maven_command resolves it (the home, its bin folder or mvn itself; ~/ from the home directory; relative paths from the project root) and a problem shows under the field. Other SDK combos keep the plain dropdown.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 13:52:19 +08:00
Qslia cda99d5495 fix(notebook): open an empty .ipynb file as an empty notebook (#7395)
New File named x.ipynb (or touch, or an agent) creates an empty file, which the notebook editor refused with 'Invalid notebook JSON: EOF while parsing a value'. It now reads as an empty nbformat 4 notebook, as in PyCharm; saving it unchanged leaves the file alone and an edit writes a real notebook. This covers every way an empty notebook file can appear, so New File needs no template of its own.

Co-authored-by: qslia <[email protected]>
2026-12-02 13:48:51 +08:00
王斌 d979e102f9 fix(editor): paste a clipboard's CRLF as single line breaks (#7399)
Paste with an empty selection in an editor (Vim Insert mode's Ctrl+V, Edit > Paste) went through document.execCommand('insertText'), which turns a Windows clipboard's CRLF into two line breaks: 1,000 pasted lines became 1,999, and a 5,000-line paste froze the window while the text was inserted line by line. A paste into a focused editor now always goes through one input.paste transaction, and the clipboard's line ends are normalized to LF; other focused elements still use insertText.

Closes #7387

Co-authored-by: kitter960324 <[email protected]>
2026-12-02 13:46:09 +08:00
aconeshanaтаaconeshana 67d68f7f4e fix(run): open the context path the embedded web server announces (#7384)
Open in Browser for a running Spring Boot app opened http://localhost:8080/ and dropped server.servlet.context-path, so an app under /api showed a 404. The embedded server's startup line (Tomcat started on port 8080 (http) with context path '/api') was parsed for the port only. It is now parsed into the port and the normalized context path, kept on run sessions (including reattached remote runs) and published for debug sessions, and both Open in Browser paths append it.

Closes #7383

Co-authored-by: aconeshana <[email protected]>
2026-12-02 13:43:53 +08:00
l0ng-ai 2b73ef73f1 perf(index): space snapshot refreshes by how long the last one took (#7401)
Any index write drops the startup snapshot, and it was written again at most every 10 s, also inline after every subtree scan. In a project of 160 000 files a write takes up to 11 s and holds the disk, so a build writing into the project kept it rewriting for minutes after startup.

The gap after a write is now 30 times what it took, between 10 s and 5 min; a subtree scan within the gap leaves the write to the scheduled refresh. Full scans still write at once. The snapshot only speeds up the next startup: one that is missing falls back to a scan.

Refs #7363
2026-12-02 13:41:25 +08:00
l0ng-ai de41651a5e fix(agents): ask AskUserQuestion forms one question at a time (#7396)
claude-agent-acp now sends AskUserQuestion as an ACP form (a choice field per question, each followed by a text field for a typed answer), and OMP's ask tool sends the same shape. They were shown as a plain form with every question stacked above the composer, at up to half the window, which in a short Agents panel left the conversation no room to scroll.

Such forms are now shown as the question card in the conversation, one question at a time with Previous/Next, option descriptions and previews; the answers are turned back into the form's values (picked options as the choice, typed text in its companion field; Skip declines). Other forms stay forms, and a long one waiting above the composer now leaves the conversation a share of the panel and scrolls within itself.

Fixes #7359
2026-12-02 13:36:43 +08:00
l0ng-ai 6bd2d5f843 fix(run): keep a log line with a stray NUL byte out of UTF-16 decoding (#7390)
On Windows the console decoder took any read containing a NUL byte for UTF-16LE output (wsl.exe, cmd /u). A Spring Boot app logging a payload that ends in a NUL turned the whole read into CJK-looking garbage. A read is now UTF-16LE only when NUL bytes are dense (one byte in eight or more, as every ASCII character in UTF-16 has one) or one follows a line feed (every UTF-16 line end has one).

Fixes #7362
2026-12-02 13:30:02 +08:00
l0ng-ai 93c15547ef fix(sdk): add a JDK from disk in Settings opened from the Welcome screen (#7389)
sdk_jdk_at was a trusted command, which needs an open trusted project, so Add JDK from Disk on the Welcome screen always failed and the error was shown as 'not a valid home for JDK'. SDKs are IDE-wide: sdk_jdk_at, sdk_flutter_at, sdk_locate_tools and sdk_php_xdebug now run outside Restricted Mode like sdk_detect (a restricted project still refuses them). A failed check now shows its error instead of calling the folder invalid.

Fixes #7361
2026-12-02 13:28:49 +08:00
Ivan 90d98f3edd feat(editor): gutter icons between Rust traits and their impls (#7253)
Rust files get RustRover's line markers between traits and implementations: an impl block and its methods get ↑ to the trait (or the trait's method, required vs default from the trait file's outline), a trait and its methods get ↓ to their implementations. The trait and the self type come from the tree-sitter impl header (outline items carry implements / self_type ranges, merged into rust-analyzer's outline), so multi-line generic headers, where clauses and const generic arguments label correctly. Lookups are asked only near the viewport, per-kind provider availability is cached, and every request of a pass is guarded by the document and pass generation, so an edit cancels a running pass and stale markers are refreshed.

Covered by lineMarkers.test.ts, ide-language syntax tests and the ide-lsp mock server.

Co-authored-by: Pecnikas <[email protected]>
2026-12-02 13:17:39 +08:00
Kamal ElFadlтаelfadl b7ef68df71 feat(debugger): make the expanded value tree popup resizable (#7374)
Expanding an object in the debugger's editor value tooltip fixed the tree at 460x260 px inside the hint's 480 px cap, truncating nested fields and package paths. The expanded tree now resizes from all eight edges and corners up to the viewport (minimum 280x120 px) and remembers its size (openidea.debugger.valueTreeSize.v1). hint.ts forwards resize/positioned from built hint content to CodeMirror's TooltipView so the tooltip keeps the dragged size and position.

Covered by valueHint.test.ts.

Co-authored-by: elfadl <[email protected]>
2026-12-02 13:08:52 +08:00
Kamal ElFadlтаelfadl fdc4df4752 feat(search): make Search Everywhere resizable from all edges and corners (#7373)
Search Everywhere opened at a fixed 700 px width with its height capped at 600 px, clipping long paths, containers and previews on wide monitors. Dialog's resizable="both" now resizes from all eight edges and corners (the opposite edge stays put), not only the bottom-right grip, and Search Everywhere uses it with a remembered size (openidea.search.everywhereSize.v1, clamped to its minimum). The other resizable dialogs get the edge handles too.

Covered by Dialog and Search Everywhere tests.

Co-authored-by: elfadl <[email protected]>
2026-12-02 13:04:52 +08:00
l0ng-ai 54ce048ec9 fix(vim): let af / if work on the right-hand side of a noremap (#7382)
A noremap runs its keys against codemirror-vim's built-in keymap only, and the function text objects were added after every mapclear as user mappings, so nnoremap X daf deleted nothing (same cause as <C-g>u in #7364). af / if are now part of the built-in keymap through the existing vim-core patch, with a placeholder motion the host overrides, and are no longer re-mapped after mapclear.
2026-12-02 12:58:43 +08:00
643 змінених файлів з 25354 додано та 2304 видалено

No files matched your search

+129
Переглянути файл
@@ -0,0 +1,129 @@
---
name: pr
description: Prepare and open an OpenIDEA pull request that a maintainer can accept from its description — scope check, the checks CI runs, evidence chosen by the kind of change, UX consistency review, and a filled-in template. Use before opening or updating a PR ("提 pr", "open a PR", "写 PR 描述", "准备验收证据").
---
# Open a pull request with evidence
A reviewer should be able to accept the PR from its description: what changed, why, and proof
that it works and didn't break its neighbours. Evidence is the part people skip; it is required.
## 1. Scope
- One problem per PR. If the description needs more than 2–4 sentences, split it.
- `Closes #<n>` when it resolves an issue. Read the issue's comments first: a maintainer may
already have decided how it should behave.
- The diff contains only what the problem needs: no drive-by refactors, formatting of untouched
files, generated files you didn't need to regenerate, or local IDE state (`.openidea/`).
- A product decision you can't make (layout or navigation restructure, a changed default, an
unclear expected behaviour) → ask in the issue, label `needs-decision`, stop.
- Title in Conventional Commits, written as the commit you want on `main`:
`fix(editor): keep the caret visible after folding`. It describes the change, not the
process; no references to screenshots, other products or "parity".
## 2. Checks
Run what CI runs for the parts you touched (`AGENTS.md` § Before opening a PR). Run long checks
one at a time. Paste the command and its result line (`test result: ok. 412 passed`,
`Tests 87 passed`), not "tests pass".
Easy to miss:
| You touched | Also run |
| --------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| Any `.ts`/`.tsx`, including tests | `pnpm typecheck` |
| A feature's UI | every spec under `e2e/` whose name contains the feature |
| New regex in frontend code | `pnpm vitest run src/platform/webkitCompatibility.test.ts` |
| Text catalog keys | `pnpm vitest run src/platform/locales/textCatalog.test.ts src/platform/i18n.test.ts` |
| `tokens.css` | `pnpm gen:theme-docs`, then the full `pnpm test` |
| Moved or removed exports | `pnpm knip` |
| A `pub fn` signature | `cargo test -p <crate>` (all targets), or workspace clippy |
| A new crate dependency, or imports in files the smoke runs load | `pnpm vitest run scripts/smoke-paths.test.ts` |
| IPC types | `pnpm gen:bindings`, commit `src/bindings.ts` |
| `wit/` or the plugin SDK | `plugins/build.sh`, commit the rebuilt `dist/` |
## 3. Evidence
Pick every row that applies. Evidence must come from the final commit of the branch; re-take it
after review changes that affect it.
| Change | Evidence |
| ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Bug fix | A test that fails on `main` and passes on the branch (name it), or exact steps from a fresh start with the before/after result |
| Visible UI | `before.png` / `after.png` at the same state and window size. Every theme the change touches (at least Islands Light and Islands Dark when colours, borders or icons change). The narrow case when width matters |
| Interaction: multi-step, drag and drop, keyboard, focus, animation | A short recording (GIF/MP4), or numbered screenshots of each step |
| Keyboard shortcut or action | Where it appears (Find Action, menu, keymap settings) and that it doesn't clash in the default keymaps |
| Code intelligence / language support | Which `fixtures/` project, `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` output; for Java, `pnpm eval --only <id>` numbers before/after |
| Run / debug | `pnpm smoke smoke/run.test.ts -t <language>` or `smoke/debug.test.ts`, plus a screenshot of the Run/Debug tool window |
| Performance | Before/after numbers on the same machine and build type (`pnpm perf`, `pnpm perf:rust`, or the exact measurement), and evidence the results are identical: a fast path must return the same results or fall back |
| Windows / Linux only | The platform's CI job, and a screenshot or log from a real machine. Say plainly if you couldn't run it on that platform |
| Backend / IPC | Test output; logs for behaviour tests can't reach |
| Remote development / containers / WSL | The flow against a real `openidea-server` host or container, with a screenshot or log |
| Plugin API / `wit/` | A sample plugin exercising the change, and the rebuilt `dist/` |
| Settings / persisted data / migrations | Start from data written by the previous release and show it still loads and behaves the same |
| Security fix | A test for the attack case. Describe the class of problem only; follow `SECURITY.md` for anything not yet public |
| Copy, docs, pure refactor | The commands run, and "No visible change" / "no behaviour change" stated |
Also state what else the change could affect (other languages, platforms, entry points such as
menu / context menu / shortcut, other themes) and how you checked each.
How to capture:
- Use the `verify` skill to drive the app and take screenshots. Before: on `main` (or with the
fix reverted). After: on the branch, same state and window size.
- Crop to the relevant area when the window is large, but keep enough context to locate it.
- Drag screenshots and recordings into the PR description on GitHub. Never commit them.
- No real credentials, tokens, private repository names or personal paths in screenshots or logs.
## 4. UX consistency
For any change users can see, review it against `DESIGN.md`, `PRODUCT.md` and
`docs/en/contribute/guidelines/ui.mdx` before taking the "after" screenshots:
- Tokens only; spacing on the `--space-*` scale; icons from `src/ui/icons.tsx`; no emoji.
- Built from `src/ui/` primitives and workbench contributions; it looks like its neighbours
(same row height, font size, padding, hover/selection, empty state) rather than new.
- Same action, same name, place and shortcut as elsewhere in the IDE.
- Keyboard reachable, visible focus, focus returns sensibly; `aria-label` on icon buttons.
- Every new string in `en.json` and `zh.json`; long translations don't break the layout.
- Light and dark, default and narrow widths all look right.
- The Impeccable design skills can help critique and polish; they read `DESIGN.md`,
`PRODUCT.md` and `.impeccable/`.
A layout or navigation restructure needs a maintainer decision first (§ 1).
## 5. Description
Fill in `.github/pull_request_template.md`; keep it short and plain:
```markdown
Closes #123
## What and why
<The change a user notices, and the root cause. 2–4 sentences.>
## How it was verified
- [x] Bug fix: `pnpm vitest run src/features/editor/folding.test.ts` — the new
`keeps caret visible after fold` fails on main, passes here (12 passed)
- [x] Visible UI: before / after (Islands Light, Islands Dark)
<screenshots>
- `pnpm typecheck`, `pnpm lint`, `pnpm e2e e2e/editor-folding.spec.ts` — all pass
- Also affected: folding from the gutter and from ⌘- — both checked in the app
## Review focus
<Optional.>
```
The `PR check` workflow labels the PR `needs-info` when **How it was verified** is empty, or when
the PR changes UI files and the section has no screenshot or recording and doesn't say
"No visible change".
## 6. Before you push
- Re-read the diff as the reviewer: anything unrelated, debug output, commented-out code,
leftover TODOs?
- Rebased on current `main`; checks re-run if the rebase changed anything they cover.
- Open as draft while evidence is missing; mark ready once it's in.
+59
Переглянути файл
@@ -0,0 +1,59 @@
---
name: verify
description: Build, launch and drive the OpenIDEA desktop app through the Tauri MCP bridge to verify a change at runtime.
---
# Verify OpenIDEA in the running app
## Launch
- Run the app from the worktree that holds the change: `pnpm tauri dev` in the background, logging
into your task's scratch subdirectory. Use `pnpm dev:app` instead when your checks call
`window.__TAURI__` from `execute_js`. The wrapper gives each worktree its own app identity, data,
settings and Vite port, so other worktrees and the installed app don't interfere. If it reports a
session already running for this worktree, reuse that one.
- Once the app is up, `pnpm dev:status` lists this worktree's MCP bridges. Pass the reported
`appIdentifier` (the port) on every `mcp__tauri__*` call. The MCP server is shared between
sessions: never `driver_session stop` without an `appIdentifier`, and re-check `document.title` /
`location.href` before acting if anything looks off.
- Make sure the binary contains the change: a session already running for this worktree may be an
older build. Restart it after Rust changes; frontend changes reload through Vite.
- After the app restarts, `driver_session start` again for your port (a stale session says "Already connected").
- If the `pnpm tauri dev` process exits while the app window stays open, Vite is gone and any webview
reload shows an empty `#root`. Stop that app and start the session again.
- Stop everything you started when done and nothing else; never use process-name kills.
## Driving
- `manage_window focus` before screenshots / timing-sensitive steps: a background window throttles timers
(debounced LSP / VCS refreshes stall, `setTimeout` promises in `execute_js` time out) and native
screenshots come back black.
- Settings is a separate native window `settings-main`; pass `windowId`, focus it before screenshotting.
- CodeMirror / xterm ignore MCP `type`. Focus the element, then `document.execCommand('insertText', false, text)`.
For xterm Enter, dispatch a `keydown` (`key: 'Enter', keyCode: 13`) on `.xterm-helper-textarea`.
- MCP clicks arrive with `event.detail === 0`; CodeMirror treats them as line-select clicks. Set the caret
through the view instead: `document.querySelector('.cm-content').cmTile.view`.
- MCP `text` strategy can resolve to a hidden node; prefer coordinates (CSS px = image px × 0.9) or CSS selectors.
- CSS-module edits often trigger a full page reload in dev: dialogs close, Run sessions and terminal
scrollback reset, and each reload spawns a fresh shell. Re-open what you were testing.
## Evidence
- For UI or interaction changes, capture `before.png` (on `main` or with the fix reverted) and
`after.png` at the same state and window size, into your task's scratch subdirectory. Multi-step
flows: a numbered series (`after-1.png`, `after-2.png`, ...). When colours, borders or icons
change, take each in Islands Light and Islands Dark. The `pr` skill lists what evidence each
kind of change needs.
- Report the absolute paths; they go into the PR's **How it was verified** section and the triage
acceptance entry. Never commit screenshots to the feature branch.
## Fixture
`fixtures/` has sample projects (go-app, rust-app, ts-app, kotlin-gradle, polyglot). Copy one into
your scratch directory before editing it, and don't commit the IDE state it creates (`.openidea/`).
## Flows worth driving
⌘⇧O Goto File · ⌘⇧F Find in Files (preview scroll + highlight) · ⌘⇧A Find Action · editor edit/undo/autosave ·
Terminal (Unicode, venv) · Commit view at the default narrow width · Problems · Run → Stop · Project view
New / Delete (nested `a/b.txt` names) · ⌘, Settings search (+ Keymap filter) · Git Log on a repo without commits.
+1
Переглянути файл
@@ -0,0 +1 @@
../../.agents/skills/pr
+1
Переглянути файл
@@ -0,0 +1 @@
../../.agents/skills/verify
+14 -5
Переглянути файл
@@ -7,11 +7,20 @@
## How it was verified
<!-- Required. Commands you actually ran and their results; what else this could
affect and how you checked it still works.
Visible UI changes: before/after screenshots (not for removed UI or copy-only
changes). Multi-step interactions: a recording.
Backend changes: logs or command output. -->
<!-- Required, from the final version of this branch. Commands you actually ran and
their results; what else this could affect and how you checked it still works.
Then the evidence for each kind of change this PR makes (AGENTS.md § Issues & PRs):
- Bug fix: a test that fails on main and passes here, or exact repro steps
- Visible UI: before/after screenshots, same state and size; each theme touched
- Interaction (multi-step, drag, keyboard, focus): a recording
- Code intelligence / run / debug: language_smoke or smoke output on a fixture
- Performance: before/after numbers on the same machine, and the results unchanged
- Windows/Linux only: CI job plus a screenshot or log from a real machine
- Settings / persisted data: starting from the previous version's data
- Copy, docs, refactor, no UI change: write "No visible change"
Drag screenshots and recordings in here; don't commit them. -->
## Review focus
+2 -1
Переглянути файл
@@ -36,6 +36,7 @@ on:
- "src/editor/core/cm/iconArea.ts"
- "src/editor/core/cm/inlineBg.ts"
- "src/editor/core/cm/localAppearance.ts"
- "src/editor/core/cm/lineNumberOptions.ts"
- "src/editor/lsp/availability.ts"
- "src/editor/lsp/diagnostics.ts"
- "src/editor/lsp/files.ts"
@@ -110,7 +111,7 @@ jobs:
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|lineNumberOptions|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
+20 -2
Переглянути файл
@@ -1,9 +1,9 @@
name: PR check
on:
# pull_request_target so the check can label PRs from forks. It never checks out
# or runs PR code: it only reads the PR title and description.
# or runs PR code: it only reads the PR title, description and changed file names.
pull_request_target:
types: [opened, edited, reopened, ready_for_review]
types: [opened, edited, reopened, ready_for_review, synchronize]
permissions:
issues: write
@@ -34,6 +34,24 @@ jobs:
const { owner, repo } = context.repo;
const issue_number = pr.number;
if (verified && verified[1].trim()) {
const section = verified[1];
const hasMedia =
/!\[[^\]]*\]\(|<img\b|<video\b|github\.com\/user-attachments\/|https?:\/\/\S+\.(png|jpe?g|gif|webp|mp4|mov|webm)\b/i.test(section);
const optedOut = /no visible change/i.test(section);
if (!hasMedia && !optedOut) {
const files = await github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number: issue_number, per_page: 100 });
const ui = files
.filter(f => f.status !== 'removed')
.map(f => f.filename)
.filter(name => /^src\/.*\.(tsx|css)$/.test(name) && !/\.(test|spec)\.tsx$/.test(name));
if (ui.length) {
const shown = ui.slice(0, 3).map(n => `\`${n}\``).join(', ') + (ui.length > 3 ? ', …' : '');
problems.push(`This PR changes UI files (${shown}). Add before/after screenshots, or a recording for interactions, to **How it was verified**; if nothing users see changed, write "No visible change" and say what you checked.`);
}
}
}
const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number });
const existing = comments.find(c => c.user.type === 'Bot' && c.body.includes(MARKER));
const labeled = pr.labels.some(l => l.name === LABEL);
+6 -5
Переглянути файл
@@ -33,12 +33,13 @@ target/
test-results/
playwright-report/
# Local AI agent files
AGENTS.md
CLAUDE.md
# Local AI agent files. Shared skills live in .agents/skills; .claude/skills links to them.
CLAUDE.local.md
.agents/
.claude/
.claude/*
!.claude/skills/
.claude/skills/*
!.claude/skills/pr
!.claude/skills/verify
# Local reference screenshots
pycharm-screenshots/
+197
Переглянути файл
@@ -0,0 +1,197 @@
# OpenIDEA — contributor guide
Rust + Tauri 2 desktop IDE with full-featured, multi-language code intelligence.
Visual style: rounded content islands on a grey frame, low-contrast greys, one cool accent;
Islands Light is the default theme. `src/styles/tokens.css` is the source of truth for colours
and metrics; `DESIGN.md` and `PRODUCT.md` describe the design system and who the product is for.
## Layout
- `crates/ide-*` — backend crates; one domain each. Depend on `ide-core` for shared
types; never reach into another crate's internals.
- `src-tauri/` — glue only: `state.rs` (AppState / Project), `commands/<domain>.rs`
(desktop-only commands; the adapters of `ide-host` commands are derived), `events.rs`.
No domain logic here.
- `src/bindings.ts` — generated by tauri-specta (`pnpm gen:bindings`). Never edit.
- `src/platform/` — ipc (`call`, `onIdeEvent`, `nextRequestId`), actions registry,
keymap + dispatcher, context keys / `when` clauses, project store.
- `src/workbench/contributions.ts` — extension points (tool windows, status items,
overlays, editor kinds) and cross-feature services (editor, tool windows, notifications).
- `src/ui/` — design-system primitives. `src/features/<name>/` — one feature each,
exporting `activate()` registered in `src/features/index.ts`.
- `languages/<id>.toml` — language definitions (detection, comments, LSP, DAP).
- `crates/ide-host` — the `openidea-server` binary for remote development and the
`openidea-plugin` CLI (plugin starter templates live in its `templates.rs`).
- `wit/` — plugin interface definitions; `plugins/` — sample and bundled plugins.
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`). `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/`.
## Rules
- IPC coordinates: 0-based lines, **UTF-16** columns/offsets everywhere (`ide-core::text`).
- Every command returns `IdeResult<T>`; convert internal errors at the crate edge.
- Declare a command once, on its implementation: `#[command(trust = …)]` in `ide-host::ops`
plus its module's `domain!` list (Tauri adapter, server handler and bindings are derived);
desktop-only commands use `#[desktop_command(trust = …)]` and `desktop_domain!`.
- Streaming → `tauri::ipc::Channel<T>`; cancellable → UI-allocated `RequestId` +
`cancel_request`. Backend → UI notifications → `IdeEvent` via `EventSink`.
- Long work never blocks the UI thread or a Tauri command thread: use
`spawn_blocking`/rayon, honour `CancellationToken`.
- Frontend features never import each other; communicate via actions, contributions
and services. All user-invocable behaviour is an action with a stable id; default
shortcuts live in `src/platform/keymaps/`.
- Styling: CSS Modules + tokens only (no hex literals in components). Inline SVG
icons from `src/ui/icons.tsx`, never emoji. Real `<button>`/`<input>`; `aria-label` on icon buttons.
`gap` uses the `--space-*` scale (`src/styles/tokens.css`, 4px grid) where a value is on it.
- User-visible text goes through the text catalog: add every new string to both
`src/platform/locales/text/en.json` and `zh.json` (`textCatalog.test.ts` enforces it).
Other locales may lack entries; their UI shows the English text until a translator adds it.
- Keep comments sparse and purposeful; match surrounding style.
- New regular expressions in frontend code must run on WebKit (no lookbehind):
`src/platform/webkitCompatibility.test.ts` checks them.
- For GUI verification, prefer Tauri MCP; use Computer Use only when Tauri MCP is
unavailable or cannot cover the required checks.
## UX changes
A change to what users see or how they interact must look and behave like the rest of the IDE.
- `DESIGN.md` (colours, type, layout, components, Do's and Don'ts) and `PRODUCT.md`
(users, principles, accessibility) are the reference; `docs/en/contribute/guidelines/ui.mdx`
has the code-level rules. Build from `src/ui/` primitives and workbench contributions;
don't create a one-off control, colour or spacing when an existing one fits.
- Check every theme the change touches (at least Islands Light and Islands Dark) and narrow
sizes (e.g. the Commit tool window at its default width, a small window). Long translated
strings must not break the layout.
- Everything works from the keyboard; focus is visible and lands somewhere sensible when a
popup or dialog closes. Icon-only buttons have an `aria-label` and a tooltip.
- Follow the conventions users of this kind of IDE already know: the same action keeps the
same name, place and shortcut across views. Don't invent a new pattern for an existing one.
- Agent and MCP features follow good agent-tool practice: restrained, predictable, reversible.
- Restructuring a page layout or navigation, or changing a default behaviour, needs a
maintainer's decision first: ask in the issue and label it `needs-decision`.
- The Impeccable design skills may be used for design critique and polish; they read
`DESIGN.md`, `PRODUCT.md` and `.impeccable/`. A detector exception goes in
`.impeccable/config.json` with a reason.
## Issues & PRs
Follow `CONTRIBUTING.md` and `.github/pull_request_template.md`: one problem per PR
(`Closes #<n>` when it resolves an issue), reproduce first, keep the diff focused, short plain
description. Unclear product decisions → `needs-decision` and stop.
Every PR carries evidence a reviewer can accept without re-running everything, in
**How it was verified**. It must come from the final version of the branch:
| Change | Evidence |
| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| Bug fix | A test that fails before the fix and passes after, or exact reproduction steps with before/after result |
| Visible UI | Before/after screenshots at the same state and window size; each theme the change touches |
| Interaction (multi-step, drag, keyboard, focus) | A short recording or numbered screenshots |
| Code intelligence / language support | The fixture used and `language_smoke` output; `pnpm eval` numbers for Java |
| Run / debug | `pnpm smoke smoke/run.test.ts` / `smoke/debug.test.ts -t <language>` output |
| Performance | Before/after numbers on the same machine (`pnpm perf`, `pnpm perf:rust` or a stated measurement), plus proof the results are unchanged |
| Windows / Linux only | The platform's CI job, and a screenshot or log from a real machine |
| Backend / IPC | Test output; regenerated `src/bindings.ts` when types changed |
| Remote development | The flow against a real `openidea-server` host |
| Plugin API / `wit/` | `plugins/build.sh` run and `dist/` committed; a sample plugin using the change |
| Settings / persisted data | Behaviour when starting from data written by the previous version |
| Copy, docs, refactor | The commands run; "No visible change" when nothing users see changed |
Attach screenshots and recordings to the PR description; never commit them. The `pr` skill
has the full checklist.
## Skills
Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
`pr` prepares a pull request — checks to run, evidence for the kind of change, description;
`verify` drives the running app through Tauri MCP and captures screenshot evidence.
## Commands
- Optional: `mise install` provisions the contributor toolchain; `mise tasks` lists the task aliases.
See [Development setup](docs/en/contribute/setup.mdx). The direct commands below still work without mise.
- `pnpm tauri dev` — run the app with worktree isolation. Use Node 22.22.2 or later on the 22.x line.
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
this worktree's running MCP bridges and actual ports.
- `pnpm build` — typecheck + bundle frontend.
- `pnpm dogfood:local [--build-only]` (or `mise run dogfood:local`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
- `pnpm dogfood:all <remote_name> [--restart | --no-restart]` (or `mise run dogfood:all <remote_name>`) — run `dogfood:local` and `dogfood:remote <remote_name>` in parallel.
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
- `pnpm smoke smoke/run.test.ts -t <language>` — run and test that language's fixture through the
run store and a real `openidea-server` (build it first: `cargo build -p ide-host --bin openidea-server`).
- `pnpm smoke smoke/debug.test.ts -t <language>` — debug that fixture's entry point the same way, with
the debugger the IDE installs (on macOS, CodeLLDB and Delve may need Developer Mode:
`sudo DevToolsSecurity -enable`).
- `pnpm test`, `pnpm e2e`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm typecheck`,
`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.
## Before opening a PR
Run what CI runs for the parts you touched:
- Rust: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,
`cargo nextest run --workspace`. After changing IPC types, run `pnpm gen:bindings` and
commit `src/bindings.ts`; CI fails if it differs.
- Frontend: `pnpm typecheck` (vitest does not type-check), `pnpm lint`, `pnpm format:check`,
`pnpm knip`, `pnpm test`, `pnpm build`, and every `e2e/` spec of the feature you touched.
- New text keys: `src/platform/locales/textCatalog.test.ts` and `src/platform/i18n.test.ts`.
New or renamed tokens: `pnpm gen:theme-docs`.
- Changed a `pub fn` signature in a crate: run that crate's whole `cargo test`, not one test.
- UI or runtime behaviour: verify in the running app (`.agents/skills/verify`) and collect
the evidence above (`.agents/skills/pr`).
## Pitfalls
- Run a subset of frontend tests with `pnpm vitest run <path>`. `pnpm test -- <path>` ignores
the filter and runs the whole suite, which takes several minutes.
- Don't run clippy while iterating: `pnpm tauri dev` compiles anyway. Run
`cargo fmt --all` + `cargo clippy -p <crate> --all-targets -- -D warnings` once, right
before committing. A cold build cache can take around 5 minutes. Run long checks one at
a time, not chained in one shell call that may hit the 10-minute tool timeout.
- `pnpm tauri dev` does a full debug build. Clippy only checks the code, so a passing clippy
doesn't make the first launch fast.
## Parallel worktrees
Several worktrees can be developed and run side by side.
- Create one per task: `git worktree add ../<name> -b <branch> origin/main`, then
`pnpm install` in it.
- Launch with `pnpm tauri dev` / `pnpm dev:app`, not the raw `pnpm exec tauri dev` CLI. The
wrapper starts Vite on a worktree-derived port (advancing if occupied), passes its actual
URL to Tauri, and reports an existing launcher instead of starting another for the same
worktree. HMR uses the Vite port.
- Debug app identity, data, settings, logs and single-instance scope follow the canonical
worktree path captured at build time, independent of launch cwd. Launching the same debug
binary again focuses its existing instance and forwards its path argument. Different
worktrees and the installed release can coexist. `--release` uses normal release identity
and bypasses the development wrapper.
- MCP bridge ports are dynamic (9223–9322). Use `pnpm dev:status`, connect to the reported
port, verify identifier/cwd, and pass `appIdentifier: <port>` explicitly. Do not assume the
default MCP session belongs to this worktree.
- Keep each worktree's Cargo output directory separate; do not point `CARGO_TARGET_DIR` or
`target` symlinks at a shared directory.
- Each worktree's first build is cold (several minutes) and `cargo build` output takes
around 9 GB; tests, clippy and incremental builds add more. Avoid running several heavy builds on one machine at the same time.
- Stop only processes started for the current worktree/session. Never use broad
process-name kills such as `pkill openidea`.
- When done: stop that worktree's app and dev session, delete its build output, then
`git worktree remove ../<name>`.
Symlink
+1
Переглянути файл
@@ -0,0 +1 @@
AGENTS.md
+8 -2
Переглянути файл
@@ -1,6 +1,7 @@
# Contributing to OpenIDEA
These rules apply to everyone, and to any coding agent working on their behalf.
Project layout, coding rules, commands, checks and the evidence a PR needs are in [AGENTS.md](AGENTS.md).
## Issues
@@ -26,7 +27,12 @@ These rules apply to everyone, and to any coding agent working on their behalf.
- **How it was verified** is required: the commands you ran and their results,
and what else the change could affect. Changes to what users see need before/after
screenshots; multi-step interactions need a recording. UI that goes away with a removed
feature, copy-only and non-visual changes don't; say what you checked instead.
feature, copy-only and non-visual changes don't; write "No visible change" and say what
you checked instead. [AGENTS.md](AGENTS.md#issues--prs) lists the evidence for each kind of
change (tests, smoke output, perf numbers, real-machine logs…).
- Changes to what users see follow [DESIGN.md](DESIGN.md) and the existing UI: tokens,
`src/ui/` primitives, both themes, keyboard access. Restructuring a layout or navigation
needs a maintainer's decision first.
- If a change needs a product decision you can't make, ask in the issue and stop
rather than guessing.
@@ -35,4 +41,4 @@ and the plugin API. Community plugins live in their authors' repositories and
are listed through [l0ng-ai/openidea-plugins](https://github.com/l0ng-ai/openidea-plugins);
see [`plugins/README.md`](plugins/README.md) § 8.1.
A check on each PR adds `needs-info` when the verification section is missing, and removes it once it's filled in.
A check on each PR adds `needs-info` when the verification section is missing, or when the PR changes UI files and the section has neither a screenshot nor a recording nor "No visible change". It removes the label once that's fixed.
Створено
+1
Переглянути файл
@@ -4862,6 +4862,7 @@ dependencies = [
"parking_lot 0.12.5",
"portable-pty",
"quick-xml 0.42.0",
"regex",
"serde",
"serde_json",
"specta",
+1
Переглянути файл
@@ -101,6 +101,7 @@ tar = "0.4"
grep-searcher = "0.1"
grep-regex = "0.1"
regex-syntax = "0.8"
regex = "1"
grep-matcher = "0.1"
nucleo-matcher = "0.3"
redb = "4"
+1 -1
Переглянути файл
@@ -4,7 +4,7 @@
`src/ui/brands/*.svg` use the unmodified logo paths from
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
## DuckDB symbol
+18
Переглянути файл
@@ -53,6 +53,24 @@ pub(crate) fn auth_required(code: i64, message: &str) -> bool {
.any(|w| w == ["logged", "out"] || w == ["sign", "in"] || w == ["log", "in"] || w == ["login", "required"])
}
/// Whether a failed request only means the agent hasn't finished starting up: OpenCode
/// rejects session opens until the location's plugins and MCP servers finish activating
/// (`ServiceUnavailableError`, "Location plugins did not finish activating") and reports
/// an unavailable server as `ServerUnavailable`. Both arrive as internal errors naming
/// the cause in `data.errorName`; retrying them once activation completes succeeds.
pub(crate) fn service_warming_up(error: &RpcError) -> bool {
let RpcError::Server { code: codes::INTERNAL_ERROR, message, data } = error else {
return false;
};
if let Some(name) = data.as_ref().and_then(|d| d.get("errorName")).and_then(Value::as_str)
&& matches!(name, "ServiceUnavailableError" | "ServerUnavailable")
{
return true;
}
let lower = message.to_lowercase();
lower.contains("did not finish activating") || lower.contains("opencode server is unavailable")
}
/// The capabilities this client offers, in v1 form.
fn client_capabilities() -> Value {
json!({
+34
Переглянути файл
@@ -52,6 +52,40 @@ fn auth_required_matches_authentication_words_and_sign_in_phrases() {
}
}
#[test]
fn service_warming_up_matches_opencode_startup_races_only() {
for (code, message, data, expected) in [
(
codes::INTERNAL_ERROR,
"Internal error: Internal service failure",
Some(json!({"errorName": "ServiceUnavailableError"})),
true,
),
(
codes::INTERNAL_ERROR,
"Internal error: OpenCode server is unavailable",
Some(json!({"errorName": "ServerUnavailable"})),
true,
),
(codes::INTERNAL_ERROR, "Location plugins did not finish activating", None, true),
(
codes::INTERNAL_ERROR,
"Internal error: Internal service failure",
Some(json!({"errorName": "SQLiteError"})),
false,
),
(codes::INTERNAL_ERROR, "Internal error: Internal service failure", None, false),
(codes::INTERNAL_ERROR, "boom", None, false),
(AUTH_REQUIRED, "Authentication required", None, false),
] {
assert_eq!(
service_warming_up(&RpcError::Server { code, message: message.into(), data: data.clone() }),
expected,
"code={code}, message={message:?}, data={data:?}"
);
}
}
/// The messages of a fixture going `dir` (`in` or `out`).
pub(crate) fn frames(fixture: &str, dir: &str) -> Vec<Value> {
fixture
+182 -1
Переглянути файл
@@ -1,7 +1,10 @@
//! ACP elicitation in form mode: the agent's restricted JSON Schema as form fields, and the
//! user's answer as the `elicitation/create` response.
use crate::model::{AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption};
use crate::model::{
AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption, AgentQuestion,
AgentQuestionOption,
};
use serde::Deserialize;
use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
use serde_json::{Map, Value, json};
@@ -10,6 +13,9 @@ use serde_json::{Map, Value, json};
/// anything else cancels it.
const DECLINE: &str = "decline";
/// What the question card sends for Skip.
const SKIP: &str = "reject";
/// The form `elicitation/create` asks for; `Err` when it asks for something else.
pub(crate) fn form_of(params: &Value) -> Result<AgentForm, String> {
if params.get("mode").and_then(Value::as_str) != Some("form") {
@@ -148,6 +154,97 @@ fn scalar(value: &Value) -> Option<String> {
}
}
/// The questions a form asks when it is an agent's question tool in form shape: every field
/// a choice, each followed by its own text field for a typed answer, named after it
/// (`question_0` + `question_0_custom` from claude-agent-acp's `AskUserQuestion`, `q0` +
/// `q0__other` from OMP's `ask`). They are shown and answered as the agent's questions, one
/// at a time like a native `AskUserQuestion` (#7359); [`answer_questions`] turns the answers
/// back into the form's values. `None` for any other form.
pub(crate) fn questions_of(form: &AgentForm, params: &Value, message: &str) -> Option<Vec<AgentQuestion>> {
let choices = form.fields.len() / 2;
if choices == 0 || form.fields.len() % 2 == 1 {
return None;
}
let properties = params.pointer("/requestedSchema/properties");
form.fields
.chunks(2)
.map(|pair| {
let [choice, text] = pair else { return None };
let asks = matches!(choice.kind, AgentFormFieldKind::Choice | AgentFormFieldKind::Choices)
&& !choice.options.is_empty()
&& text.kind == AgentFormFieldKind::Text
&& text.name.len() > choice.name.len()
&& text.name.starts_with(&choice.name);
if !asks {
return None;
}
let (title, description) = (choice.title.trim(), choice.description.trim());
let (header, question) = if choices == 1 && !message.is_empty() {
(if title == message || title == choice.name { "" } else { title }, message)
} else if description.is_empty() {
("", title)
} else {
(if title == choice.name { "" } else { title }, description)
};
let schema = properties.and_then(|p| p.get(&choice.name));
let options = choice
.options
.iter()
.map(|option| AgentQuestionOption {
label: option.label.clone(),
description: option.description.clone(),
preview: schema.and_then(|s| option_preview(s, &option.value)),
})
.collect();
Some(AgentQuestion {
answer_key: Some(choice.name.clone()),
header: header.to_owned(),
question: question.to_owned(),
multi_select: choice.kind == AgentFormFieldKind::Choices,
options,
})
})
.collect()
}
/// The preview claude-agent-acp forwards beside an option (`_meta["_claude/askUserQuestionOption"]`).
fn option_preview(schema: &Value, value: &str) -> Option<String> {
let listed = schema.get("oneOf").or_else(|| schema.get("anyOf")).or_else(|| schema.pointer("/items/anyOf"));
listed?
.as_array()?
.iter()
.find(|o| o.get("const").and_then(Value::as_str) == Some(value))?
.pointer("/_meta/_claude~1askUserQuestionOption/preview")?
.as_str()
.map(str::to_owned)
}
/// The form reply to the answers of [`questions_of`]'s questions (question key to the picked
/// labels and the typed text): picked options as the choice's values, the text in the field
/// beside it. The question card's Skip declines the form; nothing passes through.
pub(crate) fn answer_questions(form: &AgentForm, reply: Option<&str>) -> Option<String> {
let reply = reply?;
if reply == SKIP {
return Some(DECLINE.to_owned());
}
let Ok(answers) = serde_json::from_str::<Map<String, Value>>(reply) else { return Some(reply.to_owned()) };
let mut values = Map::new();
for pair in form.fields.chunks(2) {
let [choice, text] = pair else { continue };
let items = answers.get(&choice.name).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str);
let (mut picked, mut typed) = (Vec::new(), Vec::new());
for item in items {
match choice.options.iter().find(|o| o.label == item) {
Some(option) => picked.push(json!(option.value)),
None => typed.push(item),
}
}
values.insert(choice.name.clone(), Value::Array(picked));
values.insert(text.name.clone(), json!([typed.join("\n")]));
}
Some(Value::Object(values).to_string())
}
/// A form is submitted from its own card; this option only names a declined form.
pub(crate) fn options() -> Vec<AgentPermissionOption> {
vec![AgentPermissionOption { id: DECLINE.to_owned(), name: "Decline".to_owned(), kind: "reject_once".to_owned() }]
@@ -295,6 +392,90 @@ mod tests {
assert_eq!(chosen, "count: 3; ok: no; size: Small; tags: a, b");
}
/// What claude-agent-acp sends for `AskUserQuestion` with two questions.
fn claude_questions() -> Value {
json!({
"sessionId": "s", "mode": "form", "message": "Please answer the following questions.",
"requestedSchema": { "type": "object", "properties": {
"question_0": { "type": "string", "title": "Delivery", "description": "How should it ship?",
"oneOf": [{ "const": "Util + table (Recommended)", "title": "Util + table (Recommended)",
"description": "Tracks tasks",
"_meta": { "_claude/askUserQuestionOption": { "preview": "```\nUtil\n```" } } },
{ "const": "Util only", "title": "Util only" }] },
"question_0_custom": { "type": "string", "title": "Other" },
"question_1": { "type": "array", "title": "Targets", "description": "Who receives it?",
"items": { "anyOf": [{ "const": "Members", "title": "Members" },
{ "const": "Tags", "title": "Tags" }] } },
"question_1_custom": { "type": "string", "title": "Other" }
} }
})
}
fn in_order(params: &Value, names: &[&str]) -> AgentForm {
let mut form = form_of(params).unwrap();
form.fields.sort_by_key(|f| names.iter().position(|n| *n == f.name));
form
}
#[test]
fn a_question_tool_form_is_asked_as_questions() {
let params = claude_questions();
let form = in_order(&params, &["question_0", "question_0_custom", "question_1", "question_1_custom"]);
let questions = questions_of(&form, &params, "Please answer the following questions.").unwrap();
let [delivery, targets] = questions.as_slice() else { panic!("{questions:?}") };
assert_eq!(
(
delivery.answer_key.as_deref(),
delivery.header.as_str(),
delivery.question.as_str(),
delivery.multi_select
),
(Some("question_0"), "Delivery", "How should it ship?", false)
);
assert_eq!(delivery.options[0].description, "Tracks tasks");
assert_eq!(delivery.options[0].preview.as_deref(), Some("```\nUtil\n```"));
assert_eq!(delivery.options[1].preview, None);
assert_eq!((targets.question.as_str(), targets.multi_select), ("Who receives it?", true));
let reply = json!({ "question_0": ["Util only", "keep it small"], "question_1": ["Members", "Tags"] });
let reply = answer_questions(&form, Some(&reply.to_string()));
let (response, chosen) = answer(&form, reply.as_deref());
assert_eq!(
response,
json!({ "action": "accept", "content": {
"question_0": "Util only", "question_0_custom": "keep it small", "question_1": ["Members", "Tags"]
} })
);
assert_eq!(chosen, "Delivery: Util only; Other: keep it small; Targets: Members, Tags");
assert_eq!(answer_questions(&form, Some(SKIP)).as_deref(), Some(DECLINE));
assert_eq!(answer_questions(&form, None), None);
}
#[test]
fn a_single_question_reads_from_the_message() {
let params = ask();
let form = in_order(&params, &["q0", "q0__other"]);
let questions = questions_of(&form, &params, "Which database?").unwrap();
assert_eq!((questions[0].header.as_str(), questions[0].question.as_str()), ("", "Which database?"));
assert_eq!(questions[0].options[0].label, "Postgres");
let reply = answer_questions(&form, Some(&json!({ "q0": ["SQLite"] }).to_string()));
assert_eq!(answer(&form, reply.as_deref()).0, json!({ "action": "accept", "content": { "q0": "sqlite" } }));
}
#[test]
fn other_forms_stay_forms() {
let only_choices = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
"size": { "type": "string", "enum": ["s", "l"] }, "env": { "type": "string", "enum": ["dev"] }
} } }))
.unwrap();
assert_eq!(questions_of(&only_choices, &json!({}), "Pick"), None);
let unrelated_text = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
"size": { "type": "string", "enum": ["s", "l"] }, "note": { "type": "string" }
} } }))
.unwrap();
assert_eq!(questions_of(&unrelated_text, &json!({}), "Pick"), None);
}
#[test]
fn declining_and_dismissing_send_no_content() {
let form = form_of(&ask()).unwrap();
+9 -2
Переглянути файл
@@ -16,14 +16,19 @@ pub(crate) fn from_content(content: &Value) -> Option<AgentImage> {
if let (Some(data), Some(mime)) = (str_of(content, "data"), str_of(content, "mimeType"))
&& mime.starts_with("image/")
{
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None, inline_number: None });
}
from_uri(str_of(content, "uri")?)
}
"resource" => {
let resource = content.get("resource")?;
let (data, mime) = (str_of(resource, "blob")?, str_of(resource, "mimeType")?);
mime.starts_with("image/").then(|| AgentImage { mime_type: mime.into(), data: data.into(), name: None })
mime.starts_with("image/").then(|| AgentImage {
mime_type: mime.into(),
data: data.into(),
name: None,
inline_number: None,
})
}
"resource_link" => {
let uri = str_of(content, "uri")?;
@@ -51,6 +56,7 @@ pub(crate) fn from_uri(uri: &str) -> Option<AgentImage> {
mime_type: mime.into(),
data: data.into(),
name: None,
inline_number: None,
});
}
uri.starts_with("file://").then(|| from_file(Path::new(&uri_path(uri))))?
@@ -67,6 +73,7 @@ pub(crate) fn from_file(path: &Path) -> Option<AgentImage> {
mime_type: mime.into(),
data: base64::engine::general_purpose::STANDARD.encode(bytes),
name: path.file_name().and_then(|n| n.to_str()).map(str::to_owned),
inline_number: None,
})
}
+94 -35
Переглянути файл
@@ -154,6 +154,14 @@ const REPLAY_GRACE: Duration = Duration::from_millis(300);
/// Notifications are delivered on their own thread: the last `session/update`s of a turn
/// can trail its `session/prompt` response by this much.
const TURN_GRACE: Duration = Duration::from_millis(100);
/// A session open can arrive before the agent finishes activating its plugins and MCP
/// servers (OpenCode: "Location plugins did not finish activating"). That is a transient
/// startup race. The window bounds the session-open requests and the waits between them.
const WARMUP_WINDOW: Duration = Duration::from_secs(30);
/// First wait before retrying a session open the agent answered with "still starting up".
const WARMUP_DELAY: Duration = Duration::from_millis(500);
/// Backoff cap between those startup retries.
const WARMUP_MAX_DELAY: Duration = Duration::from_secs(4);
const STDERR_LINES: usize = 20;
/// An agent idle this long after its turn is stopped when it can reload its session
/// (`session/load`): the next message starts it again where it left off.
@@ -5160,6 +5168,9 @@ impl Task {
}
/// Runs `method` and, on an auth error, tries the agent's own ACP `authenticate` once before retrying.
/// A session open that lands while the agent is still activating its plugins fails with a
/// retryable "service unavailable" (see [`acp::service_warming_up`]); waits that out with
/// backoff rather than failing the task over a startup race.
async fn request_with_auth(
&self,
peer: &acp::Conn,
@@ -5168,19 +5179,39 @@ impl Task {
method: &str,
params: Value,
) -> Result<Value, RpcError> {
let first = peer.request(method, params.clone(), None).await;
if !*tried_auth
&& let Err(RpcError::Server { code, ref message, .. }) = first
&& acp::auth_required(code, message)
&& let Some(method_id) = init.agent_auth_method()
{
*tried_auth = true;
match peer.request::<_, Value>("authenticate", json!({ "methodId": method_id }), None).await {
Ok(_) => return peer.request(method, params, None).await,
Err(e) => tracing::debug!(task = %self.id, method_id, error = %e, "agent authenticate failed"),
let mut deadline = tokio::time::Instant::now() + WARMUP_WINDOW;
let mut delay = WARMUP_DELAY;
loop {
let result = tokio::time::timeout_at(deadline, peer.request(method, &params, None))
.await
.unwrap_or(Err(RpcError::Timeout));
let Err(error) = &result else {
return result;
};
if !*tried_auth
&& let RpcError::Server { code, message, .. } = error
&& acp::auth_required(*code, message)
&& let Some(method_id) = init.agent_auth_method()
{
*tried_auth = true;
let auth = peer.request::<_, Value>("authenticate", json!({ "methodId": method_id }), None);
match tokio::time::timeout(WARMUP_WINDOW, auth).await.unwrap_or(Err(RpcError::Timeout)) {
Ok(_) => {
deadline = tokio::time::Instant::now() + WARMUP_WINDOW;
delay = WARMUP_DELAY;
continue;
}
Err(e) => tracing::debug!(task = %self.id, method_id, error = %e, "agent authenticate failed"),
}
return result;
}
if !acp::service_warming_up(error) || peer.is_closed() || tokio::time::Instant::now() + delay >= deadline {
return result;
}
tracing::info!(task = %self.id, method, "agent still starting up; retrying session open in {delay:?}");
tokio::time::sleep(delay).await;
delay = (delay * 2).min(WARMUP_MAX_DELAY);
}
first
}
async fn ensure_session(self: &Arc<Self>, epoch: u64) -> Result<Live, String> {
@@ -5440,9 +5471,13 @@ impl Task {
if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) {
return Err(SessionOpenError { message, allow_acp_fallback: false });
}
// A writer conflict is temporary: retrying must retain the original session ID.
if spec.driver == provider::Driver::Codex
&& matches!(&e, RpcError::Server { message, .. } if message.contains("already has an active writer"))
// Warm-up, timeouts and writer conflicts can clear before the next attempt.
let writer_conflict = spec.driver == provider::Driver::Codex
&& matches!(&e, RpcError::Server { message, .. } if message.contains("already has an active writer"));
if acp::service_warming_up(&e)
|| matches!(e, RpcError::Timeout)
|| writer_conflict
|| pending_model.is_some()
{
return Err(SessionOpenError {
message: format!(
@@ -5453,16 +5488,6 @@ impl Task {
allow_acp_fallback: false,
});
}
if pending_model.is_some() {
return Err(SessionOpenError {
message: format!(
"Couldn't reopen this conversation's {} session: {}",
spec.name,
self.describe(e)
),
allow_acp_fallback: false,
});
}
self.start_fresh.store(true, Ordering::Release);
return Err(SessionOpenError {
message: format!(
@@ -5805,6 +5830,7 @@ impl Task {
/// A user-facing message for a failed request, with the agent's last stderr lines when it died.
fn describe(&self, e: RpcError) -> String {
let warming = acp::service_warming_up(&e);
match e {
RpcError::Closed => {
let tail: Vec<String> = self.stderr.lock().iter().cloned().collect();
@@ -5814,7 +5840,15 @@ impl Task {
format!("The agent process exited:\n{}", tail.join("\n"))
}
}
RpcError::Server { message, data, .. } => with_details(message, data.as_ref()),
RpcError::Server { message, data, .. } => {
let text = with_details(message, data.as_ref());
if warming {
format!("{text}\n\nThe agent hasn't finished starting up. Try again in a moment.")
} else {
text
}
}
RpcError::Timeout => "The agent timed out. Try again in a moment.".into(),
e => e.to_string(),
}
}
@@ -6204,6 +6238,7 @@ impl Task {
}
let id = self.next_permission.fetch_add(1, Ordering::Relaxed);
let message = params.get("message").and_then(Value::as_str).unwrap_or_default().trim().to_owned();
let questions = elicitation::questions_of(&form, params, &message);
let (tx, rx) = std::sync::mpsc::channel();
let entry = {
let mut file = self.file.lock();
@@ -6218,8 +6253,8 @@ impl Task {
title,
command: None,
options: elicitation::options(),
questions: Vec::new(),
form: Some(form.clone()),
questions: questions.clone().unwrap_or_default(),
form: if questions.is_some() { None } else { Some(form.clone()) },
chosen: None,
});
self.permissions.lock().insert(id, tx);
@@ -6233,7 +6268,10 @@ impl Task {
self.mark_dirty([(None, entry)]);
self.emit_task();
self.emit_attention_if_input_pending(epoch);
let reply = rx.recv().ok().flatten();
let mut reply = rx.recv().ok().flatten();
if questions.is_some() {
reply = elicitation::answer_questions(&form, reply.as_deref());
}
let (response, chosen) = elicitation::answer(&form, reply.as_deref());
if self.shared.shut_down_since(epoch) {
return Ok(response);
@@ -6492,12 +6530,35 @@ fn asked_questions(params: &Value) -> (Vec<AgentQuestion>, bool) {
(Vec::new(), false)
}
/// ACP content blocks: the text, each file (embedded when its text is in `contents`, else
/// a `resource_link`), then the images.
/// ACP content blocks, with text and inline images in prompt order. File references and
/// attachments without an inline label follow the prompt.
fn blocks(prompt: &AgentPrompt, contents: &[Option<String>]) -> Vec<Value> {
let mut out = Vec::new();
if !prompt.text.is_empty() {
out.push(json!({ "type": "text", "text": prompt.text }));
let mut inline: HashMap<_, _> =
prompt.images.iter().filter_map(|image| Some((image.inline_number?, image))).collect();
let mut start = 0;
const LABEL: &str = "[Image #";
if !inline.is_empty() {
for (at, _) in prompt.text.match_indices(LABEL) {
let digits_start = at + LABEL.len();
let tail = &prompt.text[digits_start..];
let count = tail.bytes().take(10).take_while(u8::is_ascii_digit).count();
if tail.starts_with('0') || tail.as_bytes().get(count) != Some(&b']') {
continue;
}
let Ok(number) = tail[..count].parse::<u32>() else { continue };
let Some(image) = inline.remove(&number) else { continue };
if at > start {
out.push(json!({ "type": "text", "text": &prompt.text[start..at] }));
}
let mut block = images::content(image);
block["_meta"] = json!({ "openideaImageNumber": number });
out.push(block);
start = digits_start + count + 1;
}
}
if start < prompt.text.len() {
out.push(json!({ "type": "text", "text": &prompt.text[start..] }));
}
for (i, f) in prompt.files.iter().enumerate() {
let uri = file_uri(&f.0);
@@ -6506,9 +6567,7 @@ fn blocks(prompt: &AgentPrompt, contents: &[Option<String>]) -> Vec<Value> {
None => json!({ "type": "resource_link", "uri": uri, "name": file_name(&f.0) }),
});
}
for i in &prompt.images {
out.push(json!({ "type": "image", "mimeType": i.media_type(), "data": i.data }));
}
out.extend(prompt.images.iter().filter(|i| i.inline_number.is_none()).map(images::content));
out
}
+3
Переглянути файл
@@ -431,6 +431,9 @@ pub struct AgentImage {
/// Base64, without a `data:` prefix.
pub data: String,
pub name: Option<String>,
/// The `[Image #n]` label in the prompt text for an inline attachment.
#[specta(optional)]
pub inline_number: Option<u32>,
}
impl AgentImage {
+6 -1
Переглянути файл
@@ -553,7 +553,12 @@ fn image_content(image: &crate::model::AgentImage) -> Value {
/// A generated image: inline (base64 PNG) or, when codex saved it, the file.
fn generated_image(item: &Value) -> Option<crate::model::AgentImage> {
if let Some(data) = item.get("result").and_then(Value::as_str).filter(|d| !d.is_empty()) {
let image = crate::model::AgentImage { mime_type: "image/png".into(), data: data.into(), name: None };
let image = crate::model::AgentImage {
mime_type: "image/png".into(),
data: data.into(),
name: None,
inline_number: None,
};
return Some(crate::model::AgentImage { mime_type: image.media_type().into(), ..image });
}
crate::images::from_file(std::path::Path::new(item.get("savedPath")?.as_str()?))
+4
Переглянути файл
@@ -1372,6 +1372,10 @@ fn build_prompt_payload(session_id: &str, blocks: &[Value]) -> (String, Vec<Valu
{
let path_str = saved.to_string_lossy().into_owned();
let name = saved.file_name().and_then(|n| n.to_str()).unwrap_or("image").to_owned();
// Copilot takes one text prompt and a separate attachments array.
if let Some(number) = block.pointer("/_meta/openideaImageNumber").and_then(Value::as_u64) {
text_parts.push(format!("[Image #{number}: {name}]"));
}
attachments.push(json!({ "type": "file", "path": path_str, "displayName": name }));
temp_files.push(saved);
}
+281 -3
Переглянути файл
@@ -69,6 +69,8 @@ struct FakeAgent {
prompts: Mutex<Vec<Value>>,
/// Queued errors returned on the next `session/prompt` calls before succeeding.
prompt_errors: Mutex<VecDeque<(i64, String)>>,
/// Queued errors returned on the next session-open calls before succeeding.
open_errors: Mutex<VecDeque<(i64, String, Option<Value>)>>,
/// Recorded `(method, _meta.openidea.memory)` payloads across `session/new`, `session/load`, and `session/fork`.
memory_calls: Mutex<Vec<(String, Option<Value>)>>,
}
@@ -150,6 +152,12 @@ impl Handler for FakeAgent {
let data = json!({"openidea": {"usageLimit": {"resetsAtMs": 1234.0}}});
return Err((codes::INTERNAL_ERROR, "You've hit your usage limit".into(), Some(data)));
}
if matches!(method, "session/new" | "session/load" | "session/fork")
&& let Some(err) = self.open_errors.lock().pop_front()
{
self.calls.lock().push(method.to_owned());
return Err(err);
}
self.on_request(method, params).map_err(|(code, message)| (code, message, None))
}
@@ -426,6 +434,28 @@ impl Handler for FakeAgent {
self.say(&session, &format!("form {answer}"));
return Ok(json!({ "stopReason": "end_turn" }));
}
if text == "question form" {
// claude-agent-acp's `AskUserQuestion`, sent as a form.
let peer = self.latest();
let answer: Value = tokio::runtime::Handle::current()
.block_on(peer.request(
"elicitation/create",
json!({"sessionId": session, "mode": "form",
"message": "Please answer the following questions.",
"requestedSchema": {"type": "object", "properties": {
"question_0": {"type": "string", "title": "Layout", "description": "Which layout?",
"oneOf": [{"const": "List", "title": "List"}, {"const": "Grid", "title": "Grid"}]},
"question_0_custom": {"type": "string", "title": "Other"},
"question_1": {"type": "array", "title": "Checks", "description": "Which checks?",
"items": {"anyOf": [{"const": "Disk", "title": "Disk"},
{"const": "GPU", "title": "GPU"}]}},
"question_1_custom": {"type": "string", "title": "Other"}}}}),
None,
))
.unwrap();
self.say(&session, &format!("form {answer}"));
return Ok(json!({ "stopReason": "end_turn" }));
}
if text == "ask" {
let peer = self.latest();
let answer: Value = tokio::runtime::Handle::current()
@@ -2226,6 +2256,175 @@ async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
mgr.shutdown();
}
fn warming_up_error() -> (i64, String, Option<Value>) {
(
codes::INTERNAL_ERROR,
"Internal error: Internal service failure".to_owned(),
Some(json!({"errorName": "ServiceUnavailableError"})),
)
}
#[tokio::test(flavor = "multi_thread")]
async fn session_open_retries_while_the_agent_finishes_starting_up() {
// OpenCode rejects session opens until its plugins and MCP servers finish activating.
let tmp = tempfile::tempdir().unwrap();
let agent =
Arc::new(FakeAgent { open_errors: Mutex::new(VecDeque::from([warming_up_error()])), ..Default::default() });
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/new").count(), 2, "retried the startup race");
let saved = mgr.task(&task.id).unwrap().state.lock().session_id.clone().expect("a session");
mgr.shutdown();
// The same race when reopening a saved session.
let agent =
Arc::new(FakeAgent { open_errors: Mutex::new(VecDeque::from([warming_up_error()])), ..Default::default() });
let mgr = manager(tmp.path(), agent.clone());
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/load").count(), 2, "retried the startup race");
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some(saved.as_str()));
mgr.shutdown();
}
async fn wait_for_session_open_attempts(agent: &FakeAgent, method: &str, attempts: usize) {
tokio::time::timeout(Duration::from_secs(5), async {
while agent.calls.lock().iter().filter(|call| call.as_str() == method).count() < attempts {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("agent received the session-open requests");
}
#[tokio::test]
async fn retry_after_warmup_expires_loads_the_saved_session_again() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let saved = mgr.task(&task.id).unwrap().state.lock().session_id.clone().unwrap();
mgr.shutdown();
let agent = Arc::new(FakeAgent {
open_errors: Mutex::new(std::iter::repeat_with(warming_up_error).take(16).collect()),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for_session_open_attempts(&agent, "session/load", 2).await;
tokio::time::pause();
tokio::time::advance(WARMUP_WINDOW - WARMUP_DELAY * 2).await;
tokio::time::resume();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
assert!(mgr.entries(&task.id, None).unwrap().iter().any(|entry| matches!(
entry, AgentEntry::Error { message } if message.contains("Try again") && !message.contains("new session")
)));
agent.open_errors.lock().clear();
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert!(!agent.calls.lock().iter().any(|call| call == "session/new"));
let handle = mgr.task(&task.id).unwrap();
assert_eq!(handle.live.lock().as_ref().unwrap().session, saved);
mgr.shutdown();
}
#[tokio::test]
async fn a_stalled_warmup_retry_times_out_and_closes_the_connection() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent {
open_errors: Mutex::new(VecDeque::from([warming_up_error()])),
hold_session_new: AtomicBool::new(true),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for_session_open_attempts(&agent, "session/new", 2).await;
tokio::time::pause();
tokio::time::advance(WARMUP_WINDOW).await;
tokio::time::resume();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
assert!(mgr.entries(&task.id, None).unwrap().iter().any(|entry| matches!(
entry, AgentEntry::Error { message } if message.contains("timed out")
)));
tokio::time::timeout(Duration::from_secs(5), agent.latest().closed())
.await
.expect("the timed-out connection closes");
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn session_open_authenticates_after_a_warmup_reply() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent {
open_errors: Mutex::new(VecDeque::from([warming_up_error()])),
auth_on_new: true,
authenticate_method: Some("agent_login".into()),
auth_methods: vec![json!({"id": "agent_login", "name": "Sign in"})],
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let calls = agent.calls.lock();
let setup: Vec<_> = calls
.iter()
.map(String::as_str)
.filter(|call| call.starts_with("session/") || call.starts_with("authenticate"))
.collect();
assert_eq!(
setup,
["session/new", "session/new", "authenticate", "authenticate agent_login", "session/new", "session/prompt"]
);
drop(calls);
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn session_open_does_not_retry_unrelated_internal_errors() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent {
open_errors: Mutex::new(VecDeque::from([(
codes::INTERNAL_ERROR,
"Internal error: Internal service failure".into(),
Some(json!({"errorName": "SQLiteError"})),
)])),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/new").count(), 1, "no retry on a real failure");
mgr.shutdown();
}
fn text(t: &str) -> AgentPrompt {
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
}
@@ -2606,7 +2805,12 @@ async fn subagents_get_their_own_conversation() {
#[test]
fn image_blocks_declare_the_type_of_their_bytes() {
let image = |mime: &str, data: &str| AgentImage { mime_type: mime.into(), data: data.into(), name: None };
let image = |mime: &str, data: &str| AgentImage {
mime_type: mime.into(),
data: data.into(),
name: None,
inline_number: None,
};
let cases = [
// A browser's JPEG pasted as PNG.
(image("image/png", "/9j/4AAQSkZJRgABAQ"), "image/jpeg"),
@@ -2628,7 +2832,7 @@ fn prompts_become_acp_content_blocks() {
let p = AgentPrompt {
text: "look".into(),
files: vec![IpcPath(PathBuf::from("/p/my file.rs"))],
images: vec![AgentImage { mime_type: "image/png".into(), data: "AAA".into(), name: None }],
images: vec![AgentImage { mime_type: "image/png".into(), data: "AAA".into(), name: None, inline_number: None }],
};
assert_eq!(
blocks(&p, &[]),
@@ -2660,6 +2864,32 @@ fn prompts_become_acp_content_blocks() {
assert!(clean(text(" ")).is_none());
}
#[test]
fn inline_images_are_distinct_content_blocks_in_text_order() {
let older: AgentImage = serde_json::from_value(json!({"mimeType":"image/png", "data":"AAA", "name":null})).unwrap();
assert!(older.inline_number.is_none());
let image = |number, data: &str| AgentImage {
mime_type: "image/png".into(),
data: data.into(),
name: None,
inline_number: Some(number),
};
let prompt = AgentPrompt {
text: "😀 [Image #2] then [Image #1] and [Image #99]".into(),
images: vec![image(1, "AAA"), image(2, "BBB"), image(3, "CCC")],
..Default::default()
};
let content = blocks(&prompt, &[]);
assert_eq!(content.len(), 5);
assert_eq!(content[0], json!({"type": "text", "text": "😀 "}));
assert_eq!(content[1]["type"], "image");
assert_eq!(content[1]["data"], "BBB");
assert_eq!(content[2], json!({"type": "text", "text": " then "}));
assert_eq!(content[3]["type"], "image");
assert_eq!(content[3]["data"], "AAA");
assert_eq!(content[4], json!({"type": "text", "text": " and [Image #99]"}));
}
#[tokio::test(flavor = "multi_thread")]
async fn claude_questions_keep_the_answer_object_as_the_option_id() {
let tmp = tempfile::tempdir().unwrap();
@@ -3930,6 +4160,54 @@ async fn an_agent_form_is_answered_declined_or_cancelled_even_when_approvals_are
}
}
/// claude-agent-acp asks `AskUserQuestion` as a form: it is shown as the question card, one
/// question at a time, and the card's answers fill the form (#7359).
#[tokio::test(flavor = "multi_thread")]
async fn a_question_tool_form_is_asked_as_questions() {
let answers = json!({"question_0": ["Grid", "with thumbnails"], "question_1": ["Disk", "GPU"]}).to_string();
for (reply, said) in [
(
answers.as_str(),
r#"form {"action":"accept","content":{"question_0":"Grid","question_0_custom":"with thumbnails","question_1":["Disk","GPU"]}}"#,
),
("reject", r#"form {"action":"decline"}"#),
] {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("question form"),
provider: "cursor".into(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
let (id, questions) = mgr
.entries(&task.id, None)
.unwrap()
.into_iter()
.find_map(|entry| match entry {
AgentEntry::Permission { id, questions, form: None, chosen: None, .. } if !questions.is_empty() => {
Some((id, questions))
}
_ => None,
})
.unwrap();
let asked: Vec<_> =
questions.iter().map(|q| (q.answer_key.as_deref(), q.question.as_str(), q.multi_select)).collect();
assert_eq!(asked, [(Some("question_0"), "Which layout?", false), (Some("question_1"), "Which checks?", true)]);
mgr.respond(&task.id, id, Some(reply.to_owned())).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let entries = mgr.entries(&task.id, None).unwrap();
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == said)), "{entries:?}");
mgr.shutdown();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_approval_choice_applies_before_first_prompt() {
let tmp = tempfile::tempdir().unwrap();
@@ -4882,7 +5160,7 @@ fn a_running_tools_output_is_sent_as_appends() {
// An image the tool returned is not part of the appended text: it goes with the whole entry.
let mut shown = titled.clone();
if let AgentEntry::Tool { images, output, .. } = &mut shown {
images.push(AgentImage { mime_type: "image/png".into(), data: "AAAA".into(), name: None });
images.push(AgentImage { mime_type: "image/png".into(), data: "AAAA".into(), name: None, inline_number: None });
output.as_mut().unwrap().push('!');
}
let imaged = event(&mut streamed, None, 2, &shown).unwrap();
+1 -1
Переглянути файл
@@ -523,7 +523,7 @@ mod tests {
t.apply(&update);
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "status": "completed"}));
let AgentEntry::Tool { images, output, status, .. } = &t.entries[0] else { panic!() };
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None }]);
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None, inline_number: None }]);
assert!(output.as_ref().unwrap().len() < MAX_OUTPUT + 100);
assert_eq!(*status, AgentToolStatus::Completed);
let saved = serde_json::to_string(&t.entries[0]).unwrap();
+76 -8
Переглянути файл
@@ -421,13 +421,14 @@ fn cargo_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
}
/// CLion's Build Project for a CMake project: configures the build directory when it has no
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild), one job per
/// `CMakeCache.txt` or no File API reply yet, then `cmake --build` (`--clean-first` to rebuild), one job per
/// logical CPU unless the profile's build arguments choose a count. The directory and
/// options come from the CMake profile; without one, a configured directory of the project
/// (the first by name), else `build`, as the generated run configurations use.
fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> Vec<BuildStep> {
let build_dir = match profile {
Some(p) if !p.build_dir.trim().is_empty() => p.build_dir.trim().to_owned(),
Some(p) if p.build_type.is_empty() => "cmake-build-default".into(),
Some(p) => format!("cmake-build-{}", p.build_type.to_lowercase()),
None => {
let mut configured: Vec<String> = std::fs::read_dir(dir)
@@ -444,18 +445,49 @@ fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> V
let build_type = profile.map_or("Debug", |p| p.build_type.as_str());
let env = profile.map(|p| p.env.clone()).unwrap_or_default();
let mut steps = Vec::new();
if !dir.join(&build_dir).join("CMakeCache.txt").is_file() {
let mut configure = BuildStep::new("cmake", &["-S", ".", "-B", &build_dir], dir, Format::Gcc);
if let Some(p) = profile.filter(|p| !p.generator.trim().is_empty()) {
configure.args.extend(["-G".into(), p.generator.clone()]);
}
configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}"));
let preset = profile.and_then(|p| p.preset.as_ref());
// The profile's toolchain may bring its own cmake.
let cmake = profile.and_then(|p| p.cmake_program.as_ref()).map_or("cmake".into(), |c| c.to_string_lossy());
let cmake = cmake.as_ref();
let build_path = dir.join(&build_dir);
// Configured without the File API queries (by another tool, or before they were written):
// configure again so the targets, and their run configurations, become known.
let fresh = !build_path.join("CMakeCache.txt").is_file();
if fresh || !build_path.join(ide_core::cmake_file_api::REPLY).is_dir() {
// Best effort: without the queries the build still runs, only the targets stay unknown.
let _ = ide_core::cmake_file_api::write_queries(&build_path);
let mut configure = match preset {
// The preset sets the generator and cache variables.
Some(preset) => BuildStep::new(cmake, &["--preset", &preset.configure], dir, Format::Gcc),
None => {
let mut configure = BuildStep::new(cmake, &["-S", ".", "-B", &build_dir], dir, Format::Gcc);
// A configured directory keeps its generator (CMake refuses another one) and,
// without a profile, its build type.
if let Some(p) = profile.filter(|p| fresh && !p.generator.trim().is_empty()) {
configure.args.extend(["-G".into(), p.generator.clone()]);
}
if fresh || profile.is_some() {
configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}"));
}
configure
}
};
configure.args.push("-DCMAKE_EXPORT_COMPILE_COMMANDS=ON".into());
configure.args.extend(profile.map(|p| p.cmake_args.clone()).unwrap_or_default());
configure.env = env.clone();
steps.push(configure);
}
let mut build = BuildStep::new("cmake", &["--build", &build_dir, "--config", build_type], dir, Format::Gcc);
let mut build = match preset.and_then(|p| p.build.as_deref()) {
Some(build) => BuildStep::new(cmake, &["--build", "--preset", build], dir, Format::Gcc),
None => {
let mut build = BuildStep::new(cmake, &["--build", &build_dir], dir, Format::Gcc);
// CLion's "Default" build type: no configuration at all.
if !build_type.is_empty() {
build.args.extend(["--config".into(), build_type.into()]);
}
build
}
};
if kind == BuildKind::Rebuild {
build.args.push("--clean-first".into());
}
@@ -1659,6 +1691,15 @@ mod tests {
"an unconfigured project is configured first"
);
write(&cm, "cmake-build-release/CMakeCache.txt", "");
let p =
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(
p.steps[0].args,
["-S", ".", "-B", "cmake-build-release", "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"],
"configured again, as it was, when it has no File API reply"
);
assert!(cm.join("cmake-build-release/.cmake/api/v1/query/client-openidea/codemodel-v2").is_file());
std::fs::create_dir_all(cm.join("cmake-build-release").join(ide_core::cmake_file_api::REPLY)).unwrap();
let p =
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(
@@ -1694,6 +1735,33 @@ mod tests {
)
.unwrap();
assert_eq!(p.steps[0].args[..4], ["-S", ".", "-B", "cmake-build-debug"]);
let preset = CMakeProfile {
build_dir: "out/dev".into(),
preset: Some(ide_core::settings::CMakePresetRef {
configure: "dev".into(),
build: Some("dev-build".into()),
..Default::default()
}),
..CMakeProfile::default()
};
let p = plan(
&cm,
&BuildModel::default(),
BuildKind::Build,
None,
Some(std::slice::from_ref(&preset)),
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(
args(&p),
[
"--preset dev -DCMAKE_EXPORT_COMPILE_COMMANDS=ON".to_owned(),
format!("--build --preset dev-build {jobs}")
],
"a preset profile configures and builds with its presets"
);
let siblings = tmp.path().join("siblings");
write(&siblings, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
+5 -1
Переглянути файл
@@ -702,7 +702,11 @@ impl JavaBuild<'_> {
let step = match top {
Reactor::Maven(top) => {
let selection = maven_project_selection(changed.iter().map(|(p, _, _)| *p));
let mut extra = vec!["-q".to_owned(), "-pl".to_owned(), selection];
// The resources plugin copies a file only when it is newer than the copy; content
// replaced without moving the mtime (a sync tool, PowerShell `Copy-Item`) would stay
// stale while its stamp is recorded as processed.
let mut extra =
vec!["-q".to_owned(), "-pl".to_owned(), selection, "-Dmaven.resources.overwrite=true".to_owned()];
extra.push("resources:resources".into());
if changed.iter().any(|(_, test, _)| *test) {
extra.push("resources:testResources".into());
+2
Переглянути файл
@@ -258,6 +258,8 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl t:app"), "{steps:?}");
// #7340: content replaced without a newer mtime is copied too.
assert!(steps[0].contains("-Dmaven.resources.overwrite=true"), "{steps:?}");
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nmore=1\n");
// A deleted source leaves no class behind.
+20
Переглянути файл
@@ -0,0 +1,20 @@
//! The CMake File API queries the IDE writes into a build directory, shared by the run
//! configurations (which read the replies) and Build Project (which configures).
use std::path::Path;
/// The objects asked for: targets, cache, toolchains and the CMake files.
pub const QUERIES: [&str; 4] = ["codemodel-v2", "cache-v2", "toolchains-v1", "cmakeFiles-v1"];
const QUERY: &str = ".cmake/api/v1/query/client-openidea";
/// Where CMake writes its replies, relative to the build directory.
pub const REPLY: &str = ".cmake/api/v1/reply";
/// Asks CMake to answer [`QUERIES`] on the next configure of `build`.
pub fn write_queries(build: &Path) -> std::io::Result<()> {
let query = build.join(QUERY);
std::fs::create_dir_all(&query)?;
for name in QUERIES {
std::fs::write(query.join(name), "")?;
}
Ok(())
}
+16
Переглянути файл
@@ -401,6 +401,8 @@ impl Default for CodeEditingSettings {
#[serde(default, rename_all = "camelCase")]
pub struct InlayHintsSettings {
pub types: bool,
/// Inferred variable and field types from the JavaScript and TypeScript servers (on, as in WebStorm).
pub js_ts_types: bool,
pub parameters: bool,
/// Hints of other kinds (chaining, closing labels…).
pub other: bool,
@@ -436,6 +438,7 @@ impl Default for InlayHintsSettings {
fn default() -> Self {
Self {
types: true,
js_ts_types: true,
parameters: true,
other: true,
closing_labels: true,
@@ -710,6 +713,19 @@ mod folding_tests {
}
}
#[cfg(test)]
mod inlay_hints_tests {
use super::InlayHintsSettings;
#[test]
fn existing_settings_enable_js_ts_type_hints_by_default() {
let settings: InlayHintsSettings = serde_json::from_str(r#"{"parameters":false}"#).unwrap();
assert!(settings.types);
assert!(settings.js_ts_types);
assert!(!settings.parameters);
}
}
#[cfg(test)]
mod sticky_lines_tests {
use super::CodeEditingSettings;
+1
Переглянути файл
@@ -6,6 +6,7 @@
pub mod build_jobs;
pub mod cli_process;
pub mod cmake_file_api;
pub mod editor_settings;
pub mod error;
pub mod event;
+88 -1
Переглянути файл
@@ -68,6 +68,8 @@ pub struct Settings {
/// Build, Execution, Deployment › Run Targets.
pub run_targets: Vec<RunTarget>,
pub cmake: CMakeSettings,
/// Build, Execution, Deployment › Toolchains; the first is the default.
pub toolchains: Vec<Toolchain>,
/// Settings › Agents.
pub agents: AgentSettings,
/// Agents › MCP Server (global only).
@@ -750,9 +752,42 @@ impl Default for SettingsSyncSettings {
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CMakeSettings {
#[serde(skip_serializing_if = "Option::is_none")]
/// Serialized as `null` when absent, so `cmake.profiles` stays a known settings key.
#[specta(optional)]
pub profiles: Option<Vec<CMakeProfile>>,
/// `true` ignores `CMakePresets.json` / `CMakeUserPresets.json`; otherwise every visible
/// configure preset whose condition holds is listed after the explicit profiles.
pub ignore_presets: bool,
/// Configure presets (by name) enabled as profiles. As in CLion, a preset is listed but
/// disabled until enabled here.
pub enabled_presets: Vec<String>,
/// The profile (by name) that build, run and debug use, as CLion's toolbar switcher;
/// empty or unknown = the first enabled one.
pub active_profile: String,
}
/// The presets a profile made from `CMakePresets.json` runs with.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CMakePresetRef {
pub configure: String,
/// The first build preset of `configure`, used by `cmake --build --preset`.
#[serde(skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub build: Option<String>,
/// The first test preset of `configure`, used by `ctest --preset`.
#[serde(skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub test: Option<String>,
/// Cache variables the resolved preset sets itself, read when presets are loaded (never
/// saved): a toolchain does not override them.
#[serde(skip)]
#[specta(skip)]
pub cache_variables: Vec<String>,
/// The preset names a toolchain file, which picks the compilers.
#[serde(skip)]
#[specta(skip)]
pub toolchain_file: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -766,6 +801,23 @@ pub struct CMakeProfile {
pub build_dir: String,
pub build_args: Vec<String>,
pub env: BTreeMap<String, String>,
/// `false` keeps the profile listed but unused (CLion's "Enable profile").
pub enabled: bool,
/// Toolchain name (Settings › Toolchains); empty = the default (first) toolchain.
pub toolchain: String,
/// Set only on the profiles made from presets: configure with `cmake --preset`, and the
/// generator and cache variables come from the preset.
#[serde(skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub preset: Option<CMakePresetRef>,
/// Resolved from the toolchain when profiles are put to use (never saved): the `cmake`
/// to run (`ctest` next to it) and the debugger to prefer.
#[serde(skip)]
#[specta(skip)]
pub cmake_program: Option<std::path::PathBuf>,
#[serde(skip)]
#[specta(skip)]
pub debugger: Option<std::path::PathBuf>,
}
impl Default for CMakeProfile {
@@ -778,10 +830,44 @@ impl Default for CMakeProfile {
build_dir: String::new(),
build_args: Vec::new(),
env: BTreeMap::new(),
enabled: true,
toolchain: String::new(),
preset: None,
cmake_program: None,
debugger: None,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum ToolchainKind {
/// Tools from the chosen paths, else from `PATH`.
#[default]
System,
/// A MinGW / MSYS2 directory: its `bin` goes first on `PATH`, with gcc, g++,
/// mingw32-make and gdb from there.
#[serde(rename = "mingw")]
MinGw,
}
/// Build, Execution, Deployment › Toolchains (IDE-wide, as in CLion). Empty fields are
/// detected: from the MinGW directory, else from `PATH`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct Toolchain {
pub name: String,
pub kind: ToolchainKind,
/// The MinGW directory (the one holding `bin`).
pub path: String,
pub cmake: String,
/// `CMAKE_MAKE_PROGRAM`: make, mingw32-make or ninja.
pub build_tool: String,
pub c_compiler: String,
pub cxx_compiler: String,
pub debugger: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ToolSettings {
@@ -893,6 +979,7 @@ impl Default for Settings {
deployment: DeploymentSettings::default(),
run_targets: Vec::new(),
cmake: CMakeSettings::default(),
toolchains: Vec::new(),
agents: AgentSettings::default(),
mcp_server: McpServerSettings::default(),
agent_security: AgentSecuritySettings::default(),
+8
Переглянути файл
@@ -296,6 +296,14 @@ pub struct OutlineItem {
#[serde(default)]
#[specta(optional)]
pub visibility: Option<Visibility>,
/// Rust `impl Trait for Type`: the trait's name in the header (its last path segment, where go-to-definition lands), from the syntax tree.
#[serde(default)]
#[specta(optional)]
pub implements: Option<Range>,
/// Rust `impl [Trait for] Type`: the implementing type's name (its last path segment), from the syntax tree.
#[serde(default)]
#[specta(optional)]
pub self_type: Option<Range>,
}
/// Fuzzy-match highlight: indices (in chars of the displayed string) that matched.
+4 -1
Переглянути файл
@@ -477,12 +477,15 @@ pub struct BuildSettings {
pub open_tool_window: String,
/// When to focus the Build tool window: `always` | `onError` | `never`.
pub focus_tool_window: String,
/// Build an Xcode project in the background when xcode-build-server has no build log to read
/// yet, so cross-file code insight works before the first Run.
pub xcode_index_build: bool,
}
impl Default for BuildSettings {
fn default() -> Self {
// Builds open the tool window without taking focus.
Self { open_tool_window: "always".into(), focus_tool_window: "never".into() }
Self { open_tool_window: "always".into(), focus_tool_window: "never".into(), xcode_index_build: true }
}
}
+9
Переглянути файл
@@ -1055,6 +1055,15 @@ impl DebugManager {
if let Some(command) = custom_command(&spec.command) {
spec.command = command;
}
// The debugger of the run configuration's toolchain (a MinGW gdb), over every other choice.
if let Some(command) = arguments
.as_object_mut()
.and_then(|o| o.remove(native::ADAPTER_COMMAND))
.and_then(|v| v.as_str().map(str::to_owned))
{
spec.command = command;
spec.pinned = None;
}
// debugpy: run the adapter with the debuggee's interpreter (venvs carry their own debugpy),
// or with the launcher's when the debuggee runs through a manager (`uv run python`).
if config.adapter == "debugpy" {
+26
Переглянути файл
@@ -8,6 +8,10 @@ use ide_core::{IdeError, IdeResult};
use serde_json::{Map, Value, json};
use std::path::{Path, PathBuf};
/// Launch argument naming the debugger to run (a toolchain's gdb or lldb-dap), which replaces
/// the search: lldb-dap if its name says so, else GDB.
pub const ADAPTER_COMMAND: &str = "__adapterCommand";
/// Prefix of the error when none of them is there; the UI offers to install CodeLLDB on it.
pub const NO_NATIVE_DEBUGGER: &str = "No C/C++ debugger found";
@@ -20,7 +24,16 @@ pub async fn choose(
if config.adapter != "lldb-dap" || config.request != "launch" {
return Ok(config);
}
let chosen = config
.extra_json
.as_deref()
.and_then(|e| serde_json::from_str::<Value>(e).ok())
.and_then(|e| e[ADAPTER_COMMAND].as_str().map(PathBuf::from));
let found = tokio::task::spawn_blocking(move || {
if let Some(chosen) = chosen {
let name = chosen.file_stem().map(|s| s.to_string_lossy().to_lowercase()).unwrap_or_default();
return if name.contains("lldb-dap") { Found::LldbDap } else { Found::Gdb(chosen) };
}
if lookup("lldb-dap").is_some() {
return Found::LldbDap;
}
@@ -154,6 +167,19 @@ mod tests {
assert_eq!(extra(&config)["swiftpm"]["product"], "app");
}
#[tokio::test]
async fn a_toolchain_debugger_replaces_the_search() {
let mut launch = cmake_launch();
launch.extra_json = Some(json!({"env": ["A=1"], ADAPTER_COMMAND: "/opt/mingw/bin/gdb.exe"}).to_string());
// lldb-dap is there, but the toolchain names its GDB (an unknown version is left to GDB).
let config = choose(launch, only(&["lldb-dap"])).await.unwrap();
assert_eq!(config.adapter, "gdb");
assert_eq!(extra(&config)[ADAPTER_COMMAND], "/opt/mingw/bin/gdb.exe", "kept for the adapter launch");
let mut launch = cmake_launch();
launch.extra_json = Some(json!({ADAPTER_COMMAND: "/opt/llvm/bin/lldb-dap"}).to_string());
assert_eq!(choose(launch, only(&[])).await.unwrap().adapter, "lldb-dap");
}
#[tokio::test]
async fn without_any_debugger_says_what_to_install() {
let e = choose(cmake_launch(), only(&[])).await.unwrap_err();
+19
Переглянути файл
@@ -1355,6 +1355,25 @@ impl DbManager {
Self::table_details_on(&pool, Some(catalog), schema, table).await
}
/// Read metadata using an existing connection only. A concurrent disconnect must not
/// cause a read-only extension request to reopen a source or prompt for credentials.
pub async fn connected_table_details(
&self,
id: &str,
catalog: Option<&str>,
schema: &str,
table: &str,
) -> IdeResult<TableDetails> {
if catalog.is_some() {
let source = self.source(id)?;
if id != source.id || source.driver != DbDriver::Jdbc || source.vendor != "duckdb" {
return Err(IdeError::invalid("Catalog browsing requires a DuckDB data source"));
}
}
let pool = self.connected_pool(id)?;
Self::table_details_on(&pool, catalog, schema, table).await
}
pub async fn table_details(&self, id: &str, schema: &str, table: &str) -> IdeResult<TableDetails> {
let pool = self.pool(id).await?;
Self::table_details_on(&pool, None, schema, table).await
+11
Переглянути файл
@@ -165,6 +165,17 @@ impl DbManager {
.collect()
}
/// Snapshot an existing connection without allocating a slot or opening a route.
pub(super) fn connected_pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
self.pools
.lock()
.get(id)
.and_then(|slot| slot.value.get())
.filter(|connection| !connection.is_closed())
.map(|connection| connection.pool.clone())
.ok_or_else(|| IdeError::invalid("Connect the data source in the Database tool window first"))
}
pub async fn pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
Ok(self.connection(id).await?.pool)
}
+23
Переглянути файл
@@ -24,6 +24,8 @@ pub enum Capability {
IdeCommands,
/// Manage only its own project database sources and write their credentials.
DatabaseSources,
/// Read table metadata of connected project sources; never rows or credentials.
DatabaseSchema,
VcsRead,
VcsWrite,
/// The Maven / Gradle dependency graph the IDE resolved.
@@ -93,6 +95,7 @@ impl Capability {
}
Self::EditorWrite
| Self::DatabaseSources
| Self::DatabaseSchema
| Self::VcsWrite
| Self::Net(_)
| Self::NetAsk
@@ -130,6 +133,7 @@ impl Capability {
Self::EditorWrite => "Change text in the editor".into(),
Self::ProjectWrite => "Create and change files in the open project".into(),
Self::DatabaseSources => "Manage its own database sources and store their passwords in trusted projects".into(),
Self::DatabaseSchema => "Read table structures of connected database sources in trusted projects, without rows or passwords".into(),
Self::IdeCommands => "Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing".into(),
Self::VcsRead => "Read version control state".into(),
Self::VcsWrite => "Change version control state (commit, fetch, checkout)".into(),
@@ -289,6 +293,7 @@ impl fmt::Display for Capability {
Self::ProjectWrite => f.write_str("project.write"),
Self::IdeCommands => f.write_str("ide.commands"),
Self::DatabaseSources => f.write_str("database.sources"),
Self::DatabaseSchema => f.write_str("database.schema"),
Self::VcsRead => f.write_str("vcs.read"),
Self::VcsWrite => f.write_str("vcs.write"),
Self::BuildRead => f.write_str("build.read"),
@@ -383,6 +388,7 @@ impl FromStr for Capability {
"project.write" => Self::ProjectWrite,
"ide.commands" => Self::IdeCommands,
"database.sources" => Self::DatabaseSources,
"database.schema" => Self::DatabaseSchema,
"vcs.read" => Self::VcsRead,
"vcs.write" => Self::VcsWrite,
"build.read" => Self::BuildRead,
@@ -677,6 +683,23 @@ mod net_setting_tests {
mod database_tests {
use super::*;
#[test]
fn database_schema_is_a_separate_medium_risk_grant_requiring_api20() {
let cap: Capability = "database.schema".parse().unwrap();
assert_eq!(cap, Capability::DatabaseSchema);
assert_eq!(cap.to_string(), "database.schema");
assert_eq!(cap.risk(), Risk::Medium);
assert!(!cap.auto_migrates());
for other in [Capability::ProjectRead, Capability::DatabaseSources] {
assert!(!other.covers(&cap));
}
for (api, valid) in [("^1.19", false), ("^1.20", true)] {
let text = format!(
"id='schema'\nname='Schema'\nversion='1.0.0'\nengines.openidea='{api}'\n[capabilities]\nrequired=['database.schema']"
);
assert_eq!(crate::Manifest::parse(&text).is_ok(), valid);
}
}
#[test]
fn database_sources_is_a_medium_risk_exact_grant_requiring_api4() {
let cap: Capability = "database.sources".parse().unwrap();
assert_eq!(cap, Capability::DatabaseSources);
+4 -1
Переглянути файл
@@ -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.19.0";
pub const ENGINE_VERSION: &str = "1.20.0";
/// The longest `[capabilities.reasons]` entry, in characters: a sentence or two.
pub const MAX_CAPABILITY_REASON: usize = 500;
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
@@ -426,6 +426,9 @@ impl Manifest {
if matches!(cap, Capability::ClipboardRead) {
self.needs_api(&format!("capability `{cap}`"), 11)?;
}
if matches!(cap, Capability::DatabaseSchema) {
self.needs_api(&format!("capability `{cap}`"), 20)?;
}
if matches!(cap, Capability::Agents) {
self.needs_api(&format!("capability `{cap}`"), 18)?;
}
+2
Переглянути файл
@@ -668,6 +668,8 @@ mod tests {
selection_range: Range::new(range.start, range.start),
children,
visibility: None,
implements: None,
self_type: None,
};
let method = outline(
"total",
+144 -3
Переглянути файл
@@ -201,6 +201,143 @@ pub async fn build_model(host: &Host, window: &str) -> IdeResult<BuildModel> {
blocking(move || workspace::load_project(&project, &config)).await
}
/// Settings › CMake and the toolbar switcher: every profile, saved ones then presets (with
/// whether each is enabled), and why the presets file cannot be read, if it cannot.
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct CMakeProfileList {
pub profiles: Vec<ide_core::settings::CMakeProfile>,
pub presets_error: Option<String>,
}
/// Reading the profiles runs nothing, so an untrusted project lists them too.
#[command(trust = always)]
pub async fn cmake_profiles(host: &Host, window: &str) -> IdeResult<CMakeProfileList> {
let project = host.project(window)?;
let (root, settings) = (project.root.clone(), project.settings.effective());
blocking(move || {
let presets_error = if settings.cmake.ignore_presets { None } else { ide_run::cmake_presets(&root).err() };
Ok(CMakeProfileList { profiles: ide_run::cmake_listed_profiles(&root, &settings.cmake), presets_error })
})
.await
}
/// Settings › CMake › Cache variables: the `CMakeCache.txt` of `build_dir` (relative to the
/// project, or absolute), empty while that directory is not configured. Reading runs nothing.
#[command(trust = always)]
pub async fn cmake_cache(
host: &Host,
window: &str,
build_dir: String,
) -> IdeResult<Vec<ide_run::cmake_cache::CacheEntry>> {
let root = host.project(window)?.root.clone();
blocking(move || {
let cache = root.join(build_dir.trim()).join("CMakeCache.txt");
Ok(std::fs::read_to_string(cache).map(|text| ide_run::cmake_cache::parse(&text)).unwrap_or_default())
})
.await
}
/// One tool of a toolchain as Settings › Toolchains shows it: the executable used (chosen, from the
/// MinGW directory, else found on `PATH`) and its version, or why it cannot be used.
#[derive(Clone, Debug, Default, serde::Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct ToolCheck {
pub path: Option<String>,
pub version: Option<String>,
pub problem: Option<String>,
}
/// Each tool of a toolchain, keyed as the toolchain's fields (`cmake`, `buildTool`, `cCompiler`,
/// `cxxCompiler`, `debugger`).
pub type ToolchainCheck = std::collections::BTreeMap<String, ToolCheck>;
async fn check_tool(path: Option<std::path::PathBuf>) -> ToolCheck {
let Some(path) = path else {
return ToolCheck { problem: Some("Not found".into()), ..Default::default() };
};
let shown = Some(path.to_string_lossy().into_owned());
if !path.is_file() {
return ToolCheck { path: shown, problem: Some("Not found".into()), ..Default::default() };
}
let mut command = tokio::process::Command::new(&path);
command.arg("--version").stdin(std::process::Stdio::null()).kill_on_drop(true);
ide_core::process::prepare(command.as_std_mut());
match tokio::time::timeout(std::time::Duration::from_secs(5), command.output()).await {
Ok(Ok(output)) => {
let text = String::from_utf8_lossy(&output.stdout).into_owned() + &String::from_utf8_lossy(&output.stderr);
let version = text.lines().map(str::trim).find(|l| !l.is_empty()).map(String::from);
ToolCheck { path: shown, version, problem: None }
}
Ok(Err(e)) => ToolCheck { path: shown, problem: Some(e.to_string()), ..Default::default() },
Err(_) => ToolCheck { path: shown, problem: Some("No answer to --version".into()), ..Default::default() },
}
}
/// Settings › Toolchains: which executable each tool of `toolchain` resolves to, and its version.
/// Only `--version` runs; the settings are IDE-wide, so no project needs to be trusted.
#[command(trust = always)]
pub async fn toolchain_check(toolchain: ide_core::settings::Toolchain) -> IdeResult<ToolchainCheck> {
let tools = ide_run::cmake_toolchain::tools(&toolchain);
let chosen = |key: &str| -> Option<std::path::PathBuf> {
match key {
"cmake" => tools.cmake.clone(),
"buildTool" => tools.build_tool.clone().map(Into::into),
"cCompiler" => tools.c_compiler.clone().map(Into::into),
"cxxCompiler" => tools.cxx_compiler.clone().map(Into::into),
_ => tools.debugger.clone(),
}
};
let search = match &tools.path {
Some(bin) => std::env::join_paths(
std::iter::once(bin.clone()).chain(std::env::split_paths(&ide_core::tool_path::search_path())),
)
.unwrap_or_else(|_| ide_core::tool_path::search_path()),
None => ide_core::tool_path::search_path(),
};
let mut out = ToolchainCheck::new();
for (key, names) in ide_run::cmake_toolchain::FALLBACKS {
let path = chosen(key)
.map(|p| {
// A bare name ("clang++") is looked up like CMake would.
if p.components().count() == 1 {
ide_core::process::find_executable(&p.to_string_lossy(), &search).unwrap_or(p)
} else {
p
}
})
.or_else(|| names.iter().find_map(|n| ide_core::process::find_executable(n, &search)));
out.insert(key.into(), check_tool(path).await);
}
Ok(out)
}
/// Settings › Toolchains: a toolchain for each MinGW / MSYS2 install found (Windows).
#[command(trust = always)]
pub async fn toolchains_detect() -> IdeResult<Vec<ide_core::settings::Toolchain>> {
blocking(|| {
Ok(ide_run::cmake_toolchain::detect_mingw()
.into_iter()
.map(|dir| {
let name = match dir.parent().and_then(|p| p.file_name()) {
// MSYS2 environments: "MSYS2 ucrt64".
Some(parent) if parent.to_string_lossy().starts_with("msys") => {
format!("MSYS2 {}", dir.file_name().unwrap_or_default().to_string_lossy())
}
_ => format!("MinGW ({})", dir.display()),
};
ide_core::settings::Toolchain {
name,
kind: ide_core::settings::ToolchainKind::MinGw,
path: dir.to_string_lossy().into_owned(),
..Default::default()
}
})
.collect())
})
.await
}
fn linked_gradle_paths(
root: &Path,
settings: &ide_core::settings::GradleSettings,
@@ -1023,7 +1160,7 @@ pub async fn build_run(
&model,
kind,
file.as_deref(),
settings.cmake.profiles.as_deref(),
ide_run::cmake_profiles(&root, &settings.cmake, &settings.toolchains).as_deref(),
None,
&token,
)?,
@@ -1071,7 +1208,7 @@ pub async fn build_run(
&model,
kind,
file.as_deref(),
settings.cmake.profiles.as_deref(),
ide_run::cmake_profiles(member, &settings.cmake, &settings.toolchains).as_deref(),
None,
&token,
)?,
@@ -1094,7 +1231,7 @@ pub async fn build_run(
&model,
kind,
file.as_deref(),
settings.cmake.profiles.as_deref(),
ide_run::cmake_profiles(&root, &settings.cmake, &settings.toolchains).as_deref(),
Some(&cache),
&token,
) {
@@ -1687,6 +1824,8 @@ ide_command::domain!(
build_model,
build_run,
build_sync,
cmake_cache,
cmake_profiles,
gradle_dependencies,
gradle_link_projects,
gradle_published_catalog,
@@ -1696,4 +1835,6 @@ ide_command::domain!(
maven_exclude_dependency,
maven_goto_declaration,
maven_managed_declarations,
toolchain_check,
toolchains_detect,
);
+1
Переглянути файл
@@ -160,6 +160,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
let syntax = syntax();
ide_language::merge_visibility(&mut items, &syntax);
ide_language::merge_kinds(&mut items, &syntax);
ide_language::merge_impl_traits(&mut items, &syntax);
}
items
}
+16 -3
Переглянути файл
@@ -355,11 +355,14 @@ pub async fn fs_undo_delete(host: &Host, window: &str, undo: DeletionUndo) -> Id
let wanted = undo.paths();
let skipped = project.history.restore_deletion_undo(undo);
// The Delete scheduled the files for deletion in a working copy (`files_deleted`): Undo
// takes that back, keeping the restored content. Git records deletions at commit time.
// takes that back, keeping the restored content. Git records deletions at commit time
// (a file it dropped from the index because it was only added comes back unversioned).
// One call per working copy: its first folder takes the tree below with it anyway.
let mut by_backend: Vec<(std::sync::Arc<dyn ide_vcs::Backend>, Vec<PathBuf>)> = Vec::new();
for path in wanted.iter().filter(|p| !skipped.iter().any(|s| s.0 == **p)) {
let Some(backend) = project.backend_of(path) else { continue };
let Some(backend) = project.backend_of(path).filter(|b| b.kind() != ide_vcs::VcsKind::Git) else {
continue;
};
match by_backend.iter_mut().find(|(b, _)| b.root() == backend.root()) {
Some((_, paths)) => paths.push(path.clone()),
None => by_backend.push((backend, vec![path.clone()])),
@@ -367,7 +370,17 @@ pub async fn fs_undo_delete(host: &Host, window: &str, undo: DeletionUndo) -> Id
}
for (backend, paths) in by_backend {
// The files are back either way; still scheduled for deletion, they would go at commit.
if let Err(e) = backend.unstage(&paths) {
// Only the rows the Delete made deleted: an added or moved file it left as it was
// keeps its schedule (unstaging it would make it unversioned).
let deleted = backend.status_paths(&paths).map(|rows| {
rows.into_iter()
.filter(|f| f.unstaged == Some(ide_vcs::ChangeKind::Deleted) && f.path.0.exists())
.map(|f| f.path.0)
.collect::<Vec<_>>()
});
if let Err(e) =
deleted.and_then(|deleted| if deleted.is_empty() { Ok(()) } else { backend.unstage(&deleted) })
{
tracing::warn!("undo of delete in {}: {e}", backend.root().display());
project.sink.emit(ide_core::IdeEvent::Notify {
level: ide_core::event::NotifyLevel::Warning,
+37 -7
Переглянути файл
@@ -722,16 +722,15 @@ pub async fn lsp_move_to_file_targets(
Ok(result?.into_iter().map(ide_core::IpcPath::from).collect())
}
/// Implementations of the symbols at `positions`, one list per position (the
/// editor's "is implemented / overridden" gutter markers). Cancel with
/// `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_implementations(
/// One `kind` of go-to request at each of `positions` (grouped by the document that answers
/// them), one list per position. Cancel with `cancel_request(request)`.
async fn goto_each(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
positions: Vec<Pos>,
kind: GotoKind,
positions: &[Pos],
) -> IdeResult<Vec<Vec<Location>>> {
let lsp = host.project(window)?.lsp.clone();
let (_, cancel) =
@@ -747,7 +746,7 @@ pub async fn lsp_implementations(
let (lsp, cancel) = (lsp.clone(), cancel.clone());
async move {
let positions: Vec<_> = entries.iter().map(|(_, p)| *p).collect();
(entries, lsp.implementations(target, &positions, cancel).await)
(entries, lsp.goto_each(kind, target, &positions, cancel).await)
}
}))
.await;
@@ -775,6 +774,21 @@ pub async fn lsp_implementations(
Err(error.expect("at least one request"))
};
host.end_request(request);
result
}
/// Implementations of the symbols at `positions`, one list per position (the
/// editor's "is implemented / overridden" gutter markers). Cancel with
/// `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_implementations(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
positions: Vec<Pos>,
) -> IdeResult<Vec<Vec<Location>>> {
let result = goto_each(host, window, request, doc, GotoKind::Implementation, &positions).await;
if let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Implementation) {
let count = positions.len();
let found = plugin_call(move || {
@@ -792,6 +806,21 @@ pub async fn lsp_implementations(
result
}
/// Go-to `kind` (declaration, definition) of the symbols at `positions`, one list per position:
/// the editor's "implements" gutter markers for languages without a type hierarchy (Rust).
/// Cancel with `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_gotos(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
kind: GotoKind,
positions: Vec<Pos>,
) -> IdeResult<Vec<Vec<Location>>> {
goto_each(host, window, request, doc, kind, &positions).await
}
/// Refines the implementations `targets` of the method at `pos` to their declarations (Java
/// dependencies' class files point at the start of the class). Cancel with
/// `cancel_request(request)`.
@@ -3402,6 +3431,7 @@ ide_command::domain!(
lsp_source_action_text,
lsp_goto,
lsp_goto_implementation,
lsp_gotos,
lsp_hierarchy_members,
lsp_hierarchy_refactor,
lsp_hover,
+2
Переглянути файл
@@ -514,6 +514,8 @@ pub fn set_settings(
let code_style = key == "editor"
|| key == "editor.codeStyle"
|| key.starts_with("editor.codeStyle.")
|| key == "editor.inlay"
|| key.starts_with("editor.inlay.")
|| key == "inspections"
|| key.starts_with("inspections.")
|| key == "files"
+24 -1
Переглянути файл
@@ -19,6 +19,16 @@ fn pairs(moves: &[FileMove]) -> Vec<(PathBuf, PathBuf)> {
moves.iter().map(|m| (m.from.to_path_buf(), m.to.to_path_buf())).collect()
}
/// Tells the version control backend of each destination about the moves, as `fs_rename` does:
/// a checkout (Subversion) records them so history follows the files; Git's hook does nothing.
fn record_moves(project: &crate::Project, moves: &[(PathBuf, PathBuf)]) {
for (from, to) in moves {
if let Err(e) = project.with_backend_of(to, |r| r.file_moved(from, to)) {
tracing::debug!("vcs file_moved {} → {}: {e}", from.display(), to.display());
}
}
}
/// `workspace/willRenameFiles` on every interested server (before the move), plus the
/// Python import updates the IDE makes itself. Cancellable.
#[command(trust = always)]
@@ -217,6 +227,13 @@ pub async fn refactor_move_files(
p.moves.perform(&p.documents, Some(&p.history), &moved, &edit, &label, &apply)
})
.await?;
let p = project.clone();
let done = pairs(&moves);
blocking(move || {
record_moves(&p, &done);
Ok(())
})
.await?;
project.lsp.did_rename_files(&pairs(&moves));
Ok(id)
}
@@ -226,7 +243,13 @@ pub async fn refactor_move_files(
pub async fn refactor_undo_file_move(host: &Host, window: &str, id: u32) -> IdeResult<UndoOutcome> {
let project = host.project(window)?;
let p = project.clone();
let outcome = blocking(move || p.moves.undo(&p.documents, id)).await?;
let outcome = blocking(move || {
let outcome = p.moves.undo(&p.documents, id)?;
// The moves made to take them back (`from` is where the refactoring put the file).
record_moves(&p, &pairs(&outcome.moves));
Ok(outcome)
})
.await?;
project.lsp.did_rename_files(&pairs(&outcome.moves));
Ok(outcome)
}
+62 -2
Переглянути файл
@@ -93,14 +93,17 @@ fn detected_and_saved(
.linked_projects
.as_ref()
.map(|_| ide_build::gradle::load_linked(root, &settings.languages.java.gradle));
let mut detected = ide_run::detect_with_profiles(root, &excluded_poms, settings.cmake.profiles.as_deref());
let (mut saved, mut suppressed) = (saved.to_vec(), suppressed.to_vec());
ide_run::upgrade_cmake_profile_ids(root, &settings.cmake, &mut saved, &mut suppressed);
let mut detected = ide_run::detect_with_cmake(root, &excluded_poms, &settings.cmake, &settings.toolchains);
ide_run::refresh_saved_cmake_profiles(&mut saved, &detected);
detected.extend(ide_run::detect_builds(root, &linked_build_dirs(root, settings, gradle.as_deref(), &detected)));
let mut all: Vec<RunConfig> = detected
.into_iter()
.filter(|d| !suppressed.contains(&d.id) && !saved.iter().any(|u| u.id == d.id))
.filter(|d| linked_config(root, gradle.as_deref(), &excluded_poms, d))
.collect();
all.extend(saved.iter().cloned());
all.extend(saved);
for config in all.iter_mut().filter(|c| !matches!(c.kind.as_str(), "gradle" | "maven")) {
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(config), root, settings);
}
@@ -548,6 +551,9 @@ async fn start_inner(
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
}
if matches!(config.kind.as_str(), "xcode" | "xcode-test" | ide_run::xcode_clean::KIND) {
super::xcode_bsp::stop_index_build(&project.root).await;
}
let xcode_container = matches!(config.kind.as_str(), "xcode" | "xcode-test")
.then(|| xcode_container(&config).map(|c| run_dir.join(c)))
.flatten();
@@ -971,6 +977,60 @@ mod ownership_tests {
container_python_path(&mut none, &["/elsewhere".into()], root);
assert!(none.is_empty());
}
#[test]
fn saved_cmake_configs_follow_the_active_profile_and_keep_launch_customizations() {
use ide_core::settings::CMakeProfile;
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
std::fs::write(root.join("CMakeLists.txt"), "project(app)").unwrap();
let profile = |name: &str| {
let reply = root.join(name).join(".cmake/api/v1/reply");
std::fs::create_dir_all(&reply).unwrap();
std::fs::write(
reply.join("index-1.json"),
r#"{"objects":[{"kind":"codemodel","version":{"major":2},"jsonFile":"model.json"}]}"#,
)
.unwrap();
std::fs::write(
reply.join("model.json"),
r#"{"configurations":[{"name":"","targets":[{"jsonFile":"app.json"}]}]}"#,
)
.unwrap();
std::fs::write(
reply.join("app.json"),
r#"{"name":"app","type":"EXECUTABLE","artifacts":[{"path":"app"}]}"#,
)
.unwrap();
CMakeProfile { name: name.into(), build_dir: name.into(), ..Default::default() }
};
let mut settings = ide_core::settings::Settings::default();
settings.cmake.profiles = Some(vec![profile("first"), profile("second")]);
let mut saved = detected_and_saved(root, &settings, &[], &[]);
let app = saved.iter_mut().find(|c| c.id == "cmake:profile:target:app").unwrap();
app.name = "Custom app".into();
app.args.push("--custom".into());
app.env.insert("APP_MODE".into(), "custom".into());
app.extras.before_launch.push(ide_run::BeforeLaunchTask {
kind: "run".into(),
target: "user:prepare".into(),
..Default::default()
});
let tasks = app.extras.before_launch.clone();
settings.cmake.active_profile = "second".into();
let configs = detected_and_saved(root, &settings, &saved, &[]);
let find = |id: &str| configs.iter().find(|c| c.id == id).unwrap();
let app = find("cmake:profile:target:app");
assert_eq!(Path::new(&app.command), root.join("second/app"));
assert_eq!(app.name, "Custom app");
assert_eq!(app.args, ["--custom"]);
assert_eq!(app.env["APP_MODE"], "custom");
assert_eq!(app.extras.before_launch, tasks);
assert_eq!(find("cmake:profile:target:app:build").args[1], "second");
assert_eq!(find("cmake:profile:configure").extras.params["buildDir"], "second");
}
#[test]
fn unlinked_builds_do_not_reappear_as_detected_application_configs() {
let temp = tempfile::tempdir().unwrap();
+12 -9
Переглянути файл
@@ -204,15 +204,15 @@ pub fn sdk_php_effective(host: &Host, window: &str) -> IdeResult<Option<ide_core
}
/// The version of the PHP interpreter `php` and of the Xdebug it loads, run in `cwd` (default: the
/// project root).
#[command(trust = trusted)]
/// project root). Also from Settings on the Welcome screen.
#[command(trust = outside_restricted)]
pub async fn sdk_php_xdebug(
host: &Host,
window: &str,
php: PathBuf,
cwd: Option<PathBuf>,
) -> IdeResult<ide_sdk::php::PhpXdebug> {
host.require_trust(window)?;
host.require_trust_if_project(window)?;
let cwd = cwd.or_else(|| host.project(window).ok().map(|p| p.root.clone()));
blocking(move || ide_sdk::php::xdebug(&php, cwd.as_deref())).await
}
@@ -349,14 +349,15 @@ pub async fn sdk_project_libraries(
}
/// Looks up `names` (bare command names): `node_modules/.bin` above `near`, then the search path.
#[command(trust = trusted)]
/// Also from Settings on the Welcome screen (the PHP interpreter).
#[command(trust = outside_restricted)]
pub async fn sdk_locate_tools(
host: &Host,
window: &str,
names: Vec<String>,
near: Option<PathBuf>,
) -> IdeResult<LocatedTools> {
host.require_trust(window)?;
host.require_trust_if_project(window)?;
blocking_value(move || LocatedTools {
tools: ide_sdk::locate::locate_tools(&names, near.as_deref()),
compile_dir: ide_sdk::locate::compile_dir().into(),
@@ -475,16 +476,18 @@ pub async fn sdk_python_pip(
result
}
/// The JDK whose home is `path`, as the SDK list shows it; `None` when it is no JDK home.
#[command(trust = trusted)]
/// The JDK whose home is `path`, as the SDK list shows it; `None` when it is no JDK home. SDKs
/// are IDE-wide, so Add JDK from Disk works from the Welcome screen as well (#7361).
#[command(trust = outside_restricted)]
pub async fn sdk_jdk_at(path: String) -> IdeResult<Option<Sdk>> {
// A macOS bundle too (Add JDK from Disk…).
blocking_value(move || ide_sdk::java::jdk_at(std::path::Path::new(&path)).map(|j| ide_sdk::jdk_sdk(&j))).await
}
/// `flutter --version --machine` of the Flutter SDK at `path`, or of the `flutter` on the
/// search path when `path` is empty; `None` when there is no Flutter SDK.
#[command(trust = trusted)]
/// search path when `path` is empty; `None` when there is no Flutter SDK. Also from Settings on
/// the Welcome screen, as the SDK list.
#[command(trust = outside_restricted)]
pub async fn sdk_flutter_at(
host: &Host,
window: &str,
+10 -2
Переглянути файл
@@ -75,13 +75,18 @@ pub async fn svn_unlock(host: &Host, window: &str, paths: Vec<PathBuf>, force: b
.await
}
/// Where a working copy points: VCS › Subversion › Relocate shows the current URL.
/// Where a working copy points (VCS › Subversion › Relocate shows the current URL), and what
/// the Working Copies tab shows of it.
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SvnRepositoryInfo {
pub url: String,
pub root_url: String,
pub uuid: String,
pub revision: Option<u32>,
pub depth: String,
/// The oldest svn release that reads the working copy (`1.8`); `None` before svn 1.15.
pub format: Option<String>,
}
#[command(trust = trusted)]
@@ -89,11 +94,14 @@ pub async fn svn_repository_info(host: &Host, window: &str, repo: Option<PathBuf
let project = host.project(window)?;
blocking(move || {
with_working_copy(&project, repo.as_deref(), |wc| {
let r = wc.repository();
let r = wc.current_repository();
Ok(SvnRepositoryInfo {
url: r.url,
root_url: r.root_url,
uuid: r.uuid,
revision: r.revision.and_then(|r| u32::try_from(r).ok()),
depth: r.depth,
format: r.format,
})
})
})
+48 -7
Переглянути файл
@@ -33,14 +33,20 @@ pub async fn vcs_status_paths(host: &Host, window: &str, paths: Vec<std::path::P
host.blocking(move || merged_status(&project, Some(&paths))).await
}
/// The Git repositories' changes and those of the non-Git working copies, each file reported
/// by the backend [`crate::Project::backend_of`] routes it to. `paths` narrows them (empty:
/// everything). A working copy that cannot answer (an unreachable server) is logged and
/// skipped while another backend answered, so it never hides the Git changes.
/// The last status failure said for each working copy root (see [`merged_status`]).
static STATUS_FAILURES: parking_lot::Mutex<std::collections::BTreeMap<std::path::PathBuf, String>> =
parking_lot::Mutex::new(std::collections::BTreeMap::new());
/// The last rows each working copy root reported in a full status: what is shown for it while it
/// cannot answer, instead of nothing (the Changes view replaces every row with a full status).
static LAST_ROWS: parking_lot::Mutex<std::collections::BTreeMap<std::path::PathBuf, Vec<FileStatus>>> =
parking_lot::Mutex::new(std::collections::BTreeMap::new());
/// The Git repositories' changes and those of the non-Git working copies, each file reported
/// by the backend [`crate::Project::backend_of`] routes it to. `paths` narrows them (empty:
/// everything). A working copy that cannot answer (an unreachable server) is logged and
/// skipped while another backend answered, so it never hides the Git changes; its last rows
/// stay.
fn merged_status(project: &crate::Project, paths: Option<&[std::path::PathBuf]>) -> IdeResult<Vec<FileStatus>> {
let settings = project.settings.effective();
let repos = project.repos();
@@ -68,14 +74,34 @@ fn merged_status(project: &crate::Project, paths: Option<&[std::path::PathBuf]>)
status.retain(|f| owner(f).is_none());
let mut answered = !repos.is_empty();
let mut failure = None;
// A refresh of some paths replaces those rows: a working copy that could not report on its
// own paths fails it, so the rows already shown stay instead of vanishing.
let mut paths_failed = false;
for backend in &backends {
let mut asked: Vec<std::path::PathBuf> = Vec::new();
let changes = match paths.filter(|p| !p.is_empty()) {
Some(paths) => {
let mine: Vec<_> = paths.iter().filter(|p| p.starts_with(backend.root())).cloned().collect();
// The paths it owns: not those of a Git repository nested in it.
let mine: Vec<_> = paths
.iter()
.filter(|p| {
crate::project::backend_for(&backends, &repos, p).map(|b| b.root()) == Some(backend.root())
})
.cloned()
// A folder refreshed with a working copy of its own below it (a nested
// checkout, an external): that one's rows are refreshed too.
.chain(
paths
.iter()
.any(|p| backend.root().starts_with(p) && backend.root() != p.as_path())
.then(|| backend.root().to_path_buf()),
)
.collect();
if mine.is_empty() {
answered = true;
continue;
}
asked = mine.clone();
backend.status_paths(&mine)
}
None => backend.status(),
@@ -83,7 +109,18 @@ fn merged_status(project: &crate::Project, paths: Option<&[std::path::PathBuf]>)
match changes {
Ok(changes) => {
answered = true;
status.extend(changes.into_iter().filter(|f| owner(f) == Some(backend.root())));
let rows: Vec<FileStatus> = changes.into_iter().filter(|f| owner(f) == Some(backend.root())).collect();
let mut last = LAST_ROWS.lock();
if asked.is_empty() {
last.insert(backend.root().to_path_buf(), rows.clone());
} else if let Some(kept) = last.get_mut(backend.root()) {
// A refresh of some paths replaces what is kept of them: a row it no longer
// lists (the file is clean now) must not come back with a failed full status.
kept.retain(|f| !asked.iter().any(|p| f.path.0.starts_with(p)));
kept.extend(rows.iter().cloned());
}
drop(last);
status.extend(rows);
STATUS_FAILURES.lock().remove(backend.root());
}
Err(e) => {
@@ -98,12 +135,16 @@ fn merged_status(project: &crate::Project, paths: Option<&[std::path::PathBuf]>)
body: Some(e.message.clone()),
});
}
paths_failed |= paths.is_some_and(|p| !p.is_empty());
if !paths_failed && let Some(rows) = LAST_ROWS.lock().get(backend.root()) {
status.extend(rows.iter().cloned());
}
failure = Some(e);
}
}
}
match failure {
Some(e) if !answered => Err(e),
Some(e) if !answered || paths_failed => Err(e),
_ => Ok(status),
}
}
+90 -8
Переглянути файл
@@ -780,7 +780,22 @@ pub async fn vcs_image_at(host: &Host, window: &str, path: PathBuf, rev: String)
{
return Err(ide_core::IdeError::invalid("image is not on a local drive or an opened share"));
}
project.with_log_repo_of(&path, read)?
match project.backend_of(&path) {
// Another system's working copy (Subversion): its own reading at that revision.
Some(backend) => {
// Its size first: an image too large to preview is never read into memory.
let size = backend.file_size_at(&path, Some(&rev))?;
if size.is_some_and(|n| n > ide_vfs::MAX_IMAGE_SIZE) {
return Err(ide_core::IdeError::invalid(format!("{} is too large to preview", path.display())));
}
let bytes = backend.file_bytes_at(&path, Some(&rev))?;
if bytes.as_ref().is_some_and(|b| b.len() > ide_vfs::MAX_IMAGE_SIZE as usize) {
return Err(ide_core::IdeError::invalid(format!("{} is too large to preview", path.display())));
}
bytes
}
None => project.with_log_repo_of(&path, read)?,
}
} else {
read(external.as_deref().ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?)?
};
@@ -1452,6 +1467,10 @@ pub async fn vcs_checkout(
format!("branches/{branch}")
};
wc.create_line(&line, &format!("Create {line}"), &ide_core::CancellationToken::new())?;
// A tag is a snapshot to keep, not a line to work on: the working copy stays.
if line.starts_with("tags/") {
return Ok(CheckoutOutcome::Done);
}
return b.switch_to(&line).map(|()| CheckoutOutcome::Done);
}
b.switch_to(&branch).map(|()| CheckoutOutcome::Done)
@@ -1960,10 +1979,14 @@ pub async fn vcs_remote(
if matches!(op, RemoteOp::Pull { .. } | RemoteOp::UpdateProjectBranch { .. })
&& project.backend_at(repo.as_deref()).is_some()
{
return with_shelf_batch(&project, shelf_batch, || {
let result = with_shelf_batch(&project, shelf_batch, || {
project
.with_backend_recorded(repo.as_deref(), Some("Update"), |b| b.update(&cancel, &out).map(|()| None))
});
// An update brings or takes away externals (working copies of their own): the roots
// are known when it returns, not only once a later scan runs.
project.refresh_backends();
return result;
}
with_shelf_batch(&project, shelf_batch, || {
project.with_repo_recorded(repo.as_deref(), recorded, |r| match op {
@@ -3272,11 +3295,14 @@ pub async fn vcs_shelve(host: &Host, window: &str, name: String, paths: Vec<Path
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || {
let shelf = shelf_dir(&project.root);
if let Some(backend) = paths.iter().find_map(|path| project.backend_of(path)) {
return shelve_working_copy(&project, backend.as_ref(), &shelf, &name, &paths);
}
let groups = project.repos().group(&paths);
if groups.is_empty() || groups.iter().map(|(_, selected)| selected.len()).sum::<usize>() != paths.len() {
return Err(ide_core::IdeError::invalid("select files in a git repository to shelve"));
}
let shelf = shelf_dir(&project.root);
if let [(repo, selected)] = groups.as_slice() {
keep_private(&project.root);
return project
@@ -3302,6 +3328,40 @@ pub async fn vcs_shelve(host: &Host, window: &str, name: String, paths: Vec<Path
.await
}
/// Shelve Changes in a Subversion working copy: the patch goes on the shelf, then the files
/// are rolled back. Files of other working copies or Git repositories are shelved on their own.
fn shelve_working_copy(
project: &Project,
backend: &dyn Backend,
shelf: &Path,
name: &str,
paths: &[PathBuf],
) -> IdeResult<ShelvedChangeList> {
let wc = crate::ops::svn::as_svn(backend)
.ok_or_else(|| ide_core::IdeError::invalid("Shelve Changes is available for Git and Subversion only"))?;
if paths.iter().any(|path| project.backend_of(path).is_none_or(|other| other.root() != wc.root())) {
return Err(ide_core::IdeError::invalid(
"select files of one Subversion working copy to shelve; shelve the others separately",
));
}
let patch = wc.shelf_patch(paths)?;
keep_private(&project.root);
let entry = ide_vcs::shelf::save(shelf, name, wc.root(), backend.head_label(), &patch)?;
project.backend_recorded(backend, Some("Shelve"), |_| wc.shelf_revert(paths, &patch))?;
project.vcs_changed();
Ok(entry)
}
/// The Subversion working copy a shelved selection was made in, if it was.
fn shelved_working_copy(
project: &Project,
selection: &ide_vcs::shelf::ShelfSelection,
) -> Option<std::sync::Arc<dyn Backend>> {
project
.backend_at(Some(selection.repo.as_deref()?))
.filter(|backend| crate::ops::svn::as_svn(backend.as_ref()).is_some())
}
#[command(trust = always)]
pub async fn vcs_shelves(host: &Host, window: &str) -> IdeResult<Vec<ShelvedChangeList>> {
let project = host.project(window)?;
@@ -3333,13 +3393,25 @@ pub async fn vcs_unshelve(
blocking(move || {
let shelf = shelf_dir(&project.root);
let selections = ide_vcs::shelf::selections(&shelf, &id, path.as_deref())?;
for selection in &selections {
project.with_repo_at(selection.repo.as_deref(), |_| Ok(()))?;
let working_copies: Vec<_> =
selections.iter().map(|selection| shelved_working_copy(&project, selection)).collect();
for (selection, wc) in selections.iter().zip(&working_copies) {
if wc.is_none() {
project.with_repo_at(selection.repo.as_deref(), |_| Ok(()))?;
}
}
let mut result = ApplyOutcome { applied: Vec::new(), conflicts: Vec::new() };
for selection in &selections {
let outcome =
project.with_repo_recorded(selection.repo.as_deref(), Some("Unshelve"), |r| selection.apply(r))?;
for (selection, wc) in selections.iter().zip(&working_copies) {
let outcome = match wc {
Some(backend) => project.backend_recorded(backend.as_ref(), Some("Unshelve"), |b| {
let wc = crate::ops::svn::as_svn(b)
.ok_or_else(|| ide_core::IdeError::invalid("not a Subversion working copy"))?;
wc.unshelve(selection.patch())
})?,
None => {
project.with_repo_recorded(selection.repo.as_deref(), Some("Unshelve"), |r| selection.apply(r))?
}
};
if remove && outcome.conflicts.is_empty() {
ide_vcs::shelf::delete_paths(&shelf, &id, &outcome.applied)?;
}
@@ -3394,6 +3466,16 @@ pub async fn vcs_shelf_diff(host: &Host, window: &str, id: String) -> IdeResult<
let shelf = shelf_dir(&project.root);
let mut files = Vec::new();
for selection in ide_vcs::shelf::selections(&shelf, &id, None)? {
if let Some(backend) = shelved_working_copy(&project, &selection) {
// The base each file had: the shelved hunks were made against it. A folder's
// change is its properties, which the patch shows.
let root = backend.root().to_path_buf();
files.extend(selection.diff_files_on(|path| match root.join(path) {
path if path.is_dir() => Ok(None),
path => backend.file_bytes_at(&path, Some("BASE")),
}));
continue;
}
files.extend(project.with_repo_at(selection.repo.as_deref(), |r| selection.diff_files(r))?);
}
Ok(files)
+132 -21
Переглянути файл
@@ -4,13 +4,20 @@
//! server: when a trusted project has none, it runs the one on `PATH` (xcode-build-server,
//! sourcekit-xcode-bsp) to write the config, keeps the config out of Git through
//! `.git/info/exclude`, then restarts sourcekit-lsp.
//!
//! xcode-build-server reads compiler arguments from the latest build log in DerivedData, so
//! until the project's first build it has none to give. [`xcode_index_build`] runs that build in
//! the background, the way Run would, so cross-file code insight works without pressing Run.
use crate::Host;
use ide_command::command;
use ide_core::{IdeError, IdeResult};
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, TaskId};
use ide_run::xcode_index::{self, XcodeIndexBuild};
use serde::Serialize;
use specta::Type;
use std::path::Path;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{LazyLock, Mutex};
/// The generators, in order of preference, and their arguments for `container`.
const TOOLS: [&str; 2] = ["xcode-build-server", "sourcekit-xcode-bsp"];
@@ -29,23 +36,6 @@ fn tool_args(tool: &str, container: &str, build_root: Option<&Path>) -> Vec<Stri
args
}
/// The DerivedData folder Xcode (and a run) builds `container` in, read from the build settings of
/// the first scheme in `root`'s projects. Without it xcode-build-server reads the build settings of
/// the workspace's first scheme, which may be a package's with none (an `IndexError` on a Tuist
/// workspace whose first scheme is a Swift package). `None` leaves it to xcode-build-server.
fn build_root(root: &Path, container: &str) -> Option<std::path::PathBuf> {
let scheme = ide_run::xcode::schemes(root).into_iter().next()?.name;
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
let mut cmd = Command::new("xcodebuild");
ide_core::process::prepare(&mut cmd)
.args([flag, container, "-scheme", &scheme, "-showBuildSettings", "-json"])
.current_dir(root)
.stdin(Stdio::null())
.stderr(Stdio::null());
let out = cmd.output().ok().filter(|o| o.status.success())?;
ide_run::xcode_clean::derived_data_of(&String::from_utf8_lossy(&out.stdout))
}
/// The config `tool` writes at the project root.
fn config_name(tool: &str) -> &'static str {
if tool == "sourcekit-xcode-bsp" { ".bsp" } else { "buildServer.json" }
@@ -143,7 +133,11 @@ pub async fn xcode_bsp_generate(host: &Host, window: &str, tool: String, contain
let mut cmd = Command::new(exe);
ide_core::process::prepare(&mut cmd)
// An absolute path: with `--build_root` it is written to the config as given.
.args(tool_args(&tool, &root.join(&container).to_string_lossy(), build_root(&root, &container).as_deref()))
.args(tool_args(
&tool,
&root.join(&container).to_string_lossy(),
xcode_index::first_scheme_build_root(&root, &container).as_deref(),
))
.current_dir(&root)
.env("PATH", &search)
.stdin(Stdio::null());
@@ -167,7 +161,111 @@ pub async fn xcode_bsp_generate(host: &Host, window: &str, tool: String, contain
Ok(())
}
ide_command::domain!(xcode_bsp: xcode_bsp_setup, xcode_bsp_generate);
#[derive(Clone)]
struct IndexBuild {
cancel: CancellationToken,
finished: CancellationToken,
}
static RUNNING: LazyLock<Mutex<HashMap<PathBuf, IndexBuild>>> = LazyLock::new(Default::default);
/// Lives in the blocking worker until its Xcode processes have exited and been reaped.
struct RunningIndexBuild {
root: PathBuf,
build: IndexBuild,
}
impl RunningIndexBuild {
fn start(root: PathBuf, cancel: CancellationToken) -> Option<Self> {
let mut running = RUNNING.lock().unwrap_or_else(|e| e.into_inner());
if running.contains_key(&root) {
return None;
}
let build = IndexBuild { cancel, finished: CancellationToken::new() };
running.insert(root.clone(), build.clone());
Some(Self { root, build })
}
}
impl Drop for RunningIndexBuild {
fn drop(&mut self) {
RUNNING.lock().unwrap_or_else(|e| e.into_inner()).remove(&self.root);
self.build.finished.cancel();
}
}
/// Stops the project's background build and waits for its processes before Run, Test or Clean.
pub(crate) async fn stop_index_build(root: &Path) {
let build = RUNNING.lock().unwrap_or_else(|e| e.into_inner()).get(root).cloned();
if let Some(build) = build {
build.cancel.cancel();
build.finished.cancelled().await;
}
}
/// Builds what Run builds (its first configuration, for its destination) at low priority
/// (`taskpolicy -c utility`), when the project's xcode-build-server config has no build log to
/// read yet: until then sourcekit-lsp has no compiler arguments, so types from other targets and
/// packages don't resolve. A cancellable background task; it backs off while Xcode uses the build
/// folder. Run later builds incrementally on top of it.
#[command(trust = trusted)]
pub async fn xcode_index_build(host: &Host, window: &str) -> IdeResult<XcodeIndexBuild> {
let project = host.project(window)?;
let root = project.root.clone();
let Some(build_root) = xcode_index::pending_build_root(&root) else { return Ok(XcodeIndexBuild::NotNeeded) };
if !cfg!(target_os = "macos") {
return Ok(XcodeIndexBuild::NotNeeded);
}
let Some(running) = RunningIndexBuild::start(root, project.closed.child_token()) else {
return Ok(XcodeIndexBuild::NotNeeded);
};
let sink = project.sink.clone();
let result = super::blocking(move || {
let result = index_build(&running.root, &build_root, &sink, &running.build.cancel);
drop(running);
result
})
.await?;
if matches!(result, XcodeIndexBuild::Built | XcodeIndexBuild::Failed { .. }) {
for server in project.lsp.servers().into_iter().filter(|s| s.name == "sourcekit-lsp") {
project.lsp.restart(server.id).await?;
}
}
Ok(result)
}
fn index_build(
root: &Path,
build_root: &Path,
sink: &ide_core::SharedSink,
cancel: &CancellationToken,
) -> IdeResult<XcodeIndexBuild> {
let params = ide_run::xcode::first_run_params(root)
.ok_or_else(|| IdeError::unavailable("The Xcode project has no scheme to build"))?;
let scheme = params.get("scheme").cloned().unwrap_or_default();
let task = TaskId::next();
let _cancel_handle = ide_core::task::on_cancel(task, {
let cancel = cancel.clone();
move || cancel.cancel()
});
let progress = |message: Option<String>, done: bool| {
sink.emit(IdeEvent::Task {
id: task,
title: format!("Building {scheme} for code insight"),
message,
fraction: None,
done,
cancellable: !done,
});
};
progress(Some("Reading build settings…".into()), false);
let result =
xcode_index::build(root, build_root, &params, &|target| progress(Some(target.to_owned()), false), cancel);
progress(None, true);
result
}
ide_command::domain!(xcode_bsp: xcode_bsp_setup, xcode_bsp_generate, xcode_index_build);
#[cfg(test)]
mod tests {
@@ -282,6 +380,19 @@ mod tests {
);
}
#[tokio::test]
async fn a_foreground_run_waits_for_only_its_background_build() {
let (a, b) = (PathBuf::from("/a11-test/App"), PathBuf::from("/a11-test/Other"));
let mine = RunningIndexBuild::start(a.clone(), CancellationToken::new()).unwrap();
let other = RunningIndexBuild::start(b, CancellationToken::new()).unwrap();
let stop = tokio::spawn(async move { stop_index_build(&a).await });
mine.build.cancel.cancelled().await;
assert!(!stop.is_finished(), "foreground waits for the worker to exit");
assert!(!other.build.cancel.is_cancelled());
drop(mine);
stop.await.unwrap();
}
#[test]
fn accepts_only_bundle_names_in_the_root() {
assert!(is_container_name("App.xcworkspace") && is_container_name("App.xcodeproj"));
+25
Переглянути файл
@@ -1746,6 +1746,31 @@ impl PluginApi {
}
impl HostApi for PluginApi {
fn database_table_schema(
&self,
root: &Path,
client: Option<&str>,
table: &ide_plugin::PluginDatabaseTableRef,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<ide_plugin::PluginDatabaseTableSchema, HostError> {
self.require_api("database table schema", 20)?;
let (host, fallback) = self.database_host(root)?;
// Connections belong to windows, even when several windows open the same root.
// Prefer the invoking window; background calls may use any connected instance.
let db = client
.and_then(|client| host.project(client).ok())
.filter(|project| project.root == root)
.map(|project| project.db.clone())
.or_else(|| {
host.projects()
.into_iter()
.find(|project| project.root == root && project.db.is_connected(&table.source_id))
.map(|project| project.db.clone())
})
.unwrap_or(fallback);
host.runtime.block_on(super::database::table_schema(&db, table, cancel, timeout))
}
fn database_upsert(&self, root: &Path, source: ide_plugin::PluginDataSource) -> Result<(), HostError> {
let (host, db) = self.database_host(root)?;
let id = source.id.clone();
+64
Переглянути файл
@@ -189,6 +189,70 @@ pub(super) fn error(e: IdeError) -> HostError {
}
}
/// Schema inspection is deliberately separate from ownership/credential management.
pub(super) async fn table_schema(
db: &ide_db::DbManager,
table: &ide_plugin::PluginDatabaseTableRef,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<ide_plugin::PluginDatabaseTableSchema, HostError> {
if table.source_id.is_empty()
|| table.table.is_empty()
|| [&table.source_id, &table.schema, &table.table]
.into_iter()
.chain(table.catalog.iter())
.any(|v| v.len() > 4096 || v.contains('\0'))
{
return Err(HostError::Invalid("invalid database table reference".into()));
}
if cancel.is_cancelled() {
return Err(HostError::Cancelled);
}
let read = db.connected_table_details(&table.source_id, table.catalog.as_deref(), &table.schema, &table.table);
let details = tokio::select! {
biased;
_ = cancel.cancelled() => return Err(HostError::Cancelled),
result = tokio::time::timeout(timeout, read) => result
.map_err(|_| HostError::Failed("Database schema request timed out".into()))?.map_err(error)?,
};
if details.columns.is_empty() {
return Err(HostError::NotFound("table has no visible columns".into()));
}
if details.columns.len() > 4096 || details.indexes.len() > 4096 || details.foreign_keys.len() > 4096 {
return Err(HostError::Invalid("table schema exceeds 4096 columns, indexes or foreign keys".into()));
}
Ok(ide_plugin::PluginDatabaseTableSchema {
comment: details.comment,
columns: details
.columns
.into_iter()
.map(|c| ide_plugin::PluginDatabaseColumn {
name: c.name,
data_type: c.data_type,
nullable: c.nullable,
default_value: c.default,
primary_key: c.primary_key,
comment: c.comment,
})
.collect(),
indexes: details
.indexes
.into_iter()
.map(|i| ide_plugin::PluginDatabaseIndex { name: i.name, unique: i.unique, columns: i.columns })
.collect(),
foreign_keys: details
.foreign_keys
.into_iter()
.map(|f| ide_plugin::PluginDatabaseForeignKey {
columns: f.columns,
referenced_schema: f.ref_schema,
referenced_table: f.ref_table,
referenced_columns: f.ref_columns,
})
.collect(),
})
}
#[cfg(test)]
mod tests {
use super::*;
+2
Переглянути файл
@@ -447,6 +447,8 @@ pub(crate) fn outline(items: Vec<DocumentSymbol>) -> Vec<ide_core::OutlineItem>
selection_range: i.selection_range,
children: vec![],
visibility: None,
implements: None,
self_type: None,
})
})
.collect();
+21 -1
Переглянути файл
@@ -119,7 +119,9 @@ const COMMIT_MESSAGE_MENU: &str = "commit.message";
const SERVICES_MENUS: [&str; 2] = ["services.context", "services.toolbar"];
/// The Open In › submenu of the editor, editor tab and project view menus: the command gets the file.
const OPEN_IN_MENU: &str = "openIn";
const MENU_IDS: [&str; 13] = [
/// Context menu of tables/views in the Database tool window (API 1.20).
const DATABASE_TABLE_MENU: &str = "database.table.context";
const MENU_IDS: [&str; 14] = [
"editor.context",
"projectView.context",
"editorTab.context",
@@ -133,6 +135,7 @@ const MENU_IDS: [&str; 13] = [
SERVICES_MENUS[0],
SERVICES_MENUS[1],
OPEN_IN_MENU,
DATABASE_TABLE_MENU,
];
const MAX_TITLE: usize = 256;
const MAX_SETTINGS: usize = 200;
@@ -200,6 +203,9 @@ pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
if SERVICES_MENUS.contains(&d.menu.as_str()) {
pkg.manifest.needs_api(&format!("contributes.menus: {}", d.menu), 18)?;
}
if d.menu == DATABASE_TABLE_MENU {
pkg.manifest.needs_api(&format!("contributes.menus: {DATABASE_TABLE_MENU}"), 20)?;
}
if d.menu == OPEN_IN_MENU {
pkg.manifest.needs_api(&format!("contributes.menus: {OPEN_IN_MENU}"), 19)?;
}
@@ -1372,6 +1378,20 @@ pub(super) fn locales(pkg: &Package, _decl: toml::Value) -> Result<UiDecl, Strin
#[cfg(test)]
mod tests {
#[test]
fn database_table_menu_requires_api20_and_a_declared_command() {
use ide_extension::{Manifest, Package};
for (api, valid) in [("^1.19", false), ("^1.20", true)] {
let source = format!(
"id='schema'\nname='Schema'\nversion='1.0.0'\nengines.openidea='{api}'\n[[contributes.commands]]\nid='generate'\ntitle='Generate Mapper'"
);
let pkg = Package::new(Manifest::parse(&source).unwrap(), std::path::PathBuf::from("/unused"));
let decl=toml::from_str("menu='database.table.context'\ncommand='generate'\nsubmenu='Generate'\nwhen='databaseObjectKind == table'").unwrap();
assert_eq!(super::menu(&pkg, decl).is_ok(), valid);
let undeclared = toml::from_str("menu='database.table.context'\ncommand='unknown'").unwrap();
assert!(super::menu(&pkg, undeclared).is_err());
}
}
use super::*;
#[test]
+23
Переглянути файл
@@ -251,6 +251,7 @@ impl Host {
ide_sdk::apply::configure_server(cfg, root, server_root, &effective);
ide_sdk::json_schemas::configure(cfg, root, &effective.json_schemas);
crate::ts_code_style::configure(cfg, server_root, &effective);
crate::ts_code_style::configure_inlay_hints(cfg, &effective);
ide_sdk::apply::configure_vue_module_resolution(cfg, &data_dir);
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
let css_modules = ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit");
@@ -1496,7 +1497,18 @@ impl BackendScan<'_> {
for folder in &folders {
// The folder itself (its working copy may start above it): every provider.
if !found.iter().any(|b| folder.starts_with(b.root())) {
let before = found.len();
ask_providers(folder, self.providers, &mut found);
// Found above the folder: the folder is not versioned in that checkout. A Git
// project there is the Git repository's alone, not the whole checkout's (whose
// other files would show as this project's changes).
let above = found.get(before).is_some_and(|b| b.root() != folder && folder.starts_with(b.root()));
if above
&& (folder.join(".git").exists()
|| !ide_vcs::marked_folders(folder, &[".git"], &skip).is_empty())
{
found.truncate(before);
}
}
// Working copies nested below it, like nested Git repositories: a separate
// checkout or a directory external inside a working copy, or one inside a Git
@@ -1512,6 +1524,17 @@ impl BackendScan<'_> {
ask_providers(&nested, marked, &mut found);
}
}
// Working copies the backends know of inside them (externals in `vendor/`, deeper
// than the search goes), and those inside these in turn.
let mut i = 0;
while i < found.len() {
for nested in found[i].nested_roots() {
if nested.starts_with(root) && !found.iter().any(|b| b.root() == nested) {
ask_providers(&nested, self.providers, &mut found);
}
}
i += 1;
}
}
let roots =
|list: &[Arc<dyn Backend>]| list.iter().map(|b| (b.kind(), b.root().to_path_buf())).collect::<Vec<_>>();
+41 -2
Переглянути файл
@@ -3,8 +3,8 @@
//! project's window through the askpass dialog (`IdeEvent::Askpass`, answered
//! with `ssh_askpass_answer`).
use ide_core::IdeEvent;
use ide_core::event::{AskpassKind, SharedSink};
use ide_core::{CancellationToken, IdeEvent};
use ide_svn::{Prompt, PromptHandler, Settings, SvnContext};
use parking_lot::Mutex;
use std::collections::HashMap;
@@ -54,12 +54,28 @@ struct WindowPrompts {
impl PromptHandler for WindowPrompts {
fn answer(&self, prompt: &Prompt) -> Option<String> {
self.answer_until(prompt, &CancellationToken::new())
}
/// The dialog closes when the command is cancelled (the Cancel of its progress), not only
/// when the user answers or after [`ANSWER_TIMEOUT`].
fn answer_until(&self, prompt: &Prompt, cancel: &CancellationToken) -> Option<String> {
let (text, kind) = describe(prompt);
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = mpsc::channel();
PENDING.lock().get_or_insert_default().insert(id, tx);
self.sink.emit(IdeEvent::Askpass { id, prompt: text, kind, remember: false });
let answer = rx.recv_timeout(ANSWER_TIMEOUT).ok().flatten();
let asked = std::time::Instant::now();
let answer = loop {
match rx.recv_timeout(Duration::from_millis(50)) {
Ok(answer) => break answer,
Err(mpsc::RecvTimeoutError::Disconnected) => break None,
Err(mpsc::RecvTimeoutError::Timeout) if cancel.is_cancelled() || asked.elapsed() >= ANSWER_TIMEOUT => {
break None;
}
Err(mpsc::RecvTimeoutError::Timeout) => {}
}
};
if let Some(pending) = PENDING.lock().as_mut() {
pending.remove(&id);
}
@@ -144,4 +160,27 @@ mod tests {
assert!(answer_prompt(id, Some("ann".into())));
assert_eq!(asked.join().unwrap().as_deref(), Some("ann"));
}
/// Review #2 P1-15: a cancelled command closes its prompt at once, not after ten minutes.
#[test]
fn a_cancelled_command_closes_its_prompt() {
let done: Arc<Mutex<Vec<u64>>> = Arc::default();
let seen = done.clone();
let sink: SharedSink = Arc::new(move |e: IdeEvent| {
if let IdeEvent::AskpassDone { id } = e {
seen.lock().push(id);
}
});
let handler = WindowPrompts { sink };
let cancel = CancellationToken::new();
let later = cancel.clone();
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(100));
later.cancel();
});
let started = std::time::Instant::now();
assert_eq!(handler.answer_until(&Prompt::Username { realm: String::new() }, &cancel), None);
assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed());
assert_eq!(done.lock().len(), 1, "the dialog is told to close");
}
}
+97
Переглянути файл
@@ -2,6 +2,7 @@
//! servers' `typescript.format.*` / `typescript.preferences.*` settings (`javascript.*` for
//! JavaScript and JSX). tsserver applies them to Reformat Code and to the code it writes:
//! quick fixes, auto-imports, refactorings and organize imports.
//! Editor › Inlay Hints › JavaScript and TypeScript types as their variable and field type hint preferences.
use ide_core::editor_settings::LanguageCodeStyle;
use ide_core::settings::Settings;
@@ -57,6 +58,27 @@ pub fn configure(cfg: &mut LanguageServerConfig, server_root: &Path, settings: &
cfg.settings = Some(merged);
}
/// The servers' inferred variable and field type hints, on while Editor › Inlay Hints shows types
/// and JavaScript and TypeScript types (both on by default, as in WebStorm). Sent either way, so a
/// change reaches a running server; the server's own settings win.
pub fn configure_inlay_hints(cfg: &mut LanguageServerConfig, settings: &Settings) {
let inlay = &settings.editor.inlay;
let on = inlay.types && inlay.js_ts_types;
// vtsls reads VS Code's names, typescript-language-server tsserver's.
let hints = match cfg.name.as_str() {
"vtsls" => json!({ "variableTypes": { "enabled": on }, "propertyDeclarationTypes": { "enabled": on } }),
"typescript-language-server" => {
json!({ "includeInlayVariableTypeHints": on, "includeInlayPropertyDeclarationTypeHints": on })
}
_ => return,
};
let mut merged = json!({ "typescript": { "inlayHints": hints }, "javascript": { "inlayHints": hints } });
if let Some(own) = cfg.settings.take() {
ide_sdk::apply::merge(&mut merged, own);
}
cfg.settings = Some(merged);
}
/// The `format` and `preferences` of one language's section.
fn section(
language: &str,
@@ -215,6 +237,81 @@ mod tests {
);
}
#[test]
fn variable_type_hints_follow_the_inlay_settings() {
let hints = |name: &str, types: bool, js_ts_types: bool, own: Option<Value>| {
let mut settings = Settings::default();
settings.editor.inlay.types = types;
settings.editor.inlay.js_ts_types = js_ts_types;
let mut cfg = server(name);
cfg.settings = own;
configure_inlay_hints(&mut cfg, &settings);
cfg.settings
};
let vtsls =
|on: bool| json!({ "variableTypes": { "enabled": on }, "propertyDeclarationTypes": { "enabled": on } });
// On by default, as in WebStorm.
assert!(Settings::default().editor.inlay.js_ts_types);
assert_eq!(
hints("vtsls", true, true, None),
Some(json!({ "typescript": { "inlayHints": vtsls(true) }, "javascript": { "inlayHints": vtsls(true) } }))
);
// Sent when off too, so that a running server turns them off.
assert_eq!(
hints("vtsls", true, false, None),
Some(json!({ "typescript": { "inlayHints": vtsls(false) }, "javascript": { "inlayHints": vtsls(false) } }))
);
// Type hints off as a whole: none asked for.
assert_eq!(hints("vtsls", false, true, None).unwrap()["typescript"]["inlayHints"], vtsls(false));
let tls = hints("typescript-language-server", true, true, None).unwrap();
assert_eq!(
tls["javascript"]["inlayHints"],
json!({ "includeInlayVariableTypeHints": true, "includeInlayPropertyDeclarationTypeHints": true })
);
// The server's own settings win, and keep their other keys.
let own = json!({ "typescript": { "inlayHints": { "variableTypes": { "enabled": true }, "x": 1 } } });
let s = hints("vtsls", true, false, Some(own)).unwrap();
assert_eq!(
s["typescript"]["inlayHints"],
json!({ "variableTypes": { "enabled": true }, "propertyDeclarationTypes": { "enabled": false }, "x": 1 })
);
assert_eq!(s["javascript"]["inlayHints"], vtsls(false));
// Other servers (Rust, Kotlin, ESLint…) keep their own defaults.
assert_eq!(hints("rust-analyzer", true, false, None), None);
assert_eq!(hints("eslint", true, false, None), None);
}
/// The bundled language definitions leave the switch's keys to it: a value there would win.
#[test]
fn bundled_settings_leave_type_hints_to_the_switch() {
let reg = ide_language::LanguageRegistry::load(None).unwrap();
for language in ["typescript", "javascript", "typescriptreact", "javascriptreact", "vue"] {
let lang = reg.get(&ide_core::LanguageId::new(language)).unwrap();
let vtsls = lang.language_servers.iter().find(|s| s.name == "vtsls").unwrap();
let options = serde_json::to_value(&vtsls.initialization_options).unwrap();
for section in ["typescript", "javascript"] {
assert_eq!(options[section]["inlayHints"]["enumMemberValues"]["enabled"], true, "{language}");
}
if language == "vue" {
continue;
}
let fallback = lang.language_servers.iter().find(|s| s.name == "typescript-language-server").unwrap();
for enabled in [true, false] {
let mut settings = Settings::default();
settings.editor.inlay.js_ts_types = enabled;
let mut cfg = fallback.clone();
configure_inlay_hints(&mut cfg, &settings);
let s = cfg.settings.unwrap();
for section in ["typescript", "javascript"] {
let hints = &s[section]["inlayHints"];
assert_eq!(hints["includeInlayVariableTypeHints"], enabled, "{language} / {section}");
assert_eq!(hints["includeInlayPropertyDeclarationTypeHints"], enabled, "{language} / {section}");
assert_eq!(hints["includeInlayEnumMemberValueHints"], true, "{language} / {section}");
}
}
}
}
#[test]
fn editorconfig_comes_first() {
let dir = tempfile::tempdir().unwrap();
+31 -2
Переглянути файл
@@ -142,6 +142,11 @@ async fn open(base: &Path, root: &Path) -> (Host, Arc<ide_host::Project>) {
/// The project's version-control roots, relative to `root` (`.` for itself), sorted.
async fn roots(host: &Host, project: &ide_host::Project, root: &Path) -> Vec<(VcsKind, String)> {
project.refresh_repositories();
listed(host, root).await
}
/// [`roots`] as the project has them now, without looking for them again.
async fn listed(host: &Host, root: &Path) -> Vec<(VcsKind, String)> {
let mut out: Vec<(VcsKind, String)> = vcs::vcs_roots(host, "main")
.await
.unwrap()
@@ -186,6 +191,25 @@ async fn externals_are_roots_of_their_own() {
assert_eq!(roots(&host, &project, &root).await, svn_roots(&[".", "ext-other", "ext-same"]));
}
/// Review #3 Medium-11: externals in folders the nested search skips (`vendor/`) or deeper than
/// it goes are roots too; their changes dropped out of the working copy's status.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn externals_in_skipped_or_deep_folders_are_roots() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("source");
std::fs::create_dir_all(root.join("vendor/a/b/c/d")).unwrap();
fx.svn(&root, &["add", "-q", "vendor"]);
fx.svn(&root, &["propset", "-q", "svn:externals", &fx.externals(), "vendor/a/b/c/d"]);
fx.svn(&root, &["commit", "-q", "-m", "externals"]);
fx.svn(&root, &["update", "-q"]);
assert!(root.join("vendor/a/b/c/d/ext-same/part.txt").exists());
let (host, project) = open(&fx.base, &root).await;
assert_eq!(
roots(&host, &project, &root).await,
svn_roots(&[".", "vendor/a/b/c/d/ext-other", "vendor/a/b/c/d/ext-same"])
);
}
/// A definition set and not committed, fetched by the IDE's Update Project: the externals the
/// update brings become roots. IntelliJ SvnExternalTest.testUncommittedExternalCopyIsDetected,
/// testUncommittedExternalCopyIsDetectedAnother.
@@ -201,7 +225,9 @@ async fn externals_an_update_brings_become_roots() {
let op = vcs::RemoteOp::UpdateProjectBranch { rebase: false };
vcs::vcs_remote(&host, "main", None, ide_core::RequestId::next(), op, channel, None).await.unwrap();
assert!(root.join("ext-same/part.txt").exists() && root.join("ext-other/inside.txt").exists());
assert_eq!(roots(&host, &project, &root).await, svn_roots(&[".", "ext-other", "ext-same"]));
// Found by the update itself (review #2: the roots were only looked for again by hand).
let _ = &project;
assert_eq!(listed(&host, &root).await, svn_roots(&[".", "ext-other", "ext-same"]));
}
/// A checkout made deep inside a working copy (`inner1/inner2/inner`), from this repository or
@@ -290,8 +316,11 @@ async fn a_root_switched_in_a_terminal_shows_its_new_line() {
let (host, project) = open(&fx.base, &root).await;
assert_eq!(vcs::vcs_branch_info(&host, "main", None).await.unwrap().head.as_deref(), Some("trunk"));
// A second later, as a person in a terminal: the working copy's database is then newer than
// what the IDE read (nothing is looked for again by hand).
std::thread::sleep(Duration::from_millis(1100));
fx.svn(&root, &["switch", "-q", &format!("{}/branches/b", fx.url)]);
project.refresh_repositories();
let _ = &project;
assert_eq!(vcs::vcs_branch_info(&host, "main", None).await.unwrap().head.as_deref(), Some("branches/b"));
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
assert_eq!(roots[0].head.as_deref(), Some("branches/b"));
+68 -1
Переглянути файл
@@ -1,4 +1,4 @@
//! Database and MCP calls through a real sandboxed API 1.4 component.
//! Database and MCP calls through a real sandboxed component.
mod common;
use ide_core::{CancellationToken, IdeEvent, event::McpUiRequest};
@@ -355,3 +355,70 @@ fn eventually(mut ready: impl FnMut() -> bool) -> bool {
}
false
}
#[tokio::test(flavor = "multi_thread")]
async fn schema_reads_user_tables_without_rows_or_credentials_and_enforces_grants() {
let f = Harness::with_timeout(Duration::from_secs(10));
let table =
serde_json::json!({"sourceId":"user-source","catalog":null,"schema":"main","table":"users"}).to_string();
assert!(f.run("table-schema", Some(&table)).is_err(), "untrusted projects are refused");
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let db = f.host.project("main").unwrap().db.clone();
db.save_sources(vec![ide_db::DataSource {
id: "user-source".into(),
name: "User-owned SQLite".into(),
driver: ide_db::DbDriver::Sqlite,
file: Some(f.root.join("db.sqlite").into()),
..Default::default()
}])
.await
.unwrap();
assert!(f.run("table-schema", Some(&table)).is_err(), "inspection never connects implicitly");
assert!(!db.is_connected("user-source"));
let cancel = CancellationToken::new();
for sql in [
"CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT NOT NULL DEFAULT 'guest', manager_id INTEGER REFERENCES users(id))",
"CREATE INDEX users_name ON users(name)",
"INSERT INTO users(name) VALUES ('private-row-value')",
] {
db.execute("user-source", sql, 100, &cancel).await.unwrap();
}
assert!(!f.host.project("second").unwrap().db.is_connected("user-source"));
assert!(
f.plugins
.run_command(
ID,
"table-schema",
Some(&table),
Invocation { client: Some("second".into()), ..f.invocation() }
)
.is_err(),
"a disconnected window cannot borrow another window's connection"
);
let response = f.run("table-schema", Some(&table)).unwrap().unwrap();
let schema: serde_json::Value = serde_json::from_str(&response).unwrap();
assert_eq!(schema["columns"][0]["name"], "id");
assert_eq!(schema["columns"][0]["primaryKey"], true);
assert_eq!(schema["columns"][1]["nullable"], false);
assert_eq!(schema["columns"][1]["defaultValue"], "'guest'");
assert!(schema["indexes"].as_array().unwrap().iter().any(|i| i["name"] == "users_name"));
assert!(schema["foreignKeys"].as_array().unwrap().iter().any(|k| k["referencedTable"] == "users"));
let menu_argument = serde_json::json!({ "tables": [{
"sourceId": "user-source", "catalog": null, "schema": "main", "table": "users",
"kind": "table", "driver": "sqlite",
}] })
.to_string();
assert_eq!(f.run("table-schema", Some(&menu_argument)).unwrap().unwrap(), response);
assert!(!response.contains("private-row-value"));
assert!(schema.get("password").is_none() && schema.get("url").is_none() && schema.get("host").is_none());
f.plugins.set_capability(ID, "database.schema", false).unwrap();
let denied = f.run("table-schema", Some(&table)).unwrap_err();
assert!(denied.message.contains("database.schema"));
assert!(db.is_connected("user-source"), "revoking inspection leaves user connections alone");
f.plugins.set_capability(ID, "database.schema", true).unwrap();
f.host.set_project_trust(&f.root, false, false).await.unwrap();
assert!(f.run("table-schema", Some(&table)).is_err());
db.disconnect("user-source").await;
assert!(db.connected_table_details("user-source", None, "main", "users").await.is_err());
assert!(!db.is_connected("user-source"), "schema reads cannot reconnect a disconnected source");
}
+257
Переглянути файл
@@ -186,6 +186,10 @@ async fn a_working_copy_through_the_shared_commands() {
let names: Vec<(&str, bool)> = branches.iter().map(|b| (b.name.as_str(), b.current)).collect();
assert_eq!(names, [("trunk", false), ("branches/feature", true)]);
vcs::vcs_checkout(&host, "main", None, "trunk".into(), false, None, None).await.unwrap();
// Review #3 Medium-9: a tag is made on the server; the working copy stays on its line.
vcs::vcs_checkout(&host, "main", None, "tags/v1".into(), true, None, None).await.unwrap();
assert_eq!(vcs::vcs_branch_info(&host, "main", None).await.unwrap().head.as_deref(), Some("trunk"));
assert!(fx.svn(&fx.base, &["list", &format!("{}/tags", fx.url)]).contains("v1/"));
// Update Project with a conflict, resolved in the merge editor (which stages the result).
let other = fx.checkout("other");
@@ -213,6 +217,10 @@ async fn a_working_copy_through_the_shared_commands() {
svn::svn_unlock(&host, "main", vec![a.clone()], false).await.unwrap();
let info = svn::svn_repository_info(&host, "main", None).await.unwrap();
assert!(info.url.ends_with("/repo/trunk"), "{}", info.url);
// What the Working Copies tab shows (issue #7433).
assert!(info.root_url.ends_with("/repo") && !info.uuid.is_empty(), "{} {}", info.root_url, info.uuid);
assert_eq!(info.depth, "infinity");
assert!(info.format.is_none() || info.format.as_deref().is_some_and(|f| f.starts_with("1.")), "{:?}", info.format);
svn::svn_cleanup(&host, "main", None).await.unwrap();
assert!(svn::svn_version(&host, "main", String::new()).await.unwrap().version.is_some());
let fresh = fx.base.join("fresh");
@@ -221,6 +229,23 @@ async fn a_working_copy_through_the_shared_commands() {
let _ = CancellationToken::new();
}
/// Review #2 P1-11: the image diff of a working copy's file reads it at the revision through
/// Subversion (the command read Git only).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn an_image_at_a_revision() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
let (host, _project) = open(&fx.base, &root).await;
let png = root.join("pic.png");
std::fs::write(&png, b"\x89PNG first").unwrap();
vcs::vcs_stage(&host, "main", vec![png.clone()]).await.unwrap();
let rev =
vcs::vcs_commit(&host, "main", None, "pic".into(), commit_options(std::slice::from_ref(&png))).await.unwrap();
std::fs::write(&png, b"\x89PNG second").unwrap();
let image = vcs::vcs_image_at(&host, "main", png.clone(), rev).await.unwrap().unwrap();
assert_eq!(image, format!("data:image/png;base64,{}", ide_vfs::base64(b"\x89PNG first")));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn svn_changelists_through_the_backend_changelist_commands() {
let Some(fx) = fixture() else { return };
@@ -555,6 +580,51 @@ async fn a_working_copy_inside_a_git_project() {
assert_eq!(project.backends()[0].root(), root.join("parts"));
}
/// Review #3 Medium-10: a Git project in an unversioned folder of a checkout is the Git
/// repository's alone; the whole checkout was a root of it too, its files the project's changes.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_git_project_in_an_unversioned_folder_of_a_checkout() {
let Some(fx) = fixture() else { return };
let wc = fx.checkout("wc");
std::fs::write(wc.join("main.txt"), "m\n").unwrap();
fx.svn(&wc, &["add", "-q", "main.txt"]);
let root = wc.join("mygit");
std::fs::create_dir(&root).unwrap();
git_init(&root);
let host = Host::new(common::host_config(&fx.base)).with_subversion(false);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("the Git repository", || !project.repos().is_empty()).await;
project.refresh_backends();
assert!(
project.backends().is_empty(),
"{:?}",
project.backends().iter().map(|b| b.root().to_owned()).collect::<Vec<_>>()
);
let status = vcs::vcs_status(&host, "main").await.unwrap();
assert!(!status.iter().any(|f| f.path.0.ends_with("main.txt")), "{status:?}");
}
/// Review of #7266: a refresh of a folder with a checkout of its own below it refreshes that
/// checkout's rows too (they dropped out: no path was its own).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_folder_refresh_includes_a_nested_working_copy() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
std::fs::create_dir(root.join("sub")).unwrap();
std::fs::write(root.join("sub/s.txt"), "s\n").unwrap();
fx.svn(&root, &["add", "-q", "sub"]);
fx.svn(&root, &["commit", "-q", "-m", "a folder"]);
let inner = root.join("sub/inner");
fx.svn(&fx.base, &["checkout", "-q", &format!("{}/trunk", fx.url), inner.to_str().unwrap()]);
fx.svn(&root, &["propset", "-q", "svn:ignore", "inner", "sub"]);
std::fs::write(inner.join("sub/s.txt"), "s\nchanged\n").unwrap();
let (host, project) = open(&fx.base, &root).await;
until("both working copies", || project.backends().len() == 2).await;
let rows = vcs::vcs_status_paths(&host, "main", vec![root.join("sub")]).await.unwrap();
assert!(rows.iter().any(|f| f.path.0 == inner.join("sub/s.txt")), "{rows:?}");
}
/// The project tree's Delete schedules a file for deletion; its Undo brings the file back and
/// takes the deletion back, keeping the restored content. (Review A4.)
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -597,6 +667,22 @@ async fn undo_of_a_delete_takes_the_deletion_back() {
ide_host::ops::fs::fs_undo_delete(&host, "main", undo).await.unwrap();
assert_eq!(std::fs::read_to_string(root.join("docs/b.txt")).unwrap(), "b\n");
assert_eq!(fx.svn(&root, &["status", "docs"]), "", "the folder is as committed");
// Review #3 High-4: a file just added and one just moved keep their schedule; the Undo used to
// leave them unversioned and the move's source deleted (a commit would delete it on the server).
let added = root.join("added.txt");
std::fs::write(&added, "new\n").unwrap();
fx.svn(&root, &["add", "-q", "added.txt"]);
fx.svn(&root, &["move", "-q", "docs/a.txt", "moved.txt"]);
let before = kinds(&vcs::vcs_status(&host, "main").await.unwrap());
for path in [added.clone(), root.join("moved.txt")] {
let undo = delete(&path);
ide_host::ops::fs::fs_undo_delete(&host, "main", undo).await.unwrap();
assert!(path.is_file());
}
assert_eq!(kinds(&vcs::vcs_status(&host, "main").await.unwrap()), before);
let status = fx.svn(&root, &["status"]);
assert!(status.contains("A added.txt") && status.contains("A + moved.txt"), "{status}");
}
/// In a project with a Git repository and a working copy, a working copy that cannot report
@@ -645,13 +731,31 @@ async fn a_working_copy_that_cannot_report_is_told() {
until("the working copy", || !project.backends().is_empty()).await;
until("the Git repository", || !project.repos().is_empty()).await;
// A change of the working copy, read while it still answers.
std::fs::write(root.join("w.txt"), "w\n").unwrap();
std::fs::write(root.join("gone.txt"), "g\n").unwrap();
let status = vcs::vcs_status(&host, "main").await.unwrap();
assert!(status.iter().any(|f| f.path.0.ends_with("w.txt")), "{status:?}");
// A row a refresh of its path then drops (the file went) does not come back below.
std::fs::remove_file(root.join("gone.txt")).unwrap();
let scoped = vcs::vcs_status_paths(&host, "main", vec![root.join("gone.txt")]).await.unwrap();
assert!(scoped.is_empty(), "{scoped:?}");
std::fs::write(&broken, "").unwrap();
for _ in 0..3 {
let status = vcs::vcs_status(&host, "main").await.unwrap();
assert!(status.iter().any(|f| f.path.0.ends_with("tool/g.txt")), "{status:?}");
// Review of #7266: its rows stay while it cannot answer (they vanished).
assert!(status.iter().any(|f| f.path.0.ends_with("w.txt")), "{status:?}");
assert!(!status.iter().any(|f| f.path.0.ends_with("gone.txt")), "{status:?}");
}
let told = told.lock().clone();
assert_eq!(told.iter().filter(|t| t.starts_with("Changes of ")).count(), 1, "{told:?}");
// Review #2 P1-17: a refresh of the working copy's own paths fails (its rows stay), one of
// the Git repository's paths alone does not.
let err = vcs::vcs_status_paths(&host, "main", vec![root.join("a.txt")]).await.unwrap_err();
assert!(err.message.contains("E155036"), "{err:?}");
let git = vcs::vcs_status_paths(&host, "main", vec![root.join("tool/g.txt")]).await.unwrap();
assert!(git.iter().any(|f| f.path.0.ends_with("tool/g.txt")), "{git:?}");
}
/// Get from Version Control › Subversion reports svn's progress line by line, and its Cancel
@@ -699,7 +803,9 @@ async fn a_checkout_reports_progress_and_can_be_cancelled() {
.spawn()
.unwrap(),
);
let started = std::time::Instant::now();
while std::net::TcpStream::connect(("127.0.0.1", port)).is_err() {
assert!(started.elapsed() < Duration::from_secs(10), "svnserve did not start");
std::thread::sleep(Duration::from_millis(50));
}
let pid = server.0.id().to_string();
@@ -791,3 +897,154 @@ async fn a_working_copy_through_the_server_protocol() {
let summaries: Vec<&str> = log.as_array().unwrap().iter().filter_map(|c| c["summary"].as_str()).collect();
assert_eq!(summaries, ["Add notes", "layout"]);
}
/// Review #2 asked: Lock and Unlock of files in two working copies (a checkout nested in the
/// project's), run in the first file's working copy, lock both (svn takes targets of several
/// working copies in one command).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn lock_and_unlock_across_working_copies() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
std::fs::write(root.join("a.txt"), "a\n").unwrap();
std::fs::write(root.join("b.txt"), "b\n").unwrap();
fx.svn(&root, &["add", "-q", "a.txt", "b.txt"]);
fx.svn(&root, &["commit", "-q", "-m", "a and b"]);
let nested = root.join("nested");
fx.svn(&fx.base, &["checkout", "-q", &format!("{}/trunk", fx.url), nested.to_str().unwrap()]);
fx.svn(&root, &["propset", "-q", "svn:ignore", "nested", "."]);
let (host, project) = open(&fx.base, &root).await;
until("both working copies", || project.backends().len() == 2).await;
let (a, b) = (root.join("a.txt"), nested.join("b.txt"));
svn::svn_lock(&host, "main", vec![a.clone(), b.clone()], "both".into(), false).await.unwrap();
let locked = |wc: &Path, name: &str| fx.svn(wc, &["status", name]);
assert!(locked(&root, "a.txt").starts_with(" K"), "{}", locked(&root, "a.txt"));
assert!(locked(&nested, "b.txt").starts_with(" K"), "{}", locked(&nested, "b.txt"));
svn::svn_unlock(&host, "main", vec![a, b], false).await.unwrap();
assert_eq!((locked(&root, "a.txt"), locked(&nested, "b.txt")), (String::new(), String::new()));
}
/// Review #3 Medium-6: a rename or move in the project tree (`refactor_move_files`) and its Undo
/// reach the working copy, as `fs_rename` does: svn records the move, so history follows the file
/// (it saw a missing file and an unversioned one).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_project_tree_move_and_its_undo_reach_the_working_copy() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
std::fs::write(root.join("a.txt"), "a\n").unwrap();
fx.svn(&root, &["add", "-q", "a.txt"]);
fx.svn(&root, &["commit", "-q", "-m", "a"]);
let (host, _project) = open(&fx.base, &root).await;
let moves = vec![ide_core::FileMove { from: root.join("a.txt").into(), to: root.join("b.txt").into() }];
let id = ide_host::ops::refactor::refactor_move_files(&host, "main", moves, Default::default(), "Rename".into())
.await
.unwrap();
assert_eq!(kinds(&vcs::vcs_status(&host, "main").await.unwrap()), [("b.txt".into(), ChangeKind::Renamed)]);
ide_host::ops::refactor::refactor_undo_file_move(&host, "main", id).await.unwrap();
assert!(root.join("a.txt").is_file());
assert_eq!(fx.svn(&root, &["status"]), "", "back as committed");
}
/// A working copy with `.openidea` (where the shelf is kept) ignored, and committed files.
fn shelf_fixture(fx: &Fixture, files: &[(&str, &[u8])]) -> PathBuf {
let root = fx.checkout("wc");
fx.svn(&root, &["propset", "-q", "svn:ignore", ".openidea", "."]);
for (name, bytes) in files {
std::fs::write(root.join(name), bytes).unwrap();
fx.svn(&root, &["add", "-q", name]);
}
fx.svn(&root, &["commit", "-q", "-m", "base"]);
root
}
/// Issue #7433: Shelve Changes in a Subversion working copy saves text, binary and property
/// changes, added and deleted files, and rolls them back; Unshelve puts them back.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shelve_and_unshelve_in_a_working_copy() {
let Some(fx) = fixture() else { return };
let files: &[(&str, &[u8])] =
&[("a.txt", b"one\n"), ("gone.txt", b"bye\n"), ("pic.bin", b"\0\x01\x02"), ("prop.txt", b"p\n")];
let root = shelf_fixture(&fx, files);
let (host, _project) = open(&fx.base, &root).await;
let path = |name: &str| root.join(name);
std::fs::write(path("a.txt"), "one\ntwo\n").unwrap();
std::fs::write(path("new.txt"), "new\n").unwrap();
fx.svn(&root, &["add", "-q", "new.txt"]);
fx.svn(&root, &["rm", "-q", "gone.txt"]);
std::fs::write(path("pic.bin"), b"\0\x03\x04\x05").unwrap();
fx.svn(&root, &["propset", "-q", "review", "yes", "prop.txt"]);
let changed = fx.svn(&root, &["status"]);
// An unversioned file is not in the patch: shelving it is refused and nothing is reverted.
std::fs::write(path("loose.txt"), "loose\n").unwrap();
let refused = vcs::vcs_shelve(&host, "main", "loose".into(), vec![path("a.txt"), path("loose.txt")]).await;
assert!(refused.unwrap_err().message.contains("loose.txt"));
assert_eq!(std::fs::read_to_string(path("a.txt")).unwrap(), "one\ntwo\n");
std::fs::remove_file(path("loose.txt")).unwrap();
let selected: Vec<PathBuf> = ["a.txt", "new.txt", "gone.txt", "pic.bin", "prop.txt"].map(path).to_vec();
let entry = vcs::vcs_shelve(&host, "main", "work".into(), selected).await.unwrap();
assert_eq!(fx.svn(&root, &["status"]), "", "rolled back");
assert!(!path("new.txt").exists(), "an added file is gone from disk");
assert_eq!(std::fs::read_to_string(path("a.txt")).unwrap(), "one\n");
assert_eq!(std::fs::read_to_string(path("gone.txt")).unwrap(), "bye\n");
assert_eq!(std::fs::read(path("pic.bin")).unwrap(), b"\0\x01\x02");
let shelves = vcs::vcs_shelves(&host, "main").await.unwrap();
assert_eq!(shelves.len(), 1);
assert_eq!(shelves[0].repo.as_deref(), Some(root.as_path()));
let mut names: Vec<_> = shelves[0].files.iter().map(|f| (f.path.as_str(), f.kind)).collect();
names.sort_by_key(|(path, _)| *path);
assert_eq!(
names,
[
("a.txt", ChangeKind::Modified),
("gone.txt", ChangeKind::Deleted),
("new.txt", ChangeKind::Added),
("pic.bin", ChangeKind::Modified),
("prop.txt", ChangeKind::Modified),
]
);
// The shelved diff: the base, and the base with the shelved hunks applied.
let diff = vcs::vcs_shelf_diff(&host, "main", entry.id.clone()).await.unwrap();
let sides = |name: &str| {
let file = diff.iter().find(|f| f.path == name).unwrap();
(file.before.clone(), file.after.clone())
};
assert_eq!(sides("a.txt"), (Some("one\n".into()), Some("one\ntwo\n".into())));
assert_eq!(sides("new.txt"), (Some(String::new()), Some("new\n".into())));
assert_eq!(sides("gone.txt"), (Some("bye\n".into()), Some(String::new())));
assert_eq!(sides("pic.bin"), (None, None));
let outcome = vcs::vcs_unshelve(&host, "main", entry.id, true, None).await.unwrap();
assert!(outcome.conflicts.is_empty(), "{outcome:?}");
let mut applied = outcome.applied.clone();
applied.sort();
assert_eq!(applied, ["a.txt", "gone.txt", "new.txt", "pic.bin", "prop.txt"]);
assert_eq!(fx.svn(&root, &["status"]), changed, "every change is back, the added file scheduled again");
assert_eq!(std::fs::read_to_string(path("a.txt")).unwrap(), "one\ntwo\n");
assert_eq!(std::fs::read(path("pic.bin")).unwrap(), b"\0\x03\x04\x05");
assert_eq!(fx.svn(&root, &["propget", "review", "prop.txt"]).trim(), "yes");
assert!(vcs::vcs_shelves(&host, "main").await.unwrap().is_empty(), "removed from the shelf");
}
/// Unshelving onto a conflicting local edit reports the file and keeps it on the shelf.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn unshelve_onto_a_conflicting_edit() {
let Some(fx) = fixture() else { return };
let root = shelf_fixture(&fx, &[("a.txt", b"one\n"), ("b.txt", b"b\n")]);
let (host, _project) = open(&fx.base, &root).await;
let (a, b) = (root.join("a.txt"), root.join("b.txt"));
std::fs::write(&a, "one\ntwo\n").unwrap();
std::fs::write(&b, "b\nmore\n").unwrap();
let entry = vcs::vcs_shelve(&host, "main", "work".into(), vec![a.clone(), b.clone()]).await.unwrap();
std::fs::write(&a, "mine\n").unwrap();
let outcome = vcs::vcs_unshelve(&host, "main", entry.id.clone(), true, None).await.unwrap();
assert_eq!((outcome.applied, outcome.conflicts), (vec!["b.txt".to_owned()], vec!["a.txt".to_owned()]));
assert_eq!(std::fs::read_to_string(&a).unwrap(), "mine\n", "the local edit is kept");
assert_eq!(std::fs::read_to_string(&b).unwrap(), "b\nmore\n");
let shelves = vcs::vcs_shelves(&host, "main").await.unwrap();
assert_eq!(shelves.len(), 1, "a conflict keeps the shelved changes");
assert_eq!(shelves[0].files.len(), 2);
}
+2 -3
Переглянути файл
@@ -199,9 +199,8 @@ async fn malicious_project_stays_editable_then_starts_in_place_after_trust() {
)
};
assert!(sync().await.is_err(), "restricted build marker: {}", root.join("build.marker").exists());
assert!(
ops::sdk::sdk_locate_tools(&host, "missing-window", vec!["server".into()], Some(root.clone())).await.is_err()
);
// SDK lookups run from the Welcome screen too (#7389), but a restricted project still refuses them.
assert!(ops::sdk::sdk_locate_tools(&host, "main", vec!["server".into()], Some(root.clone())).await.is_err());
assert!(host.authorize("main", TrustClass::Trusted).is_err());
tokio::time::sleep(Duration::from_millis(200)).await;
for marker in ["hook.marker", "lsp.marker", "build.marker"] {
+5 -3
Переглянути файл
@@ -12,8 +12,10 @@ use std::pin::Pin;
use std::process::{Command, Stdio};
/// Allowed in Restricted Mode and not swept: none of them starts git for the project.
const NOT_THE_PROJECT_REPOSITORY: [&str; 8] = [
const NOT_THE_PROJECT_REPOSITORY: [&str; 10] = [
"vcs_clone", // clones a URL the user gives into a new folder
"svn_checkout", // checks a URL the user gives out into a new folder
"svn_version", // the version of svn on PATH, run in a temporary folder
"vcs_diff_hunks", // compares two texts
"vcs_detected_git", // looks for the git executable
"vcs_shelves", // the shelf and the changelists are files of the IDE
@@ -372,13 +374,13 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
call!("vcs_init", "", vcs::vcs_init(host, w, project.root.clone())),
];
// The sweep covers every `vcs_*` command declared `trust = always`: a newly allowed one fails
// The sweep covers every `vcs_*` and `svn_*` command declared `trust = always`: a newly allowed one fails
// here until it is swept or listed as not touching the project's repository.
let dispatcher = ide_host::rpc::Dispatcher::standard();
let allowed: BTreeSet<&str> = dispatcher
.commands()
.into_iter()
.filter(|c| c.starts_with("vcs_") && dispatcher.trust(c) == Some(TrustClass::Always))
.filter(|c| (c.starts_with("vcs_") || c.starts_with("svn_")) && dispatcher.trust(c) == Some(TrustClass::Always))
.collect();
let swept: BTreeSet<&str> = calls.iter().map(|(command, _, _)| *command).collect();
let known: BTreeSet<&str> = swept.iter().copied().chain(NOT_THE_PROJECT_REPOSITORY).collect();
+3 -2
Переглянути файл
@@ -430,10 +430,11 @@ async fn git_inside_a_working_copy_keeps_its_files_and_its_changes() {
vcs::vcs_backend_changelist_create(&host, "main", Some(lib.clone()), "x".into(), String::new()).await.is_err()
);
// A server that cannot be reached leaves the Git changes visible.
// A server that cannot be reached leaves the Git changes visible, and the working copy's
// last rows stay (they vanished from the Changes view).
fake.unreachable.store(true, Ordering::Release);
let status = vcs::vcs_status(&host, "main").await.unwrap();
assert_eq!(paths(&status), BTreeSet::from([untracked.clone()]));
assert_eq!(paths(&status), BTreeSet::from([outside.clone(), untracked.clone()]));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+79
Переглянути файл
@@ -0,0 +1,79 @@
//! #7333: Delete of a file that was only added to Git also drops it from the index, as IDEA
//! does, so it does not linger as `AD`; Undo brings the content back without touching the index.
mod common;
use ide_host::{Host, Project};
use std::{
path::{Path, PathBuf},
process::Command,
sync::Arc,
time::Duration,
};
fn git(root: &Path, args: &[&str]) -> String {
let out = Command::new("git").current_dir(root).args(args).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).trim_end().to_owned()
}
fn repo() -> (tempfile::TempDir, PathBuf, PathBuf) {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir(&root).unwrap();
git(&root, &["init", "-b", "main"]);
git(&root, &["config", "user.name", "Test"]);
git(&root, &["config", "user.email", "[email protected]"]);
git(&root, &["config", "commit.gpgsign", "false"]);
(temp, base, root)
}
async fn open(base: &Path, root: &Path) -> (Host, Arc<Project>) {
let host = Host::new(common::host_config(base));
host.trust.decide(root, true, false).unwrap();
let project = host.open_project("main", root).unwrap();
for _ in 0..500 {
if !project.repos().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
(host, project)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn deleting_an_added_file_drops_it_from_the_index_and_undo_keeps_the_index() {
let (_temp, base, root) = repo();
std::fs::write(root.join("staged.txt"), "base\n").unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-qm", "base"]);
std::fs::create_dir(root.join("dir")).unwrap();
std::fs::write(root.join("dir/new file.txt"), "new\n").unwrap();
std::fs::write(root.join("staged.txt"), "staged\n").unwrap();
git(&root, &["add", "."]);
let (host, project) = open(&base, &root).await;
// What Delete does (`delete_recorded`: the same paths, history, removal and backend hook),
// without the system Trash `fs_delete_with_undo` moves things to.
let delete = |path: &Path| {
let paths = ide_workspace::file_ops::deletion_paths(path).unwrap();
let undo = project.history.capture_deletion_undo(&paths, 1 << 20);
if path.is_dir() {
std::fs::remove_dir_all(path).unwrap()
} else {
std::fs::remove_file(path).unwrap()
}
project.with_backend_of(path, |b| b.files_deleted(&paths)).unwrap();
undo
};
let undo_dir = delete(&root.join("dir"));
let undo_staged = delete(&root.join("staged.txt"));
assert_eq!(git(&root, &["status", "--porcelain"]), "MD staged.txt");
ide_host::ops::fs::fs_undo_delete(&host, "main", undo_dir).await.unwrap();
ide_host::ops::fs::fs_undo_delete(&host, "main", undo_staged).await.unwrap();
assert_eq!(std::fs::read_to_string(root.join("dir/new file.txt")).unwrap(), "new\n");
// The staged edit stays staged; the added file comes back unversioned.
assert_eq!(git(&root, &["status", "--porcelain", "-uall"]), "M staged.txt\n?? \"dir/new file.txt\"");
}
+55 -16
Переглянути файл
@@ -46,6 +46,20 @@ const SNAPSHOT_DELAY: Duration = Duration::from_millis(50);
const SNAPSHOT_EVERY: Duration = Duration::from_secs(10);
#[cfg(test)]
const SNAPSHOT_EVERY: Duration = Duration::ZERO;
/// A refresh waits this many times as long as the last one took, up to [`SNAPSHOT_EVERY_MAX`]: in
/// a project of 160 000 files a write takes seconds and holds the disk, and a build writing into
/// it would otherwise have it rewritten every few seconds for minutes (#7363).
const SNAPSHOT_COST_FACTOR: u32 = 30;
const SNAPSHOT_EVERY_MAX: Duration = Duration::from_secs(300);
/// The shortest gap after a snapshot write that took `cost` (none in tests, as [`SNAPSHOT_EVERY`]).
fn snapshot_gap(cost: Duration) -> Duration {
if cfg!(test) { SNAPSHOT_EVERY } else { gap_after(cost, SNAPSHOT_EVERY) }
}
fn gap_after(cost: Duration, every: Duration) -> Duration {
every.max(cost.saturating_mul(SNAPSHOT_COST_FACTOR).min(SNAPSHOT_EVERY_MAX))
}
/// A subtree scan with fewer files to parse runs without showing "Indexing" (see `scan`).
const QUIET_SCAN_FILES: usize = 200;
pub(crate) const MAX_RECENT: usize = 50;
@@ -87,8 +101,9 @@ pub(crate) struct Shared {
idle: Condvar,
/// Coalesced post-update snapshot refresh.
snapshot_due: Mutex<Option<Instant>>,
/// When the snapshot was last refreshed (see [`SNAPSHOT_EVERY`]).
snapshot_saved: Mutex<Option<Instant>>,
/// When the snapshot was last refreshed, and how long the next one waits after it
/// (see [`snapshot_gap`]).
snapshot_saved: Mutex<Option<(Instant, Duration)>>,
/// Directories whose watcher events still need reconciliation before a
/// refreshed snapshot can be trusted.
pending_dirs: Mutex<HashSet<PathBuf>>,
@@ -683,18 +698,19 @@ impl Shared {
let durable = durable_started.elapsed();
let update_elapsed = update_started.elapsed();
let snapshot_started = Instant::now();
let mut deferred_snapshot = false;
if let Some(store) = &self.store {
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect();
// process() may already have applied the change and deleted the snapshot;
// a follow-up reconcile scan can have scheduled=0 and still need to write it.
// A full scan writes it at once; a subtree scan within the gap after the last
// write leaves it to the scheduled refresh.
if index_changed || !store.snapshot_exists() {
let d = self.data.read();
let snapshot_started = Instant::now();
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
tracing::warn!("index snapshot: {e}");
if dirs.is_none() || self.snapshot_may_refresh() {
self.write_snapshot(store, &filter, guard);
} else {
deferred_snapshot = true;
}
tracing::info!("index snapshot: written in {:?}", snapshot_started.elapsed());
*self.snapshot_saved.lock() = Some(Instant::now());
}
if let Err(e) = store.save_recent_file(&recent) {
tracing::warn!("index recent snapshot: {e}");
@@ -702,6 +718,9 @@ impl Shared {
}
let snapshot_elapsed = snapshot_started.elapsed();
*self.snapshot_due.lock() = None;
if deferred_snapshot {
self.schedule_snapshot();
}
if let Some(task) = task {
self.indexing.store(false, Ordering::SeqCst);
self.sink.emit(IdeEvent::Task {
@@ -856,11 +875,27 @@ impl Shared {
}
let mut due = self.snapshot_due.lock();
if due.is_none() {
let soonest = self.snapshot_saved.lock().map(|saved| saved + SNAPSHOT_EVERY);
let soonest = self.snapshot_saved.lock().map(|(saved, gap)| saved + gap);
*due = Some((Instant::now() + SNAPSHOT_DELAY).max(soonest.unwrap_or(Instant::now())));
}
}
/// Whether the gap after the last snapshot write has passed.
fn snapshot_may_refresh(&self) -> bool {
self.snapshot_saved.lock().is_none_or(|(saved, gap)| saved.elapsed() >= gap)
}
fn write_snapshot(&self, store: &Store, filter: &PathFilter, guard: SystemTime) {
let d = self.data.read();
let started = Instant::now();
if let Err(e) = store.save_snapshot(&d, filter, guard) {
tracing::warn!("index snapshot: {e}");
}
let cost = started.elapsed();
tracing::info!("index snapshot: written in {cost:?}");
*self.snapshot_saved.lock() = Some((Instant::now(), snapshot_gap(cost)));
}
/// Reconciles the folders the watcher reported since the last snapshot, then refreshes it.
/// A folder the index already has files below is listed one level deep: its own files, plus
/// any subfolder that appeared (walked whole) or is gone (its files dropped). A folder it
@@ -920,15 +955,9 @@ impl Shared {
return;
}
if let Some(store) = &self.store {
let filter = self.filter();
let guard = SystemTime::now();
let d = self.data.read();
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
tracing::warn!("index snapshot: {e}");
}
self.write_snapshot(store, &self.filter(), SystemTime::now());
}
*self.snapshot_due.lock() = None;
*self.snapshot_saved.lock() = Some(Instant::now());
}
fn persist(&self, puts: &[(String, FileRecord)], deletes: &[String], durable: bool) {
@@ -1704,6 +1733,16 @@ mod metric_tests {
#[cfg(test)]
mod tests {
#[test]
fn a_costly_snapshot_waits_longer_before_the_next() {
use super::{SNAPSHOT_EVERY_MAX, gap_after};
use std::time::Duration;
let every = Duration::from_secs(10);
assert_eq!(gap_after(Duration::from_millis(120), every), every);
assert_eq!(gap_after(Duration::from_secs(4), every), Duration::from_secs(120));
assert_eq!(gap_after(Duration::from_secs(11), every), SNAPSHOT_EVERY_MAX);
}
use crate::data::safe_rel;
#[test]
+2 -2
Переглянути файл
@@ -25,8 +25,8 @@ pub use syntax::{
CSS_CLASS, CSS_ID, CSS_VARIABLE, ClassBases, ConfigurationKey, ExternalFold, ExternalSymbol, ExternalSyntax,
ExternalToken, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, SpellingKind,
SpellingRegion, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError,
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_kinds, merge_visibility,
set_external_syntax, shift_pos, shift_range,
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_impl_traits, merge_kinds,
merge_visibility, set_external_syntax, shift_pos, shift_range,
};
pub use syntax::{
MethodBody, PhpAlignment, PytestFixture, PytestFixtureSlot, PytestFixtureUse, PytestFixtureUseKind, PytestImport,
+25
Переглянути файл
@@ -80,6 +80,7 @@ const BUILTIN: &[(&str, &str)] = &[
("proto", include_str!("../../../languages/proto.toml")),
("python", include_str!("../../../languages/python.toml")),
("r", include_str!("../../../languages/r.toml")),
("razor", include_str!("../../../languages/razor.toml")),
("restructuredtext", include_str!("../../../languages/restructuredtext.toml")),
("ruby", include_str!("../../../languages/ruby.toml")),
("rust", include_str!("../../../languages/rust.toml")),
@@ -654,6 +655,7 @@ mod tests {
"Thymeleaf",
"ERB",
"JSP",
"Razor",
"FreeMarker",
"Astro",
"GoMod",
@@ -692,6 +694,27 @@ mod tests {
assert_eq!(rust.language_servers[0].name, "rust-analyzer");
}
#[test]
fn razor_shares_the_csharp_roslyn_server() {
let reg = reg();
let razor = reg.get(&LanguageId::new("razor")).unwrap();
assert_eq!(razor.ui_mode.as_deref(), Some("Razor"));
assert_eq!(razor.block_comment, Some(("@*".to_owned(), "*@".to_owned())));
assert!(razor.debugger.is_some(), "breakpoints go into views");
// One instance per project serves both: the server keys instances by name and root,
// and the first file opened decides its configuration.
let csharp = reg.get(&LanguageId::new("csharp")).unwrap();
let roslyn = |cfg: &crate::LanguageConfig| {
cfg.language_servers.iter().find(|s| s.name == "roslyn-language-server").cloned().unwrap()
};
let (a, b) = (roslyn(&razor), roslyn(&csharp));
assert_eq!(
(&a.command, &a.args, &a.root_markers, &a.settings),
(&b.command, &b.args, &b.root_markers, &b.settings)
);
assert!(!razor.language_servers.iter().any(|s| s.name == "csharp-ls"), "csharp-ls has no Razor");
}
#[test]
fn rainbow_bracket_nodes_reach_the_ui() {
let reg = reg();
@@ -1295,6 +1318,8 @@ mod tests {
("x.cc", "cpp"),
("blink.ino", "arduino"),
("P.cs", "csharp"),
("Views/Home/Index.cshtml", "razor"),
("Components/Pages/Counter.razor", "razor"),
("V.swift", "swift"),
("AppDelegate.m", "objective-c"),
("App.entitlements", "xml"),
+2
Переглянути файл
@@ -125,6 +125,8 @@ pub(crate) fn outline(lang: &LanguageId, text: &str) -> Option<Vec<OutlineItem>>
selection_range: lines.range(name_start, name_end),
children: Vec::new(),
visibility: None,
implements: None,
self_type: None,
}));
parents.push(s.parent.map(|p| p as usize).filter(|&p| p < i));
}
+1 -1
Переглянути файл
@@ -34,7 +34,7 @@ use ide_core::{LanguageId, OutlineItem, Pos, Range};
pub use inheritance::ClassBases;
pub use lines::{shift_pos, shift_range};
pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
pub use outline::{merge_kinds, merge_visibility};
pub use outline::{merge_impl_traits, merge_kinds, merge_visibility};
pub use php_align::PhpAlignment;
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression};
pub use python_fixtures::{
+55
Переглянути файл
@@ -143,6 +143,10 @@ struct Raw {
visibility: Option<Visibility>,
/// Rust `impl Trait for Type`: members take the trait's visibility.
trait_impl: bool,
/// Rust `impl Trait for Type`: the trait's own name in the header.
implements: Option<ide_core::Range>,
/// Rust `impl [Trait for] Type`: the implementing type's own name in the header.
self_type: Option<ide_core::Range>,
/// Base names of a class definition (empty where the grammar has none).
bases: Vec<String>,
}
@@ -227,6 +231,12 @@ fn collect(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) -> Vec<Built>
detail: detail.map(|d| clean(node_text(&d, text), 80)).filter(|d| !d.is_empty()),
visibility: explicit_visibility(&node, text),
trait_impl,
implements: trait_.map(|t| trait_name(t)).map(|n| idx.range(n.start_byte(), n.end_byte())),
self_type: (kind == ItemKind::Impl)
.then(|| node.child_by_field_name("type"))
.flatten()
.map(|t| trait_name(t))
.map(|n| idx.range(n.start_byte(), n.end_byte())),
// The index needs every class's bases; Python is the grammar that has them.
bases: match kind {
ItemKind::Symbol(SymbolKind::Class) if g.spec.name == "python" => {
@@ -304,6 +314,8 @@ pub(crate) fn outline(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) ->
selection_range: b.raw.sel,
children: b.children.into_iter().map(convert).collect(),
visibility: b.visibility,
implements: b.raw.implements,
self_type: b.raw.self_type,
}
}
collect(g, q, tree, text).into_iter().map(convert).collect()
@@ -398,6 +410,21 @@ pub(crate) fn tags(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) -> Ve
out
}
/// The innermost name of a trait or type path: `fmt::Display<T>` -> `Display`, `&mut Foo<T>` -> `Foo`.
fn trait_name(mut node: Node) -> Node {
loop {
let next = match node.kind() {
"generic_type" | "reference_type" => node.child_by_field_name("type"),
"scoped_type_identifier" | "scoped_identifier" => node.child_by_field_name("name"),
_ => None,
};
match next {
Some(n) => node = n,
None => return node,
}
}
}
/// Visibility spelled out by a modifier child (`visibility_modifier`, `modifiers`,
/// `accessibility_modifier`, ...) of the declaration.
fn explicit_visibility(node: &Node, text: &str) -> Option<Visibility> {
@@ -499,6 +526,34 @@ pub fn merge_visibility(target: &mut [OutlineItem], source: &[OutlineItem]) {
}
}
/// Copies the trait and self type ranges of syntax-tree `impl` items onto language-server
/// items starting at the same identifier (rust-analyzer selects the self type).
pub fn merge_impl_traits(target: &mut [OutlineItem], source: &[OutlineItem]) {
type Ranges = (Option<ide_core::Range>, Option<ide_core::Range>);
fn index(items: &[OutlineItem], out: &mut HashMap<ide_core::Pos, Ranges>) {
for i in items {
if i.implements.is_some() || i.self_type.is_some() {
out.insert(i.selection_range.start, (i.implements, i.self_type));
}
index(&i.children, out);
}
}
fn apply(items: &mut [OutlineItem], map: &HashMap<ide_core::Pos, Ranges>) {
for i in items {
if let Some((implements, self_type)) = map.get(&i.selection_range.start) {
i.implements = i.implements.or(*implements);
i.self_type = i.self_type.or(*self_type);
}
apply(&mut i.children, map);
}
}
let mut map = HashMap::new();
index(source, &mut map);
if !map.is_empty() {
apply(target, &map);
}
}
/// Takes the syntax tree's kind where a server reported a declared type as a value or a type
/// parameter: LSP has no kind for type aliases, so servers fall back to one of those
/// (typescript-language-server: Variable; rust-analyzer, sourcekit-lsp: TypeParameter).
+2
Переглянути файл
@@ -125,6 +125,8 @@ fn nest(heads: &[Heading], i: &mut usize, parent: Option<usize>, text: &str, ind
selection_range: index.range(h.name_start, h.name_end),
children: nest(heads, i, Some(h.level), text, index),
visibility: None,
implements: None,
self_type: None,
});
}
items
+51
Переглянути файл
@@ -2110,3 +2110,54 @@ fn outline_restructuredtext_unicode_crlf_and_cached_edits() {
assert_eq!(updated[0].children[0].selection_range.end, Pos::new(4, 5));
assert_ne!(items, updated);
}
fn rust_impl_traits(src: &str) -> Vec<(String, Option<Range>)> {
syntax().outline(&lang("rust"), src).into_iter().map(|i| (i.name, i.implements)).collect()
}
#[test]
fn outline_rust_impl_names_the_trait_in_the_header() {
let at = |l, a, b| Some(Range::new(Pos::new(l, a), Pos::new(l, b)));
assert_eq!(rust_impl_traits("impl<T> fmt::Display for Foo<T> {}\n")[0].1, at(0, 13, 20));
assert_eq!(rust_impl_traits("impl<T: Clone> Shape<T> for\n Holder<T>\nwhere T: Copy\n{}\n")[0].1, at(0, 15, 20));
assert_eq!(rust_impl_traits("impl Trait<{ N }> for Arr {}\n")[0].1, at(0, 5, 10));
assert_eq!(rust_impl_traits("impl Foo {}\n")[0].1, None);
}
#[test]
fn outline_rust_impl_names_the_self_type_in_the_header() {
let text_of = |src: &str| {
let item = syntax().outline(&lang("rust"), src).remove(0);
let at = |r: Option<Range>| {
r.map(|r| {
src.lines().nth(r.start.line as usize).unwrap()[r.start.col as usize..r.end.col as usize].to_owned()
})
};
(at(item.implements), at(item.self_type))
};
let some = |a: &str, b: &str| (Some(a.to_owned()), Some(b.to_owned()));
assert_eq!(text_of("impl Trait<{ 2 > 1 }> for Holder {}\n"), some("Trait", "Holder"));
let bounds = (0..12).map(|i| format!(" T: B{i},\n")).collect::<String>();
assert_eq!(text_of(&format!("impl<T> Shape<T> for Holder<T>\nwhere\n{bounds}{{}}\n")), some("Shape", "Holder"));
assert_eq!(text_of("impl<'a> Tr for &'a mut Foo<u8> {}\n"), some("Tr", "Foo"));
assert_eq!(text_of("impl a::Foo<u8> {}\n"), (None, Some("Foo".to_owned())));
}
#[test]
fn merge_impl_traits_marks_server_impls_by_their_self_type() {
let src = "trait Shape {}\nimpl<T> Shape for\n Holder<T> {\n fn area(&self) {}\n}\n";
let ts = syntax().outline(&lang("rust"), src);
let ts_impl = ts.iter().find(|i| i.implements.is_some()).unwrap();
let mut server = ts_impl.clone();
server.name = "impl Shape for Holder<T>".into();
server.kind = SymbolKind::Variable;
server.implements = None;
server.self_type = None;
server.selection_range = Range::new(Pos::new(2, 4), Pos::new(2, 13));
let mut lsp = vec![server];
crate::merge_impl_traits(&mut lsp, &ts);
assert_eq!(lsp[0].implements, ts_impl.implements);
assert_eq!(lsp[0].implements.unwrap().start, Pos::new(1, 8));
assert_eq!(lsp[0].self_type, ts_impl.self_type);
assert_eq!(lsp[0].self_type.unwrap().start, Pos::new(2, 4));
}
+237 -1
Переглянути файл
@@ -1,7 +1,9 @@
//! Client capabilities we advertise and the server capabilities we consult.
use crate::text::Encoding;
use globset::{GlobBuilder, GlobMatcher};
use serde_json::{Value, json};
use std::path::Path;
pub fn client_capabilities() -> Value {
let symbol_kinds: Vec<u32> = (1..=26).collect();
@@ -191,6 +193,75 @@ pub struct ServerCaps {
pub semantic_legend: Option<(Vec<String>, Vec<String>)>,
/// Applied to what the server announces, now and in later registrations.
pub restriction: Restriction,
/// Registrations for the documents their `documentSelector` picks ([`Self::for_document`]).
pub scoped: Vec<ScopedRegistration>,
}
/// A dynamic registration limited to some documents, e.g. Roslyn's Razor features for
/// `{ language: "aspnetcorerazor", pattern: "**/*.{razor,cshtml}" }`.
#[derive(Clone, Debug)]
pub struct ScopedRegistration {
id: String,
method: String,
selector: Vec<DocumentFilter>,
/// The registration options without the selector.
options: Value,
}
/// An LSP `DocumentFilter`: every part it has must match. File documents only.
#[derive(Clone, Debug)]
struct DocumentFilter {
language: Option<String>,
scheme: Option<String>,
pattern: Option<GlobMatcher>,
}
/// Language ids servers use for one of the IDE's, which the selectors they send name.
const LANGUAGE_ALIASES: &[(&str, &str)] = &[("aspnetcorerazor", "razor")];
impl DocumentFilter {
/// `None` when the filter can't be read: not an object, a field this doesn't know (a
/// notebook's), or one of the wrong type. Such a filter selects no document, rather than
/// more documents than the server meant.
fn parse(filter: &Value) -> Option<Self> {
let fields = filter.as_object()?;
if fields.keys().any(|key| !matches!(key.as_str(), "language" | "scheme" | "pattern")) {
return None;
}
let text = |key: &str| match fields.get(key) {
None | Some(Value::Null) => Some(None),
Some(Value::String(s)) => Some(Some(s.clone())),
Some(_) => None,
};
let (language, scheme) = (text("language")?, text("scheme")?);
let pattern = match fields.get("pattern") {
None | Some(Value::Null) => None,
// A relative pattern (`{ baseUri, pattern }`) is matched below its base.
Some(Value::String(glob)) => Some(glob.clone()),
Some(relative @ Value::Object(_)) => {
let base = relative.get("baseUri").and_then(|b| b.as_str().or_else(|| b.get("uri")?.as_str()));
let glob = relative.get("pattern").and_then(Value::as_str)?;
let base = base.and_then(crate::uri::uri_to_path)?;
Some(format!("{}/{glob}", base.to_string_lossy().replace('\\', "/").trim_end_matches('/')))
}
Some(_) => return None,
};
let pattern = match pattern {
Some(glob) => Some(GlobBuilder::new(&glob).literal_separator(true).build().ok()?.compile_matcher()),
None => None,
};
let filter = Self { language, scheme, pattern };
(filter.language.is_some() || filter.scheme.is_some() || filter.pattern.is_some()).then_some(filter)
}
fn selects(&self, language: &str, path: &Path) -> bool {
let language_matches = self.language.as_deref().is_none_or(|l| {
l == language || LANGUAGE_ALIASES.iter().any(|&(theirs, ours)| theirs == l && ours == language)
});
language_matches
&& self.scheme.as_deref().is_none_or(|s| s == "file")
&& self.pattern.as_ref().is_none_or(|p| p.is_match(path))
}
}
/// LSP request method → server capability key, for features and dynamic registration.
@@ -219,6 +290,11 @@ pub fn capability_key(method: &str) -> Option<&'static str> {
"textDocument/documentLink" => "documentLinkProvider",
"textDocument/prepareCallHierarchy" => "callHierarchyProvider",
"textDocument/prepareTypeHierarchy" => "typeHierarchyProvider",
"textDocument/onTypeFormatting" => "documentOnTypeFormattingProvider",
"textDocument/documentColor" => "colorProvider",
"textDocument/foldingRange" => "foldingRangeProvider",
"textDocument/selectionRange" => "selectionRangeProvider",
"textDocument/linkedEditingRange" => "linkedEditingRangeProvider",
_ => return None,
})
}
@@ -350,7 +426,16 @@ impl ServerCaps {
};
(strings("tokenTypes"), strings("tokenModifiers"))
});
Self { raw, encoding, open_close, sync, save, semantic_legend, restriction: Restriction::default() }
Self {
raw,
encoding,
open_close,
sync,
save,
semantic_legend,
restriction: Restriction::default(),
scoped: Vec::new(),
}
}
/// Drops the capabilities outside the server's `features`, and code action
@@ -496,8 +581,10 @@ impl ServerCaps {
{
self.raw["semanticTokensProvider"] = opts.clone();
let restriction = std::mem::take(&mut self.restriction);
let scoped = std::mem::take(&mut self.scoped);
*self = Self::parse(std::mem::take(&mut self.raw));
self.restriction = restriction;
self.scoped = scoped;
return;
}
// JDT LS registers the commands of bundles that were not loaded when it initialized.
@@ -544,6 +631,59 @@ impl ServerCaps {
}
}
/// Takes a registration with a `documentSelector` as one for the documents it selects; false
/// when it has none, or a `null` one (the server's own documents), or isn't for a feature.
pub fn register_scoped(&mut self, id: &str, method: &str, options: Option<&Value>) -> bool {
let Some(key) = capability_key(method) else { return false };
let selector: Vec<DocumentFilter> = match options.and_then(|o| o.get("documentSelector")) {
None | Some(Value::Null) => return false,
Some(Value::Array(filters)) => filters.iter().filter_map(DocumentFilter::parse).collect(),
// Scoped all the same: a filter that can't be read selects no document, and a
// selector without filters none at all, rather than every document of the server.
Some(_) => Vec::new(),
};
if !self.restriction.allows(key) {
return true;
}
let mut options = options.cloned().unwrap_or(Value::Null);
if let Some(o) = options.as_object_mut() {
o.remove("documentSelector");
}
self.scoped.retain(|s| s.id != id);
self.scoped.push(ScopedRegistration { id: id.to_owned(), method: method.to_owned(), selector, options });
true
}
/// Drops the scoped registration `id`; false when there is none.
pub fn unregister_scoped(&mut self, id: &str) -> bool {
let before = self.scoped.len();
self.scoped.retain(|s| s.id != id);
self.scoped.len() != before
}
/// The capabilities for a document of `language` at `path` when scoped registrations select
/// it: these, with each of them in place of what the server announced for its feature.
pub fn for_document(&self, language: &str, path: &Path) -> Option<ServerCaps> {
let mut selected =
self.scoped.iter().filter(|s| s.selector.iter().any(|f| f.selects(language, path))).peekable();
selected.peek()?;
let mut caps = ServerCaps { scoped: Vec::new(), ..self.clone() };
for s in selected {
let Some(key) = capability_key(&s.method) else { continue };
caps.raw[key] = if s.options.as_object().is_some_and(|o| !o.is_empty()) {
s.options.clone()
} else {
Value::Bool(true)
};
}
// The legend, code action kinds and the rest follow from the raw capabilities.
let restriction = std::mem::take(&mut caps.restriction);
let (encoding, open_close, sync, save) = (caps.encoding, caps.open_close, caps.sync, caps.save);
caps = ServerCaps { encoding, open_close, sync, save, ..Self::parse(caps.raw) };
caps.restrict(restriction);
Some(caps)
}
pub fn unregister(&mut self, method: &str) {
if let Some(op) = file_operation_key(method) {
if let Some(ops) = self.raw.pointer_mut("/workspace/fileOperations").and_then(Value::as_object_mut) {
@@ -603,6 +743,102 @@ mod tests {
assert_eq!((c.sync, c.open_close, c.save), (SyncKind::Full, true, None));
}
/// Roslyn's C# capabilities, and the Razor registrations it sends (cohosting).
fn roslyn_with_razor() -> ServerCaps {
let mut c = ServerCaps::parse(json!({
"textDocumentSync": { "openClose": true, "change": 2 },
"completionProvider": { "resolveProvider": true, "triggerCharacters": [".", " "] },
"hoverProvider": true,
"semanticTokensProvider": { "legend": { "tokenTypes": ["class", "keyword"], "tokenModifiers": ["static"] }, "full": true, "range": true }
}));
let razor = json!([{ "language": "aspnetcorerazor", "pattern": "**/*.{razor,cshtml}" }]);
for (id, method, options) in [
(
"1",
"textDocument/completion",
json!({ "documentSelector": razor, "resolveProvider": true, "triggerCharacters": ["@", "<", "."] }),
),
(
"2",
"textDocument/semanticTokens",
json!({
"documentSelector": razor,
"legend": { "tokenTypes": ["class", "keyword", "razorTransition"], "tokenModifiers": ["static", "razorCode"] },
"full": true
}),
),
("3", "textDocument/documentColor", json!({ "documentSelector": razor })),
] {
assert!(c.register_scoped(id, method, Some(&options)), "{method}");
}
c
}
#[test]
fn registrations_with_a_selector_apply_to_the_documents_it_selects() {
let c = roslyn_with_razor();
let razor = c.for_document("razor", Path::new("/p/Views/Home/Index.cshtml")).expect("selected");
assert_eq!(razor.completion_triggers(), vec!["@", "<", "."]);
assert_eq!(
razor.semantic_legend,
Some((
vec!["class".into(), "keyword".into(), "razorTransition".into()],
vec!["static".into(), "razorCode".into()]
))
);
assert!(razor.semantic_tokens_full() && razor.has("colorProvider") && razor.has("hoverProvider"));
assert!(razor.open_close && razor.sync == SyncKind::Incremental && razor.scoped.is_empty());
// C# files keep Roslyn's own capabilities.
assert!(c.for_document("csharp", Path::new("/p/Controllers/HomeController.cs")).is_none());
assert_eq!(c.completion_triggers(), vec![".", " "]);
assert!(!c.has("colorProvider"));
// Both parts of the filter must match: language (Roslyn's name for it) and pattern.
assert!(c.for_document("html", Path::new("/p/Index.cshtml")).is_none());
assert!(c.for_document("razor", Path::new("/p/Counter.razor")).is_some());
assert!(c.for_document("razor", Path::new("/p/notes.txt")).is_none());
}
#[test]
fn scoped_registrations_unregister_by_id_and_respect_features() {
let mut c = roslyn_with_razor();
assert!(c.unregister_scoped("3"));
assert!(!c.unregister_scoped("3"));
let razor = c.for_document("razor", Path::new("/p/Index.cshtml")).unwrap();
assert!(!razor.has("colorProvider"));
// Without a selector, a registration is the server's (the existing behaviour).
assert!(!c.register_scoped("4", "textDocument/rename", Some(&json!({ "prepareProvider": true }))));
// A feature the server is restricted from stays off for the documents too.
c.restrict(Restriction::new("roslyn", &["completion".into()], &[]));
let selector = json!({ "documentSelector": [{ "pattern": "**/*.cshtml" }] });
assert!(c.register_scoped("5", "textDocument/documentColor", Some(&selector)));
assert!(!c.for_document("razor", Path::new("/p/Index.cshtml")).unwrap().has("colorProvider"));
}
#[test]
fn selectors_that_select_nothing_stay_scoped() {
let mut c = roslyn_with_razor();
for (id, selector) in [
("6", json!([])),
("7", json!([{ "pattern": "**/*.{cshtml" }])),
("8", json!([{ "notebook": "jupyter-notebook" }])),
("9", json!("**/*.cshtml")),
// A field of the wrong type doesn't drop out, widening the filter to the others.
("10", json!([{ "language": 42, "scheme": "file" }])),
("11", json!([{ "scheme": "file", "pattern": 7 }])),
("12", json!([{ "language": "razor", "notebookType": "x" }])),
("13", json!([7])),
] {
let options = json!({ "documentSelector": selector });
assert!(c.register_scoped(id, "textDocument/formatting", Some(&options)), "{selector}");
}
assert!(!c.has("documentFormattingProvider"));
assert!(!c.for_document("razor", Path::new("/p/Index.cshtml")).unwrap().has("documentFormattingProvider"));
assert!(c.for_document("csharp", Path::new("/p/Home.cs")).is_none());
// A null selector is the server's own documents.
let options = json!({ "documentSelector": null });
assert!(!c.register_scoped("14", "textDocument/formatting", Some(&options)));
}
#[test]
fn dynamic_registration() {
let mut c = ServerCaps::parse(json!({}));
+4
Переглянути файл
@@ -814,6 +814,8 @@ pub fn document_symbols(conv: &Conv, path: &Path, r: lsp::DocumentSymbolResponse
selection_range: range,
children: Vec::new(),
visibility: None,
implements: None,
self_type: None,
}
})
.collect();
@@ -833,6 +835,8 @@ fn document_symbol(conv: &Conv, path: &Path, s: lsp::DocumentSymbol) -> OutlineI
selection_range: conv.range(path, s.selection_range),
children: s.children.unwrap_or_default().into_iter().map(|c| document_symbol(conv, path, c)).collect(),
visibility: None,
implements: None,
self_type: None,
}
}
+11 -1
Переглянути файл
@@ -67,7 +67,17 @@ fn item(conv: &Conv, path: &Path, node: Node) -> OutlineItem {
),
None => (node.class_name.or(node.label).unwrap_or(node.kind), detail, SymbolKind::Widget, range),
};
OutlineItem { name, detail, kind, range, selection_range, children, visibility: None }
OutlineItem {
name,
detail,
kind,
range,
selection_range,
children,
visibility: None,
implements: None,
self_type: None,
}
}
/// What follows a widget's class, as the Flutter plugin's outline shows it: the variable holding
+25 -2
Переглянути файл
@@ -356,6 +356,11 @@ impl ClientHandler {
if self.server.initialized_gen(self.generation).is_some_and(|run| !run.caps.read().restriction.diagnostics()) {
return;
}
// The HTML of a Razor document, open or closed since (a late report): Roslyn reports that
// document's problems, and the URI is no real file's.
if params.get("uri").and_then(Value::as_str).is_some_and(crate::razor::is_projection_uri) {
return;
}
let mut params = params;
crate::virtual_doc::normalize_uris(&mut params);
// One malformed diagnostic must not take the others of the file with it.
@@ -625,8 +630,14 @@ impl ClientHandler {
}
watchers_changed = true;
} else if register {
caps.register(method, reg.get("registerOptions"));
} else {
let id = reg.get("id").and_then(Value::as_str).unwrap_or_default();
// Roslyn's Razor features, for Razor documents only (see `razor.rs`).
let scoped = self.server.name == crate::razor::ROSLYN
&& caps.register_scoped(id, method, reg.get("registerOptions"));
if !scoped {
caps.register(method, reg.get("registerOptions"));
}
} else if !caps.unregister_scoped(reg.get("id").and_then(Value::as_str).unwrap_or_default()) {
caps.unregister(method);
}
}
@@ -811,6 +822,18 @@ impl Handler for ClientHandler {
// reports a missing library or configuration; diagnostics already say what's wrong.
"eslint/confirmESLintExecution" => Ok(json!(4)),
"eslint/noLibrary" | "eslint/noConfig" | "eslint/openDoc" => Ok(json!({})),
// Razor cohosting (`razor.rs`): the HTML of a Razor document, and its HTML requests.
"razor/updateHtml" if self.server.name == crate::razor::ROSLYN => {
if mgr.update_razor_html(&self.server, self.generation, &params) {
Ok(Value::Null)
} else {
// For an open of the document closed since: Roslyn publishes it again.
Err((codes::CONTENT_MODIFIED, "the Razor document was closed since".into()))
}
}
_ if self.server.name == crate::razor::ROSLYN && crate::razor::is_forwarded(&params) => {
Ok(mgr.forward_razor_html(&self.server, self.generation, method, &params))
}
other => Err((codes::METHOD_NOT_FOUND, format!("unsupported method {other}"))),
}
}
+5 -4
Переглянути файл
@@ -192,7 +192,7 @@ impl LspManager {
.servers
.iter()
.zip(ready)
.filter_map(|(s, run)| Some(Target { server: s.clone(), run: run? }))
.filter_map(|(s, run)| Some(Target::new(s.clone(), run?)))
.filter(|t| t.caps().restriction.diagnostics())
.collect();
if targets.is_empty() {
@@ -234,11 +234,12 @@ impl LspManager {
text: &str,
cancel: &CancellationToken,
) -> IdeResult<Vec<Diagnostic>> {
let snapshot = scope::snapshot_path(path, "diagnostics")?;
let diagnoses = |c: &crate::caps::ServerCaps| c.restriction.diagnostics();
let targets = tokio::select! {
r = self.snapshot_targets(path, language, "snapshot diagnostics", |c| c.restriction.diagnostics()) => r?,
r = self.snapshot_targets(path, &snapshot, language, "snapshot diagnostics", diagnoses) => r?,
() = cancel.cancelled() => return Err(IdeError::cancelled()),
};
let snapshot = scope::snapshot_path(path, "diagnostics")?;
let doc = Arc::new(DocText::new(text));
let mut result = Outcome::<Vec<_>>::new();
let opts = InspectOptions { timeout: Duration::from_secs(2), ..Default::default() };
@@ -304,7 +305,7 @@ impl LspManager {
error: None,
};
let Some(run) = run else { return Some((report, Vec::new())) };
let t = Target { server: server.clone(), run };
let t = Target::new(server.clone(), run);
if !t.caps().restriction.diagnostics() {
return None;
}
+1 -1
Переглянути файл
@@ -73,7 +73,7 @@ impl LspManager {
Some((jar, entry)) => json!({ "archive": uri::path_to_uri_string(&jar), "entry": entry }),
None => disk_class_params(path, &internal_name.await?),
};
let target = Target { server: server.clone(), run };
let target = Target::new(server.clone(), run);
let result: Option<ClassFileDocument> =
self.call(&target, CLASS_FILE, params, None, REQUEST_TIMEOUT).await?;
let doc = result
+1 -1
Переглянути файл
@@ -267,7 +267,7 @@ impl LspManager {
if !run.caps.read().commands().iter().any(|command| command == COMMAND) {
return Ok(if placeholder { local } else { None });
}
let target = Target { server: server.clone(), run };
let target = Target::new(server.clone(), run);
let position = snap.text.ide_to_lsp(Encoding::Utf16, pos);
let response: Response = match self
.call(
+135 -25
Переглянути файл
@@ -34,6 +34,7 @@ mod notebook;
mod phoxite;
mod plugin_requests;
mod pull;
mod razor;
mod scope;
mod server;
mod source_actions;
@@ -41,6 +42,7 @@ mod switch_source_header;
mod tcp;
mod text;
mod ts_file_moves;
mod ts_parameter_hints;
mod tsserver_bridge;
pub mod types;
mod uri;
@@ -190,14 +192,40 @@ impl DocState {
struct Target {
server: Arc<Server>,
run: Running,
/// The capabilities for the document asked about, when registrations scoped to some
/// documents select it (Roslyn's Razor features); the instance's otherwise.
doc_caps: Option<Arc<ServerCaps>>,
}
/// A target's capabilities: its document's, or the instance's (read-locked).
enum CapsRef<'a> {
Instance(parking_lot::RwLockReadGuard<'a, ServerCaps>),
Document(&'a ServerCaps),
}
impl std::ops::Deref for CapsRef<'_> {
type Target = ServerCaps;
fn deref(&self) -> &ServerCaps {
match self {
Self::Instance(caps) => caps,
Self::Document(caps) => caps,
}
}
}
impl Target {
/// A target not tied to one document.
fn new(server: Arc<Server>, run: Running) -> Self {
Self { server, run, doc_caps: None }
}
fn enc(&self) -> Encoding {
self.run.caps.read().encoding
}
fn caps(&self) -> parking_lot::RwLockReadGuard<'_, ServerCaps> {
self.run.caps.read()
fn caps(&self) -> CapsRef<'_> {
match &self.doc_caps {
Some(caps) => CapsRef::Document(caps),
None => CapsRef::Instance(self.run.caps.read()),
}
}
}
@@ -296,6 +324,8 @@ pub struct LspManager {
injections: injections::State,
/// Open notebooks by path. Locked before `docs` when both are.
notebooks: Mutex<HashMap<PathBuf, notebook::NotebookState>>,
/// The HTML of open Razor documents, for Roslyn's HTML requests.
razor: razor::State,
}
/// Fetched virtual documents kept before the cache is reset.
@@ -602,6 +632,7 @@ impl LspManager {
virtual_stamps: Mutex::new(HashMap::new()),
injections: injections::State::default(),
notebooks: Mutex::new(HashMap::new()),
razor: razor::State::default(),
})
}
@@ -1224,6 +1255,9 @@ impl LspManager {
if server.name == "csharp-ls" {
params["capabilities"]["experimental"]["csharp"]["metadataUris"] = json!(true);
}
if server.name == razor::ROSLYN {
razor::configure_client_capabilities(&mut params["capabilities"]);
}
if !init_options.is_null() {
params["initializationOptions"] = init_options;
}
@@ -1288,7 +1322,12 @@ impl LspManager {
self.close_document(doc);
}
let servers = self.servers_for(language, path);
self.attach(doc, path.to_owned(), uri::path_to_uri(path), language, version, text, servers);
let uri = uri::path_to_uri(path);
if language.as_str() == "razor" {
// Before Roslyn sees the document, which it answers with the document's HTML.
self.open_razor_document(uri.as_str(), true);
}
self.attach(doc, path.to_owned(), uri, language, version, text, servers);
self.schedule_injections(doc);
}
@@ -1525,6 +1564,10 @@ impl LspManager {
if compose_removed && let Some(me) = self.me.upgrade() {
me.reconfigure_soon();
}
if d.language.as_str() == "razor" {
let servers: Vec<Arc<Server>> = d.servers.iter().map(|a| a.server.clone()).collect();
self.close_razor_document(d.uri.as_str(), &servers);
}
for a in &d.servers {
self.forget_pulled(&a.server, &d.path, a.server.running().as_ref());
let Some(run) = a.server.running() else { continue };
@@ -1564,14 +1607,40 @@ impl LspManager {
}
async fn ready_targets(&self, servers: &[Arc<Server>], pred: impl Fn(&ServerCaps) -> bool) -> Vec<Target> {
self.targets_for(servers, None, pred).await
}
/// [`Self::ready_targets`] for a request about `snap`'s document, with the capabilities
/// registered for that document ([`ServerCaps::for_document`]).
async fn doc_ready_targets(
&self,
snap: &DocSnap,
servers: &[Arc<Server>],
pred: impl Fn(&ServerCaps) -> bool,
) -> Vec<Target> {
self.targets_for(servers, Some((&snap.language, snap.path.as_path())), pred).await
}
async fn targets_for(
&self,
servers: &[Arc<Server>],
doc: Option<(&LanguageId, &Path)>,
pred: impl Fn(&ServerCaps) -> bool,
) -> Vec<Target> {
let ready = join_all(servers.iter().map(|s| s.wait_ready(START_WAIT))).await;
servers
.iter()
.zip(ready)
.filter_map(|(s, run)| {
let run = run?;
let ok = pred(&run.caps.read());
ok.then(|| Target { server: s.clone(), run })
let doc_caps = doc
.and_then(|(language, path)| run.caps.read().for_document(language.as_str(), path))
.map(Arc::new);
let ok = match &doc_caps {
Some(caps) => pred(caps),
None => pred(&run.caps.read()),
};
ok.then(|| Target { server: s.clone(), run, doc_caps })
})
.collect()
}
@@ -1583,7 +1652,7 @@ impl LspManager {
pred: impl Fn(&ServerCaps) -> bool,
) -> IdeResult<(DocSnap, Vec<Target>)> {
let snap = self.snapshot(doc)?;
let targets = self.ready_targets(&snap.servers, pred).await;
let targets = self.doc_ready_targets(&snap, &snap.servers, pred).await;
if targets.is_empty() {
return Err(unsupported(&snap.servers, feature));
}
@@ -1731,7 +1800,9 @@ impl LspManager {
let snap = self.snapshot(doc)?;
let Some(server) = snap.servers.iter().find(|s| s.id == item.server) else { return Ok(original) };
let Some(t) = self
.ready_targets(std::slice::from_ref(server), |c| c.has_sub("completionProvider", "resolveProvider"))
.doc_ready_targets(&snap, std::slice::from_ref(server), |c| {
c.has_sub("completionProvider", "resolveProvider")
})
.await
.pop()
else {
@@ -1874,11 +1945,28 @@ impl LspManager {
positions: &[Pos],
cancel: CancellationToken,
) -> IdeResult<Vec<Vec<Location>>> {
let (method, cap, feature) = goto_method(GotoKind::Implementation);
self.goto_each(GotoKind::Implementation, doc, positions, cancel).await
}
/// The same `kind` of go-to request at each of `positions`, with the answers of
/// [`Self::implementations`] (the ↑ gutter markers of languages without a type hierarchy).
pub async fn goto_each(
&self,
kind: GotoKind,
doc: DocId,
positions: &[Pos],
cancel: CancellationToken,
) -> IdeResult<Vec<Vec<Location>>> {
let (method, cap, feature) = goto_method(kind);
let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await?;
let requests = positions.iter().copied().map(|pos| {
let (snap, targets, cancel) = (&snap, &targets, &cancel);
async move { self.goto_in(snap, targets, method, pos, Some(cancel), None).await }
async move {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
self.goto_in(snap, targets, method, pos, Some(cancel), None).await
}
});
let results: Vec<IdeResult<Vec<Location>>> =
futures::stream::iter(requests).buffered(IMPLEMENTATION_CONCURRENCY).collect().await;
@@ -2424,7 +2512,7 @@ impl LspManager {
if !targets.iter().any(listed) {
return Vec::new();
}
let defining = self.ready_targets(&snap.servers, |c| c.has("definitionProvider")).await;
let defining = self.doc_ready_targets(&snap, &snap.servers, |c| c.has("definitionProvider")).await;
self.goto_in(&snap, &defining, "textDocument/definition", pos, Some(&cancel), None)
.await
.unwrap_or_default()
@@ -2511,7 +2599,7 @@ impl LspManager {
pub async fn document_symbols(&self, doc: DocId) -> IdeResult<Option<Vec<OutlineItem>>> {
let snap = self.snapshot(doc)?;
let targets = self.ready_targets(&snap.servers, |c| c.has("documentSymbolProvider")).await;
let targets = self.doc_ready_targets(&snap, &snap.servers, |c| c.has("documentSymbolProvider")).await;
let mut out = Outcome::new();
for t in &targets {
let params = json!({ "textDocument": snap.ident() });
@@ -2763,7 +2851,8 @@ impl LspManager {
Some(s) => vec![s.clone()],
None => self.servers.lock().iter().filter(|s| s.id == action.server).cloned().collect(),
};
let Some(t) = self.ready_targets(&servers, |c| c.has_sub("codeActionProvider", "resolveProvider")).await.pop()
let Some(t) =
self.doc_ready_targets(&snap, &servers, |c| c.has_sub("codeActionProvider", "resolveProvider")).await.pop()
else {
return Ok(original);
};
@@ -3264,7 +3353,7 @@ impl LspManager {
}
let ready = join_all(servers.iter().map(|s| s.wait_ready(FILE_OP_START_WAIT))).await;
let targets: Vec<Target> =
servers.iter().zip(ready).filter_map(|(s, run)| Some(Target { server: s.clone(), run: run? })).collect();
servers.iter().zip(ready).filter_map(|(s, run)| Some(Target::new(s.clone(), run?))).collect();
let mut out = FileRenameEdits::default();
for t in targets {
let Some(params) = Self::file_op_params(&t, "willRename", &moves) else {
@@ -3316,7 +3405,7 @@ impl LspManager {
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
for s in servers {
let Some(run) = s.running() else { continue };
let t = Target { server: s.clone(), run };
let t = Target::new(s.clone(), run);
let Some(params) = Self::file_op_params(&t, "didRename", &moves) else { continue };
if let Err(e) = t.run.peer.notify("workspace/didRenameFiles", params) {
tracing::debug!("{}: didRenameFiles: {e}", s.name);
@@ -3452,12 +3541,14 @@ impl LspManager {
/// Checks initialized capabilities, including dynamic registrations, before choosing a formatter.
pub async fn can_format(&self, doc: DocId) -> IdeResult<bool> {
let snap = self.snapshot(doc)?;
Ok(!self.ready_targets(&snap.servers, |c| c.has("documentFormattingProvider")).await.is_empty())
Ok(!self.doc_ready_targets(&snap, &snap.servers, |c| c.has("documentFormattingProvider")).await.is_empty())
}
/// Servers for a snapshot of `path` at `snapshot`, which the request is about.
async fn snapshot_targets(
&self,
path: &Path,
snapshot: &Path,
language: &LanguageId,
feature: &str,
supports: impl Fn(&ServerCaps) -> bool,
@@ -3467,7 +3558,10 @@ impl LspManager {
for server in &servers {
self.ensure_started(server);
}
let mut targets = self.ready_targets(&servers, supports).await;
// With the capabilities registered for the snapshot: selectors match the document the
// server is sent, not the file it is a snapshot of.
let doc = Some((language, snapshot));
let mut targets = self.targets_for(&servers, doc, supports).await;
if targets.is_empty() {
// A primary server can become unavailable while it initializes.
let candidates = self.servers_for(language, path);
@@ -3475,7 +3569,7 @@ impl LspManager {
for server in &candidates {
self.ensure_started(server);
}
targets = self.ready_targets(&candidates, supports).await;
targets = self.targets_for(&candidates, doc, supports).await;
}
}
if targets.is_empty() {
@@ -3484,12 +3578,14 @@ impl LspManager {
Ok(targets)
}
async fn text_format_targets(&self, path: &Path, language: &LanguageId) -> IdeResult<Vec<Target>> {
self.snapshot_targets(path, language, "snapshot formatting", |c| c.has("documentFormattingProvider")).await
async fn text_format_targets(&self, path: &Path, snapshot: &Path, language: &LanguageId) -> IdeResult<Vec<Target>> {
self.snapshot_targets(path, snapshot, language, "snapshot formatting", |c| c.has("documentFormattingProvider"))
.await
}
pub async fn can_format_text(&self, path: &Path, language: &LanguageId) -> bool {
self.text_format_targets(path, language).await.is_ok()
let Ok(snapshot) = scope::snapshot_path(path, "format") else { return false };
self.text_format_targets(path, &snapshot, language).await.is_ok()
}
/// Use a transient URI so requests in the editor still see the working buffer.
@@ -3501,7 +3597,7 @@ impl LspManager {
options: FormatOptions,
) -> IdeResult<Vec<TextEdit>> {
let path_to_snapshot = scope::snapshot_path(path, "format")?;
let targets = self.text_format_targets(path, language).await?;
let targets = self.text_format_targets(path, &path_to_snapshot, language).await?;
let target = &targets[0];
let mut opened = scope::TransientFiles::empty(self, target);
opened.hold(&path_to_snapshot, language, text);
@@ -3557,9 +3653,20 @@ impl LspManager {
match r {
Ok(hints) => {
let conv = self.conv(t.enc());
let tsserver = t.server.config.tsserver_project;
let text = snap.text.as_str();
let acc = out.value.get_or_insert_with(Vec::new);
acc.extend(
hints.unwrap_or_default().into_iter().map(|h| convert::inlay_hint(&conv, &snap.path, h)),
hints
.unwrap_or_default()
.into_iter()
.map(|h| convert::inlay_hint(&conv, &snap.path, h))
// The TypeScript servers send all parameter names: keep WebStorm's.
.filter(|h| {
!tsserver
|| h.kind != InlayKind::Parameter
|| ts_parameter_hints::shown_at(&text[snap.text.byte_offset(h.position)..])
}),
);
}
Err(e) => out.fail(e),
@@ -3573,8 +3680,9 @@ impl LspManager {
pub async fn semantic_tokens(&self, doc: DocId) -> IdeResult<Option<SemanticTokens>> {
let snap = self.snapshot(doc)?;
let targets =
self.ready_targets(&snap.servers, |c| c.semantic_tokens_full() && c.semantic_legend.is_some()).await;
let targets = self
.doc_ready_targets(&snap, &snap.servers, |c| c.semantic_tokens_full() && c.semantic_legend.is_some())
.await;
let Some(t) = targets.first() else { return Ok(None) };
let params = json!({ "textDocument": snap.ident() });
let r: Option<Value> =
@@ -3722,7 +3830,9 @@ impl LspManager {
pub async fn color_presentations(&self, doc: DocId, color: DocumentColor) -> IdeResult<Vec<ColorPresentation>> {
let snap = self.snapshot(doc)?;
let Some(server) = snap.servers.iter().find(|s| s.id == color.server) else { return Ok(Vec::new()) };
let Some(t) = self.ready_targets(std::slice::from_ref(server), |c| c.has("colorProvider")).await.pop() else {
let Some(t) =
self.doc_ready_targets(&snap, std::slice::from_ref(server), |c| c.has("colorProvider")).await.pop()
else {
return Ok(Vec::new());
};
let params = json!({
+1 -1
Переглянути файл
@@ -48,7 +48,7 @@ impl LspManager {
.lock()
.iter()
.filter(|s| s.name == server)
.filter_map(|s| s.running().map(|run| Target { server: s.clone(), run }))
.filter_map(|s| s.running().map(|run| Target::new(s.clone(), run)))
.collect();
let at = running.iter().position(|t| t.server.root == root).unwrap_or(0);
if running.is_empty() {
+635
Переглянути файл
@@ -0,0 +1,635 @@
//! Razor (`.cshtml`, `.razor`) through Roslyn's cohosting, the way the VS Code C# extension
//! hosts it. Roslyn serves Razor documents in the same instance as the project's C#. For the
//! HTML of a document it sends the client the HTML it generated (`razor/updateHtml`) and asks
//! the client the HTML half of a request (`textDocument/completion`, `hover`, `formatting`…,
//! with params `{ textDocument, checksum, request }`). Those are answered by
//! vscode-html-language-server on a virtual `…/Index.cshtml__virtual.html?razor` document
//! holding that HTML (the document's *projection*; the query keeps it apart from any real file).
//! When a Razor document closes, Roslyn is told (`razor/documentClosed`) and the virtual
//! document is closed too.
//!
//! Requests from a server are handled concurrently, so a forwarded request can arrive before
//! the update it was made with, and two requests can need different projections at once. A
//! request waits for its update, and each change of a virtual document goes out together with
//! the request that needs it, as do its open and close ([`State::dispatch`]): the HTML server
//! answers every request on the HTML the request was made for, or the request gets its empty
//! answer and Roslyn asks again. Updates handled before Roslyn has acknowledged the close of a
//! document belong to the open before, and are turned down ([`State::closing`]).
//!
//! Roslyn registers its Razor features dynamically, for Razor documents only (`documentSelector:
//! [{ language: "aspnetcorerazor", pattern: "**/*.{razor,cshtml}" }]`): its completion triggers,
//! the semantic token legend with Razor's token types, document colors. So Roslyn is told the
//! client registers those features dynamically ([`configure_client_capabilities`]), and the
//! registrations apply to the documents they select ([`crate::caps::ServerCaps::for_document`]).
use crate::LspManager;
use crate::server::{Running, Server};
use crate::text::{DocText, Encoding};
use crate::uri::{path_to_uri_string, uri_to_path};
use ide_core::{LanguageId, ServerId};
use serde_json::{Value, json};
use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, Waker};
use std::time::Duration;
/// The Roslyn language server, which hosts Razor.
pub(crate) const ROSLYN: &str = "roslyn-language-server";
/// The server that answers the HTML of Razor documents (`html.toml`).
const HTML_SERVER: &str = "vscode-html-language-server";
/// Appended to a Razor document's URI for its HTML, as the Razor tooling names it, with a query
/// no URI of a real file has (`path_to_uri` never writes one; a `?` in a name is escaped).
const VIRTUAL_SUFFIX: &str = "__virtual.html?razor";
/// All a forwarded request may take, waits included: Roslyn answers the request it forwards
/// for within the client's deadline for it (completion's is 5 s), with its C# part on top.
const FORWARD_BUDGET: Duration = Duration::from_secs(4);
/// Older checksums of a document remembered, to tell a request made for HTML that has since
/// changed (answered empty at once) from one whose update hasn't been handled yet (waited for).
const SUPERSEDED: usize = 64;
/// The HTML requests Roslyn forwards that the HTML server answers; the others get their empty answer.
const FORWARDED: &[&str] = &[
"textDocument/completion",
"completionItem/resolve",
"textDocument/hover",
"textDocument/signatureHelp",
"textDocument/definition",
"textDocument/implementation",
"textDocument/references",
"textDocument/documentHighlight",
"textDocument/documentColor",
"textDocument/colorPresentation",
"textDocument/foldingRange",
"textDocument/formatting",
"textDocument/rangeFormatting",
"textDocument/onTypeFormatting",
"textDocument/prepareRename",
"textDocument/rename",
"textDocument/linkedEditingRange",
];
/// `textDocument` client capabilities whose registrations Roslyn scopes to Razor documents. Not
/// `diagnostic`: with it, Roslyn also moves its C# diagnostics to dynamic registrations.
const DYNAMIC_FEATURES: &[&str] = &[
"completion",
"hover",
"signatureHelp",
"definition",
"implementation",
"references",
"documentHighlight",
"documentSymbol",
"codeAction",
"codeLens",
"colorProvider",
"formatting",
"rangeFormatting",
"onTypeFormatting",
"rename",
"semanticTokens",
"inlayHint",
"callHierarchy",
"typeHierarchy",
];
/// A Razor document open in the IDE, and the HTML Roslyn generated for it.
struct Projection {
html: parking_lot::Mutex<Html>,
/// Bumped when the HTML changes or the document closes; forwarded requests wait on it.
changed: tokio::sync::watch::Sender<u64>,
}
#[derive(Default)]
struct Html {
/// Editors and transient opens holding the document; it is forgotten at 0.
opens: usize,
/// The Roslyn instance (server, generation) that generated `text`.
roslyn: Option<(ServerId, u64)>,
checksum: String,
text: String,
/// Earlier checksums from the same instance, newest last.
superseded: VecDeque<String>,
/// The virtual document as the HTML server has it.
sent: Option<Sent>,
}
struct Sent {
host: Arc<Server>,
generation: u64,
version: i32,
/// The HTML it has: from this Roslyn instance, with this checksum.
roslyn: (ServerId, u64),
checksum: String,
}
/// Where a forwarded request stands against a document's HTML.
enum Wait {
Ready(String),
Pending,
Gone,
}
impl Projection {
fn new() -> Self {
Self { html: parking_lot::Mutex::new(Html::default()), changed: tokio::sync::watch::channel(0).0 }
}
fn check(&self, roslyn: (ServerId, u64), checksum: &str) -> Wait {
let html = self.html.lock();
if html.opens == 0 {
Wait::Gone
} else if html.roslyn == Some(roslyn) && html.checksum == checksum {
Wait::Ready(html.text.clone())
} else if html.roslyn.is_some_and(|(server, generation)| server == roslyn.0 && generation > roslyn.1)
|| html.roslyn == Some(roslyn) && html.superseded.iter().any(|c| c == checksum)
{
// From an instance since replaced, or for HTML that has changed since.
Wait::Gone
} else {
Wait::Pending
}
}
/// The HTML with `checksum` from Roslyn instance `roslyn`, once its update is in; `None`
/// when the document closed or the HTML is no longer current.
async fn text(&self, roslyn: (ServerId, u64), checksum: &str) -> Option<String> {
let mut changed = self.changed.subscribe();
loop {
match self.check(roslyn, checksum) {
Wait::Ready(text) => return Some(text),
Wait::Gone => return None,
Wait::Pending => changed.changed().await.ok()?,
}
}
}
}
#[derive(Default)]
pub(crate) struct State {
/// By the path of the Razor document.
docs: parking_lot::Mutex<HashMap<PathBuf, Arc<Projection>>>,
/// Held while a virtual document is opened, changed or closed on the HTML server, and a
/// forwarded request is written right behind the change it needs: nothing comes between
/// them, and a request for a document being closed is written before its close or not at all.
/// A close also writes `razor/documentClosed` under it, and an open takes it first, so a
/// reopen's `didOpen` reaches Roslyn after the close before.
dispatch: parking_lot::Mutex<()>,
/// Razor documents whose close Roslyn hasn't acknowledged yet (`razor/documentClosed`), by
/// path. Roslyn handles the close before a reopen, so its updates until then are for the
/// open before.
closing: parking_lot::Mutex<HashMap<PathBuf, usize>>,
}
/// Lets Roslyn register its Razor features for Razor documents ([`DYNAMIC_FEATURES`]).
pub(crate) fn configure_client_capabilities(capabilities: &mut Value) {
for feature in DYNAMIC_FEATURES {
if let Some(cap) = capabilities.pointer_mut(&format!("/textDocument/{feature}")).and_then(Value::as_object_mut)
{
cap.insert("dynamicRegistration".into(), Value::Bool(true));
}
}
}
/// Whether `uri` names the HTML of a Razor document ([`VIRTUAL_SUFFIX`]), open or closed since:
/// no real file has such a URI, so what a server says about it isn't about the user's files.
pub(crate) fn is_projection_uri(uri: &str) -> bool {
uri.strip_suffix(VIRTUAL_SUFFIX).and_then(uri_to_path).is_some()
}
/// Params of an HTML request Roslyn forwards for a Razor document.
pub(crate) fn is_forwarded(params: &Value) -> bool {
params.get("checksum").is_some_and(Value::is_string)
&& params.pointer("/textDocument/uri").is_some_and(Value::is_string)
&& params.get("request").is_some()
}
fn virtual_uri(path: &Path) -> String {
format!("{}{VIRTUAL_SUFFIX}", path_to_uri_string(path))
}
/// What the HTML server can't answer: no colors, else nothing.
fn empty_answer(method: &str) -> Value {
match method {
"textDocument/documentColor" | "textDocument/colorPresentation" => json!([]),
_ => Value::Null,
}
}
/// `value` with `from`, where it names a document (a location's `uri`, a `changes` key), as `to`.
fn rename_uri(value: &mut Value, from: &str, to: &str) {
match value {
Value::String(s) if s == from => *s = to.to_owned(),
Value::Array(items) => items.iter_mut().for_each(|v| rename_uri(v, from, to)),
Value::Object(fields) => {
if let Some(edits) = fields.remove(from) {
fields.insert(to.to_owned(), edits);
}
fields.values_mut().for_each(|v| rename_uri(v, from, to));
}
_ => {}
}
}
/// Every LSP position (`{ line, character }`) in `value`, a request or an answer about `text`,
/// from encoding `from` to `to`; opaque `data` is left as it is.
fn convert_positions(value: &mut Value, text: &DocText, from: Encoding, to: Encoding) {
match value {
Value::Array(items) => items.iter_mut().for_each(|v| convert_positions(v, text, from, to)),
Value::Object(fields) => {
let line = fields.get("line").and_then(Value::as_u64);
let character = fields.get("character").and_then(Value::as_u64);
if fields.len() == 2
&& let (Some(line), Some(character)) = (line, character)
{
let pos = lsp_types::Position::new(line as u32, character as u32);
let converted = text.ide_to_lsp(to, text.lsp_to_ide(from, pos));
fields.insert("character".into(), json!(converted.character));
return;
}
for (key, v) in fields.iter_mut() {
if key != "data" {
convert_positions(v, text, from, to);
}
}
}
_ => {}
}
}
impl LspManager {
/// A Razor document opened, in an editor or transiently (`start_html: false`), before its
/// `didOpen` reaches Roslyn: Roslyn's HTML for it is kept from now on.
pub(crate) fn open_razor_document(&self, uri: &str, start_html: bool) {
let Some(path) = uri_to_path(uri) else { return };
{
// After an earlier close has been written to Roslyn.
let _dispatch = self.razor.dispatch.lock();
let mut docs = self.razor.docs.lock();
docs.entry(path.clone()).or_insert_with(|| Arc::new(Projection::new())).html.lock().opens += 1;
}
if start_html {
// Started now, so it is ready by the first request Roslyn forwards.
self.razor_html_server(&path);
}
}
/// `razor/updateHtml` from Roslyn instance `generation` of `roslyn`: new HTML for a Razor
/// document. False when it is for an open of the document that has closed since, which the
/// caller turns down: Roslyn then publishes the HTML again after the close.
pub(crate) fn update_razor_html(&self, roslyn: &Server, generation: u64, params: &Value) -> bool {
let Some(path) = params.pointer("/textDocument/uri").and_then(Value::as_str).and_then(uri_to_path) else {
return true;
};
let text = |key: &str| params.get(key).and_then(Value::as_str).unwrap_or_default().to_owned();
let docs = self.razor.docs.lock();
if self.razor.closing.lock().get(&path).is_some_and(|n| *n > 0) {
return false;
}
// Not for a document that isn't open: that would bring it back.
let Some(projection) = docs.get(&path).cloned() else { return true };
{
let mut html = projection.html.lock();
if html.roslyn.is_some_and(|(server, g)| server == roslyn.id && g > generation) {
return true;
}
let checksum = text("checksum");
if html.roslyn == Some((roslyn.id, generation)) {
if html.checksum != checksum {
let previous = std::mem::take(&mut html.checksum);
html.superseded.retain(|c| *c != checksum && *c != previous);
html.superseded.push_back(previous);
if html.superseded.len() > SUPERSEDED {
html.superseded.pop_front();
}
}
} else {
html.superseded.clear();
}
html.roslyn = Some((roslyn.id, generation));
html.checksum = checksum;
html.text = text("text");
}
drop(docs);
projection.changed.send_modify(|n| *n += 1);
true
}
/// The HTML server's answer to a request Roslyn instance `generation` of `roslyn` forwards
/// for a Razor document (`params`: `{ textDocument, checksum, request }`), or the method's
/// empty answer. Server requests are handled on blocking threads, so this waits right here.
pub(crate) fn forward_razor_html(&self, roslyn: &Server, generation: u64, method: &str, params: &Value) -> Value {
let empty = empty_answer(method);
if !FORWARDED.contains(&method) {
return empty;
}
let Some(uri) = params.pointer("/textDocument/uri").and_then(Value::as_str) else { return empty };
let checksum = params.get("checksum").and_then(Value::as_str).unwrap_or_default();
let request = params.get("request").cloned().unwrap_or(Value::Null);
let Some(encoding) = roslyn.initialized_gen(generation).map(|run| run.caps.read().encoding) else {
return empty;
};
let instance = (roslyn.id, generation);
let forward = self.razor_html_request(instance, encoding, uri, checksum, method, request);
match self.runtime.block_on(async { tokio::time::timeout(FORWARD_BUDGET, forward).await }) {
Ok(Some(answer)) => answer,
Ok(None) => empty,
Err(_) => {
tracing::debug!("{HTML_SERVER}: {method} for {uri} took longer than {FORWARD_BUDGET:?}");
empty
}
}
}
async fn razor_html_request(
&self,
roslyn: (ServerId, u64),
encoding: Encoding,
uri: &str,
checksum: &str,
method: &str,
mut request: Value,
) -> Option<Value> {
let path = uri_to_path(uri)?;
let projection = self.razor.docs.lock().get(&path).cloned()?;
let text = projection.text(roslyn, checksum).await?;
let host = self.razor_html_server(&path)?;
let run = host.wait_ready(FORWARD_BUDGET).await?;
let virtual_uri = virtual_uri(&path);
let html_encoding = run.caps.read().encoding;
let text = DocText::new(&text);
if let Some(document) = request.get_mut("textDocument").filter(|d| d.is_object()) {
document["uri"] = json!(virtual_uri);
}
if encoding != html_encoding {
convert_positions(&mut request, &text, encoding, html_encoding);
}
let mut sent = std::pin::pin!(run.peer.request::<_, Value>(method, request, None));
let first = {
let _dispatch = self.razor.dispatch.lock();
// Checked again: the HTML may have changed, or the document closed, meanwhile.
self.send_razor_html(&projection, &host, &run, &virtual_uri, roslyn, checksum)?;
// The first poll writes the request, right behind the update it needs; the answer
// is awaited below, which polls it again.
sent.as_mut().poll(&mut Context::from_waker(Waker::noop()))
};
let answer = match first {
Poll::Ready(answer) => answer,
Poll::Pending => sent.await,
};
let mut answer = match answer {
Ok(answer) => answer,
Err(e) => {
tracing::debug!("{HTML_SERVER}: {method} for {}: {e}", path.display());
return None;
}
};
if encoding != html_encoding {
convert_positions(&mut answer, &text, html_encoding, encoding);
}
rename_uri(&mut answer, &virtual_uri, uri);
Some(answer)
}
/// The HTML server for the Razor document at `path`, started if it isn't running.
fn razor_html_server(&self, path: &Path) -> Option<Arc<Server>> {
let html = LanguageId::new("html");
let cfg = self.language_servers(&html).into_iter().find(|c| c.name == HTML_SERVER)?;
let server = self.server_for(&cfg, &html, path);
self.ensure_started(&server);
Some(server)
}
/// Opens the HTML with `checksum` of `projection` on `host`'s instance `run`, or brings the
/// virtual document up to date there; `None` when that HTML is no longer the document's.
fn send_razor_html(
&self,
projection: &Projection,
host: &Arc<Server>,
run: &Running,
virtual_uri: &str,
roslyn: (ServerId, u64),
checksum: &str,
) -> Option<()> {
let mut html = projection.html.lock();
if html.opens == 0 || html.roslyn != Some(roslyn) || html.checksum != checksum {
return None;
}
let html = &mut *html;
let current = html.sent.as_ref().filter(|s| s.host.id == host.id && s.generation == run.generation);
match current.map(|sent| sent.roslyn == roslyn && sent.checksum == checksum) {
None => {
let params = json!({
"textDocument": { "uri": virtual_uri, "languageId": "html", "version": 1, "text": html.text }
});
run.peer.notify("textDocument/didOpen", params).ok()?;
html.sent = Some(Sent {
host: host.clone(),
generation: run.generation,
version: 1,
roslyn,
checksum: checksum.to_owned(),
});
}
Some(false) => {
let sent = html.sent.as_mut()?;
sent.version += 1;
sent.roslyn = roslyn;
sent.checksum = checksum.to_owned();
let params = json!({
"textDocument": { "uri": virtual_uri, "version": sent.version },
"contentChanges": [{ "text": html.text }]
});
run.peer.notify("textDocument/didChange", params).ok()?;
}
Some(true) => {}
}
Some(())
}
/// A Razor document closed (one of its opens): once nothing holds it, Roslyn forgets its
/// HTML, and the HTML server its virtual document.
pub(crate) fn close_razor_document(&self, uri: &str, servers: &[Arc<Server>]) {
let Some(path) = uri_to_path(uri) else { return };
let roslyns: Vec<_> = servers.iter().filter(|s| s.name == ROSLYN).filter_map(|s| s.running()).collect();
let fenced = !roslyns.is_empty();
let mut closes: Vec<Pin<Box<dyn Future<Output = ()> + Send>>> = Vec::new();
{
// After any request already written for it, and before a reopen's `didOpen`.
let _dispatch = self.razor.dispatch.lock();
let sent = {
let mut docs = self.razor.docs.lock();
let Some(projection) = docs.get(&path).cloned() else { return };
let mut html = projection.html.lock();
html.opens = html.opens.saturating_sub(1);
if html.opens > 0 {
return;
}
docs.remove(&path);
if fenced {
*self.razor.closing.lock().entry(path.clone()).or_default() += 1;
}
let sent = html.sent.take();
drop(html);
// Requests waiting for this document's HTML give up.
projection.changed.send_modify(|n| *n += 1);
sent
};
if let Some(sent) = sent
&& let Some(run) = sent.host.running_gen(sent.generation)
&& let Err(e) =
run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": virtual_uri(&path) } }))
{
tracing::debug!("{HTML_SERVER}: didClose: {e}");
}
// Requests, as Razor's cohosting has no document notifications, written here: before a
// reopen's `didOpen` (see `open_razor_document`). Their answers are awaited below.
for run in roslyns {
let uri = uri.to_owned();
let mut close: Pin<Box<dyn Future<Output = ()> + Send>> = Box::pin(async move {
let params = json!({ "uri": uri });
if let Err(e) = run.peer.request::<_, Value>("razor/documentClosed", params, None).await {
tracing::debug!("{ROSLYN}: razor/documentClosed: {e}");
}
});
if close.as_mut().poll(&mut Context::from_waker(Waker::noop())).is_pending() {
closes.push(close);
}
}
}
if !fenced {
return;
}
let mgr = self.me.clone();
// Once Roslyn has answered, its updates for the document are for a later open.
self.runtime.spawn(async move {
for close in closes {
close.await;
}
if let Some(mgr) = mgr.upgrade() {
let mut closing = mgr.razor.closing.lock();
if let Some(n) = closing.get_mut(&path) {
*n -= 1;
if *n == 0 {
closing.remove(&path);
}
}
}
});
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roslyn_registers_razor_features_dynamically_but_not_diagnostics() {
let mut caps = crate::caps::client_capabilities();
configure_client_capabilities(&mut caps);
for feature in ["completion", "semanticTokens", "colorProvider", "hover", "codeAction"] {
assert_eq!(caps["textDocument"][feature]["dynamicRegistration"], json!(true), "{feature}");
}
assert_eq!(caps["textDocument"]["diagnostic"]["dynamicRegistration"], json!(false));
assert_eq!(caps["textDocument"]["synchronization"]["dynamicRegistration"], json!(false));
// Only features the client has: no capability is made up.
assert!(caps["textDocument"].get("linkedEditingRange").is_none());
}
#[test]
fn tells_forwarded_requests_apart() {
let forwarded = json!({
"textDocument": { "uri": "file:///p/Views/Home/Index.cshtml" },
"checksum": "AbC=",
"request": { "textDocument": { "uri": "file:///p/Views/Home/Index.cshtml" }, "position": { "line": 1, "character": 2 } }
});
assert!(is_forwarded(&forwarded));
assert!(!is_forwarded(
&json!({ "textDocument": { "uri": "file:///p/a.cshtml" }, "checksum": "x", "text": "" })
));
assert!(!is_forwarded(&json!({ "items": [{ "section": "razor.format.code_block_brace_on_next_line" }] })));
assert_eq!(empty_answer("textDocument/documentColor"), json!([]));
assert_eq!(empty_answer("textDocument/hover"), Value::Null);
}
#[test]
fn names_the_razor_document_in_html_answers() {
let virtual_uri = "file:///p/Index.cshtml__virtual.html";
let uri = "file:///p/Index.cshtml";
let mut locations = json!([{ "uri": virtual_uri, "range": {} }, { "targetUri": "file:///p/site.css" }]);
rename_uri(&mut locations, virtual_uri, uri);
assert_eq!(locations[0]["uri"], json!(uri));
assert_eq!(locations[1]["targetUri"], json!("file:///p/site.css"));
let mut edit = json!({ "changes": {} });
edit["changes"][virtual_uri] = json!([{ "newText": "span" }]);
rename_uri(&mut edit, virtual_uri, uri);
assert_eq!(edit["changes"][uri][0]["newText"], json!("span"));
assert!(edit["changes"].get(virtual_uri).is_none());
}
#[test]
fn converts_positions_between_encodings_but_not_opaque_data() {
let text = DocText::new("<p>😀<b>x</b></p>\n<i>é</i>");
let mut request = json!({
"position": { "line": 0, "character": 5 },
"data": { "line": 0, "character": 5 }
});
convert_positions(&mut request, &text, Encoding::Utf16, Encoding::Utf8);
assert_eq!(request["position"], json!({ "line": 0, "character": 7 }));
assert_eq!(request["data"], json!({ "line": 0, "character": 5 }));
let mut answer =
json!([{ "range": { "start": { "line": 1, "character": 3 }, "end": { "line": 1, "character": 5 } } }]);
convert_positions(&mut answer, &text, Encoding::Utf8, Encoding::Utf16);
assert_eq!(answer[0]["range"]["start"], json!({ "line": 1, "character": 3 }));
assert_eq!(answer[0]["range"]["end"], json!({ "line": 1, "character": 4 }));
}
#[test]
fn requests_wait_for_their_html_and_give_up_on_html_that_changed() {
let projection = Projection::new();
let roslyn = (ServerId::next(), 1);
let state = |checksum: &str| match projection.check(roslyn, checksum) {
Wait::Ready(text) => text,
Wait::Pending => "pending".into(),
Wait::Gone => "gone".into(),
};
// Not open: nothing to wait for.
assert_eq!(state("a"), "gone");
projection.html.lock().opens = 1;
assert_eq!(state("a"), "pending");
{
let mut html = projection.html.lock();
html.roslyn = Some(roslyn);
html.checksum = "b".into();
html.text = "<b>".into();
html.superseded = VecDeque::from(["a".to_owned()]);
}
assert_eq!(state("b"), "<b>");
assert_eq!(state("a"), "gone");
// A checksum not seen yet: its update is still on its way.
assert_eq!(state("c"), "pending");
// A newer instance replaced the one that asks.
projection.html.lock().roslyn = Some((roslyn.0, 2));
assert_eq!(state("b"), "gone");
}
#[test]
fn virtual_documents_sit_next_to_their_razor_document() {
let path = if cfg!(windows) {
PathBuf::from(r"C:\p\Views\Index.cshtml")
} else {
PathBuf::from("/p/Views/Index.cshtml")
};
let uri = virtual_uri(&path);
assert!(uri.starts_with("file:///") && uri.ends_with("Index.cshtml__virtual.html?razor"));
// Not the URI of a real file of that name, nor of one with the query in its name.
let real = path.with_file_name("Index.cshtml__virtual.html");
assert_ne!(uri, path_to_uri_string(&real));
assert_ne!(uri, path_to_uri_string(&path.with_file_name("Index.cshtml__virtual.html?razor")));
// Reserved, open or not; a real file of that name isn't.
assert!(is_projection_uri(&uri));
assert!(!is_projection_uri(&path_to_uri_string(&real)));
assert!(!is_projection_uri(&path_to_uri_string(&path.with_file_name("Index.cshtml__virtual.html?razor"))));
}
}
+28 -12
Переглянути файл
@@ -454,8 +454,12 @@ impl LspManager {
continue;
}
let uri = crate::uri::path_to_uri(&path);
let language = self.languages.detect(&path, text.lines().next());
if language.as_str() == "razor" && t.server.name == crate::razor::ROSLYN {
self.open_razor_document(uri.as_str(), false);
guard.razor.push(uri.clone());
}
if t.server.hold_transient(&path, t.run.generation) {
let language = self.languages.detect(&path, text.lines().next());
let params = json!({
"textDocument": { "uri": uri, "languageId": language.as_str(), "version": 0, "text": text }
});
@@ -491,6 +495,10 @@ pub(crate) struct TransientFiles<'a> {
server: Arc<Server>,
run: Running,
pub files: Vec<(PathBuf, lsp::Uri)>,
/// The Razor documents among `files` held on Roslyn, whose HTML Roslyn sends
/// ([`crate::razor`]): each hold keeps the document's projection until this guard drops,
/// whichever holder opens or closes the file on Roslyn (or an editor takes it over).
razor: Vec<lsp::Uri>,
/// Candidates that could not be opened.
pub skipped: bool,
}
@@ -519,6 +527,10 @@ impl TransientFiles<'_> {
) -> Option<tokio::sync::watch::Receiver<Vec<lsp::Diagnostic>>> {
let _docs = self.mgr.docs.lock();
let uri = crate::uri::path_to_uri(path);
if language.as_str() == "razor" && self.server.name == crate::razor::ROSLYN {
self.mgr.open_razor_document(uri.as_str(), false);
self.razor.push(uri.clone());
}
let open = self.server.hold_transient(path, self.run.generation);
let receiver = diagnostics.then(|| self.server.watch_transient_diagnostics(path));
if open {
@@ -535,24 +547,28 @@ impl TransientFiles<'_> {
impl<'a> TransientFiles<'a> {
pub(crate) fn empty(mgr: &'a LspManager, t: &Target) -> Self {
Self { mgr, server: t.server.clone(), run: t.run.clone(), files: Vec::new(), skipped: false }
Self { mgr, server: t.server.clone(), run: t.run.clone(), files: Vec::new(), razor: Vec::new(), skipped: false }
}
}
impl Drop for TransientFiles<'_> {
fn drop(&mut self) {
if self.files.is_empty() {
return;
}
// Under the documents lock, so a user `didOpen` of the same file can't interleave.
let _docs = self.mgr.docs.lock();
for (path, uri) in self.files.drain(..) {
if self.server.release_transient(&path, self.run.generation)
&& let Err(e) = self.run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": uri } }))
{
tracing::debug!("{}: didClose: {e}", self.server.name);
if !self.files.is_empty() {
// Under the documents lock, so a user `didOpen` of the same file can't interleave.
let _docs = self.mgr.docs.lock();
for (path, uri) in self.files.drain(..) {
if self.server.release_transient(&path, self.run.generation)
&& let Err(e) =
self.run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": uri } }))
{
tracing::debug!("{}: didClose: {e}", self.server.name);
}
}
}
// After Roslyn's `didClose`, if this was the last holder of the file.
for uri in self.razor.drain(..) {
self.mgr.close_razor_document(uri.as_str(), std::slice::from_ref(&self.server));
}
}
}
+8 -5
Переглянути файл
@@ -19,9 +19,10 @@ impl LspManager {
pos: Pos,
cancel: &CancellationToken,
) -> IdeResult<Vec<CompletionItem>> {
let targets =
self.snapshot_targets(path, language, "snapshot completion", |c| c.has("completionProvider")).await?;
let snapshot = scope::snapshot_path(path, "completion")?;
let targets = self
.snapshot_targets(path, &snapshot, language, "snapshot completion", |c| c.has("completionProvider"))
.await?;
let doc = Arc::new(DocText::new(text));
let requests = targets.iter().map(|t| {
let (snapshot, doc) = (&snapshot, &doc);
@@ -64,9 +65,11 @@ impl LspManager {
if !kind.starts_with("source.") {
return Err(IdeError::invalid("a text snapshot requires a source action"));
}
let targets =
self.snapshot_targets(path, language, "snapshot source actions", |c| c.has("codeActionProvider")).await?;
let path = scope::snapshot_path(path, "source")?;
let snapshot = scope::snapshot_path(path, "source")?;
let targets = self
.snapshot_targets(path, &snapshot, language, "snapshot source actions", |c| c.has("codeActionProvider"))
.await?;
let path = snapshot;
let mut out = Outcome::new();
for target in &targets {
match self.snapshot_action(target, &path, language, text, kind, cancel).await {
+157
Переглянути файл
@@ -0,0 +1,157 @@
//! WebStorm's parameter name hints for JavaScript and TypeScript: at literal arguments and at
//! function expressions (`run(function () {}, 2)` shows `task:` and `count:`), not at variables.
//! tsserver offers only "literals" (no functions) or "all", so the servers are asked for all of
//! them and the hints at other arguments are dropped here.
/// Whether the argument starting `rest` gets a parameter name hint.
pub(crate) fn shown_at(rest: &str) -> bool {
literal(rest) || function(rest)
}
fn ident_char(c: char) -> bool {
c.is_alphanumeric() || c == '_' || c == '$'
}
/// `rest` starts with the keyword `word` (not a longer identifier).
fn keyword<'a>(rest: &'a str, word: &str) -> Option<&'a str> {
rest.strip_prefix(word).filter(|after| !after.starts_with(ident_char))
}
/// tsserver's hintable literals: strings, templates, numbers (signed too), booleans, `null`, `undefined`.
fn literal(rest: &str) -> bool {
let unsigned = rest.strip_prefix(['-', '+']).map_or(rest, str::trim_start);
let mut chars = unsigned.chars();
match chars.next() {
Some('"' | '\'' | '`') => true,
Some(c) if c.is_ascii_digit() => true,
Some('.') => chars.next().is_some_and(|c| c.is_ascii_digit()),
_ => ["true", "false", "null", "undefined"].iter().any(|w| keyword(rest, w).is_some()),
}
}
/// `function` expressions and arrow functions, `async` or not.
fn function(rest: &str) -> bool {
let rest = keyword(rest, "async").map_or(rest, str::trim_start);
if keyword(rest, "function").is_some() {
return true;
}
// `x => …`
let ident_len = rest.find(|c: char| !ident_char(c)).unwrap_or(rest.len());
if ident_len > 0 && !rest.starts_with(|c: char| c.is_ascii_digit()) {
return rest[ident_len..].trim_start().starts_with("=>");
}
// `(a, b) => …`, `(): void => …`
rest.starts_with('(') && arrow_after_parameters(rest)
}
/// `rest` (from `(`) is an arrow function: its parameter list, an optional return type, then `=>`.
fn arrow_after_parameters(rest: &str) -> bool {
let mut depth = 0usize;
let mut quote = None;
let mut chars = rest.char_indices().peekable();
while let Some((i, c)) = chars.next() {
if let Some(q) = quote {
if c == '\\' {
chars.next();
} else if c == q {
quote = None;
}
continue;
}
match c {
'"' | '\'' | '`' => quote = Some(c),
'(' | '[' | '{' | '<' => depth += 1,
')' | ']' | '}' | '>' if depth > 0 => {
// `=>` inside a type (`(f: () => void)`) is not the arrow's.
if c == '>' && rest[..i].ends_with('=') {
depth += 1;
}
depth -= 1;
if depth == 0 && c == ')' {
let after = rest[i + 1..].trim_start();
return after.starts_with("=>") || (after.starts_with(':') && return_type_then_arrow(&after[1..]));
}
}
_ => {}
}
}
false
}
/// After a return type's `:`: `=>` before the argument ends (`,` or `)` outside brackets).
fn return_type_then_arrow(rest: &str) -> bool {
let mut depth = 0usize;
let mut prev = ' ';
for c in rest.chars() {
match c {
'(' | '[' | '{' | '<' => depth += 1,
'>' if prev == '=' && depth == 0 => return true,
')' | ']' | '}' | '>' if depth > 0 => depth -= 1,
',' | ')' | ';' if depth == 0 => return false,
_ => {}
}
prev = c;
}
false
}
#[cfg(test)]
mod tests {
use super::shown_at;
#[test]
fn literals_and_functions_get_hints_other_arguments_do_not() {
let shown = [
"2)",
"-1, 2)",
"+ 1.5)",
".5)",
"0x1f)",
"'a')",
"\"a\")",
"`a${b}`)",
"true)",
"false)",
"null)",
"undefined)",
"function () {}, 2)",
"async function named() {})",
"() => {})",
"async () => 1)",
"x => x * 2)",
"async x => x)",
"(a, b) => a + b)",
"(a: number, { b }: Opts) => a)",
"(f: () => void) => f())",
"(): void => {})",
"(): Promise<Map<string, number>> => load())",
"(\n a,\n b,\n) => a)",
];
for arg in shown {
assert!(shown_at(arg), "{arg:?} should get a hint");
}
let hidden = [
"start, withTime)",
"withTime)",
"trueish)",
"nullable)",
"functionName)",
"asyncTask)",
"(a))",
"(1 + 2))",
"(a, b), c)",
"-x)",
"{ a: 1 })",
"[1, 2])",
"new Date())",
"foo(1))",
"a.b)",
"...rest)",
")",
"",
];
for arg in hidden {
assert!(!shown_at(arg), "{arg:?} should not get a hint");
}
}
}
+419
Переглянути файл
@@ -1654,6 +1654,29 @@ async fn property_editor_has_nothing_without_a_dart_server() {
assert!(h.launcher.state("mock").requested("dart/textDocument/editableArguments").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn tsserver_parameter_hints_keep_literals_and_callbacks_at_utf16_positions() {
let h = harness_configured("typescript", "ts", &[("mock", incremental_caps())], |cfg| {
cfg.tsserver_project = true;
});
let (doc, _) = h.open("a.ts", r#"run("😀", function () {}, 2, count);"#);
h.wait_status("mock", ServerStatus::Ready).await;
h.launcher.state("mock").respond(
"textDocument/inlayHint",
json!([
{"position": {"line": 0, "character": 4}, "kind": 2, "label": "label:"},
{"position": {"line": 0, "character": 10}, "kind": 2, "label": "task:"},
{"position": {"line": 0, "character": 26}, "kind": 2, "label": "count:"},
{"position": {"line": 0, "character": 29}, "kind": 2, "label": "value:"},
]),
);
let hints = h.mgr.inlay_hints(doc, rng(0, 0, 0, 36)).await.unwrap();
assert_eq!(
hints.iter().map(|hint| (hint.position.col, hint.label.as_str())).collect::<Vec<_>>(),
[(4, "label:"), (10, "task:"), (26, "count:")]
);
}
#[tokio::test(flavor = "multi_thread")]
async fn closing_labels_join_the_inlay_hints_until_the_next_edit() {
let h = harness(&[("mock", incremental_caps())]);
@@ -4313,6 +4336,48 @@ async fn implementations_per_position() {
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
}
/// Rust's ↑ gutter markers: the trait of an impl block (definition) and the trait method of an impl
/// method (declaration) are asked per position, each with its own request method.
#[tokio::test(flavor = "multi_thread")]
async fn goto_each_asks_the_requested_method_per_position() {
let caps = json!({ "textDocumentSync": 1, "declarationProvider": true });
let h = harness(&[("mock", caps)]);
let (doc, path) = h.open("a.mk", "trait A { fn f(); }\nimpl A for B { fn f() {} }\n");
h.wait_status("mock", ServerStatus::Ready).await;
let s = h.launcher.state("mock");
let uri = uri_of(&path);
*s.responder.lock() = Some(Arc::new(move |_, method, params| {
if method != "textDocument/declaration" {
return None;
}
// The method on line 1 is declared on line 0; nothing else is.
Some(match params["position"]["line"].as_u64() {
Some(1) => {
json!([{ "uri": uri, "range": {"start":{"line":0,"character":14},"end":{"line":0,"character":15}} }])
}
_ => json!([]),
})
}));
let found = h
.mgr
.goto_each(GotoKind::Declaration, doc, &[Pos::new(1, 20), Pos::new(0, 14)], Default::default())
.await
.unwrap();
assert_eq!(found.len(), 2);
assert_eq!(found[0].iter().map(|l| l.range.start.line).collect::<Vec<_>>(), vec![0]);
assert!(found[1].is_empty());
assert_eq!(s.requested("textDocument/declaration").len(), 2);
// A cancelled pass asks nothing more.
let cancelled = CancellationToken::new();
cancelled.cancel();
let err = h.mgr.goto_each(GotoKind::Declaration, doc, &[Pos::new(1, 20)], cancelled).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
assert_eq!(s.requested("textDocument/declaration").len(), 2);
// The server does not advertise definitions: an unavailable server is not "no declarations".
let err = h.mgr.goto_each(GotoKind::Definition, doc, &[Pos::new(1, 20)], Default::default()).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
}
#[tokio::test]
async fn implementation_progress_ends_on_cancel_without_server_end() {
implementation_progress_ends_with_request(false).await;
@@ -9123,3 +9188,357 @@ async fn c_family_files_use_sourcekit_lsp_only_with_an_xcode_bsp_config() {
h.mgr.shutdown_all().await;
}
}
// ------------------------------------------------------------------ Razor
const ROSLYN: &str = "roslyn-language-server";
const HTML: &str = "vscode-html-language-server";
/// Razor documents served by a mock Roslyn, whose HTML goes to a mock HTML server. The HTML
/// server answers a hover with the virtual document's text as it has it, and the position
/// it was asked about.
fn razor_harness() -> Harness {
let h = harness_languages(
&[("razor", "cshtml", &[(ROSLYN, incremental_caps())]), ("html", "html", &[(HTML, incremental_caps())])],
|_| {},
);
*h.launcher.state(HTML).responder.lock() = Some(Arc::new(|s, method, params| {
let uri = params["textDocument"]["uri"].as_str()?.to_owned();
let range = json!({ "start": params["position"], "end": params["position"] });
match method {
"textDocument/hover" => Some(json!({ "contents": s.docs.lock().get(&uri).cloned(), "range": range })),
"textDocument/definition" => Some(json!([{ "uri": uri, "range": range }])),
_ => None,
}
}));
h
}
/// Roslyn's `razor/updateHtml`; false when the client turns it down.
async fn update_html(roslyn: &MockState, uri: &str, checksum: &str, text: &str) -> bool {
let params = json!({ "textDocument": { "uri": uri }, "checksum": checksum, "text": text });
roslyn.peer().request::<_, Value>("razor/updateHtml", params, None).await.is_ok()
}
/// Sends the update until the client takes it, as Roslyn publishes HTML again after a turn-down.
async fn update_html_until_taken(roslyn: &MockState, uri: &str, checksum: &str, text: &str) {
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while !update_html(roslyn, uri, checksum, text).await {
assert!(std::time::Instant::now() < deadline, "the update for {checksum} was never taken");
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
/// A request Roslyn forwards to the client for the HTML with `checksum`.
async fn forward(roslyn: &MockState, method: &str, uri: &str, checksum: &str, line: u32, character: u32) -> Value {
let request = json!({ "textDocument": { "uri": uri }, "position": { "line": line, "character": character } });
let params = json!({ "textDocument": { "uri": uri }, "checksum": checksum, "request": request });
roslyn.peer().request(method, params, None).await.unwrap()
}
fn server_id(h: &Harness, name: &str) -> ServerId {
h.mgr.servers().into_iter().find(|s| s.name == name).unwrap().id
}
#[tokio::test(flavor = "multi_thread")]
async fn razor_html_requests_are_answered_on_the_html_they_were_made_for() {
let h = razor_harness();
let (doc, path) = h.open("Index.cshtml", "<p>@Model.Name</p>");
h.wait_status(ROSLYN, ServerStatus::Ready).await;
// Started with the Razor document, before anything is forwarded.
h.wait_status(HTML, ServerStatus::Ready).await;
let roslyn = h.launcher.state(ROSLYN);
let html = h.launcher.state(HTML);
let uri = uri_of(&path);
let virtual_uri = format!("{uri}__virtual.html?razor");
let virtual_opens = || {
html.notified("textDocument/didOpen").iter().filter(|p| p["textDocument"]["uri"] == json!(virtual_uri)).count()
};
let hover = |checksum: &'static str| {
let (roslyn, uri) = (roslyn.clone(), uri.clone());
async move { forward(&roslyn, "textDocument/hover", &uri, checksum, 0, 1).await }
};
// Requests run concurrently: one can arrive before the update it was made with, and waits.
let early = tokio::spawn(hover("a"));
tokio::time::sleep(Duration::from_millis(100)).await;
assert!(!early.is_finished());
update_html(&roslyn, &uri, "a", "<p>a</p>").await;
assert_eq!(early.await.unwrap()["contents"], "<p>a</p>");
assert_eq!(html.notified("textDocument/didOpen")[0]["textDocument"]["uri"], json!(virtual_uri));
// Requests for two versions at once: each is answered on its own HTML, or not at all.
update_html(&roslyn, &uri, "b", "<p>b</p>").await;
let (b, c) = tokio::join!(hover("b"), async {
update_html(&roslyn, &uri, "c", "<p>c</p>").await;
hover("c").await
});
assert!(b.is_null() || b["contents"] == "<p>b</p>", "{b}");
assert_eq!(c["contents"], "<p>c</p>");
// HTML that has changed since gets the empty answer right away; Roslyn asks again.
let started = std::time::Instant::now();
assert_eq!(hover("a").await, Value::Null);
assert!(started.elapsed() < Duration::from_secs(2));
// The same HTML again (an undo) is current again.
update_html(&roslyn, &uri, "a", "<p>a</p>").await;
assert_eq!(hover("a").await["contents"], "<p>a</p>");
let versions: Vec<Value> =
html.notified("textDocument/didChange").iter().map(|p| p["textDocument"]["version"].clone()).collect();
assert!(versions.windows(2).all(|w| w[0].as_i64() < w[1].as_i64()), "{versions:?}");
// Positions are UTF-16 on both sides, astral characters included; answers name the Razor document.
update_html(&roslyn, &uri, "d", "<p>😀<b>x</b></p>").await;
let answer = forward(&roslyn, "textDocument/definition", &uri, "d", 0, 5).await;
assert_eq!(
answer,
json!([{ "uri": uri, "range": { "start": { "line": 0, "character": 5 }, "end": { "line": 0, "character": 5 } } }])
);
assert_eq!(html.requested("textDocument/definition")[0]["position"], json!({ "line": 0, "character": 5 }));
// A real file named as the Razor tooling names the HTML is open on the same HTML server,
// under its own URI.
let real = h.root.join("Index.cshtml__virtual.html");
std::fs::write(&real, "<i>real</i>").unwrap();
h.mgr.did_open(DocId::next(), &real, &LanguageId::new("html"), 1, "<i>real</i>");
eventually(|| html.docs.lock().get(&uri_of(&real)).is_some_and(|t| t == "<i>real</i>")).await;
assert_eq!(html.docs.lock().get(&virtual_uri).map(String::as_str), Some("<p>😀<b>x</b></p>"));
assert_ne!(uri_of(&real), virtual_uri);
// The HTML server reports problems in the virtual document, which aren't the user's; the
// real file keeps its own.
let diagnostic = json!({ "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 1 } }, "message": "m" });
let publish = |uri: &str| {
let params = json!({ "uri": uri, "diagnostics": [diagnostic.clone()] });
html.peer().notify("textDocument/publishDiagnostics", params).unwrap();
};
publish(&virtual_uri);
publish(&uri_of(&real));
let reported = || -> Vec<PathBuf> {
h.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::Diagnostics { path, items, .. } if !items.is_empty() => Some(path.to_path_buf()),
_ => None,
})
.collect()
};
eventually(|| !reported().is_empty()).await;
assert_eq!(reported(), vec![real]);
// A restarted HTML server gets the virtual document again.
h.mgr.restart(server_id(&h, HTML)).await.unwrap();
assert_eq!(hover("d").await["contents"], "<p>😀<b>x</b></p>");
assert_eq!(virtual_opens(), 2);
// A restarted Roslyn: HTML from the instance before isn't used, even with the same checksum.
h.mgr.restart(server_id(&h, ROSLYN)).await.unwrap();
eventually(|| roslyn.notified("textDocument/didOpen").len() == 2).await;
let pending = tokio::spawn(hover("d"));
tokio::time::sleep(Duration::from_millis(100)).await;
assert!(!pending.is_finished());
update_html(&roslyn, &uri, "d", "<p>new</p>").await;
assert_eq!(pending.await.unwrap()["contents"], "<p>new</p>");
// Closed: the virtual document goes, and an update arriving late doesn't bring it back.
h.mgr.did_close(doc);
eventually(|| {
html.notified("textDocument/didClose").iter().any(|p| p["textDocument"]["uri"] == json!(virtual_uri))
})
.await;
eventually(|| roslyn.requested("razor/documentClosed").iter().any(|p| p["uri"] == json!(uri))).await;
// Turned down until Roslyn has acknowledged the close, ignored after.
update_html(&roslyn, &uri, "e", "<p>late</p>").await;
assert_eq!(hover("e").await, Value::Null);
// Reopened: a fresh start.
let opens = virtual_opens();
h.mgr.did_open(DocId::next(), &path, &h.lang, 1, "<p>@Model.Name</p>");
eventually(|| roslyn.notified("textDocument/didOpen").len() == 3).await;
update_html_until_taken(&roslyn, &uri, "f", "<p>f</p>").await;
assert_eq!(hover("f").await["contents"], "<p>f</p>");
assert_eq!(virtual_opens(), opens + 1);
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn razor_updates_for_an_open_closed_since_are_turned_down_until_roslyn_acknowledges_the_close() {
let h = razor_harness();
// Roslyn takes a while to acknowledge a close.
*h.launcher.state(ROSLYN).responder.lock() = Some(Arc::new(|_, method, _| {
(method == "razor/documentClosed").then(|| {
std::thread::sleep(Duration::from_millis(400));
Value::Null
})
}));
let (doc, path) = h.open("Index.cshtml", "<p>@Model.Name</p>");
h.wait_status(ROSLYN, ServerStatus::Ready).await;
let roslyn = h.launcher.state(ROSLYN);
let uri = uri_of(&path);
assert!(update_html(&roslyn, &uri, "a", "<p>a</p>").await);
h.mgr.did_close(doc);
h.mgr.did_open(DocId::next(), &path, &h.lang, 2, "<p>@Model.Name</p>");
// Made before Roslyn saw the close: for the open before, which is gone.
assert!(!update_html(&roslyn, &uri, "b", "<p>b</p>").await);
eventually(|| !roslyn.requested("razor/documentClosed").is_empty()).await;
update_html_until_taken(&roslyn, &uri, "c", "<p>c</p>").await;
assert_eq!(forward(&roslyn, "textDocument/hover", &uri, "c", 0, 1).await["contents"], "<p>c</p>");
h.mgr.shutdown_all().await;
}
/// Project-wide references searches that open `Other.cshtml` for Roslyn and hold it while Roslyn
/// answers: the answers with it open wait in turn at `gates` (none past them).
fn razor_search_harness(gates: Vec<Arc<Gate>>) -> (Harness, PathBuf) {
let h = razor_harness();
let other = h.root.join("Other.cshtml");
std::fs::write(&other, "<p>@target</p>").unwrap();
// Its mentions are never in Roslyn's answers, so every search opens it to look.
let base = open_files_only(vec![uri_of(&other)]);
let answered = std::sync::atomic::AtomicUsize::new(0);
*h.launcher.state(ROSLYN).responder.lock() = Some(Arc::new(move |s, method, params| {
if method == "textDocument/references" && s.docs.lock().keys().any(|u| u.ends_with("Other.cshtml")) {
let turn = answered.fetch_add(1, Ordering::SeqCst);
if let Some(gate) = gates.get(turn) {
gate.hold();
}
}
base(s, method, params)
}));
grep_candidates(&h);
(h, other)
}
#[tokio::test(flavor = "multi_thread")]
async fn razor_documents_opened_for_a_search_are_released_by_whoever_holds_them_last() {
// The answers with `Other.cshtml` open: the first search's second one; the second search's
// first and second ones; the third search's second one.
let gates: Vec<Arc<Gate>> = (0..4).map(|_| Arc::new(Gate::default())).collect();
gates[1].open();
let (h, other) = razor_search_harness(gates.clone());
let (doc, _) = h.open("Index.cshtml", "<p>@target</p>");
h.wait_status(ROSLYN, ServerStatus::Ready).await;
let roslyn = h.launcher.state(ROSLYN);
let other_uri = uri_of(&other);
let closed = || roslyn.requested("razor/documentClosed").iter().filter(|p| p["uri"] == json!(other_uri)).count();
let held = || roslyn.docs.lock().contains_key(&other_uri);
let search = || {
let mgr = h.mgr.clone();
tokio::spawn(async move {
// Project-wide: files beyond Roslyn's own answer are opened for it.
mgr.references_streaming(doc, Pos::new(0, 5), true, true, true, Default::default(), None).await
})
};
// Two searches hold it; the one that opened it lets go first.
let first = search();
eventually(|| gates[0].entered()).await;
assert!(held());
let second = search();
eventually(|| gates[2].entered()).await;
gates[0].open();
first.await.unwrap().unwrap();
assert!(held(), "the second search still holds it");
assert_eq!(closed(), 0);
gates[2].open();
second.await.unwrap().unwrap();
eventually(|| !held()).await;
eventually(|| closed() == 1).await;
// An editor takes it over while a search holds it, and closes it after the search ends.
let third = search();
eventually(|| gates[3].entered()).await;
let editor = DocId::next();
h.mgr.did_open(editor, &other, &h.lang, 1, "<p>@target</p>");
gates[3].open();
third.await.unwrap().unwrap();
tokio::time::sleep(Duration::from_millis(100)).await;
assert!(held());
assert_eq!(closed(), 1, "the editor still has it");
h.mgr.did_close(editor);
eventually(|| closed() == 2).await;
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn razor_snapshot_formatting_follows_the_selectors_for_the_snapshot_sent() {
let mut caps = incremental_caps();
caps.as_object_mut().unwrap().remove("documentFormattingProvider");
let h = harness_languages(&[("razor", "cshtml", &[(ROSLYN, caps)])], |_| {});
let (doc, path) = h.open("Index.cshtml", "<p>@x</p>");
h.wait_status(ROSLYN, ServerStatus::Ready).await;
let s = h.launcher.state(ROSLYN);
let registrations = json!({ "registrations": [{ "id": "1", "method": "textDocument/formatting",
"registerOptions": { "documentSelector": [{ "pattern": "**/Index.cshtml" }] } }] });
s.peer().request::<_, Value>("client/registerCapability", registrations, None).await.unwrap();
let options = || FormatOptions { tab_size: 4, insert_spaces: true, on_save: false, tool: None };
s.respond("textDocument/formatting", json!([]));
// The document itself is selected; a snapshot of it (`.openidea-format-…-Index.cshtml`) isn't.
h.mgr.format(doc, None, options()).await.unwrap();
let razor = LanguageId::new("razor");
assert!(!h.mgr.can_format_text(&path, &razor).await);
assert!(h.mgr.format_text(&path, &razor, "<p>@x</p>", options()).await.is_err());
assert_eq!(s.requested("textDocument/formatting").len(), 1);
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn razor_registrations_apply_to_razor_documents_and_not_to_csharp_ones_on_the_same_server() {
let mut caps = incremental_caps();
caps["completionProvider"] = json!({ "triggerCharacters": ["."] });
caps["codeActionProvider"] = json!(true);
caps.as_object_mut().unwrap().remove("documentFormattingProvider");
let h = harness_languages(
&[("razor", "cshtml", &[(ROSLYN, caps.clone())]), ("csharp", "cs", &[(ROSLYN, caps)])],
|_| {},
);
let (razor, razor_path) = h.open("Index.cshtml", "<p>@x</p>");
let cs_path = h.root.join("Home.cs");
std::fs::write(&cs_path, "class Home {}").unwrap();
let csharp = DocId::next();
let csharp_language = LanguageId::new("csharp");
h.mgr.did_open(csharp, &cs_path, &csharp_language, 1, "class Home {}");
h.wait_status(ROSLYN, ServerStatus::Ready).await;
assert_eq!(h.mgr.servers().len(), 1, "one Roslyn for both");
let s = h.launcher.state(ROSLYN);
let selector = json!([{ "language": "aspnetcorerazor", "pattern": "**/*.{razor,cshtml}" }]);
let registrations = json!({ "registrations": [
{ "id": "1", "method": "textDocument/completion",
"registerOptions": { "documentSelector": selector, "resolveProvider": true, "triggerCharacters": ["@"] } },
{ "id": "2", "method": "textDocument/codeAction",
"registerOptions": { "documentSelector": selector, "resolveProvider": true } },
{ "id": "3", "method": "textDocument/formatting", "registerOptions": { "documentSelector": selector } },
// Selects no document, rather than every one.
{ "id": "4", "method": "textDocument/rangeFormatting", "registerOptions": { "documentSelector": [] } },
]});
s.peer().request::<_, Value>("client/registerCapability", registrations, None).await.unwrap();
s.respond("textDocument/completion", json!([{ "label": "Model" }]));
s.respond("completionItem/resolve", json!({ "label": "Model", "detail": "resolved" }));
s.respond("textDocument/codeAction", json!([{ "title": "Fix", "kind": "quickfix", "data": 7 }]));
s.respond("codeAction/resolve", json!({ "title": "Fix", "kind": "quickfix", "edit": { "changes": {} } }));
for (doc, resolves) in [(razor, true), (csharp, false)] {
let completions = s.requested("completionItem/resolve").len();
let list = h.mgr.completion(doc, Pos::new(0, 1), None, Default::default()).await.unwrap();
let resolved = h.mgr.resolve_completion(doc, list.items[0].clone()).await.unwrap();
assert_eq!(resolved.detail.as_deref(), resolves.then_some("resolved"));
assert_eq!(s.requested("completionItem/resolve").len(), completions + usize::from(resolves));
let actions = s.requested("codeAction/resolve").len();
let action = h.mgr.code_actions(doc, rng(0, 0, 0, 0), vec![]).await.unwrap().remove(0);
h.mgr.resolve_code_action(doc, action).await.unwrap();
assert_eq!(s.requested("codeAction/resolve").len(), actions + usize::from(resolves));
}
let options = || FormatOptions { tab_size: 4, insert_spaces: true, on_save: false, tool: None };
let razor_language = LanguageId::new("razor");
assert!(h.mgr.can_format_text(&razor_path, &razor_language).await);
assert!(!h.mgr.can_format_text(&cs_path, &csharp_language).await);
s.respond("textDocument/formatting", json!([]));
h.mgr.format_text(&razor_path, &razor_language, "<p>@x</p>", options()).await.unwrap();
let snapshot = s.requested("textDocument/formatting")[0]["textDocument"]["uri"].clone();
// The snapshot is a Razor document while it's open: Roslyn is told when it closes.
eventually(|| s.requested("razor/documentClosed").iter().any(|p| p["uri"] == snapshot)).await;
for doc in [razor, csharp] {
assert!(h.mgr.format(doc, Some(rng(0, 0, 0, 1)), options()).await.is_err());
}
h.mgr.shutdown_all().await;
}
+42
Переглянути файл
@@ -972,6 +972,48 @@ async fn bundler_path_aliases_resolve_below_tsconfig_paths() {
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// JavaScript and TypeScript inlay hints with the bundled vtsls settings (#7326), as in WebStorm:
/// parameter names at literal and function arguments only, and inferred variable types. Set
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vtsls/[email protected] typescript@6`.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires @vtsls/language-server and typescript@6 (OPENIDEA_TEST_NPM_TOOLS)"]
async fn vtsls_parameter_hints_follow_webstorm() {
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
std::fs::write(root.join("package.json"), "{\"name\":\"app\",\"private\":true}").unwrap();
let text = "function run(task: () => void, count: number, label?: string) {}\n\
const n = 2;\n\
run(function () {}, 2);\n\
run(() => {}, n, 'x');\n\
const total = n * 2;\n";
std::fs::write(root.join("main.ts"), text).unwrap();
let bundled = LanguageRegistry::load(None).unwrap();
let bundled = bundled.get(&LanguageId::new("typescript")).unwrap().language_servers;
let bundled = bundled.iter().find(|s| s.name == "vtsls").unwrap();
let mut server = npm_server(&tools, "vtsls", "vtsls", None);
server.initialization_options = bundled.initialization_options.clone();
server.tsserver_project = true;
let (mgr, _events) = manager(&root, LanguageRegistry::from_configs(vec![lang("typescript", "ts", server)]));
let doc = DocId::next();
mgr.did_open(doc, &root.join("main.ts"), &LanguageId::new("typescript"), 1, text);
let range = Range::new(Pos::new(0, 0), Pos::new(5, 0));
let hints = retry("inlay hints", Duration::from_secs(90), || {
let mgr = mgr.clone();
async move { mgr.inlay_hints(doc, range).await.ok().filter(|h| !h.is_empty()) }
})
.await;
let mut labels: Vec<_> = hints.iter().map(|h| (h.position.line, h.label.trim().to_owned())).collect();
labels.sort();
// `run(function () {}, 2)`: both; `run(() => {}, n, 'x')`: not `count:` before the variable.
assert_eq!(
labels,
[(2, "count:".into()), (2, "task:".into()), (3, "label:".into()), (3, "task:".into()), (4, ": number".into()),],
"{hints:?}"
);
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// vtsls' own commands (#6922): Go to Source Definition opens a library's JavaScript instead
/// of its `.d.ts`, Go to Project Configuration and Open TS Server Log answer with
/// `window/showDocument`, JSDoc `{@link}` in hovers is a `file://…#L1,1` link, and Move to File
+8 -1
Переглянути файл
@@ -147,7 +147,11 @@ impl NotebookDocument {
pub fn from_text(path: PathBuf, text: String) -> IdeResult<Self> {
let text: Arc<str> = text.into();
let (root, prefix, suffix) = Node::parse(text.clone())?;
// An empty file (New File named `x.ipynb`, `touch`) opens as an empty notebook, as in
// PyCharm; it is written as one once edited and saved.
let parsed =
if text.trim_start_matches('\u{feff}').trim().is_empty() { EMPTY_NOTEBOOK.into() } else { text.clone() };
let (root, prefix, suffix) = Node::parse(parsed)?;
validate_notebook(&root)?;
let nodes = root.get("cells").and_then(Node::array).expect("validated cells");
let mut persisted = HashMap::<String, usize>::new();
@@ -365,6 +369,9 @@ fn source(node: &Node) -> IdeResult<String> {
}
}
/// What an empty `.ipynb` file reads as, formatted as Jupyter writes it.
const EMPTY_NOTEBOOK: &str = "{\n \"cells\": [],\n \"metadata\": {},\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n";
fn validate_notebook(root: &Node) -> IdeResult<()> {
if root.members().is_none()
|| uint_field(root, "nbformat") != Some(4)
+23
Переглянути файл
@@ -43,6 +43,29 @@ fn two_code_cells() -> NotebookDocument {
}).to_string())
}
/// New File named `x.ipynb` creates an empty file: it opens as an empty notebook, saving it
/// unchanged leaves it empty, and an edit saves a real notebook.
#[test]
fn an_empty_file_opens_as_an_empty_notebook() {
let dir = tempfile::tempdir().unwrap();
for text in ["", "\n", "\u{feff}"] {
let path = dir.path().join("new.ipynb");
std::fs::write(&path, text).unwrap();
let mut doc = NotebookDocument::load(&path).unwrap();
let snapshot = doc.snapshot();
assert!(snapshot.cells.is_empty() && !snapshot.dirty);
assert_eq!((snapshot.nbformat, snapshot.nbformat_minor), (4, 5));
doc.save().unwrap();
assert_eq!(std::fs::read(&path).unwrap(), text.as_bytes());
apply(&mut doc, NotebookEdit::InsertCell { after: None, cell_type: "code".into() });
doc.save().unwrap();
let saved: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!((saved["nbformat"].clone(), saved["cells"].as_array().unwrap().len()), (json!(4), 1));
assert!(NotebookDocument::load(&path).is_ok());
}
}
#[test]
fn noop_save_preserves_all_bytes_for_utf8_bom_crlf_and_no_final_newline() {
let dir = tempfile::tempdir().unwrap();
+12 -1
Переглянути файл
@@ -64,7 +64,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.19";
pub const API_VERSION: &str = "1.20";
const EPOCH_TICK: Duration = Duration::from_millis(10);
pub(crate) const MAX_TEXT: usize = 1 << 20;
/// The most text, and the most PNG bytes, `ui.read-clipboard` returns.
@@ -87,6 +87,17 @@ pub enum SettingsTarget {
}
pub trait HostApi: Send + Sync {
/// Read only the schema of a connected project table; database.schema was checked.
fn database_table_schema(
&self,
_root: &Path,
_client: Option<&str>,
_table: &crate::PluginDatabaseTableRef,
_cancel: &CancellationToken,
_timeout: Duration,
) -> Result<crate::PluginDatabaseTableSchema, HostError> {
Err(HostError::Invalid("Database schema access is unavailable on this host".into()))
}
/// Creates/replaces this plugin's non-secret project connection settings.
fn database_upsert(&self, root: &Path, source: crate::PluginDataSource) -> Result<(), HostError>;
/// Removes only an owned data source and its credentials.
+44
Переглянути файл
@@ -1166,3 +1166,47 @@ pub struct RunConfigCompletion {
pub replace_start: u32,
pub replace_end: u32,
}
/// Identifies a table in an already connected project data source (API 1.20).
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginDatabaseTableRef {
pub source_id: String,
pub catalog: Option<String>,
pub schema: String,
pub table: String,
}
/// Read-only column metadata. No row values or connection settings.
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginDatabaseColumn {
pub name: String,
pub data_type: String,
pub nullable: bool,
pub default_value: Option<String>,
pub primary_key: bool,
pub comment: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginDatabaseIndex {
pub name: String,
pub unique: bool,
pub columns: Vec<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginDatabaseForeignKey {
pub columns: Vec<String>,
pub referenced_schema: String,
pub referenced_table: String,
pub referenced_columns: Vec<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginDatabaseTableSchema {
pub comment: Option<String>,
pub columns: Vec<PluginDatabaseColumn>,
pub indexes: Vec<PluginDatabaseIndex>,
pub foreign_keys: Vec<PluginDatabaseForeignKey>,
}
+54
Переглянути файл
@@ -3282,6 +3282,60 @@ pub(crate) mod injections_bindings {
}
impl bindings::openidea::plugin::database::Host for StoreData {
fn describe_table(
&mut self,
project: Resource<ProjectRes>,
table: bindings::openidea::plugin::database::TableRef,
) -> Fallible<bindings::openidea::plugin::database::TableSchema> {
if let Err(e) = self.require(Capability::DatabaseSchema) {
return Ok(Err(e));
}
let root = self.table.get(&project)?.root.clone();
let table = crate::PluginDatabaseTableRef {
source_id: table.source_id,
catalog: table.catalog,
schema: table.schema,
table: table.table,
};
let result =
self.host.database_table_schema(&root, self.client(), &table, &self.cancel.token(), self.io_timeout());
if result.is_err() {
self.grant_io_error_grace();
}
use bindings::openidea::plugin::database as db;
Ok(result
.map(|s| db::TableSchema {
comment: s.comment,
columns: s
.columns
.into_iter()
.map(|c| db::ColumnSchema {
name: c.name,
data_type: c.data_type,
nullable: c.nullable,
default_value: c.default_value,
primary_key: c.primary_key,
comment: c.comment,
})
.collect(),
indexes: s
.indexes
.into_iter()
.map(|i| db::IndexSchema { name: i.name, unique: i.unique, columns: i.columns })
.collect(),
foreign_keys: s
.foreign_keys
.into_iter()
.map(|f| db::ForeignKeySchema {
columns: f.columns,
referenced_schema: f.referenced_schema,
referenced_table: f.referenced_table,
referenced_columns: f.referenced_columns,
})
.collect(),
})
.map_err(to_wit))
}
fn upsert_source(
&mut self,
project: Resource<ProjectRes>,
+5 -4
Переглянути файл
@@ -98,7 +98,7 @@ fn the_sdk_carries_the_hosts_wit() {
#[test]
fn the_version_check_runs_compatible_components_and_explains_the_rest() {
let host = v("1.19.0");
let host = v("1.20.0");
for ok in [
"1.0.0",
"1.3.0",
@@ -118,15 +118,16 @@ fn the_version_check_runs_compatible_components_and_explains_the_rest() {
"1.17.0",
"1.18.0",
"1.19.0",
"1.20.0",
"1.0.0-rc.1",
] {
assert_eq!(check_api(&v(ok), &host), Ok(()), "{ok}");
}
let newer = check_api(&v("1.20.0"), &host).unwrap_err();
assert!(newer.contains("1.20") && newer.contains("update OpenIDEA"), "{newer}");
let newer = check_api(&v("1.21.0"), &host).unwrap_err();
assert!(newer.contains("1.21") && 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.19 SDK"), "{older}");
assert!(older.contains("rebuild it with the 1.20 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 @@
8da08e3230812e4f7cf875362c095ac4885c3262636e51b111e95f2fd962e08a
daf3ed46b1e98c6b416c0092a10a02579d2cf97959cedd03df1851a5e76d675d
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
9ebd066471e76d6261ab1b4b1e057a85bfdd9abb9f596149798d573336a6d1af
b54f16ce7e7caf877ea464b50014117fc10f30b761236e5ddcb19ad07254ea13
Бінарний файл не відображається.
Loaded 100 of 643 files, more files were not shown because too many files have changed in this diff. Show more