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

...
Автор SHA1 Повідомлення Дата
l0ng-ai c3e0b8bd58 fix(vcs): stop rescanning the file per hunk when opening large diffs
Opening a working-tree diff from the commit panel computes a key for
every hunk (hunkKeys). Each key called currentHunkText, which rebuilt the
line-start table of the whole file, so a file with many changes cost
hunks x file size: a 9.4 MB JSON with 17,931 changes kept the web view
busy for minutes and froze the window.

rollbackEdit and currentHunkText now take an optional precomputed
lineStarts table. hunkKeys builds it once. The other per-hunk loops pass
theirs too: line-level partial commits (commitSelection), the partial
commit projection, the commit-check rollback fallback, and stage/unstage
from the gutter.
2026-12-01 06:25:35 +08:00
l0ng-ai 1bf29ab3d7 test(typescript): wait for import style changes to reach vtsls in the smoke (#7115)
typescript_import_style failed intermittently on slower CI runners: with autoImportSpecifierExcludeRegexes set, third.ts kept offering alphaHelper for 120 s. settings_set reconfigures the servers in a background task, so the first completion in third.ts could run under the old preferences; tsserver caches that file's module specifiers under a key without autoImportSpecifierExcludeRegexes, and vtsls' per-file configure doesn't clear it, so every retry got the old answer. Each setting change in the test now awaits LspManager::reconfigure before the next completion.
2026-12-01 06:02:57 +08:00
Deng Liuтаdengliu 49b52a8bfa feat(agents): import and fork Copilot sessions (#7111)
Import Sessions now lists Copilot sessions of the project, read from <config>/session-state/<id>/workspace.yaml (COPILOT_HOME or ~/.copilot) and titled by their name or first prompt without reading the whole event log. Importing resumes the session and replays its history (session.getMessages) into the task, and the Copilot shim now supports session/fork through sessions.fork, so Copilot sessions can be forked without changing the source. Imported sessions of every provider load in the background so their history shows before the first message. The plugin docs list copilot among the native fork providers.

Co-authored-by: dengliu <[email protected]>

Co-authored-by: dengliu <[email protected]>
2026-12-01 05:58:56 +08:00
lleviathe 77342b8e71 feat(mcp): ask a background project's confirmations in a project window (#7114)
A tool call needing confirmation in a project served in the background (build_project, execute_run_configuration, http_run_request, destructive plugin tools) failed with "no project window is available" unless brave mode was on. It now asks in the trusted project window focused last, with the usual dialog naming the background project and its path. Requests queue there; the dialog keeps the keyboard focus where it is and answers no key typed outside it, and the Dock icon bounces when the app isn't active. When that window closes, switches project, reloads or loses trust, the request moves to the next trusted project window, within the same 180 s deadline. Tools whose result needs a window (run_command, open_file_in_editor, xdebug_start_debugger_session and the breakpoint tools) refuse in a background project before asking.

Closes #7035

Co-authored-by: lleviathe <[email protected]>

Co-authored-by: lleviathe <[email protected]>
2026-12-01 05:57:12 +08:00
Vadim LazukтаInf1mum 369ff7cec8 fix(editor): fill warning, usage-match and link boxes to the full line height (#7110)
Three inline marks still painted only their font box: the warning lint fill (a flat background-color), the Usages preview match, and the Cmd/Ctrl-hover link, whose pointer cursor stopped at the font so the gap above and below the word showed the I-beam. They now use the inlineBg pattern: the mark grows to the row with padding-block and the fill is a 1lh-capped gradient centred in it; the link only needs the padding. An unnecessary warning still drops the fill, and the active warning keeps it. The usage contrast e2e check reads the fill from the gradient.

Closes #7105, closes #7106, closes #7107

Co-authored-by: Inf1mum <[email protected]>

Co-authored-by: Inf1mum <[email protected]>
2026-12-01 05:49:19 +08:00
solhovoy 4016c410db feat(bookmarks): add toolbar actions and embedded editor preview (#7102)
The Bookmarks tool window gets Rename, Select in Project View, Expand All, Collapse All and an Editor Preview toggle in its header. The preview shows the selected bookmark's or file's code with the bookmark gutter, below the tree when the window is docked at a side and beside it when docked at the bottom; the toggle is remembered. Remove All Bookmarks now asks first, and the bookmark and list rename dialogs get a labelled form with Create/Rename buttons.

Co-authored-by: solhovoy <[email protected]>

Co-authored-by: solhovoy <[email protected]>
2026-12-01 05:44:33 +08:00
lleviathe 3c3d02d7be feat(mcp): list tools on a connection without a project of its own (#7103)
An MCP client started in a folder no project serves got -32001 for tools/list and registered no tools, so it couldn't reach the projects inside even with projectPath. Such a connection (and one naming no folder with zero or several windows open) now lists the tools a trusted project gets; each call still resolves its project, and a tool that writes or runs refuses an untrusted project with the Restricted Mode error before the project loads. initialize tells the agent to pass projectPath in every call.

The stdio bridge picks its IDE process with a new openidea/servesFolder method (falling back to the tools/list probe for older IDEs), keeps the process initialize picked, picks again when processes stop or start, and sends cancellations to every process. Plugin tools list projectPath in their schema and get the call without it when their own schema refuses it.

Closes #7039

Co-authored-by: lleviathe <[email protected]>

Co-authored-by: lleviathe <[email protected]>
2026-12-01 03:53:20 +08:00
NK StudioтаNK-Studio 2f66eb0503 fix(editor): recognize C# using fixes in auto import and imports on paste (#7100)
Add unambiguous imports on the fly and Insert imports on paste pick the import quick fix by its title, but Roslyn (csharp-ls) titles it with the directive itself (using UnityEngine.SceneManagement;), so C# never got a missing using added. Both now also accept a whole using [static] directive title; fully-qualify and Remove unnecessary usings fixes stay ignored.

Co-authored-by: NK-Studio <[email protected]>

Co-authored-by: NK-Studio <[email protected]>
2026-12-01 03:48:45 +08:00
l0ng-ai 63db10a688 fix(vcs): reuse one diff tab with the preview tab turned off (#7108)
Diffs from the version control views reused one tab only through the preview tab, so turning off Opening Policy > Enable preview tab opened every diff in a new tab. Editor kinds can now have their previews granted regardless of that setting (reusesPreviewTab); the diff, combined diff and merge commit diff kinds do, so Commit / Local Changes, the Git Log, shelves and stashes keep one diff tab while project files still open as regular tabs. Pinned and kept diff tabs stay, and activeInput({ previewOnly }) uses the same check so the Git Log's selection-following preview works too.

Fixes #7096
2026-12-01 03:47:32 +08:00
l0ng-ai 1dd3d64781 feat(freemarker): HTML, script and style languages and completion in FreeMarker templates (#7104)
FreeMarker files were highlighted by a stream mode, so markup had no HTML completion and script/style content was plain text. A Lezer grammar now parses the template layer (directives, user-defined directive calls, interpolations, comments, noparse), the first directive fixing the angle or square syntax, and the text between them is mounted as one HTML document: markup nests across directives and <script>/<style> get JavaScript and CSS.

Block directives fold, indent, match their end tags and get their end tag when > is typed; completion offers directives after <#, the open blocks' end tags after </, and built-ins after ?. Comment Block uses <#-- --> ([#-- --] in the square syntax).

Fixes #6906
2026-12-01 03:44:08 +08:00
l0ng-ai 8ac194cf50 fix(plugins): let capabilities.reasons explain capabilities a contribution brings (#7101)
A plugin with [[contributes.javaAgents]] gets java.agent without listing it under [capabilities], so the manifest check rejected a reason for it and the install dialog and Permissions showed only the IDE's description. Manifest::derived_capabilities names the capabilities contributions bring (java.agent from javaAgents, project.read from documentIndexers) and reasons may use those keys too; docs updated.

Fixes #7088
2026-12-01 03:26:09 +08:00
Ivan 3b488a7824 fix(macos): let background project tabs give their web content memory back (#7060)
A background project tab of a native tab group detaches its WKWebView from the window 30 s after it leaves the front, so WebKit frees the hidden page's graphics and caches. The view comes back when the tab is selected through our tab bar, when its window becomes key (Window menu, Close Project) or when AppKit makes it visible by itself; an inactive app's full-screen group waits for activation (#6937).

Every macOS with_webview caller goes through macos::with_web_view, which hands the retained view to a detached tab instead of panicking in wry; titlebar::set_height uses the NSWindow directly. clippy.toml disallows the raw with_webview calls. Covered by BackgroundTabs unit tests and an AppKit test of the synchronous re-attach on the key notification (it no longer asks a never-loaded web view for its process ids, which WebKit asserts on).

Fixes #6938

Co-authored-by: Pecnikas <[email protected]>

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 03:20:08 +08:00
l0ng-ai b5e89aace0 feat(run): show each invocation of a parameterized test in the Run window (#7099)
The JUnit runner and the Gradle test init script report an invocation of a parameterized, repeated or dynamic test with its display name, and the JVM parser puts it under its method node with its own status, output and stack trace; the method shows the aggregate. Rerunning a failed invocation reruns its method.

Fixes #7046
2026-12-01 03:06:11 +08:00
Akbar Husain 81c95b2ab7 perf(lint): clear remaining non-e2e React perf violations (#7093)
Clears the remaining non-e2e React perf lint violations and turns the three rules on outside e2e/ so they can't come back: data-derived keys for diagram edges and deadlock cycles (index keys stay, with a documented suppression, where position is the identity), context values in tests hoisted to constants or memoized, and array/JSX default props replaced with module-level constants.

Co-authored-by: akbar1214 <[email protected]>
2026-12-01 02:59:24 +08:00
LU XIANGRUIтаwildcatDownstairs f7b5cc388c feat(run): debug Python on a WSL run target (#6777)
A Python run configuration on a WSL target can now be debugged: the program starts under the container debugger's bootstrap in the distribution, which waits for the IDE on the distribution's loopback (WSL forwards it), finding the IDE's debugpy and bootstrap through wslpath when the distro has none. Stop ends the debugged process in the distribution, with pkill or, where it is missing, a /proc scan. Other kinds say they can't be debugged in WSL.

Also carries the WSL run target review fixes that neither #6764 nor #6770 included: Maven options naming this machine's files are dropped from remote runs, a failed wsl.exe listing is reported in Run Targets and retried on focus, an unsafe distribution name is cleared and asked for again, a printed path whose .. climbs above its root is refused, and prepare_wsl is built only on Windows.

Verified by the contributor on Windows 11 with WSL 2 (Ubuntu 24.04): a breakpoint is hit and Stop leaves no debug process.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 02:54:14 +08:00
LU XIANGRUIтаwildcatDownstairs 277d0e9d1e feat(python): a Python in WSL as the project interpreter (#6770)
Python > Add Interpreter gets a WSL tab: pick a distribution and a Python in it (a bare python3 is looked up on the distribution's PATH; Windows paths are refused). The project interpreter then runs in the distribution: packages are listed from there, the project's virtualenv inside the distro is read, the language server resolves imports from the distro's site-packages through \\wsl.localhost, and runs go through the WSL run target. Verified by the contributor on Windows 11 with WSL 2 (Ubuntu 24.04).

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 02:38:34 +08:00
LU XIANGRUIтаwildcatDownstairs d6adb7aa40 feat(run): run configurations in a WSL distribution from a Windows project (#6764)
Settings > Run Targets gets a WSL target that lists the installed distributions. A run configuration on it starts locally as wsl.exe -d <distro> --cd <dir> --exec ..., with the project's Windows paths mapped to /mnt/<drive>/..., arguments passed unchanged, environment variables forwarded through WSLENV, and Stop ending the Linux process. Verified by the contributor on Windows 11 with WSL 2 (Ubuntu 24.04), including quoted arguments and Emulate terminal.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 02:21:28 +08:00
l0ng-ai 6e5e482410 test(memory): make the debounce test tolerate a loaded machine (#7098)
memory::tests::a_burst_of_calls_runs_once_after_the_delay failed on a loaded macOS runner: with a 100 ms delay and 20 ms gaps, oversleeping let the debounced call fire before the burst ended. The test now uses a 500 ms delay, checks "nothing ran yet" only when less than the delay has passed since the last call, waits for the run, and asserts exactly one run only when no gap in the burst reached the delay.
2026-12-01 02:20:22 +08:00
solhovoy cc02c2fe40 feat(vcs): show shelved files under their shelf with grouping and diff preview (#7090)
The Shelf tab now lists each shelf's files beneath it in one tree instead of a separate files pane. View Options groups the files by Directory or Module and toggles Show Diff Preview (a side-by-side diff of the selected file, hidden in non-modal commit mode); Expand All / Collapse All work on the groups. File paths show inline, Delete and Cmd+Backspace delete the selected shelf or file, and the Shelve button, already in Local Changes, is gone from this toolbar.

Co-authored-by: solhovoy <[email protected]>
2026-12-01 02:16:33 +08:00
Игорь Тихомиров 74a3f6470a feat(php): add PHPantom as a built-in language server (#7052)
PHPantom (MIT) joins the selectable PHP language servers, with a tools-registry entry for installing it.

textDocument/implementation now sends a client-created workDoneToken for any server; its progress shows as a cancellable task and is retired when the request ends (response, cancel or timeout). A server's TOML can list server-created progress-token prefixes to ignore (ignored-progress-token-prefixes); php.toml uses it for PHPantom 1.1.0, which can leave find_references/goto_implementation progress open after a cancel (PHPantom-dev/phpantom_lsp#603).

Co-authored-by: fenndooscar <[email protected]>
2026-12-01 02:04:13 +08:00
Ivan 4c8c078666 perf(lsp): bound the cache of virtual document text (#7082)
The window-wide cache of lspVirtualDocument results (decompiled classes, library sources, jdt:// documents) kept one entry per document ever shown, hover previews and go-to-definition included, for the window's lifetime. It now keeps the 32 most recently used; an evicted document is fetched again on next use, and a failed fetch is dropped only while it is still the cached one.

Refs #6938

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 02:00:34 +08:00
Ivan e672b14d52 fix(plugins,mcp): stop idle IPC loops in Restricted Mode windows (#7091)
Idle Restricted Mode windows called the backend over 100 times a second. PluginHost::restrict_project announced CommandsChanged even when the project had no plugins to restrict; every window answered with plugin_list, which restricted the untrusted root again. Separately, the MCP editor and problems reporters retried every 300 ms on commands Restricted Mode refuses.

restrict_project now announces only when it restricted something, and the reporters skip untrusted projects and report once trust is granted. Measured over 4 idle windows: invoke calls 115/s -> 0.7/s, CPU per idle minute 12.3 s -> 1.1 s.

Refs #6938

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 01:59:18 +08:00
audichuang c0300f8959 fix(vcs): find a worktree added below the project when its HEAD lands after the watcher's rescan (#7086)
git worktree add writes the worktree's .git file before its gitdir's commondir and HEAD, so a watcher rescan in between found no repository there, and the later .git/worktrees/<id>/HEAD write never triggered another rescan. That HEAD now rescans too while its worktree is unknown and is one a scan would find (Repos::searched, sharing discover's depth, hidden, vendor and skip rules, plus Directory Mappings exclusions).

Co-authored-by: audichuang <[email protected]>
2026-12-01 01:57:06 +08:00
l0ng-ai 11cf9864a1 fix(vcs): guide GitHub HTTPS failures to project account settings (#7061)
A Git Update, Fetch, Push or branch update that fails on an https://github.com remote with "repository not found" or "Authentication failed" now checks the GitHub CLI accounts. When several are signed in, the original Git error is kept and a hint says the effective account may lack access, with a GitHub Settings action that opens the project-scoped account selector. Nothing switches gh's global account, rewrites remotes or retries the operation; other hosts, SSH remotes and network errors are left as they were.
2026-12-01 01:52:43 +08:00
l0ng-ai 04a4d98d68 fix(vcs): open the Log User filter without waiting for every author (#7095)
The Log's User filter popup waited for git log --all to list every author before opening, which takes 8-10 s on a history of 500K+ commits, on every open.

The popup now opens at once with the authors already known (loaded commits plus each repository's last full list). The full list is fetched in the background, reusing a running fetch and a list younger than five minutes, and only Select..., which shows every author, waits for it.

Fixes #7064
2026-12-01 01:44:26 +08:00
l0ng-ai 9a984f64a3 fix(vcs): keep No Merges fast on long pull-request histories (#7094)
With No Merges on, a hidden commit's graph parents are projected onto its nearest shown ancestors. On a pull-request history (M_k = merge(M_k-1, F_k)) each hidden merge projected onto all older features, because the projection of M_k-1 was kept next to F_k although M_k-1 is F_k's own parent. The lists grew with every merge and the first page walked the whole history, so a 500K-commit repository never finished loading.

Before projecting through a hidden commit, parents that are ancestors of another of its parents are dropped (a bounded walk that keeps the parent when unsure). The graph builder and the filtered log view (path, date and author filters share the projection) both apply it.

Fixes #7063
2026-12-01 01:39:39 +08:00
l0ng-ai e35a607556 fix(welcome): expand JetBrains path variables without re-checking the base (#7092)
expand_jetbrains_path re-checked is_absolute after joining a path variable onto the home or IDE config folder. Those folders are already absolute; on Windows the unit test's /home/me home has no drive, so recent::tests::expands_jetbrains_path_variables failed on Rust (windows-latest) since #6979. Only a path without a variable is checked now.
2026-12-01 01:32:47 +08:00
Muuтаmuutot 3fa990fce2 feat(editor): add Render All Doc Comments (#7066)
Adds the Render All Doc Comments action (IDEA id ToggleRenderedDocPresentationForAll, no default shortcut). It flips Editor > Appearance > Render documentation comments globally and clears every open document's per-file rendered-docs override, so all editors follow the new default.

Co-authored-by: muutot <[email protected]>
2026-12-01 01:31:03 +08:00
RuyimgByCN 11e520dedb feat(project-tree): add "Add as Library…" for JARs and library directories (#7077)
Right-clicking a .jar or a folder of jars (such as WEB-INF/lib) in the Project view, or running it from Find Action, opens a Create Library dialog (name, scope, classes) that appends the library to projectStructure.libraries. Collapsed folders are probed briefly before the menu opens. Registered library folders get the library icon and an Open Library Settings entry instead of a duplicate add, External Libraries refreshes when jars inside them are added or removed, and manifest-free Java projects with libraries show the project JDK there.

Library class entries (jar globs, root-relative paths) are parsed once in platform/languageSettings for both the action and the refresh.

Closes #7051

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-01 01:24:16 +08:00
Chris-young42таChris-young42 a0c0b69b4a feat(project-structure): add search and batch folder marking (#7069)
Project Structure gets a search field: sections and module tabs are filtered by English or translated labels, the matching section or Sources/Paths tab opens, and staged edits are kept while searching.

The module folder tree now allows Shift and Ctrl/Cmd selection, and the Mark as buttons mark or unmark all selected folders at once (pressed only when every selected folder already has that role). Long paths in the marked folders pane wrap in narrow windows.

Co-authored-by: Chris-young42 <[email protected]>
2026-12-01 01:14:04 +08:00
RuyimgByCN b89128649f fix(project-structure): show full content root tooltips and enable custom test output path (#7076)
Long content root and library paths in Project Structure were truncated with only a native title attribute, which the tooltip host skips and WKWebView suppresses; they now use verbatim tooltips, and the module Sources tree scrolls horizontally.

Test output path was always disabled, although the builder already compiles tests into the module's testCompilerOutput. It is now editable for a root module not managed by Maven or Gradle. Browse dialogs for output paths resolve relative values against the project root.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-01 01:08:10 +08:00
RuyimgByCN 9973cad74c fix(java): expand JAR directories in Project Structure libraries (#7074)
A Project Structure library whose class root is a folder of jars (such as WebRoot/WEB-INF/lib) was passed through as a bare folder, so jdtls, javac, artifact layouts, External Libraries and the Java launch classpath all missed its jars.

Folder roots and dir/*.jar, dir/**/*.jar globs now expand consistently: jdtls gets a **/*.jar glob, javac gets <dir>/* per folder holding jars, and artifacts, External Libraries and launch classpaths get the individual jars. A folder without jars stays a class folder. The jar walk and glob parsing are shared from ide-core, and the class-root expansion from ide_sdk::libraries::library_class_paths.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-01 01:02:29 +08:00
RuyimgByCN 8cb7a2fe06 fix(tomcat): keep Project Structure WAR and exploded artifacts across prepare (#7073)
Launching Tomcat with a Project Structure artifact in a project without Maven or Gradle failed with 'The built WAR artifact does not exist': the WAR was written inside Tomcat's runtime directory, which tomcat::prepare deletes and recreates. Project Structure artifacts are now built to their configured output (compile::artifact_file), exploded artifacts are laid out directly without packing and unpacking a WAR, Tomcat deploys a recorded exploded directory as is, and the artifact list falls back to Project Structure web artifacts when there is no build tool. Refs #404.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-01 00:57:16 +08:00
faysouтаfaysou 5d867d7d2d fix(markdown): preview Git repository versions (#7067)
Open Repository Version opened Markdown in a read-only tab that skipped the Markdown wrapper, so a committed README had no preview. Editor wrappers can now match virtual documents (matchesVirtual), and the Markdown wrapper matches Git revisions of Markdown files: those tabs get Editor Only, Editor and Preview and Preview Only, with the preview rendering the committed text and the source staying read-only.

Co-authored-by: faysou <[email protected]>
2026-12-01 00:54:08 +08:00
Ivan 70f6678271 perf(memory): release freed heap pages after closing a project or tabs (#7072)
Closing a project or a batch of documents now calls release_free_pages once, 2 s after the last close, on a background thread. On macOS the freed pages are already reclaimable, so the footprint change is within noise; on Linux malloc_trim can return pages glibc would keep resident (not measured).

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 00:51:07 +08:00
lleviathe 530388a79d fix(mcp): pick the innermost project across windows and background projects (#7085)
A call naming a folder went to the innermost project open in a window, and the background policy was asked only for folders outside every open project. With a window on a parent folder, a call naming a nested trusted repository served in the background read the parent's files instead, so the answer depended on which windows were open. resolve_project now also asks the policy for a path below the innermost open root, passing that root so only folders strictly inside it are considered and nothing else is looked up on disk. A path at an open root, or one no nested folder serves, stays with the window and loads nothing; a remote window's root answers nothing locally. The MCP guide (English and Chinese) describes how the project is picked. Closes #7040.

Co-authored-by: lleviathe <[email protected]>
2026-12-01 00:49:59 +08:00
Bake Yam 98cb85003a fix(notebook): let commands find a cell document (#7071)
A notebook's cells are documents of the language servers only, never of the editor's document table, so commands that read that table failed on a cell: Reformat Code answered 'document is not open' and Alt+Enter offered no import for an installed package's name. Formatting and the Python import quick fix now fall back to the LSP manager's cell buffer (new LspManager::cell_text), and the formatter is given the notebook path with a .py extension so Ruff parses the cell as Python rather than notebook JSON. Part of #5846 (items 1 and 3).

Co-authored-by: Renjiankang <[email protected]>
2026-12-01 00:46:37 +08:00
l0ng-ai dfae46868c test(lsp): compare server roots without cloning into a slice (#7087)
The Xcode C-family test added in #7023 built a one-element array by cloning the root, which clippy's cloned_ref_to_slice_refs rejects under -D warnings, so the three Rust CI jobs failed to compile ide-lsp's mock_server test. It now compares against std::slice::from_ref.
2026-12-01 00:45:21 +08:00
faysouтаfaysou 635da15486 fix(markdown): follow explicit preview anchors (#7070)
A Markdown link such as #ref-1 can point to an explicit HTML id in the document, but the preview only looked for the generated heading id, so a citation link jumped to a heading with the same slug or nowhere. The preview now tries the exact id first and falls back to the generated heading id.

Co-authored-by: faysou <[email protected]>
2026-11-30 23:56:35 +08:00
lleviathe 249d0526f0 fix(settings): fill the row with the background folders list (#7078)
In Settings › Agents › IDE MCP Server › Background Projects the Folders list was 116 px wide while empty and grew with its longest path up to 480 px. The wrapper that turns it off in mode Off kept it from being the row's flex item; the wrapper now fills the row and the list passes fullWidth like the other stacked lists.

Co-authored-by: lleviathe <[email protected]>
2026-11-30 23:55:06 +08:00
Игорь Тихомиров 181bbdfdc2 fix(remote): clear background tasks when the backend changes (#7068)
After a remote backend disconnected or was replaced, its progress rows stayed in the window because the old connection could no longer deliver completion events. When the connection is lost or the session changes, the window now drops the backend's numeric task IDs, their pending delayed updates and the indexing row, and keeps client-side tasks.

Co-authored-by: fenndooscar <[email protected]>
2026-11-30 23:53:33 +08:00
l0ng-ai c7172184ad feat(editor): choose the styles Cycle Identifier Case goes through (#7081)
Cycle Identifier Case always went through all five styles. Settings › Editor › General › Smart Keys gets a Cycle Identifier Case group with one checkbox per style (snake_case, SCREAMING_SNAKE_CASE, kebab-case, camelCase, PascalCase), all on by default. The action skips the styles that are off and keeps starting from the style the name is written in, even when that one is off. Fixes #6972.
2026-11-30 23:50:27 +08:00
Muuтаmuutot 8380732e60 fix(vcs): split global and per-tab Git Log options (#6931)
All Git Log options were one store, so changing the sort or first-parent view in one log tab or File History tab changed every other tab, and switching tabs overwrote the global choices. Application-level properties (compact refs, tag names, labels on the left, commit date, author/date/hash/signature/checks columns and column order, diff preview and its location, changes from parents) are now saved globally and shared across tabs and windows. Graph options, long edges, highlighters, details and root visibility, text filters and column widths stay per tab and are restored with the log session. Tab switches and cross-window storage updates no longer overwrite the global set.

Co-authored-by: muutot <[email protected]>
2026-11-30 23:25:11 +08:00
Muuтаmuutot 42fcbb336a feat(settings): copy the selected Settings page path (#7037)
Adds Copy Settings Path (CopySettingsPath alias). It copies the current Settings page as 'Settings | Group | Page', built from the same translated page-tree breadcrumb the dialog header shows. The page tree's context menu offers it for the right-clicked page.

Co-authored-by: muutot <[email protected]>
2026-11-30 23:17:46 +08:00
Muuтаmuutot 93a450aa8c feat(editor): toggle breadcrumbs for the active editor (#7034)
Adds the Show Breadcrumbs toggle action (EditorToggleShowBreadcrumbs alias). It forces breadcrumbs on or off for the active editor tab only, ahead of the global setting and the per-language disabled list, without changing either. The override lives as long as the tab: it is dropped when the tab closes or the editor session stops, and split editors of one file keep their own.

Co-authored-by: muutot <[email protected]>
2026-11-30 23:12:21 +08:00
Muuтаmuutot 8e0a36fb1c feat(tree): center the focused selection like IDEA (#7025)
Adds Scroll Tree to Center for the focused tree, reachable from Find Action and the ScrollTreeToCenter IDEA action alias. It centers the selected lead row without changing the selection, does nothing with an empty selection, and is disabled once the tree loses focus. Every Tree registers for focused-action lookup, so it works in tool windows, Settings and tree dialogs alike.

Co-authored-by: muutot <[email protected]>
2026-11-30 23:07:15 +08:00
l0ng-ai 11da3ecce7 fix(welcome): flatten the project switcher list (#7009)
The title-bar project switcher keeps only Open Projects and Recent Projects, as one flat list ordered by recency, without host or custom group headings. Local and remote projects share one row layout; remote rows keep the avatar badge and show host:path on the path line. Section headings line up with the project badges. The Welcome screen and the standalone Recent Projects popup keep their grouping.
2026-11-30 23:02:06 +08:00
l0ng-ai 53d295d785 fix(agents): align task controls and questions with workbench styling (#7015)
The agent composer, recovery notices and question forms used one-off styles. Skills and agent Resume get dedicated monochrome icons that inherit the menu, toolbar or button colour, leaving the editor intention bulb and debugger Resume icons unchanged. Interrupted, network-retry and archived notices share one inset geometry with warning colours from the theme, and question forms use the standard control styles.
2026-11-30 23:00:32 +08:00
l0ng-ai 9f1380cf04 fix(agents): edit user messages in place without layout jump (#7007)
Clicking Edit on a user message replaced the bubble with a full-width, left-aligned textarea and dropped the timestamp and You label, so the text jumped. Editing now stays inside the user message container: the header is kept, the editor takes the measured bubble width (bounded by the bubble max-width) with the same padding, and the actions sit under it.
2026-11-30 22:54:56 +08:00
l0ng-ai 338e1a5b02 fix(agents): keep active and pinned task order stable (#7002)
Active status groups and active tasks in custom groups were ordered by updatedMs, so concurrent turns, status changes, renames and per-task MCP/skill/memory overrides kept reshuffling the list. They now sort by creation time, newest first, and Pinned keeps its pinned order including manual drag overrides. Renaming a task or changing its overrides no longer bumps updated_ms.
2026-11-30 22:52:26 +08:00
l0ng-ai 092cde1319 fix(agents): prevent native context menu on conversation images (#6995)
Right-clicking a conversation image thumbnail or its full-size preview showed the WebView's native image menu (Open Image in New Window, Download Image, Copy Image). Both contextmenu handlers stopped propagation without preventing the default action; they now call preventDefault as well.
2026-11-30 22:50:39 +08:00
LU XIANGRUIтаwildcatDownstairs fc1e1838ca feat(run): run Xcode apps on a connected iPhone or iPad (#7056)
The Xcode run destination chooser lists paired iPhones and iPads from devicectl under a Devices header, marking ones that are not connected or have Developer Mode off. Running on a device stops before building when the device is not ready or the app would be unsigned (CODE_SIGNING_ALLOWED = NO, or automatic signing without a team), and otherwise builds with -allowProvisioningUpdates, installs with devicectl and launches with --console so output shows in the Run console and Stop ends the app. Scheme environment goes through DEVICECTL_CHILD_*, and a failed launch adds an unlock hint after devicectl's error. Debugging on a device is not supported yet. Install and launch on real hardware were exercised with a stubbed xcrun only.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 22:45:00 +08:00
solhovoy 9a9a536525 feat(bookmarks): show a tooltip on gutter bookmarks, update the icon and add Rename Bookmark to context menu (#7057)
Hovering a bookmark in the editor gutter shows its description, or the line text when it has none, and the marker carries the same text as its accessible label. The plain marker uses the shared filled bookmark icon at 13px instead of a custom outline. The gutter context menu on a bookmarked line offers Rename Bookmark…, which opens the bookmark description editor, next to Delete Bookmark.

Co-authored-by: solhovoy <[email protected]>
2026-11-30 22:39:04 +08:00
LU XIANGRUIтаwildcatDownstairs 2d7928374e fix(ui): keep list and popup match highlights off the editor scheme's search colour (#7045)
Matched characters in Search Everywhere and every chooser built on HighlightedText used --bg-search-match, which editor colour schemes rewrite for their Search result attribute (Darcula: dark green), so the popup highlight turned dark green instead of the SearchMatch gold. Lists now read new --bg-list-match / --fg-list-match tokens set per theme (dark, light, high contrast, palette themes) and mapped from IntelliJ theme SearchMatch keys; they are not scheme variables, so applying a colour scheme leaves them alone. In-editor search marks and code previews still follow the scheme. The Harbor Night template and the theme token docs include the new tokens.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 22:18:41 +08:00
audichuang 58eb5ae667 fix(network): route plugin WebSockets and the MCP probe through the IDE proxy (#7062)
The plugin WebSocket API opened a direct socket and the MCP server probe built a bare reqwest client, so both ignored the IDE's proxy settings (Manual and the macOS PAC). Plugin WebSockets now open their TCP stream through ide_http::tunnel; loopback stays direct in every mode, and a proxy the tunnel cannot speak to (SOCKS, https://) keeps the previous direct connection. The tunnel's reason, such as a proxy that needs a login, is part of the failure message. The MCP probe uses the shared ide_http client builder and sets the MCP headers and 12 s limit per request, with protocol headers taking precedence over configured ones. The tunnel also no longer double-brackets IPv6 literals ([[::1]]:port), which broke the Jupyter kernel channels for IPv6 hosts.

Co-authored-by: audichuang <[email protected]>
2026-11-30 22:12:37 +08:00
Игорь Тихомиров 0698ebb9b0 fix(php): check Composer dependencies from the project owning vendor files (#7053)
A file inside an installed package under vendor/ (or a custom config.vendor-dir) has its own composer.json, so the dependency check treated the package as a separate Composer project and reported it as not installed. The check now walks from the content root inward and attributes a file to the outermost project whose vendor directory contains it; nested projects outside vendor still use their own manifest.

Co-authored-by: fenndooscar <[email protected]>
2026-11-30 22:09:31 +08:00
l0ng-ai 647e564127 fix(ui): align descriptive columns in option pickers (#7032)
Option descriptions in pickers such as Effort Level started at different horizontal positions because each virtualized row sized its own label. The shared select can now align descriptions in one column sized from the widest rendered label, capped for narrow menus and re-measured when fonts change; agent effort, model and configuration pickers, agent defaults, task isolation and Git fetch tag modes use it.
2026-11-30 22:06:17 +08:00
l0ng-ai edd2e90b9b feat(editor): colour Vue component tags apart from HTML elements (#7059)
Component tags in Vue templates (<Icon>, <el-input>) had the same colour as HTML elements. PascalCase or hyphenated tag names now use a new --syn-custom-tag token, the Custom tag name colour: #2fbaa3 in Islands Dark and #b21dbf in Islands Light, with values for high contrast, the palette themes and Harbor Night; other themes fall back to the tag colour.

Fixes #6894
2026-11-30 21:59:52 +08:00
nako-ruruтаnako-ruru 5bfefff5e1 feat(jni): navigate between Java native methods and C++ JNI implementations (#7020)
Go to Declaration on a Java native method opens its Java_<mangled name> implementation in C/C++ files, and on such a function goes back to the native declaration, with a chooser for several targets. Symbols come from the project index, with a text search as fallback; JNI names are mangled and unmangled per the JNI spec (escapes, nested classes, overload signatures). Contributed definition providers may now answer asynchronously.

Co-authored-by: nako-ruru <[email protected]>
2026-11-30 21:45:44 +08:00
LU XIANGRUIтаwildcatDownstairs 49097bf5c0 feat(swift): show SwiftLint findings as diagnostics (#7029)
Swift files below a .swiftlint.yml are linted with swiftlint lint --reporter json: an opened or saved file by its path (so excluded paths and nested configs apply), an edited buffer through stdin. Findings show in the editor and Problems with severity and rule id. SwiftLint joins the tool registry as an installable CLI under Swift; a missing swiftlint is reported once, and nothing runs in Restricted Mode.

Closes #7028

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 21:39:53 +08:00
LU XIANGRUIтаwildcatDownstairs 09a44bebbe feat(lsp): serve C-family files of Xcode projects through sourcekit-lsp (#7023)
In an Xcode project plain clangd finds no compile flags, so headers on the target's search paths and the generated <Module>-Swift.h were not found. C, C++, Objective-C and Objective-C++ now list sourcekit-lsp before clangd with require-root-marker on buildServer.json and replaces clangd: with an Xcode BSP config sourcekit-lsp serves them with the build server's flags; without one, or without sourcekit-lsp, clangd serves as before.

Closes #7022

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 21:32:00 +08:00
LU XIANGRUIтаwildcatDownstairs 7237a37104 feat(language): bundle the Objective-C tree-sitter grammar for outline, folding and symbols (#7027)
Bundles tree-sitter-objc (MIT) with an outline query for Objective-C and Objective-C++: @interface/@implementation/@protocol blocks, categories, methods named by selector, properties, instance variables, C declarations and #pragma mark labels, so the Structure view, folding and the symbol index work for .m and .mm files. The built-in syntax-error diagnostics skip both languages, since the grammar misreads Apple's macros and C++.

Closes #7026

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 21:29:33 +08:00
LU XIANGRUIтаwildcatDownstairs c864cec32f feat(languages): recognize Apple entitlements, privacy manifests, String Catalogs, xcconfig and .strings files (#7021)
.entitlements and .xcprivacy open as XML property lists and .xcstrings as JSON; .xcconfig and .strings get small language definitions that use the C mode for comments, #include and quoted strings. Each gets a matching file icon.

Closes #7018

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 21:25:40 +08:00
l0ng-ai f7f2efaace feat(debugger): evaluate the expression of an operator on hover and Quick Evaluate (#7055)
Hovering or Alt-clicking an operator while suspended evaluated nothing, because only identifiers, member chains and calls were taken. An operator now gives the expression it belongs to, from the syntax tree: && gives a > 1 && !flag, > gives a > 1, ! gives !flag. A hover leaves out expressions with calls, increments or assignments, which Quick Evaluate still evaluates; an identifier is still just the identifier.

Fixes #7000
2026-11-30 21:19:38 +08:00
l0ng-ai e8cb141d86 fix(plugins): activate plugins whose activation event fired before they loaded (#7054)
A remote project's server receives the desktop's plugin packages after the window has opened its files, so on-language:twig reached the server before the Twig plugin was installed there and was lost; the plugin stayed inactive and Twig files got no highlighting or completion. The same happened locally when a plugin was installed with a matching file already open. The host now remembers the language, file and view activation events fired so far (bounded) and activates a plugin that loads later if one matches, and the window reports on-language again when the active file's language changes.

Fixes #7014
2026-11-30 21:16:47 +08:00
l0ng-ai 3eb6933644 fix(find): keep the usages popup size loader private and fix a knip import (#7049)
#7048 exported the size loader only its own file uses, and its e2e test imported usages.ts from a literal path; knip reported both. Unexport the loader and import through a variable like the other spec in the file.
2026-11-30 21:06:50 +08:00
l0ng-ai 72669a04c2 fix(find): make the Show Usages popup resizable and remember its size (#7048)
The usages popup had a fixed width and a height derived from its row count, so it could not be enlarged on any platform. It now resizes from its right and bottom edges and corner, the list takes the added height, and the size is remembered for the next time it opens.

Fixes #6999
2026-11-30 21:05:36 +08:00
audichuang 0b9c675172 test(mcp): stop agent commands only once they run, not while the login shell reads its profile (#7041)
The agent-commands MCP test stopped and interrupted 'sleep 30' right after run_command returned with timeout 0, while the login shell could still be reading its profile; a profile command that handles SIGINT lets the shell go on to run the command, leaving the tab stopping past the 10 s wait. Both stops now wait for the command to print 'ready' and assert it is running first.

Co-authored-by: audichuang <[email protected]>
2026-11-30 20:58:49 +08:00
Chris-young42таChris-young42 5188a34e3d fix(java): hot swap Gradle applications without resources (#7044)
Gradle's processResources succeeds with NO-SOURCE when a project has no resources and never creates its output directory, so Update Application stopped before asking the debugger to reload classes. A missing output directory now counts as an empty resource set, and resources an earlier update copied are removed.

Refs #6977

Co-authored-by: Chris-young42 <[email protected]>
2026-11-30 20:56:38 +08:00
Qslia 8d26a9b483 fix(notebook): respect editor tab size (#7043)
Notebook cell editors used CodeMirror's default indent of 4 regardless of settings. Cells now take the Python (code cells) or Markdown Code Style, falling back to the editor tab size, through an indent compartment that is reconfigured in place when settings change, so the cell editor is not rebuilt.

Co-authored-by: qslia <[email protected]>
2026-11-30 20:55:53 +08:00
LU XIANGRUIтаwildcatDownstairs 267a61c581 feat(coverage): run Xcode tests with coverage (#6944)
Run with Coverage is offered for xcode-test configurations: it adds -enableCodeCoverage YES and names the run's result bundle, which xcode::prepare_test uses instead of its own, so there is still one test run and one bundle. Afterwards xcrun xccov view --report and --archive feed the shared coverage accumulator: files compiled only by .xctest targets, files outside the project and DerivedData/.build are left out, resolved paths map back to the project root, and lines with a missed subrange are partial.

Closes #6941

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 20:53:41 +08:00
LU XIANGRUIтаwildcatDownstairs 21dfa8dd10 feat(xcode): build CocoaPods projects through their workspace and run pod install/update (#6957)
In a project with a Podfile the app project's schemes are built and tested through the .xcworkspace that pod install writes (it has no schemes of its own), and Pods/ gets no run configurations. Pod Install and Pod Update run in the Run tool window from Find Action, Build > Xcode and a Podfile's context menu; afterwards configurations are detected again and an xcode-build-server buildServer.json is regenerated for the workspace. Opening a project whose Pods/Manifest.lock is missing or differs from Podfile.lock offers Pod Install.

Closes #6956

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 20:49:53 +08:00
LU XIANGRUIтаwildcatDownstairs 0cfabdbbbd feat(swift): choose the Xcode a project uses and pass it to its tools as DEVELOPER_DIR (#6964)
Settings > Languages > Swift gets an Xcode field (empty = the xcode-select one). For a trusted project the chosen Xcode.app or Contents/Developer becomes DEVELOPER_DIR in the project environment, so sourcekit-lsp, xcodebuild, xcrun, simulators, debug adapters and terminals use it; it overrides a DEVELOPER_DIR from .envrc and is not applied to untrusted projects or LightEdit.

Closes #6963

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 20:43:48 +08:00
l0ng-ai 485d7bf99d test(vim): count Select in Project View as a known action (#7042)
#7011 mapped IDEA's SelectInProjectView to navigate.selectInProjectView, a registered action with no default shortcut in any preset, so the rc.test.ts :action id check failed on main. List it with the other unbound actions.
2026-11-30 20:40:00 +08:00
Anka Tamaтаxirf 53a1e9255e fix(vcs): reopen the repository after its volume was remounted (#6949)
The cached gitoxide handle kept pack mappings from the old mount; after a remount with the same device, inodes and mtimes it was reused and reading it raised SIGBUS. The cache now detects the remount and reopens the repository. A volume lost in the middle of a git operation is not covered.

Refs #6948

Co-authored-by: xirf <[email protected]>
2026-11-30 20:27:43 +08:00
audichuang 40ab249cb8 fix(http): route WebSocket tunnels through the macOS PAC in Auto mode (#6939)
In Auto mode the TCP/CONNECT tunnel used for WebSockets resolved the proxy with the system matcher only, so a macOS PAC script was ignored. It now asks the PAC resolver first on a blocking thread and falls back to the matcher when there is no PAC or an env proxy is set.

Co-authored-by: audichuang <[email protected]>
2026-11-30 20:27:28 +08:00
LU XIANGRUIтаwildcatDownstairs 9da3d6d9b5 feat(typescript): Go to Source Definition, Project Configuration, Move to File and TS Server log through vtsls (#6935)
Five vtsls commands, run through workspace/executeCommand on a vtsls server that advertises them (other TypeScript servers report that vtsls is needed). Go to Source Definition opens the JavaScript implementation instead of the .d.ts; Go to Project Configuration opens the file's tsconfig.json or jsconfig.json; Move to File appears in Refactor > Move and the intention menu, offering tsserver's suggested target files and Choose File, and applies the move with its import updates as one workspace edit; Open TS Server Log offers to turn on logging through the new languages.typescript.tsserverLog setting, which restarts vtsls, and then opens the log.

Closes #6922

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 20:24:55 +08:00
l0ng-ai 0df7cb1da2 fix(keymap): list Select Opened File in the VS Code preset (#7038)
project.selectOpenedFile (#7011) was added to the IntelliJ presets only, so the keymap test that the VS Code preset covers every IntelliJ action id failed on main.
2026-11-30 20:23:48 +08:00
LU XIANGRUIтаwildcatDownstairs ee9b50179e feat(welcome): import recent projects and groups from a JetBrains IDE (#6979)
Import Recent Projects from JetBrains IDE (Welcome screen more menu, File > Manage IDE Settings) reads the IDE's options/recentProjects.xml and merges its recent projects and project groups into OpenIDEA's. Entries keep their custom or display name and the later of their open and activation times; hidden (LightEdit) entries are skipped, $USER_HOME$ and $APPLICATION_CONFIG_DIR$ are expanded, and projects whose folder is gone are skipped and counted. Existing entries and groups are kept, a taken group name gets a number, and importing twice adds nothing. Import Settings from JetBrains IDE lists the recent projects as a row of its confirmation and merges them too.

Closes #6970

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 20:15:11 +08:00
Muuтаmuutot baab92c804 feat(vcs): create patches from selected historical files (#6981)
Git Log and File History changed files get Create Patch and Copy as Patch to Clipboard, in the toolbar and the context menu. Only the selected repository-relative paths are exported, as path-filtered revision diffs with Git's empty tree on the missing side of additions and deletions and both names for renames. The existing patch dialog, base directory defaults, reverse option and clipboard flow are reused; empty, malformed, no-op, mixed-repository and external-repository selections are disabled.

Co-authored-by: muutot <[email protected]>
2026-11-30 20:08:11 +08:00
l0ng-ai 2b7a18ffd7 fix(search): start Find in Files from the selection in its preview (#7033)
Find in Files and Search Everywhere took the selection only from the active editor tab, so text selected in the Find in Files preview (or another focused editor, such as a diff pane) was ignored when the action ran again. The focused editor's selection now comes first, then the active editor's.

Fixes #6992
2026-11-30 20:04:14 +08:00
Muuтаmuutot f47a83828c feat(structure): temporarily enable filters to find matches (#6934)
With Narrow down on typing on, a File Structure query that matches nothing now turns on the unchecked filters (Show fields, Show non-public, Show inherited members) one at a time until a match appears. Filters enabled this way are restored as the query gets shorter and when the popup closes, and are never saved; a checkbox the user changes by hand keeps its new state, and the cascade stops right after a backspace restores a filter.

Co-authored-by: muutot <[email protected]>
2026-11-30 19:58:05 +08:00
薛纪克таxuejike 4d5ee2d01c feat(agents): drag and delete the whole task list selection (#6933)
In the Agents task list, dragging a row of a multi-selection moves every selected task (into a group, Pinned, a status group, or before or after a task, keeping their order), and Delete deletes the selection while the list has focus. Tree collapsed the selection to the pressed row on mouse down, before a drag could start; a press on a selected row now narrows the selection only on a release without movement. agents.deleteTasks gets a list-focus key binding like agents.archiveTasks, and a click or arrow key opens the session without taking focus from the list; Enter and double-click still focus it.

Closes #6932

Co-authored-by: xuejike <[email protected]>
2026-11-30 19:56:24 +08:00
l0ng-ai 2ecb44098a fix(debugger): drop lldb-dap pseudo paths on Windows too (#7030)
A referenced source's pseudo path such as /usr/lib/swift/libswiftCore.dylib`swift_willThrow was kept on Windows, where a path with a root but no drive is not absolute, so frames_drop_pseudo_paths_of_referenced_sources failed on Rust (windows-latest) since #6961. A rooted path now counts.
2026-11-30 19:48:37 +08:00
Mollo-i b1039bc175 feat(search): select Search Everywhere results in the Project view (#6955)
File, symbol and text results in Search Everywhere get Select in Project View, in the Alt+Enter menu and in a new right-click menu on the row: it closes the popup and selects the result in the Project tool window. This helps with files that open in another application, such as a .doc, where choosing the result leaves no trace of where the file lives. The item is offered only for paths inside the project. One item list now feeds both menus, and Open to the Side is disabled for folders.

Co-authored-by: Greenker <[email protected]>
2026-11-30 19:43:10 +08:00
薛纪克таxuejike 182c7c1dbb feat(editor): double-click the empty tab strip to maximize the editor (#6969)
A double click on the empty part of an editor tab strip (not on a tab, a button or trailing content) now maximizes the editor by hiding all tool windows, the same as a double click on a regular tab; doing it again restores them. Tabs gets an onBlankDoubleClick callback that fires only for the strip itself or its scroller.

Closes #6968

Co-authored-by: xuejike <[email protected]>
2026-11-30 19:42:00 +08:00
l0ng-ai c8dc613485 fix(projects): offer New Tab when opening a remote project or from a remote window (#7017)
The Open Project prompt gated Attach and New Tab on one flag that required a local project in a local window, so opening an SSH/WSL project, or any project from a remote window, offered only New Window and This Window, and "Open project in: tab" fell back to a new window. Attach still needs a local project in a local window, but a project tab is a window of its own joined to this window's group, so it now applies whenever this window has a project: a remote project opens in a new window that joins the group.

Fixes #6923
2026-11-30 18:36:46 +08:00
audichuang 88a6bbca14 perf(vcs): run Git outside the log index lock so commit details and one-commit queries do not wait for a history walk (#7006)
history::log held the log index lock for its whole run, so every Git subprocess it started (file history, path selection, range ids, rev-list, the --grep text filter) ran under the lock, and commit details plus the one-commit queries behind inline blame waited for the whole walk. The lock is now taken per phase: Git runs unlocked and only in-memory work holds the guard. update_head_reachable runs under the guard that builds the rows, and the shared nodes are used only when they were built for the query's shallow set, rebuilt otherwise, so a query stays on one snapshot while others run in between.

Co-authored-by: audichuang <[email protected]>
2026-11-30 18:32:37 +08:00
Ivan b9e555300f fix(macos): defer moving a full-screen tab out of its group until the app is active (#6997)
Close Project on a tab of a native full-screen group moves the tab into a window, and so a full-screen Space, of its own. While the app is inactive, AppKit's enter-full-screen transition for that Space crashes in SLSWindowServerClientSpaceAddWindowsAndRemoveFromSpaces as soon as the web view draws its next frame, taking every project window with it. Detaching such a tab is now deferred: the tab stays in its group (showing Welcome) and moves to its own Space when the app is next activated. Foreground closes and windowed groups detach immediately as before.

Fixes #6937

Co-authored-by: Pecnikas <[email protected]>
2026-11-30 18:30:57 +08:00
l0ng-ai 7ff223001b fix(fonts): keep Latin text monospaced when the chosen font isn't installed (#7013)
With a fallback font set and a primary family that isn't installed, every glyph came from the fallback. A CJK fallback such as PingFang SC has proportional Latin letters, and the terminal sized its cells for the widest of them, so text came out spread apart. Once the native font catalog shows the family is missing, the bundled JetBrains Mono now stands in for it ahead of the fallback, which still covers the glyphs it lacks. Applies to every monospace stack built from the editor or terminal font settings.

Fixes #6974
2026-11-30 18:25:17 +08:00
l0ng-ai cc9279a6d6 fix(editor): indent Slint element blocks by their braces (#7012)
Slint borrows the C mode for highlighting until slint-lsp's semantic tokens arrive, and Enter used that mode's statement indentation: after a child element's closing brace the next line went back to column 0, and nested blocks below it opened one level short. Slint now uses the brace-based fallback indentation even though a highlighting mode is loaded. No other language with a borrowed mode has this mismatch.

Fixes #6976
2026-11-30 18:22:26 +08:00
l0ng-ai 1cfbb24b31 fix(project-tree): add Select Opened File as a Project View action for the keymap (#7011)
The keymap listed "Select Opened File" only as the Database view action, so a shortcut assigned to it revealed the file in the Database view and did nothing in a project without data sources. Like IDEA's SelectOpenedFileInProjectView, the Project view now has its own Select Opened File action (the toolbar button runs it), and imported IDEA keymaps map SelectOpenedFileInProjectView and SelectInProjectView.

Fixes #6978
2026-11-30 18:18:33 +08:00
l0ng-ai a8a0cdb315 fix(plugins): load precompiled plugin components in the signed macOS app (#7010)
compile_cached loaded the cached .cwasm with Component::deserialize_file, which maps the file and makes its pages executable; the hardened runtime of the signed app refuses that, so every activation discarded the cache and compiled the plugin again. The file is now read into memory and deserialized from the bytes. A new test checks the cache is hit; signed with the app entitlements it fails with the old code.

Refs #6954
2026-11-30 18:16:20 +08:00
l0ng-ai 8ab776ada6 fix(keymap): import an Emacs-based IDEA keymap on top of $default, not macOS (#7008)
presetOf picked the macOS preset for any parent whose name contains "mac", including "Emacs", so a keymap derived from IDEA's Emacs keymap was imported as based on macOS. The match is now on the word (Mac OS X, macOS), and Emacs and its copies map to the $default preset they inherit in IDEA.

Refs #6896
2026-11-30 18:14:01 +08:00
466 змінених файлів з 19459 додано та 2177 видалено

No files matched your search

+1
Переглянути файл
@@ -15,6 +15,7 @@
"src/editor/core/cm/jsp/parser*.ts",
"src/editor/core/cm/astro/parser*.ts",
"src/editor/core/cm/django/parser*.ts",
"src/editor/core/cm/freemarker/parser*.ts",
"plugins/themes.md",
"pnpm-lock.yaml",
"**/*.toml",
+4 -1
Переглянути файл
@@ -152,7 +152,10 @@
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
"excludeFiles": ["e2e/**"],
"rules": {
"no-await-in-loop": "error"
"no-await-in-loop": "error",
"react/no-array-index-key": "error",
"react/jsx-no-constructed-context-values": "error",
"react/no-object-type-as-default-prop": "error"
}
}
]
Створено
+12
Переглянути файл
@@ -4684,6 +4684,7 @@ dependencies = [
"tree-sitter-make",
"tree-sitter-md",
"tree-sitter-nix",
"tree-sitter-objc",
"tree-sitter-ocaml",
"tree-sitter-php",
"tree-sitter-prisma-io",
@@ -5116,6 +5117,7 @@ dependencies = [
"ide-text",
"ide-vfs",
"parking_lot 0.12.5",
"quick-xml 0.42.0",
"semver",
"serde",
"serde_json",
@@ -10641,6 +10643,16 @@ dependencies = [
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-objc"
version = "3.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ca8bb556423fc176f0535e79d525f783a6684d3c9da81bf9d905303c129e1d2"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-ocaml"
version = "0.26.0"
+131 -3
Переглянути файл
@@ -2,9 +2,10 @@
//! scanned so they can be listed and imported as tasks instead of re-explained (#312).
//!
//! Only the native providers keep transcripts on disk in a readable form: Claude Code
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`) and Codex
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`), Codex
//! (`<home>/.codex/sessions/**`, rollout files with a `session_meta` line, named in
//! `<home>/.codex/session_index.jsonl`).
//! `<home>/.codex/session_index.jsonl`), and Copilot
//! (`<config>/session-state/<id>/workspace.yaml` plus `events.jsonl`).
use super::native::claude::history;
use serde::Serialize;
@@ -17,7 +18,7 @@ use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExternalSession {
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`).
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`, `copilot`).
pub provider: String,
/// The id resuming it names (`--resume`, `thread/resume`).
pub session_id: String,
@@ -246,6 +247,88 @@ pub fn codex_sessions(codex_home: &Path, root: &Path) -> Vec<ExternalSession> {
sessions
}
/// One scalar at the root of Copilot's `workspace.yaml`.
///
/// Copilot writes a flat mapping of scalar values. Most values are plain, while names can
/// be JSON-compatible double-quoted YAML strings (including `\n`).
fn yaml_scalar(line: &str) -> Option<(String, String)> {
let (key, raw) = line.split_once(':')?;
let key = key.trim();
let raw = raw.trim();
if key.is_empty() || raw.is_empty() || line.starts_with(char::is_whitespace) {
return None;
}
let value = if raw.starts_with('"') {
serde_json::from_str(raw).unwrap_or_else(|_| raw.trim_matches('"').to_owned())
} else if raw.starts_with('\'') && raw.ends_with('\'') && raw.len() >= 2 {
raw[1..raw.len() - 1].replace("''", "'")
} else {
raw.to_owned()
};
Some((key.to_owned(), value))
}
/// Metadata for one Copilot session, read without opening its potentially multi-gigabyte event log.
fn copilot_metadata(path: &Path) -> Option<HashMap<String, String>> {
let file = std::fs::File::open(path).ok()?;
let metadata = std::io::BufReader::new(file)
.lines()
.map_while(Result::ok)
.filter_map(|line| yaml_scalar(&line))
.collect::<HashMap<_, _>>();
(!metadata.is_empty()).then_some(metadata)
}
/// The first real prompt in a Copilot event log, used when an old or unnamed session has no title.
fn copilot_prompt(path: &Path) -> Option<String> {
let file = std::fs::File::open(path).ok()?;
std::io::BufReader::new(file)
.lines()
.take(400)
.filter_map(|line| line.ok())
.filter_map(|line| serde_json::from_str::<serde_json::Value>(&line).ok())
.find_map(|event| {
(event.get("type").and_then(serde_json::Value::as_str) == Some("user.message"))
.then(|| event.pointer("/data/content").and_then(serde_json::Value::as_str).map(str::trim))
.flatten()
.filter(|text| !text.is_empty())
.map(short)
})
}
/// Copilot sessions of the project at `root`: `<config>/session-state/<id>`, titled by
/// their recorded name or first prompt. Directories without an event log are unfinished
/// sessions and are not listed.
pub fn copilot_sessions(copilot_home: &Path, root: &Path) -> Vec<ExternalSession> {
std::fs::read_dir(copilot_home.join("session-state"))
.into_iter()
.flatten()
.flatten()
.filter_map(|entry| {
let dir = entry.path();
let events = dir.join("events.jsonl");
if !events.is_file() {
return None;
}
let metadata = copilot_metadata(&dir.join("workspace.yaml"))?;
let session_id = metadata.get("id").cloned().or_else(|| entry.file_name().to_str().map(str::to_owned))?;
let cwd = metadata.get("cwd").cloned().or_else(|| metadata.get("git_root").cloned());
if !in_project(cwd.as_deref(), root) {
return None;
}
let title = metadata
.get("name")
.map(String::as_str)
.map(str::trim)
.filter(|name| !name.is_empty())
.map(short)
.or_else(|| copilot_prompt(&events))
.unwrap_or_else(|| format!("Copilot session {}", &session_id[..session_id.len().min(8)]));
Some(ExternalSession { provider: "copilot".to_owned(), session_id, title, cwd, updated_ms: mtime(&events) })
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -344,6 +427,51 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
assert!(claude_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
assert!(codex_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
assert!(copilot_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
}
#[test]
fn lists_copilot_sessions_with_names_and_prompt_fallbacks() {
let tmp = tempfile::tempdir().unwrap();
let session = tmp.path().join("session-state/copilot-1");
write(
&session.join("events.jsonl"),
&[
json!({"type": "session.start", "data": {}}),
json!({"type": "user.message", "data": {"content": "fix the parser"}}),
],
);
std::fs::write(
session.join("workspace.yaml"),
"id: copilot-1\ncwd: /work/app/api\nname: \"Fix parser\\nand tests\"\n",
)
.unwrap();
let unnamed = tmp.path().join("session-state/copilot-2");
write(
&unnamed.join("events.jsonl"),
&[json!({"type": "user.message", "data": {"content": "add a regression test"}})],
);
std::fs::write(unnamed.join("workspace.yaml"), "id: copilot-2\ncwd: /work/app\n").unwrap();
let empty = tmp.path().join("session-state/copilot-empty");
std::fs::create_dir_all(&empty).unwrap();
std::fs::write(empty.join("workspace.yaml"), "id: copilot-empty\ncwd: /work/app\n").unwrap();
let other = tmp.path().join("session-state/copilot-other");
write(
&other.join("events.jsonl"),
&[json!({"type": "user.message", "data": {"content": "unrelated project"}})],
);
std::fs::write(other.join("workspace.yaml"), "id: copilot-other\ncwd: /other\n").unwrap();
let sessions = copilot_sessions(tmp.path(), Path::new("/work"));
assert_eq!(sessions.len(), 2);
let mut by_id: HashMap<_, _> = sessions.into_iter().map(|s| (s.session_id.clone(), s)).collect();
let named = by_id.remove("copilot-1").unwrap();
assert_eq!((named.provider.as_str(), named.title.as_str()), ("copilot", "Fix parser and tests"));
assert_eq!(named.cwd.as_deref(), Some("/work/app/api"));
assert_eq!(by_id.remove("copilot-2").unwrap().title, "add a regression test");
}
#[test]
+22 -9
Переглянути файл
@@ -1409,9 +1409,14 @@ impl AgentManager {
out.extend(external::claude_sessions(&dir, &root));
}
let home = self.shared.paths.home_dir.clone().or_else(home_dir);
if let Some(home) = home {
if let Some(home) = home.as_deref() {
out.extend(external::codex_sessions(&home.join(".codex"), &root));
}
if let Some(spec) = self.shared.spec("copilot")
&& let Some(dir) = native::copilot::config_dir(&spec.env, home.as_deref())
{
out.extend(external::copilot_sessions(&dir, &root));
}
let known = self.imported_session_ids();
out.retain(|s| !known.contains(&s.session_id));
out.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
@@ -1421,7 +1426,7 @@ impl AgentManager {
/// Imports an external session as a task, loading it in the background to show its history (#312).
pub fn import_session(&self, provider: &str, session_id: &str) -> IdeResult<AgentTask> {
if !matches!(provider, "claude" | "codex") {
if !matches!(provider, "claude" | "codex" | "copilot") {
return Err(IdeError::invalid(format!("cannot import {provider} sessions")));
}
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
@@ -1488,9 +1493,21 @@ impl AgentManager {
pending_native_fork: None,
};
let handle = Task::restore(file, self.shared.clone());
self.tasks.write().insert(task.id.clone(), handle.clone());
let epoch = {
let mut tasks = self.tasks.write();
let epoch = self.shared.shutdown_epoch();
tasks.insert(task.id.clone(), handle.clone());
epoch
};
handle.emit_task();
handle.persist();
// Loading the session replays its history into the task, so it shows before a first message.
self.shared.runtime.spawn(async move {
match handle.ensure_session(epoch).await {
Ok(_) => handle.release_when_idle(),
Err(e) => tracing::info!("agent task {}: loading the imported session failed: {e}", handle.id),
}
});
Ok(task)
}
@@ -1498,7 +1515,7 @@ impl AgentManager {
/// recording as the agent's own fork, under an id the host chooses. The session must
/// belong to this project and have been recorded in `cwd`.
pub fn fork_session(&self, provider: &str, session_id: &str, cwd: &Path) -> IdeResult<AgentTask> {
if !matches!(provider, "claude" | "codex") {
if !matches!(provider, "claude" | "codex" | "copilot") {
return Err(IdeError::invalid(format!("cannot fork {provider} sessions")));
}
if !canonical_uuid(session_id) {
@@ -1526,7 +1543,7 @@ impl AgentManager {
let config = self.shared.known_config(&spec.id);
let now = now_ms();
let id = uuid::Uuid::new_v4().simple().to_string();
// The host names the fork's session id for claude; codex assigns its own.
// The host names the fork's session id for claude; codex and Copilot assign their own.
let target = (provider == "claude").then(|| uuid::Uuid::new_v4().to_string());
let task = AgentTask {
project_root: Some(IpcPath(root)),
@@ -2762,7 +2779,6 @@ impl AgentManager {
}
s.task.title = title;
s.title_renamed = true;
s.task.updated_ms = now_ms();
}
task.persist();
task.emit_task();
@@ -3126,7 +3142,6 @@ impl AgentManager {
let changed = s.task.mcp_overrides != cleaned;
if changed {
s.task.mcp_overrides = cleaned;
s.task.updated_ms = now_ms();
}
(changed, s.busy, !s.background_tasks.is_empty(), s.snapshot())
};
@@ -3158,7 +3173,6 @@ impl AgentManager {
let changed = s.task.skill_overrides != cleaned;
if changed {
s.task.skill_overrides = cleaned;
s.task.updated_ms = now_ms();
}
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
};
@@ -3194,7 +3208,6 @@ impl AgentManager {
let changed = s.task.memory_overrides != next_boxed;
if changed {
s.task.memory_overrides = next_boxed;
s.task.updated_ms = now_ms();
}
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
};
+54 -3
Переглянути файл
@@ -37,6 +37,15 @@ const DISCOVER_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(5) } else
const EARLY_CANCEL: Duration = Duration::from_secs(2);
const EXIT_GRACE: Duration = Duration::from_millis(100);
/// Copilot's configuration directory (`COPILOT_HOME`, otherwise `<home>/.copilot`).
pub(crate) fn config_dir(env: &[(String, String)], home: Option<&Path>) -> Option<PathBuf> {
env.iter()
.find(|(key, _)| key == "COPILOT_HOME")
.map(|(_, value)| PathBuf::from(value))
.or_else(|| std::env::var_os("COPILOT_HOME").map(PathBuf::from))
.or_else(|| home.map(|home| home.join(".copilot")))
}
/// Pre-session discovery result for `Shared::fetch_settings`.
pub(crate) struct Discovered {
pub commands: Vec<Value>,
@@ -551,6 +560,7 @@ impl CopilotShim {
"initialize" => self.initialize().await,
"session/new" => self.new_session(&params).await,
"session/load" => self.load_session(&params).await,
"session/fork" => self.fork_session(&params).await,
"session/set_config_option" => self.set_config(&params).await,
"session/prompt" => self.prompt(&params, false).await,
"_openidea/steer" => self.prompt(&params, true).await,
@@ -569,7 +579,7 @@ impl CopilotShim {
"loadSession": true,
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
"mcpCapabilities": { "http": true, "sse": true, "stdio": true },
"sessionCapabilities": { "close": {}, "list": {} },
"sessionCapabilities": { "fork": {}, "close": {}, "list": {} },
"_meta": { "openidea": { "steer": true, "backgroundTasks": true, "contextUsage": true } },
},
"agentInfo": {
@@ -649,6 +659,25 @@ impl CopilotShim {
async fn load_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
let session_id = str_param(params, "sessionId")?.to_owned();
let loaded = self.resume_session(params, &session_id).await?;
let actual_id = loaded.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
self.replay_history(&actual_id).await;
Ok(loaded)
}
async fn fork_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
let source = str_param(params, "sessionId")?;
let forked = self.call("sessions.fork", json!({ "sessionId": source })).await?;
let target = forked
.get("sessionId")
.and_then(Value::as_str)
.filter(|id| !id.is_empty())
.ok_or_else(|| error(codes::INTERNAL_ERROR, "Copilot fork returned no sessionId"))?
.to_owned();
self.resume_session(params, &target).await
}
async fn resume_session(self: &Arc<Self>, params: &Value, session_id: &str) -> Result<Value, ResponseError> {
let cwd = str_param(params, "cwd")?;
let catalog = self.models().await?;
let defaults = fetch_user_defaults(self.copilot(), &self.args).await;
@@ -675,7 +704,8 @@ impl CopilotShim {
apply_memory(params, &mut req);
let resumed = self.call("session.resume", req).await?;
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(session_id).to_owned();
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": actual_id })).await {
if let Some(model_id) = current.get("modelId").or_else(|| current.get("model")).and_then(Value::as_str) {
let _ = settings.set(&catalog, MODEL, model_id);
}
@@ -686,7 +716,6 @@ impl CopilotShim {
let _ = settings.set(&catalog, CONTEXT_TIER, tier);
}
}
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
let options = models::config_options(&catalog, &settings);
self.state.lock().sessions.insert(actual_id.clone(), SessionEntry::new(settings));
self.publish_commands(&actual_id, cwd);
@@ -697,6 +726,28 @@ impl CopilotShim {
}))
}
async fn replay_history(&self, session_id: &str) {
let history = match self.call("session.getMessages", json!({ "sessionId": session_id })).await {
Ok(history) => history,
Err(error) => {
tracing::info!("copilot session {session_id}: could not load history: {}", error.message);
return;
}
};
let events = history.get("events").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
let updates = {
let mut state = self.state.lock();
let Some(entry) = state.sessions.get_mut(session_id) else { return };
events
.iter()
.flat_map(|event| entry.translator.translate_history(session_id, event, None).updates)
.collect::<Vec<_>>()
};
for (target_session, update) in updates {
self.send_update(&target_session, update);
}
}
fn sync_usage_metrics(self: &Arc<Self>, session_id: &str) {
let shim = self.clone();
let sid = session_id.to_owned();
+120
Переглянути файл
@@ -115,6 +115,18 @@ fn sample_price_units() -> Value {
})
}
#[test]
fn resolves_copilot_home_from_agent_env_or_user_home() {
let home = std::path::Path::new("/home/test");
assert_eq!(
super::config_dir(&[("COPILOT_HOME".into(), "/custom/copilot".into())], Some(home)).as_deref(),
Some(std::path::Path::new("/custom/copilot"))
);
if std::env::var_os("COPILOT_HOME").is_none() {
assert_eq!(super::config_dir(&[], Some(home)), Some(home.join(".copilot")));
}
}
#[test]
fn parses_an_enabled_auto_only_catalog() {
let list = json!({
@@ -434,6 +446,39 @@ impl Handler for FakeCopilotServer {
"skills.discover" => Ok(json!({ "skills": [] })),
"session.create" => Ok(json!({ "sessionId": "cop-sess-1" })),
"session.resume" => Ok(json!({ "sessionId": params["sessionId"] })),
"sessions.fork" => Ok(json!({ "sessionId": "cop-sess-fork" })),
"session.getMessages" => Ok(json!({
"events": [
{
"type": "user.message",
"data": { "content": "Fix the parser" }
},
{
"type": "assistant.message",
"data": {
"messageId": "history-message",
"reasoningText": "Inspect the grammar first.",
"content": "I fixed the parser."
}
},
{
"type": "tool.execution_start",
"data": {
"toolCallId": "history-tool",
"toolName": "view",
"arguments": { "path": "/tmp/parser.rs" }
}
},
{
"type": "tool.execution_complete",
"data": {
"toolCallId": "history-tool",
"success": true,
"result": { "content": "fn parse() {}" }
}
}
]
})),
"session.model.getCurrent" => Ok(json!({ "modelId": "gemini-4-carbon" })),
"session.model.switchTo" => Ok(json!({ "modelId": params["modelId"] })),
"session.mode.set" => Ok(json!({})),
@@ -674,6 +719,81 @@ async fn shim_creates_session_with_copilot_defaults_switches_tiers_and_streams_t
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shim_loads_and_replays_copilot_history() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates.clone(), move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let init: Value = client.request("initialize", json!({}), None).await.unwrap();
assert!(init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object());
let loaded: Value = client
.request("session/load", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
.await
.unwrap();
assert_eq!(loaded["sessionId"], "cop-sess-1");
assert!(
server
.calls
.lock()
.iter()
.any(|(method, params)| { method == "session.getMessages" && params["sessionId"] == "cop-sess-1" })
);
let seen = updates.0.lock();
assert!(
seen.iter().any(|u| u["sessionUpdate"] == "user_message_chunk" && u["content"]["text"] == "Fix the parser")
);
assert!(
seen.iter().any(
|u| u["sessionUpdate"] == "agent_thought_chunk" && u["content"]["text"] == "Inspect the grammar first."
)
);
assert!(
seen.iter()
.any(|u| u["sessionUpdate"] == "agent_message_chunk" && u["content"]["text"] == "I fixed the parser.")
);
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call" && u["toolCallId"] == "history-tool"));
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call_update" && u["toolCallId"] == "history-tool"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shim_forks_copilot_sessions_and_resumes_the_new_id() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates, move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
let forked: Value = client
.request("session/fork", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
.await
.unwrap();
assert_eq!(forked["sessionId"], "cop-sess-fork");
let calls = server.calls.lock();
assert!(calls.iter().any(|(method, params)| method == "sessions.fork" && params["sessionId"] == "cop-sess-1"));
assert!(calls.iter().any(|(method, params)| method == "session.resume" && params["sessionId"] == "cop-sess-fork"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shim_forwards_disabled_mcp_servers_on_create_and_resume() {
let server =
+49
Переглянути файл
@@ -370,6 +370,55 @@ impl EventTranslator {
}
out
}
/// Translates one persisted Copilot event returned by `session.getMessages`. The live
/// event stream omits historical user messages and emits reasoning deltas, while the
/// persisted form has complete user and assistant messages.
pub fn translate_history(&mut self, main_session: &str, event: &Value, fallback_limit: Option<u32>) -> Translated {
let event_type = str_of(event, "type").unwrap_or_default();
let data = event.get("data").unwrap_or(&Value::Null);
if event_type == "user.message" {
let Some(text) = str_of(data, "content").map(str::trim).filter(|text| !text.is_empty()) else {
return Translated { updates: Vec::new(), terminal: None };
};
let target_session = str_of(event, "agentId")
.filter(|id| !id.is_empty())
.map(|id| format!("{main_session}:sub:{id}"))
.unwrap_or_else(|| main_session.to_owned());
return Translated {
updates: vec![(
target_session,
json!({
"sessionUpdate": "user_message_chunk",
"content": { "type": "text", "text": text },
}),
)],
terminal: None,
};
}
let mut translated = self.translate(main_session, event, fallback_limit);
if event_type == "assistant.message"
&& !(data.get("parentToolCallId").and_then(Value::as_str).is_some() && str_of(event, "agentId").is_none())
&& let Some(reasoning) = str_of(data, "reasoningText").map(str::trim).filter(|text| !text.is_empty())
{
let target_session = str_of(event, "agentId")
.filter(|id| !id.is_empty())
.map(|id| format!("{main_session}:sub:{id}"))
.unwrap_or_else(|| main_session.to_owned());
translated.updates.insert(
0,
(
target_session,
json!({
"sessionUpdate": "agent_thought_chunk",
"content": { "type": "text", "text": reasoning },
}),
),
);
}
translated
}
}
fn describe_tool(name: &str, args: &Value) -> ToolInfo {
+107
Переглянути файл
@@ -3241,6 +3241,58 @@ fn plant_codex_session(root: &Path, session_id: &str) {
.unwrap();
}
/// Plants a recorded Copilot session below the test home.
fn plant_copilot_session(root: &Path, session_id: &str) {
let dir = root.join(".copilot").join("session-state").join(session_id);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("workspace.yaml"),
format!("id: {session_id}\ncwd: {}\nname: Fix the Copilot parser\n", root.to_string_lossy()),
)
.unwrap();
std::fs::write(
dir.join("events.jsonl"),
format!(
"{}\n",
json!({
"type": "user.message",
"data": {"content": "fix the Copilot parser"}
})
),
)
.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn imports_copilot_sessions_and_loads_their_history() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
plant_copilot_session(tmp.path(), NATIVE_SOURCE);
let sessions = mgr.external_sessions();
assert!(sessions.iter().any(|session| session.provider == "copilot" && session.session_id == NATIVE_SOURCE));
let task = mgr.import_session("copilot", NATIVE_SOURCE).unwrap();
assert_eq!(task.provider, "copilot");
for _ in 0..200 {
if agent.calls.lock().iter().any(|call| call == "session/load")
&& mgr.entries(&task.id, None).unwrap().len() >= 2
{
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert!(agent.calls.lock().iter().any(|call| call == "session/load"));
assert!(
mgr.entries(&task.id, None)
.unwrap()
.iter()
.any(|entry| matches!(entry, AgentEntry::User { text, .. } if text == "earlier question"))
);
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_uses_the_id_codex_assigns() {
let tmp = tempfile::tempdir().unwrap();
@@ -3261,6 +3313,28 @@ async fn fork_session_uses_the_id_codex_assigns() {
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_uses_the_id_copilot_assigns() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
plant_copilot_session(tmp.path(), NATIVE_SOURCE);
let task = mgr.fork_session("copilot", NATIVE_SOURCE, tmp.path()).unwrap();
for _ in 0..200 {
if !agent.forks.lock().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let forks = agent.forks.lock().clone();
assert_eq!(forks.len(), 1);
assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE);
assert!(forks[0].pointer("/_meta/openidea/forkSessionId").is_none(), "copilot names its own fork");
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some("s2"));
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_rejects_invalid_input_before_starting() {
let tmp = tempfile::tempdir().unwrap();
@@ -6928,3 +7002,36 @@ async fn network_outage_window_off_or_expired_degrades_to_interrupted_and_auth_e
mgr2.shutdown();
mgr3.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn metadata_edits_do_not_bump_updated_ms() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let _down = ShutDown(&mgr);
let task = mgr
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let handle = mgr.task(&task.id).unwrap();
let fixed_ms = 1_234.0;
handle.state.lock().task.updated_ms = fixed_ms;
mgr.rename(&task.id, "Custom Title").unwrap();
assert_eq!(handle.state.lock().task.updated_ms, fixed_ms);
let after_mcp = mgr.set_mcp_overrides(&task.id, BTreeMap::from([("github".into(), false)])).unwrap();
assert_eq!(after_mcp.updated_ms, fixed_ms);
let after_skill =
mgr.set_skill_overrides(&task.id, BTreeMap::from([("triage".into(), AgentSkillMode::Off)])).unwrap();
assert_eq!(after_skill.updated_ms, fixed_ms);
let after_memory = mgr
.set_memory_overrides(
&task.id,
AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off), entries: BTreeMap::new() },
)
.unwrap();
assert_eq!(after_memory.updated_ms, fixed_ms);
}
+53 -9
Переглянути файл
@@ -85,13 +85,26 @@ gradle.projectsEvaluated {{
pub fn publish(root: &Path, cache: &Path, class_paths: &[String], main_class: &str) -> IdeResult<()> {
let output = PathBuf::from(fs::read_to_string(cache.join("resource-output.txt"))?.trim());
if !output.is_absolute() || !output.is_dir() {
return Err(IdeError::invalid("The resource build did not report an output directory"));
let invalid_output = "The resource build did not report an output directory";
if !output.is_absolute() {
return Err(IdeError::invalid(invalid_output));
}
let output = dunce::canonicalize(output)?;
let output = match fs::metadata(&output) {
Ok(metadata) if metadata.is_dir() => Some(dunce::canonicalize(output)?),
// Gradle's processResources can succeed with NO-SOURCE and never create its destination.
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
_ => return Err(IdeError::invalid(invalid_output)),
};
let paths: Vec<_> = class_paths.iter().filter_map(|p| dunce::canonicalize(root.join(p)).ok()).collect();
// A separate resource directory is already on the runtime classpath (e.g. build/resources/main).
if paths.contains(&output) {
if output.as_ref().is_some_and(|dir| paths.contains(dir)) {
return Ok(());
}
let previous: Vec<String> = fs::read(cache.join("published-resources.json"))
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default();
if output.is_none() && previous.is_empty() {
return Ok(());
}
// jdtls uses bin/main for Gradle, rather than Gradle's build/resources/main.
@@ -99,12 +112,10 @@ pub fn publish(root: &Path, cache: &Path, class_paths: &[String], main_class: &s
let destination = paths.iter().find(|p| p.join(&class_file).is_file()).ok_or_else(|| {
IdeError::invalid("Cannot find the running main class output directory; restart the application")
})?;
let previous: Vec<String> = fs::read(cache.join("published-resources.json"))
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default();
let mut current = Vec::new();
copy_resources(&output, &output, destination, &mut current)?;
if let Some(output) = output {
copy_resources(&output, &output, destination, &mut current)?;
}
for rel in previous.iter().filter(|p| !current.contains(p)) {
let path = destination.join(rel);
if path.is_file() {
@@ -220,6 +231,39 @@ mod tests {
}
}
#[test]
fn missing_resource_output_publishes_an_empty_set() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let output = root.join("build/resources/main");
let cache = root.join("cache");
let runtime = root.join("bin/main");
let class_paths = [runtime.to_string_lossy().into_owned()];
let resource = "application.properties";
fs::create_dir(&cache).unwrap();
fs::create_dir_all(runtime.join("example")).unwrap();
fs::write(cache.join("resource-output.txt"), output.to_string_lossy().as_bytes()).unwrap();
let class = runtime.join("example/Application.class");
fs::write(&class, "running").unwrap();
publish(root, &cache, &class_paths, "example.Application").unwrap();
assert!(!output.exists());
fs::create_dir_all(&output).unwrap();
fs::write(output.join(resource), "server.port=8081").unwrap();
publish(root, &cache, &class_paths, "example.Application").unwrap();
assert!(runtime.join(resource).is_file());
fs::remove_file(output.join(resource)).unwrap();
fs::remove_dir(&output).unwrap();
publish(root, &cache, &class_paths, "example.Application").unwrap();
assert!(!runtime.join(resource).exists());
assert_eq!(fs::read_to_string(class).unwrap(), "running");
fs::write(output, "not a directory").unwrap();
assert!(publish(root, &cache, &class_paths, "example.Application").is_err());
}
#[test]
fn leaves_separate_runtime_resource_directories_in_place_and_rejects_jar_only_runs() {
let tmp = tempfile::tempdir().unwrap();
+102 -24
Переглянути файл
@@ -4,7 +4,8 @@
//! same way into the test output, which also sees the production classes.
use super::*;
use ide_core::settings::{
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings,
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings, jar_files,
split_jar_glob,
};
use std::fs;
@@ -104,13 +105,17 @@ fn library_entries(root: &Path, ps: &ProjectStructureSettings, test: bool) -> Ve
module_deps.iter().find(|d| d.kind == "library" && d.target == lib.name).map_or(lib.scope, |d| d.scope);
if wanted(scope) {
for class in &lib.classes {
add(class_entry(root, class));
for entry in class_entries(root, class) {
add(entry);
}
}
}
}
for dep in module_deps.iter().filter(|d| d.kind == "library" && wanted(d.scope)) {
if !ps.libraries.iter().any(|l| l.name == dep.target) && !dep.target.trim().is_empty() {
add(class_entry(root, &dep.target));
for entry in class_entries(root, &dep.target) {
add(entry);
}
}
}
for facet in ps.facets.iter().filter(|f| f.kind == "web") {
@@ -133,29 +138,50 @@ fn web_root(root: &Path, facet: &ide_core::settings::FacetConfig) -> PathBuf {
root.join(dir)
}
/// The class archives and folders of a library path (`lib/*.jar` lists the folder's jars).
fn library_files(root: &Path, value: &str) -> Vec<PathBuf> {
let entry = class_entry(root, value);
match entry.strip_suffix('*') {
Some(dir) => {
let mut jars: Vec<PathBuf> = fs::read_dir(dir)
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "jar")).collect())
.unwrap_or_default();
jars.sort();
jars
/// The folders under `dir` (itself included) that hold `.jar` files, in walk order.
fn jar_dirs(dir: &Path) -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = Vec::new();
for jar in jar_files(dir, true) {
if let Some(parent) = jar.parent().filter(|p| !dirs.iter().any(|d| d == p)) {
dirs.push(parent.to_path_buf());
}
None => vec![PathBuf::from(entry)],
}
dirs
}
/// A classpath entry for a library path: a folder of jars (`lib/*`) stays a wildcard javac expands.
fn class_entry(root: &Path, value: &str) -> String {
let path = root.join(value.trim());
let text = path.to_string_lossy().into_owned();
if text.ends_with("/*.jar") || text.ends_with("\\*.jar") {
return text[..text.len() - 4].to_owned();
/// The class archives and folders of a library path (`lib/*.jar`, `lib/**/*.jar`, or a folder
/// containing JARs expands to those JARs; a folder without JARs stays a class folder).
fn library_files(root: &Path, value: &str) -> Vec<PathBuf> {
if let Some((base, recursive)) = split_jar_glob(value) {
return jar_files(&root.join(base), recursive);
}
text
let path = root.join(value.trim());
if path.is_dir() {
let jars = jar_files(&path, true);
if !jars.is_empty() {
return jars;
}
}
vec![path]
}
/// Classpath entries for a library path: `lib/*.jar` stays `lib/*` for javac to expand; a
/// directory containing JARs expands to `<dir>/*` per folder holding JARs.
fn class_entries(root: &Path, value: &str) -> Vec<String> {
let wildcard = |dir: &Path| format!("{}{}*", dir.to_string_lossy(), std::path::MAIN_SEPARATOR);
if let Some((base, recursive)) = split_jar_glob(value) {
let dir = root.join(base);
let dirs = if recursive { jar_dirs(&dir) } else { Vec::new() };
return if dirs.is_empty() { vec![wildcard(&dir)] } else { dirs.iter().map(|d| wildcard(d)).collect() };
}
let path = root.join(value.trim());
if path.is_dir() {
let dirs = jar_dirs(&path);
if !dirs.is_empty() {
return dirs.iter().map(|d| wildcard(d)).collect();
}
}
vec![path.to_string_lossy().into_owned()]
}
fn classpath(entries: &[String]) -> String {
@@ -440,7 +466,10 @@ pub fn structure_web_artifacts(ps: &ProjectStructureSettings) -> Vec<&ArtifactCo
ps.artifacts.iter().filter(|a| matches!(a.kind, ArtifactKind::War | ArtifactKind::WarExploded)).collect()
}
/// A build of `artifact` into the WAR `war` (Tomcat's deployment), compiling first.
/// A build of `artifact` for Tomcat's deployment, compiling production classes first.
/// When `war` is `Some`, packs a WAR archive at that path; when `None`, writes to the
/// artifact's own output (`artifact_file`: a `.war` archive for `War`, or the exploded
/// directory for `WarExploded`).
#[allow(clippy::too_many_arguments)]
pub fn structure_war_plan(
root: &Path,
@@ -449,7 +478,7 @@ pub fn structure_war_plan(
jdk: Option<&StructureJdk>,
language_level: &str,
artifact: &ArtifactConfig,
war: &Path,
war: Option<&Path>,
cache: &Path,
) -> IdeResult<BuildPlan> {
let mut plan = structure_plan(root, ps, roots, jdk, language_level, BuildKind::Build, cache)?
@@ -459,7 +488,7 @@ pub fn structure_war_plan(
plan.steps.retain(|s| !s.args.iter().any(|a| a.ends_with("test.args")));
plan.steps
.retain(|s| !matches!(&s.action, Some((Action::CopyResources { to, .. }, _)) if !to.starts_with(&main_out)));
plan.steps.extend(artifact_steps(root, ps, artifact, &main_out, Some(war), cache));
plan.steps.extend(artifact_steps(root, ps, artifact, &main_out, war, cache));
plan.title = artifact.name.clone();
Ok(plan)
}
@@ -1144,4 +1173,53 @@ mod tests {
bad_result.messages
);
}
#[test]
fn expands_jar_directory_libraries_for_javac_and_artifacts() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("app");
let cache = tmp.path().join("cache");
write(&root.join("src/A.java"), "class A {}");
write(&root.join("WebRoot/WEB-INF/lib/gson.jar"), "jar1");
write(&root.join("WebRoot/WEB-INF/lib/sub/extra.jar"), "jar2");
fs::create_dir_all(root.join("plain-classes")).unwrap();
write(&root.join("plain-classes/Helper.class"), "");
let ps = ProjectStructureSettings {
libraries: vec![
ProjectLibrary {
name: "web-libs".into(),
classes: vec!["WebRoot/WEB-INF/lib".into()],
..Default::default()
},
ProjectLibrary { name: "classes".into(), classes: vec!["plain-classes".into()], ..Default::default() },
],
artifacts: vec![ArtifactConfig {
name: "app:war exploded".into(),
kind: ArtifactKind::WarExploded,
module: ".".into(),
output_directory: "out/artifacts/app_war_exploded".into(),
main_class: String::new(),
include_libraries: vec!["web-libs".into()],
}],
..Default::default()
};
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
let plan = structure_plan(&root, &ps, &roots, None, "17", BuildKind::Artifacts, &cache).unwrap().unwrap();
let javac = &plan.steps[0];
let cp = &javac.args[javac.args.iter().position(|a| a == "-cp").unwrap() + 1];
let sep = std::path::MAIN_SEPARATOR;
assert!(cp.contains(&format!("lib{sep}*")), "expected JAR dir wildcard in cp: {cp}");
assert!(cp.contains(&format!("sub{sep}*")), "expected nested JAR dir wildcard in cp: {cp}");
assert!(cp.contains("plain-classes") && !cp.contains(&format!("plain-classes{sep}*")), "cp={cp}");
let layout = plan.steps.iter().find_map(|s| match &s.action {
Some((Action::Layout { entries, .. }, _)) => Some(entries),
_ => None,
});
let entries = layout.expect("layout step");
assert!(entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/gson.jar")), "{entries:?}");
assert!(entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/extra.jar")), "{entries:?}");
assert!(!entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/lib")), "{entries:?}");
}
}
+25
Переглянути файл
@@ -314,6 +314,30 @@ pub struct SmartKeysSettings {
pub insert_doc_stub: bool,
/// Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`.
pub backspace_unindent: String,
/// The styles Cycle Identifier Case goes through.
pub cycle_case: CycleCaseSettings,
}
/// Editor › General › Smart Keys › Cycle Identifier Case: the styles the action goes through.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CycleCaseSettings {
/// `snake_case`
pub snake: bool,
/// `SCREAMING_SNAKE_CASE`
pub screaming: bool,
/// `kebab-case`
pub kebab: bool,
/// `camelCase`
pub camel: bool,
/// `PascalCase`
pub pascal: bool,
}
impl Default for CycleCaseSettings {
fn default() -> Self {
Self { snake: true, screaming: true, kebab: true, camel: true, pascal: true }
}
}
impl Default for SmartKeysSettings {
@@ -335,6 +359,7 @@ impl Default for SmartKeysSettings {
smart_indent: true,
insert_doc_stub: true,
backspace_unindent: "autoindent".into(),
cycle_case: CycleCaseSettings::default(),
}
}
}
+4
Переглянути файл
@@ -27,6 +27,10 @@ pub enum McpUiRequest {
subject: String,
project: String,
detail: Option<String>,
/// The project is served without a window: the request shows in another project's window,
/// which names it and keeps the keyboard focus where it is.
#[serde(default)]
background: bool,
},
OpenFile {
path: crate::IpcPath,
+72
Переглянути файл
@@ -1,5 +1,35 @@
//! Returning freed heap pages to the OS.
use std::sync::Mutex;
use std::time::{Duration, Instant};
/// Like [`release_free_pages`], on a background thread once 2 s pass without another call:
/// closing a project or a batch of tabs frees memory in bursts, released once.
pub fn release_free_pages_soon() {
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
debounce(&DUE, Duration::from_secs(2), release_free_pages);
}
/// Runs `run` on a background thread once `delay` passes after the last call.
fn debounce(due: &'static Mutex<Option<Instant>>, delay: Duration, run: fn()) {
let idle = due.lock().unwrap().replace(Instant::now() + delay).is_none();
if idle {
std::thread::spawn(move || {
loop {
let mut slot = due.lock().unwrap();
let left = slot.map_or(Duration::ZERO, |at| at.saturating_duration_since(Instant::now()));
if left.is_zero() {
*slot = None;
drop(slot);
return run();
}
drop(slot);
std::thread::sleep(left);
}
});
}
}
/// Hands pages the allocator has freed but kept back to the OS. Call after a burst of
/// short-lived allocations (a full index scan); until then they still count towards the
/// process's memory footprint.
@@ -18,3 +48,45 @@ pub fn release_free_pages() {
libc::malloc_trim(0);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
static RUNS: AtomicUsize = AtomicUsize::new(0);
fn count() {
RUNS.fetch_add(1, SeqCst);
}
#[test]
fn a_burst_of_calls_runs_once_after_the_delay() {
// Timing-based: a loaded CI machine can oversleep, so each check allows for that.
let delay = Duration::from_millis(500);
let (mut last, mut widest_gap) = (None::<Instant>, Duration::ZERO);
for _ in 0..5 {
debounce(&DUE, delay, count);
let now = Instant::now();
widest_gap = widest_gap.max(last.map_or(Duration::ZERO, |l| now - l));
last = Some(now);
std::thread::sleep(Duration::from_millis(20));
}
if last.unwrap().elapsed() < delay {
assert_eq!(RUNS.load(SeqCst), 0, "ran before the delay passed");
}
let deadline = Instant::now() + Duration::from_secs(10);
while RUNS.load(SeqCst) == 0 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
// A second run would come within another delay.
std::thread::sleep(delay);
if widest_gap < delay {
assert_eq!(RUNS.load(SeqCst), 1);
} else {
assert!(RUNS.load(SeqCst) >= 1);
}
release_free_pages_soon();
}
}
+23
Переглянути файл
@@ -1176,6 +1176,29 @@ mod tests {
set_env_overlay(Vec::new());
}
#[test]
fn a_child_inside_a_project_gets_its_xcode() {
let root = std::path::Path::new("/openidea-test-process/xcode");
let xcode = "/Applications/Xcode-beta.app/Contents/Developer";
crate::project_env::set_developer_dir(root, Some(xcode.into()));
let developer_dir = |cmd: &Command| {
cmd.get_envs().find(|(n, _)| *n == "DEVELOPER_DIR").and_then(|(_, v)| v.map(OsStr::to_owned))
};
// xcodebuild, xcrun, a language server: a `Command` started in the project.
let mut tool = Command::new("xcodebuild");
prepare(tool.current_dir(root.join("App")));
assert_eq!(developer_dir(&tool), Some(xcode.into()));
// A terminal: a PTY applies the fixes itself.
assert!(host_env_fixes_in(root).contains(&("DEVELOPER_DIR".into(), Some(xcode.into()))));
let mut elsewhere = Command::new("xcodebuild");
prepare(elsewhere.current_dir("/openidea-test-process/other"));
assert_eq!(developer_dir(&elsewhere), None);
crate::project_env::set_developer_dir(root, None);
let mut tool = Command::new("xcodebuild");
prepare(tool.current_dir(root));
assert_eq!(developer_dir(&tool), None, "empty: the system default");
}
#[test]
fn a_child_inside_a_project_gets_its_environment() {
let root = std::path::Path::new("/openidea-test-process/project");
+62 -2
Переглянути файл
@@ -16,13 +16,21 @@ struct Entry {
root: PathBuf,
direnv: Vec<(OsString, Option<OsString>)>,
github_token: Option<OsString>,
developer_dir: Option<OsString>,
changes: Changes,
loading: bool,
}
impl Entry {
fn new(root: PathBuf) -> Self {
Self { root, direnv: Vec::new(), github_token: None, changes: Changes::default(), loading: false }
Self {
root,
direnv: Vec::new(),
github_token: None,
developer_dir: None,
changes: Changes::default(),
loading: false,
}
}
fn rebuild(&mut self) {
@@ -33,11 +41,16 @@ impl Entry {
// `.envrc` entries override the project GitHub token when both define `GH_TOKEN`.
combined.retain(|(k, _)| !self.direnv.iter().any(|(dk, _)| dk == k));
combined.extend(self.direnv.iter().cloned());
// The project's chosen Xcode overrides a `DEVELOPER_DIR` from `.envrc`: it is set for this project only.
if let Some(dir) = &self.developer_dir {
combined.retain(|(k, _)| k != DEVELOPER_DIR);
combined.push((DEVELOPER_DIR.into(), Some(dir.clone())));
}
self.changes = Arc::new(combined);
}
fn is_idle_empty(&self) -> bool {
!self.loading && self.direnv.is_empty() && self.github_token.is_none()
!self.loading && self.direnv.is_empty() && self.github_token.is_none() && self.developer_dir.is_none()
}
}
@@ -144,6 +157,31 @@ pub fn set_github_token(root: &Path, token: Option<OsString>) -> bool {
}
}
const DEVELOPER_DIR: &str = "DEVELOPER_DIR";
/// Sets or clears the `DEVELOPER_DIR` (the Xcode `xcrun`, `xcodebuild` and sourcekit-lsp use)
/// injected for children started in `root`. Returns whether it changed.
pub fn set_developer_dir(root: &Path, dir: Option<OsString>) -> bool {
let dir = dir.filter(|d| !d.is_empty());
let mut entries = entries();
let idx = match entries.iter().position(|e| e.root == root) {
Some(idx) if entries[idx].developer_dir == dir => return false,
Some(idx) => idx,
None if dir.is_none() => return false,
None => {
entries.push(Entry::new(root.to_path_buf()));
entries.len() - 1
}
};
let entry = &mut entries[idx];
entry.developer_dir = dir;
entry.rebuild();
if entry.is_idle_empty() {
entries.remove(idx);
}
true
}
/// The project-scoped `GH_TOKEN` configured for the innermost project holding `dir`, if any.
pub fn github_token(dir: &Path) -> Option<OsString> {
find(&entries(), dir).and_then(|e| e.github_token.clone())
@@ -202,6 +240,28 @@ mod tests {
assert!(for_dir(inner).is_empty());
}
#[test]
fn the_projects_xcode_wins_over_envrc_and_clears() {
let root = Path::new("/openidea-test-env/xcode");
set(root, vec![change("DEVELOPER_DIR", Some("/envrc")), change("A", Some("1"))]);
assert!(set_developer_dir(root, Some("/Applications/Xcode-beta.app/Contents/Developer".into())));
assert!(!set_developer_dir(root, Some("/Applications/Xcode-beta.app/Contents/Developer".into())));
assert_eq!(
*for_dir(&root.join("App")),
[change("A", Some("1")), change("DEVELOPER_DIR", Some("/Applications/Xcode-beta.app/Contents/Developer"))]
);
assert!(set_developer_dir(root, None));
assert_eq!(*for_dir(root), [change("DEVELOPER_DIR", Some("/envrc")), change("A", Some("1"))]);
remove(root);
assert!(for_dir(root).is_empty());
let alone = Path::new("/openidea-test-env/xcode-alone");
assert!(!set_developer_dir(alone, Some("".into())), "empty is the system default");
assert!(set_developer_dir(alone, Some("/X".into())));
assert_eq!(*for_dir(alone), [change("DEVELOPER_DIR", Some("/X"))]);
assert!(set_developer_dir(alone, None));
assert!(entries().iter().all(|e| e.root != alone), "an empty entry is dropped");
}
#[test]
fn waiting_ends_once_the_environment_is_read() {
let root = Path::new("/openidea-test-env/waiting");
+7 -1
Переглянути файл
@@ -203,6 +203,9 @@ pub enum RunTargetKind {
Docker,
/// A new container of a Compose service (`docker compose run --rm`).
Compose,
/// A WSL distribution on this Windows machine (`wsl.exe -d <distro>`), the project read
/// through `/mnt/<drive>`.
Wsl,
}
/// Build, Execution, Deployment › Run Targets: run configurations on another machine
@@ -215,7 +218,8 @@ pub struct RunTarget {
pub name: String,
/// [`SshConfiguration::id`] (SSH).
pub ssh_config: String,
/// Remote folder the project is synchronised to and run from (SSH).
/// Remote folder the project is synchronised to and run from (SSH); the project's Linux
/// path, empty = its `/mnt/<drive>` path (WSL).
pub project_root: String,
/// Upload changed project files before each run (SSH).
pub sync_before_run: bool,
@@ -241,6 +245,8 @@ pub struct RunTarget {
pub run_options: String,
/// Run as the image's user instead of the project folder's owner (Linux).
pub image_user: bool,
/// Distribution name, as `wsl.exe -l -q` lists it (WSL).
pub distro: String,
}
/// A plugin-owned argv wrapper for project runs (API 1.4).
+103 -1
Переглянути файл
@@ -1452,6 +1452,7 @@ pub struct LanguagesSettings {
pub arduino: ArduinoSettings,
pub zig: ZigSettings,
pub flutter: FlutterSettings,
pub swift: SwiftSettings,
}
impl Default for LanguagesSettings {
@@ -1485,6 +1486,7 @@ impl Default for LanguagesSettings {
arduino: ArduinoSettings::default(),
zig: ZigSettings::default(),
flutter: FlutterSettings::default(),
swift: SwiftSettings::default(),
}
}
}
@@ -1769,6 +1771,26 @@ pub struct ZigSettings {
pub zig: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct SwiftSettings {
/// The Xcode (`Xcode.app` or its `Contents/Developer`) whose tools the project's sourcekit-lsp,
/// `xcodebuild`, `xcrun` and terminals use, as `DEVELOPER_DIR`. Empty = the `xcode-select` one.
pub xcode: String,
}
impl SwiftSettings {
/// [`Self::xcode`] as a `DEVELOPER_DIR` value (`Xcode.app` gets `/Contents/Developer`); `None` when unset.
pub fn developer_dir(&self) -> Option<std::path::PathBuf> {
let xcode = self.xcode.trim();
if xcode.is_empty() {
return None;
}
let path = std::path::Path::new(xcode);
Some(if path.extension().is_some_and(|e| e == "app") { path.join("Contents/Developer") } else { path.into() })
}
}
/// The Flutter plugin's "Flutter SDK path".
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -1975,6 +1997,10 @@ pub struct TypeScriptSettings {
/// plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the
/// vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
pub tsserver_max_memory: u32,
/// tsserver's log (`typescript.tsserver.log`). TypeScript: Open TS Server Log opens it.
#[serde(deserialize_with = "or_default")]
#[specta(type = TsServerLog)]
pub tsserver_log: TsServerLog,
/// Problems › TypeScript project errors: the project's own `tsc --watch` per root
/// `tsconfig.json` reports the errors of files that are not open.
pub watch_problems: bool,
@@ -1982,10 +2008,27 @@ pub struct TypeScriptSettings {
impl Default for TypeScriptSettings {
fn default() -> Self {
Self { version: "bundled".into(), tsserver_max_memory: 0, watch_problems: false }
Self {
version: "bundled".into(),
tsserver_max_memory: 0,
tsserver_log: TsServerLog::Off,
watch_problems: false,
}
}
}
/// tsserver's log verbosity, as vtsls' `typescript.tsserver.log` spells it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum TsServerLog {
#[default]
Off,
Terse,
Normal,
RequestTime,
Verbose,
}
/// Dependency scope for a module dependency or project library (IDEA's Modules › Dependencies).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -2011,6 +2054,37 @@ pub struct ProjectLibrary {
pub scope: DependencyScope,
}
/// A library class entry written as a jar glob: `dir/*.jar` → `(dir, false)`, `dir/**/*.jar` → `(dir, true)`.
pub fn split_jar_glob(entry: &str) -> Option<(&str, bool)> {
let entry = entry.trim();
if let Some(base) = entry.strip_suffix("/**/*.jar").or_else(|| entry.strip_suffix(r"\**\*.jar")) {
return Some((base, true));
}
entry.strip_suffix("/*.jar").or_else(|| entry.strip_suffix(r"\*.jar")).map(|base| (base, false))
}
/// The `.jar` files in `dir` (and its subfolders when `recursive`), sorted by name per folder.
pub fn jar_files(dir: &std::path::Path, recursive: bool) -> Vec<std::path::PathBuf> {
fn walk(dir: &std::path::Path, recursive: bool, out: &mut Vec<std::path::PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
let mut entries: Vec<_> = entries.flatten().collect();
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let path = entry.path();
match entry.file_type() {
Ok(t) if t.is_dir() && recursive => walk(&path, true, out),
Ok(t) if t.is_file() && path.extension().is_some_and(|x| x.eq_ignore_ascii_case("jar")) => {
out.push(path)
}
_ => {}
}
}
}
let mut out = Vec::new();
walk(dir, recursive, &mut out);
out
}
/// Dependency entry of a module (Project Structure › Modules › Dependencies).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -2158,6 +2232,20 @@ impl Settings {
mod tests {
use super::*;
#[test]
fn the_xcode_setting_becomes_a_developer_dir() {
let dir = |xcode: &str| SwiftSettings { xcode: xcode.into() }.developer_dir();
assert_eq!(dir(""), None);
assert_eq!(dir(" "), None);
assert_eq!(dir("/Applications/Xcode-beta.app"), Some("/Applications/Xcode-beta.app/Contents/Developer".into()));
assert_eq!(
dir("/Applications/Xcode.app/Contents/Developer"),
Some("/Applications/Xcode.app/Contents/Developer".into())
);
let s: Settings = serde_json::from_str(r#"{"languages":{"swift":{"xcode":"/X.app"}}}"#).unwrap();
assert_eq!(s.languages.swift.xcode, "/X.app");
}
#[test]
fn ruff_safe_fixes_on_save_default_off_and_round_trip() {
let old: Settings = serde_json::from_str(r#"{"languages":{"ruff":{"runOnSave":true}}}"#).unwrap();
@@ -2168,6 +2256,20 @@ mod tests {
assert_eq!(serde_json::to_value(&on).unwrap()["languages"]["ruff"]["fixOnSave"], true);
}
#[test]
fn tsserver_log_reads_known_levels_and_drops_anything_else() {
let log = |v: &str| {
let s: Settings =
serde_json::from_str(&format!(r#"{{"languages":{{"typescript":{{"tsserverLog":{v}}}}}}}"#)).unwrap();
s.languages.typescript.tsserver_log
};
assert_eq!(log(r#""requestTime""#), TsServerLog::RequestTime);
assert_eq!(log(r#""verbose""#), TsServerLog::Verbose);
assert_eq!(log(r#""--trace""#), TsServerLog::Off);
assert_eq!(log("3"), TsServerLog::Off);
assert_eq!(serde_json::to_value(TsServerLog::RequestTime).unwrap(), "requestTime");
}
#[test]
fn python_interpreter_may_name_a_run_target() {
let python = |interpreter: &str| PythonSettings { interpreter: interpreter.into(), ..Default::default() };
+92
Переглянути файл
@@ -35,6 +35,24 @@ pub fn parse(path: &Path) -> Option<WslPath> {
Some(WslPath { distro: distro.to_owned(), path: format!("/{}", tail.trim_end_matches('/')) })
}
/// The Linux path of a Windows path seen from `distro`: `C:\a` → `/mnt/c/a` (WSL's default
/// automount root), `\\wsl.localhost\<distro>\a` → `/a`. `None` for another distro's share,
/// other network shares and relative paths.
pub fn linux_path(path: &Path, distro: &str) -> Option<String> {
if let Some(w) = parse(path) {
return w.distro.eq_ignore_ascii_case(distro).then_some(w.path);
}
let s = path.to_string_lossy().replace('\\', "/");
let s = s.strip_prefix("//?/").unwrap_or(&s);
let mut chars = s.chars();
let drive = chars.next().filter(char::is_ascii_alphabetic)?;
let rest = chars.as_str().strip_prefix(':')?;
if !(rest.is_empty() || rest.starts_with('/')) {
return None;
}
Some(format!("/mnt/{}{}", drive.to_ascii_lowercase(), rest.trim_end_matches('/')))
}
/// A distro name `wsl.exe -d` can be given safely: Windows creates them from letters, digits,
/// `.`, `_` and `-`. A leading `-` would be read as an option, so it is refused too.
pub fn is_valid_distro(name: &str) -> bool {
@@ -86,6 +104,57 @@ pub fn list_distros() -> Vec<String> {
Vec::new()
}
/// Where this machine reads `distro`'s file system.
pub fn share_root(distro: &str) -> std::path::PathBuf {
format!(r"\\wsl.localhost\{distro}").into()
}
/// The names of a Linux path, `.` dropped and `..` taking the name before it.
pub fn path_parts(linux: &str) -> Vec<&str> {
let mut parts: Vec<&str> = Vec::new();
for c in linux.split('/').filter(|c| !c.is_empty() && *c != ".") {
if c == ".." {
parts.pop();
} else {
parts.push(c);
}
}
parts
}
/// Where this machine reads the absolute path `linux` of `distro`: a drive mounted at
/// `/mnt/<drive>` is read directly, anything else through [`share_root`]. `..` goes up
/// within `linux`, never above the drive or the share.
pub fn windows_path(linux: &str, distro: &str) -> std::path::PathBuf {
let parts = path_parts(linux);
let base = match parts.as_slice() {
["mnt", drive, ..] if drive.len() == 1 && drive.chars().all(|c| c.is_ascii_alphabetic()) => {
let base = std::path::PathBuf::from(format!("{}:\\", drive.to_ascii_uppercase()));
return parts[2..].iter().fold(base, |p, c| p.join(c));
}
_ => share_root(distro),
};
parts.iter().fold(base, |p, c| p.join(c))
}
/// Runs `args` in `distro` without its shell and returns the standard output; a failed
/// run is an error with its output. `wsl.exe`'s own messages are UTF-16: their NULs go.
pub fn exec(distro: &str, args: &[&str], timeout: std::time::Duration) -> crate::IdeResult<String> {
use crate::cli_process::{CliTool, Decoding};
if !is_valid_distro(distro) {
return Err(crate::IdeError::invalid(format!("'{distro}' is not a WSL distribution name")));
}
let mut cmd = std::process::Command::new(EXE);
cmd.args(["-d", distro, "--exec"]).args(args);
let out = CliTool::new(EXE, Decoding::Utf8Lossy).run(cmd, timeout, None)?;
let (stdout, stderr) = (out.stdout.replace('\0', ""), out.stderr.replace('\0', ""));
if out.success {
return Ok(stdout);
}
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
Err(crate::IdeError::internal(format!("{EXE} -d {distro} --exec {}: {detail}", args.first().unwrap_or(&""))))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -103,6 +172,21 @@ mod tests {
assert_eq!(p(r"\\?\UNC\WSL.LOCALHOST\Ubuntu-24.04\home\me\app"), want);
}
#[test]
fn windows_paths_map_onto_the_distro() {
let l = |s: &str| linux_path(Path::new(s), "Ubuntu");
assert_eq!(l(r"C:\Users\me\app"), Some("/mnt/c/Users/me/app".into()));
assert_eq!(l(r"D:\"), Some("/mnt/d".into()));
assert_eq!(l("e:/work/x/"), Some("/mnt/e/work/x".into()));
assert_eq!(l(r"\\?\C:\proj"), Some("/mnt/c/proj".into()));
assert_eq!(l(r"\\wsl.localhost\ubuntu\home\me"), Some("/home/me".into()));
assert_eq!(l(r"\\wsl$\Debian\home\me"), None);
assert_eq!(l(r"\\server\share\a"), None);
assert_eq!(l(r"C:relative"), None);
assert_eq!(l("app"), None);
assert_eq!(l("/home/me"), None);
}
#[test]
fn distro_root_and_foreign_paths() {
assert_eq!(p(r"\\wsl.localhost\Debian"), Some(("Debian".to_owned(), "/".to_owned())));
@@ -127,6 +211,14 @@ mod tests {
assert!(parse_distro_list(b"").is_empty());
}
#[test]
fn linux_paths_are_read_on_their_drive_or_through_the_share() {
use std::path::PathBuf;
assert_eq!(windows_path("/mnt/d/lib/../x.py", "U"), PathBuf::from("D:\\").join("x.py"));
assert_eq!(windows_path("/usr/lib/a.py", "U"), share_root("U").join("usr").join("lib").join("a.py"));
assert_eq!(windows_path("/mnt/wsl/x", "U"), share_root("U").join("mnt").join("wsl").join("x"));
}
#[test]
fn distro_names_cannot_smuggle_options_or_paths() {
for bad in ["", "-d", "--exec", "a b", "a/b", r"a\b", "a;b", "a$(x)", "a\"b"] {
+1 -1
Переглянути файл
@@ -1,6 +1,6 @@
[package]
name = "ide-coverage"
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data)"
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo, xcodebuild) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data, xccov)"
version.workspace = true
edition.workspace = true
license.workspace = true
+1 -1
Переглянути файл
@@ -59,7 +59,7 @@ pub(crate) fn parse(text: &str, module: &str, module_dir: &Path) -> Accumulator
impl Accumulator {
/// Removes the branch data of lines whose branches are all taken or all missed.
fn drop_unanimous_branches(&mut self) {
pub(crate) fn drop_unanimous_branches(&mut self) {
for lines in self.files.values_mut() {
for acc in lines.values_mut() {
let taken = acc.branches.values().filter(|t| **t).count();
+26
Переглянути файл
@@ -13,6 +13,7 @@
//! | Ruby (rspec, minitest, rake, scripts) | SimpleCov (`coverage/.resultset.json`) | SimpleCov resultset |
//! | Go (`go test`) | `-coverprofile` | Go cover profile |
//! | Maven / Gradle tests | JaCoCo (plugin goals / an init script) | JaCoCo XML |
//! | Xcode tests (`xcodebuild test`) | `-enableCodeCoverage YES` | the result bundle, read with `xccov` |
//!
//! Lines in the model are 0-based, like every IPC coordinate.
@@ -24,6 +25,7 @@ mod jacoco;
mod lcov;
mod plan;
mod simplecov;
mod xccov;
pub use coveragepy::is_data_file;
pub use import::{import, import_data};
@@ -94,6 +96,8 @@ pub enum CoverageReportSpec {
Jacoco { dir: IpcPath },
/// The tool's raw data is exported to lcov by `argv` first (coverage.py: `… -m coverage lcov -o <lcov>`).
Exported { runner: String, argv: Vec<String>, cwd: IpcPath, env: BTreeMap<String, String>, lcov: IpcPath },
/// An Xcode result bundle, read with `xcrun xccov`; only files under `root` are kept.
Xccov { bundle: IpcPath, root: IpcPath },
}
/// A command line that installs a missing tool (run in the Run tool window).
@@ -234,9 +238,31 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult<CoverageSuite> {
let text = read_report(lcov)?;
Ok(lcov::parse(&text, cwd).finish(runner))
}
CoverageReportSpec::Xccov { bundle, root } => {
if !bundle.exists() {
return Err(IdeError::not_found(format!("the run produced no result bundle ({})", bundle.display())));
}
let report = xccov_json(&["--report", "--json"], bundle)?;
let archive = xccov_json(&["--archive", "--json"], bundle)?;
Ok(xccov::parse(&report, &archive, root)
.map_err(|e| IdeError::invalid(format!("unexpected xccov output: {e}")))?
.finish("xccov"))
}
}
}
/// `xcrun xccov view <args> <bundle>`'s output.
fn xccov_json(args: &[&str], bundle: &Path) -> IdeResult<String> {
let out = ide_core::process::prepare(Command::new("xcrun").args(["xccov", "view"]).args(args).arg(bundle))
.output()
.map_err(|e| IdeError::unavailable(format!("cannot run xcrun xccov: {e}")))?;
if !out.status.success() {
let text = ide_core::output_encoding::decode_tool_output(&out.stderr).trim().to_owned();
return Err(IdeError::not_found(format!("the result bundle has no coverage data: {text}")));
}
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}
fn read_report(path: &Path) -> IdeResult<String> {
std::fs::read_to_string(path).map_err(|e| match e.kind() {
std::io::ErrorKind::NotFound => {
+34
Переглянути файл
@@ -61,6 +61,9 @@ fn ready(
/// data; it must exist (the Gradle init script is written there). Probes tools,
/// so call it from a blocking thread.
pub fn prepare(root: &Path, config: &RunConfig, out: &Path) -> CoveragePrepared {
if config.kind == "xcode-test" {
return xcode(root, config, out);
}
let dir = wrap::run_dir(root, config);
let program = program_name(&config.command);
let first = config.args.first().map(String::as_str).unwrap_or_default();
@@ -336,6 +339,20 @@ fn python(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) -
ready("coverage.py", &config, command, args, report)
}
/// `xcodebuild test` with coverage on, into a result bundle of its own (`xcode::prepare_test`
/// adds it at launch).
fn xcode(root: &Path, config: &RunConfig, out: &Path) -> CoveragePrepared {
let mut config = config.clone();
if let Some(at) = config.args.iter().position(|a| a == "-enableCodeCoverage") {
config.args.drain(at..(at + 2).min(config.args.len()));
}
config.args.extend([s("-enableCodeCoverage"), s("YES")]);
let bundle = out.join("coverage.xcresult");
config.extras.params.insert(s(ide_run::xcode::RESULT_BUNDLE_PARAM), path(&bundle));
let report = CoverageReportSpec::Xccov { bundle: bundle.into(), root: root.to_path_buf().into() };
ready("xccov", &config, config.command.clone(), config.args.clone(), report)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -535,6 +552,23 @@ mod tests {
);
}
#[test]
fn xcode_tests_turn_coverage_on_into_their_own_bundle() {
let dir = tempfile::tempdir().unwrap();
let config = cfg("xcode-test", "xcodebuild", &["test", "-scheme", "App", "-enableCodeCoverage", "NO"]);
let p = prepare(dir.path(), &config, dir.path());
let (l, report) = launch(&p);
assert_eq!(l.args, ["test", "-scheme", "App", "-enableCodeCoverage", "YES"]);
let bundle = dir.path().join("coverage.xcresult");
assert_eq!(l.extras.params[ide_run::xcode::RESULT_BUNDLE_PARAM], bundle.to_string_lossy());
assert!(matches!(report, CoverageReportSpec::Xccov { bundle: b, .. } if (b.as_ref() as &Path) == bundle));
// A trailing flag without a value is replaced too.
let config = cfg("xcode-test", "xcodebuild", &["test", "-enableCodeCoverage"]);
let p = prepare(dir.path(), &config, dir.path());
assert_eq!(launch(&p).0.args, ["test", "-enableCodeCoverage", "YES"]);
}
#[test]
fn unknown_commands_are_unsupported() {
let dir = tempfile::tempdir().unwrap();
+188
Переглянути файл
@@ -0,0 +1,188 @@
//! Xcode coverage (`xcodebuild test -enableCodeCoverage YES`), read from the result bundle:
//!
//! - `xcrun xccov view --report --json <bundle>`: the targets and their files. Files that only
//! test bundles (`*.xctest`) compile are left out.
//! - `xcrun xccov view --archive --json <bundle>`: `{ "<path>": [{ line, isExecutable,
//! executionCount, subranges? }] }` for every file. A subrange is a region of the line with its
//! own count; a covered line with a missed region is partial.
use crate::Accumulator;
use serde::Deserialize;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path, PathBuf};
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Report {
#[serde(default)]
targets: Vec<Target>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Target {
#[serde(default)]
build_product_path: String,
#[serde(default)]
files: Vec<ReportFile>,
}
#[derive(Deserialize)]
struct ReportFile {
path: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Line {
line: u32,
is_executable: bool,
#[serde(default)]
execution_count: u64,
#[serde(default)]
subranges: Vec<Subrange>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Subrange {
column: u32,
#[serde(default)]
length: u32,
#[serde(default)]
execution_count: u64,
}
/// `path` inside the project as the project names it: the project and xccov may name it through
/// different symlinks (`/tmp` and `/private/tmp`). `None` outside the project and for DerivedData.
fn in_project(path: &Path, root: &Path, real_root: &Path) -> Option<PathBuf> {
let real;
let rel = match path.strip_prefix(root) {
Ok(rel) => rel,
Err(_) => {
real = path.canonicalize().ok()?;
real.strip_prefix(real_root).ok()?
}
};
let generated = rel.components().any(|c| matches!(c, Component::Normal(n) if n == "DerivedData" || n == ".build"));
(!generated).then(|| root.join(rel))
}
pub(crate) fn parse(report: &str, archive: &str, root: &Path) -> Result<Accumulator, serde_json::Error> {
let report: Report = serde_json::from_str(report)?;
let archive: BTreeMap<String, Vec<Line>> = serde_json::from_str(archive)?;
// App and framework sources: a file listed by an app or framework target counts even when a test
// bundle compiles it too (sources added to the test target's membership instead of `@testable`).
let is_test_bundle = |t: &Target| {
Path::new(&t.build_product_path)
.components()
.any(|c| matches!(c, Component::Normal(n) if Path::new(n).extension().is_some_and(|e| e == "xctest")))
};
let real_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
// Both views go through `in_project`, so they match however each spells the path.
let sources: BTreeSet<PathBuf> = report
.targets
.iter()
.filter(|t| !is_test_bundle(t))
.flat_map(|t| &t.files)
.filter_map(|f| in_project(Path::new(&f.path), root, &real_root))
.collect();
let mut acc = Accumulator::default();
for (file, lines) in &archive {
let Some(path) = in_project(Path::new(file), root, &real_root).filter(|p| sources.contains(p)) else {
continue;
};
acc.file(&path);
for l in lines.iter().filter(|l| l.is_executable && l.line > 0) {
let n = l.line - 1;
acc.line(&path, n, l.execution_count);
if !l.subranges.is_empty() {
acc.branch(&path, n, "line".into(), l.execution_count > 0);
for r in &l.subranges {
acc.branch(&path, n, format!("{}+{}", r.column, r.length), r.execution_count > 0);
}
}
}
}
// Regions are not branches: keep only the partial marks of lines with mixed regions.
acc.drop_unanimous_branches();
Ok(acc)
}
#[cfg(test)]
mod tests {
use super::*;
// Captured from `xcodebuild test -enableCodeCoverage YES` (Xcode 27.1) on an app with a unit
// test target; paths rewritten to /Users/me.
const REPORT: &str = include_str!("../tests/fixtures/xccov-report.json");
const ARCHIVE: &str = include_str!("../tests/fixtures/xccov-archive.json");
#[test]
fn reads_app_sources_and_leaves_out_test_bundles() {
let suite = parse(REPORT, ARCHIVE, Path::new("/Users/me/CovDemo")).unwrap().finish("xccov");
assert!(!suite.has_branches);
let names: Vec<_> = suite.files.iter().map(|f| f.path.as_ref() as &Path).collect();
assert_eq!(
names,
[Path::new("/Users/me/CovDemo/CovDemo/App.swift"), Path::new("/Users/me/CovDemo/CovDemo/Calculator.swift")]
);
// xccov's own totals for Calculator.swift: 14 of 17 lines.
let calc = &suite.files[1];
assert_eq!((calc.lines_total, calc.lines_covered), (17, 14));
let at = |n: u32| calc.lines.iter().find(|l| l.line == n).unwrap();
// `return nil` (line 8) never ran; `if b == 0 {` (line 7) ran with a missed region.
assert_eq!(at(7).hits, 0);
assert!(at(6).partial());
assert!(!at(1).partial());
}
#[test]
fn files_outside_the_project_are_dropped() {
let suite = parse(REPORT, ARCHIVE, Path::new("/Users/me/Other")).unwrap().finish("xccov");
assert!(suite.files.is_empty());
let report = r#"{"targets":[{"buildProductPath":"/d/App.app/App","files":[{"path":"/p/DerivedData/G.swift"},{"path":"/p/A.swift"}]}]}"#;
let line = r#"[{"line":1,"isExecutable":true,"executionCount":2}]"#;
let archive = format!(r#"{{"/p/DerivedData/G.swift":{line},"/p/A.swift":{line}}}"#);
let suite = parse(report, &archive, Path::new("/p")).unwrap().finish("xccov");
assert_eq!(suite.files.len(), 1);
assert_eq!(suite.files[0].lines[0].hits, 2);
}
#[test]
fn a_file_of_an_app_and_a_test_bundle_counts() {
let report = r#"{"targets":[
{"buildProductPath":"/d/App.app/App","files":[{"path":"/p/A.swift"}]},
{"buildProductPath":"/d/AppTests.xctest/AppTests","files":[{"path":"/p/A.swift"},{"path":"/p/T.swift"}]}]}"#;
let line = r#"[{"line":1,"isExecutable":true,"executionCount":1}]"#;
let archive = format!(r#"{{"/p/A.swift":{line},"/p/T.swift":{line}}}"#);
let suite = parse(report, &archive, Path::new("/p")).unwrap().finish("xccov");
let names: Vec<_> = suite.files.iter().map(|f| f.path.as_ref() as &Path).collect();
assert_eq!(names, [Path::new("/p/A.swift")]);
}
#[cfg(unix)]
#[test]
fn paths_through_another_symlink_map_to_the_project() {
let dir = tempfile::tempdir().unwrap();
let real = dir.path().canonicalize().unwrap().join("real");
std::fs::create_dir_all(&real).unwrap();
std::fs::write(real.join("A.swift"), "").unwrap();
let link = dir.path().join("link");
std::os::unix::fs::symlink(&real, &link).unwrap();
let file = real.join("A.swift").to_string_lossy().into_owned();
let report =
format!(r#"{{"targets":[{{"buildProductPath":"/d/App.app/App","files":[{{"path":"{file}"}}]}}]}}"#);
let archive = format!(r#"{{"{file}":[{{"line":1,"isExecutable":true,"executionCount":1}}]}}"#);
let suite = parse(&report, &archive, &link).unwrap().finish("xccov");
assert_eq!(suite.files.len(), 1);
assert_eq!(suite.files[0].path.as_ref() as &Path, link.join("A.swift"));
// The report names the file through the symlink, the archive by its real path.
let linked = link.join("A.swift").to_string_lossy().into_owned();
let report = report.replace(&file, &linked);
let suite = parse(&report, &archive, &link).unwrap().finish("xccov");
assert_eq!(suite.files.len(), 1);
assert_eq!(suite.files[0].lines[0].hits, 1);
}
}
+226
Переглянути файл
@@ -0,0 +1,226 @@
{
"/Users/me/CovDemo/CovDemo/App.swift": [
{
"isExecutable": false,
"line": 1
},
{
"isExecutable": false,
"line": 2
},
{
"isExecutable": false,
"line": 3
},
{
"isExecutable": false,
"line": 4
},
{
"executionCount": 1,
"isExecutable": true,
"line": 5
},
{
"executionCount": 1,
"isExecutable": true,
"line": 6
},
{
"executionCount": 1,
"isExecutable": true,
"line": 7
}
],
"/Users/me/CovDemo/CovDemo/Calculator.swift": [
{
"isExecutable": false,
"line": 1
},
{
"executionCount": 1,
"isExecutable": true,
"line": 2
},
{
"executionCount": 1,
"isExecutable": true,
"line": 3
},
{
"executionCount": 1,
"isExecutable": true,
"line": 4
},
{
"isExecutable": false,
"line": 5
},
{
"executionCount": 1,
"isExecutable": true,
"line": 6
},
{
"executionCount": 1,
"isExecutable": true,
"line": 7,
"subranges": [
{
"column": 19,
"executionCount": 0,
"length": 0
}
]
},
{
"executionCount": 0,
"isExecutable": true,
"line": 8
},
{
"executionCount": 1,
"isExecutable": true,
"line": 9,
"subranges": [
{
"column": 1,
"executionCount": 0,
"length": 9
}
]
},
{
"executionCount": 1,
"isExecutable": true,
"line": 10
},
{
"executionCount": 1,
"isExecutable": true,
"line": 11
},
{
"isExecutable": false,
"line": 12
},
{
"executionCount": 1,
"isExecutable": true,
"line": 13
},
{
"executionCount": 1,
"isExecutable": true,
"line": 14,
"subranges": [
{
"column": 18,
"executionCount": 0,
"length": 0
}
]
},
{
"executionCount": 0,
"isExecutable": true,
"line": 15
},
{
"executionCount": 1,
"isExecutable": true,
"line": 16,
"subranges": [
{
"column": 1,
"executionCount": 0,
"length": 9
},
{
"column": 26,
"executionCount": 0,
"length": 0
}
]
},
{
"executionCount": 0,
"isExecutable": true,
"line": 17
},
{
"executionCount": 1,
"isExecutable": true,
"line": 18,
"subranges": [
{
"column": 1,
"executionCount": 0,
"length": 9
}
]
},
{
"executionCount": 1,
"isExecutable": true,
"line": 19
},
{
"executionCount": 1,
"isExecutable": true,
"line": 20
}
],
"/Users/me/CovDemo/CovDemoTests/CalculatorTests.swift": [
{
"isExecutable": false,
"line": 1
},
{
"isExecutable": false,
"line": 2
},
{
"isExecutable": false,
"line": 3
},
{
"isExecutable": false,
"line": 4
},
{
"executionCount": 1,
"isExecutable": true,
"line": 5
},
{
"executionCount": 1,
"isExecutable": true,
"line": 6
},
{
"executionCount": 1,
"isExecutable": true,
"line": 7
},
{
"isExecutable": false,
"line": 8
},
{
"executionCount": 1,
"isExecutable": true,
"line": 9
},
{
"executionCount": 1,
"isExecutable": true,
"line": 10
},
{
"executionCount": 1,
"isExecutable": true,
"line": 11
}
]
}
+140
Переглянути файл
@@ -0,0 +1,140 @@
{
"coveredLines": 28,
"executableLines": 31,
"lineCoverage": 0.9032258064516129,
"targets": [
{
"buildProductPath": "/Users/me/Library/Developer/Xcode/DerivedData/CovDemo-abc/Build/Products/Debug-iphonesimulator/CovDemo.app/CovDemo",
"coveredLines": 18,
"executableLines": 21,
"files": [
{
"coveredLines": 14,
"executableLines": 17,
"functions": [
{
"coveredLines": 3,
"executableLines": 3,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 2,
"name": "Calculator.add(_:_:)"
},
{
"coveredLines": 5,
"executableLines": 6,
"executionCount": 1,
"lineCoverage": 0.8333333333333334,
"lineNumber": 6,
"name": "Calculator.divide(_:_:)"
},
{
"coveredLines": 6,
"executableLines": 8,
"executionCount": 1,
"lineCoverage": 0.75,
"lineNumber": 13,
"name": "Calculator.describe(_:)"
}
],
"lineCoverage": 0.8235294117647058,
"name": "Calculator.swift",
"path": "/Users/me/CovDemo/CovDemo/Calculator.swift"
},
{
"coveredLines": 4,
"executableLines": 4,
"functions": [
{
"coveredLines": 3,
"executableLines": 3,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 5,
"name": "CovDemoApp.body.getter"
},
{
"coveredLines": 1,
"executableLines": 1,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 6,
"name": "closure #1 in CovDemoApp.body.getter"
}
],
"lineCoverage": 1,
"name": "App.swift",
"path": "/Users/me/CovDemo/CovDemo/App.swift"
}
],
"lineCoverage": 0.8571428571428571,
"name": "CovDemo.app"
},
{
"buildProductPath": "/Users/me/Library/Developer/Xcode/DerivedData/CovDemo-abc/Build/Products/Debug-iphonesimulator/CovDemo.app/PlugIns/CovDemoTests.xctest/CovDemoTests",
"coveredLines": 10,
"executableLines": 10,
"files": [
{
"coveredLines": 10,
"executableLines": 10,
"functions": [
{
"coveredLines": 3,
"executableLines": 3,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 5,
"name": "CalculatorTests.testAdd()"
},
{
"coveredLines": 1,
"executableLines": 1,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 6,
"name": "implicit closure #1 in CalculatorTests.testAdd()"
},
{
"coveredLines": 1,
"executableLines": 1,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 6,
"name": "implicit closure #2 in CalculatorTests.testAdd()"
},
{
"coveredLines": 3,
"executableLines": 3,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 9,
"name": "CalculatorTests.testDivide()"
},
{
"coveredLines": 1,
"executableLines": 1,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 10,
"name": "implicit closure #1 in CalculatorTests.testDivide()"
},
{
"coveredLines": 1,
"executableLines": 1,
"executionCount": 1,
"lineCoverage": 1,
"lineNumber": 10,
"name": "implicit closure #2 in CalculatorTests.testDivide()"
}
],
"lineCoverage": 1,
"name": "CalculatorTests.swift",
"path": "/Users/me/CovDemo/CovDemoTests/CalculatorTests.swift"
}
],
"lineCoverage": 1,
"name": "CovDemoTests.xctest"
}
]
}
+7 -4
Переглянути файл
@@ -362,21 +362,24 @@ fn find_binary_in(
/// [`find_binary`], plus Xcode's toolchain on macOS (`xcrun -f lldb-dap`): Xcode ships
/// lldb-dap without putting it on `PATH`.
pub fn resolve_binary(command: &str, cwd: &Path) -> Option<PathBuf> {
find_binary(command, cwd).or_else(|| xcrun_tool(command))
find_binary(command, cwd).or_else(|| xcrun_tool(command, cwd))
}
/// `cwd`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
#[cfg(target_os = "macos")]
fn xcrun_tool(command: &str) -> Option<PathBuf> {
fn xcrun_tool(command: &str, cwd: &Path) -> Option<PathBuf> {
if command != "lldb-dap" {
return None;
}
let out = std::process::Command::new("/usr/bin/xcrun").args(["-f", command]).stderr(Stdio::null()).output().ok()?;
let mut cmd = std::process::Command::new("/usr/bin/xcrun");
cmd.current_dir(cwd);
let out = ide_core::process::prepare(&mut cmd).args(["-f", command]).stderr(Stdio::null()).output().ok()?;
let path = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
(out.status.success() && is_executable(&path, false)).then_some(path)
}
#[cfg(not(target_os = "macos"))]
fn xcrun_tool(_command: &str) -> Option<PathBuf> {
fn xcrun_tool(_command: &str, _cwd: &Path) -> Option<PathBuf> {
None
}
+2 -1
Переглянути файл
@@ -618,9 +618,10 @@ pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult<Option<Debug
/// lldb-dap's ``/usr/lib/swift/libswiftCore.dylib`swift_willThrow`` for a frame without
/// debug info. Opening it would show an error tab; without a path the stop selects the
/// first frame with source instead. Non-file paths (`jdt://`, `<node_internals>`) stay.
/// Rooted rather than absolute: on Windows a `/usr/…` path has a root but no drive.
fn is_pseudo_path(source: Option<&Value>, path: &str) -> bool {
let reference = source.and_then(|s| s.get("sourceReference")).and_then(Value::as_i64).unwrap_or(0);
reference > 0 && Path::new(path).is_absolute() && !Path::new(path).exists()
reference > 0 && Path::new(path).has_root() && !Path::new(path).exists()
}
/// DAP stack frame → [`StackFrame`] (1-based → 0-based).
+27 -2
Переглянути файл
@@ -391,9 +391,12 @@ impl Manifest {
if !self.capabilities.reasons.is_empty() {
self.needs_api("`capabilities.reasons`", 19)?;
}
let derived = self.derived_capabilities();
for (key, text) in &self.capabilities.reasons {
if !self.capabilities.all().any(|c| c.to_string() == *key) {
return Err(format!("capabilities.reasons: {key:?} is not under `required` or `optional`"));
if !self.capabilities.all().chain(&derived).any(|c| c.to_string() == *key) {
return Err(format!(
"capabilities.reasons: {key:?} is not under `required` or `optional`, nor comes from a contribution"
));
}
if text.trim().is_empty() || text.chars().count() > MAX_CAPABILITY_REASON {
return Err(format!(
@@ -522,6 +525,17 @@ impl Manifest {
Ok(())
}
/// Capabilities the plugin's contributions bring without being listed under `[capabilities]`:
/// `java.agent` from `[[contributes.javaAgents]]`, `project.read` from
/// `[[contributes.documentIndexers]]` (the extension points in `ide-host` add them to the grant).
pub fn derived_capabilities(&self) -> Vec<Capability> {
[("javaAgents", Capability::JavaAgent), ("documentIndexers", Capability::ProjectRead)]
.into_iter()
.filter(|(point, _)| self.contributes.contains_key(*point))
.map(|(_, cap)| cap)
.collect()
}
/// The declarations of one extension point: `[[contributes.x]]` gives
/// several, `[contributes.x]` one.
pub fn declarations(&self, point: &str) -> Vec<toml::Value> {
@@ -843,6 +857,17 @@ required = [\"lsp:phoxite\"]
assert!(err(&src(&long)).contains("1 to 500 characters"));
}
#[test]
fn capability_reasons_explain_capabilities_that_contributions_bring() {
let src = |rest: &str| format!("{}{rest}", BASE.replace("^1.2", "^1.19"));
let reason = "[capabilities.reasons]\n\"java.agent\" = \"Captures the SQL MyBatis runs.\"\n";
let agent = "[[contributes.javaAgents]]\npath = \"agent.jar\"\n";
let m = Manifest::parse(&src(&format!("{reason}{agent}"))).unwrap();
assert_eq!(m.derived_capabilities(), [Capability::JavaAgent]);
assert_eq!(m.capabilities.reason(&Capability::JavaAgent), Some("Captures the SQL MyBatis runs."));
assert!(err(&src(reason)).contains("nor comes from a contribution"), "no javaAgents declaration");
}
#[test]
fn the_clipboard_read_capability_needs_api_1_11() {
let caps = "[capabilities]\noptional = [\"clipboard.read\"]\n";
+37 -8
Переглянути файл
@@ -448,18 +448,39 @@ pub async fn format(
options: FormatOptions,
) -> IdeResult<Vec<TextEdit>> {
let project = host.project(window)?;
let snap = project.documents.snapshot(doc)?;
let source = FormatSource {
path: snap.path,
language: snap.language,
text: snap.text,
doc: Some(doc),
version: snap.version,
read_only: snap.read_only,
// A notebook cell is a document of the language servers only: `documents` holds what the
// editor opened, so ⌥⌘L in a cell used to answer "document DocId#N is not open".
let source = match project.documents.snapshot(doc) {
Ok(snap) => FormatSource {
path: snap.path,
language: snap.language,
text: snap.text,
doc: Some(doc),
version: snap.version,
read_only: snap.read_only,
},
Err(e) => match project.lsp.cell_text(doc) {
Some(cell) => FormatSource {
path: cell_script_path(&cell.path).into(),
language: cell.language,
text: cell.text,
doc: Some(doc),
version: cell.version,
read_only: false,
},
None => return Err(e),
},
};
format_source(host, window, &project, source, range, options).await
}
/// The file name a formatter is given for a cell's text. It only picks the language and the
/// settings: the text arrives on stdin. The notebook's own `.ipynb` would make Ruff parse the
/// cell as notebook JSON instead of Python.
fn cell_script_path(notebook: &Path) -> PathBuf {
notebook.with_extension("py")
}
/// Format a separate snapshot using the file's language, settings and formatter.
pub async fn format_text(
host: &Host,
@@ -1385,6 +1406,14 @@ mod tests {
assert!(project_configured(Oxfmt, &root.join("c/src/app.ts")));
}
#[test]
fn a_cell_is_formatted_as_python_rather_than_as_notebook_json() {
// Ruff reads the extension of `--stdin-filename` to decide what the text is; `.ipynb`
// made it expect notebook JSON and fail on the cell's source.
assert_eq!(cell_script_path(Path::new("/p/notebooks/a.ipynb")), Path::new("/p/notebooks/a.py"));
assert_eq!(cell_script_path(Path::new("/p/a.b.ipynb")), Path::new("/p/a.b.py"));
}
#[test]
fn only_the_typescript_server_languages_give_way_to_an_installed_project_formatter() {
let dir = tempfile::tempdir().unwrap();
+10
Переглянути файл
@@ -27,10 +27,12 @@ pub mod relay;
mod requests;
pub mod rpc;
pub mod shell_env;
mod swiftlint;
pub mod trust;
mod ts_code_style;
mod tsc_watch;
pub mod web_server;
mod xcode_env;
pub use project::{Project, history_retention};
@@ -463,6 +465,9 @@ impl Host {
if let Some(phpstan) = &project.phpstan {
phpstan.stop();
}
if let Some(swiftlint) = &project.swiftlint {
swiftlint.stop();
}
if let Some(watch) = &project.tsc_watch {
watch.stop();
}
@@ -546,6 +551,8 @@ impl Host {
if let Some(retired) = retired {
let _ = retired.join();
}
// The project's buffers, index and caches are dropped: hand their pages back.
ide_core::memory::release_free_pages_soon();
})
}
@@ -703,6 +710,9 @@ impl Host {
if let Some(phpstan) = &project.phpstan {
phpstan.stop();
}
if let Some(swiftlint) = &project.swiftlint {
swiftlint.stop();
}
if let Some(watch) = &project.tsc_watch {
watch.stop();
}
+7 -7
Переглянути файл
@@ -172,15 +172,15 @@ impl Policy {
})
}
fn resolve(&self, path: &Path) -> Option<PathBuf> {
policy::resolve(self.mode, &self.listed, &self.decisions, &self.recents, self.home.as_deref(), path)
fn resolve(&self, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
policy::resolve(self.mode, &self.listed, &self.decisions, &self.recents, self.home.as_deref(), path, within)
}
}
/// The root of the project that serves `path` in the background under the current
/// settings and trust decisions. Opens nothing.
pub(crate) fn serving_root(host: &Host, path: &Path) -> Option<PathBuf> {
Policy::current(host)?.resolve(path)
/// settings and trust decisions; with `within`, only a root strictly inside it. Opens nothing.
pub(crate) fn serving_root(host: &Host, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
Policy::current(host)?.resolve(path, within)
}
/// How long a project may stay idle; `None` when `minutes` is 0 (never unloaded).
@@ -283,7 +283,7 @@ impl BackgroundProjects {
state.opening = Some(root.to_path_buf());
Opening(self)
};
if serving_root(host, root).as_deref() != Some(root) {
if serving_root(host, root, None).as_deref() != Some(root) {
return Err(IdeError::unavailable(format!("{} is not served in the background", root.display())));
}
let limit = project_limit(host.global_settings.effective().mcp_server.background_project_limit);
@@ -463,7 +463,7 @@ impl Host {
}
let policy = Policy::current(self);
for root in roots {
if policy.as_ref().and_then(|policy| policy.resolve(&root)).as_deref() != Some(&root) {
if policy.as_ref().and_then(|policy| policy.resolve(&root, None)).as_deref() != Some(&root) {
self.mcp_background.detach(self, &root, None);
}
}
+59 -13
Переглянути файл
@@ -10,7 +10,9 @@ use std::path::{Path, PathBuf};
/// folders containing it and, in `Trusted` mode, of the trusted projects, the trusted recent
/// projects and the nearest trusted folder with a project marker. `None` when the mode is
/// `Off`, when `path` is relative or missing, and when no folder qualifies. Listed and
/// recent folders that are gone or not absolute paths are skipped.
/// recent folders that are gone or not absolute paths are skipped. With `within` (the root
/// of the open project containing `path`) only folders strictly inside it count, and the
/// others aren't looked up on disk.
pub(crate) fn resolve(
mode: McpBackgroundProjects,
listed: &[PathBuf],
@@ -18,6 +20,7 @@ pub(crate) fn resolve(
recents: &[PathBuf],
home: Option<&Path>,
path: &Path,
within: Option<&Path>,
) -> Option<PathBuf> {
let by_trust = match mode {
McpBackgroundProjects::Off => return None,
@@ -28,23 +31,37 @@ pub(crate) fn resolve(
return None;
}
let path = dunce::canonicalize(path).ok()?;
let within = within.map(|root| (root, dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf())));
let open = within.as_ref().map(|(_, root)| root.as_path());
// Only folders strictly inside `within` count. An entry is checked by its text before it
// is canonicalized, so folders elsewhere (a network mount among them) aren't touched; one
// that reaches inside through a link from elsewhere is left out.
let inside = |entry: &Path, canonical: bool| {
within.as_ref().is_none_or(|(raw, root)| {
(entry.starts_with(root) && entry != root) || (!canonical && entry.starts_with(raw) && entry != *raw)
})
};
// A relative entry would be read against the working directory, which says nothing
// about the user's folders (`/` for an app started from the Finder).
let existing = |entry: &PathBuf| entry.is_absolute().then(|| dunce::canonicalize(entry).ok()).flatten();
let existing = |entry: &PathBuf| {
(entry.is_absolute() && inside(entry, false)).then(|| dunce::canonicalize(entry).ok()).flatten()
};
// A listed folder serves its subtree whether or not it is trusted: it opens restricted then.
let mut candidates: Vec<PathBuf> = listed.iter().filter_map(existing).collect();
if by_trust {
candidates.extend(decisions.projects.iter().filter(|p| trusted_here(decisions, p)).cloned());
let projects = decisions.projects.iter().filter(|p| inside(p, true));
candidates.extend(projects.filter(|p| trusted_here(decisions, p)).cloned());
// Remote projects are recorded as locations (`ssh://…`), not as folders of this machine.
let local = recents.iter().filter(|p| !p.to_string_lossy().contains("://"));
candidates.extend(local.filter_map(existing).filter(|p| trusted_here(decisions, p)));
let home = home.map(|h| dunce::canonicalize(h).unwrap_or_else(|_| h.to_path_buf()));
// A trusted location and the home folder hold projects; neither is one.
candidates
.extend(marker_root(&path).filter(|a| {
.extend(marker_root(&path, open).filter(|a| {
trusted_here(decisions, a) && !decisions.locations.contains(a) && home.as_ref() != Some(a)
}));
}
candidates.retain(|candidate| inside(candidate, true));
innermost(&candidates, &path).cloned()
}
@@ -64,9 +81,10 @@ fn trusted_here(decisions: &TrustDecisions, root: &Path) -> bool {
/// The first ancestor of `path`, itself included, that looks like a project: it holds an
/// `.openidea` folder, or a `.git` or `.jj` entry (a linked worktree's `.git` is a file).
fn marker_root(path: &Path) -> Option<PathBuf> {
/// The search stops short of `within`.
fn marker_root(path: &Path, within: Option<&Path>) -> Option<PathBuf> {
let marked = |dir: &&Path| dir.join(".openidea").is_dir() || dir.join(".git").exists() || dir.join(".jj").exists();
path.ancestors().find(marked).map(Path::to_path_buf)
path.ancestors().take_while(|dir| Some(*dir) != within).find(marked).map(Path::to_path_buf)
}
#[cfg(test)]
@@ -159,7 +177,35 @@ mod tests {
restricted: paths(restricted),
};
let home = base.join("home");
let found = resolve(*mode, &paths(listed), &decisions, &paths(recents), Some(&home), &base.join(path));
let found =
resolve(*mode, &paths(listed), &decisions, &paths(recents), Some(&home), &base.join(path), None);
assert_eq!(found, expected.map(|root| base.join(root)), "{what}");
}
}
#[test]
fn inside_an_open_project_only_a_folder_below_its_root_serves_a_path() {
let (_tmp, base) = tree();
let at = |folders: &[&str]| folders.iter().map(|folder| base.join(folder)).collect::<Vec<_>>();
let trusted = |projects: &[&str], locations: &[&str]| TrustDecisions {
projects: at(projects),
locations: at(locations),
..Default::default()
};
let within = base.join("code/app");
let (none, root, location) = (trusted(&[], &[]), trusted(&["code/app"], &[]), trusted(&[], &["code"]));
let (src, nested) = ("code/app/src", "code/app/.wt/feature");
let below = trusted(&[nested], &[]);
let nested_src = "code/app/.wt/feature/src";
for (what, mode, listed, decisions, path, expected) in [
("a listed folder below the root", Listed, &[src][..], &none, src, Some(src)),
("the listed root and a listed folder around it", Listed, &["code", "code/app"], &none, src, None),
("the trusted root", Trusted, &[], &root, src, None),
("the root's own marker", Trusted, &[], &location, src, None),
("a repository below the root", Trusted, &[], &location, nested_src, Some(nested)),
("a trusted project below the root", Trusted, &[], &below, nested_src, Some(nested)),
] {
let found = resolve(mode, &at(listed), decisions, &[], None, &base.join(path), Some(&within));
assert_eq!(found, expected.map(|root| base.join(root)), "{what}");
}
}
@@ -170,7 +216,7 @@ mod tests {
let listed = [base.join("code/app"), PathBuf::from("code/app"), PathBuf::from(".")];
let none = TrustDecisions::default();
for path in ["code/app/src", ".", "src"] {
assert_eq!(resolve(Listed, &listed, &none, &[], None, Path::new(path)), None, "{path}");
assert_eq!(resolve(Listed, &listed, &none, &[], None, Path::new(path), None), None, "{path}");
}
}
@@ -188,7 +234,7 @@ mod tests {
("the same folder listed by its full path", Listed, absolute, &none, &[][..], Some(&here)),
("the same folder recent by its full path", Trusted, &[][..], &around, absolute, Some(&here)),
] {
assert_eq!(resolve(mode, listed, decisions, recents, None, &here).as_ref(), expected, "{what}");
assert_eq!(resolve(mode, listed, decisions, recents, None, &here, None).as_ref(), expected, "{what}");
}
}
@@ -200,13 +246,13 @@ mod tests {
let none = TrustDecisions::default();
// Listed by the link, asked for by the real path, and the other way round (`/tmp` and `/private/tmp`).
for (listed, path) in [("link/app", "code/app/src"), ("code/app", "link/app/src"), ("link/app", "link/app")] {
let found = resolve(Listed, &[base.join(listed)], &none, &[], None, &base.join(path));
let found = resolve(Listed, &[base.join(listed)], &none, &[], None, &base.join(path), None);
assert_eq!(found, Some(base.join("code/app")), "{listed} for {path}");
}
let trusted = TrustDecisions { locations: vec![base.join("code")], ..Default::default() };
let recent = [base.join("link/plain")];
assert_eq!(
resolve(Trusted, &[], &trusted, &recent, None, &base.join("link/plain/src")),
resolve(Trusted, &[], &trusted, &recent, None, &base.join("link/plain/src"), None),
Some(base.join("code/plain"))
);
}
@@ -219,10 +265,10 @@ mod tests {
std::fs::create_dir_all(base.join("ssh:/box/app/src")).unwrap();
let recent = [PathBuf::from(format!("{}/ssh://box/app", base.display()))];
let trusted = TrustDecisions { locations: vec![base.clone()], ..Default::default() };
assert_eq!(resolve(Trusted, &[], &trusted, &recent, None, &base.join("ssh:/box/app/src")), None);
assert_eq!(resolve(Trusted, &[], &trusted, &recent, None, &base.join("ssh:/box/app/src"), None), None);
let local = [base.join("ssh:/box/app")];
assert_eq!(
resolve(Trusted, &[], &trusted, &local, None, &base.join("ssh:/box/app/src")),
resolve(Trusted, &[], &trusted, &local, None, &base.join("ssh:/box/app/src"), None),
Some(base.join("ssh:/box/app"))
);
}
+3 -3
Переглянути файл
@@ -708,7 +708,7 @@ async fn a_host_that_serves_none_refuses_every_folder_whatever_the_settings_say(
let root = f.root("inventory");
f.host.mcp_background.serve_none();
let registry = crate::mcp::Registry::new(f.host.clone());
assert_eq!(registry.resolve(&root.join("parts")), None);
assert_eq!(registry.resolve(&root.join("parts"), None), None);
assert_eq!(f.refused("inventory"), format!("{} is not served in the background", root.display()));
assert!(f.loaded().is_empty());
assert!(f.host.projects().is_empty());
@@ -726,11 +726,11 @@ async fn a_call_that_arrives_after_the_server_was_turned_off_opens_nothing() {
assert!(f.loaded().is_empty());
assert!(f.host.projects().is_empty());
let registry = crate::mcp::Registry::new(f.host.clone());
assert_eq!(registry.resolve(&root.join("parts")), None, "no folder is served with the server off");
assert_eq!(registry.resolve(&root.join("parts"), None), None, "no folder is served with the server off");
assert!(registry.tools(&root).is_err());
f.set("enabled", json!(true));
assert_eq!(registry.resolve(&root.join("parts")), Some(root));
assert_eq!(registry.resolve(&root.join("parts"), None), Some(root));
f.open("inventory");
assert_eq!(f.loaded(), ["inventory"]);
}
+4
Переглянути файл
@@ -213,6 +213,7 @@ In OpenIDEA the user is asked first, then the IDE's own Debug action starts the
before-launch tasks and Debug tool window as when you press Debug. This needs a project window (it does not work \
for a background project without one). Program output goes to the Debug console, not into this tool's result.",
|call| async move {
call.needs_window()?;
let target =
execution_target(call.opt_str("configurationName")?, call.opt_str("filePath")?, call.opt_i64("line")?)?;
let envs = call.args.get("envs").filter(|v| !v.is_null()).map(|_| call.str_map("envs")).transpose()?;
@@ -490,6 +491,7 @@ optional `message` from the last verification. Function and data breakpoints are
`function:` and `data:`. Call this before RESUME to check that an enabled breakpoint will be hit. Breakpoints set \
with `xdebug_set_breakpoint` are the same ones the editor shows and persists.",
|call| async move {
call.needs_window()?;
// The editor mirrors every change to the backend synchronously on request, so
// flushing its pending debounced syncs makes this the same list the editor shows.
call.ask(McpUiRequest::FlushBreakpoints).await?;
@@ -589,6 +591,7 @@ suspends the thread and does not implement one-shot or stack-logging breakpoints
`lineText` so the placement can be checked before RESUME. The breakpoint is shown in the editor's gutter and \
persists with the project; this needs a project window.",
|call| async move {
call.needs_window()?;
let _guard = BREAKPOINT_EDITS.lock().await;
let files = editor_breakpoints(&call);
let (path, line0, relocate_from) = if let Some(id) = call.opt_str("breakpointId")? {
@@ -680,6 +683,7 @@ that file are removed; with neither (the default `owner=agent`), all line breakp
Removal of a missing breakpoint is not an error: `removed` says whether anything was removed. `owner` is accepted \
for compatibility. Function and data breakpoints are managed in the IDE; this needs a project window.",
|call| async move {
call.needs_window()?;
let _guard = BREAKPOINT_EDITS.lock().await;
let owner = call.opt_str("owner")?;
if owner.as_deref().is_some_and(|o| o != "agent" && o != "user") {
+1
Переглянути файл
@@ -429,6 +429,7 @@ Requires a filePath parameter containing the path to the file to open.
The file path can be absolute or relative to the project root.
Optionally puts the caret at a 1-based line and column.",
|call| async move {
call.needs_window()?;
let raw = call.str("filePath")?;
// Opening shows the file to the user: outside the project the user agrees first.
let path = call.resolve_readable(&raw).await?;
+5 -17
Переглянути файл
@@ -1,7 +1,7 @@
use super::page::{OFFSET, Page};
use super::search::{PathScope, paths_param};
use super::tool::{Call, Output, Param, ParamType, Tool};
use ide_core::{Diagnostic, IdeError, IdeResult, Severity};
use ide_core::{Diagnostic, IdeResult, Severity};
use serde_json::{Map, Value, json};
/// Problems `get_project_problems` lists by default.
@@ -51,28 +51,16 @@ Lines and UTF-16 columns are 1-based.",
]
}
/// Editors and the Problems view are reported by a window: a project served in the
/// background has none, and says so instead of answering as if nothing were open.
fn reported_by_a_window(call: &Call) -> IdeResult<()> {
if !super::BackgroundProjects::is_key(call.window()) {
return Ok(());
}
let (tool, root) = (&call.tool, call.root().display());
Err(IdeError::unavailable(format!(
"{tool} needs the project open in a window: {root} is served in the background."
)))
}
/// [`reported_by_a_window`] for the Problems view, which `check_files` stands in for.
/// [`Call::needs_window`] for the Problems view, which `check_files` stands in for.
fn problems_reported_by_a_window(call: &Call) -> IdeResult<()> {
reported_by_a_window(call).map_err(|mut error| {
call.needs_window().map_err(|mut error| {
error.message.push_str(" Use check_files for diagnostics.");
error
})
}
async fn open_editors(call: Call) -> IdeResult<Output> {
reported_by_a_window(&call)?;
call.needs_window()?;
let paths = PathScope::of(&call)?;
let windows = call.host.mcp_windows(call.root());
let open = call.host.mcp_reports.editors(&windows);
@@ -84,7 +72,7 @@ async fn open_editors(call: Call) -> IdeResult<Output> {
}
async fn current_file(call: Call) -> IdeResult<Output> {
reported_by_a_window(&call)?;
call.needs_window()?;
let editor = call.host.mcp_reports.focused(call.window());
Output::json(match editor {
None => json!({}),
+68 -15
Переглянути файл
@@ -18,7 +18,7 @@ pub mod service;
mod symbols;
mod tool;
pub(crate) use tool::trusted_attachments;
pub(crate) use tool::{PROJECT_PATH, trusted_attachments};
mod util;
use crate::Host;
@@ -28,6 +28,7 @@ pub use reports::{
FileProblems, FocusedEditor, Reports, mcp_report_problems, mcp_set_focused_editor, mcp_set_open_editors,
};
pub use run::agent::{AGENT_PARAM, AgentRun, AgentRuns, NAME_PREFIX, SHELL_PARAM};
use serde_json::json;
pub use service::{McpServerStatus, McpService};
use std::path::{Path, PathBuf};
use std::sync::Arc;
@@ -55,7 +56,8 @@ fn tools() -> Vec<tool::Tool> {
tools
}
// Checked both when listing and calling, so a later trust change takes effect immediately.
// What a project lists. A call checks the trust it has then (`call_with_client`), so a later
// trust change takes effect immediately.
fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
trusted || tool.read_only
}
@@ -63,11 +65,36 @@ fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
fn tools_for(host: &Host, root: &Path, trusted: bool) -> Vec<ide_mcp::Tool> {
let mut all: Vec<_> = tools().into_iter().map(|t| t.metadata).collect();
if let Some(plugins) = host.plugin_host() {
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| tool));
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| with_project_path(tool)));
}
all.into_iter().filter(|t| allowed(t, trusted)).collect()
}
/// A plugin's tool as clients see it: it takes `projectPath` like every other tool, which the
/// plugin gets only if its own schema takes it (`PluginHost::call_mcp_tool`).
fn with_project_path(mut tool: ide_mcp::Tool) -> ide_mcp::Tool {
if let Some(schema) = tool.input_schema.as_object_mut()
&& let Some(properties) = schema.entry("properties").or_insert_with(|| json!({})).as_object_mut()
{
properties.entry(tool::PROJECT_PATH).or_insert_with(tool::project_path);
}
tool
}
/// The tool a call runs: a plugin's or a built-in one.
enum Found {
Plugin { plugins: Arc<crate::plugins::PluginHost>, plugin: String, tool: String, metadata: ide_mcp::Tool },
Builtin(tool::Tool),
}
impl Found {
fn writes(&self) -> bool {
match self {
Self::Plugin { metadata, .. } => !metadata.read_only,
Self::Builtin(tool) => !tool.metadata.read_only,
}
}
}
/// Lists the built-in IDE and plugin-contributed MCP tools visible to `window`.
pub(crate) fn list_tools_for_window(host: &Host, window: &str) -> Vec<ide_mcp::Tool> {
match host.project(window).ok().filter(|p| !p.light) {
@@ -110,6 +137,16 @@ impl Registry {
}
}
/// The tool `name` for `root`: a plugin's first. Loads nothing.
fn find(&self, root: &Path, name: &str) -> Option<Found> {
if let Some(plugins) = self.0.plugin_host()
&& let Some((plugin, tool, metadata)) = plugins.mcp_tools(root).into_iter().find(|(_, _, t)| t.name == name)
{
return Some(Found::Plugin { plugins, plugin, tool, metadata });
}
tools().into_iter().find(|t| t.metadata.name == name).map(Found::Builtin)
}
/// Whether the tools listed for `root` include those that write and run. Opens nothing:
/// a background project that is not loaded is judged as its open will judge it.
fn lists_as_trusted(&self, root: &Path) -> Result<bool, String> {
@@ -119,7 +156,7 @@ impl Registry {
if let Some(project) = self.0.mcp_background.project(&self.0, root) {
return Ok(project.is_trusted());
}
if background::serving_root(&self.0, root).as_deref() == Some(root) {
if background::serving_root(&self.0, root, None).as_deref() == Some(root) {
return Ok(self.0.trust.window_trusted(root).unwrap_or(false));
}
Err("project is no longer open".into())
@@ -138,13 +175,21 @@ impl ToolRegistry for Registry {
let attached: Vec<_> = open.iter().flat_map(|p| tool::attached_projects(&p.root)).collect();
open.into_iter().map(|p| p.root.clone()).chain(attached).chain(self.0.mcp_reports.remote_roots()).collect()
}
fn resolve(&self, path: &Path) -> Option<PathBuf> {
background::serving_root(&self.0, path)
fn resolve(&self, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
// A remote window's project holds that host's folders, even where this computer has
// folders at the same paths.
if within.is_some_and(|root| self.0.mcp_reports.remote_roots().iter().any(|remote| remote == root)) {
return None;
}
background::serving_root(&self.0, path, within)
}
fn tools(&self, root: &Path) -> Result<Vec<ide_mcp::Tool>, String> {
let trusted = self.lists_as_trusted(root)?;
Ok(tools_for(&self.0, root, trusted))
}
fn tools_without_project(&self) -> Vec<ide_mcp::Tool> {
tools_for(&self.0, Path::new(""), true)
}
fn call(
&self,
root: &Path,
@@ -162,19 +207,27 @@ impl ToolRegistry for Registry {
cancel: CancellationToken,
client: &str,
) -> Result<String, ToolCallError> {
let unknown = || ToolCallError::UnknownTool(format!("unknown tool: {name}"));
// Before the project loads, so the refusal neither loads a background project nor
// unloads an idle one at the limit to make room.
if self.find(root, name).ok_or_else(unknown)?.writes() && self.lists_as_trusted(root) == Ok(false) {
return Err(ToolCallError::Failed(crate::project::RESTRICTED_MODE.into()));
}
// The guard lives until the call ends, whichever way it leaves: neither the idle
// sweep nor the limit unloads a background project a call runs in.
let (window, project, _activity) = self.target(root).map_err(ToolCallError::Failed)?;
if let Some(plugins) = self.0.plugin_host()
&& let Some((plugin, tool, metadata)) =
plugins.mcp_tools(root).into_iter().find(|(_, _, t)| t.name == name && allowed(t, project.is_trusted()))
{
return self.call_plugin(window, project, plugins, plugin, tool, metadata, arguments, cancel, client);
// Found again: a plugin can change while a background project opens, and the call
// runs the tool as it is now.
let found = self.find(root, name).ok_or_else(unknown)?;
if found.writes() {
project.require_trust().map_err(|e| ToolCallError::Failed(e.message))?;
}
let tool = tools()
.into_iter()
.find(|t| t.metadata.name == name && allowed(&t.metadata, project.is_trusted()))
.ok_or_else(|| ToolCallError::UnknownTool(format!("unknown tool: {name}")))?;
let tool = match found {
Found::Plugin { plugins, plugin, tool, metadata } => {
return self.call_plugin(window, project, plugins, plugin, tool, metadata, arguments, cancel, client);
}
Found::Builtin(tool) => tool,
};
let args = serde_json::from_str(arguments).map_err(|e| ToolCallError::Failed(e.to_string()))?;
let call = tool::Call {
host: self.0.clone(),
+222 -24
Переглянути файл
@@ -1,9 +1,13 @@
//! Window-bound requests; missing windows, cancellation and timeout all fail closed.
//! Window-bound requests; missing windows, cancellation and timeout all fail closed. A
//! confirmation for a project served in the background shows in another project's window
//! and moves to the next one when that window stops answering.
use super::tool::Call;
use crate::Host;
use ide_core::{IdeError, IdeEvent, IdeResult, event::McpUiRequest};
use parking_lot::Mutex;
use parking_lot::{Mutex, MutexGuard};
use std::collections::{HashMap, HashSet};
use tokio::sync::oneshot;
use std::sync::Arc;
use tokio::sync::{Notify, oneshot};
#[derive(Default)]
pub struct Requests(Mutex<State>);
@@ -13,10 +17,24 @@ struct State {
pending: HashMap<u32, Pending>,
}
struct Pending {
window: String,
/// The window key of the call that asked.
owner: String,
/// The window that shows the request and may answer it.
shown_in: String,
/// Signalled when `shown_in` stops answering while `owner` still waits.
moved: Arc<Notify>,
answer: oneshot::Sender<Result<bool, String>>,
value: oneshot::Sender<Option<String>>,
}
impl State {
/// `window` answers no more requests: the ones it shows for another window move on.
fn stop_showing(&mut self, window: &str) {
self.ready.remove(window);
for pending in self.pending.values().filter(|p| p.shown_in == window && p.owner != window) {
pending.moved.notify_one();
}
}
}
impl Requests {
pub fn set_ready(&self, window: &str, ready: bool) {
if ready {
@@ -25,10 +43,18 @@ impl Requests {
self.forget_window(window);
}
}
/// `window` closed: its own requests fail, and the ones it shows for a project served in
/// the background move to another window.
pub fn forget_window(&self, window: &str) {
let mut state = self.0.lock();
state.ready.remove(window);
state.pending.retain(|_, p| p.window != window);
state.pending.retain(|_, p| p.owner != window);
state.stop_showing(window);
}
/// `window` lost its project's trust: the requests it shows for a project served in the
/// background move to another window; its own stay there and fail the trust check after
/// the answer.
pub(crate) fn withdraw(&self, window: &str) {
self.0.lock().stop_showing(window);
}
pub fn answer(&self, window: &str, id: u32, allow: bool, error: Option<String>) -> IdeResult<()> {
self.answer_with(window, id, allow, error, None)
@@ -43,10 +69,10 @@ impl Requests {
value: Option<String>,
) -> IdeResult<()> {
let mut state = self.0.lock();
if !state.pending.get(&id).is_some_and(|p| p.window == window) {
if !state.pending.get(&id).is_some_and(|p| p.shown_in == window) {
return Err(IdeError::invalid("MCP request expired or belongs to another window"));
}
let pending = state.pending.remove(&id).unwrap();
let pending = state.pending.remove(&id).expect("the request was just found");
let _ = pending.value.send(value);
let _ = pending.answer.send(error.map_or(Ok(allow), Err));
Ok(())
@@ -64,30 +90,96 @@ impl Requests {
self.ask_inner(call, request).await
}
/// The window to show a background project's request in: the most recently focused ready
/// window whose project is trusted. Returns it with the state locked while it is still
/// ready, or `None` when there is none.
fn pick(&self, host: &Host) -> Option<(MutexGuard<'_, State>, String)> {
loop {
// Projects and focus are read without the lock, which is never held with theirs.
let mut windows: Vec<String> = self.0.lock().ready.iter().cloned().collect();
windows.retain(|w| host.project(w).is_ok_and(|p| p.is_trusted()));
host.mcp_reports.most_recently_focused_first(&mut windows);
let target = windows.into_iter().next()?;
let state = self.0.lock();
if state.ready.contains(&target) {
return Some((state, target));
}
}
}
async fn ask_inner(&self, call: &Call, request: McpUiRequest) -> IdeResult<Option<String>> {
let id = super::tool::request_id().0;
let (tx, rx) = oneshot::channel();
let (tx, mut rx) = oneshot::channel();
let (value_tx, value_rx) = oneshot::channel();
{
let mut state = self.0.lock();
if !state.ready.contains(call.window()) {
return Err(IdeError::unavailable("MCP request denied: no project window is available"));
}
state.pending.insert(id, Pending { window: call.window.clone(), answer: tx, value: value_tx });
let moved = Arc::new(Notify::new());
let background = matches!(request, McpUiRequest::Confirm { background: true, .. });
let shown_in = {
let own = self.0.lock();
let (mut state, shown_in) = if own.ready.contains(call.window()) {
(own, call.window.clone())
} else {
drop(own);
background
.then(|| self.pick(&call.host))
.flatten()
.ok_or_else(|| IdeError::unavailable("MCP request denied: no project window is available"))?
};
let pending = Pending {
owner: call.window.clone(),
shown_in: shown_in.clone(),
moved: moved.clone(),
answer: tx,
value: value_tx,
};
state.pending.insert(id, pending);
shown_in
};
struct Close<'a> {
requests: &'a Requests,
call: &'a Call,
id: u32,
shown_in: String,
}
struct Close<'a>(&'a Requests, &'a Call, u32);
impl Drop for Close<'_> {
fn drop(&mut self) {
self.0.0.lock().pending.remove(&self.2);
self.1.project.sink.emit(IdeEvent::McpRequestClosed { id: self.2 });
self.requests.0.lock().pending.remove(&self.id);
self.call.host.window_sink(&self.shown_in).emit(IdeEvent::McpRequestClosed { id: self.id });
}
}
let _close = Close(self, call, id);
call.project.sink.emit(IdeEvent::McpRequest { id, request });
let result = tokio::select! {
result = rx => result.map_err(|_| IdeError::unavailable("MCP request denied: project window closed"))?,
_ = tokio::time::sleep(std::time::Duration::from_secs(180)) => return Err(IdeError::unavailable("MCP request denied: confirmation timed out")),
_ = call.cancel.cancelled() => return Err(IdeError::cancelled()),
let mut close = Close { requests: self, call, id, shown_in };
call.host.window_sink(&close.shown_in).emit(IdeEvent::McpRequest { id, request: request.clone() });
// One deadline however often the request moves.
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(180);
let result = loop {
// An answer that arrives together with a move or a close still counts.
tokio::select! {
biased;
result = &mut rx => break result.map_err(|_| IdeError::unavailable("MCP request denied: project window closed"))?,
_ = call.cancel.cancelled() => return Err(IdeError::cancelled()),
// A project unloading after its window was forgotten must not reach another window.
_ = call.project.closed.cancelled() => return Err(IdeError::unavailable("MCP request denied: project closed")),
_ = tokio::time::sleep_until(deadline) => return Err(IdeError::unavailable("MCP request denied: confirmation timed out")),
_ = moved.notified() => {
if self.window_ready(&close.shown_in) {
// The window answers again after a reload, whose new page has not seen the
// request: show it there again (the page drops a repeated id).
call.host.window_sink(&close.shown_in).emit(IdeEvent::McpRequest { id, request: request.clone() });
continue;
}
let target = {
let (mut state, target) = self
.pick(&call.host)
.ok_or_else(|| IdeError::unavailable("MCP request denied: project window closed"))?;
// Answered or dropped meanwhile: `rx` says which.
let Some(pending) = state.pending.get_mut(&id) else { continue };
pending.shown_in = target.clone();
target
};
let left = std::mem::replace(&mut close.shown_in, target);
call.host.window_sink(&left).emit(IdeEvent::McpRequestClosed { id });
call.host.window_sink(&close.shown_in).emit(IdeEvent::McpRequest { id, request: request.clone() });
}
}
};
match result {
Ok(true) => Ok(value_rx.await.unwrap_or(None)),
@@ -96,3 +188,109 @@ impl Requests {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{HostConfig, mcp::BackgroundProjects};
use futures::FutureExt;
use ide_core::{CancellationToken, IdeEvent};
use std::path::PathBuf;
type Events = Arc<Mutex<Vec<(String, IdeEvent)>>>;
/// A trusted project open in the ready window `main`, and the folder `inventory` loaded in the
/// background next to it.
struct Fixture {
host: Arc<Host>,
inventory: PathBuf,
events: Events,
_temp: tempfile::TempDir,
}
impl Fixture {
async fn new() -> Self {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let (root, inventory) = (base.join("project"), base.join("inventory"));
for dir in [&root, &inventory] {
std::fs::create_dir_all(dir).unwrap();
}
let events = Events::default();
let sink = events.clone();
let host = Arc::new(Host::new(HostConfig {
local_data_dir: base.join("local"),
sink_for: Box::new(move |window| {
let (window, events) = (window.to_owned(), sink.clone());
Arc::new(move |e| events.lock().push((window.clone(), e)))
}),
..HostConfig::for_test(&base)
}));
host.open_project("main", &root).unwrap();
host.set_project_trust(&root, true, false).await.unwrap();
host.mcp_requests.set_ready("main", true);
Self { host, inventory, events, _temp: temp }
}
/// A call from the background project at `inventory`.
fn background_call(&self) -> Call {
let window = BackgroundProjects::key(&self.inventory);
Call {
client: "test-client".into(),
tool: "build_project".into(),
host: self.host.clone(),
project: self.host.open_project(&window, &self.inventory).unwrap(),
window,
args: serde_json::Value::Null,
cancel: CancellationToken::new(),
}
}
fn confirm(&self) -> McpUiRequest {
McpUiRequest::Confirm {
client: "test-client".into(),
tool: "build_project".into(),
subject: "build".into(),
project: self.inventory.to_string_lossy().into_owned(),
detail: None,
background: true,
}
}
/// The ids of the requests `main` was asked to show, in order.
fn shown_in_main(&self) -> Vec<u32> {
let events = self.events.lock();
let asked = events.iter().filter(|(window, _)| window == "main");
asked.filter_map(|(_, e)| if let IdeEvent::McpRequest { id, .. } = e { Some(*id) } else { None }).collect()
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_request_of_a_project_that_closed_fails_instead_of_moving() {
let f = Fixture::new().await;
let call = f.background_call();
// Unloading forgets the project's key before it cancels `closed`; a request registered in
// between belongs to nobody that will answer it.
call.project.closed.cancel();
let error = f.host.mcp_requests.ask(&call, f.confirm()).now_or_never().expect("fails at once").unwrap_err();
assert_eq!(error.message, "MCP request denied: project closed");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_reloaded_window_shows_the_request_again() {
let f = Fixture::new().await;
let call = f.background_call();
let ask = f.host.mcp_requests.ask(&call, f.confirm());
tokio::pin!(ask);
assert!((&mut ask).now_or_never().is_none());
let [id] = f.shown_in_main()[..] else { panic!("{:?}", f.shown_in_main()) };
// A reload: the old page stops answering and drops the request, the new one is ready.
f.host.mcp_requests.set_ready("main", false);
f.host.mcp_requests.set_ready("main", true);
assert!((&mut ask).now_or_never().is_none());
assert_eq!(f.shown_in_main(), [id, id]);
f.host.mcp_requests.answer("main", id, false, None).unwrap();
let error = ask.await.unwrap_err();
assert_eq!(error.message, "MCP request denied by the user");
}
}
+1
Переглянути файл
@@ -137,6 +137,7 @@ crashed, stoppedByAgent, stoppedByUser or startFailed; `exitCode`; `crash` with
process) and its output so far.{OUTPUT}{SEQUENCE}{INTERVENTIONS}"
),
|call| async move {
call.needs_window()?;
let name = tab_name(&call.str("name")?)?;
let command = call.str("command")?;
if command.trim().is_empty() {
+22 -4
Переглянути файл
@@ -5,6 +5,14 @@ use serde_json::{Value, json};
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// The argument that names the project a call is for; the server routes the call by it.
pub(crate) const PROJECT_PATH: &str = "projectPath";
/// The schema of [`PROJECT_PATH`], which every tool takes.
pub(crate) fn project_path() -> Value {
json!({ "type": "string", "description": "Any directory inside a project that is open in a window or served in the background. Defaults to the connection's project (`?project=`) or the only one open in a window." })
}
pub struct Call {
pub client: String,
pub tool: String,
@@ -88,12 +96,24 @@ impl Call {
client: self.client.clone(),
tool: self.tool.clone(),
subject: subject.into(),
project: self.root().to_string_lossy().into_owned(),
project: ide_core::ipc_path::to_ipc(self.root()),
detail,
background: super::BackgroundProjects::is_key(&self.window),
})
.await?;
self.project.require_trust()
}
/// Refuses a tool that works through the project's window (its editors, Problems view, Run
/// tool window or breakpoints) when the project is served in the background without one.
pub fn needs_window(&self) -> IdeResult<()> {
if !super::BackgroundProjects::is_key(&self.window) {
return Ok(());
}
let (tool, root) = (&self.tool, self.root().display());
Err(IdeError::unavailable(format!(
"{tool} needs the project open in a window: {root} is served in the background."
)))
}
pub fn host(&self) -> Arc<Host> {
self.host.clone()
}
@@ -242,9 +262,7 @@ impl Tool {
read_only: true,
destructive: false,
output_schema: None,
input_schema: json!({ "type": "object", "properties": {
"projectPath": { "type": "string", "description": "Any directory inside a project that is open in a window or served in the background. Defaults to the connection's project (`?project=`) or the only one open in a window." }
}, "required": [] }),
input_schema: json!({ "type": "object", "properties": { PROJECT_PATH: project_path() }, "required": [] }),
},
handler: Arc::new(move |call| Box::pin(handler(call))),
}
+2
Переглянути файл
@@ -277,6 +277,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("file.exportSettings", "Export Settings…"),
act("file.importSettings", "Import Settings…"),
act("file.importJetBrainsSettings", "Import Settings from JetBrains IDE…"),
act("file.importJetBrainsRecentProjects", "Import Recent Projects from JetBrains IDE…"),
act("file.syncSettings", "Sync Settings Now"),
],
),
@@ -484,6 +485,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("navigate.declaration", "Declaration or Usages"),
act("navigate.implementation", "Implementation(s)"),
act("navigate.typeDeclaration", "Type Declaration"),
act("navigate.sourceDefinition", "Source Definition"),
act("navigate.superMethod", "Super Method"),
act("navigate.gotoTest", "Test"),
act("navigate.relatedSymbol", "Related Symbol…"),
+139 -26
Переглянути файл
@@ -1115,11 +1115,16 @@ pub async fn agent_mcp_test(host: &Host, window: &str, id: String) -> IdeResult<
let cwd = project.as_ref().map(|p| p.root.clone()).or_else(dirs::home_dir).unwrap_or_else(std::env::temp_dir);
match server.transport {
McpTransport::Stdio => Ok(ide_agent::mcp::probe_stdio_server(&server, &cwd).await),
McpTransport::Http | McpTransport::Sse => Ok(probe_http_mcp_server(&server).await),
McpTransport::Http | McpTransport::Sse => {
Ok(probe_http_mcp_server(&server, &ide_core::proxy_settings::proxy()).await)
}
}
}
async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> McpProbeResult {
async fn probe_http_mcp_server(
server: &ide_core::settings::AgentMcpServer,
proxy: &ide_core::proxy_settings::ProxySettings,
) -> McpProbeResult {
let started = std::time::Instant::now();
let elapsed_ms = || u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
let Some(url) = server.url.as_deref().map(str::trim).filter(|u| !u.is_empty()) else {
@@ -1145,31 +1150,36 @@ async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> M
headers.insert(name, val);
}
}
let client =
match reqwest::Client::builder().default_headers(headers).timeout(std::time::Duration::from_secs(12)).build() {
Ok(c) => c,
Err(e) => {
return McpProbeResult {
ok: false,
server_name: None,
server_version: None,
protocol_version: None,
tools: Vec::new(),
duration_ms: elapsed_ms(),
error: Some(format!("HTTP client error: {e}")),
};
}
};
let client = match ide_http::client::build(proxy) {
Ok(c) => c,
Err(e) => {
return McpProbeResult {
ok: false,
server_name: None,
server_version: None,
protocol_version: None,
tools: Vec::new(),
duration_ms: elapsed_ms(),
error: Some(format!("HTTP client error: {}", e.message)),
};
}
};
// The shared client has no MCP headers or 12 s limit of its own. The protocol's headers win over the
// configured ones, as they did over the client's default headers.
let post = |client: &reqwest::Client, url: &str, session_id: Option<&str>| {
let mut headers = headers.clone();
headers.insert(reqwest::header::CONTENT_TYPE, reqwest::header::HeaderValue::from_static("application/json"));
if let Some(value) = session_id.and_then(|sid| reqwest::header::HeaderValue::from_str(sid).ok()) {
headers.insert("mcp-session-id", value);
}
client.post(url).headers(headers).timeout(std::time::Duration::from_secs(12))
};
let post_rpc = |session_id: Option<String>, body: serde_json::Value| {
let client = client.clone();
let url = url.to_owned();
async move {
let mut req =
client.post(&url).header(reqwest::header::CONTENT_TYPE, "application/json").body(body.to_string());
if let Some(sid) = session_id.as_deref() {
req = req.header("Mcp-Session-Id", sid);
}
let req = post(&client, &url, session_id.as_deref()).body(body.to_string());
let resp = req
.send()
.await
@@ -1218,7 +1228,7 @@ async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> M
};
// Best-effort `notifications/initialized` + `tools/list`.
let mut not_req = client.post(url).header(reqwest::header::CONTENT_TYPE, "application/json").body(
let not_req = post(&client, url, session_id.as_deref()).body(
serde_json::json!({
"jsonrpc": "2.0",
"method": "notifications/initialized",
@@ -1226,9 +1236,6 @@ async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> M
})
.to_string(),
);
if let Some(sid) = session_id.as_deref() {
not_req = not_req.header("Mcp-Session-Id", sid);
}
let _ = not_req.send().await;
let tools_res = post_rpc(
@@ -1866,6 +1873,112 @@ fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::P
mod tests {
use super::*;
#[tokio::test]
async fn the_mcp_probe_goes_through_the_manual_proxy_and_keeps_its_headers() {
use std::io::{BufRead, BufReader, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let settings = ide_core::proxy_settings::ProxySettings {
mode: ide_core::proxy_settings::ProxyMode::Manual,
host: "127.0.0.1".into(),
port: address.port(),
..Default::default()
};
let proxy = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut head = String::new();
while !head.ends_with("\r\n\r\n") {
if reader.read_line(&mut head).unwrap() == 0 {
break;
}
}
let _ = stream.write_all(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
head
});
let server = ide_core::settings::AgentMcpServer {
transport: McpTransport::Http,
url: Some("http://mcp-target.invalid/mcp".into()),
headers: [("X-Test".to_owned(), "1".to_owned())].into(),
..Default::default()
};
let result = probe_http_mcp_server(&server, &settings).await;
assert!(!result.ok);
// A probe that bypassed the proxy leaves it waiting in `accept`; a dummy connection releases it.
let _ = std::net::TcpStream::connect(address);
let head = proxy.join().unwrap().to_ascii_lowercase();
assert!(head.starts_with("post http://mcp-target.invalid/mcp http/1.1"), "{head}");
assert!(head.contains("accept: application/json, text/event-stream"), "{head}");
assert!(head.contains("x-test: 1"), "{head}");
}
#[tokio::test]
async fn mcp_protocol_headers_win_over_configured_ones_in_all_three_requests() {
use std::io::{Read, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let server = std::thread::spawn(move || {
let mut heads = Vec::new();
for reply in [
r#"{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2024-11-05","capabilities":{},"serverInfo":{"name":"t","version":"1"}}}"#,
"",
r#"{"jsonrpc":"2.0","id":2,"result":{"tools":[]}}"#,
] {
let (mut stream, _) = listener.accept().unwrap();
let mut raw = Vec::new();
let mut byte = [0u8; 1];
while !raw.ends_with(b"\r\n\r\n") {
stream.read_exact(&mut byte).unwrap();
raw.push(byte[0]);
}
let head = String::from_utf8(raw).unwrap().to_ascii_lowercase();
let length = head
.lines()
.find_map(|line| line.strip_prefix("content-length: "))
.map_or(0, |value| value.trim().parse().unwrap());
let mut body = vec![0u8; length];
stream.read_exact(&mut body).unwrap();
heads.push(head);
let _ = stream.write_all(
format!(
"HTTP/1.1 200 OK\r\nMcp-Session-Id: s1\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}",
reply.len()
)
.as_bytes(),
);
}
heads
});
let settings = ide_core::proxy_settings::ProxySettings {
mode: ide_core::proxy_settings::ProxyMode::None,
..Default::default()
};
let server_config = ide_core::settings::AgentMcpServer {
transport: McpTransport::Http,
url: Some(format!("http://127.0.0.1:{port}/mcp")),
headers: [
("Content-Type".to_owned(), "text/plain".to_owned()),
("Mcp-Session-Id".to_owned(), "configured".to_owned()),
("Accept".to_owned(), "text/x-configured".to_owned()),
]
.into(),
..Default::default()
};
let result = probe_http_mcp_server(&server_config, &settings).await;
assert!(result.ok, "{:?}", result.error);
let heads = server.join().unwrap();
let values = |head: &str, name: &str| -> Vec<String> {
head.lines().filter_map(|line| line.strip_prefix(name)).map(|v| v.trim().to_owned()).collect()
};
for (i, head) in heads.iter().enumerate() {
assert_eq!(values(head, "content-type:"), ["application/json"], "request {i}: {head}");
assert_eq!(values(head, "accept:"), ["text/x-configured"], "request {i}: {head}");
// The first request has no session yet, so the configured value stands.
let session = if i == 0 { "configured" } else { "s1" };
assert_eq!(values(head, "mcp-session-id:"), [session], "request {i}: {head}");
}
}
#[test]
fn an_agent_installs_once_at_a_time() {
let first = Installing::begin("test-agent").unwrap();
+1
Переглянути файл
@@ -26,6 +26,7 @@ pub async fn doc_close(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
project.documents.close(doc);
ide_core::memory::release_free_pages_soon();
Ok(())
})
.await
+4 -4
Переглянути файл
@@ -8,16 +8,16 @@ async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + '
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
/// The available iOS simulators, booted first; `None` outside macOS or when the project has no
/// Xcode project or workspace at its root. Asked again whenever the chooser opens: `simctl` has
/// no change feed, and one listing takes a fraction of a second.
/// The available iOS simulators, booted first, then the paired iPhones and iPads; `None` outside
/// macOS or when the project has no Xcode project or workspace at its root. Asked again whenever
/// the chooser opens: `simctl` has no change feed, and one listing takes a fraction of a second.
#[command(trust = trusted)]
pub async fn ios_simulators(host: &Host, window: &str) -> IdeResult<Option<Vec<IosSimulator>>> {
let root = host.project(window)?.root.clone();
if !cfg!(target_os = "macos") || !simulator::is_xcode_project(&root) {
return Ok(None);
}
blocking(simulator::list).await.map(Some)
blocking(move || simulator::list(&root)).await.map(Some)
}
/// Boots a simulator; returns once it is booted.
+24 -2
Переглянути файл
@@ -695,8 +695,10 @@ fn apply_library_classpath(
DependencyScope::Compile | DependencyScope::Runtime => true,
DependencyScope::Test | DependencyScope::Provided => test,
};
lib.classes.iter().filter_map(move |entry| {
ide_sdk::apply::setting_path(root, entry).map(|path| (path.to_string_lossy().into_owned(), allowed))
lib.classes.iter().flat_map(move |entry| {
ide_sdk::libraries::library_class_paths(root, entry)
.into_iter()
.map(move |p| (p.to_string_lossy().into_owned(), allowed))
})
})
.collect();
@@ -1492,6 +1494,26 @@ mod tests {
let mut info = JavaLaunchInfo::default();
apply_library_classpath(&mut info, root.path(), &libraries, false);
assert_eq!(info.class_paths, &paths[..2]);
// Directory library roots expand to the JAR files inside them.
let web_lib = root.path().join("WebRoot/WEB-INF/lib");
std::fs::create_dir_all(&web_lib).unwrap();
let a_jar = web_lib.join("a.jar");
let b_jar = web_lib.join("b.jar");
std::fs::write(&a_jar, b"").unwrap();
std::fs::write(&b_jar, b"").unwrap();
let dir_libs = vec![ProjectLibrary {
name: "web".into(),
classes: vec!["WebRoot/WEB-INF/lib".into()],
scope: DependencyScope::Compile,
..Default::default()
}];
let mut dir_info = JavaLaunchInfo::default();
apply_library_classpath(&mut dir_info, root.path(), &dir_libs, false);
assert_eq!(
dir_info.class_paths,
vec![a_jar.to_string_lossy().into_owned(), b_jar.to_string_lossy().into_owned()]
);
}
/// JDT LS and our build model spell a module output differently on Windows; the
+50
Переглянути файл
@@ -675,6 +675,53 @@ pub async fn lsp_switch_source_header(
Ok(result?.map(|path| path.to_string_lossy().into_owned()))
}
/// Go to Source Definition (vtsls): the JavaScript implementation of the symbol at `pos`
/// instead of its `.d.ts`. Cancel with `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_source_definition(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
pos: Pos,
) -> IdeResult<Vec<Location>> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let result = tokio::select! {
result = lsp.source_definition(doc, pos, cancel.clone()) => result,
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
};
host.end_request(request);
result
}
/// Has vtsls open the document's `tsconfig.json` / `jsconfig.json` or the TS Server log.
#[command(trust = trusted)]
pub async fn lsp_open_typescript_file(host: &Host, window: &str, doc: DocId, what: TypeScriptFile) -> IdeResult<()> {
let lsp = host.project(window)?.lsp.clone();
lsp.open_typescript_file(doc, what).await
}
/// The files tsserver suggests for vtsls' Move to File code action `command`. Cancel with
/// `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_move_to_file_targets(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
command: Command,
) -> IdeResult<Vec<ide_core::IpcPath>> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let result = tokio::select! {
result = lsp.move_to_file_targets(doc, command, cancel.clone()) => result,
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
};
host.end_request(request);
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)`.
@@ -3344,6 +3391,9 @@ ide_command::domain!(
lsp_implementation_locations,
lsp_file_references,
lsp_switch_source_header,
lsp_source_definition,
lsp_open_typescript_file,
lsp_move_to_file_targets,
lsp_implementations,
lsp_inlay_hints,
lsp_inline_completion,
+11 -3
Переглянути файл
@@ -521,11 +521,19 @@ pub async fn nav_python_library_imports(
let config_dir = host.config_dir.clone();
let token = host.begin_request(request);
let result = blocking(move || {
let snap = project.documents.snapshot(doc)?;
if snap.language.as_str() != "python" {
// A notebook cell is a document of the language servers only: `documents` holds what the
// editor opened, so ⌥↵ on a cell's unresolved name used to answer nothing.
let (language, path) = match project.documents.snapshot(doc) {
Ok(snap) => (snap.language, snap.path.0),
Err(e) => match project.lsp.cell_text(doc) {
Some(cell) => (cell.language, cell.path),
None => return Err(e),
},
};
if language.as_str() != "python" {
return Ok(Vec::new());
}
let Some(python) = super::sdk::effective_python(&config_dir, &project, Some(&snap.path)) else {
let Some(python) = super::sdk::effective_python(&config_dir, &project, Some(&path)) else {
return Ok(Vec::new());
};
let roots = interpreter_site_packages(&python);
+6
Переглянути файл
@@ -468,6 +468,12 @@ pub fn set_settings(
}
});
}
if ["languages", "languages.swift", "languages.swift.xcode"].contains(&key) {
// An untrusted project keeps no Xcode of its own (see `xcode_env`).
for project in affected().into_iter().filter(|p| p.is_trusted()) {
host.runtime.spawn(async move { crate::xcode_env::apply_and_restart(&project).await });
}
}
// `flutter daemon` and DevTools run on the Flutter SDK; the next request starts DevTools again.
if ["languages", "languages.flutter", "languages.flutter.sdk"].contains(&key) {
for project in affected() {
+89 -12
Переглянути файл
@@ -448,13 +448,18 @@ async fn start_inner(
}
let target = ide_remote::service::run_target(&settings, id)?;
if target.kind != RunTargetKind::Ssh {
// A local run of the docker CLI: the command is resolved in the container, and
// this machine's toolchains and `PYTHONPATH` don't apply.
let mut config = config;
if ide_run::is_python_kind(&config.kind) {
container_python_path(&mut config.env, &super::python::paths(&project), &project.root);
}
let (config, note) = container::prepare(host, &project.root, target, config).await?;
// A local run of the docker CLI or `wsl.exe`: the command is resolved in the
// container or distribution, and this machine's toolchains and `PYTHONPATH` don't apply.
// The settings of the workspace member it belongs to derived its values.
let mut member = config.clone();
let (member_root, member_settings, fallback) = settings_for(host, &project, &mut member)?;
let derived = Derived { root: &member_root, fallback: fallback.as_deref(), settings: &member_settings };
let config = remote_config(&config, derived, &project.root, &super::python::paths(&project));
let (config, note) = if target.kind == RunTargetKind::Wsl {
(container::prepare_wsl(host, &project.root, target, config).await?, None)
} else {
container::prepare(host, &project.root, target, config).await?
};
if let Some(note) = note {
on_output(OutputChunk::System { text: format!("{note}\n") });
}
@@ -462,7 +467,7 @@ async fn start_inner(
let options = StartOptions {
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
python_paths: Vec::new(),
// A folder on this machine: not in the container.
// A folder on this machine: not in the container or distribution.
ruby_reporter: None,
plots: None,
capture_junit_reports: false,
@@ -575,9 +580,10 @@ async fn start_inner(
}
if config.kind == "xcode-test" {
let bundles = project.cache_dir.join("xcresult");
let dir = project.root.clone();
config = host
.blocking(move || {
ide_run::xcode::prepare_test(&mut config, &bundles)?;
ide_run::xcode::prepare_test(&mut config, &dir, &bundles)?;
Ok(config)
})
.await?;
@@ -863,6 +869,44 @@ pub use commands::*;
mod ownership_tests {
use super::*;
#[cfg(unix)]
#[test]
fn a_remote_run_gets_none_of_this_machines_derived_values() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let venv = root.join(".venv");
std::fs::create_dir_all(venv.join("bin")).unwrap();
std::fs::write(venv.join("pyvenv.cfg"), "home = /usr/bin\n").unwrap();
std::fs::write(venv.join("bin/python"), "").unwrap();
let mut settings = ide_core::settings::Settings::default();
settings.languages.python.interpreter = venv.join("bin/python").to_string_lossy().into_owned();
let mut config = RunConfig {
id: "app".into(),
name: "app".into(),
kind: "python".into(),
command: "python".into(),
args: vec!["main.py".into()],
cwd: None,
env: [("FOO".to_owned(), "bar".to_owned())].into(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
config.extras.target = Some("wsl".into());
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
assert!(config.env.contains_key("VIRTUAL_ENV") && config.env.contains_key("PATH"), "{:?}", config.env);
config.env.insert("GOFLAGS".into(), "-mod=mod".into());
let derived = Derived { root, fallback: None, settings: &settings };
let out = remote_config(&config, derived, root, &[root.to_path_buf()]);
assert_eq!(out.env.keys().collect::<Vec<_>>(), ["FOO", "GOFLAGS", "PYTHONPATH"], "{:?}", out.env);
assert_eq!(out.command, "python", "the interpreter is the target's");
assert_eq!(out.extras.target.as_deref(), Some("wsl"));
assert!(has_local_path("/opt/go") && has_local_path("/a/bin:/b/bin"));
assert!(!has_local_path("-mod=mod") && !has_local_path("https://proxy.golang.org,direct"), "kept: not paths");
}
#[cfg(unix)]
#[test]
fn source_roots_go_on_the_container_pythonpath() {
@@ -1061,6 +1105,9 @@ pub async fn run_container_path(
if !path.starts_with('/') {
return Ok(None);
}
if run_target.kind == RunTargetKind::Wsl {
return Ok(ide_remote::wsl::local_file(&path, &run_target, &root).filter(|f| f.is_file()).map(Into::into));
}
let library = snapshots
.and_then(|dir| ide_sdk::container_python::current(&dir))
.and_then(|(dir, snapshot)| ide_sdk::container_python::snapshot_file(&dir, &snapshot, &path));
@@ -1073,9 +1120,39 @@ pub async fn run_container_path(
.await
}
/// The project's source roots on `PYTHONPATH` in a container, as a local run gets them:
/// they are mounted with the project, and `container::prepare` maps their paths. The
/// container's separator is `:`, whatever this machine's is.
/// `config` for a container or WSL distribution: without what settings derived from this
/// machine (its `PATH`, `VIRTUAL_ENV`, toolchain homes, resolved interpreter paths), which
/// would replace the values there, and with the project's source roots on `PYTHONPATH`.
/// Values that settings derive but that are not paths of this machine (`GOPROXY`, `GOFLAGS`)
/// still apply there and are kept.
fn remote_config(config: &RunConfig, derived: Derived<'_>, root: &Path, python_roots: &[PathBuf]) -> RunConfig {
let plain = ide_sdk::apply::without_derived_in(config, derived.root, derived.fallback, derived.settings);
let mut out = config.clone();
out.command = plain.command;
out.env.retain(|key, value| plain.env.contains_key(key) || !has_local_path(value));
if ide_run::is_python_kind(&out.kind) {
container_python_path(&mut out.env, python_roots, root);
}
out
}
/// The settings a configuration's derived values come from (see [`settings_for`]).
#[derive(Clone, Copy)]
struct Derived<'a> {
root: &'a Path,
fallback: Option<&'a Path>,
settings: &'a ide_core::settings::Settings,
}
/// `value` is an absolute path of this machine, alone or first in a path list (a URL such
/// as `GOPROXY`'s is not: its first part is `https`).
fn has_local_path(value: &str) -> bool {
std::env::split_paths(value).find(|p| !p.as_os_str().is_empty()).is_some_and(|p| p.is_absolute())
}
/// The project's source roots on `PYTHONPATH` in a container or WSL distribution, as a local
/// run gets them: they are mounted with the project, and `container::prepare` /
/// `prepare_wsl` map their paths. The separator there is `:`, whatever this machine's is.
fn container_python_path(env: &mut std::collections::BTreeMap<String, String>, roots: &[PathBuf], root: &Path) {
let mut paths: Vec<String> =
roots.iter().filter(|p| p.starts_with(root)).map(|p| p.to_string_lossy().into_owned()).collect();
+114 -11
Переглянути файл
@@ -30,6 +30,8 @@ pub async fn run_xcode_test_results(host: &Host, window: &str, bundle: std::path
return Err(IdeError::invalid("Not an Xcode result bundle"));
}
let mut cmd = tokio::process::Command::new("xcrun");
// The project's Xcode reads the bundle its `xcodebuild` wrote.
cmd.current_dir(&host.project(window)?.root);
cmd.args(["xcresulttool", "get", "test-results", "tests", "--compact", "--path"]).arg(&bundle);
ide_core::process::prepare(cmd.as_std_mut());
let out = cmd.output().await?;
@@ -251,8 +253,10 @@ fn project_web_artifacts(ps: &ide_core::settings::ProjectStructureSettings) -> V
.collect()
}
/// Compiles the project and packs the Project Structure artifact `name` as the WAR Tomcat
/// deploys, recorded in `base` like a build tool's archive.
/// Compiles the project and builds the Project Structure artifact `name` for Tomcat to
/// deploy, recording its output path in `base` like a build tool's archive.
/// The artifact lives outside `base` (at `artifact_file`), so `tomcat::prepare` recreating
/// the runtime directory does not delete what was just built.
fn build_project_war(
root: &std::path::Path,
settings: &ide_core::settings::Settings,
@@ -268,10 +272,7 @@ fn build_project_war(
.iter()
.find(|a| a.name == name)
.ok_or_else(|| IdeError::invalid(format!("No artifact named {name} in Project Structure › Artifacts")))?;
let war = base.join("artifact").join(format!(
"{}.war",
name.split(':').next().unwrap_or(name).replace(|c: char| !c.is_alphanumeric() && c != '-', "_")
));
let target = compile::artifact_file(root, artifact);
let plan = compile::structure_war_plan(
root,
&ps,
@@ -279,7 +280,7 @@ fn build_project_war(
jdk.as_ref(),
&settings.languages.java.language_level,
artifact,
&war,
None,
cache,
)?;
let result = compile::run(root, &plan, &ide_core::CancellationToken::new(), &|_| {})?;
@@ -298,7 +299,7 @@ fn build_project_war(
}
std::fs::create_dir_all(base)?;
std::fs::write(base.join("artifact-id.txt"), format!("{PROJECT_ARTIFACT}{name}"))?;
std::fs::write(base.join("artifact-path.txt"), war.to_string_lossy().as_bytes())?;
std::fs::write(base.join("artifact-path.txt"), target.to_string_lossy().as_bytes())?;
Ok(())
}
@@ -330,8 +331,14 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
}
let project = host.project(window)?;
tokio::task::spawn_blocking(move || {
let model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &project.settings.effective());
let artifacts = ide_build::web::artifacts(&project.root, &model);
let settings = project.settings.effective();
let model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &settings);
let mut artifacts = ide_build::web::artifacts(&project.root, &model);
if model.maven.is_none() && model.gradle.is_empty() {
let detected = project.detected_roots.read().clone();
let (ps, _, _) = crate::ops::build::structure_inputs(&project.root, &settings, &detected);
artifacts.extend(project_web_artifacts(&ps));
}
let id = config
.extras
.params
@@ -343,7 +350,6 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
let base = ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?;
let base = ide_run::tomcat::state_dir(&base, &config);
if let Some(name) = id.strip_prefix(PROJECT_ARTIFACT) {
let settings = project.settings.effective();
let detected = project.detected_roots.read().clone();
build_project_war(&project.root, &settings, &detected, name, &base, &project.build_cache_dir())?;
return Ok(None);
@@ -465,3 +471,100 @@ ide_command::domain!(
run_tomcat_sync,
run_tomcat_update,
);
#[cfg(test)]
mod tests {
use super::*;
use ide_core::settings::{ArtifactConfig, ArtifactKind, FacetConfig, Settings};
use std::io::Write;
fn fake_tomcat(home: &std::path::Path) {
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::create_dir_all(home.join("conf")).unwrap();
std::fs::create_dir_all(home.join("lib")).unwrap();
std::fs::write(home.join("bin/catalina.sh"), "").unwrap();
std::fs::write(home.join("bin/catalina.bat"), "").unwrap();
let server = "<Server port='8005'><Service><Connector port='8080'/><Engine name='Catalina'><Host name='localhost'/></Engine></Service></Server>";
std::fs::write(home.join("conf/server.xml"), server).unwrap();
let mut zip = zip::ZipWriter::new(std::fs::File::create(home.join("lib/catalina.jar")).unwrap());
zip.start_file("org/apache/catalina/util/ServerInfo.properties", zip::write::SimpleFileOptions::default())
.unwrap();
zip.write_all(b"server.info=Apache Tomcat/10.1").unwrap();
zip.finish().unwrap();
}
#[test]
fn project_structure_war_and_exploded_artifacts_survive_tomcat_prepare() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("EJSH");
let cache = root.parent().unwrap().join("cache");
let tomcat_home = root.parent().unwrap().join("tomcat-home");
fake_tomcat(&tomcat_home);
std::fs::create_dir_all(root.join("WebRoot/WEB-INF")).unwrap();
std::fs::write(root.join("WebRoot/WEB-INF/web.xml"), "<web-app/>").unwrap();
std::fs::write(root.join("WebRoot/index.jsp"), "<h1>ok</h1>").unwrap();
let mut settings = Settings::default();
settings.project_structure.facets.push(FacetConfig {
kind: "web".into(),
module: ".".into(),
descriptor: "WebRoot/WEB-INF/web.xml".into(),
web_root: "WebRoot".into(),
});
settings.project_structure.artifacts.push(ArtifactConfig {
name: "EJSH:war exploded".into(),
kind: ArtifactKind::WarExploded,
module: ".".into(),
output_directory: "out/artifacts/EJSH_war_exploded".into(),
..Default::default()
});
settings.project_structure.artifacts.push(ArtifactConfig {
name: "EJSH:war".into(),
kind: ArtifactKind::War,
module: ".".into(),
output_directory: "out/artifacts/EJSH_war".into(),
..Default::default()
});
for (artifact_name, expect_exploded_dir) in [("EJSH:war exploded", true), ("EJSH:war", false)] {
let mut config = RunConfig {
id: format!("tomcat-{artifact_name}"),
name: "Tomcat".into(),
kind: "tomcat".into(),
command: "catalina".into(),
args: vec![],
cwd: None,
env: Default::default(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
config.extras.params.insert("tomcatHome".into(), tomcat_home.to_string_lossy().into_owned());
config.extras.params.insert("deployment".into(), "artifact".into());
config.extras.params.insert("artifact".into(), format!("{PROJECT_ARTIFACT}{artifact_name}"));
config.extras.params.insert("artifactName".into(), "EJSH".into());
config.extras.params.insert("httpPort".into(), "8080".into());
let base = ide_run::tomcat::effective_base_dir(&root, &cache, &config).unwrap();
let state = ide_run::tomcat::state_dir(&base, &config);
build_project_war(&root, &settings, &[], artifact_name, &state, &cache.join("build")).unwrap();
// `prepare` deletes and recreates `base`; the built artifact must remain intact.
ide_run::tomcat::prepare(&root, &cache, &mut config).unwrap();
let catalina_base = std::path::PathBuf::from(&config.env["CATALINA_BASE"]);
let ctx = std::fs::read_to_string(catalina_base.join("conf/Catalina/localhost/EJSH.xml")).unwrap();
if expect_exploded_dir {
let expected = root.join("out/artifacts/EJSH_war_exploded");
assert!(expected.join("WEB-INF/web.xml").is_file());
assert!(ctx.contains(expected.to_string_lossy().as_ref()), "{ctx}");
} else {
assert!(root.join("out/artifacts/EJSH_war/EJSH.war").is_file());
assert!(catalina_base.join("deployment/WEB-INF/web.xml").is_file());
assert!(ctx.contains("deployment"), "{ctx}");
}
}
}
}
+33 -2
Переглянути файл
@@ -1,5 +1,5 @@
//! Docker and Compose run targets: the configuration becomes a local run of the
//! docker CLI (see `ide_remote::docker`).
//! Docker, Compose and WSL run targets: the configuration becomes a local run of the
//! docker CLI (see `ide_remote::docker`) or of `wsl.exe` (see `ide_remote::wsl`).
use crate::Host;
use ide_core::remote_settings::{RunTarget, RunTargetKind};
@@ -73,6 +73,37 @@ pub(super) async fn prepare(
.await
}
/// `config` rewritten to run in `target`'s WSL distribution.
pub(super) async fn prepare_wsl(
host: &Host,
root: &Path,
target: RunTarget,
config: RunConfig,
) -> IdeResult<RunConfig> {
if !cfg!(windows) {
return Err(IdeError::invalid(format!(
"Run target '{}' is a WSL distribution: WSL needs Windows",
target.name
)));
}
let root = root.to_path_buf();
host.blocking(move || {
let linux_root = ide_remote::wsl::project_root(&target, &root)?;
let file_env = env_files(&root, &config)?;
let inherited = std::env::var("WSLENV").ok();
ide_remote::wsl::wsl_config(
&config,
&target,
&root,
&linux_root,
ide_core::wsl::EXE,
&file_env,
inherited.as_deref(),
)
})
.await
}
/// The project can only be bind-mounted from a daemon on this machine.
pub(crate) fn require_local(endpoint: &DockerEndpoint, target: &RunTarget) -> IdeResult<()> {
if !ide_docker::endpoint_is_local(endpoint)? {
+1 -1
Переглянути файл
@@ -12,7 +12,7 @@ use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
pub mod container_python;
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh};
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh, sdk_wsl_pythons};
/// Executables found for "run this file", and where single files are compiled to.
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
+126 -12
Переглянути файл
@@ -4,6 +4,9 @@
//! A snapshot runs the target's Python once in a new container (the image's entrypoint
//! and the service's dependencies skipped), then copies its `sys.path` folders out of
//! the stopped container with `docker cp`. Nothing is installed in the container.
//!
//! A WSL run target's snapshot only records its Python's `sys.path`: the folders are read
//! in place through `\\wsl.localhost\<distro>`.
use crate::Host;
use crate::project::Project;
@@ -23,6 +26,8 @@ use std::time::Duration;
const PROBE_TIMEOUT: Duration = Duration::from_secs(15 * 60);
const COPY_TIMEOUT: Duration = Duration::from_secs(10 * 60);
const QUICK: Duration = Duration::from_secs(30);
/// Starting the distribution may come first.
const WSL_TIMEOUT: Duration = Duration::from_secs(2 * 60);
/// The project interpreter when it is a run target's.
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
@@ -34,8 +39,10 @@ pub struct ContainerPython {
pub name: String,
/// The Python version of the snapshot in use; `None`: no snapshot yet.
pub version: Option<String>,
/// The image the snapshot was copied from.
/// The image the snapshot was copied from; `None` for WSL.
pub image: Option<String>,
/// The interpreter's path in the container or distribution.
pub executable: Option<String>,
/// The copied library folders on this machine.
pub folders: Vec<IpcPath>,
/// Packages of the snapshot (read-only).
@@ -108,22 +115,25 @@ pub(crate) fn library_group(host: &Host, root: &Path, settings: &Settings) -> Op
}
/// The project interpreter when it is a Docker or Compose run target's, with its snapshot.
/// Off the calling thread: a WSL interpreter's packages are read over `\\wsl.localhost`.
#[command(trust = trusted)]
pub fn sdk_container_python(host: &Host, window: &str) -> IdeResult<Option<ContainerPython>> {
pub async fn sdk_container_python(host: &Host, window: &str) -> IdeResult<Option<ContainerPython>> {
host.require_trust(window)?;
let project = host.project(window)?;
Ok(describe(host, &project.root, &project.settings.effective()))
let (dirs, root, settings) = (Dirs::of(host), project.root.clone(), project.settings.effective());
host.blocking(move || Ok(describe(&dirs, &root, &settings))).await
}
fn describe(host: &Host, root: &Path, settings: &Settings) -> Option<ContainerPython> {
fn describe(dirs: &Dirs, root: &Path, settings: &Settings) -> Option<ContainerPython> {
let target = settings.languages.python.run_target()?;
let name = settings.run_targets.iter().find(|t| t.id == target).map(|t| t.name.clone()).unwrap_or_default();
let dir = Dirs::of(host).target(root, target);
let dir = dirs.target(root, target);
let mut out = ContainerPython {
target: target.to_owned(),
name,
version: None,
image: None,
executable: None,
folders: Vec::new(),
packages: Vec::new(),
updating: updating(&dir),
@@ -132,7 +142,8 @@ fn describe(host: &Host, root: &Path, settings: &Settings) -> Option<ContainerPy
out.folders = snapshots::local_folders(&dir, &snapshot).into_iter().map(Into::into).collect();
out.packages = snapshots::packages(&dir, &snapshot);
out.version = Some(snapshot.probe.version);
out.image = Some(snapshot.image);
out.executable = Some(snapshot.probe.executable);
out.image = snapshot.distro.is_none().then_some(snapshot.image);
}
Some(out)
}
@@ -144,7 +155,8 @@ pub async fn sdk_container_python_refresh(host: &Host, window: &str) -> IdeResul
host.require_trust(window)?;
let project = host.project(window)?;
update(Dirs::of(host), &project, true).await?;
Ok(describe(host, &project.root, &project.settings.effective()))
let (dirs, root, settings) = (Dirs::of(host), project.root.clone(), project.settings.effective());
host.blocking(move || Ok(describe(&dirs, &root, &settings))).await
}
/// Takes a snapshot when the project interpreter is a run target's and the current image
@@ -154,13 +166,22 @@ pub(crate) fn ensure(host: &Host, project: &Arc<Project>) {
return;
}
let (dirs, project) = (Dirs::of(host), project.clone());
let settings = project.settings.effective();
let wsl = settings
.languages
.python
.run_target()
.and_then(|id| settings.run_targets.iter().find(|t| t.id == id))
.is_some_and(|t| t.kind == RunTargetKind::Wsl);
let title =
if wsl { "Cannot read the WSL Python's libraries" } else { "Cannot copy the container's Python libraries" };
host.runtime.spawn(async move {
if let Err(e) = update(dirs, &project, false).await
&& e.kind != ide_core::error::ErrorKind::Cancelled
{
project.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Warning,
title: "Cannot copy the container's Python libraries".into(),
title: title.into(),
body: Some(e.message),
});
}
@@ -173,7 +194,7 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
let target = ide_remote::service::run_target(&settings, id)?;
if target.kind == RunTargetKind::Ssh {
return Err(IdeError::invalid(format!(
"Run target '{}' runs over SSH: only a Docker or Compose run target can be the project interpreter",
"Run target '{}' is an SSH host: only a Docker, Compose or WSL run target can be the project interpreter",
target.name
)));
}
@@ -182,7 +203,10 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
return Ok(());
}
let _done = Updating(dir.clone());
let endpoint = crate::ops::run::container::endpoint(&dirs.data, &target)?;
let endpoint = match target.kind {
RunTargetKind::Wsl => None,
_ => Some(crate::ops::run::container::endpoint(&dirs.data, &target)?),
};
let task = TaskId::next();
let title = format!("Python libraries of {}", target.name);
let (root, sink) = (project.root.clone(), project.sink.clone());
@@ -198,7 +222,11 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
};
let report = progress.clone();
let result = tokio::task::spawn_blocking(move || {
take(&endpoint, &root, &target, &dir, &dirs.cache, force, &|message| report(message, false))
let report = |message: &str| report(message, false);
match endpoint {
Some(endpoint) => take(&endpoint, &root, &target, &dir, &dirs.cache, force, &report),
None => take_wsl(&root, &target, &dir, &dirs.cache, &report),
}
})
.await
.map_err(|e| IdeError::internal(e.to_string()))
@@ -288,6 +316,7 @@ fn take(
image: image.clone(),
probe,
folders,
distro: None,
};
snapshots::write(&partial, &snapshot)?;
if dir.exists() {
@@ -298,6 +327,72 @@ fn take(
Ok(true)
}
/// Records where the WSL target's Python finds its libraries and makes that the snapshot in
/// use; `false` when nothing changed. Nothing is copied, so packages installed later show up.
fn take_wsl(
root: &Path,
target: &RunTarget,
target_dir: &Path,
cache: &Path,
progress: &dyn Fn(&str),
) -> IdeResult<bool> {
if !cfg!(windows) {
return Err(IdeError::unavailable(format!(
"Run target '{}' is a WSL distribution: WSL needs Windows",
target.name
)));
}
let linux_root = ide_remote::wsl::project_root(target, root)?;
let distro = target.distro.trim();
progress("Starting the WSL Python");
let out = ide_core::wsl::exec(distro, &[ide_remote::wsl::python(target), "-c", snapshots::PROBE], WSL_TIMEOUT)?;
let probe = snapshots::parse_probe(&out)?;
let id = format!("wsl-{}-{}", probe.executable, probe.version);
let snapshot = Snapshot {
image: id.clone(),
folders: wsl_folders(&probe, &linux_root),
neutral_python: snapshots::neutral_python(cache, &probe.version),
distro: Some(distro.to_owned()),
probe,
};
// What the language server is given: the probe's other details (its raw `sys.path` order,
// say) are kept in the snapshot but don't restart it.
let libraries = |s: &Snapshot| (s.image.clone(), s.folders.clone(), s.neutral_python.clone(), s.distro.clone());
let changed = snapshots::current(target_dir).map(|(_, s)| libraries(&s)) != Some(libraries(&snapshot));
let dir = target_dir.join(snapshots::dir_name(&id));
std::fs::create_dir_all(&dir)?;
snapshots::write(&dir, &snapshot)?;
snapshots::make_current(target_dir, &id)?;
Ok(changed)
}
/// The library folders of a WSL Python: as a container's, plus a virtualenv's in the project
/// (`.venv/lib/python3.12/site-packages`), which a container mount would hold anyway.
fn wsl_folders(probe: &snapshots::Probe, linux_root: &str) -> Vec<String> {
let root = linux_root.trim_end_matches('/');
let in_project = |f: &str| root.is_empty() || f == root || f.starts_with(&format!("{root}/"));
let packages = |f: &str| f.split('/').any(|c| c == "site-packages" || c == "dist-packages");
snapshots::folders_to_copy(probe, "").into_iter().filter(|f| !in_project(f) || packages(f)).collect()
}
/// The Pythons found in a WSL distribution, for Add Python Interpreter: the ones on its
/// `PATH`, in `/usr/bin` and `/usr/local/bin`, pyenv's, and the project's virtualenv. Empty off Windows.
#[command(trust = trusted)]
pub async fn sdk_wsl_pythons(host: &Host, window: &str, distro: String) -> IdeResult<Vec<String>> {
host.require_trust(window)?;
if !cfg!(windows) {
return Ok(Vec::new());
}
let root = host.project(window)?.root.clone();
host.blocking(move || {
let distro = distro.trim();
let linux_root = ide_core::wsl::linux_path(&root, distro).unwrap_or_default();
let script = ["sh", "-c", ide_remote::wsl::FIND_PYTHONS, "sh", &linux_root];
Ok(ide_remote::wsl::parse_pythons(&ide_core::wsl::exec(distro, &script, WSL_TIMEOUT)?))
})
.await
}
/// Distinguishes probe containers.
fn unique() -> String {
use std::sync::atomic::{AtomicU32, Ordering};
@@ -306,4 +401,23 @@ fn unique() -> String {
format!("{:x}-{}-{}", secs & 0xff_ffff, std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed))
}
ide_command::domain!(sdk_container_python: sdk_container_python, sdk_container_python_refresh);
#[cfg(test)]
mod wsl_tests {
#[test]
fn a_virtualenv_in_the_project_is_read_and_its_sources_are_not() {
let probe = super::snapshots::Probe {
version: "3.12.3".into(),
executable: "/mnt/c/p/.venv/bin/python".into(),
stdlib: vec![Some("/usr/lib/python3.12".into())],
path: ["/mnt/c/p/src", "/usr/lib/python3.12", "/mnt/c/p/.venv/lib/python3.12/site-packages", "/opt/extra"]
.map(String::from)
.to_vec(),
};
assert_eq!(
super::wsl_folders(&probe, "/mnt/c/p"),
["/mnt/c/p/.venv/lib/python3.12/site-packages", "/opt/extra"]
);
}
}
ide_command::domain!(sdk_container_python: sdk_container_python, sdk_container_python_refresh, sdk_wsl_pythons);
+35 -6
Переглянути файл
@@ -118,21 +118,50 @@ impl PluginHost {
.find(|(p, n, _)| p == plugin && n == tool)
.ok_or_else(|| IdeError::not_found("plugin MCP tool is no longer available"))?;
let args: serde_json::Value = serde_json::from_str(arguments).map_err(|e| IdeError::invalid(e.to_string()))?;
let validator =
jsonschema::validator_for(&declared.input_schema).map_err(|e| IdeError::invalid(e.to_string()))?;
if !validator.is_valid(&args) {
return Err(IdeError::invalid("MCP arguments do not match inputSchema"));
}
let (tool, arguments) = (tool.to_owned(), arguments.to_owned());
let arguments = arguments_for(&declared.input_schema, args)?;
let tool = tool.to_owned();
self.code_call_cancellable(plugin, invocation, "calling the MCP tool", Some(cancel), move |rt, inv| {
rt.mcp_call(&tool, &arguments, inv)
})
}
}
/// `args` as the tool's `schema` takes them. Every listed tool takes `projectPath`, which the
/// server routes a call by; a schema that refuses it gets the call without it.
fn arguments_for(schema: &serde_json::Value, mut args: serde_json::Value) -> IdeResult<String> {
let validator = jsonschema::validator_for(schema).map_err(|e| IdeError::invalid(e.to_string()))?;
if !validator.is_valid(&args)
&& let Some(args) = args.as_object_mut()
{
args.remove(crate::mcp::PROJECT_PATH);
}
if !validator.is_valid(&args) {
return Err(IdeError::invalid("MCP arguments do not match inputSchema"));
}
Ok(args.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_schema_gets_the_project_path_only_when_it_takes_it() {
let call = serde_json::json!({ "text": "hi", "projectPath": "/work/inventory" });
let strict = serde_json::json!({
"type": "object", "properties": { "text": { "type": "string" } }, "additionalProperties": false
});
assert_eq!(arguments_for(&strict, call.clone()).unwrap(), r#"{"text":"hi"}"#);
// Declared through a local `$ref` and required: the plugin keeps it.
let declared = serde_json::json!({
"$ref": "#/$defs/call",
"$defs": { "call": { "type": "object", "required": ["projectPath"], "additionalProperties": false,
"properties": { "text": { "type": "string" }, "projectPath": { "type": "string" } } } }
});
let kept: serde_json::Value = serde_json::from_str(&arguments_for(&declared, call).unwrap()).unwrap();
assert_eq!(kept["projectPath"], "/work/inventory");
assert!(arguments_for(&strict, serde_json::json!({ "text": 12, "projectPath": "/p" })).is_err());
}
#[test]
fn validates_names_schema_files_versions_and_schema_keywords_at_install() {
let tmp = tempfile::tempdir().unwrap();
+29 -2
Переглянути файл
@@ -422,6 +422,10 @@ pub struct PluginHost {
initial_load: (Mutex<bool>, Condvar),
/// `on-startup-finished` has fired.
startup_finished: AtomicBool,
/// Language, file and view activation events fired so far (with their project), so a plugin
/// installed or synced afterwards (a remote server gets its packages after the window opened
/// files) still activates for a Twig file that is already open.
fired_activations: Mutex<Vec<(ActivationEvent, Option<PathBuf>)>>,
/// The theme last announced with `ThemeChanged`.
announced_theme: Mutex<Option<ActiveTheme>>,
/// [`PluginLanguages::revision`] last announced with `LanguagesChanged`.
@@ -541,6 +545,7 @@ impl PluginHost {
lifecycle: Mutex::new(()),
initial_load: (Mutex::new(false), Condvar::new()),
startup_finished: AtomicBool::new(false),
fired_activations: Mutex::new(Vec::new()),
announced_theme: Mutex::new(None),
announced_languages: AtomicU64::new(0),
announced_skills: AtomicU64::new(0),
@@ -699,6 +704,16 @@ impl PluginHost {
/// Fires an activation event from the UI (`on-language:rust`, `on-file:…`, `on-view:…`).
pub fn activation_event(&self, event: &ActivationEvent, project: Option<&Path>) {
{
let mut fired = self.fired_activations.lock();
let entry = (event.clone(), project.map(Path::to_path_buf));
if !fired.contains(&entry) {
if fired.len() >= MAX_FIRED_ACTIVATIONS {
fired.remove(0);
}
fired.push(entry);
}
}
let targets: Vec<_> = self
.plugins
.read()
@@ -745,6 +760,11 @@ impl PluginHost {
.filter(|(_, p)| p.dev_root.as_deref() == Some(root))
.map(|(id, _)| id.clone())
.collect();
// Nothing to unload, nothing to announce: `CommandsChanged` makes every window list the
// plugins again, and listing restricts an untrusted project again, which looped while idle.
if ids.is_empty() {
return;
}
for id in ids {
self.unload(&id);
}
@@ -3096,8 +3116,12 @@ impl PluginHost {
meta.pending = pending;
meta.status = if plugin.manifest().wasm.is_some() { PluginStatus::Inactive } else { PluginStatus::Static };
}
let eager = plugin.manifest().activation.contains(&ActivationEvent::StartupFinished)
&& self.startup_finished.load(Ordering::Acquire);
let eager = (plugin.manifest().activation.contains(&ActivationEvent::StartupFinished)
&& self.startup_finished.load(Ordering::Acquire))
|| self.fired_activations.lock().iter().any(|(event, project)| {
(plugin.dev_root.is_none() || plugin.dev_root == *project)
&& plugin.manifest().activation.iter().any(|a| activation_matches(a, event))
});
if eager {
let _ = self.ensure_active(plugin, None);
}
@@ -3725,6 +3749,9 @@ fn counts(m: &Manifest) -> Vec<ContributionCount> {
m.declaration_counts().into_iter().map(|(point, count)| ContributionCount { point, count }).collect()
}
/// How many fired activation events [`PluginHost::activation_event`] remembers (oldest dropped first).
const MAX_FIRED_ACTIVATIONS: usize = 512;
fn activation_matches(declared: &ActivationEvent, fired: &ActivationEvent) -> bool {
match (declared, fired) {
(ActivationEvent::Language(a), ActivationEvent::Language(b)) => a == b || a == "*",
+118 -11
Переглянути файл
@@ -5,6 +5,10 @@ use super::{
network_inbox::{Inbox, Push},
};
use futures::{SinkExt, StreamExt};
use ide_core::{
IdeResult,
proxy_settings::{ProxyMode, ProxySettings},
};
use ide_plugin::WebSocketBatch;
use parking_lot::Mutex;
use std::{
@@ -17,7 +21,7 @@ use std::{
};
use tokio::sync::{Notify, watch};
use tokio_tungstenite::{
Connector, connect_async_tls_with_config,
Connector, client_async_tls_with_config,
tungstenite::{
Message,
client::IntoClientRequest,
@@ -128,11 +132,20 @@ impl WebSocketHub {
.map(Arc::new)
.map(Connector::Rustls)
.map_err(|error| ConnectError::Failed(error.message))?;
let (socket, response) =
tokio::time::timeout(timeout, connect_async_tls_with_config(request, Some(config), false, Some(tls)))
let target = reqwest::Url::parse(url).map_err(|_| ConnectError::Invalid("invalid WebSocket URL".into()))?;
// Through the IDE's proxy settings, like the Jupyter kernel channels.
let (socket, response) = tokio::time::timeout(timeout, async {
// The tunnel's reason (a proxy that needs a login, refuses or is unreachable) helps the user.
let stream = open_stream(&target, &ide_core::proxy_settings::proxy())
.await
.map_err(|_| ConnectError::Failed("WebSocket connection timed out".into()))?
.map_err(|_| ConnectError::Failed("WebSocket connection failed".into()))?;
.map_err(|error| format!("WebSocket connection failed: {}", error.message))?;
client_async_tls_with_config(request, stream, Some(config), Some(tls))
.await
.map_err(|_| "WebSocket connection failed".to_owned())
})
.await
.map_err(|_| ConnectError::Failed("WebSocket connection timed out".into()))?
.map_err(ConnectError::Failed)?;
if !subprotocol.is_empty()
&& response.headers().get("sec-websocket-protocol").and_then(|value| value.to_str().ok())
!= Some(subprotocol)
@@ -257,14 +270,30 @@ impl WebSocketHub {
}
}
fn validate_url(url: &str) -> Result<(), String> {
let parsed = reqwest::Url::parse(url).map_err(|_| "invalid WebSocket URL")?;
// `host_str` keeps an IPv6 address in brackets.
let loopback = parsed.host_str().is_some_and(|host| {
/// `host_str` keeps an IPv6 address in brackets.
fn is_loopback(url: &reqwest::Url) -> bool {
url.host_str().is_some_and(|host| {
let host = host.trim_start_matches('[').trim_end_matches(']');
host.eq_ignore_ascii_case("localhost") || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
});
if parsed.scheme() != "wss" && !(parsed.scheme() == "ws" && loopback) {
})
}
/// The TCP stream to `url` under `settings`. Loopback stays direct in every mode (plaintext `ws://` is
/// loopback-only); a proxy the tunnel cannot speak to (SOCKS) keeps the direct connection plugins had before.
async fn open_stream(url: &reqwest::Url, settings: &ProxySettings) -> IdeResult<tokio::net::TcpStream> {
if is_loopback(url) {
return ide_http::tunnel::connect_best_effort(
url,
&ProxySettings { mode: ProxyMode::None, ..Default::default() },
)
.await;
}
ide_http::tunnel::connect_best_effort(url, settings).await
}
fn validate_url(url: &str) -> Result<(), String> {
let parsed = reqwest::Url::parse(url).map_err(|_| "invalid WebSocket URL")?;
if parsed.scheme() != "wss" && !(parsed.scheme() == "ws" && is_loopback(&parsed)) {
return Err("WebSocket requires WSS outside loopback".into());
}
if !parsed.username().is_empty() || parsed.password().is_some() || parsed.fragment().is_some() {
@@ -392,6 +421,84 @@ mod tests {
(url, task)
}
fn manual(port: u16) -> ProxySettings {
ProxySettings { mode: ProxyMode::Manual, host: "127.0.0.1".into(), port, ..Default::default() }
}
async fn head_of_first_connection(listener: TcpListener) -> String {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let (mut client, _) = listener.accept().await.unwrap();
let mut head = Vec::new();
let mut byte = [0u8; 1];
while !head.ends_with(b"\r\n\r\n") {
client.read_exact(&mut byte).await.unwrap();
head.push(byte[0]);
}
client.write_all(b"HTTP/1.1 502 Bad Gateway\r\n\r\n").await.unwrap();
String::from_utf8(head).unwrap()
}
#[tokio::test]
async fn a_manual_proxy_carries_the_connection() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let settings = manual(listener.local_addr().unwrap().port());
let proxy = tokio::spawn(head_of_first_connection(listener));
let url = reqwest::Url::parse("wss://ws-target.invalid/socket").unwrap();
assert!(open_stream(&url, &settings).await.is_err());
// A connection that bypasses the proxy leaves it waiting, so bound the wait.
let asked = tokio::time::timeout(Duration::from_secs(2), proxy).await.expect("the proxy was never asked");
assert!(asked.unwrap().starts_with("CONNECT ws-target.invalid:443 HTTP/1.1\r\n"));
}
#[tokio::test]
async fn loopback_stays_direct_in_every_mode() {
let proxy = TcpListener::bind("127.0.0.1:0").await.unwrap();
let proxy_port = proxy.local_addr().unwrap().port();
let proxy_task = tokio::spawn(head_of_first_connection(proxy));
let target = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url =
reqwest::Url::parse(&format!("ws://localhost:{}/socket", target.local_addr().unwrap().port())).unwrap();
let settings = manual(proxy_port);
open_stream(&url, &settings).await.unwrap();
tokio::time::timeout(Duration::from_secs(1), target.accept()).await.expect("no direct connection").unwrap();
// Auto mode asks the system proxy, which may be set in the environment: loopback must not.
open_stream(&url, &ProxySettings::default()).await.unwrap();
tokio::time::timeout(Duration::from_secs(1), target.accept()).await.expect("no direct connection").unwrap();
assert!(tokio::time::timeout(Duration::from_millis(200), proxy_task).await.is_err(), "the proxy was asked");
}
#[tokio::test]
async fn an_ipv6_loopback_websocket_connects() {
let Ok(listener) = TcpListener::bind("[::1]:0").await else { return }; // no IPv6 loopback here
let url = format!("ws://[::1]:{}/socket", listener.local_addr().unwrap().port());
let server = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap();
socket.send(Message::Binary(vec![7].into())).await.unwrap();
socket.close(None).await.unwrap();
});
let hub = WebSocketHub::default();
hub.connect("plugin", "/project", &url, &[], "", Duration::from_secs(2)).await.unwrap();
server.await.unwrap();
}
#[tokio::test]
async fn a_refusing_proxy_says_why() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let settings = manual(listener.local_addr().unwrap().port());
let proxy = tokio::spawn(async move {
use tokio::io::AsyncWriteExt;
let (mut client, _) = listener.accept().await.unwrap();
client.write_all(b"HTTP/1.1 407 Proxy Authentication Required\r\n\r\n").await.unwrap();
// Keep the socket open until the client has read the reply.
tokio::time::sleep(Duration::from_millis(200)).await;
});
let url = reqwest::Url::parse("wss://ws-target.invalid/socket").unwrap();
let error = open_stream(&url, &settings).await.unwrap_err();
assert!(error.message.contains("needs a login"), "{}", error.message);
proxy.await.unwrap();
}
#[tokio::test]
async fn outbound_message_reaches_the_websocket_server() {
let (url, server) = server().await;
+52 -10
Переглянути файл
@@ -77,6 +77,7 @@ pub struct Project {
pub(crate) widget_preview: ide_flutter::ToolServer,
pub(crate) kotlin_bridge: Option<Arc<crate::kotlin_bridge::KotlinBridge>>,
pub(crate) phpstan: Option<Arc<crate::phpstan::Phpstan>>,
pub(crate) swiftlint: Option<Arc<crate::swiftlint::SwiftLint>>,
pub(crate) tsc_watch: Option<Arc<crate::tsc_watch::TscWatch>>,
pub(crate) watcher: Arc<Watcher>,
/// Watchers of the Project Structure content roots outside the project folder.
@@ -419,6 +420,8 @@ impl Host {
trusted.clone(),
);
documents.add_observer(phpstan.clone());
let swiftlint = crate::swiftlint::SwiftLint::new(root.clone(), sink.clone(), trusted.clone());
documents.add_observer(swiftlint.clone());
let tsc_watch = crate::tsc_watch::TscWatch::new(root.clone(), settings.clone(), sink.clone(), trusted.clone());
documents.add_observer(tsc_watch.clone());
let repos = Arc::new(RwLock::new(Repos::enclosing(&root)?));
@@ -441,6 +444,7 @@ impl Host {
let window = window.to_owned();
let kotlin_bridge = kotlin_bridge.clone();
let phpstan = phpstan.clone();
let swiftlint = swiftlint.clone();
let repos = repos.clone();
let git_metadata = git_metadata.clone();
let settings = settings.clone();
@@ -470,6 +474,7 @@ impl Host {
index.update(&[&changed[..], &ignored].concat(), &[&batch.removed[..], &ignored_gone].concat());
kotlin_bridge.files_changed(changed.iter().chain(&batch.removed));
phpstan.files_removed(batch.removed.iter());
swiftlint.files_removed(batch.removed.iter());
lsp.project_files_changed(batch.created.iter().chain(&batch.removed));
lsp.watched_files_changed(&batch.created, &batch.modified, &batch.removed, &batch.excluded_dirs);
if composer_changed(&root, changed.iter().chain(&batch.removed))
@@ -560,6 +565,21 @@ impl Host {
.collect();
matches!(rest.as_slice(), [first, ..] if first == "worktrees" && rest.len() <= 2)
});
// `git worktree add` writes the worktree's gitfile before its gitdir's
// `HEAD`: a rescan in between finds no repository there yet, so that `HEAD`
// rescans too while its worktree is unknown and one a rescan would find.
git_dirs |= batch.vcs.iter().any(|p| {
let Some(gitdir) = p.parent().filter(|_| p.ends_with("HEAD")) else { return false };
if !gitdir.parent().is_some_and(|d| d.ends_with(".git/worktrees")) {
return false;
}
// `gitdir` may be relative to itself (`git worktree add --relative-paths`).
let worktree = std::fs::read_to_string(gitdir.join("gitdir"))
.and_then(|gitfile| dunce::canonicalize(gitdir.join(gitfile.trim())));
worktree.ok().as_deref().and_then(Path::parent).is_some_and(|dir| {
!known.iter().any(|r| r == dir) && repository_searched(&root, dir, &settings.effective())
})
});
// A repository folder moved or restored into the project: no `.git` event is
// written inside it before the watcher sees the new directory, its creation is
// the signal. A `git clone` / `git init` inside the project already arrives
@@ -720,6 +740,7 @@ impl Host {
notebooks,
kotlin_bridge: Some(kotlin_bridge),
phpstan: Some(phpstan),
swiftlint: Some(swiftlint),
tsc_watch: Some(tsc_watch),
watcher,
content_watchers: Mutex::new(content_watchers),
@@ -773,6 +794,8 @@ impl Host {
let weak = Arc::downgrade(&project);
project.agents.set_git_enabled_hook(Arc::new(move || weak.upgrade().is_some_and(|p| p.git_enabled())));
}
// Before anything starts a language server or a tool in the project; a trusted project only.
crate::xcode_env::apply(&project);
self.insert_project(window, project.clone());
for (key, text, dirty) in &carried {
let _ = project.documents.restore_untitled_buffer(key, text, *dirty);
@@ -784,6 +807,9 @@ impl Host {
if let Some(phpstan) = &project.phpstan {
phpstan.start(&self.runtime);
}
if let Some(swiftlint) = &project.swiftlint {
swiftlint.start(&self.runtime);
}
if let Some(watch) = &project.tsc_watch {
watch.apply(&self.runtime);
}
@@ -1015,6 +1041,7 @@ impl Host {
notebooks,
kotlin_bridge: None,
phpstan: None,
swiftlint: None,
tsc_watch: None,
watcher: Arc::new(watcher),
content_watchers: Mutex::new(Vec::new()),
@@ -1036,17 +1063,16 @@ impl Host {
}
}
/// Why a tool that writes or runs refuses a project the user hasn't trusted.
pub(crate) const RESTRICTED_MODE: &str = "Project is in Restricted Mode. Trust the project to enable execution.";
impl Project {
pub fn is_trusted(&self) -> bool {
self.trusted.load(Ordering::Acquire)
}
pub fn require_trust(&self) -> IdeResult<()> {
if self.is_trusted() {
Ok(())
} else {
Err(IdeError::unavailable("Project is in Restricted Mode. Trust the project to enable execution."))
}
if self.is_trusted() { Ok(()) } else { Err(IdeError::unavailable(RESTRICTED_MODE)) }
}
/// LightEdit: follow external changes to the files of `dir` (its own entries only).
@@ -1174,18 +1200,34 @@ fn detect_repositories(
build_cache: &Path,
trusted: bool,
) -> IdeResult<Repos> {
let mut roots = vec![root.to_path_buf()];
roots.extend(content_roots(settings, root, build_cache, trusted));
Repos::discover_roots(&roots, &repository_scan_skips(settings))
}
/// Folders the search for nested repositories leaves out, besides hidden and dependency ones.
fn repository_scan_skips(settings: &ide_core::settings::Settings) -> impl Fn(&Path) -> bool {
let ignored = settings.ignored_names();
let skip = |p: &Path| {
move |p: &Path| {
p.file_name().is_some_and(|n| {
let name = n.to_string_lossy();
ignored.is_ignored_name(&name)
|| (ide_workspace::unity::GENERATED_DIRS.contains(&name.as_ref())
&& p.parent().is_some_and(ide_workspace::unity::is_project))
})
};
let mut roots = vec![root.to_path_buf()];
roots.extend(content_roots(settings, root, build_cache, trusted));
Repos::discover_roots(&roots, &skip)
}
}
/// Whether a scan of the project at `root` would look for a repository at `dir` and keep it.
fn repository_searched(root: &Path, dir: &Path, settings: &ide_core::settings::Settings) -> bool {
settings.vcs.git.enabled
&& !settings
.vcs
.mappings
.excluded
.iter()
.any(|p| dunce::canonicalize(VcsMappings::resolve(root, p)).is_ok_and(|e| e == dir))
&& Repos::searched(root, dir, &repository_scan_skips(settings))
}
impl Project {
+1
Переглянути файл
@@ -500,6 +500,7 @@ mod tests {
subject: "rm -rf".into(),
project: "/srv/app".into(),
detail: None,
background: false,
};
let update = ide_core::updates::UpdateInfo {
version: "9.9.9".into(),
+404
Переглянути файл
@@ -0,0 +1,404 @@
//! Swift files below a `.swiftlint.yml` -> `swiftlint lint --reporter json` -> `swiftlint` diagnostics.
//!
//! A file as saved is linted by its path, so the configuration's `excluded` paths and nested
//! configurations apply; an edited buffer is linted through stdin, unless its saved file was excluded.
use ide_core::event::NotifyLevel;
use ide_core::output_encoding::decode_tool_output;
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink};
use ide_text::AppliedChange;
use ide_workspace::documents::{DocumentInfo, DocumentObserver};
use parking_lot::Mutex;
use serde::Deserialize;
use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::{Output, Stdio};
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use std::time::Duration;
use tokio::io::AsyncWriteExt;
use tokio::sync::Notify;
const DELAY: Duration = Duration::from_millis(400);
const SOURCE: &str = "swiftlint";
const CONFIG: &str = ".swiftlint.yml";
/// What to lint: the saved file, or the text of its edited buffer.
#[derive(Clone, Debug, PartialEq)]
enum Job {
Saved,
Buffer(String),
}
pub(crate) struct SwiftLint {
root: PathBuf,
sink: SharedSink,
trusted: Arc<AtomicBool>,
lifetime: CancellationToken,
/// The latest job per file; a newer one replaces it, and its result is dropped.
pending: Mutex<BTreeMap<PathBuf, Job>>,
changed: Notify,
/// Files with SwiftLint diagnostics, the only ones a clean result or a close clears.
shown: Mutex<HashSet<PathBuf>>,
/// Files the configuration excludes, as found by their last saved-file lint.
excluded: Mutex<HashSet<PathBuf>>,
/// Failures already reported (a missing `swiftlint` included), each once until a run succeeds.
reported: Mutex<Option<String>>,
}
impl SwiftLint {
pub(crate) fn new(root: PathBuf, sink: SharedSink, trusted: Arc<AtomicBool>) -> Arc<Self> {
Arc::new(Self {
root,
sink,
trusted,
lifetime: CancellationToken::new(),
pending: Mutex::new(BTreeMap::new()),
changed: Notify::new(),
shown: Mutex::new(HashSet::new()),
excluded: Mutex::new(HashSet::new()),
reported: Mutex::new(None),
})
}
pub(crate) fn start(self: &Arc<Self>, runtime: &tokio::runtime::Handle) {
let linter = self.clone();
runtime.spawn(async move { linter.run().await });
}
pub(crate) fn stop(&self) {
self.lifetime.cancel();
}
fn queue(&self, path: &Path, job: Job) {
if self.lifetime.is_cancelled() || !path.extension().is_some_and(|e| e == "swift") {
return;
}
self.pending.lock().insert(path.to_path_buf(), job);
self.changed.notify_one();
}
/// Trusting the project lints its open files; Restricted Mode drops what was shown.
pub(crate) fn trust_changed(&self, trusted: bool, open: impl Iterator<Item = DocumentInfo>) {
if trusted {
open.for_each(|info| self.opened(&info));
} else {
self.pending.lock().clear();
let shown: Vec<PathBuf> = self.shown.lock().iter().cloned().collect();
for path in shown {
self.publish(path, Vec::new());
}
}
}
/// Deleted files and folders lose their diagnostics.
pub(crate) fn files_removed<'a>(&self, removed: impl Iterator<Item = &'a PathBuf>) {
let removed: Vec<&PathBuf> = removed.collect();
self.excluded.lock().retain(|p| !removed.iter().any(|r| p.starts_with(r)));
let gone: Vec<PathBuf> =
self.shown.lock().iter().filter(|p| removed.iter().any(|r| p.starts_with(r))).cloned().collect();
for path in gone {
self.publish(path, Vec::new());
}
}
fn publish(&self, path: PathBuf, items: Vec<Diagnostic>) {
let mut shown = self.shown.lock();
if items.is_empty() {
if !shown.remove(&path) {
return;
}
} else {
shown.insert(path.clone());
}
self.sink.emit(IdeEvent::Diagnostics { path: path.into(), source: SOURCE.into(), items });
}
async fn run(self: Arc<Self>) {
loop {
tokio::select! {
_ = self.lifetime.cancelled() => return,
_ = self.changed.notified() => {},
}
// Typing keeps replacing the pending job: lint once it pauses.
tokio::select! {
_ = self.lifetime.cancelled() => return,
_ = tokio::time::sleep(DELAY) => {},
}
loop {
let Some((path, job)) = self.pending.lock().pop_first() else { break };
if !self.trusted.load(Ordering::Acquire) {
continue;
}
let Some(dir) = config_dir(&self.root, &path) else {
self.publish(path, Vec::new());
continue;
};
if job != Job::Saved && self.excluded.lock().contains(&path) {
continue;
}
let text = match &job {
Job::Saved => None,
Job::Buffer(text) => Some(text.as_str()),
};
let Some(output) = lint(&dir, &path, text, &self.lifetime).await else { return };
// Edited again meanwhile: the newer job's result replaces this one. Restricted
// meanwhile: `trust_changed` already cleared the findings.
if self.pending.lock().contains_key(&path) || !self.trusted.load(Ordering::Acquire) {
continue;
}
let result = output.map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
"swiftlint was not found on PATH. Install SwiftLint (brew install swiftlint), \
or from Settings › Languages & Frameworks › Language Servers."
.to_string()
} else {
format!("Cannot run swiftlint: {e}")
}
});
let result = result.and_then(|o| parse(&decode_tool_output(&o.stdout), &decode_tool_output(&o.stderr)));
match result {
Ok(Report::Excluded) => {
self.excluded.lock().insert(path.clone());
self.publish(path, Vec::new());
*self.reported.lock() = None;
}
Ok(Report::Violations(violations)) => {
if job == Job::Saved {
self.excluded.lock().remove(&path);
}
let text = match job {
Job::Buffer(text) => text,
Job::Saved => std::fs::read(&path)
.map(|b| String::from_utf8_lossy(&b).into_owned())
.unwrap_or_default(),
};
let items = violations.into_iter().map(|v| diagnostic(v, &text)).collect();
self.publish(path, items);
*self.reported.lock() = None;
}
Err(text) => {
self.publish(path, Vec::new());
self.failure(text);
}
}
}
}
}
fn failure(&self, text: String) {
let mut reported = self.reported.lock();
if reported.as_ref() == Some(&text) {
return;
}
self.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Error,
title: "SwiftLint check failed".into(),
body: Some(text.clone()),
});
*reported = Some(text);
}
}
impl DocumentObserver for SwiftLint {
fn opened(&self, info: &DocumentInfo) {
let path = info.path.to_path_buf();
self.queue(&path, if info.dirty { Job::Buffer(info.text.clone()) } else { Job::Saved });
}
fn changed(
&self,
_doc: ide_core::DocId,
path: &Path,
_version: u32,
_changes: &[AppliedChange],
full_text: &dyn Fn() -> String,
) {
if path.extension().is_some_and(|e| e == "swift") {
self.queue(path, Job::Buffer(full_text()));
}
}
fn saved(&self, _doc: ide_core::DocId, path: &Path, _text: &str) {
self.queue(path, Job::Saved);
}
/// A closed buffer's unsaved text is gone, and with it what its diagnostics described.
fn closed(&self, _doc: ide_core::DocId, path: &Path) {
self.pending.lock().remove(path);
self.publish(path.to_path_buf(), Vec::new());
}
}
/// The folder of the `.swiftlint.yml` nearest to `file` within the project, where SwiftLint
/// runs so it finds that configuration. Files outside the project, or below no configuration,
/// are not linted.
fn config_dir(root: &Path, file: &Path) -> Option<PathBuf> {
file.ancestors()
.skip(1)
.take_while(|d| d.starts_with(root))
.find(|d| d.join(CONFIG).is_file())
.map(Path::to_path_buf)
}
/// Runs `swiftlint lint` in `dir` on the saved `file`, or on `text` through stdin;
/// `None` when `cancel` fires first, which kills it.
async fn lint(
dir: &Path,
file: &Path,
text: Option<&str>,
cancel: &CancellationToken,
) -> Option<std::io::Result<Output>> {
let mut cmd = std::process::Command::new("swiftlint");
cmd.args(["lint", "--reporter", "json", "--quiet", "--no-cache"]).current_dir(dir);
match text {
Some(_) => cmd.arg("--use-stdin"),
None => cmd.arg("--force-exclude").arg(file),
};
ide_core::process::prepare(&mut cmd);
cmd.stdin(if text.is_some() { Stdio::piped() } else { Stdio::null() });
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
let mut cmd = tokio::process::Command::from(cmd);
cmd.kill_on_drop(true);
let run = async {
let mut child = cmd.spawn()?;
if let (Some(text), Some(mut stdin)) = (text, child.stdin.take()) {
stdin.write_all(text.as_bytes()).await?;
}
child.wait_with_output().await
};
tokio::select! {
output = run => Some(output),
() = cancel.cancelled() => None,
}
}
/// One entry of SwiftLint's JSON report; `line` and `character` are 1-based, the
/// character counted in UTF-16 units.
#[derive(Debug, Deserialize, PartialEq)]
struct Violation {
line: Option<u32>,
character: Option<u32>,
reason: String,
rule_id: String,
severity: String,
}
#[derive(Debug, PartialEq)]
enum Report {
Violations(Vec<Violation>),
/// `--force-exclude` dropped the file: the configuration's `excluded` lists it.
Excluded,
}
/// The `--reporter json` report (SwiftLint exits with 2 when it has errors), or the text
/// to report when there is none.
fn parse(stdout: &str, stderr: &str) -> Result<Report, String> {
if let Ok(violations) = serde_json::from_str::<Vec<Violation>>(stdout.trim()) {
return Ok(Report::Violations(violations));
}
if stderr.contains("No lintable files found") {
return Ok(Report::Excluded);
}
let lines: Vec<&str> = stderr.lines().chain(stdout.lines()).map(str::trim).filter(|l| !l.is_empty()).collect();
if lines.is_empty() {
return Err("SwiftLint ended with no report".into());
}
Err(lines.iter().take(20).copied().collect::<Vec<_>>().join("\n"))
}
fn diagnostic(v: Violation, text: &str) -> Diagnostic {
Diagnostic {
range: range(text, v.line, v.character),
severity: if v.severity.eq_ignore_ascii_case("error") { Severity::Error } else { Severity::Warning },
message: v.reason,
source: Some("SwiftLint".into()),
server: Some(SOURCE.into()),
code: Some(v.rule_id),
unnecessary: false,
deprecated: false,
}
}
/// The word at the reported position, or the line from its first non-blank character when
/// SwiftLint gives no column (or the column has no word: a semicolon, a brace).
fn range(text: &str, line: Option<u32>, character: Option<u32>) -> Range {
let line = line.unwrap_or(1).max(1) - 1;
let content = text.strip_prefix('\u{feff}').unwrap_or(text).split('\n').nth(line as usize).unwrap_or("");
let content: Vec<u16> = content.trim_end().encode_utf16().collect();
let len = u32::try_from(content.len()).unwrap_or(u32::MAX);
let Some(start) = character.map(|c| c.max(1) - 1).filter(|&c| c < len) else {
let indent = content.iter().take_while(|&&u| u == u16::from(b' ') || u == u16::from(b'\t')).count();
return Range { start: Pos { line, col: indent as u32 }, end: Pos { line, col: len } };
};
let word = |u: &u16| char::from_u32(u32::from(*u)).is_some_and(|c| c.is_alphanumeric() || c == '_');
let run = content[start as usize..].iter().take_while(|u| word(u)).count() as u32;
Range { start: Pos { line, col: start }, end: Pos { line, col: start + run.max(1) } }
}
#[cfg(test)]
mod tests {
use super::*;
const REPORT: &str = r#"[
{"character": 5, "file": null, "line": 1, "reason": "Variable name 'a_b' should only contain alphanumeric characters",
"rule_id": "identifier_name", "severity": "Error", "type": "Identifier Name"},
{"character": null, "file": "/p/A.swift", "line": 3, "reason": "Line should be 40 characters or less",
"rule_id": "line_length", "severity": "Warning", "type": "Line Length"},
{"character": 13, "file": null, "line": 2, "reason": "Lines should not have trailing semicolons",
"rule_id": "trailing_semicolon", "severity": "Warning", "type": "Trailing Semicolon"}
]"#;
#[test]
fn violations_map_to_diagnostics() {
let Ok(Report::Violations(violations)) = parse(REPORT, "") else { panic!() };
let text = "let a_b = 1\nlet 😀x = 1 ;\n let long = 2\n";
let items: Vec<Diagnostic> = violations.into_iter().map(|v| diagnostic(v, text)).collect();
let summary: Vec<_> = items.iter().map(|d| (d.code.as_deref().unwrap(), d.severity, d.range)).collect();
let r = |line, a, b| Range { start: Pos { line, col: a }, end: Pos { line, col: b } };
assert_eq!(
summary,
[
("identifier_name", Severity::Error, r(0, 4, 7)),
// No column: the line from its first non-blank character.
("line_length", Severity::Warning, r(2, 4, 16)),
// UTF-16 columns: the emoji takes two, and a semicolon gets one.
("trailing_semicolon", Severity::Warning, r(1, 12, 13)),
]
);
assert_eq!((items[0].source.as_deref(), items[0].server.as_deref()), (Some("SwiftLint"), Some("swiftlint")));
assert!(items[0].message.starts_with("Variable name 'a_b'"));
}
#[test]
fn excluded_files_and_failures_are_told_apart() {
assert_eq!(parse("[]\n", ""), Ok(Report::Violations(vec![])));
let excluded = "Error: No lintable files found at paths: 'Gen/g.swift'\n";
assert_eq!(parse("", excluded), Ok(Report::Excluded));
assert_eq!(parse("", "Fatal error: crashed\n\n"), Err("Fatal error: crashed".into()));
assert_eq!(parse("", ""), Err("SwiftLint ended with no report".into()));
// A bad column or line stays on the text.
assert_eq!(
range("x", Some(9), Some(40)),
Range { start: Pos { line: 8, col: 0 }, end: Pos { line: 8, col: 0 } }
);
}
#[test]
fn the_nearest_configuration_in_the_project_wins() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("p");
std::fs::create_dir_all(root.join("Sources/App")).unwrap();
std::fs::create_dir_all(root.join("Pkg/Sources")).unwrap();
let file = root.join("Sources/App/A.swift");
assert_eq!(config_dir(&root, &file), None);
std::fs::write(dir.path().join(CONFIG), "").unwrap();
assert_eq!(config_dir(&root, &file), None, "a configuration above the project is not the project's");
std::fs::write(root.join(CONFIG), "").unwrap();
std::fs::write(root.join("Pkg").join(CONFIG), "").unwrap();
assert_eq!(config_dir(&root, &file), Some(root.clone()));
assert_eq!(config_dir(&root, &root.join("Pkg/Sources/B.swift")), Some(root.join("Pkg")));
}
}
+7
Переглянути файл
@@ -267,6 +267,10 @@ impl crate::Host {
if let Some(phpstan) = &project.phpstan {
phpstan.interrupt();
}
if let Some(swiftlint) = &project.swiftlint {
let docs = project.documents.open_documents();
swiftlint.trust_changed(trusted, docs.into_iter().filter_map(|d| project.documents.snapshot(d).ok()));
}
if let Some(watch) = &project.tsc_watch {
watch.apply(&self.runtime);
}
@@ -276,6 +280,8 @@ impl crate::Host {
}
project.lsp.set_execution_allowed(false);
}
// Before anything runs `git` (a `/usr/bin` shim that follows `DEVELOPER_DIR`): set or cleared.
crate::xcode_env::apply(&project);
project.repos();
if trusted {
if let Some(cmd) = self.environment.project_opened(&project.root, &project.sink) {
@@ -308,6 +314,7 @@ impl crate::Host {
.map(|(window, _)| window.clone())
.collect();
for window in windows {
self.mcp_requests.withdraw(&window);
let requests = self.project_requests.write().remove(&window).unwrap_or_default();
for request in requests {
self.cancel_request(request);
+49
Переглянути файл
@@ -0,0 +1,49 @@
//! The project's Xcode (`languages.swift.xcode`): every child started in the project gets it as
//! `DEVELOPER_DIR` through [`ide_core::project_env`] — sourcekit-lsp, `xcodebuild` and `xcrun` of
//! runs, tests, coverage and debugging, and terminals.
use crate::project::Project;
use ide_core::settings::SwiftSettings;
use std::path::PathBuf;
/// The `DEVELOPER_DIR` a project's children get. Only a trusted project's: the setting lives in the
/// repository (`.openidea/settings.toml`), and the `/usr/bin` shims (`git`, `xcrun`, `clang`, …)
/// run `$DEVELOPER_DIR/usr/bin/<tool>`, so an untrusted one could point them at its own binaries.
fn developer_dir(trusted: bool, swift: &SwiftSettings) -> Option<PathBuf> {
trusted.then(|| swift.developer_dir()).flatten()
}
/// Applies the project's Xcode to its environment, or clears it for an untrusted project; returns
/// whether it changed.
pub fn apply(project: &Project) -> bool {
let trusted = project.is_trusted() && !project.light;
let dir = developer_dir(trusted, &project.settings.effective().languages.swift).map(Into::into);
let root = ide_core::project_env::set_developer_dir(&project.root, dir.clone());
let worktrees = ide_core::project_env::set_developer_dir(project.agents.worktrees_dir(), dir);
root || worktrees
}
/// [`apply`], then restarts a running sourcekit-lsp when the Xcode changed.
pub async fn apply_and_restart(project: &Project) {
if !apply(project) {
return;
}
for server in project.lsp.servers().into_iter().filter(|s| s.name == "sourcekit-lsp") {
if let Err(e) = project.lsp.restart(server.id).await {
tracing::warn!("restarting sourcekit-lsp for the new Xcode: {e}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_trusted_project_gets_its_xcode() {
let swift = SwiftSettings { xcode: "./x.app".into() };
assert_eq!(developer_dir(false, &swift), None, "untrusted: the repository's own binaries must not run");
assert_eq!(developer_dir(true, &swift), Some("./x.app/Contents/Developer".into()));
assert_eq!(developer_dir(true, &SwiftSettings::default()), None);
}
}
+1 -1
Переглянути файл
@@ -107,7 +107,7 @@ async fn compose_target_is_the_python_interpreter() {
eprintln!("run target interpreter: {after:?}");
assert!(after.iter().all(|m| !m.contains("could not be resolved")), "{after:?}");
let info = ops::sdk::sdk_container_python(&host, WINDOW).unwrap().expect("a run target interpreter");
let info = ops::sdk::sdk_container_python(&host, WINDOW).await.unwrap().expect("a run target interpreter");
eprintln!("snapshot: version {:?}, image {:?}, folders {:?}", info.version, info.image, info.folders);
assert_eq!(info.name, "Compose web");
assert!(info.version.as_deref().is_some_and(|v| v.starts_with("3.12.")), "{info:?}");
+15 -10
Переглянути файл
@@ -742,38 +742,43 @@ async fn typescript_import_style() {
..TYPESCRIPT
};
let smoke = Smoke::start("typescript", &checks).await;
let set = |key: &str, value: &str| {
let lsp = smoke.host.project(WINDOW).unwrap().lsp.clone();
// Returns once vtsls has the change. A completion that runs before it fills tsserver's
// module specifier cache for that file under the old preferences, and that cache is keyed
// without `autoImportSpecifierExcludeRegexes`, so the file keeps the old answer.
let set = async |key: &str, value: &str| {
let scope = ide_workspace::settings::SettingsScope::Project;
let key = format!("editor.codeStyle.languages.typescript.{key}");
ops::project::settings_set(&smoke.host, WINDOW, scope, key, value.into()).unwrap();
lsp.reconfigure().await;
};
let alpha = typed("src/app/main.ts", "export const ready", "alphaH");
let beta = typed("src/app/main.ts", "export const ready", "betaW");
let import = |typed, label, result| AutoImport { typed, label, result };
set("importModuleSpecifier", r#""relative""#);
set("importModuleSpecifier", r#""relative""#).await;
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
set("importModuleSpecifier", r#""non-relative""#);
set("importModuleSpecifier", r#""non-relative""#).await;
smoke.auto_import(import(alpha, "alphaHelper", r#"from "@/lib/alpha""#)).await;
set("importModuleSpecifier", r#""relative""#);
set("importModuleSpecifierEnding", r#""index""#);
set("importModuleSpecifier", r#""relative""#).await;
set("importModuleSpecifierEnding", r#""index""#).await;
smoke.auto_import(import(beta, "betaWidget", r#"from "./components/index""#)).await;
set("importModuleSpecifierEnding", r#""minimal""#);
set("importModuleSpecifierEnding", r#""minimal""#).await;
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
// tsserver keeps the auto-import candidates of the file it last completed in until the
// program changes; other files see an exclusion at once.
set("autoImportFileExcludePatterns", r#"["**/index.ts"]"#);
set("autoImportFileExcludePatterns", r#"["**/index.ts"]"#).await;
smoke.not_offered(typed("src/app/other.ts", "export const other", "betaW"), "betaWidget", "betaWord").await;
set("autoImportSpecifierExcludeRegexes", r#"["lib/alpha$"]"#);
set("autoImportSpecifierExcludeRegexes", r#"["lib/alpha$"]"#).await;
smoke.not_offered(typed("src/app/third.ts", "export const third", "alphaH"), "alphaHelper", "alphaHint").await;
// Emptied lists reach the server too: the symbols are offered again.
set("autoImportFileExcludePatterns", "[]");
set("autoImportFileExcludePatterns", "[]").await;
let beta = typed("src/app/fourth.ts", "export const fourth", "betaW");
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
set("autoImportSpecifierExcludeRegexes", "[]");
set("autoImportSpecifierExcludeRegexes", "[]").await;
let alpha = typed("src/app/fifth.ts", "export const fifth", "alphaH");
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
}
+437 -56
Переглянути файл
@@ -1,6 +1,8 @@
mod common;
use ide_core::{CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, Severity, TextChange};
use ide_core::{
CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, Severity, TextChange, event::McpUiRequest,
};
use ide_host::mcp::{BackgroundProjects, FileProblems, FocusedEditor, Registry};
use ide_host::{Host, HostConfig};
use ide_mcp::ToolRegistry;
@@ -12,7 +14,8 @@ struct Harness {
host: Arc<Host>,
root: PathBuf,
tmp: tempfile::TempDir,
events: Arc<std::sync::Mutex<Vec<IdeEvent>>>,
/// Every event, with the window whose sink it was emitted on.
events: Arc<std::sync::Mutex<Vec<(String, IdeEvent)>>>,
}
impl Harness {
fn new() -> Self {
@@ -27,9 +30,9 @@ impl Harness {
let events = Arc::new(std::sync::Mutex::new(Vec::new()));
let sink = events.clone();
let host = Arc::new(Host::new(HostConfig {
sink_for: Box::new(move |_| {
let events = sink.clone();
Arc::new(move |e| events.lock().unwrap().push(e))
sink_for: Box::new(move |window| {
let (window, events) = (window.to_owned(), sink.clone());
Arc::new(move |e| events.lock().unwrap().push((window.clone(), e)))
}),
local_data_dir: tmp.path().join("local"),
..common::host_config(tmp.path())
@@ -55,7 +58,7 @@ impl Harness {
async fn request(&self) -> u32 {
tokio::time::timeout(std::time::Duration::from_secs(10), async {
loop {
if let Some(id) = self.events.lock().unwrap().iter().rev().find_map(|e| match e {
if let Some(id) = self.events.lock().unwrap().iter().rev().find_map(|(_, e)| match e {
IdeEvent::McpRequest { id, .. } => Some(*id),
_ => None,
}) {
@@ -67,6 +70,54 @@ impl Harness {
.await
.unwrap()
}
/// The requests `window` shows: asked there and not closed since.
fn shown(&self, window: &str) -> Vec<(u32, McpUiRequest)> {
let mut shown = Vec::new();
for (_, event) in self.events.lock().unwrap().iter().filter(|(w, _)| w == window) {
match event {
IdeEvent::McpRequest { id, request } => shown.push((*id, request.clone())),
IdeEvent::McpRequestClosed { id } => shown.retain(|(open, _)| open != id),
_ => {}
}
}
shown
}
/// Waits until `window` shows `count` requests, and returns them.
async fn shown_in(&self, window: &str, count: usize) -> Vec<(u32, McpUiRequest)> {
tokio::time::timeout(std::time::Duration::from_secs(10), async {
loop {
let shown = self.shown(window);
if shown.len() >= count {
return shown;
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.unwrap_or_else(|_| panic!("{window} shows no {count} requests"))
}
/// The request `window` shows, once it shows one.
async fn request_in(&self, window: &str) -> (u32, McpUiRequest) {
self.shown_in(window, 1).await.pop().unwrap()
}
/// Whether `window` was told that request `id` closed.
fn closed_in(&self, window: &str, id: u32) -> bool {
let events = self.events.lock().unwrap();
events
.iter()
.any(|(w, e)| w == window && matches!(e, IdeEvent::McpRequestClosed { id: closed } if *closed == id))
}
/// Reports `window` focused, as its frontend does when the user brings it to the front.
fn focus(&self, window: &str) {
self.host.mcp_reports.set_focused_editor(window, None, true);
}
/// Opens the window `second` on the folder `second` next to the open project.
fn open_second(&self) -> PathBuf {
let second = self.root.parent().unwrap().join("second");
std::fs::create_dir_all(&second).unwrap();
self.host.open_project("second", &second).unwrap();
second
}
async fn call(&self, name: &str, args: Value) -> String {
let (host, root, name) = (self.host.clone(), self.root.clone(), name.to_owned());
tokio::task::spawn_blocking(move || {
@@ -252,6 +303,10 @@ async fn restricted_projects_have_only_read_tools_and_remote_projects_explain_th
assert!(!h.host.project("main").unwrap().is_trusted());
let registry = Registry::new(h.host.clone());
assert!(registry.tools(&h.root).unwrap().iter().all(|t| t.read_only && !t.destructive));
// A tool that writes, called all the same, says why it can't run.
let refused = h.error("create_new_file", json!({"pathInProject":"x.txt","text":"no"})).await;
assert_eq!(refused, "Project is in Restricted Mode. Trust the project to enable execution.");
assert!(!h.root.join("x.txt").exists());
assert!(!h.host.global_settings.effective().mcp_server.enabled);
h.host.mcp_reports.set_remote("remote", PathBuf::from("/remote/project"));
assert_eq!(
@@ -391,7 +446,11 @@ async fn mutations_preserve_unsaved_text_and_reject_metadata_and_escapes() {
assert!(p.documents.is_dirty(doc.id).unwrap());
assert_eq!(std::fs::read_to_string(&path).unwrap(), "old text\nneedle needle\n");
assert!(
h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::DocPatched { doc: id, .. } if *id == doc.id))
h.events
.lock()
.unwrap()
.iter()
.any(|(_, e)| matches!(e, IdeEvent::DocPatched { doc: id, .. } if *id == doc.id))
);
let edit_id = h
.events
@@ -399,7 +458,7 @@ async fn mutations_preserve_unsaved_text_and_reject_metadata_and_escapes() {
.unwrap()
.iter()
.rev()
.find_map(|event| match event {
.find_map(|(_, event)| match event {
// Undoable like a refactoring, but marked as the agent's, so it isn't announced as one.
IdeEvent::WorkspaceEditApplied { id, by_agent, .. } => {
assert!(*by_agent, "an MCP edit is the agent's");
@@ -438,14 +497,16 @@ async fn execution_requires_a_window_and_denial_never_runs_a_build() {
h.host.mcp_requests.set_ready("main", true);
let denied = h.error("build_project", json!({}));
let answer = async {
let id = h.request().await;
let (id, request) = h.request_in("main").await;
// A window's own project is not a background one.
assert!(matches!(request, McpUiRequest::Confirm { background: false, .. }), "{request:?}");
assert!(h.host.mcp_requests.answer("other", id, true, None).is_err());
h.host.mcp_requests.answer("main", id, false, None).unwrap();
};
let (error, ()) = tokio::join!(denied, answer);
assert!(error.contains("denied by the user"), "{error}");
assert!(h.host.processes.list().is_empty());
assert!(h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequestClosed { .. })));
assert!(h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequestClosed { .. })));
h.events.lock().unwrap().clear();
let closed = h.error("build_project", json!({}));
let close = async {
@@ -774,7 +835,7 @@ fn config_run_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig
tokio::spawn(async move {
let mut handled = std::collections::HashSet::new();
loop {
let request = events.lock().unwrap().iter().find_map(|e| match e {
let request = events.lock().unwrap().iter().find_map(|(_, e)| match e {
IdeEvent::McpRequest { id, request: ide_core::event::McpUiRequest::RunConfiguration { config } }
if !handled.contains(id) =>
{
@@ -847,11 +908,9 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
assert_eq!(tabs[0].name, "MCP test");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
let h = Harness::new();
h.trust().await;
let config = ide_run::RunConfig {
/// A shell configuration named `MCP test` that prints `windowless` and exits with 3.
fn windowless_config() -> ide_run::RunConfig {
ide_run::RunConfig {
id: "test".into(),
name: "MCP test".into(),
kind: "shell".into(),
@@ -864,8 +923,14 @@ async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
ide_run::save_user_configs(&h.root, &[config]).unwrap();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
let h = Harness::new();
h.trust().await;
ide_run::save_user_configs(&h.root, &[windowless_config()]).unwrap();
h.host
.global_settings
.set(ide_workspace::SettingsScope::Global, "mcpServer.runWithoutConfirmation", json!(true))
@@ -873,7 +938,7 @@ async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
let result = h.json("execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000})).await;
assert_eq!(result["exitCode"], 3, "{result}");
assert!(result["output"].as_str().unwrap().contains("windowless"));
assert!(!h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
}
#[tokio::test(flavor = "multi_thread")]
@@ -1020,7 +1085,7 @@ async fn brave_mode_runs_tools_without_asking_only_from_the_global_settings() {
.expect("ran without waiting for an answer")
.unwrap();
assert!(!format!("{result:?}").contains("denied"), "{result:?}");
assert!(!h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
}
#[tokio::test(flavor = "multi_thread")]
@@ -1052,7 +1117,7 @@ fn run_tool_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig>>
tokio::spawn(async move {
let mut handled = std::collections::HashSet::new();
loop {
let request = events.lock().unwrap().iter().find_map(|e| match e {
let request = events.lock().unwrap().iter().find_map(|(_, e)| match e {
IdeEvent::McpRequest {
id,
request: ide_core::event::McpUiRequest::AgentRun { name, command, cwd, env },
@@ -1166,8 +1231,12 @@ async fn agent_commands_run_in_named_tabs_and_report_what_the_user_did() {
assert_eq!(stopped["state"], "stoppedByAgent", "{stopped}");
assert!(stopped.get("interventions").is_none());
// The user's Stop, rerun and closing the tab are reported with their time.
h.json("run_command", json!({"name": "server", "command": "sleep 30", "timeout": 0})).await;
// The user's Stop, rerun and closing the tab are reported with their time. A stop waits for the command
// itself: a Ctrl+C while the login shell still reads its profile can be taken by a profile command that
// handles it, and the shell then runs the command anyway.
let ready = json!({"name": "server", "command": "echo ready; sleep 30", "pattern": "(?m)^ready", "timeout": 10000});
let ready = h.json("run_command", ready).await;
assert_eq!((&ready["waitEnded"], &ready["state"]), (&json!("matched"), &json!("running")), "{ready}");
ide_host::ops::run::run_stop(&h.host, "main", agent_process(&h, "_agent_server")).unwrap();
let stop = h.json("wait_for_run", json!({"name": "server", "timeout": 10000})).await;
assert!(stop["interventions"][0]["message"].as_str().unwrap().starts_with("The user stopped this command at"));
@@ -1217,7 +1286,10 @@ async fn agent_commands_run_in_named_tabs_and_report_what_the_user_did() {
assert_eq!(head["output"], "one\n<<<...content truncated...>>>\n", "{head}");
// Ctrl+C stops the command as stop_run does; terminal keys have no meaning on pipes.
h.json("run_command", json!({"name": "interrupt", "command": "sleep 30", "timeout": 0})).await;
let ready =
json!({"name": "interrupt", "command": "echo ready; sleep 30", "pattern": "(?m)^ready", "timeout": 10000});
let ready = h.json("run_command", ready).await;
assert_eq!((&ready["waitEnded"], &ready["state"]), (&json!("matched"), &json!("running")), "{ready}");
let key = h.error("send_run_input", json!({"name": "interrupt", "keys": ["Up"]})).await;
assert!(key.contains("runs on pipes"), "{key}");
h.json("send_run_input", json!({"name": "interrupt", "keys": ["Ctrl+C"]})).await;
@@ -1539,22 +1611,91 @@ async fn a_folder_without_a_window_is_opened_by_its_first_tool_call() {
}
#[tokio::test(flavor = "multi_thread")]
async fn with_background_projects_off_a_folder_outside_the_open_projects_is_refused() {
async fn with_background_projects_off_a_folder_outside_the_open_projects_lists_tools_and_refuses_calls() {
let h = Harness::new();
let inventory = h.root.parent().unwrap().join("inventory");
std::fs::create_dir_all(&inventory).unwrap();
let (_server, discovery) = h.server();
let list = rpc(1, "tools/list", json!({}));
let read = rpc(2, "tools/call", json!({"name":"read_file","arguments":{"file_path":"a.txt"}}));
for reply in bridged(&discovery, &inventory, &[list, read]).await {
assert_eq!(reply["error"]["code"], -32001, "{reply}");
let message = reply["error"]["message"].as_str().unwrap();
assert!(message.contains("isn't served in the background"), "{message}");
}
let replies = bridged(&discovery, &inventory, &[list, read]).await;
let tools = replies[0]["result"]["tools"].as_array().unwrap();
assert!(tools.iter().any(|t| t["name"] == "create_new_file" && t["annotations"]["readOnlyHint"] == false));
assert_eq!(replies[1]["error"]["code"], -32001, "{}", replies[1]);
let message = replies[1]["error"]["message"].as_str().unwrap();
assert!(message.contains("isn't served in the background"), "{message}");
assert!(h.background().is_empty());
assert_eq!(h.host.projects().len(), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_connection_in_a_folder_no_project_serves_lists_the_tools_and_each_call_names_its_project() {
let h = Harness::new();
// A folder that only holds repositories: one trusted, one not.
let work = h.root.parent().unwrap().join("work");
let (inventory, ledger) = (work.join("inventory"), work.join("ledger"));
for project in [&inventory, &ledger] {
std::fs::create_dir_all(project.join("src")).unwrap();
}
std::fs::write(inventory.join("src/stock.txt"), "forty crates\n").unwrap();
h.set("enabled", json!(true));
h.set("backgroundProjects", json!("listed"));
h.set("backgroundProjectPaths", json!([inventory, ledger]));
h.host.set_project_trust(&inventory, true, false).await.unwrap();
let (_server, discovery) = h.server();
let requests =
[rpc(1, "initialize", json!({})), rpc(2, "tools/list", json!({})), rpc(3, "openidea/servesFolder", json!({}))];
let replies = bridged(&discovery, &work, &requests).await;
let instructions = replies[0]["result"]["instructions"].as_str().unwrap();
assert!(instructions.contains("no project of its own: pass `projectPath`"), "{instructions}");
let tools = replies[1]["result"]["tools"].as_array().unwrap();
assert!(tools.iter().any(|t| t["name"] == "create_new_file" && t["annotations"]["readOnlyHint"] == false));
assert_eq!(replies[2]["result"], json!({ "root": null }), "{}", replies[2]);
assert!(h.background().is_empty(), "initialize, tools/list and servesFolder open nothing");
// A tool that writes is refused for the untrusted project before it loads; a call that
// names no project is refused too.
let create = rpc(
4,
"tools/call",
json!({"name":"create_new_file","arguments":{
"projectPath":ledger,"pathInProject":"notes.txt","text":"no"}}),
);
let unnamed = rpc(5, "tools/call", json!({"name":"read_file","arguments":{"file_path":"src/stock.txt"}}));
let replies = bridged(&discovery, &work, &[create, unnamed]).await;
assert_eq!(replies[0]["result"]["isError"], true, "{}", replies[0]);
let refused = replies[0]["result"]["content"][0]["text"].as_str().unwrap();
assert!(refused.contains("Restricted Mode"), "{refused}");
assert!(!ledger.join("notes.txt").exists());
assert_eq!(replies[1]["error"]["code"], -32001, "{}", replies[1]);
assert!(h.background().is_empty(), "refusals open nothing");
// Inside a served project, servesFolder names it, and loads nothing either.
let serves = [rpc(7, "openidea/servesFolder", json!({}))];
let replies = bridged(&discovery, &inventory.join("src"), &serves).await;
assert_eq!(replies[0]["result"], json!({ "root": inventory }), "{}", replies[0]);
assert!(h.background().is_empty());
let read = rpc(
6,
"tools/call",
json!({"name":"read_file","arguments":{
"projectPath":inventory,"file_path":"src/stock.txt"}}),
);
let replies = bridged(&discovery, &work, &[read]).await;
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: forty crates\nL2: ", "{replies:?}");
assert_eq!(h.background(), std::slice::from_ref(&inventory));
// A remote window's root is that host's to serve.
let remote = work.join("remote");
std::fs::create_dir_all(&remote).unwrap();
h.host.mcp_reports.set_remote("remote", remote.clone());
let replies = bridged(&discovery, &remote, &serves).await;
assert_eq!(replies[0]["result"], json!({ "root": null }), "{}", replies[0]);
h.host.close_project_detached("remote");
}
#[tokio::test(flavor = "multi_thread")]
async fn the_tools_of_a_background_project_are_the_same_before_and_after_it_opens() {
let h = Harness::new();
@@ -1596,14 +1737,15 @@ async fn post(server: &ide_mcp::McpServer, body: &Value) -> Value {
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_open_in_a_window_answers_before_any_background_project() {
async fn a_project_open_in_a_window_answers_for_its_folders_that_no_nested_project_holds() {
let h = Harness::new();
let inventory = h.serve_inventory();
// A listed folder inside the open project: the window's project answers for it.
h.set("backgroundProjectPaths", json!([inventory, h.root.join("src")]));
// A listed folder around the open project leaves the project's folders to its window.
let around = h.root.parent().unwrap().to_path_buf();
h.set("backgroundProjectPaths", json!([inventory, around]));
let (server, discovery) = h.server();
let inside = json!({"projectPath": h.root.join("src"), "file_path": "src/b.txt"});
let read = rpc(1, "tools/call", json!({"name":"read_file","arguments":inside.clone()}));
let read = rpc(1, "tools/call", json!({"name":"read_file","arguments":inside}));
let replies = bridged(&discovery, &inventory, &[read]).await;
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: needle\nL2: ", "{replies:?}");
assert!(h.background().is_empty());
@@ -1614,13 +1756,13 @@ async fn a_project_open_in_a_window_answers_before_any_background_project() {
let unnamed = rpc(2, "tools/call", json!({"name":"read_file","arguments":{"file_path":"src/b.txt"}}));
let reply = post(&server, &unnamed).await;
assert_eq!(reply["result"]["content"][0]["text"], "L1: needle\nL2: ", "{reply}");
// Nor does a background project loaded inside the window's project take its folder over.
// A folder listed inside the window's project is a project of its own (#7040).
let nested = h.root.join("src");
h.call_at(&nested, "read_file", json!({"file_path":"b.txt"})).await.unwrap();
assert_eq!(h.background(), [inventory.clone(), nested]);
let read = rpc(3, "tools/call", json!({"name":"read_file","arguments":inside}));
h.set("backgroundProjectPaths", json!([inventory, around, nested]));
let read = rpc(3, "tools/call", json!({"name":"read_file","arguments":{"projectPath":nested,"file_path":"b.txt"}}));
let replies = bridged(&discovery, &inventory, &[read]).await;
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: needle\nL2: ", "{replies:?}");
assert_eq!(h.background(), [inventory.clone(), nested]);
// A second window on another root is served as before.
let second = h.root.parent().unwrap().join("second");
std::fs::create_dir_all(&second).unwrap();
@@ -1631,6 +1773,61 @@ async fn a_project_open_in_a_window_answers_before_any_background_project() {
assert_eq!(h.background().len(), 2);
}
/// The layout of #7040: `marker.txt` in the window's project and in `contracts`, a trusted
/// repository inside it that trusted mode serves in the background.
#[tokio::test(flavor = "multi_thread")]
async fn a_nested_trusted_project_answers_for_its_folders_whether_or_not_a_window_is_open_around_it() {
let h = Harness::new();
std::fs::write(h.root.join("marker.txt"), "from packages").unwrap();
let contracts = h.root.join("contracts");
std::fs::create_dir_all(contracts.join(".git")).unwrap();
std::fs::create_dir_all(contracts.join("src")).unwrap();
std::fs::write(contracts.join("marker.txt"), "from contracts").unwrap();
std::fs::write(contracts.join("src/only.txt"), "only in contracts").unwrap();
h.trust().await;
h.host.trust.decide(&contracts, true, false).unwrap();
h.set("enabled", json!(true));
h.set("backgroundProjects", json!("trusted"));
let (server, discovery) = h.server();
let read = |file: &str| {
let arguments = json!({"projectPath": contracts, "file_path": file});
rpc(1, "tools/call", json!({"name":"read_file","arguments":arguments}))
};
let text = |reply: Value| reply["result"]["content"][0]["text"].as_str().map(str::to_owned).ok_or(reply);
h.host.close_project("main");
assert_eq!(text(post(&server, &read("marker.txt")).await), Ok("L1: from contracts".to_owned()));
// A window opens on the folder around it between two calls.
h.host.open_project("main", &h.root).unwrap();
assert_eq!(text(post(&server, &read("marker.txt")).await), Ok("L1: from contracts".to_owned()));
assert_eq!(text(post(&server, &read("src/only.txt")).await), Ok("L1: only in contracts".to_owned()));
let roots = rpc(2, "tools/call", json!({"name":"get_workspace_roots","arguments":{"projectPath":contracts}}));
let roots = post(&server, &roots).await;
assert_eq!(roots["result"]["structuredContent"]["projectRoot"], json!(contracts), "{roots}");
// The stdio bridge started in the nested project reaches it too.
let unnamed = rpc(3, "tools/call", json!({"name":"read_file","arguments":{"file_path":"marker.txt"}}));
let replies = bridged(&discovery, &contracts.join("src"), &[unnamed]).await;
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: from contracts", "{replies:?}");
assert_eq!(h.background(), std::slice::from_ref(&contracts));
// A folder of the window's project that no nested project holds stays with the window.
let outside = json!({"projectPath": h.root.join("src"), "file_path": "marker.txt"});
let reply = post(&server, &rpc(4, "tools/call", json!({"name":"read_file","arguments":outside}))).await;
assert_eq!(text(reply), Ok("L1: from packages".to_owned()));
assert_eq!(h.background(), std::slice::from_ref(&contracts), "it loads nothing");
// A remote window's project at the same path keeps its folders, the nested one included:
// they are that host's.
h.host.close_project("main");
h.host.mcp_reports.set_remote("remote", h.root.clone());
let reply = post(&server, &read("marker.txt")).await;
assert_eq!(
reply["result"]["content"][0]["text"],
"project is on a remote host; connect to the MCP server on that host"
);
h.host.close_project_detached("remote");
}
#[tokio::test(flavor = "multi_thread")]
async fn tools_fed_by_a_window_say_that_a_background_project_has_none() {
let h = Harness::new();
@@ -1657,31 +1854,215 @@ async fn tools_fed_by_a_window_say_that_a_background_project_has_none() {
}
#[tokio::test(flavor = "multi_thread")]
async fn tools_that_ask_the_user_fail_closed_in_a_background_project() {
async fn tools_that_need_a_window_refuse_in_a_background_project_before_asking() {
let h = Harness::new();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
let inventory = h.serve_inventory();
h.host.trust.decide(&inventory, true, false).unwrap();
for (tool, args) in [
("build_project", json!({})),
("run_command", json!({"name":"check","command":"true"})),
("open_file_in_editor", json!({"filePath":"src/stock.txt"})),
] {
let error = h.call_at(&inventory, tool, args).await.unwrap_err();
assert!(error.contains("no project window"), "{tool}: {error}");
let root = inventory.display();
// Running without confirmation does not give them a window either.
for brave in [false, true] {
h.set("runWithoutConfirmation", json!(brave));
for (tool, args) in [
("run_command", json!({"name":"check","command":"true"})),
("open_file_in_editor", json!({"filePath":"src/stock.txt"})),
("xdebug_start_debugger_session", json!({"filePath":"src/stock.txt","line":1})),
("xdebug_set_breakpoint", json!({"filePath":"src/stock.txt","line":1})),
("xdebug_remove_breakpoint", json!({})),
("xdebug_list_breakpoints", json!({})),
] {
let error = h.call_at(&inventory, tool, args).await.unwrap_err();
assert_eq!(
error,
format!("{tool} needs the project open in a window: {root} is served in the background.")
);
}
}
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
assert!(h.host.processes.list().is_empty());
// Running without confirmation does not give `run_command` or the editor a window.
h.set("runWithoutConfirmation", json!(true));
for (tool, args) in [
("run_command", json!({"name":"check","command":"true"})),
("open_file_in_editor", json!({"filePath":"src/stock.txt"})),
] {
let error = h.call_at(&inventory, tool, args).await.unwrap_err();
assert!(error.contains("no project window"), "{tool}: {error}");
}
assert_eq!(h.background(), [inventory]);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_background_project_asks_in_the_most_recently_focused_project_window() {
let h = Harness::new();
h.trust().await;
let second = h.open_second();
h.host.set_project_trust(&second, true, false).await.unwrap();
let inventory = h.serve_inventory();
h.host.trust.decide(&inventory, true, false).unwrap();
let error = h.call_at(&inventory, "build_project", json!({})).await.unwrap_err();
assert!(error.contains("no project window is available"), "{error}");
for window in ["main", "second"] {
h.host.mcp_requests.set_ready(window, true);
}
h.focus("second");
h.focus("main");
let denied = h.call_at(&inventory, "build_project", json!({}));
let deny = async {
let (id, request) = h.request_in("main").await;
let McpUiRequest::Confirm { background, project, .. } = request else { panic!("{request:?}") };
assert!(background);
assert_eq!(project, ide_core::ipc_path::to_ipc(&inventory));
assert!(h.shown("second").is_empty());
assert!(h.host.mcp_requests.answer("second", id, true, None).is_err());
h.host.mcp_requests.answer("main", id, false, None).unwrap();
};
let (error, ()) = tokio::join!(denied, deny);
assert!(error.unwrap_err().contains("denied by the user"));
assert!(h.host.processes.list().is_empty());
// Allowed there, a configuration runs on its own, as without a window under brave mode.
ide_run::save_user_configs(&inventory, &[windowless_config()]).unwrap();
let run =
h.call_at(&inventory, "execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000}));
let allow = async {
let (id, request) = h.request_in("main").await;
assert!(matches!(request, McpUiRequest::Confirm { background: true, .. }), "{request:?}");
h.host.mcp_requests.answer("main", id, true, None).unwrap();
};
let (result, ()) = tokio::join!(run, allow);
let result: Value = serde_json::from_str(&result.unwrap()).unwrap();
assert_eq!(result["exitCode"], 3, "{result}");
assert!(result["output"].as_str().unwrap().contains("windowless"));
std::fs::write(inventory.join("api.http"), "### Health\nGET http://127.0.0.1:9/health\n").unwrap();
let denied = h.call_at(&inventory, "http_run_request", json!({"path":"api.http","index":0}));
let deny = async {
let (id, request) = h.request_in("main").await;
assert!(matches!(request, McpUiRequest::Confirm { background: true, .. }), "{request:?}");
h.host.mcp_requests.answer("main", id, false, None).unwrap();
};
let (error, ()) = tokio::join!(denied, deny);
assert!(error.unwrap_err().contains("denied by the user"));
assert!(h.shown("second").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn requests_for_two_background_projects_queue_in_one_window() {
let h = Harness::new();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
let inventory = h.serve_inventory();
let ledger = h.root.parent().unwrap().join("ledger");
std::fs::create_dir_all(&ledger).unwrap();
h.set("backgroundProjectPaths", json!([inventory, ledger]));
for root in [&inventory, &ledger] {
h.host.trust.decide(root, true, false).unwrap();
}
let first = h.call_at(&inventory, "build_project", json!({}));
let second = h.call_at(&ledger, "build_project", json!({}));
let deny = async {
let shown = h.shown_in("main", 2).await;
let mut projects: Vec<_> = shown
.iter()
.map(|(_, request)| match request {
McpUiRequest::Confirm { project, background: true, .. } => PathBuf::from(project),
other => panic!("{other:?}"),
})
.collect();
projects.sort();
assert_eq!(projects, [inventory.clone(), ledger.clone()]);
for (id, _) in shown {
h.host.mcp_requests.answer("main", id, false, None).unwrap();
}
};
let (first, second, ()) = tokio::join!(first, second, deny);
for error in [first.unwrap_err(), second.unwrap_err()] {
assert!(error.contains("denied by the user"), "{error}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_request_moves_when_its_window_closes_and_fails_when_none_is_left() {
let h = Harness::new();
h.trust().await;
let second = h.open_second();
h.host.set_project_trust(&second, true, false).await.unwrap();
let inventory = h.serve_inventory();
h.host.trust.decide(&inventory, true, false).unwrap();
for window in ["second", "main"] {
h.host.mcp_requests.set_ready(window, true);
h.focus(window);
}
let denied = h.call_at(&inventory, "build_project", json!({}));
let moves = async {
let (id, _) = h.request_in("main").await;
h.host.close_project_detached("main");
let (moved, _) = h.request_in("second").await;
assert_eq!(moved, id);
assert!(h.closed_in("main", id));
h.host.mcp_requests.answer("second", id, false, None).unwrap();
};
let (error, ()) = tokio::join!(denied, moves);
assert!(error.unwrap_err().contains("denied by the user"));
let closed = h.call_at(&inventory, "build_project", json!({}));
let close = async {
let (id, _) = h.request_in("second").await;
h.host.close_project_detached("second");
id
};
let (error, id) = tokio::join!(closed, close);
assert!(error.unwrap_err().contains("project window closed"));
assert!(h.closed_in("second", id));
}
#[tokio::test(flavor = "multi_thread")]
async fn a_request_leaves_the_window_when_its_project_unloads_or_the_call_is_cancelled() {
let h = Harness::new();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
let inventory = h.serve_inventory();
h.host.trust.decide(&inventory, true, false).unwrap();
let unloaded = h.call_at(&inventory, "build_project", json!({}));
let unload = async {
let (id, _) = h.request_in("main").await;
assert!(h.host.mcp_background.detach(&h.host, &inventory, None));
id
};
let (error, id) = tokio::join!(unloaded, unload);
assert!(error.unwrap_err().contains("project window closed"));
assert!(h.closed_in("main", id));
let (host, root, cancel) = (h.host.clone(), inventory.clone(), CancellationToken::new());
let token = cancel.clone();
let cancelled = tokio::task::spawn_blocking(move || Registry::new(host).call(&root, "build_project", "{}", token));
let (id, _) = h.request_in("main").await;
cancel.cancel();
assert!(cancelled.await.unwrap().is_err());
assert!(h.closed_in("main", id));
assert!(h.shown("main").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn an_untrusted_window_never_shows_a_background_request() {
let h = Harness::new();
h.trust().await;
let second = h.open_second();
let inventory = h.serve_inventory();
h.host.trust.decide(&inventory, true, false).unwrap();
// `second` is untrusted and focused last; its ready mark is a stale one.
for window in ["main", "second"] {
h.host.mcp_requests.set_ready(window, true);
h.focus(window);
}
let call = h.call_at(&inventory, "build_project", json!({}));
let moves = async {
let (id, _) = h.request_in("main").await;
assert!(h.shown("second").is_empty());
h.host.set_project_trust(&second, true, false).await.unwrap();
h.host.set_project_trust(&h.root, false, false).await.unwrap();
let (moved, _) = h.request_in("second").await;
assert_eq!(moved, id);
assert!(h.closed_in("main", id));
h.host.set_project_trust(&second, false, false).await.unwrap();
};
let (error, ()) = tokio::join!(call, moves);
assert!(error.unwrap_err().contains("project window closed"));
}
#[tokio::test(flavor = "multi_thread")]
async fn a_cancelled_or_failed_call_leaves_nothing_holding_the_project() {
let h = Harness::new();
@@ -1787,7 +2168,7 @@ fn debugger_window(h: &Harness) {
tokio::spawn(async move {
let mut handled = std::collections::HashSet::new();
loop {
let request = events.lock().unwrap().iter().find_map(|e| match e {
let request = events.lock().unwrap().iter().find_map(|(_, e)| match e {
IdeEvent::McpRequest { id, request }
if !handled.contains(id)
&& matches!(
+69 -10
Переглянути файл
@@ -70,6 +70,20 @@ impl Harness {
fn run(&self, id: &str, arg: Option<&str>) -> ide_core::IdeResult<Option<String>> {
self.plugins.run_command(ID, id, arg, self.invocation())
}
/// The folder `inventory` next to the project, listed to be served without a window.
fn serve_inventory(&self) -> PathBuf {
let inventory = self.root.parent().unwrap().join("inventory");
std::fs::create_dir(&inventory).unwrap();
for (key, value) in [
("enabled", serde_json::json!(true)),
("backgroundProjects", serde_json::json!("listed")),
("backgroundProjectPaths", serde_json::json!([inventory])),
] {
let key = format!("mcpServer.{key}");
self.host.global_settings.set(ide_workspace::SettingsScope::Global, &key, value).unwrap();
}
inventory
}
fn source(&self) -> String {
serde_json::json!({"id":"local","name":"Example","driver":"sqlite","database":self.root.join("db.sqlite").to_string_lossy(),"options":[]}).to_string()
}
@@ -189,21 +203,66 @@ async fn mcp_listing_dispatch_confirmation_and_lifecycle_use_plugin_authority()
assert!(spin.await.unwrap().is_err(), "command budget interrupts wasm");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_destructive_plugin_tool_of_a_background_project_asks_in_a_project_window() {
let f = Harness::with_timeout(Duration::from_secs(10));
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let inventory = f.serve_inventory();
f.host.trust.decide(&inventory, true, false).unwrap();
f.host.mcp_requests.set_ready("main", true);
let (registry, root) = (Registry::new(f.host.clone()), inventory.clone());
let call = tokio::task::spawn_blocking(move || {
registry.call(&root, "test_data_tools__erase", "{}", CancellationToken::new())
});
let (window, id, background) = tokio::time::timeout(Duration::from_secs(5), async {
loop {
if let Some(found) = f.events.lock().unwrap().iter().find_map(|(w, e)| match e {
IdeEvent::McpRequest { id, request: McpUiRequest::Confirm { background, .. } } => {
Some((w.clone(), *id, *background))
}
_ => None,
}) {
break found;
}
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert_eq!((window.as_str(), background), ("main", true));
f.host.mcp_requests.answer("main", id, false, None).unwrap();
let denied = call.await.unwrap().unwrap_err();
assert!(format!("{denied:?}").contains("denied by the user"), "{denied:?}");
f.host.close_project(&ide_host::mcp::BackgroundProjects::key(&inventory));
}
#[tokio::test(flavor = "multi_thread")]
async fn plugin_tools_take_the_project_path_and_refuse_an_untrusted_project_before_it_loads() {
let f = Harness::with_timeout(Duration::from_secs(10));
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let inventory = f.serve_inventory();
let registry = Registry::new(f.host.clone());
// A connection without a project of its own lists the tool with `projectPath`, which its
// calls have to pass, and the plugin's strict schema still takes the call.
let listed = registry.tools_without_project();
let echo = listed.iter().find(|t| t.name == "test_data_tools__echo").unwrap();
assert!(echo.input_schema["properties"]["projectPath"].is_object(), "{}", echo.input_schema);
let arguments = serde_json::json!({ "text": "hello", "projectPath": f.root }).to_string();
let result = registry.call(&f.root, "test_data_tools__echo", &arguments, CancellationToken::new()).unwrap();
assert!(result.contains("hello"), "{result}");
// A tool that writes refuses the untrusted folder, and nothing loads.
let refused = registry.call(&inventory, "test_data_tools__write", "{}", CancellationToken::new()).unwrap_err();
let restricted = "Project is in Restricted Mode. Trust the project to enable execution.";
assert_eq!(refused, ToolCallError::Failed(restricted.into()));
assert!(f.host.mcp_background.snapshot(&f.host, std::time::Instant::now()).is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn a_plugin_tool_call_holds_its_background_project_until_it_ends() {
use ide_host::mcp::{BackgroundProjects, McpBackgroundHold};
// The fixture's `spin` runs until it is cancelled or its budget ends.
let f = Harness::with_timeout(Duration::from_secs(10));
let inventory = f.root.parent().unwrap().join("inventory");
std::fs::create_dir(&inventory).unwrap();
for (key, value) in [
("enabled", serde_json::json!(true)),
("backgroundProjects", serde_json::json!("listed")),
("backgroundProjectPaths", serde_json::json!([inventory])),
] {
let key = format!("mcpServer.{key}");
f.host.global_settings.set(ide_workspace::SettingsScope::Global, &key, value).unwrap();
}
let inventory = f.serve_inventory();
let held_by = || {
let loaded = f.host.mcp_background.snapshot(&f.host, std::time::Instant::now());
loaded.into_iter().next().map(|project| project.kept_open_by)
+39
Переглянути файл
@@ -1590,6 +1590,28 @@ fn misbehave_with_language(dir: &Path) -> PathBuf {
pkg
}
/// A language activation fired before the plugin was there (a remote server gets the desktop's
/// packages after the window opened its files; a plugin installed with such a file open)
/// activates it once it loads; one that never fired doesn't.
#[test]
fn plugins_loaded_after_their_activation_event_fired_activate() {
use ide_extension::ActivationEvent;
let tmp = tempfile::tempdir().unwrap();
let host = Arc::new(
PluginHost::new(tmp.path().join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(),
);
host.load_all();
host.startup_finished();
host.activation_event(&ActivationEvent::Language("other".into()), None);
host.install_from_dir(&misbehave_with_language(tmp.path()), &Consent::all()).unwrap();
assert_eq!(host.info_of("misbehave").unwrap().status, PluginStatus::Inactive);
host.uninstall("misbehave").unwrap();
host.activation_event(&ActivationEvent::Language("mis".into()), None);
host.install_from_dir(&misbehave_with_language(tmp.path()), &Consent::all()).unwrap();
assert!(eventually(|| host.info_of("misbehave").is_ok_and(|i| i.status == PluginStatus::Active)));
}
/// Edit-path calls stop waiting at the soft deadline (the result is
/// dropped, the instance kept) and are interrupted at the hard one.
#[test]
@@ -8148,3 +8170,20 @@ fn contributes_skills_needs_api_1_15_and_warns_without_failing_plugin_on_bad_ent
assert_eq!(dirs.len(), 1);
assert!(dirs[0].ends_with("skills/good-skill"), "{dirs:?}");
}
#[test]
fn restricting_a_project_without_its_plugins_announces_nothing() {
let tmp = tempfile::tempdir().unwrap();
let events: Events = Arc::default();
let sink = {
let events = events.clone();
move |client: Option<&str>, e: PluginEvent| events.lock().push((client.map(str::to_owned), e))
};
let host = PluginHost::new(tmp.path().join("plugins"), Arc::new(sink), Limits::default()).unwrap();
host.load_all();
events.lock().clear();
// A restricted window lists the plugins, which restricts its project again each time.
host.restrict_project(tmp.path());
host.restrict_project(tmp.path());
assert!(!events.lock().iter().any(|(_, e)| matches!(e, PluginEvent::CommandsChanged)));
}
+50 -1
Переглянути файл
@@ -28,6 +28,10 @@ struct Fixture {
impl Fixture {
async fn new() -> Self {
Self::with_sink(Arc::new(ide_core::NullSink)).await
}
async fn with_sink(sink: ide_core::SharedSink) -> Self {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
@@ -40,7 +44,8 @@ impl Fixture {
std::fs::write(root.join("file.txt"), "original\n").unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-m", "original"]);
let host = Host::new(common::host_config(&base));
let host =
Host::new(ide_host::HostConfig { sink_for: Box::new(move |_| sink.clone()), ..common::host_config(&base) });
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
wait_for_repos(&project, 1).await;
@@ -278,6 +283,50 @@ async fn watcher_picks_up_a_worktree_added_below_the_project() {
assert!(roots.contains(&linked), "watcher did not discover the worktree added below the project: {roots:?}");
}
/// `git worktree add` writes the worktree's gitfile before its gitdir's `commondir` and `HEAD`; a
/// slow git lets the watcher rescan in between and find no repository there yet.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn watcher_picks_up_a_worktree_whose_head_is_written_after_a_rescan() {
let changes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let counter = changes.clone();
let sink: ide_core::SharedSink = Arc::new(move |event: ide_core::IdeEvent| {
if matches!(event, ide_core::IdeEvent::VcsChanged { .. }) {
counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
});
let f = Fixture::with_sink(sink).await;
// The watcher reports a batch that rescans only once the rescan is done.
let next_change = || {
let (changes, seen) = (changes.clone(), changes.load(std::sync::atomic::Ordering::SeqCst));
async move {
for _ in 0..200 {
if changes.load(std::sync::atomic::Ordering::SeqCst) > seen {
return;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
panic!("the watcher reported no change");
}
};
let linked = f.root.join("watched");
let gitdir = f.root.join(".git/worktrees/watched");
let registered = next_change();
std::fs::create_dir_all(&gitdir).unwrap();
std::fs::write(gitdir.join("gitdir"), format!("{}\n", linked.join(".git").display())).unwrap();
registered.await;
let rescanned = next_change();
std::fs::create_dir_all(&linked).unwrap();
std::fs::write(linked.join(".git"), format!("gitdir: {}\n", gitdir.display())).unwrap();
rescanned.await;
assert_eq!(f.project.repos().all().len(), 1, "a gitfile without its gitdir's HEAD is no repository yet");
std::fs::write(gitdir.join("commondir"), "../..\n").unwrap();
// As git does: through a lock file.
std::fs::write(gitdir.join("HEAD.lock"), "ref: refs/heads/main\n").unwrap();
std::fs::rename(gitdir.join("HEAD.lock"), gitdir.join("HEAD")).unwrap();
wait_for_repos(&f.project, 2).await;
assert!(f.project.repos().roots().contains(&linked));
}
impl Fixture {
async fn open(&self, root: &std::path::Path) {
self.host.trust.decide(root, true, false).unwrap();
+157 -17
Переглянути файл
@@ -2,7 +2,8 @@
//! speak (a WebSocket): direct, or through an HTTP proxy's `CONNECT` tunnel.
use base64::Engine;
use ide_core::proxy_settings::ProxyRoute;
use hyper_util::client::proxy::matcher::Matcher;
use ide_core::proxy_settings::{ProxyRoute, ProxySettings};
use ide_core::{IdeError, IdeResult};
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@@ -10,32 +11,84 @@ use tokio::net::TcpStream;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
/// The PAC lookup of the system proxy settings; none outside macOS.
#[cfg(target_os = "macos")]
const SYSTEM_PAC: fn(&str) -> Option<ProxyRoute> = crate::system_pac_route;
#[cfg(not(target_os = "macos"))]
const SYSTEM_PAC: fn(&str) -> Option<ProxyRoute> = |_| None;
/// A connection to `url`'s host and port, through the proxy System Settings › HTTP Proxy
/// (or, in Auto mode, the system) routes that host to.
pub async fn connect(url: &reqwest::Url) -> IdeResult<TcpStream> {
let route = ide_core::proxy_settings::proxy().route(url.host_str());
connect_with(url, route, SYSTEM_PAC, Matcher::from_system, false).await
}
/// [`connect`] under explicit proxy `settings`; a proxy the tunnel cannot speak to (SOCKS) is skipped and
/// the connection goes direct, as it did before the proxy was consulted at all.
pub async fn connect_best_effort(url: &reqwest::Url, settings: &ProxySettings) -> IdeResult<TcpStream> {
connect_with(url, settings.route(url.host_str()), SYSTEM_PAC, Matcher::from_system, true).await
}
/// `host:port`; `host_str` already brackets an IPv6 address (the same rule as `pac.rs`'s `authority`).
fn authority(host: &str, port: u16) -> String {
if host.contains(':') && !host.starts_with('[') { format!("[{host}]:{port}") } else { format!("{host}:{port}") }
}
/// The URI the system proxy settings are asked about: the scheme reqwest would use (`ws` → `http`).
fn system_uri(url: &reqwest::Url) -> IdeResult<http::Uri> {
let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?;
let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?;
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
let proxy = match ide_core::proxy_settings::proxy().route(Some(host)) {
let target = authority(host, port);
let scheme = if url.scheme() == "wss" || url.scheme() == "https" { "https" } else { "http" };
format!("{scheme}://{target}/").parse().map_err(|_| IdeError::invalid("invalid host"))
}
/// `connect` with the proxy settings' `route`, the PAC lookup and the system matcher injected;
/// `skip_unusable` sends a route the tunnel cannot speak to direct instead of failing.
async fn connect_with(
url: &reqwest::Url,
route: ProxyRoute,
pac: impl FnOnce(&str) -> Option<ProxyRoute> + Send + 'static,
matcher: impl FnOnce() -> Matcher,
skip_unusable: bool,
) -> IdeResult<TcpStream> {
let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?;
let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?;
let target = authority(host, port);
let proxy = match route {
ProxyRoute::Direct => None,
ProxyRoute::Via(via) => Some(via),
ProxyRoute::System => {
// The system proxy of the scheme reqwest would use (`ws` → `http`).
let scheme = if url.scheme() == "wss" || url.scheme() == "https" { "https" } else { "http" };
let uri: http::Uri =
format!("{scheme}://{target}/").parse().map_err(|_| IdeError::invalid("invalid host"))?;
hyper_util::client::proxy::matcher::Matcher::from_system().intercept(&uri).map(|intercept| {
let auth =
intercept.raw_auth().map(|(user, password)| format!("{user}:{password}@")).unwrap_or_default();
let uri = intercept.uri();
format!(
"{}://{auth}{}",
uri.scheme_str().unwrap_or("http"),
uri.authority().map(|a| a.as_str()).unwrap_or_default()
)
})
let uri = system_uri(url)?;
// On macOS the resolver may run the PAC script (`dnsResolve`), so it stays off the async threads. A
// script still loading answers with the matcher's route.
let probe = uri.to_string();
#[cfg(target_os = "macos")]
let pac = tokio::task::spawn_blocking(move || pac(&probe))
.await
.map_err(|error| IdeError::unavailable(format!("proxy lookup failed: {error}")))?;
// Nothing to evaluate outside macOS: no hop to the blocking pool.
#[cfg(not(target_os = "macos"))]
let pac = pac(&probe);
match pac {
Some(ProxyRoute::Via(via)) if via.starts_with("http://") => Some(via),
Some(ProxyRoute::Direct) => None,
// No PAC applies, or it names a proxy this tunnel cannot speak to (SOCKS): the matcher's route.
_ => matcher().intercept(&uri).map(|intercept| {
let auth =
intercept.raw_auth().map(|(user, password)| format!("{user}:{password}@")).unwrap_or_default();
let uri = intercept.uri();
format!(
"{}://{auth}{}",
uri.scheme_str().unwrap_or("http"),
uri.authority().map(|a| a.as_str()).unwrap_or_default()
)
}),
}
}
};
let proxy = proxy.filter(|proxy| !skip_unusable || proxy.starts_with("http://"));
let connecting = async {
let Some(proxy) = proxy else {
return TcpStream::connect(&target).await.map_err(|error| reach(&target, &error));
@@ -157,6 +210,93 @@ mod tests {
assert!(error.message.contains("needs a login"), "{}", error.message);
}
use std::sync::{Arc, Mutex};
fn matcher_via(address: &str) -> impl FnOnce() -> Matcher {
let address = address.to_owned();
move || Matcher::builder().all(format!("http://{address}")).build()
}
/// The CONNECT line a proxy was asked for, or `None` when nothing connected within a moment.
async fn asked(task: tokio::task::JoinHandle<String>) -> Option<String> {
tokio::time::timeout(Duration::from_millis(300), task).await.ok().map(|head| head.unwrap())
}
#[tokio::test]
async fn the_pac_route_wins_over_the_matcher_and_ws_is_looked_up_as_http() {
let (pac_proxy, pac_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
let seen = Arc::new(Mutex::new(String::new()));
let recorded = Arc::clone(&seen);
let pac = move |probe: &str| {
*recorded.lock().unwrap() = probe.to_owned();
Some(ProxyRoute::Via(format!("http://{pac_proxy}")))
};
let url = reqwest::Url::parse("ws://pac-target.invalid:8080/s").unwrap();
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy), false).await.unwrap();
assert_eq!(*seen.lock().unwrap(), "http://pac-target.invalid:8080/");
assert!(asked(pac_asked).await.unwrap().starts_with("CONNECT pac-target.invalid:8080 HTTP/1.1\r\n"));
assert_eq!(asked(matcher_asked).await, None, "the matcher's proxy must not be used");
}
#[tokio::test]
async fn wss_is_looked_up_as_https() {
let (pac_proxy, _) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
let seen = Arc::new(Mutex::new(String::new()));
let recorded = Arc::clone(&seen);
let pac = move |probe: &str| {
*recorded.lock().unwrap() = probe.to_owned();
Some(ProxyRoute::Via(format!("http://{pac_proxy}")))
};
let url = reqwest::Url::parse("wss://pac-target.invalid/s").unwrap();
connect_with(&url, ProxyRoute::System, pac, || Matcher::builder().build(), false).await.unwrap();
assert_eq!(*seen.lock().unwrap(), "https://pac-target.invalid:443/");
}
#[tokio::test]
async fn a_resolved_direct_route_skips_the_matchers_proxy() {
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap();
connect_with(&url, ProxyRoute::System, |_| Some(ProxyRoute::Direct), matcher_via(&matcher_proxy), false)
.await
.unwrap();
tokio::time::timeout(Duration::from_millis(300), listener.accept())
.await
.expect("no direct connection")
.unwrap();
assert_eq!(asked(matcher_asked).await, None, "the matcher's proxy must not be used");
}
#[tokio::test]
async fn a_socks_pac_route_keeps_the_matchers_route() {
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
let url = reqwest::Url::parse("ws://pac-target.invalid:8080/s").unwrap();
let pac = |_: &str| Some(ProxyRoute::Via("socks5h://127.0.0.1:1080".into()));
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy), false).await.unwrap();
assert!(asked(matcher_asked).await.unwrap().starts_with("CONNECT pac-target.invalid:8080 HTTP/1.1\r\n"));
}
#[tokio::test]
async fn an_unusable_proxy_is_skipped_only_when_asked() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap();
let socks = || ProxyRoute::Via("socks5h://127.0.0.1:1".into());
let none = || Matcher::builder().build();
assert!(connect_with(&url, socks(), |_| None, none, false).await.unwrap_err().message.contains("socks5h"));
connect_with(&url, socks(), |_| None, none, true).await.unwrap();
listener.accept().await.unwrap();
}
#[tokio::test]
async fn an_ipv6_literal_is_connected_to() {
let Ok(listener) = TcpListener::bind("[::1]:0").await else { return }; // no IPv6 loopback here
let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap();
connect_with(&url, ProxyRoute::Direct, |_| None, || Matcher::builder().build(), false).await.unwrap();
listener.accept().await.unwrap();
assert_eq!(authority("[::1]", 9), "[::1]:9");
}
#[test]
fn proxy_credentials_are_percent_decoded() {
assert_eq!(percent_decode("a%40b%3Ac"), "a@b:c");
+1
Переглянути файл
@@ -32,6 +32,7 @@ tree-sitter-java = "0.23.5"
tree-sitter-kotlin-ng = "1.1.0"
tree-sitter-c = "0.24.2"
tree-sitter-cpp = "0.23.4"
tree-sitter-objc = "3.0.2"
tree-sitter-c-sharp = "0.23.5"
tree-sitter-ruby = "0.23.1"
tree-sitter-php = "0.25.1"
+50
Переглянути файл
@@ -0,0 +1,50 @@
(class_interface . (identifier) @name category: (identifier) @detail) @def.extension
(class_implementation . (identifier) @name category: (identifier) @detail) @def.extension
(class_interface . (identifier) @name) @def.class
(class_implementation . (identifier) @name) @def.class
(protocol_declaration . (identifier) @name) @def.interface
(method_declaration ["+" "-"] @detail [(identifier) @name (method_parameter)]+) @def.method
(method_definition ["+" "-"] @detail [(identifier) @name (method_parameter)]+) @def.method
(property_declaration (struct_declaration (struct_declarator [
(identifier) @name
(pointer_declarator declarator: (identifier) @name)
(function_declarator declarator: (parenthesized_declarator (block_pointer_declarator declarator: (identifier) @name)))
]))) @def.property
(instance_variable (struct_declaration (struct_declarator [
(identifier) @name
(pointer_declarator declarator: (identifier) @name)
]))) @def.field
(preproc_call directive: (preproc_directive) @_d argument: (preproc_arg) @name
(#eq? @_d "#pragma") (#match? @name "^mark\\s")) @outline.heading
(function_definition
declarator: [
(function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail)
(pointer_declarator declarator: (function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail))
(pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail)))
]) @def.function
(translation_unit (declaration
declarator: [
(function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail)
(pointer_declarator declarator: (function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail))
]) @def.function)
(struct_specifier name: (type_identifier) @name body: (field_declaration_list)) @def.struct
(union_specifier name: (type_identifier) @name body: (field_declaration_list)) @def.struct
(enum_specifier name: (type_identifier) @name body: (enumerator_list)) @def.enum
(enumerator name: (identifier) @name) @def.enum_member
(field_declaration_list (field_declaration declarator: [
(field_identifier) @name
(pointer_declarator declarator: (field_identifier) @name)
(array_declarator declarator: (field_identifier) @name)
]) @def.field)
(type_definition declarator: (type_identifier) @name) @def.type
(preproc_def name: (identifier) @name) @def.macro
(preproc_function_def name: (identifier) @name parameters: (preproc_params) @detail) @def.macro
(translation_unit (declaration declarator: [
(identifier) @name
(init_declarator declarator: (identifier) @name)
(init_declarator declarator: (pointer_declarator declarator: (identifier) @name))
]) @def.variable)
+4
Переглянути файл
@@ -227,6 +227,10 @@ pub struct LanguageServerConfig {
/// it parses a document.
#[serde(default)]
pub resync_on_configuration: bool,
/// Server-created work-done tokens to ignore, including slash-delimited suffixes.
/// Client-created request tokens are handled independently.
#[serde(default)]
pub ignored_progress_token_prefixes: Vec<String>,
/// Set by the settings hook: what the user sees as the server when another program serves
/// in its place (TypeScript 7's own `tsc --lsp` for vtsls).
#[serde(skip)]
+11 -1
Переглянути файл
@@ -90,6 +90,7 @@ const BUILTIN: &[(&str, &str)] = &[
("slint", include_str!("../../../languages/slint.toml")),
("sql", include_str!("../../../languages/sql.toml")),
("svelte", include_str!("../../../languages/svelte.toml")),
("strings", include_str!("../../../languages/strings.toml")),
("swift", include_str!("../../../languages/swift.toml")),
("terraform", include_str!("../../../languages/terraform.toml")),
("terraform-vars", include_str!("../../../languages/terraform-vars.toml")),
@@ -98,6 +99,7 @@ const BUILTIN: &[(&str, &str)] = &[
("typescriptreact", include_str!("../../../languages/typescriptreact.toml")),
("typst", include_str!("../../../languages/typst.toml")),
("vue", include_str!("../../../languages/vue.toml")),
("xcconfig", include_str!("../../../languages/xcconfig.toml")),
("xml", include_str!("../../../languages/xml.toml")),
("yaml", include_str!("../../../languages/yaml.toml")),
("zig", include_str!("../../../languages/zig.toml")),
@@ -907,7 +909,10 @@ mod tests {
let cfg = reg.get(&LanguageId::new("php")).unwrap();
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
// After the fallback: hover, rename and symbols stay with Intelephense.
assert_eq!(names, ["intelephense", "phpactor", "phoxite", "devsense-php-ls", "laravel-lsp"]);
assert_eq!(names, ["intelephense", "phpantom", "phpactor", "phoxite", "devsense-php-ls", "laravel-lsp"]);
let phpantom = &cfg.language_servers[1];
assert!(phpantom.fallback && phpantom.args.is_empty());
assert_eq!(phpantom.command, "phpantom_lsp");
// Phoxite answers the Laravel strings itself.
let phoxite = cfg.language_servers.iter().find(|s| s.name == "phoxite").unwrap();
assert!(phoxite.fallback && phoxite.replaces == ["laravel-lsp"]);
@@ -1277,6 +1282,11 @@ mod tests {
("P.cs", "csharp"),
("V.swift", "swift"),
("AppDelegate.m", "objective-c"),
("App.entitlements", "xml"),
("PrivacyInfo.xcprivacy", "xml"),
("Localizable.xcstrings", "json"),
("Debug.xcconfig", "xcconfig"),
("en.lproj/Localizable.strings", "strings"),
("a.rb", "ruby"),
("Gemfile", "ruby"),
("show.html.erb", "erb"),
+18
Переглянути файл
@@ -156,6 +156,24 @@ pub(crate) static SPECS: &[Spec] = &[
imports: &["preproc_include", "using_declaration"],
constructors: NONE,
},
Spec {
name: "objc",
language: tree_sitter_objc::LANGUAGE,
outline: outline!("objc"),
highlights: None,
// `@interface` / `@implementation` / `@protocol` ... `@end` have no brackets.
fold_nodes: &[
"class_interface",
"class_implementation",
"protocol_declaration",
"preproc_if",
"preproc_ifdef",
"preproc_function_def",
],
fold_bodies: NONE,
imports: &["preproc_include", "module_import"],
constructors: NONE,
},
Spec {
name: "csharp",
language: tree_sitter_c_sharp::LANGUAGE,
+11 -1
Переглянути файл
@@ -180,7 +180,11 @@ fn collect(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) -> Vec<Built>
}
names.sort_by_key(|n| n.start_byte());
names.dedup_by_key(|n| n.id());
let base = names.iter().map(|n| name_text(n, text)).collect::<Vec<_>>().join(".");
let mut base = names.iter().map(|n| name_text(n, text)).collect::<Vec<_>>().join(".");
// Objective-C selectors: `- (id)initWithName:(id)n age:(int)a` is `initWithName:age:`.
if g.spec.name == "objc" && node.children(&mut node.walk()).any(|c| c.kind() == "method_parameter") {
base = names.iter().map(|n| format!("{}:", name_text(n, text))).collect();
}
if base.is_empty() {
continue;
}
@@ -539,6 +543,12 @@ fn name_text(n: &Node, text: &str) -> String {
let t = node_text(n, text);
// Ruby / Elixir symbols: `:total` -> `total`.
let t = if matches!(n.kind(), "simple_symbol" | "atom") { t.trim_start_matches(':') } else { t };
// Objective-C `#pragma mark - Lifecycle` -> `Lifecycle` (a bare `mark -` is a separator, so empty).
let t = if n.kind() == "preproc_arg" {
t.trim().trim_start_matches("mark").trim_start().trim_start_matches('-')
} else {
t
};
clean(t, 120)
}
+113
Переглянути файл
@@ -546,6 +546,119 @@ int main() { return 0; }
assert_eq!(t.iter().filter(|(n, k, _)| n == "draw" && *k == SymbolKind::Method).count(), 2);
}
#[test]
fn outline_objc() {
let src = r#"#import <Foundation/Foundation.h>
#define MAX 10
@protocol Greeting <NSObject>
- (NSString *)greet;
@optional
@property (nonatomic) int level;
@end
@interface Person : NSObject <Greeting> {
int _age;
}
@property (nonatomic, copy) NSString *name;
+ (instancetype)personWithName:(NSString *)name age:(int)age;
- (void)run;
@end
@interface Person (Extra)
- (void)extra;
@end
@implementation Person
#pragma mark - Lifecycle
+ (instancetype)personWithName:(NSString *)name age:(int)age {
return nil;
}
- (void)run {
}
@end
static int helper(int x) { return x; }
"#;
check_outline(
"objective-c",
src,
"
Macro MAX
Interface Greeting
Method greet
Property level
Class Person
Field _age
Property name
Method personWithName:age:
Method run
Namespace Person
Method extra
Class Person
Key Lifecycle
Method personWithName:age:
Method run
Function helper
",
);
let t = tags("objective-c", src);
assert!(has_tag(&t, "greet", SymbolKind::Method, Some("Greeting")));
assert!(has_tag(&t, "personWithName:age:", SymbolKind::Method, Some("Person")));
assert!(has_tag(&t, "extra", SymbolKind::Method, Some("Person")));
assert!(has_tag(&t, "name", SymbolKind::Property, Some("Person")));
assert!(!t.iter().any(|(n, _, _)| n == "Lifecycle"));
let t = tags("objective-c", "@interface A\n@property (copy) void (^onTap)(int i);\n@end\n");
assert!(has_tag(&t, "onTap", SymbolKind::Property, Some("A")), "{t:?}");
// `@interface` / `@protocol` / `@implementation` ... `@end` fold like a braced body.
let f = folds("objective-c", src);
for range in [(2, 6), (8, 14), (16, 18), (20, 27), (22, 24)] {
assert!(f.contains(&(range.0, range.1, FoldKind::Region)), "{range:?} not in {f:?}");
}
}
#[test]
fn outline_objective_cpp_keeps_the_objc_structure() {
// C++ declarations outside the ObjC blocks are lost to error recovery; the ObjC
// classes and methods, which are why a file is `.mm`, stay.
check_outline(
"objective-cpp",
r#"#import "Bridge.h"
#include <vector>
#include <string>
namespace engine {
class Renderer {
public:
void draw(const std::vector<int> &xs);
};
}
@implementation Bridge {
std::unique_ptr<engine::Renderer> _renderer;
}
- (instancetype)init {
self = [super init];
_renderer = std::make_unique<engine::Renderer>();
return self;
}
- (void)drawValues:(NSArray<NSNumber *> *)values {
std::vector<int> xs;
for (NSNumber *n in values) { xs.push_back(n.intValue); }
_renderer->draw(xs);
}
@end
static std::string helper() { return "x"; }
"#,
"
Class Bridge
Method init
Method drawValues:
Function helper
",
);
}
#[test]
fn outline_csharp() {
check_outline(
+1
Переглянути файл
@@ -73,6 +73,7 @@ fn server_config() -> LanguageServerConfig {
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
}
+17
Переглянути файл
@@ -151,6 +151,23 @@ impl ClientHandler {
}
fn progress(&self, mgr: &LspManager, params: Value) {
if let Some(token) = params["token"].as_str() {
if let Some(id) = token.strip_prefix(crate::server::REQUEST_PROGRESS_PREFIX) {
if let (Ok(id), Ok(update)) = (id.parse::<u32>(), serde_json::from_value(params["value"].clone())) {
self.server.request_progress(mgr.sink(), TaskId(id), update);
}
return;
}
if self
.server
.config
.ignored_progress_token_prefixes
.iter()
.any(|prefix| token.strip_prefix(prefix).is_some_and(|rest| rest.is_empty() || rest.starts_with('/')))
{
return;
}
}
let token = progress_key(&params["token"]);
let value = &params["value"];
let kind = value.get("kind").and_then(Value::as_str);
+65 -2
Переглянути файл
@@ -122,10 +122,24 @@ pub fn configure_project_structure(
// JDT resolves relative library globs against its own root, which may be a submodule.
Some(root.join(trimmed).to_string_lossy().replace('\\', "/"))
};
let normalize_class = |entry: &str| -> Option<String> {
let trimmed = entry.trim();
if trimmed.is_empty() {
return None;
}
let resolved = root.join(trimmed);
let path = resolved.to_string_lossy().replace('\\', "/");
// A directory library root (e.g. `WebRoot/WEB-INF/lib`) needs a `**/*.jar` glob so jdtls
// indexes the JAR archives inside it rather than ignoring the bare folder path.
if resolved.is_dir() && !ide_core::settings::jar_files(&resolved, true).is_empty() {
return Some(format!("{}/**/*.jar", path.trim_end_matches('/')));
}
Some(path)
};
let mut include: Vec<String> = Vec::new();
let mut sources = serde_json::Map::new();
for lib in &structure.libraries {
let class_entries: Vec<String> = lib.classes.iter().filter_map(|c| normalize(c)).collect();
let class_entries: Vec<String> = lib.classes.iter().filter_map(|c| normalize_class(c)).collect();
let source_entries: Vec<String> = lib.sources.iter().filter_map(|s| normalize(s)).collect();
for c in &class_entries {
if !include.contains(c) {
@@ -133,7 +147,9 @@ pub fn configure_project_structure(
}
}
for (class, source) in class_entries.iter().zip(&source_entries) {
sources.insert(class.clone(), json!(source));
if !class.contains('*') {
sources.insert(class.clone(), json!(source));
}
}
}
for facet in &structure.facets {
@@ -1953,4 +1969,51 @@ mod tests {
configure_project_structure(&mut cfg, tmp.path(), tmp.path(), &structure);
assert!(cfg.launch_error.as_deref().unwrap().contains("inside its module"));
}
#[test]
fn directory_library_root_expands_to_recursive_jar_glob_for_jdtls() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let web_lib = root.join("WebRoot/WEB-INF/lib");
std::fs::create_dir_all(&web_lib).unwrap();
std::fs::write(web_lib.join("gson.jar"), b"").unwrap();
let structure = ide_core::settings::ProjectStructureSettings {
libraries: vec![ide_core::settings::ProjectLibrary {
name: "lib".into(),
classes: vec!["WebRoot/WEB-INF/lib".into()],
sources: vec![],
javadocs: vec![],
scope: ide_core::settings::DependencyScope::Runtime,
}],
..Default::default()
};
let mut cfg: ide_language::LanguageServerConfig = toml::from_str("name = 'jdtls'\ncommand = 'jdtls'").unwrap();
configure_project_structure(&mut cfg, root, root, &structure);
let include = cfg
.settings
.as_ref()
.unwrap()
.pointer("/java/project/referencedLibraries/include")
.and_then(Value::as_array)
.unwrap();
let expected = format!("{}/**/*.jar", web_lib.to_string_lossy().replace('\\', "/"));
assert!(include.contains(&json!(expected)), "include={include:?}");
// A class folder without jars stays a plain path.
let classes = root.join("classes");
std::fs::create_dir_all(&classes).unwrap();
let structure = ide_core::settings::ProjectStructureSettings {
libraries: vec![ide_core::settings::ProjectLibrary {
name: "classes".into(),
classes: vec!["classes".into()],
..Default::default()
}],
..Default::default()
};
let mut cfg: ide_language::LanguageServerConfig = toml::from_str("name = 'jdtls'\ncommand = 'jdtls'").unwrap();
configure_project_structure(&mut cfg, root, root, &structure);
let include = cfg.settings.as_ref().unwrap().pointer("/java/project/referencedLibraries/include").cloned();
assert!(!format!("{include:?}").contains("classes/**"), "include={include:?}");
}
}
+86 -3
Переглянути файл
@@ -58,7 +58,7 @@ pub use jdtls::stream_trace::JdtStreamTracer;
pub use kotlin_lsp::{KotlinDebugServer, KotlinDebugUnavailable};
pub use launch::{LaunchError, Launcher, ProcessLauncher};
pub use message_requests::answer as answer_message_request;
pub use notebook::{NotebookCell, NotebookCellDoc, cell_uri};
pub use notebook::{NotebookCell, NotebookCellDoc, NotebookCellText, cell_uri};
pub use plugin_requests::plugin_method_allowed;
pub use scope::{CandidateFiles, CandidateFn, CandidateQuery, MAX_CANDIDATES};
pub use uri::{path_to_uri_string, uri_target, uri_to_path};
@@ -1598,10 +1598,20 @@ impl LspManager {
cancel: Option<&CancellationToken>,
timeout: Duration,
) -> IdeResult<R> {
let params = serde_json::to_value(params).map_err(|e| IdeError::internal(e.to_string()))?;
let mut params = serde_json::to_value(params).map_err(|e| IdeError::internal(e.to_string()))?;
// ImplementationParams accepts an optional client work-done token. Servers
// may report on it even when implementationProvider is advertised as `true`.
let progress = (method == "textDocument/implementation")
.then(|| t.server.track_request_progress(t.run.generation, self.sink(), cancel));
let cancel = if let Some(progress) = &progress {
params["workDoneToken"] = json!(progress.wire_token());
Some(progress.cancel.clone())
} else {
cancel.cloned()
};
let stamp = self.injected_request_stamp(&params);
let fut = async {
let mut value = t.run.peer.request::<Value, Value>(method, params, cancel.cloned()).await?;
let mut value = t.run.peer.request::<Value, Value>(method, params, cancel).await?;
virtual_doc::normalize_uris(&mut value);
serde_json::from_value(value).map_err(|e| RpcError::Protocol(format!("{method}: {e}")))
};
@@ -2811,6 +2821,79 @@ impl LspManager {
Ok(ts_file_moves::file_references(&result))
}
/// Runs vtsls' own `command` for `doc`. typescript-language-server, TypeScript 7 and the
/// Vue / Astro servers have none of these commands: they need vtsls.
async fn vtsls_command(
&self,
doc: DocId,
command: &str,
arguments: impl FnOnce(&DocSnap, &Target) -> Option<Value>,
cancel: Option<&CancellationToken>,
) -> IdeResult<(Target, Value)> {
let snap = self.snapshot(doc)?;
let t = self
.ready_targets(&snap.servers, |c| c.commands().iter().any(|c| c == command))
.await
.into_iter()
.find(|t| t.server.name == "vtsls")
.ok_or_else(|| IdeError::unavailable("This needs the vtsls TypeScript language server"))?;
let arguments =
arguments(&snap, &t).ok_or_else(|| IdeError::invalid(format!("invalid `{command}` arguments")))?;
let params = json!({ "command": command, "arguments": arguments });
let result = self.call(&t, "workspace/executeCommand", params, cancel, LONG_TIMEOUT).await?;
Ok((t, result))
}
/// Go to Source Definition: the JavaScript implementation of what `pos` refers to, not its
/// `.d.ts` declaration (vtsls' `typescript.goToSourceDefinition`).
pub async fn source_definition(&self, doc: DocId, pos: Pos, cancel: CancellationToken) -> IdeResult<Vec<Location>> {
let (t, result) = self
.vtsls_command(
doc,
"typescript.goToSourceDefinition",
|snap, t| Some(json!([snap.uri, snap.position(t, pos)])),
Some(&cancel),
)
.await?;
let locs: Vec<lsp::Location> = serde_json::from_value::<Option<_>>(result)
.map_err(|e| IdeError::internal(format!("typescript.goToSourceDefinition: {e}")))?
.unwrap_or_default();
let conv = self.conv(t.enc());
Ok(locs.iter().filter_map(|l| conv.location(l)).collect())
}
/// Opens the `tsconfig.json` / `jsconfig.json` of `doc`'s project, or the TS Server log:
/// vtsls answers with `window/showDocument` (or a message when there is none).
pub async fn open_typescript_file(&self, doc: DocId, what: TypeScriptFile) -> IdeResult<()> {
let (command, with_uri) = match what {
TypeScriptFile::ProjectConfig => {
let snap = self.snapshot(doc)?;
let js = snap.language.as_str().starts_with("javascript");
(if js { "javascript.goToProjectConfig" } else { "typescript.goToProjectConfig" }, true)
}
TypeScriptFile::ServerLog => ("typescript.openTsServerLog", false),
};
self.vtsls_command(doc, command, |snap, _| Some(if with_uri { json!([snap.uri]) } else { json!([]) }), None)
.await?;
Ok(())
}
/// The files tsserver suggests for vtsls' Move to File `command` (from a code action).
pub async fn move_to_file_targets(
&self,
doc: DocId,
command: Command,
cancel: CancellationToken,
) -> IdeResult<Vec<PathBuf>> {
let snap = self.snapshot(doc)?;
let request = ts_file_moves::move_to_file_suggestions_request(&snap.path, &command.arguments)
.ok_or_else(|| IdeError::invalid("invalid Move to File command"))?;
let (_, result) = self
.vtsls_command(doc, ts_file_moves::COMMAND, |_, _| request.get("arguments").cloned(), Some(&cancel))
.await?;
Ok(ts_file_moves::move_to_file_suggestions(&result))
}
/// Whether a server of `doc` (`server`, when given) provides the command `name`. Code actions
/// can carry commands other editors' extensions run themselves after the edit (vtsls'
/// `_typescript.didOrganizeImports`): no server provides those.
+47
Переглянути файл
@@ -40,6 +40,14 @@ pub struct NotebookCellDoc {
pub uri: String,
}
/// A cell document's buffer, as the notebook service keeps it.
pub struct NotebookCellText {
pub path: std::path::PathBuf,
pub language: LanguageId,
pub text: String,
pub version: u32,
}
pub(crate) struct NotebookState {
uri: lsp::Uri,
language: LanguageId,
@@ -154,6 +162,22 @@ impl LspManager {
.collect()
}
/// A cell document's buffer, for work that runs without asking a server — formatting reads
/// it from `documents`, which only holds files the editor opened, never a notebook's cells.
pub fn cell_text(&self, doc: DocId) -> Option<NotebookCellText> {
let docs = self.docs.lock();
let d = docs.get(&doc)?;
// The notebook file, not the cell's own `vscode-notebook-cell:` uri: a formatter
// looks the file up to find the project's settings and the language of the file.
let path = d.notebook.clone()?;
Some(NotebookCellText {
path,
language: d.language.clone(),
text: d.text.as_str().to_owned(),
version: d.version.max(0) as u32,
})
}
/// Opens the notebooks of `server`'s language on its instance that just became ready.
pub(crate) fn reopen_notebooks(&self, server: &Arc<Server>, run: &Running) {
let mut pull = Vec::new();
@@ -384,4 +408,27 @@ mod tests {
assert!(is_cell_uri(&uri) && parse_uri(&uri).is_some());
assert!(!is_cell_uri("file:///a.ipynb") && !is_cell_uri("vscode-notebook-cellx:/a"));
}
/// A cell lives in `docs` only, never in `documents`; formatting asks for its buffer here.
#[test]
fn cell_text_answers_for_a_cell_document_and_nothing_else() {
let manager = LspManager::new(
PathBuf::from("/work"),
std::sync::Arc::new(crate::LanguageRegistry::load(None).unwrap()),
std::sync::Arc::new(|_: ide_core::IdeEvent| {}),
);
let path = PathBuf::from("/work/a.ipynb");
let cells = [NotebookCell { id: "cell-a".into(), source: "x=1".into() }];
manager.sync_notebook(&path, &LanguageId::new("python"), &cells);
let doc = manager.notebook_cells(&path)[0].doc;
let text = manager.cell_text(doc).expect("a cell document answers");
assert_eq!(text.text, "x=1");
// The notebook file, so a formatter finds the project's settings for it.
assert_eq!(text.path, path);
assert_eq!(text.language.as_str(), "python");
// A document the notebook service does not know stays unknown.
assert!(manager.cell_text(DocId(9999)).is_none());
}
}
+107
Переглянути файл
@@ -53,10 +53,58 @@ struct State {
generation: u64,
conn: Conn,
restarting: bool,
request_progress: HashMap<TaskId, RequestProgressState>,
events: VecDeque<IdeEvent>,
publishing: bool,
}
pub(crate) const REQUEST_PROGRESS_PREFIX: &str = "openidea/request/";
struct RequestProgressState {
title: Option<String>,
message: Option<String>,
fraction: Option<f32>,
_cancel: ide_core::task::CancelHandle,
}
impl RequestProgressState {
fn event(&self, id: TaskId, done: bool) -> Option<IdeEvent> {
Some(IdeEvent::Task {
id,
title: self.title.clone()?,
message: self.message.clone(),
fraction: self.fraction,
done,
cancellable: !done,
})
}
}
/// Progress provided to an LSP request. Dropping the request always retires its token.
pub(crate) struct RequestProgress<'a> {
id: TaskId,
server: &'a Server,
sink: &'a SharedSink,
pub(crate) cancel: CancellationToken,
}
impl RequestProgress<'_> {
pub(crate) fn wire_token(&self) -> String {
format!("{REQUEST_PROGRESS_PREFIX}{}", self.id.0)
}
}
impl Drop for RequestProgress<'_> {
fn drop(&mut self) {
let mut st = self.server.state.lock();
if let Some(progress) = st.request_progress.remove(&self.id) {
st.events.extend(progress.event(self.id, true));
}
drop(st);
self.server.publish(self.sink);
}
}
/// A file opened on the server by the client itself (not by the user) for the
/// duration of a request, e.g. to widen a references search.
struct Transient {
@@ -172,6 +220,7 @@ impl Server {
generation: 0,
conn: Conn::Idle,
restarting: false,
request_progress: HashMap::new(),
events: VecDeque::new(),
publishing: false,
}),
@@ -552,6 +601,9 @@ impl Server {
fn queue_cleanup(&self, st: &mut State) {
*self.initializing.lock() = None;
for (id, progress) in st.request_progress.drain() {
st.events.extend(progress.event(id, true));
}
for (id, title) in self.take_progress() {
st.events.push_back(IdeEvent::Task {
id,
@@ -572,6 +624,61 @@ impl Server {
}
}
pub(crate) fn track_request_progress<'a>(
&'a self,
generation: u64,
sink: &'a SharedSink,
parent_cancel: Option<&CancellationToken>,
) -> RequestProgress<'a> {
let id = TaskId::next();
let cancel = parent_cancel.map(CancellationToken::child_token).unwrap_or_default();
let mut st = self.state.lock();
if st.generation == generation && matches!(st.conn, Conn::Ready(_)) {
let token = cancel.clone();
st.request_progress.insert(
id,
RequestProgressState {
title: None,
message: None,
fraction: None,
_cancel: ide_core::task::on_cancel(id, move || token.cancel()),
},
);
}
RequestProgress { id, server: self, sink, cancel }
}
pub(crate) fn request_progress(&self, sink: &SharedSink, id: TaskId, update: lsp::WorkDoneProgress) {
let mut st = self.state.lock();
let Some(progress) = st.request_progress.get_mut(&id) else { return };
let fraction = |p: u32| p.min(100) as f32 / 100.0;
let event = match update {
lsp::WorkDoneProgress::Begin(begin) => {
progress.title = Some(begin.title);
progress.message = begin.message;
progress.fraction = begin.percentage.map(fraction);
progress.event(id, false)
}
lsp::WorkDoneProgress::Report(report) => {
progress.message = report.message.or_else(|| progress.message.take());
progress.fraction = report.percentage.map(fraction).or(progress.fraction);
progress.event(id, false)
}
lsp::WorkDoneProgress::End(end) => {
progress.message = end.message.or_else(|| progress.message.take());
progress.fraction = Some(1.0);
let event = progress.event(id, true);
st.request_progress.remove(&id);
event
}
};
// Queue under the state lock so a reply or cancellation can't publish `done`
// before a concurrent progress update and leave a stale row.
st.events.extend(event);
drop(st);
self.publish(sink);
}
pub fn emit(&self, sink: &SharedSink, event: IdeEvent) {
self.state.lock().events.push_back(event);
self.publish(sink);
+46
Переглянути файл
@@ -87,10 +87,56 @@ pub(crate) fn file_references(result: &Value) -> Vec<ide_core::Location> {
.collect()
}
/// The `typescript.tsserverRequest` arguments asking where the selection of vtsls' Move to File
/// command (`_typescript.moveToFileRefactoring` with `[action, uri, range]`, run with the target
/// file appended) can go.
pub(crate) fn move_to_file_suggestions_request(file: &std::path::Path, arguments: &[Value]) -> Option<Value> {
let range: lsp_types::Range = serde_json::from_value(arguments.get(2)?.clone()).ok()?;
// tsserver: 1-based lines and UTF-16 offsets; vtsls speaks UTF-16.
Some(json!({
"command": COMMAND,
"arguments": ["getMoveToRefactoringFileSuggestions", {
"file": file,
"startLine": range.start.line + 1,
"startOffset": range.start.character + 1,
"endLine": range.end.line + 1,
"endOffset": range.end.character + 1,
}],
}))
}
/// The files tsserver suggests in its `getMoveToRefactoringFileSuggestions` answer.
pub(crate) fn move_to_file_suggestions(result: &Value) -> Vec<PathBuf> {
let body = result.get("body").unwrap_or(result);
serde_json::from_value(body.get("files").cloned().unwrap_or_default()).unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn asks_tsserver_where_the_move_to_file_selection_can_go() {
let action = json!({ "name": "Move to file", "kind": "refactor.move.file" });
let range = json!({ "start": { "line": 6, "character": 16 }, "end": { "line": 8, "character": 1 } });
let request = move_to_file_suggestions_request(
std::path::Path::new("/p/src/util.ts"),
&[action.clone(), json!("file:///p/src/util.ts"), range],
)
.unwrap();
assert_eq!(
request["arguments"],
json!(["getMoveToRefactoringFileSuggestions", {
"file": "/p/src/util.ts", "startLine": 7, "startOffset": 17, "endLine": 9, "endOffset": 2,
}])
);
assert!(move_to_file_suggestions_request(std::path::Path::new("/p/a.ts"), &[action]).is_none());
let answer =
json!({ "success": true, "body": { "newFileName": "/p/src/greet.ts", "files": ["/p/src/app.ts"] } });
assert_eq!(move_to_file_suggestions(&answer), vec![PathBuf::from("/p/src/app.ts")]);
assert!(move_to_file_suggestions(&json!({ "success": false })).is_empty());
}
#[test]
fn converts_tsserver_file_references() {
let result = json!({ "success": true, "body": { "symbolName": "\"./Hello.vue\"", "refs": [
+8
Переглянути файл
@@ -109,6 +109,14 @@ pub struct Signature {
pub parameters: Vec<(u32, u32)>,
}
/// A file vtsls opens for a document: its project's configuration or the TS Server log.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum TypeScriptFile {
ProjectConfig,
ServerLog,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum GotoKind {
+209
Переглянути файл
@@ -277,6 +277,7 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
}
@@ -2225,6 +2226,54 @@ async fn a_progress_token_begun_again_ends_the_task_it_replaces() {
h.wait_status("mock", ServerStatus::Ready).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn toml_progress_quirk_ignores_server_tokens_left_open_after_cancel() {
let registry = LanguageRegistry::load(None).unwrap();
let php = registry.get(&LanguageId::new("php")).unwrap();
let quirk = &php.language_servers.iter().find(|s| s.name == "phpantom").unwrap().ignored_progress_token_prefixes;
let h = harness_configured("php", "php", &[("mock", incremental_caps())], |cfg| {
cfg.ignored_progress_token_prefixes = quirk.clone();
});
let (doc, path) = h.open("a.php", "<?php target();");
h.wait_status("mock", ServerStatus::Ready).await;
let server = h.launcher.state("mock");
let peer = server.peer();
let progress = |token, kind, title| {
peer.notify("$/progress", json!({ "token": token, "value": { "kind": kind, "title": title } })).unwrap();
};
let method = "textDocument/references";
let search = || h.mgr.references_streaming(doc, Pos::new(0, 7), true, false, true, Default::default(), None);
progress("find_references/1", "begin", "Find References");
progress("find_references", "begin", "Find References");
progress("goto_implementation/1", "begin", "Go to Implementation");
progress("find_references_index/1", "begin", "Indexing");
h.wait_status("mock", ServerStatus::Busy).await;
server.errors.lock().insert(method.into(), (-32800, "Canceled".into()));
assert_eq!(search().await.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
server.errors.lock().remove(method);
server.respond(
method,
json!([{
"uri": uri_of(&path),
"range": { "start": { "line": 0, "character": 6 }, "end": { "line": 0, "character": 12 } }
}]),
);
progress("find_references/2", "begin", "Find References");
assert_eq!(search().await.unwrap().locations.len(), 1);
progress("find_references/2", "end", "Find References");
progress("find_references_index/1", "end", "Indexing");
h.wait_status("mock", ServerStatus::Ready).await;
let events = h.events.lock();
assert!(!events.iter().any(
|e| matches!(e, IdeEvent::Task { title, .. } if title == "Find References" || title == "Go to Implementation")
));
assert!(events.iter().any(|e| matches!(e, IdeEvent::Task { title, done: false, .. } if title == "Indexing")));
assert!(events.iter().any(|e| matches!(e, IdeEvent::Task { title, done: true, .. } if title == "Indexing")));
}
#[tokio::test(flavor = "multi_thread")]
async fn replacing_progress_keeps_cancellation_reports_and_indexing_on_the_new_task() {
let h = harness(&[("mock", incremental_caps())]);
@@ -4239,6 +4288,118 @@ async fn implementations_per_position() {
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
}
#[tokio::test]
async fn implementation_progress_ends_on_cancel_without_server_end() {
implementation_progress_ends_with_request(false).await;
}
#[tokio::test]
async fn implementation_progress_ends_on_timeout_without_server_end() {
implementation_progress_ends_with_request(true).await;
}
async fn implementation_progress_ends_with_request(timeout: bool) {
let caps = json!({ "textDocumentSync": 1, "implementationProvider": true });
let h = harness_for("php", "php", &[("mock", caps)], &[]);
let (doc, path) = h.open("a.php", "<?php\ninterface A {}\nclass B implements A {}\n");
h.wait_status("mock", ServerStatus::Ready).await;
let server = h.launcher.state("mock");
let method = "textDocument/implementation";
let gate = Arc::new(Gate::default());
let uri = uri_of(&path);
*server.responder.lock() =
Some(Arc::new({
let gate = gate.clone();
move |server, requested, params| {
if requested != method {
return None;
}
let token = &params["workDoneToken"];
let peer = server.peer();
peer.notify("$/progress", json!({
"token": token, "value": { "kind": "begin", "title": "Go to Implementation", "cancellable": false }
})).unwrap();
if params["position"]["character"] == 10 {
peer.notify(
"$/progress",
json!({
"token": token, "value": { "kind": "report", "percentage": 88 }
}),
)
.unwrap();
gate.hold();
}
// The mock answers without sending `end`.
Some(json!([{
"uri": uri,
"range": { "start": { "line": 2, "character": 6 }, "end": { "line": 2, "character": 7 } }
}]))
}
}));
let mgr = h.mgr.clone();
let batch = tokio::spawn(async move {
mgr.implementations(doc, &[Pos::new(1, 10), Pos::new(2, 6)], Default::default()).await.unwrap()
});
let task_events = || {
h.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::Task { id, title, done, fraction, cancellable, .. } if title == "Go to Implementation" => {
Some((*id, *done, *fraction, *cancellable))
}
_ => None,
})
.collect::<Vec<_>>()
};
eventually(|| {
let events = task_events();
gate.entered() && events.iter().any(|e| e.2 == Some(0.88)) && events.iter().any(|(_, done, _, _)| *done)
})
.await;
let scanning = task_events().into_iter().find(|e| e.2 == Some(0.88)).expect("scan reported 88%");
let (task, _, _, cancellable) = scanning;
assert!(cancellable);
assert!(!task_events().iter().any(|(id, done, _, _)| *id == task && *done));
let requests = server.requested(method);
assert_eq!(requests.len(), 2);
assert_ne!(requests[0]["workDoneToken"], requests[1]["workDoneToken"]);
if timeout {
tokio::time::pause();
tokio::time::advance(Duration::from_secs(31)).await;
tokio::time::resume();
} else {
assert!(ide_core::task::cancel(task));
}
let found = batch.await.unwrap();
gate.open();
eventually(|| !server.notified("$/cancelRequest").is_empty()).await;
assert!(found[0].is_empty());
assert_eq!(found[1][0].range.start.line, 2);
assert!(!ide_core::task::cancel(task));
assert_eq!(task_events().iter().filter(|(id, done, _, _)| *id == task && *done).count(), 1);
// Late progress for either retired token must not bring back its task.
let before = task_events();
let peer = server.peer();
for request in requests {
peer.notify(
"$/progress",
json!({
"token": request["workDoneToken"], "value": { "kind": "begin", "title": "Go to Implementation" }
}),
)
.unwrap();
}
peer.notify("$/progress", json!({ "token": "index", "value": { "kind": "begin", "title": "Indexing" } })).unwrap();
h.wait_status("mock", ServerStatus::Busy).await;
assert_eq!(task_events(), before);
peer.notify("$/progress", json!({ "token": "index", "value": { "kind": "end" } })).unwrap();
h.wait_status("mock", ServerStatus::Ready).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn java_implementations_come_from_sources_first() {
let caps = json!({
@@ -8824,3 +8985,51 @@ async fn switch_source_header_asks_clangd_and_only_clangd() {
assert!(h.launcher.state("mock").requested("textDocument/switchSourceHeader").is_empty());
h.mgr.shutdown_all().await;
}
/// C-family files go to sourcekit-lsp in an Xcode project with a BSP config (`buildServer.json`),
/// which hands them to clangd with the build's flags; elsewhere, and when sourcekit-lsp is missing,
/// to plain clangd. Uses the shipped language definitions.
#[tokio::test(flavor = "multi_thread")]
async fn c_family_files_use_sourcekit_lsp_only_with_an_xcode_bsp_config() {
let registry = LanguageRegistry::load(None).unwrap();
for (language, ext) in [("c", "h"), ("cpp", "cpp"), ("objective-c", "m"), ("objective-cpp", "mm")] {
let shipped = registry.get(&LanguageId::new(language)).unwrap().language_servers;
let names: Vec<_> = shipped.iter().map(|c| c.name.as_str()).collect();
assert_eq!(names, ["sourcekit-lsp", "clangd"], "{language}");
let servers = [("sourcekit-lsp", incremental_caps()), ("clangd", incremental_caps())];
let as_shipped = |cfg: &mut LanguageServerConfig| {
let real = shipped.iter().find(|c| c.name == cfg.name).unwrap();
cfg.root_markers = real.root_markers.clone();
cfg.require_root_marker = real.require_root_marker;
cfg.replaces = real.replaces.clone();
};
let file = format!("Foo.{ext}");
// A plain folder, or one with only compile_commands.json: clangd alone.
let h = harness_configured(language, ext, &servers, as_shipped);
std::fs::write(h.root.join("compile_commands.json"), "[]").unwrap();
h.open(&file, "");
h.wait_status("clangd", ServerStatus::Ready).await;
assert!(h.statuses("sourcekit-lsp").is_empty(), "{language}");
h.mgr.shutdown_all().await;
// An Xcode project with buildServer.json: sourcekit-lsp alone, rooted at the config.
let h = harness_configured(language, ext, &servers, as_shipped);
std::fs::write(h.root.join("buildServer.json"), "{}").unwrap();
let (_, path) = h.open(&file, "");
h.wait_status("sourcekit-lsp", ServerStatus::Ready).await;
eventually(|| h.launcher.state("sourcekit-lsp").docs.lock().contains_key(&uri_of(&path))).await;
assert!(h.statuses("clangd").is_empty(), "{language}");
assert_eq!(h.mgr.servers().iter().map(|s| s.root.clone()).collect::<Vec<_>>(), std::slice::from_ref(&h.root));
h.mgr.shutdown_all().await;
// sourcekit-lsp not installed: clangd still serves.
let h = harness_configured(language, ext, &servers, as_shipped);
h.launcher.state("sourcekit-lsp").missing.store(true, Ordering::SeqCst);
std::fs::write(h.root.join("buildServer.json"), "{}").unwrap();
h.open(&file, "");
h.wait_status("sourcekit-lsp", ServerStatus::Missing).await;
h.wait_status("clangd", ServerStatus::Ready).await;
h.mgr.shutdown_all().await;
}
}
+132
Переглянути файл
@@ -428,6 +428,7 @@ async fn missing_binary_is_reported_with_install_hint() {
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
};
@@ -721,6 +722,7 @@ async fn typescript_language_server_end_to_end() {
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
};
@@ -775,6 +777,7 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
}
@@ -969,6 +972,135 @@ async fn bundler_path_aliases_resolve_below_tsconfig_paths() {
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
/// suggests the project's files and moves a function with its imports in one applied edit. 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_commands_open_sources_configs_logs_and_move_to_file() {
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();
for dir in ["src", "node_modules/greeting"] {
std::fs::create_dir_all(root.join(dir)).unwrap();
}
let files = [
("package.json", "{\"name\":\"app\",\"private\":true}"),
("tsconfig.json", "{\"files\":[],\"references\":[{\"path\":\"./src/tsconfig.app.json\"}]}"),
(
"src/tsconfig.app.json",
"{\"compilerOptions\":{\"strict\":true,\"composite\":true,\"module\":\"ESNext\",\"moduleResolution\":\"Bundler\"},\"include\":[\"./**/*.ts\"]}",
),
(
"node_modules/greeting/package.json",
"{\"name\":\"greeting\",\"main\":\"index.js\",\"types\":\"index.d.ts\"}",
),
("node_modules/greeting/index.d.ts", "export declare function shout(s: string): string;\n"),
("node_modules/greeting/index.js", "export function shout(s) {\n return s.toUpperCase();\n}\n"),
(
"src/main.ts",
"import { shout } from \"greeting\";\nimport { greet, Greeter } from \"./util\";\n\n/** Uses {@link Greeter} to say hello. */\nexport function hello(name: string) {\n return shout(greet(name));\n}\n\nexport const g = new Greeter();\n",
),
(
"src/util.ts",
"export class Greeter {\n greet(name: string) {\n return `Hello, ${name}`;\n }\n}\n\nexport function greet(name: string) {\n return new Greeter().greet(name);\n}\n",
),
("src/strings.ts", "export const upper = (s: string) => s.toUpperCase();\n"),
("src/app.ts", "import { greet } from \"./util\";\n\nconsole.log(greet(\"app\"));\n"),
];
for (path, text) in files {
std::fs::write(root.join(path), text).unwrap();
}
// The IDE's settings hook: Move to File on, a TypeScript 6 lib, the log on.
let init = serde_json::json!({
"vtsls": { "enableMoveToFileCodeAction": true, "autoUseWorkspaceTsdk": true },
"typescript": {
"tsdk": tools.join("node_modules/typescript/lib").to_string_lossy(),
"tsserver": { "log": "verbose" },
},
});
let ts = lang("typescript", "ts", npm_server(&tools, "vtsls", "vtsls", Some(init)));
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![ts]));
let applied: Arc<Mutex<Vec<ide_core::WorkspaceEdit>>> = Arc::default();
mgr.set_apply_edit_hook(Box::new({
let applied = applied.clone();
move |edit| {
applied.lock().push(edit);
true
}
}));
let open = |path: &str| {
let doc = DocId::next();
let file = root.join(path);
mgr.did_open(doc, &file, &LanguageId::new("typescript"), 1, &std::fs::read_to_string(&file).unwrap());
doc
};
let (main, util) = (open("src/main.ts"), open("src/util.ts"));
// `shout`: Go to Declaration is the `.d.ts`, Go to Source Definition the `.js`.
let at = Pos::new(0, 10);
// The syntax server answers with the import itself until the project is loaded.
let dts = |d: &ide_core::Location| d.path.to_string_lossy().ends_with("greeting/index.d.ts");
let declaration = retry("declaration", Duration::from_secs(90), || {
let mgr = mgr.clone();
async move { mgr.goto(main, at, GotoKind::Definition).await.ok().filter(|d| d.iter().any(dts)) }
})
.await;
assert!(declaration.iter().all(dts), "{declaration:?}");
let source = mgr.source_definition(main, at, Default::default()).await.unwrap();
assert_eq!(source.len(), 1, "{source:?}");
assert_eq!(*source[0].path, *root.join("node_modules/greeting/index.js"));
assert_eq!(source[0].range.start, Pos::new(0, 16));
let shown = |events: &Events, suffix: &str| {
events
.lock()
.iter()
.any(|e| matches!(e, IdeEvent::LspShowDocument { path: Some(path), .. } if path.to_string_lossy().ends_with(suffix)))
};
mgr.open_typescript_file(main, ide_lsp::types::TypeScriptFile::ProjectConfig).await.unwrap();
retry("tsconfig.app.json shown", Duration::from_secs(10), || {
let found = shown(&events, "src/tsconfig.app.json").then_some(());
async move { found }
})
.await;
mgr.open_typescript_file(main, ide_lsp::types::TypeScriptFile::ServerLog).await.unwrap();
retry("tsserver.log shown", Duration::from_secs(10), || {
let found = shown(&events, "tsserver.log").then_some(());
async move { found }
})
.await;
let hover = mgr.hover(main, Pos::new(4, 17), Default::default()).await.unwrap();
let hover = format!("{hover:?}");
assert!(hover.contains("src/util.ts#L1%2C1"), "{hover}");
// Move to File on `greet`: tsserver suggests the other files, the move updates the importers.
let caret = Pos::new(6, 16);
let actions = mgr.code_actions(util, Range::new(caret, caret), vec!["refactor.move".into()]).await.unwrap();
let command = actions
.iter()
.find_map(|a| a.command.clone().filter(|c| c.command == "_typescript.moveToFileRefactoring"))
.unwrap_or_else(|| panic!("no Move to File: {actions:?}"));
let targets = mgr.move_to_file_targets(util, command.clone(), Default::default()).await.unwrap();
let strings = root.join("src/strings.ts");
assert!(targets.contains(&strings) && targets.contains(&root.join("src/app.ts")), "{targets:?}");
let mut moving = command;
moving.arguments.push(serde_json::json!(strings));
mgr.execute_command(util, moving).await.unwrap();
let edits = applied.lock().clone();
assert_eq!(edits.len(), 1, "{edits:?}");
let edit = format!("{:?}", edits[0]);
for file in ["src/util.ts", "src/strings.ts", "src/app.ts", "src/main.ts"] {
assert!(edit.contains(&*root.join(file).to_string_lossy()), "{file}: {edit}");
}
assert!(edit.contains("export function greet(name: string)"), "{edit}");
assert!(edit.contains("import { greet } from \\\"./strings\\\""), "{edit}");
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// CSS Modules Kit (`@css-modules-kit/ts-plugin`) on vtsls, which serves the `.module.css`
/// files too (`languages: ["css"]`): definition and completion from TSX, references and rename
/// from the stylesheet (#6071), with the settings hook's own plugin configuration. Exactly the
+15 -4
Переглянути файл
@@ -9,7 +9,11 @@
//! `Origin` or `Host` are refused (DNS rebinding).
//! - **Projects:** the `X-OpenIDEA-Project` header or the `?project=` query
//! names a folder; the server picks the open project containing it, or the
//! project the IDE serves it from without a window.
//! project the IDE serves it from without a window. A connection whose
//! folder no project serves lists the tools a trusted project gets, and each
//! call names its project with `projectPath`. `openidea/servesFolder`
//! answers which project serves the connection's folder (`{"root": null}`
//! for none).
//! - **Discovery:** `<app-data>/mcp/server.json` (`address`, `port`, `token`,
//! `pid`, `version`; readable only by the user) while the server runs.
//! - **Stdio:** `<app exe> --mcp-stdio [--project <path>]` reads the discovery
@@ -67,14 +71,21 @@ pub trait ToolRegistry: Send + Sync + 'static {
/// Roots of the projects open in a window of the IDE that the server serves.
fn projects(&self) -> Vec<PathBuf>;
/// The root of the project the IDE serves `path` from without a window (a background
/// project), asked when no project of [`Self::projects`] contains `path`. Opens nothing:
/// the first call for that root does.
fn resolve(&self, _path: &Path) -> Option<PathBuf> {
/// project). `within` is the root of the innermost project of [`Self::projects`] that
/// contains `path`, when one does: then only a root strictly inside it answers, and the
/// open project keeps the path otherwise. Opens nothing: the first call for that root does.
fn resolve(&self, _path: &Path, _within: Option<&Path>) -> Option<PathBuf> {
None
}
/// The tools callable for `project` (one of [`Self::projects`] or a root
/// [`Self::resolve`] gave). `Err` says why there are none (an unsupported project).
fn tools(&self, project: &Path) -> Result<Vec<Tool>, String>;
/// The tools listed on a connection whose project doesn't resolve (a folder no project
/// serves, or no folder and not exactly one window): those a trusted project gets. Each
/// call still resolves its project and refuses by that project's trust.
fn tools_without_project(&self) -> Vec<Tool> {
Vec::new()
}
fn call_with_client(
&self,
project: &Path,
+66 -22
Переглянути файл
@@ -1,6 +1,6 @@
//! MCP over JSON-RPC 2.0: `initialize`, `ping`, `tools/list`, `tools/call`
//! and notifications, for one POST body (a message or a batch). Blocking: the
//! server runs it on a blocking thread.
//! MCP over JSON-RPC 2.0: `initialize`, `ping`, `tools/list`, `tools/call`,
//! our own `openidea/servesFolder` and notifications, for one POST body (a
//! message or a batch). Blocking: the server runs it on a blocking thread.
use crate::{CancellationToken, Tool, ToolCallError, ToolRegistry};
use serde_json::{Value, json};
@@ -26,16 +26,22 @@ impl Drop for InFlight<'_> {
}
}
/// How long a cancellation that arrived before its call is kept.
const EARLY_CANCELLATION: std::time::Duration = std::time::Duration::from_secs(60);
/// The protocol version answered when the client asks for one this server doesn't know.
pub(crate) const LATEST: &str = "2025-06-18";
pub(crate) const SUPPORTED: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"];
const PARSE_ERROR: i64 = -32700;
const INVALID_REQUEST: i64 = -32600;
const METHOD_NOT_FOUND: i64 = -32601;
pub(crate) const METHOD_NOT_FOUND: i64 = -32601;
const INVALID_PARAMS: i64 = -32602;
/// The requested folder isn't in a project the IDE serves (or has no tools there).
pub(crate) const NOT_OPEN: i64 = -32001;
/// Which project serves the connection's folder: `{"root": "<path>"}`, or `{"root": null}`
/// for none. The stdio bridge asks it to pick the IDE process for its folder.
pub(crate) const SERVES_FOLDER: &str = "openidea/servesFolder";
pub(crate) struct RpcError {
code: i64,
@@ -105,7 +111,12 @@ impl Session<'_> {
let mut state = self.requests.0.lock().unwrap();
if let Some(cancel) = state.running.get(&key) {
cancel.cancel();
} else if state.early.len() < 1024 {
return None;
}
// The stdio bridge sends a cancellation to every server, so one that runs few
// calls drops the stale ones here as well.
state.early.retain(|_, at| at.elapsed() < EARLY_CANCELLATION);
if state.early.len() < 1024 {
state.early.insert(key, std::time::Instant::now());
}
}
@@ -116,7 +127,7 @@ impl Session<'_> {
let cancel = self.cancel.child_token();
{
let mut requests = self.requests.0.lock().unwrap();
requests.early.retain(|_, at| at.elapsed() < std::time::Duration::from_secs(60));
requests.early.retain(|_, at| at.elapsed() < EARLY_CANCELLATION);
if requests.running.contains_key(&key) {
return Some(error_response(id, INVALID_REQUEST, "request id already in flight"));
}
@@ -139,11 +150,18 @@ impl Session<'_> {
"initialize" => Ok(self.initialize(&params)),
"ping" => Ok(json!({})),
"tools/list" => {
let project = self.project()?;
let tools = self.registry.tools(&project).map_err(|e| RpcError::new(NOT_OPEN, e))?;
let tools = match self.project() {
Ok(project) => self.registry.tools(&project).map_err(|e| RpcError::new(NOT_OPEN, e))?,
Err(_) => self.registry.tools_without_project(),
};
Ok(json!({ "tools": tools.iter().map(tool_json).collect::<Vec<_>>() }))
}
"tools/call" => self.call(params, cancel),
SERVES_FOLDER => {
// A root without tools here (a remote window's) is another server's to serve.
let root = self.project().ok().filter(|root| self.registry.tools(root).is_ok());
Ok(json!({ "root": root.map(|root| root.display().to_string()) }))
}
_ => Err(RpcError::new(METHOD_NOT_FOUND, format!("no method {method:?}"))),
}
}
@@ -157,9 +175,13 @@ impl Session<'_> {
}
let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or(LATEST);
let version = if SUPPORTED.contains(&asked) { asked } else { LATEST };
let about = match self.project() {
Ok(root) => format!("the project OpenIDEA serves at {}", root.display()),
Err(_) => "a project open in OpenIDEA or served in the background".to_owned(),
let (about, without_project) = match self.project() {
Ok(root) => (format!("the project OpenIDEA serves at {}", root.display()), ""),
Err(_) => (
"a project open in OpenIDEA or served in the background".to_owned(),
" This connection has no project of its own: pass `projectPath`, a folder inside a project \
OpenIDEA serves, in every call, `get_workspace_roots` included.",
),
};
json!({
"protocolVersion": version,
@@ -174,7 +196,7 @@ impl Session<'_> {
its `roots` are every project in the IDE workspace. That is the scope to search and read, \
not a list of projects to change; it doesn't change your working directory or \
permissions. Pass another root as `projectPath` to reach that project. Call it again \
when the user switches projects or attaches one."
when the user switches projects or attaches one.{without_project}"
),
})
}
@@ -223,9 +245,7 @@ impl Session<'_> {
roots.sort();
roots.dedup();
if let Some(requested) = requested.filter(|p| !p.trim().is_empty()) {
let path = Path::new(requested);
// An open project wins; the registry is asked only for a folder outside all of them.
return resolve(&roots, path).or_else(|| self.registry.resolve(path)).ok_or_else(|| {
return self.serving_root(&roots, Path::new(requested)).ok_or_else(|| {
RpcError::new(
NOT_OPEN,
format!(
@@ -247,10 +267,30 @@ impl Session<'_> {
),
))
}
/// The innermost project containing `path`, whether a window has it open (one of `roots`)
/// or the registry serves it in the background, so the answer doesn't depend on which
/// windows are open. Inside an open project the registry is asked only for a path below
/// its root, about the folders inside that root: a folder of a window's project that no
/// nested project holds loads nothing.
fn serving_root(&self, roots: &[PathBuf], path: &Path) -> Option<PathBuf> {
let Some(open) = resolve(roots, path) else { return self.registry.resolve(path, None) };
let nested = if open.below { self.registry.resolve(path, Some(&open.root)) } else { None };
Some(nested.unwrap_or(open.root))
}
}
/// The innermost open project containing a path.
#[derive(Debug, PartialEq)]
struct OpenRoot {
/// As the registry lists it.
root: PathBuf,
/// Whether the path lies below the root rather than at it.
below: bool,
}
/// The project among `roots` containing `path` (the innermost one).
fn resolve(roots: &[PathBuf], path: &Path) -> Option<PathBuf> {
fn resolve(roots: &[PathBuf], path: &Path) -> Option<OpenRoot> {
if !path.is_absolute() {
return None;
}
@@ -274,7 +314,7 @@ fn resolve(roots: &[PathBuf], path: &Path) -> Option<PathBuf> {
path.starts_with(&canonical).then(|| (canonical.components().count(), root))
})
.max_by_key(|(depth, _)| *depth)
.map(|(_, root)| root.clone())
.map(|(depth, root)| OpenRoot { root: root.clone(), below: path.components().count() > depth })
}
fn tool_json(tool: &Tool) -> Value {
@@ -299,11 +339,15 @@ mod tests {
let inner = outer.join("inner");
std::fs::create_dir_all(inner.join("src")).unwrap();
let roots = [outer.clone(), inner.clone()];
assert_eq!(resolve(&roots, &inner.join("src")), Some(inner.clone()));
assert_eq!(resolve(&roots, &outer.join("other")), Some(outer.clone()));
assert_eq!(resolve(&roots[1..], &outer), None);
assert_eq!(resolve(&roots, Path::new("relative/path")), None);
let root = |roots: &[PathBuf], path: &Path| resolve(roots, path).map(|open| open.root);
assert_eq!(root(&roots, &inner.join("src")), Some(inner.clone()));
assert_eq!(root(&roots, &outer.join("other")), Some(outer.clone()));
assert_eq!(root(&roots[1..], &outer), None);
assert_eq!(root(&roots, Path::new("relative/path")), None);
// Siblings sharing a prefix are not inside.
assert_eq!(resolve(&roots[1..], &outer.join("inner-two")), None);
assert_eq!(root(&roots[1..], &outer.join("inner-two")), None);
// Only a path below the root is below it.
assert_eq!(resolve(&roots, &inner), Some(OpenRoot { root: inner.clone(), below: false }));
assert_eq!(resolve(&roots, &inner.join("src")), Some(OpenRoot { root: inner.clone(), below: true }));
}
}
+124 -24
Переглянути файл
@@ -4,7 +4,7 @@
//! running IDE's server, found through the discovery file.
use crate::discovery::Discovery;
use crate::protocol::{NOT_OPEN, error_response};
use crate::protocol::{METHOD_NOT_FOUND, NOT_OPEN, SERVES_FOLDER, error_response};
use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::{Request, StatusCode, header};
@@ -17,7 +17,11 @@ use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt};
#[derive(Default)]
struct BridgeState {
preferred: Option<SocketAddr>,
/// The server that serves the connection's folder, or the first one when none does. A
/// server restarted on its port is another one: its entry names another process or token.
preferred: Option<Discovery>,
/// The servers there were when `preferred` was picked: one started since may serve the folder.
picked_among: Vec<Discovery>,
init_message: Option<Value>,
initialized_on: HashSet<SocketAddr>,
}
@@ -171,18 +175,28 @@ async fn post(
if candidates.is_empty() {
return Err(not_running());
}
if let Some(preferred) = state.lock().unwrap().preferred
&& let Some(pos) = candidates.iter().position(|c| SocketAddr::new(c.address, c.port) == preferred)
{
if message.get("method").and_then(Value::as_str) == Some("notifications/cancelled") {
return cancel_everywhere(candidates, project, message, scope, sent).await.ok_or_else(not_running);
}
let preferred = state.lock().unwrap().preferred.clone();
if let Some(pos) = preferred.and_then(|preferred| candidates.iter().position(|c| *c == preferred)) {
let chosen = candidates.remove(pos);
candidates.insert(0, chosen);
}
// `initialize` picks the server that serves the connection's folder, and later messages
// keep it: a call whose `projectPath` another server serves doesn't move `tools/list`
// there. A message after that server stopped, or after another one started, picks again.
let initializing = is_initialize(message);
let mut fallback: Option<(SocketAddr, Answer)> = None;
if !initializing {
pick_again(&mut candidates, project, scope, state).await;
}
let listed = candidates.clone();
let mut answered = None;
let mut fallback: Option<(Discovery, Answer)> = None;
let mut last_error: Option<String> = None;
let total = candidates.len();
for (idx, info) in candidates.into_iter().enumerate() {
let at = SocketAddr::new(info.address, info.port);
let at = address(&info);
if !initializing {
let init = {
let guard = state.lock().unwrap();
@@ -190,7 +204,7 @@ async fn post(
};
if let Some(mut init_msg) = init {
if let Some(obj) = init_msg.as_object_mut() {
obj.insert("id".into(), Value::String(format!("__openidea_init_{idx}__")));
obj.insert("id".into(), Value::String(own_id("init")));
}
if post_one(&info, project, &init_msg, scope, sent).await.is_ok() {
state.lock().unwrap().initialized_on.insert(at);
@@ -202,34 +216,120 @@ async fn post(
if initializing {
state.lock().unwrap().initialized_on.insert(at);
if total > 1 && !serves_project(&info, project, scope).await {
fallback.get_or_insert((at, answer));
fallback.get_or_insert((info, answer));
continue;
}
} else if idx + 1 < total && is_not_open_reply(&answer) {
fallback = Some((at, answer));
fallback = Some((info, answer));
continue;
}
state.lock().unwrap().preferred = Some(at);
return Ok(answer);
answered = Some((info, answer));
break;
}
Err(err) => last_error = Some(err),
}
}
if let Some((at, answer)) = fallback {
state.lock().unwrap().preferred = Some(at);
return Ok(answer);
let Some((info, answer)) = answered.or(fallback) else {
return Err(last_error.unwrap_or_else(not_running));
};
if initializing {
let mut state = state.lock().unwrap();
state.preferred = Some(info);
state.picked_among = listed;
}
Err(last_error.unwrap_or_else(not_running))
Ok(answer)
}
/// Whether the server of `info` has `project` open: its `tools/list` doesn't answer "not open".
async fn serves_project(info: &Discovery, project: &Path, scope: &str) -> bool {
let probe = serde_json::json!({ "jsonrpc": "2.0", "id": "__openidea_probe__", "method": "tools/list" });
let (discard, _) = tokio::sync::mpsc::unbounded_channel();
match post_one(info, project, &probe, scope, &discard).await {
Ok(answer @ Answer::Body(StatusCode::OK, _)) => !is_not_open_reply(&answer),
_ => false,
fn address(info: &Discovery) -> SocketAddr {
SocketAddr::new(info.address, info.port)
}
/// An id of the bridge's own for a request it makes: concurrent messages can make one to the
/// same server at once, and a server refuses an id that is already in flight.
fn own_id(kind: &str) -> String {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
format!("__openidea_{kind}_{}__", NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))
}
/// How long a server has to answer a probe or take a cancellation.
const PROBE_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
/// Sends a cancellation to every server at once, since the call may run in any of them (its
/// `projectPath` picks one); the answer of one that took it. A server that doesn't run the call
/// keeps the id for a while, in case the call reaches it later. One that doesn't answer in
/// time holds up neither the others nor the bridge.
async fn cancel_everywhere(
candidates: Vec<Discovery>,
project: &Path,
message: &Value,
scope: &str,
sent: &tokio::sync::mpsc::UnboundedSender<Value>,
) -> Option<Answer> {
let mut posts = tokio::task::JoinSet::new();
for info in candidates {
let (project, message, scope, sent) = (project.to_owned(), message.clone(), scope.to_owned(), sent.clone());
posts.spawn(async move {
tokio::time::timeout(PROBE_WAIT, post_one(&info, &project, &message, &scope, &sent)).await
});
}
let mut accepted = None;
while let Some(posted) = posts.join_next().await {
if let Ok(Ok(Ok(answer))) = posted {
accepted.get_or_insert(answer);
}
}
accepted
}
/// Picks the server for the connection's folder again when the one picked is gone or another
/// server started since, as `initialize` picks it: the first of `candidates` (the one picked
/// before leads) that serves the folder, else the first. Puts it first.
async fn pick_again(candidates: &mut Vec<Discovery>, project: &Path, scope: &str, state: &Mutex<BridgeState>) {
{
let state = state.lock().unwrap();
let kept = state.preferred.as_ref().is_some_and(|preferred| candidates.contains(preferred));
if kept && candidates.iter().all(|c| state.picked_among.contains(c)) {
return;
}
}
let mut chosen = 0;
if candidates.len() > 1 {
for (pos, info) in candidates.iter().enumerate() {
if serves_project(info, project, scope).await {
chosen = pos;
break;
}
}
}
let picked = candidates.remove(chosen);
candidates.insert(0, picked);
let mut state = state.lock().unwrap();
state.preferred = Some(candidates[0].clone());
state.picked_among = candidates.clone();
}
/// Whether the server of `info` serves `project`: its `openidea/servesFolder` names a root.
/// An IDE older than that method answers "method not found"; its `tools/list` answers "not
/// open" for a folder it doesn't serve, so that answers instead. A server that doesn't answer
/// in time doesn't serve it.
async fn serves_project(info: &Discovery, project: &Path, scope: &str) -> bool {
let probe = |method| serde_json::json!({ "jsonrpc": "2.0", "id": own_id("probe"), "method": method });
let (discard, _) = tokio::sync::mpsc::unbounded_channel();
let ask = async {
let reply = match post_one(info, project, &probe(SERVES_FOLDER), scope, &discard).await {
Ok(Answer::Body(StatusCode::OK, body)) => serde_json::from_slice::<Value>(&body).ok(),
_ => None,
};
let Some(reply) = reply else { return false };
if reply.pointer("/error/code").and_then(Value::as_i64) == Some(METHOD_NOT_FOUND) {
return match post_one(info, project, &probe("tools/list"), scope, &discard).await {
Ok(answer @ Answer::Body(StatusCode::OK, _)) => !is_not_open_reply(&answer),
_ => false,
};
}
reply.pointer("/result/root").is_some_and(Value::is_string)
};
tokio::time::timeout(PROBE_WAIT, ask).await.unwrap_or(false)
}
fn is_not_open_reply(answer: &Answer) -> bool {
@@ -253,7 +353,7 @@ async fn post_one(
project.display()
)
};
let at = SocketAddr::new(info.address, info.port);
let at = address(info);
let stream = tokio::net::TcpStream::connect(at).await.map_err(|_| not_running())?;
let (mut sender, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream))
.await
+490 -33
Переглянути файл
@@ -5,7 +5,7 @@ use ide_mcp::{Discovery, McpServer, ServerOptions, Tool, ToolCallError, ToolRegi
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
struct Registry {
project: PathBuf,
@@ -28,6 +28,10 @@ impl ToolRegistry for Registry {
}])
}
fn tools_without_project(&self) -> Vec<Tool> {
vec![named("everything")]
}
fn call(
&self,
project: &Path,
@@ -48,6 +52,18 @@ impl ToolRegistry for Registry {
}
}
/// A read-only tool with no arguments.
fn named(name: &str) -> Tool {
Tool {
name: name.into(),
description: format!("The tool {name}"),
input_schema: json!({ "type": "object" }),
read_only: true,
destructive: false,
output_schema: None,
}
}
struct Setup {
_tmp: tempfile::TempDir,
project: PathBuf,
@@ -215,30 +231,45 @@ async fn requests_without_the_token_or_from_web_pages_are_refused() {
async fn folders_that_are_not_open_are_named_in_the_error() {
let s = setup();
let elsewhere = s.project.parent().unwrap().join("elsewhere");
let header = format!("X-OpenIDEA-Project: {}", elsewhere.display());
let (status, body) =
post(&s, "/mcp", &[&bearer(&s), &header], &json!({"jsonrpc":"2.0","id":3,"method":"tools/list"})).await;
assert_eq!(status, 200);
let reply: Value = serde_json::from_str(&body).unwrap();
assert!(reply["error"]["message"].as_str().unwrap().contains("isn't open in OpenIDEA"));
// The connection's folder isn't open: the list is the one without a project, and a call
// that names no project of its own is refused with the folder named.
let list = rpc_for(&s, &elsewhere, "tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["name"], "everything", "{list}");
let call = rpc_for(&s, &elsewhere, "tools/call", json!({ "name": "echo" })).await;
assert_eq!(call["error"]["code"], -32001, "{call}");
let message = call["error"]["message"].as_str().unwrap();
assert!(message.contains("isn't open in OpenIDEA") && message.contains(elsewhere.to_str().unwrap()), "{message}");
// No folder named and one window: that window's project lists its tools.
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &json!({"jsonrpc":"2.0","id":3,"method":"tools/list"})).await;
assert!(serde_json::from_str::<Value>(&body).unwrap()["result"]["tools"].is_array());
assert_eq!(serde_json::from_str::<Value>(&body).unwrap()["result"]["tools"][0]["name"], "echo");
}
/// One project open in a window and, optionally, one folder served without a window.
/// One project open in a window, the folders served without a window and, optionally, the
/// root of a window on a remote host (which has no tools here).
struct WithBackground {
open: PathBuf,
background: Option<PathBuf>,
background: Vec<PathBuf>,
remote: Option<PathBuf>,
}
impl ToolRegistry for WithBackground {
fn projects(&self) -> Vec<PathBuf> {
vec![self.open.clone()]
std::iter::once(self.open.clone()).chain(self.remote.clone()).collect()
}
fn resolve(&self, path: &Path) -> Option<PathBuf> {
self.background.clone().filter(|root| path.starts_with(root))
/// The innermost served folder containing `path`, strictly inside `within`, as the
/// background policy answers.
fn resolve(&self, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
let inside = |root: &&PathBuf| within.is_none_or(|open| root.starts_with(open) && *root != open);
let served = self.background.iter().filter(|root| path.starts_with(root)).filter(inside);
served.max_by_key(|root| root.components().count()).cloned()
}
fn tools_without_project(&self) -> Vec<Tool> {
vec![named("anything")]
}
fn tools(&self, project: &Path) -> Result<Vec<Tool>, String> {
if self.remote.as_deref() == Some(project) {
return Err("project is on a remote host".into());
}
Ok(vec![Tool {
name: "where".into(),
description: format!("Names {}", project.display()),
@@ -253,17 +284,23 @@ impl ToolRegistry for WithBackground {
}
}
/// The server over [`WithBackground`]; the folder `inventory` next to the open project.
fn setup_with_background(served: bool) -> (Setup, PathBuf) {
let mut s = setup();
/// Stops the server of `s` and serves `registry` in its place.
fn restart(s: &mut Setup, registry: impl ToolRegistry) {
s.server.take().unwrap().stop();
let inventory = s.project.parent().unwrap().join("inventory");
let runtime = tokio::runtime::Handle::current();
s.server = Some(McpServer::start_with(Arc::new(registry), None, &runtime, ServerOptions::default()).unwrap());
}
/// The server over [`WithBackground`] serving the `served` folders, relative to the folder
/// that holds the open project; the folder `inventory` next to the open project.
fn setup_with_background(served: &[&str]) -> (Setup, PathBuf) {
let mut s = setup();
let base = s.project.parent().unwrap().to_path_buf();
let inventory = base.join("inventory");
std::fs::create_dir_all(inventory.join("src")).unwrap();
let registry = WithBackground { open: s.project.clone(), background: served.then(|| inventory.clone()) };
s.server = Some(
McpServer::start_with(Arc::new(registry), None, &tokio::runtime::Handle::current(), ServerOptions::default())
.unwrap(),
);
let background = served.iter().map(|folder| base.join(folder).components().collect()).collect();
let registry = WithBackground { open: s.project.clone(), background, remote: None };
restart(&mut s, registry);
(s, inventory)
}
@@ -277,13 +314,14 @@ async fn rpc_for(s: &Setup, folder: &Path, method: &str, params: Value) -> Value
#[tokio::test(flavor = "multi_thread")]
async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
let (s, inventory) = setup_with_background(true);
let (s, inventory) = setup_with_background(&["inventory"]);
let inside = inventory.join("src");
let init = rpc_for(&s, &inside, "initialize", json!({})).await;
let instructions = init["result"]["instructions"].as_str().unwrap();
assert!(instructions.contains(inventory.to_str().unwrap()), "{instructions}");
// Clients that load tool descriptions lazily still learn to establish the workspace first (#5751).
assert!(instructions.contains("first project-related operation in a session, call `get_workspace_roots`"));
assert!(!instructions.contains("no project of its own"), "{instructions}");
let list = rpc_for(&s, &inside, "tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", inventory.display()), "{list}");
let call = rpc_for(&s, &inside, "tools/call", json!({ "name": "where" })).await;
@@ -297,18 +335,71 @@ async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
}
#[tokio::test(flavor = "multi_thread")]
async fn a_folder_that_is_neither_open_nor_served_in_the_background_says_where_to_turn_it_on() {
let (s, inventory) = setup_with_background(false);
for (method, params) in [("tools/list", json!({})), ("tools/call", json!({ "name": "where" }))] {
let reply = rpc_for(&s, &inventory, method, params).await;
assert_eq!(reply["error"]["code"], -32001, "{method}: {reply}");
let message = reply["error"]["message"].as_str().unwrap();
assert!(message.contains("isn't open in OpenIDEA and isn't served in the background"), "{message}");
assert!(message.contains("Settings › Agents › IDE MCP Server"), "{message}");
assert!(message.contains(inventory.to_str().unwrap()) && message.contains(s.project.to_str().unwrap()));
async fn the_innermost_project_answers_whether_a_window_has_it_open_or_it_is_served_in_the_background() {
// The layout of #7040: a window on `project` and `contracts` inside it served in the
// background. The policy serves the window's root and the folder around it as well, as
// trusted projects and listed folders do.
let (s, _) = setup_with_background(&["", "project", "project/contracts"]);
let contracts = s.project.join("contracts");
std::fs::create_dir_all(contracts.join("src")).unwrap();
let base = s.project.parent().unwrap().to_path_buf();
for (folder, served) in [
(contracts.join("src"), &contracts),
(contracts.clone(), &contracts),
// Folders of the window's project that no nested project holds stay with the window.
(s.project.join("src"), &s.project),
(s.project.clone(), &s.project),
(base.join("elsewhere"), &base),
] {
let at = folder.display();
let call = rpc(&s, "tools/call", json!({ "name": "where", "arguments": { "projectPath": folder } })).await;
assert_eq!(call["result"]["structuredContent"]["project"], json!(served), "{at}: {call}");
let list = rpc_for(&s, &folder, "tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", served.display()), "{at}: {list}");
let init = rpc_for(&s, &folder, "initialize", json!({})).await;
let instructions = init["result"]["instructions"].as_str().unwrap();
assert!(instructions.contains(&format!("serves at {}:", served.display())), "{at}: {instructions}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_folder_that_is_neither_open_nor_served_in_the_background_says_where_to_turn_it_on() {
let (s, inventory) = setup_with_background(&[]);
let list = rpc_for(&s, &inventory, "tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["name"], "anything", "{list}");
let reply = rpc_for(&s, &inventory, "tools/call", json!({ "name": "where" })).await;
assert_eq!(reply["error"]["code"], -32001, "{reply}");
let message = reply["error"]["message"].as_str().unwrap();
assert!(message.contains("isn't open in OpenIDEA and isn't served in the background"), "{message}");
assert!(message.contains("Settings › Agents › IDE MCP Server"), "{message}");
assert!(message.contains(inventory.to_str().unwrap()) && message.contains(s.project.to_str().unwrap()));
let init = rpc_for(&s, &inventory, "initialize", json!({})).await;
assert!(init["result"]["instructions"].is_string(), "initialize answers without a project: {init}");
let instructions = init["result"]["instructions"].as_str().unwrap();
assert!(
instructions.contains("pass `projectPath`, a folder inside a project OpenIDEA serves, in every call"),
"{instructions}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn serves_folder_names_the_project_that_answers_for_the_connection_folder() {
let (mut s, inventory) = setup_with_background(&[]);
let base = s.project.parent().unwrap().to_owned();
let remote = base.join("remote");
let registry =
WithBackground { open: s.project.clone(), background: vec![inventory.clone()], remote: Some(remote.clone()) };
restart(&mut s, registry);
let cases = [
(s.project.join("src"), json!(s.project)),
(inventory.join("src"), json!(inventory)),
(base.join("elsewhere"), Value::Null),
// A remote window's root is that host's to serve.
(remote, Value::Null),
];
for (folder, root) in cases {
let reply = rpc_for(&s, &folder, "openidea/servesFolder", json!({})).await;
assert_eq!(reply["result"], json!({ "root": root }), "{}: {reply}", folder.display());
}
}
#[tokio::test(flavor = "multi_thread")]
@@ -378,6 +469,9 @@ async fn routing_an_argument_overrides_the_header_and_ambiguity_lists_projects()
fn tools(&self, _: &Path) -> Result<Vec<Tool>, String> {
Ok(Vec::new())
}
fn tools_without_project(&self) -> Vec<Tool> {
vec![named("anywhere")]
}
fn call(
&self,
project: &Path,
@@ -401,8 +495,14 @@ async fn routing_an_argument_overrides_the_header_and_ambiguity_lists_projects()
)
.unwrap(),
);
// No folder named and two windows: the list without a project, and a call has to name one.
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &json!({"jsonrpc":"2.0","id":1,"method":"tools/list"})).await;
let list: Value = serde_json::from_str(&body).unwrap();
assert_eq!(list["result"]["tools"][0]["name"], "anywhere", "{list}");
let call = json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"where"}});
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &call).await;
let reply: Value = serde_json::from_str(&body).unwrap();
assert_eq!(reply["error"]["code"], -32602, "{reply}");
let message = reply["error"]["message"].as_str().unwrap();
assert!(message.contains(s.project.to_str().unwrap()) && message.contains(second.to_str().unwrap()));
let result = rpc(&s, "tools/call", json!({"name":"where","arguments":{"projectPath":second.join("nested")}})).await;
@@ -589,3 +689,360 @@ async fn multiple_servers_sharing_app_data_route_by_project_and_survive_one_clos
server_a.stop();
assert!(!discovery.exists());
}
/// The stdio bridge started in `folder`, driven as MCP clients drive it: each request goes
/// out once the answer to the one before has come back.
struct Client {
input: tokio::io::DuplexStream,
output: tokio::io::Lines<tokio::io::BufReader<tokio::io::DuplexStream>>,
bridge: tokio::task::JoinHandle<std::io::Result<()>>,
id: u64,
}
impl Client {
fn start(discovery: &Path, folder: &Path) -> Self {
let (input, bridge_input) = tokio::io::duplex(1 << 16);
let (bridge_output, output) = tokio::io::duplex(1 << 16);
let (discovery, folder) = (discovery.to_owned(), folder.to_owned());
let bridge = tokio::spawn(async move {
stdio::bridge(&discovery, &folder, tokio::io::BufReader::new(bridge_input), bridge_output).await
});
Self { input, output: tokio::io::BufReader::new(output).lines(), bridge, id: 0 }
}
/// Sends a request without waiting for its answer; its id.
async fn send(&mut self, method: &str, params: Value) -> u64 {
self.id += 1;
self.notify(json!({ "jsonrpc": "2.0", "id": self.id, "method": method, "params": params })).await;
self.id
}
async fn notify(&mut self, message: Value) {
self.input.write_all(format!("{message}\n").as_bytes()).await.unwrap();
}
async fn answer(&mut self, id: u64) -> Value {
let answer = async {
loop {
let line = self.output.next_line().await.unwrap().expect("the bridge answers");
let reply: Value = serde_json::from_str(&line).unwrap();
if reply["id"] == id {
return reply;
}
}
};
tokio::time::timeout(std::time::Duration::from_secs(10), answer).await.expect("an answer in time")
}
async fn ask(&mut self, method: &str, params: Value) -> Value {
let id = self.send(method, params).await;
self.answer(id).await
}
async fn close(self) {
let Self { input, output, bridge, .. } = self;
drop(input);
bridge.await.unwrap().unwrap();
drop(output);
}
}
fn start_in(discovery: &Path, registry: impl ToolRegistry) -> McpServer {
let runtime = tokio::runtime::Handle::current();
McpServer::start_with(Arc::new(registry), Some(discovery.to_owned()), &runtime, ServerOptions::default()).unwrap()
}
/// A temporary folder holding `folders` (each with a `src`), and the discovery file of the
/// servers that share its data directory.
fn layout(folders: &[&str]) -> (tempfile::TempDir, PathBuf, PathBuf) {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
for folder in folders {
std::fs::create_dir_all(base.join(folder).join("src")).unwrap();
}
let discovery = discovery_path(&base.join("app-data"));
(tmp, base, discovery)
}
impl WithBackground {
/// A window on `open` and `background` served without one.
fn serving(open: &Path, background: &Path) -> Self {
Self { open: open.to_owned(), background: vec![background.to_owned()], remote: None }
}
}
/// What an MCP client started in a folder of `proj-b` gets when two servers share the
/// discovery directory: A has `proj-a` in a window, B serves `proj-b` in the background.
/// Each order makes the other server the one in `server.json`.
#[tokio::test(flavor = "multi_thread")]
async fn the_bridge_sends_a_folder_to_the_process_that_serves_it_in_either_order() {
for b_first in [false, true] {
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
let a = || Registry { project: proj_a.clone() };
let b = || WithBackground::serving(&proj_c, &proj_b);
let servers = if b_first {
[start_in(&discovery, b()), start_in(&discovery, a())]
} else {
[start_in(&discovery, a()), start_in(&discovery, b())]
};
let mut client = Client::start(&discovery, &proj_b.join("src"));
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
let instructions = init["result"]["instructions"].as_str().unwrap();
assert!(instructions.contains(proj_b.to_str().unwrap()), "b_first {b_first}: {instructions}");
let list = client.ask("tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", proj_b.display()), "{list}");
let call = client.ask("tools/call", json!({ "name": "where" })).await;
assert_eq!(call["result"]["structuredContent"]["project"], json!(proj_b), "{call}");
client.close().await;
for server in servers {
server.stop();
}
}
}
/// A client started in `work`, a folder neither server serves: the tools of the server
/// `initialize` picked, and each call goes where its `projectPath` is served.
#[tokio::test(flavor = "multi_thread")]
async fn a_bridge_in_a_folder_no_process_serves_lists_tools_and_routes_each_call_by_project_path() {
for b_first in [false, true] {
let (_tmp, base, discovery) = layout(&["proj-a", "proj-c", "work/repo"]);
let (proj_a, proj_c, work) = (base.join("proj-a"), base.join("proj-c"), base.join("work"));
let repo = work.join("repo");
let a = || Registry { project: proj_a.clone() };
let b = || WithBackground::serving(&proj_c, &repo);
// The server started last is in `server.json`; with neither serving the folder,
// `initialize` settles on it.
let (servers, listed) = if b_first {
([start_in(&discovery, b()), start_in(&discovery, a())], "everything")
} else {
([start_in(&discovery, a()), start_in(&discovery, b())], "anything")
};
let mut client = Client::start(&discovery, &work);
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
let instructions = init["result"]["instructions"].as_str().unwrap();
assert!(instructions.contains("no project of its own"), "{instructions}");
let list = client.ask("tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["name"], listed, "b_first {b_first}: {list}");
let in_repo = json!({ "name": "echo", "arguments": { "text": "x", "projectPath": repo.join("src") } });
let call = client.ask("tools/call", in_repo).await;
assert_eq!(call["result"]["structuredContent"]["project"], json!(repo), "{call}");
let in_a = json!({ "name": "echo", "arguments": { "text": "x", "projectPath": proj_a } });
let call = client.ask("tools/call", in_a).await;
assert_eq!(call["result"]["content"][0]["text"], format!("x in {}", proj_a.display()), "{call}");
let unnamed = client.ask("tools/call", json!({ "name": "echo", "arguments": { "text": "x" } })).await;
assert_eq!(unnamed["error"]["code"], -32001, "{unnamed}");
// A call sent to the other server doesn't move the connection there.
let list = client.ask("tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["name"], listed, "b_first {b_first}: {list}");
client.close().await;
for server in servers {
server.stop();
}
}
}
/// The server `initialize` picked stops, or one that serves the folder starts later: the
/// next message picks again, as `initialize` does.
#[tokio::test(flavor = "multi_thread")]
async fn the_bridge_picks_the_server_again_when_the_servers_change() {
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
let a = || Registry { project: proj_a.clone() };
let b = || WithBackground::serving(&proj_c, &proj_b);
let serving_b = format!("Names {}", proj_b.display());
// Only A runs at `initialize`; B starts afterwards.
let server_a = start_in(&discovery, a());
let mut client = Client::start(&discovery, &proj_b.join("src"));
client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
let server_b = start_in(&discovery, b());
let list = client.ask("tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["description"], serving_b, "a server started later: {list}");
// B restarts, and A restarts after it, so A is first in the discovery file.
server_b.stop();
let server_b = start_in(&discovery, b());
server_a.stop();
let server_a = start_in(&discovery, a());
let list = client.ask("tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["description"], serving_b, "the picked server restarted: {list}");
client.close().await;
server_a.stop();
server_b.stop();
}
/// A server restarted on the port it had (a fixed port in the settings) is another server: one
/// that didn't serve the folder may serve it now.
#[tokio::test(flavor = "multi_thread")]
async fn the_bridge_picks_the_server_again_after_a_restart_on_the_same_port() {
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let fixed = ServerOptions { port: Some(port), ..Default::default() };
let runtime = tokio::runtime::Handle::current();
let start_b = |registry: WithBackground| {
McpServer::start_with(Arc::new(registry), Some(discovery.clone()), &runtime, fixed.clone()).unwrap()
};
// Neither serves `proj-b` at `initialize`, which settles on A, the server started last.
let server_b = start_b(WithBackground { open: proj_c.clone(), background: Vec::new(), remote: None });
let server_a = start_in(&discovery, Registry { project: proj_a.clone() });
let mut client = Client::start(&discovery, &proj_b.join("src"));
client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
let list = client.ask("tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["name"], "everything", "{list}");
server_b.stop();
let server_b = start_b(WithBackground::serving(&proj_c, &proj_b));
assert_eq!(server_b.port(), port);
let list = client.ask("tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", proj_b.display()), "{list}");
client.close().await;
server_a.stop();
server_b.stop();
}
/// Holds every call until it is cancelled: a window on `open`, `background` served without one.
struct Holding {
open: PathBuf,
background: PathBuf,
}
impl ToolRegistry for Holding {
fn projects(&self) -> Vec<PathBuf> {
vec![self.open.clone()]
}
fn resolve(&self, path: &Path, _: Option<&Path>) -> Option<PathBuf> {
path.starts_with(&self.background).then(|| self.background.clone())
}
fn tools(&self, _: &Path) -> Result<Vec<Tool>, String> {
Ok(vec![named("hold")])
}
fn call(&self, _: &Path, _: &str, _: &str, cancel: ide_mcp::CancellationToken) -> Result<String, ToolCallError> {
tokio::runtime::Handle::current().block_on(cancel.cancelled());
Err(ToolCallError::Failed("cancelled".into()))
}
}
/// The connection is A's, and a call whose `projectPath` B serves runs in B: its
/// cancellation reaches B.
#[tokio::test(flavor = "multi_thread")]
async fn a_cancellation_reaches_the_server_that_runs_the_call() {
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
let server_b = start_in(&discovery, Holding { open: proj_c, background: proj_b.clone() });
let server_a = start_in(&discovery, Registry { project: proj_a.clone() });
let mut client = Client::start(&discovery, &proj_a);
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
assert!(init["result"]["instructions"].as_str().unwrap().contains(proj_a.to_str().unwrap()), "{init}");
let call = client.send("tools/call", json!({ "name": "hold", "arguments": { "projectPath": proj_b } })).await;
client
.notify(json!({ "jsonrpc": "2.0", "method": "notifications/cancelled", "params": { "requestId": call } }))
.await;
let answer = client.answer(call).await;
assert_eq!(answer["result"]["isError"], true, "{answer}");
client.close().await;
server_a.stop();
server_b.stop();
}
/// An OpenIDEA older than `openidea/servesFolder`, registered in `discovery`: it answers
/// "method not found" to that, and "not open" to `tools/list` and `tools/call` for a folder
/// outside `serves`.
async fn fake_older_ide(discovery: &Path, serves: Option<PathBuf>) -> tokio::task::JoinHandle<()> {
use http_body_util::{BodyExt, Full};
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let server = tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
let serves = serves.clone();
let service = hyper::service::service_fn(move |request: hyper::Request<hyper::body::Incoming>| {
let serves = serves.clone();
async move {
let query = request.uri().query().unwrap_or_default().to_owned();
let folder = query.strip_prefix("project=").unwrap_or_default();
let folder =
PathBuf::from(percent_encoding::percent_decode_str(folder).decode_utf8_lossy().as_ref());
let body = request.into_body().collect().await.unwrap().to_bytes();
let message: Value = serde_json::from_slice(&body).unwrap();
let served = serves.as_ref().is_some_and(|root| folder.starts_with(root));
let id = message["id"].clone();
let reply = match message["method"].as_str().unwrap_or_default() {
_ if id.is_null() => None,
"initialize" => Some(json!({ "jsonrpc": "2.0", "id": id, "result": {
"protocolVersion": "2025-06-18", "capabilities": { "tools": {} },
"serverInfo": { "name": "OpenIDEA", "version": "0.1.0" },
"instructions": "an older OpenIDEA" } })),
"tools/list" if served => {
Some(json!({ "jsonrpc": "2.0", "id": id, "result": { "tools": [] } }))
}
"tools/call" if served => Some(json!({ "jsonrpc": "2.0", "id": id, "result": {
"content": [{ "type": "text", "text": "older" }], "isError": false } })),
"tools/list" | "tools/call" => Some(
json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32001, "message": "not open" } }),
),
_ => Some(
json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32601, "message": "no method" } }),
),
};
let response = match reply {
Some(reply) => hyper::Response::builder()
.header("content-type", "application/json")
.body(Full::new(bytes::Bytes::from(reply.to_string()))),
None => hyper::Response::builder().status(202).body(Full::new(bytes::Bytes::new())),
};
Ok::<_, std::convert::Infallible>(response.unwrap())
}
});
tokio::spawn(async move {
let io = hyper_util::rt::TokioIo::new(stream);
let _ = hyper::server::conn::http1::Builder::new().serve_connection(io, service).await;
});
}
});
// Written once it listens, so the stale-entry sweep of the next server keeps it.
let info = Discovery {
address: std::net::Ipv4Addr::LOCALHOST.into(),
port,
token: "test-token-older".into(),
pid: std::process::id(),
version: "0.1.0".into(),
};
info.write(discovery).unwrap();
server
}
#[tokio::test(flavor = "multi_thread")]
async fn an_older_ide_without_serves_folder_is_probed_with_tools_list() {
for older_serves in [false, true] {
let (_tmp, base, discovery) = layout(&["proj-c", "inventory"]);
let (proj_c, folder) = (base.join("proj-c"), base.join("inventory"));
// Either way the server that doesn't serve the folder is in `server.json`.
let (older, real) = if older_serves {
let older = fake_older_ide(&discovery, Some(folder.clone())).await;
(older, start_in(&discovery, Registry { project: proj_c.clone() }))
} else {
let real = start_in(&discovery, WithBackground::serving(&proj_c, &folder));
(fake_older_ide(&discovery, None).await, real)
};
let mut client = Client::start(&discovery, &folder.join("src"));
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
let instructions = init["result"]["instructions"].as_str().unwrap();
let expected = if older_serves { "an older OpenIDEA".to_owned() } else { folder.display().to_string() };
assert!(instructions.contains(&expected), "older_serves {older_serves}: {instructions}");
let call = client.ask("tools/call", json!({ "name": "where" })).await;
let answered = match older_serves {
true => call["result"]["content"][0]["text"] == "older",
false => call["result"]["structuredContent"]["project"] == json!(folder),
};
assert!(answered, "older_serves {older_serves}: {call}");
client.close().await;
real.stop();
older.abort();
}
}
+25 -2
Переглянути файл
@@ -613,11 +613,14 @@ impl PluginEngine {
pub fn compile_cached(&self, wasm: &Path, cache_dir: &Path) -> Result<Component, String> {
let bytes = std::fs::read(wasm).map_err(|e| format!("{}: {e}", wasm.display()))?;
let file = cache_dir.join(format!("{}.cwasm", self.cache_key(&bytes)));
if file.is_file() {
// Read into memory rather than `deserialize_file`: that maps the file and makes its pages
// executable, which the hardened runtime of the signed macOS app refuses ("failed to make
// memory executable"), so the cache never hit and every activation compiled again.
if let Ok(precompiled) = std::fs::read(&file) {
// SAFETY: the cache directory belongs to the IDE (inside its plugins
// directory) and is written only by `store_precompiled` below from
// components this engine compiled; a corrupt file fails validation.
match unsafe { Component::deserialize_file(&self.engine, &file) } {
match unsafe { Component::deserialize(&self.engine, &precompiled) } {
Ok(component) => return Ok(component),
Err(e) => {
tracing::info!("discarding precompiled {}: {e}", file.display());
@@ -3035,6 +3038,26 @@ impl Runtime {
mod tests {
use super::*;
/// The second compile of the same component loads the cached one instead of compiling and
/// writing it again (a failed load deletes and rewrites the file).
#[test]
fn a_precompiled_component_is_loaded_from_the_cache() {
let engine = PluginEngine::new().unwrap();
let wasm = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/hello/dist/plugin.wasm");
let cache = tempfile::tempdir().unwrap();
engine.compile_cached(&wasm, cache.path()).unwrap();
let cached = || {
let entries: Vec<_> = std::fs::read_dir(cache.path()).unwrap().flatten().map(|e| e.path()).collect();
assert_eq!(entries.len(), 1, "{entries:?}");
let file = entries[0].clone();
(std::fs::metadata(&file).unwrap().modified().unwrap(), file)
};
let before = cached();
std::thread::sleep(std::time::Duration::from_millis(20));
engine.compile_cached(&wasm, cache.path()).unwrap();
assert_eq!(cached(), before, "loaded, not compiled and stored again");
}
#[test]
fn readonly_field_extensions_are_parsed_and_unknown_or_malformed_fields_are_skipped() {
let fields = [
+4 -2
Переглянути файл
@@ -225,7 +225,9 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
args.push("--no-TTY".into());
}
}
RunTargetKind::Ssh => return Err(IdeError::internal("an SSH target does not run in a container")),
RunTargetKind::Ssh | RunTargetKind::Wsl => {
return Err(IdeError::internal("this run target does not run in a container"));
}
}
args.extend(["--name".into(), run.name.to_owned(), "--label".into(), format!("openidea.run={}", config.id)]);
args.extend(["--workdir".into(), command.cwd.clone()]);
@@ -341,7 +343,7 @@ pub fn python_probe_args(target: &RunTarget, root: &Path, name: &str, code: &str
}
args.extend(["run", "--no-deps", "--no-TTY"].map(String::from));
}
RunTargetKind::Ssh => {
RunTargetKind::Ssh | RunTargetKind::Wsl => {
return Err(IdeError::invalid(format!("Run target '{}' is not a container", target.name)));
}
}
+3 -1
Переглянути файл
@@ -1,5 +1,6 @@
//! Remote work over SSH: SFTP deployment ([`deploy`], [`mapping`]) and run
//! configurations on run targets ([`target`]; Docker and Compose ones in [`docker`]).
//! configurations on run targets ([`target`]; Docker and Compose ones in [`docker`], WSL
//! ones in [`wsl`]).
pub mod container_tunnel;
pub mod deploy;
@@ -10,6 +11,7 @@ pub mod mapping;
pub mod service;
pub mod target;
pub mod upload;
pub mod wsl;
pub use deploy::{
Deployment, DeploymentCoverage, SyncAction, SyncEntry, SyncStatus, SyncStep, TransferReport, coverage,
+1 -1
Переглянути файл
@@ -438,7 +438,7 @@ impl RemoteService {
let target_id = config.extras.target.as_deref().unwrap_or_default();
let target = run_target(settings, target_id)?;
if target.kind != ide_core::remote_settings::RunTargetKind::Ssh {
return Err(IdeError::internal("container run targets start as local runs of the docker CLI"));
return Err(IdeError::internal("container and WSL run targets start as local runs"));
}
let session = self.ssh.session(&target.ssh_config).await?;
let fs = RemoteFs::new(session.sftp().await?).with_shell(session.clone());
+8 -2
Переглянути файл
@@ -72,7 +72,8 @@ fn replace_root(s: &str, root: &str, remote: &str) -> String {
out.push_str(remote);
if root.contains('\\') {
let end = after
.find(|c: char| c.is_whitespace() || matches!(c, ';' | ',' | '"' | '\''))
// `:` too: past the drive letter, it only separates a POSIX path list.
.find(|c: char| c.is_whitespace() || matches!(c, ';' | ':' | ',' | '"' | '\''))
.unwrap_or(after.len());
out.push_str(&after[..end].replace('\\', "/"));
after = &after[end..];
@@ -191,7 +192,7 @@ pub fn debugpy_probe(debug: &RemoteCommand, bootstrap: &str) -> String {
/// `java` flags whose value is a path list that may point outside the project
/// (`~/.m2` jars, `--module-path` entries): deployment sync only uploads the
/// project root, so these entries need their own sync + rewrite (#2641).
const PATH_LIST_FLAGS: [&str; 6] =
pub(crate) const PATH_LIST_FLAGS: [&str; 6] =
["-cp", "-classpath", "--class-path", "-p", "--module-path", "--upgrade-module-path"];
/// The separator of a `-cp` value on this (client) machine.
@@ -635,6 +636,11 @@ mod tests {
assert_eq!(replace_root("/work/proj2/x:/work/proj/y", "/work/proj", "/srv"), "/work/proj2/x:/srv/y");
assert_eq!(replace_root("/work/proj", "/work/proj", "/srv"), "/srv");
assert_eq!(replace_root(r"C:\p\src/a.py C:\p2", r"C:\p", "/srv"), r"/srv/src/a.py C:\p2");
assert_eq!(
replace_root(r"C:\work\proj:C:\work\proj\src", r"C:\work\proj", "/mnt/c/work/proj"),
"/mnt/c/work/proj:/mnt/c/work/proj/src",
"each root of a PYTHONPATH list"
);
}
/// Unix/Windows spellings of the same layout: one inside-root entry, one
+426
Переглянути файл
@@ -0,0 +1,426 @@
//! Run configurations on WSL run targets: rewritten into a local run of
//! `wsl.exe -d <distro> --cd <dir> --exec <program> <args>`, with the project's paths
//! and interpreters swapped for their Linux counterparts. The console, stdin, Stop and
//! test parsers then work as for any local run.
use crate::target::remote_command;
use ide_core::remote_settings::RunTarget;
use ide_core::{IdeError, IdeResult};
use ide_run::RunConfig;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
/// Where the project is inside the target's distribution.
pub fn project_root(target: &RunTarget, root: &Path) -> IdeResult<String> {
match target.project_root.trim().trim_end_matches('/') {
"" if target.project_root.trim().starts_with('/') => Ok("/".into()),
"" => ide_core::wsl::linux_path(root, target.distro.trim()).ok_or_else(|| {
IdeError::invalid(format!(
"Run target '{}' can't reach {} from WSL: set the project's Linux path in Settings › Run Targets",
target.name,
root.display()
))
}),
folder => Ok(folder.to_owned()),
}
}
/// The file on this machine of a path a run in the target's distribution printed (a
/// traceback line): in the project, on a drive under `/mnt/<drive>`, else in the
/// distribution's own file system (`\\wsl.localhost\<distro>`).
pub fn local_file(path: &str, target: &RunTarget, root: &Path) -> Option<PathBuf> {
if !path.starts_with('/') {
return None;
}
if let Ok(linux_root) = project_root(target, root) {
let linux_root = linux_root.trim_end_matches('/');
if let Some(rest) =
path.strip_prefix(linux_root).filter(|r| r.is_empty() || r.starts_with('/') || linux_root.is_empty())
{
return Some(ide_core::wsl::path_parts(rest).into_iter().fold(root.to_path_buf(), |p, c| p.join(c)));
}
}
Some(ide_core::wsl::windows_path(path, target.distro.trim()))
}
fn is_java(command: &str) -> bool {
let name = command.trim().rsplit(['/', '\\']).next().unwrap_or("");
name.to_ascii_lowercase().trim_end_matches(".exe") == "java"
}
/// The `-cp` / `--module-path` values of `java` arguments as the distribution reads them:
/// each absolute entry outside the project through its `/mnt` path, joined with `:`.
/// Entries in the project stay as they are: `remote_command` maps them onto its folder there.
fn linux_path_lists(args: &[String], root: &Path, distro: &str) -> Vec<String> {
let mut out = args.to_vec();
for i in 1..out.len() {
if !crate::target::PATH_LIST_FLAGS.contains(&out[i - 1].as_str()) || out[i].contains("${") {
continue;
}
let entries: Vec<String> = out[i]
.split(crate::target::classpath_separator())
.filter(|e| !e.is_empty())
.map(|e| {
let path = Path::new(e);
if path.starts_with(root) {
return e.to_owned();
}
match path.is_absolute().then(|| ide_core::wsl::linux_path(path, distro)).flatten() {
Some(linux) => linux,
None => e.replace('\\', "/"),
}
})
.collect();
out[i] = entries.join(":");
}
out
}
/// The target's Python: its own, or `python3` on the distribution's `PATH`.
pub fn python(target: &RunTarget) -> &str {
match target.python.trim() {
"" => "python3",
python => python,
}
}
/// Run with `sh -c` in a distribution, the project's Linux folder as `$1`: prints the
/// Pythons found there, one path a line.
pub const FIND_PYTHONS: &str = r#"for p in "$(command -v python3)" "$(command -v python)" /usr/bin/python3* /usr/local/bin/python3* "$HOME"/.pyenv/versions/*/bin/python "$1/.venv/bin/python" "$1/venv/bin/python"; do case "$p" in *-config) continue ;; esac; [ -f "$p" ] && [ -x "$p" ] && echo "$p"; done; true"#;
/// The paths [`FIND_PYTHONS`] printed, without repeats and without the tools named after
/// Python (`python3-pytest`, `python3.12-config`).
pub fn parse_pythons(out: &str) -> Vec<String> {
let interpreter = |path: &str| {
let name = path.rsplit('/').next().unwrap_or("");
let version = name.strip_prefix("python").unwrap_or("-");
version.chars().all(|c| c.is_ascii_digit() || c == '.')
};
let mut found: Vec<String> = Vec::new();
for line in out.lines().map(str::trim).filter(|l| l.starts_with('/') && interpreter(l)) {
if !found.iter().any(|f| f == line) {
found.push(line.to_owned());
}
}
found
}
/// `config` as a local run of `wsl_exe` that runs it in the target's distribution.
/// `file_env` holds the variables of the configuration's `.env` files, already read;
/// `inherited_wslenv` is this machine's `WSLENV`, kept for the distribution.
pub fn wsl_config(
config: &RunConfig,
target: &RunTarget,
root: &Path,
linux_root: &str,
wsl_exe: &str,
file_env: &BTreeMap<String, String>,
inherited_wslenv: Option<&str>,
) -> IdeResult<RunConfig> {
let distro = target.distro.trim();
if !ide_core::wsl::is_valid_distro(distro) {
return Err(IdeError::invalid(format!(
"Run target '{}' has no WSL distribution; choose one in Settings › Run Targets",
target.name
)));
}
let mut command = if is_java(&config.command) {
let mut java = config.clone();
java.args = linux_path_lists(&config.args, root, distro);
remote_command(&java, target, root, linux_root)
} else {
remote_command(config, target, root, linux_root)
};
// Outside the project `remote_command` falls back to the project folder: a folder of
// this machine is reached through its own `/mnt` path instead.
if let Some(dir) = config.cwd.as_ref().map(|d| d.to_path_buf()).filter(|d| d.is_absolute() && !d.starts_with(root))
{
command.cwd = ide_core::wsl::linux_path(&dir, distro).ok_or_else(|| {
IdeError::invalid(format!(
"Run target '{}' can't reach the working folder {} from WSL",
target.name,
dir.display()
))
})?;
}
let mut env = file_env.clone();
if ide_run::is_python_kind(&config.kind) && !command.env.contains_key("PYTHONUNBUFFERED") {
env.insert("PYTHONUNBUFFERED".into(), "1".into());
}
env.extend(command.env.clone());
// The distribution keeps its own `PATH`: a value here is this machine's, or a `.env`
// `PATH=$PATH:…` already expanded against it.
env.remove("PATH");
let mut args: Vec<String> = ["-d", distro, "--cd", &command.cwd, "--exec"].map(String::from).to_vec();
// A Python run finds the console scripts next to the target's interpreter (a virtualenv's
// `pytest`) first, as a local run with the project interpreter does.
let scripts = (ide_run::is_python_kind(&config.kind) && target.python.trim().starts_with('/'))
.then(|| target.python.trim().rsplit_once('/').map(|(dir, _)| dir.to_owned()))
.flatten()
.filter(|dir| !dir.is_empty());
match (command.shell_line, scripts) {
(Some(line), None) => args.extend(["sh".into(), "-c".into(), line]),
(Some(line), Some(dir)) => args.extend(["sh".into(), "-c".into(), format!("PATH=\"$0:$PATH\"; {line}"), dir]),
(None, None) => {
args.push(command.program);
args.extend(command.args);
}
(None, Some(dir)) => {
args.extend(["sh".into(), "-c".into(), r#"PATH="$0:$PATH" exec "$@""#.into(), dir, command.program]);
args.extend(command.args);
}
}
// Values cross into the distribution through the environment (`WSLENV` lists the
// names), so they stay out of the command line echoed in the console. The configuration's
// own `WSLENV` entries (`FOO/p`) are kept with their flags.
let own = env.remove("WSLENV");
let mut wslenv: Vec<&str> = inherited_wslenv
.into_iter()
.chain(own.as_deref())
.flat_map(|v| v.split(':'))
.filter(|n| !n.is_empty())
.collect();
let listed = |name: &str, list: &[&str]| list.iter().any(|n| n.split('/').next() == Some(name));
for name in env.keys() {
if !listed(name, &wslenv) {
wslenv.push(name);
}
}
let wslenv = wslenv.join(":");
if !wslenv.is_empty() {
env.insert("WSLENV".into(), wslenv);
}
let mut out = config.clone();
out.command = wsl_exe.to_owned();
out.args = args;
out.cwd = Some(root.to_path_buf().into());
out.env = env;
let extras = &mut out.extras;
extras.target = None;
extras.env_files.clear();
// `wsl.exe` needs this machine's environment; the distribution gets only `WSLENV`'s names.
extras.include_system_env = true;
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::remote_settings::RunTargetKind;
fn target() -> RunTarget {
RunTarget { kind: RunTargetKind::Wsl, name: "wsl".into(), distro: "Ubuntu-24.04".into(), ..Default::default() }
}
fn config(command: &str, args: &[&str]) -> RunConfig {
RunConfig {
id: "app".into(),
name: "app".into(),
kind: "python".into(),
command: command.into(),
args: args.iter().map(|a| (*a).to_owned()).collect(),
cwd: None,
env: BTreeMap::new(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
}
}
#[test]
fn the_project_root_is_the_targets_or_its_mnt_path() {
let t = target();
assert_eq!(project_root(&t, Path::new(r"C:\work\proj")).unwrap(), "/mnt/c/work/proj");
assert_eq!(project_root(&t, Path::new(r"\\wsl.localhost\Ubuntu-24.04\home\me\p")).unwrap(), "/home/me/p");
let err = project_root(&t, Path::new(r"\\server\share\p")).unwrap_err();
assert!(err.message.contains("set the project's Linux path"), "{}", err.message);
let custom = RunTarget { project_root: " /c/work/proj/ ".into(), ..t.clone() };
assert_eq!(project_root(&custom, Path::new(r"\\server\share\p")).unwrap(), "/c/work/proj");
let slash = RunTarget { project_root: "/".into(), ..t };
assert_eq!(project_root(&slash, Path::new("x")).unwrap(), "/");
}
// Unix paths are not absolute on Windows; `windows_paths_are_mapped` covers Windows.
#[cfg(unix)]
#[test]
fn a_program_runs_through_wsl_exe_with_its_variables_by_name() {
let mut c = config("/work/proj/.venv/bin/python", &["-u", "/work/proj/main.py", "a b"]);
c.cwd = Some(Path::new("/work/proj/src").to_path_buf().into());
c.env.insert("DATA".into(), "/work/proj/data".into());
c.extras.target = Some("t".into());
c.extras.env_files = vec![".env".into()];
let files = BTreeMap::from([("SECRET".to_owned(), "s3".to_owned())]);
let out =
wsl_config(&c, &target(), Path::new("/work/proj"), "/mnt/c/proj", "wsl.exe", &files, Some("USERPROFILE/p"))
.unwrap();
assert_eq!(out.command, "wsl.exe");
assert_eq!(
out.args,
["-d", "Ubuntu-24.04", "--cd", "/mnt/c/proj/src", "--exec", "python3", "-u", "/mnt/c/proj/main.py", "a b"]
);
assert_eq!(out.env["DATA"], "/mnt/c/proj/data");
assert_eq!(out.env["SECRET"], "s3");
assert_eq!(out.env["PYTHONUNBUFFERED"], "1");
assert_eq!(out.env["WSLENV"], "USERPROFILE/p:DATA:PYTHONUNBUFFERED:SECRET");
assert_eq!(out.cwd.as_ref().map(|p| p.to_path_buf()), Some(Path::new("/work/proj").to_path_buf()));
assert_eq!(out.extras.target, None);
assert!(out.extras.env_files.is_empty());
assert!(out.extras.include_system_env);
}
#[test]
fn a_shell_line_runs_in_sh_and_the_targets_interpreter_is_used() {
let mut shell = config("npm run dev", &[]);
shell.kind = "shell".into();
let out =
wsl_config(&shell, &target(), Path::new("proj"), "/mnt/c/proj", "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(out.args, ["-d", "Ubuntu-24.04", "--cd", "/mnt/c/proj", "--exec", "sh", "-c", "npm run dev"]);
assert!(!out.env.contains_key("WSLENV"));
let t = RunTarget { python: "/home/me/.venv/bin/python".into(), ..target() };
let out =
wsl_config(&config("python.exe", &["-V"]), &t, Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), None)
.unwrap();
let path_first = r#"PATH="$0:$PATH" exec "$@""#;
assert_eq!(
&out.args[4..],
["--exec", "sh", "-c", path_first, "/home/me/.venv/bin", "/home/me/.venv/bin/python", "-V"],
"the virtualenv's scripts come first on PATH"
);
let mut pytest = config("pytest", &["tests"]);
pytest.kind = "pytest".into();
let out = wsl_config(&pytest, &t, Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(&out.args[9..], ["pytest", "tests"]);
}
#[test]
fn a_configurations_wslenv_keeps_its_flags_and_an_outside_folder_is_refused() {
let mut c = config("python", &[]);
c.env.insert("WSLENV".into(), "DATA/p".into());
c.env.insert("DATA".into(), "x".into());
let out = wsl_config(&c, &target(), Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), Some("A/u")).unwrap();
assert_eq!(out.env["WSLENV"], "A/u:DATA/p:PYTHONUNBUFFERED");
c.env.insert("PATH".into(), "/here/bin:/usr/bin".into());
let out = wsl_config(&c, &target(), Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), None).unwrap();
assert!(!out.env.contains_key("PATH") && !out.env["WSLENV"].contains("PATH"), "{:?}", out.env);
// An absolute folder of this machine outside the project (`/elsewhere` has no `/mnt` path).
let outside = if cfg!(windows) { r"\\server\share\x" } else { "/elsewhere" };
c.cwd = Some(Path::new(outside).to_path_buf().into());
let root = if cfg!(windows) { r"C:\proj" } else { "/proj" };
let err = wsl_config(&c, &target(), Path::new(root), "/p", "wsl.exe", &BTreeMap::new(), None).unwrap_err();
assert!(err.message.contains("can't reach the working folder"), "{}", err.message);
}
#[cfg(unix)]
#[test]
fn java_path_lists_are_joined_with_colons() {
let args: Vec<String> = ["-cp", "out:lib/*", "-p", "/opt/mods", "Main"].map(String::from).to_vec();
assert_eq!(linux_path_lists(&args, Path::new("/p"), "Ubuntu"), ["-cp", "out:lib/*", "-p", "/opt/mods", "Main"]);
assert!(is_java("/usr/lib/jvm/bin/java") && is_java(r"C:\jdk\bin\JAVA.EXE") && !is_java("javac"));
}
#[test]
fn printed_paths_lead_back_to_files_here() {
let t = RunTarget { project_root: "/mnt/c/work/proj".into(), ..target() };
let root = Path::new("proj-here");
assert_eq!(local_file("/mnt/c/work/proj/app/main.py", &t, root), Some(root.join("app").join("main.py")));
assert_eq!(
local_file("/mnt/d/lib/x.py", &t, root),
Some(PathBuf::from("D:\\").join("lib").join("x.py")),
"another drive"
);
assert_eq!(
local_file("/usr/lib/python3/dist-packages/a.py", &t, root),
Some(
ide_core::wsl::share_root("Ubuntu-24.04")
.join("usr")
.join("lib")
.join("python3")
.join("dist-packages")
.join("a.py")
)
);
assert_eq!(
local_file("/mnt/c/work/proj2/a.py", &t, root),
Some(PathBuf::from("C:\\").join("work").join("proj2").join("a.py"))
);
assert_eq!(local_file("main.py", &t, root), None);
assert_eq!(local_file("/mnt/c/work/proj/app/../lib/a.py", &t, root), Some(root.join("lib").join("a.py")));
}
#[test]
fn pythons_are_listed_once_and_python3_is_the_default() {
let out = "/usr/bin/python3\n\n/usr/bin/python3\n/usr/bin/python3.12\nsh: 1: bad\n/usr/bin/python3-pytest\n\
/usr/bin/python3.12-config\n/mnt/c/p/.venv/bin/python\r\n";
assert_eq!(parse_pythons(out), ["/usr/bin/python3", "/usr/bin/python3.12", "/mnt/c/p/.venv/bin/python"]);
assert_eq!(python(&target()), "python3");
assert_eq!(python(&RunTarget { python: " /opt/py/bin/python ".into(), ..target() }), "/opt/py/bin/python");
}
// The script itself, in this machine's `sh`.
#[cfg(unix)]
#[test]
fn the_python_finder_lists_a_venv_of_the_project() {
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join(".venv/bin");
std::fs::create_dir_all(&bin).unwrap();
let python = bin.join("python");
std::fs::write(&python, "#!/bin/sh\n").unwrap();
std::fs::set_permissions(&python, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
let out = std::process::Command::new("sh").args(["-c", FIND_PYTHONS, "sh"]).arg(dir.path()).output().unwrap();
assert!(out.status.success());
let found = parse_pythons(&String::from_utf8_lossy(&out.stdout));
assert!(found.contains(&python.to_string_lossy().into_owned()), "{found:?}");
assert!(found.iter().all(|p| !p.ends_with("-config")), "{found:?}");
}
#[test]
fn a_target_without_a_valid_distribution_is_refused() {
for distro in ["", " ", "-u root", "a;b"] {
let t = RunTarget { distro: distro.into(), ..target() };
let err = wsl_config(&config("python", &[]), &t, Path::new("p"), "/p", "wsl.exe", &BTreeMap::new(), None)
.unwrap_err();
assert!(err.message.contains("no WSL distribution"), "{distro}: {}", err.message);
}
}
#[cfg(windows)]
#[test]
fn windows_paths_are_mapped() {
let root = Path::new(r"C:\work\proj");
let linux = project_root(&target(), root).unwrap();
let mut c = config(r"C:\work\proj\.venv\Scripts\python.exe", &[r"C:\work\proj\app\main.py"]);
c.cwd = Some(Path::new(r"C:\work\proj\app").to_path_buf().into());
let out = wsl_config(&c, &target(), root, &linux, "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(
out.args,
["-d", "Ubuntu-24.04", "--cd", "/mnt/c/work/proj/app", "--exec", "python3", "/mnt/c/work/proj/app/main.py"]
);
let java = config(
r"C:\jdk\bin\java.exe",
&["-cp", r"C:\work\proj\out;D:\m2\a.jar;lib\*", "--module-path", r"C:\work\proj\mods", "app.Main"],
);
let out = wsl_config(&java, &target(), root, &linux, "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(
&out.args[4..],
[
"--exec",
"java",
"-cp",
"/mnt/c/work/proj/out:/mnt/d/m2/a.jar:lib/*",
"--module-path",
"/mnt/c/work/proj/mods",
"app.Main"
]
);
let custom = RunTarget { project_root: "/home/me/proj".into(), ..target() };
let java = config(r"C:\jdk\bin\java.exe", &["-cp", r"C:\work\proj\out;D:\m2\a.jar", "app.Main"]);
let out = wsl_config(&java, &custom, root, "/home/me/proj", "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(out.args[7], "/home/me/proj/out:/mnt/d/m2/a.jar", "project entries go to its folder there");
c.cwd = Some(Path::new(r"D:\data").to_path_buf().into());
let out = wsl_config(&c, &target(), root, &linux, "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(out.args[3], "/mnt/d/data", "a folder outside the project, through its /mnt path");
}
}
+55 -4
Переглянути файл
@@ -1,6 +1,6 @@
//! Xcode schemes: one configuration per scheme that builds its app and runs it on the iOS
//! Simulator or the Mac (see [`crate::xcode::prepare`]). A workspace next to the projects builds them all,
//! so its schemes and theirs are built through it.
//! so its schemes and theirs are built through it, as is the workspace of a CocoaPods project.
use super::{ConfigExt, config};
use crate::RunConfig;
@@ -8,10 +8,12 @@ use crate::xcode::{XcodeScheme, schemes};
use std::path::Path;
/// A folder holding an Xcode project or workspace, other than the `ios/` / `macos/` host app
/// of a Flutter or React Native project, which that project's own tooling runs.
/// of a Flutter or React Native project, which that project's own tooling runs, and a CocoaPods
/// `Pods/` folder.
pub(super) fn is_project(dir: &Path) -> bool {
let hosted = dir.parent().is_some_and(|p| p.join("pubspec.yaml").is_file() || p.join("package.json").is_file());
!hosted
&& !crate::xcode::is_pods_dir(dir)
&& std::fs::read_dir(dir).is_ok_and(|entries| {
entries.flatten().any(|e| e.path().extension().is_some_and(|x| x == "xcodeproj" || x == "xcworkspace"))
})
@@ -19,9 +21,13 @@ pub(super) fn is_project(dir: &Path) -> bool {
pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
let found = schemes(dir);
let workspace = found.iter().map(|s| &s.container).find(|c| c.extension().is_some_and(|x| x == "xcworkspace"));
let workspace = found
.iter()
.map(|s| s.container.clone())
.find(|c| c.extension().is_some_and(|x| x == "xcworkspace"))
.or_else(|| crate::xcode::pods_workspace(dir));
for scheme in &found {
let container = workspace.unwrap_or(&scheme.container);
let container = workspace.as_ref().unwrap_or(&scheme.container);
let container = container.strip_prefix(dir).unwrap_or(container).to_string_lossy().into_owned();
out.push(scheme_config(scheme, &container));
}
@@ -77,4 +83,49 @@ mod tests {
assert_eq!(app.env["API_HOST"], "localhost:8080");
assert!(!app.extras.params.contains_key(crate::xcode::SIMULATOR_PARAM));
}
#[test]
fn a_cocoapods_project_builds_and_tests_through_its_workspace() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let scheme = std::fs::read_to_string(
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/xcode/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme"),
)
.unwrap();
for dir in ["App.xcodeproj", "Pods/Pods.xcodeproj"] {
let schemes = root.join(dir).join("xcshareddata/xcschemes");
std::fs::create_dir_all(&schemes).unwrap();
std::fs::write(schemes.join("App.xcscheme"), &scheme).unwrap();
}
// `pod install`'s workspace has no schemes of its own.
std::fs::create_dir(root.join("App.xcworkspace")).unwrap();
let args = |out: &[RunConfig]| out.iter().map(|c| c.args.join(" ")).collect::<Vec<_>>();
let mut out = Vec::new();
detect(root, &mut out);
assert_eq!(args(&out), ["-project App.xcodeproj -scheme App -configuration Staging"]);
// Without a Podfile, a `Pods/` folder is just another project.
assert!(is_project(&root.join("Pods")));
std::fs::write(root.join("Podfile"), "").unwrap();
assert!(is_project(root) && !is_project(&root.join("Pods")));
let mut out = Vec::new();
detect(root, &mut out);
assert_eq!(args(&out), ["-workspace App.xcworkspace -scheme App -configuration Staging"]);
let mut tests = Vec::new();
super::super::xcode_test::detect(root, &mut tests);
assert_eq!(args(&tests), ["test -workspace App.xcworkspace -scheme App"]);
// A leftover workspace that sorts first: the one named after the project still wins.
std::fs::create_dir(root.join("Aardvark.xcworkspace")).unwrap();
let mut out = Vec::new();
detect(root, &mut out);
assert_eq!(args(&out), ["-workspace App.xcworkspace -scheme App -configuration Staging"]);
assert_eq!(crate::xcode::pods_workspace(root), Some(root.join("App.xcworkspace")));
// Without a workspace named after a project, the first by name.
std::fs::remove_dir(root.join("App.xcworkspace")).unwrap();
std::fs::create_dir(root.join("Old.xcworkspace")).unwrap();
assert_eq!(crate::xcode::pods_workspace(root), Some(root.join("Aardvark.xcworkspace")));
}
}
+7 -2
Переглянути файл
@@ -1,4 +1,5 @@
//! Xcode test configurations: `xcodebuild test` for each scheme whose `TestAction` has tests.
//! Xcode test configurations: `xcodebuild test` for each scheme whose `TestAction` has tests,
//! through the CocoaPods workspace when the project has one.
//! The simulator destination and the result bundle are added at launch (`xcode::prepare_test`).
use super::{ConfigExt, config};
@@ -6,11 +7,15 @@ use crate::RunConfig;
use std::path::Path;
pub(super) fn detect(root: &Path, out: &mut Vec<RunConfig>) {
// With a Podfile every scheme is built through the Pods workspace, assuming one app project
// per folder: the workspace `pod install` writes links that project's targets.
let pods = crate::xcode::pods_workspace(root);
for scheme in crate::xcode::schemes(root) {
if !scheme.has_tests {
continue;
}
let Some(container) = scheme.container.file_name().and_then(|n| n.to_str()) else { continue };
let path = pods.as_ref().unwrap_or(&scheme.container);
let Some(container) = path.file_name().and_then(|n| n.to_str()) else { continue };
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
out.push(
config(
+126 -11
Переглянути файл
@@ -1,4 +1,5 @@
//! iOS Simulators, through `xcrun simctl` (macOS only): the devices an Xcode project can run on.
//! iOS Simulators, through `xcrun simctl`, and connected iPhones and iPads, through
//! `xcrun devicectl` (macOS only): the devices an Xcode project can run on.
//!
//! Flutter projects get theirs from `flutter daemon` (`ide-flutter`), so only native Xcode
//! projects use this.
@@ -11,7 +12,8 @@ use specta::Type;
use std::path::Path;
use std::process::Command;
/// One simulator `simctl list devices available` reports.
/// One simulator `simctl list devices available` reports, or one physical device
/// `devicectl list devices` knows.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct IosSimulator {
@@ -19,10 +21,18 @@ pub struct IosSimulator {
pub name: String,
/// The runtime, as Xcode shows it: `iOS 27.0`.
pub runtime: String,
/// `Booted`, `Shutdown`, `Booting`, `Shutting Down`.
/// `Booted`, `Shutdown`, `Booting`, `Shutting Down`; for a physical device [`AVAILABLE`],
/// [`UNAVAILABLE`] (not connected) or [`DEVELOPER_MODE_OFF`].
pub state: String,
/// An iPhone or iPad rather than a simulator.
pub physical: bool,
}
/// The states of a physical device.
pub const AVAILABLE: &str = "Available";
pub const UNAVAILABLE: &str = "Unavailable";
pub const DEVELOPER_MODE_OFF: &str = "Developer Mode Off";
/// An Xcode project or workspace directly in `root`, outside a Flutter project (whose
/// `ios/Runner.xcodeproj` sits one level down and whose devices come from Flutter).
pub fn is_xcode_project(root: &Path) -> bool {
@@ -54,7 +64,8 @@ pub fn parse_list(json: &str) -> IdeResult<Vec<IosSimulator>> {
for d in list.as_array().into_iter().flatten() {
let text = |key| d.get(key).and_then(Value::as_str).map(str::to_owned);
let (Some(udid), Some(name), Some(state)) = (text("udid"), text("name"), text("state")) else { continue };
devices.push((version.clone(), IosSimulator { udid, name, runtime: label.clone(), state }));
devices
.push((version.clone(), IosSimulator { udid, name, runtime: label.clone(), state, physical: false }));
}
}
devices.sort_by(|(va, a), (vb, b)| {
@@ -67,8 +78,73 @@ pub fn parse_list(json: &str) -> IdeResult<Vec<IosSimulator>> {
Ok(devices.into_iter().map(|(_, d)| d).collect())
}
fn run(program: &str, args: &[&str]) -> IdeResult<String> {
/// The physical iOS and iPadOS devices in `devicectl list devices --json-output` output, by name.
/// Reads the fields Xcode 15 and later write, falling back to the `properties` that replace them.
pub fn parse_devices(json: &str) -> IdeResult<Vec<IosSimulator>> {
let value: Value = serde_json::from_str(json).map_err(|e| IdeError::internal(format!("devicectl list: {e}")))?;
let mut devices = Vec::new();
for d in value.pointer("/result/devices").and_then(Value::as_array).into_iter().flatten() {
let text = |old: &str, new: &str| {
d.pointer(old).or_else(|| d.pointer(new)).and_then(Value::as_str).unwrap_or_default().to_owned()
};
let reality = text("/hardwareProperties/reality", "/properties/hardware/reality");
let platform = text("/hardwareProperties/platform", "/properties/hardware/platform");
let udid = text("/hardwareProperties/udid", "/properties/hardware/udid");
if reality != "physical" || !matches!(&*platform, "iOS" | "iPadOS") || udid.is_empty() {
continue;
}
let version = d
.pointer("/deviceProperties/osVersionNumber")
.or_else(|| d.pointer("/properties/software/osVersionNumber/stringValue"))
.and_then(Value::as_str)
.unwrap_or_default();
// `tunnelState` (`connected`, `disconnected`: reachable, connects on use) or `state`.
let connection = text("/connectionProperties/tunnelState", "/properties/connection/state");
let developer_mode = d
.pointer("/deviceProperties/developerModeStatus")
.and_then(Value::as_str)
.map(str::to_owned)
.or_else(|| d.pointer("/properties/state/developerModeStatus")?.as_object()?.keys().next().cloned());
let state = if connection == "unavailable" || connection.is_empty() {
UNAVAILABLE
} else if developer_mode.as_deref() == Some("disabled") {
DEVELOPER_MODE_OFF
} else {
AVAILABLE
};
devices.push(IosSimulator {
udid,
name: text("/deviceProperties/name", "/properties/state/name"),
runtime: format!("{platform} {version}").trim().to_owned(),
state: state.to_owned(),
physical: true,
});
}
devices.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then_with(|| a.udid.cmp(&b.udid)));
Ok(devices)
}
/// The physical devices paired with this Mac, as [`parse_devices`] reads them; none when
/// `devicectl` (Xcode 15 and later) is missing or fails. `dir` picks the project's Xcode.
pub fn devices(dir: &Path) -> Vec<IosSimulator> {
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos();
let file = std::env::temp_dir().join(format!("openidea-devicectl-{}-{stamp}.json", std::process::id()));
let path = file.to_string_lossy().into_owned();
let listed = run_in(Some(dir), "xcrun", &["devicectl", "list", "devices", "--quiet", "--json-output", &path]);
let json = std::fs::read_to_string(&file);
let _ = std::fs::remove_file(&file);
match (listed, json) {
(Ok(_), Ok(json)) => parse_devices(&json).unwrap_or_default(),
_ => Vec::new(),
}
}
/// `dir`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
fn run_in(dir: Option<&Path>, program: &str, args: &[&str]) -> IdeResult<String> {
let mut cmd = Command::new(program);
if let Some(dir) = dir {
cmd.current_dir(dir);
}
prepare(&mut cmd).args(args);
let out = cmd.output().map_err(|e| IdeError::unavailable(format!("could not run {program}: {e}")))?;
if out.status.success() {
@@ -78,23 +154,26 @@ fn run(program: &str, args: &[&str]) -> IdeResult<String> {
Err(IdeError::unavailable(format!("{program} {} failed: {}", args.join(" "), stderr.trim())))
}
/// The available iOS simulators, sorted as [`parse_list`] does.
pub fn list() -> IdeResult<Vec<IosSimulator>> {
parse_list(&run("xcrun", &["simctl", "list", "devices", "available", "--json"])?)
/// The available iOS simulators of the Xcode the project at `root` uses, sorted as
/// [`parse_list`] does, then the physical devices.
pub fn list(root: &Path) -> IdeResult<Vec<IosSimulator>> {
let mut list = parse_list(&run_in(Some(root), "xcrun", &["simctl", "list", "devices", "available", "--json"])?)?;
list.extend(devices(root));
Ok(list)
}
/// Boots a simulator; returns once `simctl` has it booted.
pub fn boot(udid: &str) -> IdeResult<()> {
run("xcrun", &["simctl", "boot", udid]).map(drop)
run_in(None, "xcrun", &["simctl", "boot", udid]).map(drop)
}
pub fn shutdown(udid: &str) -> IdeResult<()> {
run("xcrun", &["simctl", "shutdown", udid]).map(drop)
run_in(None, "xcrun", &["simctl", "shutdown", udid]).map(drop)
}
/// Brings Simulator.app to the front, which shows the booted simulators.
pub fn open_app() -> IdeResult<()> {
run("open", &["-a", "Simulator"]).map(drop)
run_in(None, "open", &["-a", "Simulator"]).map(drop)
}
#[cfg(test)]
@@ -137,6 +216,42 @@ mod tests {
assert_eq!(parse_list("{}").unwrap(), []);
}
#[test]
fn lists_physical_devices_by_name_from_old_and_new_fields() {
// Trimmed `devicectl list devices --json-output` (Xcode 27): one device with the
// deprecated fields too, one with `properties` only, a simulator and a Mac.
let json = r#"{"info": {"outcome": "success"}, "result": {"devices": [
{"hardwareProperties": {"reality": "physical", "platform": "iOS", "udid": "00008110-AAA"},
"deviceProperties": {"name": "Work iPhone", "osVersionNumber": "27.3", "developerModeStatus": "enabled"},
"connectionProperties": {"tunnelState": "disconnected"},
"properties": {"hardware": {"reality": "physical", "platform": "iOS", "udid": "00008110-AAA"},
"connection": {"state": "disconnected"}}},
{"properties": {"hardware": {"reality": "physical", "platform": "iPadOS", "udid": "00008103-BBB"},
"software": {"osVersionNumber": {"stringValue": "26.1"}},
"state": {"name": "Test iPad", "developerModeStatus": {"disabled": {"mode": 0}}},
"connection": {"state": "connected"}}},
{"properties": {"hardware": {"reality": "physical", "platform": "iOS", "udid": "00008150-CCC"},
"state": {"name": "Away iPhone", "developerModeStatus": {"enabled": {"mode": 1}}},
"connection": {"state": "unavailable"}}},
{"hardwareProperties": {"reality": "simulated", "platform": "iOS", "udid": "SIM"},
"connectionProperties": {"tunnelState": "disconnected"}},
{"hardwareProperties": {"reality": "physical", "platform": "macOS", "udid": "MAC"},
"connectionProperties": {"tunnelState": "connected"}}
]}}"#;
let devices = parse_devices(json).unwrap();
let rows: Vec<_> = devices.iter().map(|d| (&*d.name, &*d.udid, &*d.runtime, &*d.state, d.physical)).collect();
assert_eq!(
rows,
[
("Away iPhone", "00008150-CCC", "iOS", UNAVAILABLE, true),
("Test iPad", "00008103-BBB", "iPadOS 26.1", DEVELOPER_MODE_OFF, true),
("Work iPhone", "00008110-AAA", "iOS 27.3", AVAILABLE, true),
]
);
assert!(parse_devices("not json").is_err());
assert_eq!(parse_devices(r#"{"info": {"outcome": "failed"}}"#).unwrap(), []);
}
#[test]
fn finds_xcode_projects_at_the_root_only() {
let dir = std::env::temp_dir().join(format!("ide-run-simulator-{}", std::process::id()));
+47 -8
Переглянути файл
@@ -1027,13 +1027,13 @@ pub fn artifact_is_current(root: &Path, base: &Path, config: &RunConfig, modules
let id_matches = selected.is_none_or(|id| recorded_id.as_deref().map(str::trim) == Some(id.as_str()));
let recorded = fs::read_to_string(base.join("artifact-path.txt")).ok().map(|s| PathBuf::from(s.trim()));
let war = match recorded.filter(|_| id_matches) {
Some(war) if war.is_file() && is_war(&war) => war,
Some(war) if (war.is_file() && is_war(&war)) || war.is_dir() => war,
_ => match find_built_war(root, Some(&module)) {
Some(war) => war,
None => return false,
},
};
let Ok(war_time) = fs::metadata(&war).and_then(|m| m.modified()) else { return false };
let Some(war_time) = newest_mtime_under(&war) else { return false };
let mut newest = newest_mtime_under(&module.join("src"));
// Web content packaged from outside `src` (a custom `warSourceDirectory`, `webResources`
// directories, a custom Gradle web app dir) also lands in the WAR — the running-session
@@ -1077,12 +1077,10 @@ pub fn deployment(root: &Path, base: &Path, config: &RunConfig, resources_only:
let recorded = fs::read_to_string(base.join("artifact-path.txt")).ok().map(|s| PathBuf::from(s.trim()));
let module = artifact_module_dir(root, config);
let war = match recorded.filter(|_| id_matches) {
Some(war) => {
if war.is_file() && is_war(&war) {
war
} else {
return Err(invalid(format!("The built WAR artifact does not exist: {}", war.display())));
}
Some(path) if path.is_file() && is_war(&path) => path,
Some(path) if path.is_dir() => return Ok(path),
Some(path) => {
return Err(invalid(format!("The built WAR artifact does not exist: {}", path.display())));
}
None => find_built_war(root, Some(module.as_path())).ok_or_else(|| {
invalid("No built WAR artifact found - build the project first, or add 'Build' to Before launch")
@@ -2417,4 +2415,45 @@ mod tests {
let error = prepare(root, &cache, &mut c).unwrap_err().to_string();
assert!(error.contains("Two deployments use the application context /"), "{error}");
}
#[test]
fn deploys_recorded_exploded_artifact_directory_directly() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let home = root.join("Tomcat Home");
fs::create_dir_all(home.join("bin")).unwrap();
fs::create_dir_all(home.join("conf")).unwrap();
fs::write(home.join("bin/catalina.sh"), "").unwrap();
fs::write(home.join("bin/catalina.bat"), "").unwrap();
archive(
&home.join("lib/catalina.jar"),
&[("org/apache/catalina/util/ServerInfo.properties", "server.info=Apache Tomcat/10.1")],
);
let server = "<Server port='8005'><Service><Connector port='8080'/><Engine name='Catalina'><Host name='localhost'/></Engine></Service></Server>";
fs::write(home.join("conf/server.xml"), server).unwrap();
let exploded = root.join("out/artifacts/EJSH_war_exploded");
fs::create_dir_all(exploded.join("WEB-INF")).unwrap();
fs::write(exploded.join("WEB-INF/web.xml"), "<web-app/>").unwrap();
let mut c = config();
for (k, v) in [
("tomcatHome", "Tomcat Home"),
("deployment", "artifact"),
("artifact", "project:EJSH:war exploded"),
("artifactName", "EJSH"),
] {
c.extras.params.insert(k.into(), v.into());
}
let cache = root.join("cache");
let base = base_dir(&cache, &c.id);
fs::create_dir_all(&base).unwrap();
fs::write(base.join("artifact-id.txt"), "project:EJSH:war exploded").unwrap();
fs::write(base.join("artifact-path.txt"), exploded.to_string_lossy().as_bytes()).unwrap();
prepare(root, &cache, &mut c).unwrap();
let runtime = PathBuf::from(&c.env["CATALINA_BASE"]);
let ctx = fs::read_to_string(runtime.join("conf/Catalina/localhost/EJSH.xml")).unwrap();
assert!(ctx.contains(&format!("docBase=\"{}\"", escape(&exploded.to_string_lossy()))), "{ctx}");
assert!(artifact_is_current(root, &runtime, &c, &[]));
}
}
Loaded 100 of 466 files, more files were not shown because too many files have changed in this diff. Show more