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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 4ba6c23f9b Merge remote-tracking branch 'origin/main' into t7002 2026-11-30 22:50:55 +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
LU XIANGRUIтаwildcatDownstairs 88b463d888 fix(debugger): let a tsx program behind a remote root run under Attach to Node.js (#6926)
On a loopback address js-debug makes the program require its child-process bootloader by a local path; behind a remote root (published container port, SSH tunnel) that path is missing, tsx's esbuild worker exits and the program waits for it forever. Attach to Node.js with a remote root, and Node.js debugging on SSH/Docker/Compose run targets, now pass autoAttachChildProcesses: false.

Closes #6925

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 18:11:42 +08:00
LU XIANGRUIтаwildcatDownstairs ac88059d0f fix(plugins): index the first 20,000 files of a large project instead of none (#6958)
Plugin navigation discovery refused the whole project above 20,000 matching files, counted out-of-scope and git-ignored files toward the cap, and showed the raw error text half translated. Discovery now keeps the first 20,000 in-scope, non-ignored files, reports total/truncated, and shows one warning naming the project and the counts.

Fixes #6940

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 18:11:27 +08:00
Waiting-Night a09c9aa9ad fix(java): navigate inherited method references to their declarations (#6953)
JDT's selection-based definition can answer the functional interface method (Function.apply) for a method reference whose method is inherited. Go to Definition on a Java method reference now asks the app-owned JDT command openidea.java.methodReferenceDefinition (java-usages 1.20.1) for the AST method binding; Lombok accessors without a source range fall back to their field or declaring type. The bundled jar is reproducible from source (SHA-256 a111a935...); tests/method-reference.py checks the command against a real JDT LS.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-30 18:06:54 +08:00
LU XIANGRUIтаwildcatDownstairs 7fef1e10a8 fix(ai-completion): say why no suggestions appear and let the model be chosen (#6936)
The plugin's optional net:localhost permission is not ticked by default, and a missing Ollama model answers 404; both only reached the IDE log. Failed requests now show one warning that says why and what to do, and a new AI Completion: Set Model command (Set Endpoint URL also asks for its value from the palette). The host answers an empty list instead of "no server supports inline completion" when a plugin offers ghost text, so the editor keeps asking while typing.

Fixes #6930

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 18:03:40 +08:00
l0ng-ai 1748c98ac8 test(agents): type the store import of the long agent form e2e (#7004)
The e2e from #7003 imported the store by a literal /src path, which pnpm typecheck rejects (TS2307); it now imports through a variable typed as the store module.
2026-11-30 17:59:41 +08:00
l0ng-ai 399ae25ab6 fix(agents): keep a long agent form scrollable above the composer (#7003)
An agent form (ACP elicitation, used by opencode for its questions) had no height limit, so a form with several fields pushed its last choices, its buttons and the composer out of view with nothing to scroll. FormCard now uses the pinned question card layout (at most half the window, scrolling within), and the pinned card shrinks when the session is shorter so the composer stays in view.

Fixes #6945
2026-11-30 17:58:47 +08:00
l0ng-aiтаCursor 3676596a60 fix(agents): keep active and pinned task order stable
Co-authored-by: Cursor <[email protected]>
2026-11-30 17:54:10 +08:00
audichuang f28dd8125b fix(deps): update yanked async-executor 1.14.0 to 1.14.1 (#6971)
crates.io yanked async-executor 1.14.0 for a use-after-free when a Waker fires during Executor::drop (smol-rs/async-executor#164). Lock-only update to 1.14.1.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:51:51 +08:00
arookieofcтаarookieofc d5f7e0a99b fix(maven): delegate launch classpath to Maven without jdtls (#6984)
With delegateBuild on a Maven module, launches without jdtls (java-analyzer) used the language server classpath, which ignores child POM exclusions. They now merge the classpath Maven resolves, as the jdtls path does, and fall back to the server classpath when the probe fails.

Fixes #5586

Co-authored-by: arookieofc <[email protected]>
2026-11-30 17:50:57 +08:00
audichuang a66c9e6d05 fix(vcs): retry git status without rename detection when a partial clone cannot fetch a blob (#6987)
In a blobless partial clone rename detection needs a staged blob it cannot fetch (Restricted Mode sets GIT_NO_LAZY_FETCH, or the promisor is unreachable) and git status fails. Status retries once with --no-renames when git reports the promisor remote.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:50:44 +08:00
audichuang 59bcf7eac5 fix(refactor): keep external changes when a file move's reference edits are rejected (#6990)
FileMoves::perform restored its pre-edit snapshots when the reference edits were rejected, overwriting a change another program wrote after the snapshot. apply_edit is transactional and leaves nothing behind on error, so a rejected edit is now returned without a restore; a failed move still rolls back the applied edits.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:50:29 +08:00
LU XIANGRUIтаwildcatDownstairs fe21c67537 fix(debugger): do not open lldb-dap's disassembly pseudo paths as files (#6961)
lldb-dap reports frames without debug info with a sourceReference and a pseudo path such as libswiftCore.dylib`swift_willThrow, which opened as a missing file. An absolute path that does not exist on a referenced source is dropped, so the stop selects the first frame with source.

Closes #6960

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 17:50:10 +08:00
audichuang c085f52b59 fix(editor): paste an image from the Markdown editor's context menu without WebKit's Paste callout (#6994)
On macOS the context-menu Paste in a Markdown editor called execCommand(paste), which shows the WebKit Paste callout. Images and copied image files are read through the backend instead; text takes the native path.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:43:14 +08:00
Bin 0104ed63c1 fix(project-tree): open external files on double-click only (#6993)
Single-click in the project tree opened files associated with an external application. Those now open on double-click only.

Co-authored-by: ffgenius <[email protected]>
2026-11-30 17:42:57 +08:00
Chris-young42таChris-young42 a441b2a906 fix(java): remove extra spaces from annotation completions (#6989)
JDT LS appends a space to annotation completions; it is dropped when nothing follows that needs a separator, so no trailing whitespace after @Override or space before the parenthesis.

Co-authored-by: Chris-young42 <[email protected]>
2026-11-30 17:42:42 +08:00
audichuang c4f7fec86c fix(build): keep output the channel delivers after the build result (#6988)
Tauri delivers channel messages over 8 KiB through an async fetch and holds later ones back, so output can arrive after the command result. Output and step events of the latest build are still applied after it finished, until another build takes the window.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:42:28 +08:00
audichuang 37a8aae018 fix(vcs): keep focused and unsaved all-in-one diff blocks mounted while the view has no height (#6983)
With no height (a maximized tool window over the diff) the virtualizer rendered no range and unmounted the focused and unsaved blocks, saving an unsaved index edit. The view now reports at least 1 px and keeps the last measured block sizes while hidden.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:42:16 +08:00
LU XIANGRUIтаwildcatDownstairs acc48a4816 fix(run): clear a selected test's output with Clear All (#6982)
A selected test node shows the output captured on that node, which Clear All did not touch. Clear All now drops captured test output as well; statuses and the tree stay.

Closes #6975

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 17:42:00 +08:00
audichuang 8301326289 fix(ui): remeasure the custom scrollbar when its content grows without the scroller resizing (#6973)
The custom scrollbar observed only the scroller, whose size does not change when its content grows (a Markdown preview reflowing after a width change). It now also observes the scroller children, re-observing them when they are replaced.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:41:43 +08:00
sonnartliao 4c71299745 fix(editor): resolve C declarations without include metadata (#6959)
Without a compilation database clangd leaves nested includes unresolved or answers with the call site itself. For C-family files an empty or self-only answer falls back to syntax and the project index (including identifiers in macro bodies), Go to Implementation from a header finds the source definition, and member access is never guessed by bare name.

Co-authored-by: sonnartliao <[email protected]>
2026-11-30 17:41:27 +08:00
Jimmy Song 08249ca5fd fix(viewers): reload preview images when files change on disk (#6952)
Preview image data URLs were cached by path forever. The cache now drops entries on fsChanged and open Markdown and reStructuredText previews reload the affected images.

Co-authored-by: zhiai007 <[email protected]>
2026-11-30 17:41:09 +08:00
Waiting-Night edd6746439 fix(editor): stop type hierarchy searches from library gutter markers (#6951)
Library gutter markers asked jdtls for inheritors of every visible class, which on a JDK interface ran a full type hierarchy search and timed out. Library sources keep super-method markers but ask for no inheritors; Go to Implementation still answers.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-30 17:40:54 +08:00
LU XIANGRUIтаwildcatDownstairs 695424beb2 fix(editor): reopen restored library source tabs read-only (#6950)
The library-source mark lived only in memory, so a tab restored after a reload opened the same file editable. The editor session now saves the mark and restores it before the documents open.

Closes #6947

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 17:40:41 +08:00
LU XIANGRUIтаwildcatDownstairs 9943d71d02 fix(editor): show no diagnostics in library sources (#6946)
Language servers publish errors for files they generate or read outside the project (sourcekit-lsp parse errors in its .swiftinterface). Library sources open read-only, so their diagnostics are dropped from the editor and the Problems view.

Closes #6943

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 17:40:25 +08:00
l0ng-ai e03c5507f7 ci: publish a nightly prerelease of main every day (#6962)
nightly.yml builds main at 18:00 UTC, when it has moved since the last
nightly, as v<next patch>-nightly.<date>: a tag on a commit over main that
only sets the version (scripts/nightly-prepare.ts), built and published by
release.yml, which can now be called with `nightly: true` (notes from the
previous nightly; no official plugins, CNB mirror or Homebrew cask).

Nightly apps update from the rolling `nightly` release, which holds the
newest nightly's latest.json, and skip the CNB mirror, which carries only
stable releases. Stable apps keep reading releases/latest, never a
prerelease. The MSI gets a numeric version (last release + run number),
and the newest 14 nightlies are kept.
2026-11-30 15:55:50 +08:00
l0ng-ai 745099feaa chore: v0.1.56 2026-11-30 15:07:20 +08:00
l0ng-ai 6894d0a4e3 fix(web): declare the GTK dialog probe and hotkey probe as always allowed in the web shell (#6967)
file_dialog_needs_gtk and system_probe_hotkeys are trust = always on the desktop, but the web shell table still declared them Trusted, so commands::tests::web_shell_commands_match_the_desktop_declarations failed on every Rust job on main.
2026-11-30 15:06:25 +08:00
l0ng-ai f80be658ea fix(run-targets): apply a published ports edit that hasn't left the field (#6966)
Published ports and the other list fields of a run target were stored only on blur, so OK pressed with Enter, or applying the settings while the field still had focus, dropped the edit. The list is now staged on every change; the text stays as typed while the field has focus.
2026-11-30 15:01:45 +08:00
l0ng-ai 1c377b7f66 fix(run): show configuration types in the UI language in Add New Configuration (#6965)
The Add New Configuration type picker and the Edit Configurations Templates list showed each type's English label while the form showed the translation. Rows now carry the translated label, which the list also sorts and searches by.
2026-11-30 15:01:28 +08:00
LU XIANGRUIтаwildcatDownstairs 093cf6fdf8 feat(cpp): switch between a header and its source file (#6928)
A Switch Header/Source action (F10; Alt+O in the VS Code keymaps) opens the counterpart of the current C, C++, Objective-C or Objective-C++ file. It asks clangd with textDocument/switchSourceHeader (new lsp_switch_source_header, cancellable), so headers in include/ and sources in src/ are found; without clangd or an answer it opens a project file with the same stem and a counterpart extension, as Related Symbol does.

Closes #6927

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

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 12:00:32 +08:00
LU XIANGRUIтаwildcatDownstairs 9b578c2fad feat(run): debug Node.js on SSH, Docker and Compose run targets (#6919)
Debug on a Node.js configuration or a .js / .ts file run whose run target is SSH, Docker or Compose now debugs the program there, extending the Python flow. A js-debug configuration starts node with --inspect-brk on a free port (0.0.0.0 inside the container, published on this machine's loopback only; the host's loopback over the existing SSH forward). The run prints the project folder on the target as a system line, which the frontend reads to map sources before attaching js-debug. tsx is refused for now (it hangs once js-debug attaches); other programs get an error naming the fix.

Closes #6901

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

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 11:52:59 +08:00
LU XIANGRUIтаwildcatDownstairs f5bb97babd feat(js): CSS completion and diagnostics in styled-components and emotion templates (#6917)
Adds the managed tool typescript-styled-plugin (@styled/typescript-styled-plugin, pinned, hosted by vtsls). ide_sdk::apply::configure_styled adds it to vtsls' globalPlugins when it is installed and a package.json at, above or below the server root depends on styled-components or emotion; a tsconfig that declares the plugin keeps one copy. Opening a script that imports one of those libraries offers the install once per project and session. The bounded walk below the root is now shared with CSS Modules Kit.

Closes #6900

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

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 11:49:27 +08:00
l0ng-ai e23088d558 fix(vfs): don't cache ignore rules read before an invalidation (#6929)
GitignoreStack::matcher_for read a directory's ignore files outside the cache lock and stored the matcher afterwards, so a watcher-thread lookup racing a command that rewrote .gitignore and invalidated could leave the older rules cached; the next listing then missed the new entry. Invalidations now bump a generation counter under the cache lock and a lookup stores its matcher only when none happened since it started reading. This made rpc::serves_projects_files_documents_search_and_runs fail intermittently on Windows.
2026-11-30 11:48:07 +08:00
LU XIANGRUIтаwildcatDownstairs 7279f515db feat(xcode): run macOS app schemes on the Mac (#6918)
Xcode run configurations only ran iOS apps on the Simulator. The run now reads the scheme's build settings without a destination and, when its first application supports macOS but not the iOS Simulator (or the Simulator field is macos), builds with -destination platform=macOS and execs the app's executable, so its output reaches the Run console and Stop's SIGINT reaches it; NSUnbufferedIO=YES is set as Xcode does. The destination choice is shared by Clean Build Folder, which now cleans a macOS app's build for the Mac too.

Closes #6907

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

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 11:36:02 +08:00
LU XIANGRUIтаwildcatDownstairs 710d120689 feat(swift): debug SwiftPM executables from swift build's bin path (#6914)
Debug on a SwiftPM executable configuration launched lldb-dap on a hardcoded .build/debug/<product>, which misses -c release, --scratch-path / --build-path and the .build/out/Products layout of recent toolchains. The launch now carries a swiftpm key (product and the swift run build options), and ide-dap resolves program with swift build <options> --show-bin-path, like the cargo key. The Swift docs describe the SwiftPM run configurations and Debug.

Closes #6913

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

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 11:33:15 +08:00
JunChang Peng 38709947fe feat(database): give a table's tab its data source's colour (#6916)
A table's EditorInput has no path, so the path-keyed file decorations that tint console tabs never reached it. Editor kinds can now supply tabTint, read next to tabTrailing and refreshed by notifyTabTintsChanged when a source's colour changes; the table kind answers with its source's colour, and the data view's toolbar carries it too. A selected tinted tab now shows the colour at full strength instead of mixing it with the selection background, and inactive tinted tabs are dimmed.

Closes #6915

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

Co-authored-by: junchangpeng <[email protected]>
2026-11-30 11:31:00 +08:00
JunChang Peng d9fbb19787 feat(database): show a table's DDL from the data view (#6909)
The data view's toolbar gets a DDL button that opens the table's definition through the same openDdl the tree's Go to DDL uses, so checking an index or constraint no longer means leaving the rows. It is disabled while the DDL loads, for custom JDBC sources (no vendor DDL) and for catalog-qualified tables.

Closes #6910

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

Co-authored-by: junchangpeng <[email protected]>
2026-11-30 11:30:32 +08:00
LU XIANGRUIтаwildcatDownstairs 6aa613d4ec fix(editor): drop the unused gutter icon group re-exports that fail knip (#6920)
prefs.ts re-exported GUTTER_ICON_GROUPS and GutterIconGroup from ./localAppearance, but their users import localAppearance directly, so pnpm knip failed on main since #6912.

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

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 11:26:32 +08:00
LU XIANGRUIтаwildcatDownstairs 60ef498deb feat(run): add Clean Build Folder and Delete DerivedData for Xcode schemes (#6902)
Xcode projects had no way to clean a scheme's build or clear its DerivedData. Clean Build Folder runs xcodebuild clean in the Run tool window with the same flags as an xcode run. Delete DerivedData resolves the project's <Name>-<hash> folder from xcodebuild -showBuildSettings (never a guessed hash) plus the IDE's own run builds, asks, moves them to the Trash and restarts sourcekit-lsp. Both are in a new Build › Xcode submenu, Find Action and the .xcodeproj / .xcworkspace context menu; Flutter's and Xcode's build submenus now come from one dynamic_submenu table in both menu renderers.

Closes #6897

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

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 11:25:40 +08:00
LU XIANGRUIтаwildcatDownstairs 719b73ecd9 feat(xcode): flag new source files an Xcode project doesn't build (#6888)
xcodebuild compiles only the files a target lists, so a source file created or renamed in the IDE inside a classic .xcodeproj group was silently left out of the build. After file operations in the IDE (one check per burst), an XcodeGen or Tuist project gets an offer to regenerate it, and a classic project without synchronized folders gets a warning naming the files project.pbxproj doesn't list, with Open in Xcode. Regenerate Xcode Project is also in Find Action and in the context menus of project.yml / Project.swift. Names are matched as whole file names, and file operations without source files skip the check.

Closes #6887

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

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 11:20:17 +08:00
l0ng-ai 6c3284c300 fix(settings): change the local data directory without an open project (#6921)
The Caches settings commands were trusted-only, so the welcome window could neither show the current location nor apply a custom directory, though the directory is an app-wide setting. Reading it now runs everywhere and changing it runs outside Restricted Mode. The Linux GTK file chooser and the global hotkey probe had the same gate and are now always allowed.

Fixes #6886
2026-11-30 11:15:49 +08:00
Bert Verhelstтаbertyhell 69cec11761 ci: run the release jobs that read secrets in the release environment (#6873)
The signing keys and tokens are repository secrets, readable by any workflow on any branch, and secrets: inherit hands them all to the called release workflows. The jobs that read a secret other than GITHUB_TOKEN now name environment: release (plugins, plugin-keys, build, server-signatures, mirror, cask). secrets: inherit stays until the secrets move into the environment, so releases build and sign as before; the environment is created on first use with no rules. Refs #6701.

Co-authored-by: bertyhell <[email protected]>
2026-11-30 10:52:02 +08:00
l0ng-ai 6c76cfd316 fix(editor): keep the run gutter from loading the editor preferences (#6912)
runGutter, which the Language smoke loads, imported gutterIconsOn from cm/prefs, pulling about 40 editor modules into the smoke inputs and failing scripts/smoke-paths.test.ts on main. The gutter icon groups and the per-editor appearance override move to cm/localAppearance, which prefs re-exports; the gutter providers import it directly and language-smoke.yml lists the new file.
2026-11-30 10:51:33 +08:00
audichuang 66496221b9 fix(ci): run Language smoke for every language when ide-http changes (#6905)
Since #6893 ide-tools depends on ide-http on macOS, so ide-http is an input of the Language smoke, but the Changes step still listed it as unused and scripts/smoke-paths.test.ts failed on main. Removes ide-http from that list.

Co-authored-by: audichuang <[email protected]>
2026-11-30 10:49:13 +08:00
l0ng-ai e9f3aef5ae fix(markdown): keep the preview painted while scrolling (#6908)
Trackpad scrolling in the Markdown preview could leave a large part of it blank until the next scroll. The preview moves itself on each wheel event with scrollBy, and in WebKit a run of scrollBy calls can leave the compositor at an older, never-painted offset than the page's. Setting scrollTop/scrollLeft keeps them in step; the source editor's large wheel jumps and the diff divider's wheel did the same and now set offsets too.

A fenced code block overflowing by a pixel no longer counts as a vertical scroller, and a nested scroller keeps the wheel only while it can still move in that direction, so scrolling no longer stops over code blocks.
2026-11-30 10:31:45 +08:00
LU XIANGRUIтаwildcatDownstairs 4ca46032c4 feat(run): debug Xcode run configurations on the iOS Simulator (#6889)
Debug on an Xcode run configuration builds and installs the app as Run does, launches it suspended on the iOS Simulator (simctl launch --wait-for-debugger) and attaches lldb-dap to its pid, so breakpoints in the app's Swift sources hit while its output stays in the Run console; stopping the debug session stops the run. simctl holds back its <bundle id>: <pid> line when stdout is a pipe, so the launch script prints it once the suspended process under the installed bundle appears. Detected and new Xcode configurations get debugAdapter lldb-dap. Closes #6885.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 10:27:53 +08:00
Muuтаmuutot 8d8f66dfe5 feat(editor): add active-editor appearance toggles (#6891)
Show Line Numbers, Show Whitespaces, Show Gutter Icons and Show Indent Guides can be toggled for the active editor without changing the global setting. Overrides live in each CodeMirror EditorState, so split panes on one document can differ and untouched editors keep following the settings; line numbers, whitespace marks, indent guides and gutter providers reconfigure through one appearance path, and a local Gutter Icons override can enable providers even when the global setting is off. The toggles are in View > Active Editor, with IdeaVim aliases and unbound keymap entries.

Co-authored-by: muutot <[email protected]>
2026-11-30 10:26:06 +08:00
LU XIANGRUIтаwildcatDownstairs 5229e44a9c feat(swift): resolve and update Swift packages from the IDE (#6899)
Resolve Swift Packages and Update Swift Packages run swift package resolve / update in the Run tool window from the folder of Package.swift, like Go Mod Tidy, using the swiftpm run kind. They are in Find Action (category Swift) and on a single Package.swift in the Project view, editor and tab menus; when the run ends, run configurations and external libraries reload. sourcekit-lsp already reloads on Package.resolved changes through its file watcher, so no restart is added. Documented on the Swift page.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 10:17:00 +08:00
audichuang 7be55e4eec fix(tools): follow the macOS PAC script for tool downloads in Auto proxy mode (#6893)
Tool downloads run through the system curl, which in Auto proxy mode only got the manual macOS proxy from Matcher::from_system(), never the PAC script, so on a PAC-only network language-server installs went direct while the rest of the IDE followed the PAC.

Http::base now asks the same PacResolver the HTTP client uses (ide_http::system_pac_route, evaluated inline with the per-host cache) and passes its proxy to curl as --proxy; while the script loads or fails it answers with the manual proxy, as before. Linux and Windows build the same command as before.

Co-authored-by: audichuang <[email protected]>
2026-11-30 10:14:57 +08:00
l0ng-ai ce206f74af fix(deps): update curve25519-dalek to 5.1.0 (RUSTSEC-2026-0620) (#6903)
cargo deny failed on RUSTSEC-2026-0620: curve25519-dalek 5.0.0, pulled in by ed25519-dalek for extension signature checks in ide-extension, has an AVX-512 backend bug in scalar multiplication. Our builds do not enable that backend; lock-only update to the fixed 5.1.0.
2026-11-30 10:13:10 +08:00
Muuтаmuutot 3c6bc1b29f feat(editor): zoom Quick Documentation with the mouse wheel (#6883)
With Editor > General > Change font size with Ctrl/Command+Mouse Wheel enabled, Ctrl/Cmd+wheel over Quick Documentation changes the documentation font size. One persisted zoom (-6..36 px) is shared by the hover, the F1 popup and the Documentation tool window, and the focused Increase/Decrease/Reset Font Size actions go through the existing font-zoom surface registry. Only documentation typography scales; editor text, toolbar controls and popup scrolling are unchanged.

Co-authored-by: muutot <[email protected]>
2026-11-30 09:12:45 +08:00
audichuang f9a8ad3fa7 fix(editor): do not recreate a file deleted outside the IDE on autosave (#6884)
A dirty buffer whose file another program deleted (git switch, git stash -u, a build clean) was written back by the next autosave, because check_disk_conflict only ran when fs::metadata succeeded.

A missing file (NotFound) now goes through the existing disk-conflict path: autosave refuses and the buffer stays dirty. DocDiskConflict carries deleted, so the notice says the file was deleted and offers no Load Changes from Disk; an explicit save recreates the file and clears the conflict.

Co-authored-by: audichuang <[email protected]>
2026-11-30 09:10:13 +08:00
audichuang 3d3ed6e120 fix(editor): update the status bar when a file's encoding or line ending changes (#6882)
When another program rewrote a clean open file in a different encoding or line ending, Documents::reload_from_disk re-detected and stored the new values but nothing sent them to the editor's DocMeta, so the status bar kept the old encoding and line separator until the tab was reopened; Load Changes from Disk had the same gap for the BOM.

Adds IdeEvent::DocEncoding (modelled on DocLanguage): both reload paths emit it through one helper only when the encoding, BOM or line ending changed, and the DocumentManager updates the meta.

Co-authored-by: audichuang <[email protected]>
2026-11-30 08:00:08 +08:00
Deng Liuтаdengliu 61dbb2f863 docs(agents): add agent resources and lifecycle guide (#6875)
Adds an English and Chinese guide under Guide > AI explaining how plugins, memory, MCP, tools and skills interact across an agent task, and what enters the LLM context window: plugin mcpTools reach the model through the built-in server's tools/list while plugin code stays out of the prompt. Linked from the Agents guide. The walkthrough video was left out to keep large binaries out of the repository.

Co-authored-by: dengliu <[email protected]>
2026-11-30 07:51:43 +08:00
Deng Liuтаdengliu 79e5ddda3e feat(agents): inspect built-in openidea MCP tools in MCP Connections (#6878)
The built-in openidea card in Settings > Agents > MCP Connections is now expandable like the other servers: it shows the tool count, status, stdio command and HTTP endpoint, lists the core and enabled plugin-contributed tools, and the search box filters them.

A read-only mcp_server_tools host command (trust = always) lists them through the same tools_for helper as Registry::tools, so Restricted Mode filtering and plugin tools match what agents see, while external server probing stays trusted-only. Tool descriptions are clamped to two lines with the full text in a tooltip.

Co-authored-by: dengliu <[email protected]>
2026-11-30 07:50:28 +08:00
Elmir Abkerimov 53cc0059a4 perf(macos): unlock 120Hz scrolling in WKWebView (#6874)
WebKit enables PreferPageRenderingUpdatesNear60FPSEnabled by default, throttling rendering updates (requestAnimationFrame, scrolling, viewport updates) to about 60 Hz on ProMotion and other high-refresh displays. The webview configuration now disables it through the private feature API (_features, falling back to _experimentalFeatures on macOS 12.0-13.2), sharing one helper with the TextInputClientSelectionUpdatesEnabled workaround.

To keep frames within the shorter budget: the window-level wheel listener stays passive unless a wheel shortcut is bound (none by default), horizontalScrollHold skips unchanged writes, and the overview lane moves its thumb with a transform and folds the pass-through hit test into its measure pass.

Co-authored-by: w4terlaw <[email protected]>
2026-11-30 07:40:26 +08:00
audichuang 6c945c73ad fix(github): look the pull request up again when the review repository's upstream changes (#6880)
When the review repository is not the VCS store's branch root, connectedBranch() reports upstream: null, so a change of that branch's upstream under the same HEAD (git branch -u, git push -u) never triggered a new pull request lookup.

For such a root each VCS refresh re-reads branch.<head>.remote/.merge and looks the pull request up again only when they differ from the last lookup; the change is recorded when read so a later reset also supersedes a late answer. The single-repository path is unchanged and no GitHub request is sent while the config is unchanged.

Co-authored-by: audichuang <[email protected]>
2026-11-30 07:26:25 +08:00
audichuang 51b93d25bd fix(github): check out the Review Mode branch in the repository the sync check uses (#6879)
"Update Branch to Enable Review Mode..." ran gh pr checkout in connectedRoot() while the sync check and pull request lookup use reviewRoot() (#6622), so with a worktree or a second clone selected the update acted on another repository and could fail with "refusing to fetch into branch checked out at ...".

checkoutPullRequest takes an optional root (default connectedRoot(), so other callers keep theirs); updateReviewBranch captures reviewRoot() before the details reload so a selection change during the reload cannot move the checkout.

Co-authored-by: audichuang <[email protected]>
2026-11-30 07:25:46 +08:00
l0ng-ai c0b5789dd6 fix(run): rebuild the WAR before redeploying a copied Tomcat update (#6871)
Update classes while debugging copies the compiled outputs into the exploded
deployment, then HotSwaps. When HotSwap could not apply the change (a new
class or method) it fell back to a redeploy, which explodes the recorded WAR
into the deployment again; that WAR predates the change, so the old classes
came back and classes added since were removed while the IDE reported
"Application updated". The WAR is now rebuilt before that redeploy.

Refs #6603
2026-11-30 02:05:05 +08:00
l0ng-ai 016240ac1b fix(windows): open one Settings window when it is requested in a burst (#6870)
The auxiliary-window commands are async, so several requests for the same
window (Ctrl+Alt+S pressed quickly or held) could all pass the already-open
check before the first window registered; five parallel requests opened
five Settings windows for one project window. The window's creation is now
claimed before the check, and a request arriving during the build leaves
its launch for that window and returns.

Fixes #6630
2026-11-30 01:36:01 +08:00
l0ng-ai 97598641be fix(agents): keep the reader's place when streamed content reflows above or below (#6863)
Scrolled away from the end while a reply streams, the view jumped when rows
changed height (a reasoning folding once the next tool call arrives, a lone
call joining a folded run): WebKit has no scroll anchoring. Away from the
end, Stream now keeps the row at the top of the view in place after every
render, row resize and scroll; content that gets shorter below leaves blank
room (now an ::after spacer) instead of pulling the view down. Following
the end is unchanged.
2026-11-30 01:25:34 +08:00
l0ng-ai f220ceb117 feat(data-dirs): portable installs with an openidea.properties file (#6869)
An openidea.properties next to the executable (the AppImage file on Linux,
the folder holding OpenIDEA.app on macOS) sets the OPENIDEA_CONFIG_DIR,
OPENIDEA_DATA_DIR, OPENIDEA_LOCAL_DATA_DIR and OPENIDEA_LOG_DIR variables at
start, so a portable install needs no environment. Relative paths are taken
from the file's folder and the environment wins. Applied first thing in main
so every directory and child process sees the same locations.

Closes #6207
Closes #6437
2026-11-30 01:06:22 +08:00
l0ng-ai 263c95738e fix(test-runner): show the run's time when the runner reports no total (#6868)
The test status bar only showed a duration from the runner's summary line.
JUnit runs through the IDE's runner report each test's time but no total,
so the bar showed none. TestResults.totalDurationMs() now falls back to the
tests' summed time; the status bar and the export share it.
2026-11-30 00:55:13 +08:00
l0ng-ai 3a07f05a75 fix(endpoints): keep every Spring controller in large multi-project trees (#6867)
The Spring route source scan kept every Java/Kotlin file containing
"Mapping" (MapStruct mappers, DTOs, @Mapping) and stopped at 1024 files.
In a large multi-module backend those filled the budget and, with the
parallel walk, which controllers survived varied between runs.

Only files naming a request mapping annotation and a controller or Feign
client are kept now (what the endpoint index reads), the caps are raised
to 8192 files / 128 MB, and hitting a cap is logged.
2026-11-30 00:48:16 +08:00
Muuтаmuutot 81d0ada2f3 feat(vcs): maximize selected Git Log commit messages (#6864)
Adds Maximize Commit Message after Copy Revision Number in the Git Log and
File History commit menus and on the commit details toolbar. It opens a
resizable, scrollable dialog with the full message and metadata of every
selected commit (read-only commits included); disabled without a
selection.

Co-authored-by: muutot <[email protected]>
2026-11-30 00:45:16 +08:00
Muuтаmuutot 04bea8718e feat(vcs): refresh Git Log with the Refresh shortcut (#6862)
Adds the Git Log Refresh action (Vcs.Log.Refresh) for Git Log and File
History, bound to the Refresh shortcut (Ctrl+F5 on Windows/Linux, Cmd+R on
macOS) and scoped to the log so other bindings keep the key elsewhere. The
toolbar button and the action share one refresh path that keeps the current
log while reloading, invalidates commit-detail caches for the visible
repositories and is ignored while the log is already loading.

Co-authored-by: muutot <[email protected]>
2026-11-30 00:36:23 +08:00
l0ng-ai 7f32d04b19 feat(plugins): open files as text and contribute to Open In (API 1.19) (#6866)
Plugins can open a file in the built-in text editor even when a custom
editor claims it (workspace.editor open-as-text, SDK open_editor_as_text),
and commands can contribute to the Open In submenu (openIn menu location,
file as the argument, no submenus). Docs, versioning table and rebuilt
components included.

Fixes #6852
Fixes #6853
2026-11-30 00:32:41 +08:00
Muuтаmuutot 4a714b2eff feat(editor): speed-search navigation bar children (#6855)
Typing in a Navigation Bar child list (the floating Alt+Home bar and the status-bar breadcrumbs) filters its rows with fuzzy matching and highlights the matched characters; Backspace edits the query, Escape clears it before closing, and Enter opens the selected match. The query resets when the list moves to another folder or back to a parent.

The typed text shows in a row above the list, red when nothing matches, as in the project tree's speed search.

Co-authored-by: muutot <[email protected]>
2026-11-30 00:07:33 +08:00
l0ng-ai 83b273ec4c fix(editor): keep a horizontally scrolled view in place while line-end hints refresh (#6865)
Line-end hints (inline blame, line-end lenses, plugin messages) draw from a zero-width anchor: they widen the scroll range but not the content, and most leave on an edit and return a moment later. While one was away the range shrank and the browser clamped scrollLeft, so a horizontally scrolled editor jumped sideways on every keystroke.

A 1px spacer at the visible right edge, moved on every scroll and geometry change, keeps the range from shrinking under the view without adding scroll room. Covers every line-end hint, not only blame.

Fixes #6624
2026-11-30 00:02:14 +08:00
Muuтаmuutot 37e2e250e9 feat(vcs): focus Git Log text filter with Ctrl+L (#6861)
Adds Focus Text Filter (Vcs.Log.FocusTextFilter, Ctrl+L) to Git Log and File History: from the commit list it focuses the message filter, from inside the filters toolbar it returns to the commit list.

The action is ordered ahead of the Agents input (also Ctrl+L in the Windows keymap), which otherwise took the key whenever an agent task was on screen, and it leaves popups their own Ctrl+L. Eclipse keymaps share Go to Line's Ctrl+L with it; the title has a zh entry.

Co-authored-by: muutot <[email protected]>
2026-11-29 23:48:08 +08:00
l0ng-ai 16c2613cc0 fix(agents): harden the GitHub skill installer
- Resolve each symlink target through the other symlinks of the skill,
  folding case, and reject trees that place entries beneath a symlink.
  Installs create directories without following symlinks and re-check
  every created link on disk before the skill is moved into place.
- Scan every form of an `allowed-tools` value (block scalars, flow and
  block sequences, continuation lines, quoted keys, aliases, escapes)
  for shell grants instead of only inline values and `-` lists.
- Install exactly the tree the preview showed: the request carries the
  preview's tree SHA and the installer fetches that tree, so commits
  pushed to the ref after review are not installed. Downloaded blobs
  are checked against their Git object id.
2026-11-29 23:21:59 +08:00
arookieofcтаarookieofc e40a03c373 fix(run): shorten long Java debug launch command lines (#6802)
Run launches already shorten long Java command lines, but Debug through java-analyzer sent the full classPaths list, and the Kotlin debuggee was spawned with java -cp and the whole classpath, so large JDK 8 Spring Boot projects on Windows failed with os error 206. java-analyzer launches now pack an oversized classpath into a temporary manifest-only pathing jar (works on JDK 8 and later), the Kotlin debuggee goes through the same shortening as Run, and the session removes its temporary files when it stops.

Fixes #4733

Co-authored-by: arookieofc <[email protected]>
2026-11-29 22:54:43 +08:00
l0ng-ai cf6d8fa510 fix(remote): download the server from the update source and verify its signature (#6860)
Remote development fetched openidea-server from GitHub only, even when the app updates from the CNB mirror. The server now comes from the configured update source first, then the other host. Releases sign every server archive with the updater key in a dedicated server-signatures job, the only one given the key, and the app verifies the archive against the updater public key from tauri.conf.json, so a signed archive is trusted from either host. Releases without signatures keep the GitHub download checked against its .sha256. When a signature exists but no host serves a matching archive, the download fails instead of falling back to an unverified binary.

Fixes #6747
2026-11-29 22:54:25 +08:00
arookieofcтаarookieofc 73ee2117e9 fix(maven): run plugin prefix goals under the plugin's coordinates (#6807)
A goal typed or picked as prefix:goal (spring-javaformat:apply) reached mvn verbatim, and Maven only resolves prefixes of its default plugin groups when the plugin metadata is missing from the repositories, so plugins such as io.spring.javaformat failed with No plugin found for prefix. Goals whose prefix matches a plugin of the project's effective model (inherited plugins included) now run as groupId:artifactId[:version]:goal, keeping @execution; flags and their values, phases, full coordinates and unknown prefixes stay as typed. The configuration name keeps the prefix form.

Fixes #5570

Co-authored-by: arookieofc <[email protected]>
2026-11-29 22:52:46 +08:00
l0ng-ai 1ec634619c feat(plugins): read HTTP responses as they arrive with net.fetch-stream (#6859)
Plugin API 1.19 adds net.fetch-stream: it returns a response-stream once the headers arrive, and the body is read piece by piece with a timeout (read returns nothing with done=false when no bytes came in time). It applies the same grants, net:ask, secrets, body limit and redirect checks as fetch, which now shares the request builder; at most eight streams per plugin, closed on resource drop or plugin stop. The SDK adds host::fetch_stream, ResponseStream and an incremental text/event-stream parser (ResponseStream::events), with mock support; components are rebuilt for the new WIT.

Fixes #6844
2026-11-29 22:49:50 +08:00
l0ng-aiтаrohitdanda 18860f5f98 ci: give signing secrets only to the steps that sign, and pin actions by SHA (#6854)
The updater signing key and Apple credentials were exported job-wide through GITHUB_ENV, so every later step in the release build (dependency installs, third-party actions) could read them. They now reach only the steps that sign: a signed tauri-action build when the updater key is configured (an unsigned build otherwise, since an empty key still counts as set), DMG notarization, and the portable zip. All third-party actions across the workflows are pinned to commit SHAs with their release in a comment, and Dependabot keeps the github-actions ecosystem current with weekly grouped updates.

Refs #6142, #6701

Co-authored-by: rohitdanda <[email protected]>
2026-11-29 22:46:18 +08:00
l0ng-ai 8e9c02cae6 test(e2e): expect editable artifacts in a project without a build tool (#6857)
#6834 made Project Structure › Artifacts editable when the project has no Maven or Gradle build; the settings spec still expected a disabled JAR button. It now checks the button is enabled and the Maven/Gradle note is absent.
2026-11-29 22:45:25 +08:00
l0ng-ai 28b879c668 fix(run): show the iOS Simulator chooser only in confirmed Xcode projects (#6856)
The chooser appeared whenever listing simulators failed, so Restricted Mode windows, hosts without the command and the browser e2e harness showed "Simulators unavailable" in every project's toolbar (breaking the toolbar layout e2e specs on main). A failure is now shown only after a listing has confirmed an Xcode project; later refresh failures still appear in the chooser.
2026-11-29 22:44:10 +08:00
Deng Liuтаdengliu 19aef36354 feat(agents): add Agent Memory settings and a per-session memory picker (#6826)
Adds Settings › Agents › Memory and a Session Memory picker (/memory, /memories, the composer + menu and the context meter link). They list each agent's own instruction files, path-scoped rules and auto-memory notes: AGENTS.md, CLAUDE.md and .claude/rules, .github/copilot-instructions.md and .github/instructions, .cursor/rules, GEMINI.md, and the Claude Code, Codex and Hermes auto-memory folders.

Per-file modes (Auto / Always / Off) and the auto-memory policy (Inherit / Read & Write / Read Only / Off) are stored in settings.toml at user or workspace scope and never edit tracked files. Workspace entries load only in trusted projects. Each driver receives the policy natively: Claude Code through --settings and --add-dir, Codex through its memories config and /memories, GitHub Copilot through excludedTools and the system message, and Hermes through config.yaml. A file set to Always is staged into other agents' sessions. Auto-memory notes can be promoted into the workspace AGENTS.md, and an idle session restarts when a memory policy changes.

Groups of the same agent are titled by scope, for example Claude Code (User) and Claude Code (Auto Memory).

Closes #6810

Co-authored-by: dengliu <[email protected]>
2026-11-29 22:38:20 +08:00
Muuтаmuutot c8efb2917d feat(bookmarks): select and rename lists in the popup (#6849)
List headers in the Bookmarks popup are now selectable rows; F2 on one opens the list name dialog, while file section rows stay non-selectable and are skipped by the keyboard. The popup claims F2 while its list is focused so the global Rename File shortcut does not take it.

Co-authored-by: muutot <[email protected]>
2026-11-29 22:28:40 +08:00
Vladislav Kuzmin 94ddb1807d fix(ci): cache Maven launch classpath artifacts (#6565)
The Rust job's Maven cache only held what resources:resources and compiler:compile resolve,
so the Java launch and rebuild tests on GitHub-hosted runners missed artifacts (#6561).
The preparation step now also runs clean and fetches slf4j-api 1.7.36 with
maven-dependency-plugin 3.8.1 (both pinned, from Maven Central), and the cache key gets a
v2 prefix so the incomplete caches are not restored.

Co-authored-by: principalwater <[email protected]>
2026-11-29 22:15:32 +08:00
l0ng-ai 27447d21a7 ci: keep the Windows Rust cache warm and allow a cold build 75 minutes (#6850)
A Windows run on main that ended in a test failure skipped the Rust cache save, so the next PR
compiled every dependency again (about 19 minutes of Clippy plus 30 of test binaries) and ran out
of the 60-minute limit partway through the tests.

- rust-cache in the Rust job saves on failure too; still only on main, PRs and forks restore.
- The Windows Rust job gets 75 minutes; macOS and Linux stay at 60.

Refs #6496
2026-11-29 22:07:17 +08:00
l0ng-ai 3edbcc0dcd ci(smoke): run the TypeScript project-errors and import-style smokes (#6851)
The TypeScript job in Language smoke now also runs typescript_project_errors (Problems ›
TypeScript Project Errors against the global tsc the job installs) and typescript_import_style
(the import style settings through real vtsls). Both smokes came with #6097 and #6342 but were
not run in CI yet.
2026-11-29 22:06:27 +08:00
Akbar Husain 782a0a98e3 feat(mcp): add debugger tools (#6579)
The built-in MCP server gets xdebug_* tools: debugger status, start a session for a run configuration or run point, control it (resume, pause, step, wait for pause, stop), list/set/remove breakpoints, run to line, threads, stack, frame values, values by path, evaluate and set variable. Breakpoints go through the window's editor model, so they show in the gutter, persist and are the list the user sees; sessions start through the IDE's Debug action with its before-launch tasks. Mutating tools are marked write for the trust gate.

Co-authored-by: akbar1214 <[email protected]>
2026-11-29 21:59:42 +08:00
arookieofcтаarookieofc bd0455bda5 fix(vcs): stop retrying stale git worktrees (#6794)
A failed reopen of a repository never updated the cache stamp, so every gix() call reopened it again and logged a warning, and status fell back to running git in a worktree folder that no longer existed (os error 267 on Windows). The stamp is now updated on failure too, and a repository whose worktree or git directory is missing is skipped by status, ignored-files and path status, logged once, and picked up again when both directories are back.

Fixes #5514

Co-authored-by: arookieofc <[email protected]>
2026-11-29 21:56:58 +08:00
l0ng-ai 13cd8ba006 fix(updates): flush the received bytes before a broken download returns (#6407)
append_body returned on a body error before flushing the tokio File, whose writes run on a
background thread, so a resume could measure the partial file shorter than the bytes already
received (the Linux CI flake in a_broken_download_resumes_with_range). The error is now held
until the file is flushed; the success path and signature checks are unchanged.
2026-11-29 21:53:33 +08:00
Muuтаmuutot 9b413fde11 feat(search): share text match options with Search Everywhere (#6843)
Search Everywhere's Text tab gets Match Case, Words and Regex toggles (Alt+C / Alt+W / Alt+X). They use Find in Files' option store, so both entry points send the same search flags, and the choices are persisted across restarts.

Co-authored-by: muutot <[email protected]>
2026-11-29 21:42:37 +08:00
Muuтаmuutot 29e5571186 fix(editor): extend Select Line through the next line on each call (#6839)
Select Line at Caret dropped the line where a selection ended at column 0 and kept a backward selection's direction, so invoking it again selected the same lines. It now covers every line the selection touches, including the one it ends at the start of, and leaves the caret at the selection end, so repeated calls extend line by line. Folded lines and multiple carets work as before.

Co-authored-by: muutot <[email protected]>
2026-11-29 21:37:01 +08:00
audichuang 08eb9e3ff9 fix(editor): don't save stale text over a file replaced by binary content (#6840)
reload_from_disk treated a file that now loads as binary like a document opened as binary: it refreshed the disk stamp without a disk-change report, so autosave wrote the next edit over the binary file. A detected-encoding buffer now gets the disk conflict too. Reopening a file whose closed tab kept unsaved changes shows that buffer as text instead of a binary viewer that hid what Save would write. A clean buffer gets its own disk-change wording.

Co-authored-by: audichuang <[email protected]>
2026-11-29 21:34:53 +08:00
LU XIANGRUIтаwildcatDownstairs 3d6ad2e254 feat(run): show xcodebuild errors and warnings in Problems (#6848)
Xcode run and test configurations now publish the compiler and linker messages in their xcodebuild output to Problems and the editor as they arrive. A Format::Xcode on top of the GCC/Clang line parser folds in notes, project-level lines and Undefined symbols blocks; XcodebuildMessages resolves positions, maps symlinked paths back to the project, reports each message once across architectures and stops at the build result. A new run clears the files its previous run reported; messages without a location go on the project file.

Closes #6842

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 21:32:42 +08:00
LU XIANGRUIтаwildcatDownstairs 55b23c90b8 feat(lsp): open documents a language server asks to show (#6846)
Advertise window/showDocument support. An existing file: URI becomes an LspShowDocument event that the frontend opens through openCodeLocation with the requested selection and focus; external http/https/mailto links open in the browser. Anything else answers success: false. This makes sourcekit-lsp's Expand Macro and Inline Macro code actions work.

Closes #6845

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 21:27:53 +08:00
l0ng-ai 3fb58cf69b feat(lsp): stop a language server from the status bar popup (#6847)
Running, busy and starting servers get a Stop button next to Restart in the language server popup. LspManager::stop shuts the instance down and leaves it idle, so it starts again when a file it serves is opened; a notification says it will restart when needed. Adds the lsp_stop command.

Fixes #6835
2026-11-29 21:20:31 +08:00
l0ng-ai 3b6ee66b74 fix(debugger): keep the inlay Run to Cursor button while the pointer moves to it (#6841)
The button sits left of the line's first non-space character, over the indent or the gutter, but the hover area started at the text and ended four characters in: moving the pointer to the button left the area and hid it before it could be clicked. The area now includes the gutter, and while the button is shown it reaches the button's right edge on that line.

Fixes #6832
2026-11-29 20:37:05 +08:00
l0ng-ai 243b9ffa7a fix(editor): let other X11 apps keep the primary selection while the window is inactive (#6838)
Another application taking the primary selection makes WebKitGTK clear the page's selection. An editor in an inactive window is still the active element, so CodeMirror wrote its selection back and claimed the primary selection again: terminals and other X11 apps could not keep a selection while an OpenIDEA editor had one. On Linux the editor now accepts the cleared selection while its window is inactive, keeping its carets.

Fixes #6309
2026-11-29 20:03:46 +08:00
LU XIANGRUIтаwildcatDownstairs 86fabc7d1b feat(project-structure): add Project Structure and Open Module Settings entry points (#6834)
Adds Project Structure… to the title bar gear menu (before Settings) and Open Module Settings to the Project view context menu (below Compare With, above Mark Directory as). Open Module Settings is offered on the project folder, Maven / Gradle / Project Structure module folders and sources / resources roots; it opens Project Structure › Modules with the innermost module holding the path selected, and F4 / Cmd+Down on a module folder opens it too. The action uses a new project-structure icon.

Artifacts in Project Structure are now editable when the project has no build tool, since the IDE builds and deploys them itself; with Maven or Gradle the page stays read-only with a note. The Tomcat run configuration's "No artifacts configured" Fix opens Project Structure › Artifacts and the deployment list refreshes when artifacts change.

Refs #404

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 19:15:50 +08:00
l0ng-ai ae3405486f fix(debugger): skip Windows Store Python aliases when starting debugpy (#6831)
The built-in python.toml starts debugpy's adapter with a bare python3. On Windows that name (and often python) resolves to an App Execution Alias in %LOCALAPPDATA%\Microsoft\WindowsApps, which fails to start unless the Store's Python is installed, so a Python Debug Server reported failed to start ...\WindowsApps\python3.exe even with Python installed and on PATH.

The adapter now takes every match on PATH of the command, then python, then the py launcher, and uses the first that is no alias or one that runs, as the IDE already does when it installs Python tools.

Fixes #6818
2026-11-29 19:03:50 +08:00
l0ng-ai dfea6d2c1e feat(plugins): explain capabilities and open a plugin's own settings (API 1.19) (#6830)
[capabilities.reasons] lets a plugin say in one sentence why it asks for a declared capability. The permission dialog and the plugin's details in Settings › Plugins show it below the IDE's own description, marked as the plugin's words and never instead of it; it is translated through the plugin's locales/<tag>.json. Keys must be capabilities under required or optional; reasons are 1-500 characters.

settings.open(page) opens Settings at the plugin's node or one of its declared pages, and settings.open-permissions at its permissions in Settings › Plugins (plugins#permissions:<id>, so it also reaches a separate Settings window), letting a notice take the user straight there. Both work only from a command or event of a window; an undeclared page is not-found.

Plugin API 1.19.0: WIT package, engine, SDK wrappers and mock, rebuilt components; 1.18 is recorded as shipped with 0.1.54. The settings-pages fixture exercises both additions.

Refs #6745
2026-11-29 18:24:29 +08:00
l0ng-ai b9a25462ea fix(vfs): reload ignore rules after git init on Windows (#6829)
A watcher that started outside a repository caches, per directory, that no .git encloses it. After git init the explicit reload invalidated that cache from /, which is no ancestor of C:\ paths, so on Windows the .gitignore and .git/info/exclude entries written right after were not applied to listings until a file event arrived. It now invalidates from the watch root's topmost ancestor.

The Python library index test no longer opens a directory as a plain file to bump its mtime: Windows refuses that, and the bump is only needed for coarse Unix clocks.
2026-11-29 18:13:01 +08:00
l0ng-ai 04e68f6a12 fix(plugins): keep a plugin's settings pages in manifest order (#6828)
A plugin's settings sub-pages registered without an order, so the settings tree sorted them by title. They now keep the order the manifest lists them in, so no new manifest field is needed. Part of #6745.
2026-11-29 17:28:37 +08:00
Muuтаmuutot 4cfc794f60 feat(lsp): open trusted external documentation (#6819)
Documentation entries can carry a trusted externalUrl supplied by the language (never parsed from Markdown links), and the Quick Documentation window and popup menu offer External Documentation for the current page when it is an absolute http(s) URL. The built-in PHP empty/isset documentation is the first provider, pointing at its PHP manual page.

Co-authored-by: muutot <[email protected]>
2026-11-29 17:26:51 +08:00
LU XIANGRUIтаwildcatDownstairs 8105dfd41a feat(logcat): stream iOS Simulator logs in the Logcat tool window (#6822)
On macOS the Logcat device picker also lists booted iOS Simulators (simctl list devices booted). Selecting one follows simctl spawn <udid> log stream --style ndjson --level debug, mapping each log event to a Logcat line (timestamp, pid, thread, a process (subsystem:category) tag, message type to level), so simulator logs get the same level filter, colors, filter language, pause/follow and history as Android. The stream ends normally when the simulator shuts down, the list is empty off macOS or without Xcode, and a missing adb is only reported when there are no simulators either.

Closes #6801

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 17:24:11 +08:00
LU XIANGRUIтаwildcatDownstairs fca497d246 feat(run): choose the iOS simulator for Xcode projects in the toolbar (#6821)
Native Xcode projects get an iOS Simulator chooser next to the run widget on macOS, shown when the project root holds an .xcodeproj or .xcworkspace and no pubspec.yaml (Flutter lists simulators through its own daemon). ide_run::simulator lists available iOS simulators from simctl, booted first, then newest runtime, then name; the menu has Booted and Available sections with Boot / Shut Down per row and Open Simulator, refreshes on open and after each boot or shutdown, and the choice is kept per project root. Xcode run configurations without a pinned simulator launch on the chooser's selection.

Closes #6797

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 17:16:33 +08:00
l0ng-ai 5cb73c5fd1 fix(i18n): translate the Xcode run configuration type (#6827)
The Xcode App run configuration type (#6824) shipped without zh entries for its name, description and fields, so the source-text catalog test failed on main. Adds zh and zh-TW translations; the App.xcodeproj placeholder stays in English.
2026-11-29 17:14:19 +08:00
811 змінених файлів з 32197 додано та 2257 видалено

No files matched your search

+9
Переглянути файл
@@ -0,0 +1,9 @@
# Keeps the commit SHAs the workflows pin their actions to current (the trailing comment names
# the release each SHA comes from).
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule: { interval: weekly }
groups:
actions: { patterns: ["*"] }
+1 -1
Переглянути файл
@@ -12,7 +12,7 @@ jobs:
cancel:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v8
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
script: |
// A merged or closed PR's remaining CI only holds runners other PRs wait for.
+42 -34
Переглянути файл
@@ -106,7 +106,8 @@ jobs:
if: needs.changes.outputs.rust == 'true'
permissions:
contents: read
timeout-minutes: 60
# A Windows build that misses the Rust cache spends ~50 minutes compiling before the tests run.
timeout-minutes: ${{ matrix.os == 'windows-latest' && 75 || 60 }}
strategy:
fail-fast: false
matrix:
@@ -115,22 +116,24 @@ jobs:
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { components: "clippy, rustfmt" }
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
# (only main saves it because saving takes minutes on Windows; PRs restore main's).
- uses: Swatinem/rust-cache@v2
# A failing test run on main still saves it, so the next PR doesn't compile from scratch.
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: runner.environment != 'self-hosted'
with:
save-if: ${{ github.ref == 'refs/heads/main' }}
cache-on-failure: true
# The persistent target dir makes incremental builds pay off; cap its size so it can't fill the disk.
- name: Persistent Cargo target dir
if: runner.environment == 'self-hosted'
@@ -142,7 +145,8 @@ jobs:
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
rm -rf "$CARGO_TARGET_DIR"
fi
- uses: taiki-e/install-action@nextest
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
with: { tool: nextest }
- name: Linux deps
if: runner.os == 'Linux'
run: |
@@ -159,10 +163,10 @@ jobs:
- name: Restore Maven artifacts for Java build tests
id: jbuild-maven-cache
if: runner.environment == 'github-hosted'
uses: actions/cache/restore@v5
uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: jbuild-maven-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
key: jbuild-maven-v2-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
- name: Prepare Maven artifacts for Java build tests
id: jbuild-maven
if: runner.environment == 'github-hosted'
@@ -179,10 +183,13 @@ jobs:
if [[ "$CACHE_HIT" == true ]]; then
exit 0
fi
# The IDE also reads the compiler plugin descriptor when it builds the Maven model.
# The Java tests read the compiler descriptor and run Maven launch and rebuild.
for delay in 0 10 30; do
sleep "$delay"
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml resources:resources compiler:compile; then
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml \
clean resources:resources compiler:compile \
org.apache.maven.plugins:maven-dependency-plugin:3.8.1:get \
-Dartifact=org.slf4j:slf4j-api:1.7.36; then
echo "prepared=true" >> "$GITHUB_OUTPUT"
exit 0
fi
@@ -190,7 +197,7 @@ jobs:
exit 1
- name: Save Maven artifacts for Java build tests
if: steps.jbuild-maven.outputs.prepared == 'true'
uses: actions/cache/save@v5
uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
@@ -235,10 +242,10 @@ jobs:
timeout-minutes: 40
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: x86_64-unknown-linux-musl }
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: runner.environment != 'self-hosted'
with: { key: server-musl }
- name: Persistent Cargo target dir
@@ -264,13 +271,13 @@ jobs:
timeout-minutes: 30
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: wasm32-wasip2, components: "clippy, rustfmt" }
- if: runner.environment != 'self-hosted'
shell: bash
run: echo "CARGO_TARGET_DIR=$GITHUB_WORKSPACE/target-plugins" >> "$GITHUB_ENV"
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: runner.environment != 'self-hosted'
with:
key: plugins
@@ -300,9 +307,9 @@ jobs:
cargo test --locked --manifest-path "$dir/Cargo.toml"
echo "::endgroup::"
done
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with: { node-version: 22, package-manager-cache: false }
# Plugin web pages (`web-src/`, their own pnpm projects): typecheck and test.
- name: Web pages typecheck and test
@@ -329,9 +336,10 @@ jobs:
timeout-minutes: 15
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: taiki-e/install-action@cargo-deny
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
with: { tool: cargo-deny }
- run: cargo deny check
frontend:
@@ -341,13 +349,13 @@ jobs:
timeout-minutes: 30
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
# scripts/smoke-paths.test.ts runs `cargo metadata`, which is not preinstalled in the runner container.
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
if: runner.environment == 'self-hosted'
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -368,10 +376,10 @@ jobs:
timeout-minutes: 15
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -390,10 +398,10 @@ jobs:
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -401,7 +409,7 @@ jobs:
- run: pnpm install --frozen-lockfile
- run: pnpm exec playwright install --with-deps chromium
- run: pnpm e2e --shard=${{ matrix.shard }}/4
- uses: actions/upload-artifact@v6
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
if: failure()
with:
name: playwright-report-${{ matrix.shard }}
+3 -2
Переглянути файл
@@ -21,6 +21,7 @@ concurrency:
jobs:
mirror:
environment: release
runs-on: ubuntu-latest
timeout-minutes: 120
env:
@@ -35,10 +36,10 @@ jobs:
echo "::notice::CNB_TOKEN unset: not mirroring $TAG"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.token.outputs.skip != 'true'
with: { sparse-checkout: scripts }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.token.outputs.skip != 'true'
with: { node-version: 22 }
- name: Download release
+4 -3
Переглянути файл
@@ -23,6 +23,7 @@ concurrency:
jobs:
cask:
environment: release
runs-on: ubuntu-latest
timeout-minutes: 30
env:
@@ -41,16 +42,16 @@ jobs:
echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.check.outputs.skip != 'true'
with: { sparse-checkout: scripts }
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.check.outputs.skip != 'true'
with:
repository: ${{ env.TAP }}
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
path: tap
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.check.outputs.skip != 'true'
with: { node-version: 22 }
- name: Download DMGs
+21 -16
Переглянути файл
@@ -34,6 +34,7 @@ on:
- "src/editor/relatedProviders.ts"
- "src/editor/core/cm/cornerInset.ts"
- "src/editor/core/cm/iconArea.ts"
- "src/editor/core/cm/localAppearance.ts"
- "src/editor/lsp/availability.ts"
- "src/editor/lsp/diagnostics.ts"
- "src/editor/lsp/files.ts"
@@ -106,9 +107,9 @@ jobs:
# SDKs, build tools, the project model, Find Usages candidates, debug stream traces):
# cargo metadata, ide-host's direct deps ide-search/ide-streams and the deps of
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
@@ -154,9 +155,9 @@ jobs:
# stripping local-variable debuginfo from fixtures debugged in the smoke job (CodeLLDB).
CARGO_PROFILE_DEV_DEBUG: line-tables-only
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: runner.environment != 'self-hosted'
with:
shared-key: language-smoke
@@ -183,7 +184,7 @@ jobs:
test -x smoke-bin/language_smoke && test -x smoke-bin/project_smoke
# A tar keeps the executable bits, which artifacts drop.
tar -cf smoke-bin.tar smoke-bin
- uses: actions/upload-artifact@v6
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
smoke:
@@ -202,20 +203,20 @@ jobs:
env:
CARGO_MANIFEST_DIR: ${{ github.workspace }}/crates/ide-host
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
# Tool versions, shared with the evals (pnpm eval).
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { components: "rust-analyzer, rustfmt" }
- uses: actions/download-artifact@v6
- uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0
with: { name: smoke-bin }
- run: |
tar -xf smoke-bin.tar && rm smoke-bin.tar
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -241,19 +242,19 @@ jobs:
fi
- if: matrix.language == 'python'
uses: actions/setup-python@v5
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
with: { python-version: "3.12" }
- if: matrix.language == 'python'
run: pip install "basedpyright==$BASEDPYRIGHT" "ruff==$RUFF"
- if: matrix.language == 'go'
uses: actions/setup-go@v5
uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
with: { go-version: "1.27", cache: false }
- if: matrix.language == 'go'
run: go install "golang.org/x/tools/gopls@$GOPLS"
- if: matrix.language == 'java' || matrix.language == 'kotlin'
uses: actions/setup-java@v4
uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
- if: matrix.language == 'java'
run: |
@@ -265,7 +266,7 @@ jobs:
# The Kotlin fixture has no Gradle wrapper: the server imports it with the Gradle on PATH.
- if: matrix.language == 'kotlin'
uses: gradle/actions/setup-gradle@v4
uses: gradle/actions/setup-gradle@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
with: { gradle-version: "${{ env.GRADLE }}" }
- if: matrix.language == 'kotlin'
run: |
@@ -277,7 +278,7 @@ jobs:
# Xdebug for the debug smoke; Composer installs the fixture's Pest for the run smoke.
- if: matrix.language == 'php'
uses: shivammathur/setup-php@v2
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
with: { php-version: "8.5", coverage: xdebug, tools: composer }
- if: matrix.language == 'php'
run: npm install --global "intelephense@$INTELEPHENSE"
@@ -285,6 +286,10 @@ jobs:
# The binaries from the build job, run from the crate directory as `cargo test` does.
- working-directory: crates/ide-host
run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }}
# Problems › TypeScript Project Errors runs the project's own tsc: the global install stands in.
- if: matrix.language == 'typescript'
working-directory: crates/ide-host
run: ../../smoke-bin/language_smoke --ignored --exact typescript_project_errors typescript_import_style
- if: matrix.language == 'java'
working-directory: crates/ide-host
run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
+104
Переглянути файл
@@ -0,0 +1,104 @@
name: Nightly
# Builds main every night, when it has moved since the last nightly, into a prerelease
# v<next patch>-nightly.<date> (scripts/nightly-prepare.ts: the tag points at a commit on top of
# main that only sets the version). Nightly apps update from the rolling `nightly` release, which
# holds the newest nightly's latest.json; stable apps read releases/latest, which is never a
# prerelease, so they never see a nightly. The newest 14 nightlies are kept.
on:
schedule:
- cron: "0 18 * * *" # 02:00 Beijing
workflow_dispatch:
inputs:
force:
description: "Build even when main has not changed since the last nightly"
type: boolean
default: false
permissions:
contents: read
concurrency:
group: nightly
jobs:
prepare:
if: github.repository == 'l0ng-ai/openidea'
permissions:
contents: write
runs-on: ubuntu-latest
outputs:
tag: ${{ steps.tag.outputs.tag }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with: { ref: main, fetch-depth: 0 }
- id: changed
env:
FORCE: ${{ inputs.force == true }}
run: |
last="$(git tag --list 'v*-nightly.*' --sort=-creatordate | head -1)"
if [ "$FORCE" != true ] && [ -n "$last" ] && [ "$(git rev-parse "$last^")" = "$(git rev-parse HEAD)" ]; then
echo "::notice::main has not changed since $last"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.changed.outputs.skip != 'true'
with: { node-version: 22 }
- name: Version commit and tag
id: tag
if: steps.changed.outputs.skip != 'true'
env:
BUILD: ${{ github.run_number }}
run: |
version="$(node scripts/nightly-prepare.ts --date "$(date -u +%Y%m%d)" --build "$BUILD" | tail -1)"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add -A
git commit -q -m "chore: v$version"
git tag "v$version"
# Pushed with GITHUB_TOKEN, the tag does not start release.yml: the job below calls it.
git push origin "refs/tags/v$version"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
release:
needs: prepare
if: needs.prepare.outputs.tag != ''
permissions:
contents: write
uses: ./.github/workflows/release.yml
with:
tag: ${{ needs.prepare.outputs.tag }}
nightly: true
secrets: inherit
# Points the nightly channel at the new nightly and drops the old ones.
channel:
needs: [prepare, release]
permissions:
contents: write
runs-on: ubuntu-latest
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
TAG: ${{ needs.prepare.outputs.tag }}
steps:
- name: Nightly manifest
run: |
if ! gh release download "$TAG" -p latest.json -D "$RUNNER_TEMP/manifest"; then
echo "::warning::$TAG has no latest.json (unsigned build): the nightly channel stays where it was"
exit 0
fi
notes="The update channel of the [nightly builds](https://github.com/$GH_REPO/releases?q=nightly&expanded=true): its latest.json is the newest nightly's, [$TAG](https://github.com/$GH_REPO/releases/tag/$TAG)."
if gh release view nightly >/dev/null 2>&1; then
gh release edit nightly --notes "$notes"
else
gh release create nightly --prerelease --target main --title "OpenIDEA Nightly" --notes "$notes"
fi
gh release upload nightly "$RUNNER_TEMP/manifest/latest.json" --clobber
- name: Drop old nightlies
run: |
gh release list --limit 200 --json tagName,createdAt \
--jq '[.[] | select(.tagName | test("^v.*-nightly\\."))] | sort_by(.createdAt) | reverse | .[14:][] | .tagName' |
while read -r old; do
gh release delete "$old" --cleanup-tag --yes
done
+1 -1
Переглянути файл
@@ -18,7 +18,7 @@ jobs:
if: github.event.pull_request.user.type != 'Bot' && !github.event.pull_request.draft
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v8
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
script: |
const pr = context.payload.pull_request;
+84 -24
Переглянути файл
@@ -19,6 +19,7 @@ env:
jobs:
plugin-keys:
permissions: {}
environment: release
runs-on: ubuntu-latest
outputs:
keys: ${{ steps.keys.outputs.keys }}
@@ -43,6 +44,7 @@ jobs:
contents: write
needs: plugin-keys
name: Build (${{ matrix.name }})
environment: release
env:
OPENIDEA_OFFICIAL_PLUGIN_KEYS: ${{ needs.plugin-keys.outputs.keys }}
strategy:
@@ -69,15 +71,15 @@ jobs:
target: x86_64-pc-windows-msvc
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with: { ref: "${{ env.TAG }}" }
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with: { node-version: 22, cache: pnpm }
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: "${{ matrix.target }}" }
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with: { key: "${{ matrix.target }}", cache-on-failure: true }
- name: Linux deps
if: runner.os == 'Linux'
@@ -85,40 +87,57 @@ jobs:
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf
- run: pnpm install --frozen-lockfile
# Signing is optional: only secrets that are set get exported, so forks and
# unconfigured repos produce unsigned builds instead of failing.
- name: Signing env
# Signing is optional: forks and unconfigured repos produce unsigned builds instead of
# failing. The secrets go only into the steps that sign (never $GITHUB_ENV), so the other
# steps and the actions' post steps never see them. Tauri treats a set-but-empty key as a
# key, so the unsigned build is a separate step without the secrets.
- name: Signing configured
id: signing
shell: bash
env:
UPDATER_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
APPLE_ID: ${{ runner.os == 'macOS' && secrets.APPLE_ID || '' }}
run: |
echo "updater=$([ -n "$UPDATER_KEY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
echo "apple=$([ -n "$APPLE_ID" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
- name: Build (signed)
if: steps.signing.outputs.updater == 'true'
uses: tauri-apps/tauri-action@84b9d35b5fc46c1e45415bdb6144030364f7ebc5 # v0.6.2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
APPLE_CERTIFICATE: ${{ runner.os == 'macOS' && secrets.APPLE_CERTIFICATE || '' }}
APPLE_CERTIFICATE_PASSWORD: ${{ runner.os == 'macOS' && secrets.APPLE_CERTIFICATE_PASSWORD || '' }}
APPLE_SIGNING_IDENTITY: ${{ runner.os == 'macOS' && secrets.APPLE_SIGNING_IDENTITY || '' }}
APPLE_ID: ${{ runner.os == 'macOS' && secrets.APPLE_ID || '' }}
APPLE_PASSWORD: ${{ runner.os == 'macOS' && secrets.APPLE_PASSWORD || '' }}
APPLE_TEAM_ID: ${{ runner.os == 'macOS' && secrets.APPLE_TEAM_ID || '' }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: |
for v in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD APPLE_SIGNING_IDENTITY APPLE_ID \
APPLE_PASSWORD APPLE_TEAM_ID TAURI_SIGNING_PRIVATE_KEY TAURI_SIGNING_PRIVATE_KEY_PASSWORD; do
[ -n "${!v}" ] && { echo "$v<<__EOF__"; echo "${!v}"; echo "__EOF__"; } >> "$GITHUB_ENV"
done
true
- uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
releaseId: ${{ inputs.release_id }}
tagName: ${{ env.TAG }}
args: --target ${{ matrix.target }}
# The parallel builds would race on one latest.json; `updater-manifest` writes it once.
uploadUpdaterJson: false
- name: Build (unsigned)
if: steps.signing.outputs.updater != 'true'
uses: tauri-apps/tauri-action@84b9d35b5fc46c1e45415bdb6144030364f7ebc5 # v0.6.2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
releaseId: ${{ inputs.release_id }}
tagName: ${{ env.TAG }}
args: --target ${{ matrix.target }}
uploadUpdaterJson: false
# tauri-action notarizes the .app but not the DMG around it; notarize and
# staple the DMG too, then replace the uploaded asset.
- name: Notarize DMG
if: runner.os == 'macOS' && env.APPLE_ID != ''
if: runner.os == 'macOS' && steps.signing.outputs.apple == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: |
for dmg in target/${{ matrix.target }}/release/bundle/dmg/*.dmg; do
xcrun notarytool submit "$dmg" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \
@@ -137,6 +156,8 @@ jobs:
shell: pwsh
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: |
$target = "${{ matrix.target }}"
$arch = if ($target -like "x86_64*") { "x64" } else { "arm64" }
@@ -176,11 +197,11 @@ jobs:
- { runner: macos-latest, target: x86_64-apple-darwin, os: macos, arch: x86_64 }
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with: { ref: "${{ env.TAG }}" }
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: "${{ matrix.target }}" }
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with: { key: "server-${{ matrix.target }}", cache-on-failure: true }
- name: musl toolchain
if: runner.os == 'Linux'
@@ -201,6 +222,45 @@ jobs:
if command -v sha256sum >/dev/null; then sha256sum "$ASSET"; else shasum -a 256 "$ASSET"; fi > "$ASSET.sha256"
gh release upload "$TAG" "$ASSET" "$ASSET.sha256" --clobber
# Signs every server archive with the updater key (`<asset>.sig`), so the app verifies a
# server from the CNB mirror as it does from GitHub (ide-tools `server::fetch`). Only this job
# gets the key; without it the archives keep only their .sha256.
server-signatures:
permissions:
contents: write
needs: server
environment: release
runs-on: ubuntu-latest
steps:
- name: Signing configured
id: signing
env:
UPDATER_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
run: echo "updater=$([ -n "$UPDATER_KEY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.signing.outputs.updater == 'true'
with: { ref: "${{ env.TAG }}" }
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
if: steps.signing.outputs.updater == 'true'
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.signing.outputs.updater == 'true'
with: { node-version: 22, cache: pnpm }
- if: steps.signing.outputs.updater == 'true'
run: pnpm install --frozen-lockfile
- name: Sign server archives
if: steps.signing.outputs.updater == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: |
gh release download "$TAG" -p 'openidea-server-*.gz' -D "$RUNNER_TEMP/server"
for asset in "$RUNNER_TEMP"/server/*.gz; do
pnpm exec tauri signer sign "$asset"
done
gh release upload "$TAG" "$RUNNER_TEMP"/server/*.gz.sig --clobber
# The updater manifest (latest.json), built once from the signed bundles every build uploaded.
# Fails when a platform is missing, so a release never ships a manifest without it.
updater-manifest:
@@ -209,7 +269,7 @@ jobs:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v8
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
RELEASE_ID: ${{ inputs.release_id }}
with:
+38 -16
Переглянути файл
@@ -7,19 +7,27 @@ on:
tag:
description: "Tag to release (e.g. v0.1.0); must already exist"
required: true
# nightly.yml: a nightly is a prerelease whose notes start at the previous nightly, without the
# official plugins, the CNB mirror or the Homebrew cask.
workflow_call:
inputs:
tag: { type: string, required: true }
nightly: { type: boolean, default: false }
permissions:
contents: read
concurrency:
group: release-${{ github.event.inputs.tag || github.ref_name }}
group: release-${{ inputs.tag || github.ref_name }}
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
TAG: ${{ github.event.inputs.tag || github.ref_name }}
TAG: ${{ inputs.tag || github.ref_name }}
COMMUNITY_PLUGINS_INDEX: https://github.com/l0ng-ai/openidea-plugins/releases/download/index/index.json
# The jobs that read a signing key or token, here and in the workflows called below, run in
# the `release` environment, which holds those secrets.
jobs:
# Creates (or reuses) one draft release that every platform build uploads into.
create-release:
@@ -29,7 +37,7 @@ jobs:
outputs:
release_id: ${{ steps.release.outputs.id }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with: { ref: "${{ env.TAG }}" }
- name: Tag matches app version
run: |
@@ -49,7 +57,9 @@ jobs:
exit 1
fi
- id: release
uses: actions/github-script@v8
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
NIGHTLY: ${{ inputs.nightly == true }}
with:
script: |
const tag = process.env.TAG;
@@ -61,8 +71,13 @@ jobs:
core.setOutput("id", existing.id);
return;
}
// Prereleases are skipped: the notes span stable release to stable release.
const previous = releases.find((r) => !r.draft && !r.prerelease);
// Prereleases are skipped: the notes span stable release to stable release. A
// nightly's span from the newest published release, nightly or stable (not the
// rolling `nightly` release, which only holds the channel's manifest).
const nightly = process.env.NIGHTLY === "true";
const previous = releases.find(
(r) => !r.draft && r.tag_name !== "nightly" && (nightly || !r.prerelease),
);
const { data: notes } = await github.rest.repos.generateReleaseNotes({
owner, repo, tag_name: tag, previous_tag_name: previous?.tag_name,
});
@@ -78,7 +93,7 @@ jobs:
needs: create-release
uses: ./.github/workflows/release-build.yml
with:
tag: ${{ github.event.inputs.tag || github.ref_name }}
tag: ${{ inputs.tag || github.ref_name }}
release_id: ${{ needs.create-release.outputs.release_id }}
secrets: inherit
@@ -96,29 +111,34 @@ jobs:
contents: write
needs: create-release
name: Official plugins
environment: release
runs-on: ubuntu-22.04
env:
SIGNING_KEY: ${{ secrets.PLUGIN_SIGNING_KEY }}
NIGHTLY: ${{ inputs.nightly == true }}
steps:
- id: key
run: |
if [ -z "$SIGNING_KEY" ]; then
if [ "$NIGHTLY" = true ]; then
echo "a nightly does not publish the official plugins"
echo "skip=true" >> "$GITHUB_OUTPUT"
elif [ -z "$SIGNING_KEY" ]; then
echo "::warning::PLUGIN_SIGNING_KEY is not set: the official plugins are not published"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.key.outputs.skip != 'true'
with: { ref: "${{ env.TAG }}" }
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
if: steps.key.outputs.skip != 'true'
with: { targets: wasm32-wasip2 }
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: steps.key.outputs.skip != 'true'
with: { key: release-plugins }
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
if: steps.key.outputs.skip != 'true'
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.key.outputs.skip != 'true'
with: { node-version: 22 }
# Builds the web pages; fails when a checked-in component isn't built from these sources.
@@ -163,7 +183,7 @@ jobs:
needs: [create-release, binaries, plugins]
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v8
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
with:
@@ -175,13 +195,15 @@ jobs:
# The China mirror the updater's CNB source reads; a failure here leaves the GitHub release as is.
cnb-mirror:
needs: publish
if: ${{ !inputs.nightly }}
uses: ./.github/workflows/cnb-mirror.yml
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
with: { tag: "${{ inputs.tag || github.ref_name }}" }
secrets: inherit
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
homebrew:
needs: publish
if: ${{ !inputs.nightly }}
uses: ./.github/workflows/homebrew.yml
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
with: { tag: "${{ inputs.tag || github.ref_name }}" }
secrets: inherit
Створено
+71 -53
Переглянути файл
@@ -252,9 +252,9 @@ dependencies = [
[[package]]
name = "async-executor"
version = "1.14.0"
version = "1.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
dependencies = [
"async-task",
"concurrent-queue",
@@ -1552,9 +1552,9 @@ dependencies = [
[[package]]
name = "curve25519-dalek"
version = "5.0.0"
version = "5.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"
checksum = "94c1aa5a9b7626ed65ac0cf5ea9d4f1547af89017fbac20bd4de40022fff516f"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
@@ -4154,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4171,6 +4171,7 @@ dependencies = [
"semver",
"serde",
"serde_json",
"sha1 0.10.7",
"specta",
"tempfile",
"tokio",
@@ -4182,7 +4183,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4194,10 +4195,11 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"serde",
"serde_json",
"specta",
"tempfile",
"which",
@@ -4205,7 +4207,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"blake3",
"chardetng",
@@ -4223,7 +4225,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4237,7 +4239,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4248,7 +4250,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -4259,7 +4261,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4281,7 +4283,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-run",
@@ -4294,7 +4296,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4305,6 +4307,7 @@ dependencies = [
"ide-jvm-attach",
"ide-jvm-inspect",
"ide-language",
"ide-run",
"libc",
"memchr",
"parking_lot 0.12.5",
@@ -4323,7 +4326,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4362,7 +4365,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"serde",
@@ -4375,7 +4378,7 @@ dependencies = [
[[package]]
name = "ide-drag-out"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4389,7 +4392,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4409,7 +4412,7 @@ dependencies = [
[[package]]
name = "ide-flutter"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-android",
"ide-core",
@@ -4420,7 +4423,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4432,7 +4435,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4444,7 +4447,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"criterion",
"ide-core",
@@ -4463,7 +4466,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4546,7 +4549,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"http",
@@ -4569,7 +4572,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"blake3",
"criterion",
@@ -4592,7 +4595,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4604,7 +4607,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4620,7 +4623,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"libc",
"tempfile",
@@ -4629,7 +4632,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"futures",
"serde",
@@ -4640,7 +4643,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"blake3",
"criterion",
@@ -4681,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",
@@ -4699,7 +4703,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"criterion",
"dunce",
@@ -4729,7 +4733,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"bytes",
"dunce",
@@ -4748,7 +4752,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"futures",
"ide-core",
@@ -4773,7 +4777,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"blake3",
"dunce",
@@ -4795,7 +4799,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4809,7 +4813,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"dunce",
"futures",
@@ -4829,7 +4833,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"blake3",
"dunce",
@@ -4855,7 +4859,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-tools",
@@ -4871,7 +4875,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4897,7 +4901,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"criterion",
"encoding_rs",
@@ -4918,7 +4922,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"parking_lot 0.12.5",
@@ -4931,7 +4935,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4956,7 +4960,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-language",
@@ -4969,7 +4973,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-language",
@@ -4984,7 +4988,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"libc",
@@ -4998,7 +5002,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"criterion",
"ide-core",
@@ -5011,16 +5015,19 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"blake3",
"flate2",
"hex",
"http",
"hyper-util",
"ide-core",
"ide-http",
"ide-language",
"libc",
"minisign-verify",
"parking_lot 0.12.5",
"serde",
"serde_json",
@@ -5035,7 +5042,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"blake3",
"dunce",
@@ -5057,7 +5064,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"chardetng",
"dunce",
@@ -5084,7 +5091,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5100,7 +5107,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"blake3",
"dunce",
@@ -5110,6 +5117,7 @@ dependencies = [
"ide-text",
"ide-vfs",
"parking_lot 0.12.5",
"quick-xml 0.42.0",
"semver",
"serde",
"serde_json",
@@ -6748,7 +6756,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -9854,7 +9862,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"getrandom 0.3.4",
"once_cell",
"rustix",
"windows-sys 0.61.2",
@@ -10635,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"
+1 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.55"
version = "0.1.56"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+1
Переглянути файл
@@ -27,6 +27,7 @@ uuid.workspace = true
tempfile.workspace = true
which = "8"
semver = "1"
sha1 = "0.10"
[target.'cfg(unix)'.dependencies]
rustix = { version = "1", features = ["fs"] }
+129 -7
Переглянути файл
@@ -18,6 +18,7 @@ mod external;
pub mod hermes;
mod images;
pub mod mcp;
pub mod memory;
mod model;
mod native;
mod provider;
@@ -239,6 +240,9 @@ impl Default for SkillsPolicy {
/// Returns the skill policies for this project.
pub type SkillsPolicyFn = dyn Fn() -> SkillsPolicy + Send + Sync;
/// Returns the memory policies for this project.
pub type MemoryPolicyFn = dyn Fn() -> memory::MemoryPolicy + Send + Sync;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct CopilotBinaryKey {
command: String,
@@ -277,6 +281,7 @@ struct Shared {
mcp_servers_hook: RwLock<Option<Arc<McpServersFn>>>,
mcp_executable_hook: RwLock<Option<Arc<McpExecutableFn>>>,
skills_policy_hook: RwLock<Option<Arc<SkillsPolicyFn>>>,
memory_policy_hook: RwLock<Option<Arc<MemoryPolicyFn>>>,
/// Monotonic id for [`AgentEvent::Attention`] episodes.
attention_seq: AtomicU64,
/// Bumped on every [`AgentManager::shutdown`]: in-flight turns, session opens,
@@ -943,6 +948,8 @@ struct Task {
mcp_reload_pending: AtomicBool,
/// Turned on when per-session skill overrides changed while a turn was busy; dropped once idle.
skills_reload_pending: AtomicBool,
/// Turned on when per-session memory overrides changed while a turn was busy; dropped once idle.
memory_reload_pending: AtomicBool,
/// Settings already sent this session (`(option, value)`), so a refusal is not retried.
config_sent: Mutex<HashSet<(String, String)>>,
dirty: Mutex<BTreeSet<(Session, usize)>>,
@@ -1025,6 +1032,7 @@ impl AgentManager {
mcp_servers_hook: RwLock::new(None),
mcp_executable_hook: RwLock::new(None),
skills_policy_hook: RwLock::new(None),
memory_policy_hook: RwLock::new(None),
attention_seq: AtomicU64::new(0),
shutdown_epoch: AtomicU64::new(0),
});
@@ -1270,6 +1278,11 @@ impl AgentManager {
*self.shared.skills_policy_hook.write() = Some(Arc::from(hook));
}
/// Provides the user and workspace memory policies and the workspace's trust.
pub fn set_memory_policy_hook(&self, hook: Box<MemoryPolicyFn>) {
*self.shared.memory_policy_hook.write() = Some(Arc::from(hook));
}
/// The slash commands to complete for `provider`, in `task`'s directory or (without one)
/// in the project: what the agent offered last time there, unadvertised builtins,
/// for Claude Code the skills and custom commands on disk it has not listed (for
@@ -1450,6 +1463,7 @@ impl AgentManager {
background: Box::default(),
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
memory_overrides: None,
stats: Box::default(),
interrupted: None,
unread: false,
@@ -1539,6 +1553,7 @@ impl AgentManager {
background: Box::default(),
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
memory_overrides: None,
stats: Box::default(),
interrupted: None,
unread: false,
@@ -1686,6 +1701,7 @@ impl AgentManager {
background: Box::default(),
mcp_overrides: req.mcp_overrides,
skill_overrides: req.skill_overrides,
memory_overrides: req.memory_overrides.filter(|m| !m.is_empty()).map(Box::new),
stats: Box::default(),
interrupted: None,
unread: false,
@@ -2032,13 +2048,20 @@ impl AgentManager {
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref());
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
let memory_delivery = source.stage_memory(&provider_id, &cwd).await;
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
let reply: Value = live
.peer
.request(
"session/fork",
{
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
let mut params = session_params(
&cwd_s,
&mcp_servers,
skills_delivery.as_ref(),
memory_delivery.as_ref(),
&roots,
);
params["sessionId"] = json!(live.session);
params
},
@@ -2739,7 +2762,6 @@ impl AgentManager {
}
s.task.title = title;
s.title_renamed = true;
s.task.updated_ms = now_ms();
}
task.persist();
task.emit_task();
@@ -2765,6 +2787,7 @@ impl AgentManager {
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json")));
let _ = std::fs::remove_dir_all(task.turn_dir());
skills::remove_farm(&self.shared.paths.store_dir, id);
memory::remove_farm(&self.shared.paths.store_dir, id);
let saved = task.state.lock().saved.clone();
if let Some(saved) = saved
&& !self.tasks.read().values().any(|t| t.state.lock().saved.as_ref() == Some(&saved))
@@ -3102,7 +3125,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())
};
@@ -3134,7 +3156,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())
};
@@ -3150,6 +3171,41 @@ impl AgentManager {
Ok(out)
}
/// Sets the session's memory overrides (auto-memory mode and per-entry modes); like MCP
/// and skill overrides, an idle resumable session recycles so the next turn starts with
/// the updated delivery.
pub fn set_memory_overrides(&self, id: &str, overrides: AgentMemoryOverrides) -> IdeResult<AgentTask> {
let task = self.task(id)?;
let cleaned_entries: BTreeMap<String, AgentMemoryMode> = overrides
.entries
.into_iter()
.filter_map(|(k, v)| (!k.trim().is_empty()).then(|| (k.trim().to_owned(), v)))
.collect();
let cleaned = AgentMemoryOverrides { auto_memory: overrides.auto_memory, entries: cleaned_entries };
let next_boxed = (!cleaned.is_empty()).then(|| Box::new(cleaned));
let (changed, busy, has_bg, out) = {
let mut s = task.state.lock();
if s.task.status == AgentStatus::Archived {
return Err(IdeError::invalid("the task is archived"));
}
let changed = s.task.memory_overrides != next_boxed;
if changed {
s.task.memory_overrides = next_boxed;
}
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
};
if changed {
task.persist();
task.emit_task();
if busy || has_bg || !task.permissions.lock().is_empty() {
task.memory_reload_pending.store(true, Ordering::Release);
} else {
task.recycle_resumable_session();
}
}
Ok(out)
}
/// Recycles idle resumable live sessions (or schedules reload after the running turn) when
/// global, workspace, or built-in IDE MCP server settings change.
pub fn notify_mcp_servers_changed(&self) {
@@ -3254,6 +3310,44 @@ impl Task {
}
}
/// Resolves and stages the session's memory delivery (`_meta.openidea.memory`).
async fn stage_memory(&self, provider: &str, cwd: &Path) -> Option<memory::Delivery> {
let (policy, overrides, home, roots) = {
let shared = &self.shared;
let mut policy = shared.memory_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
let (overrides, task_root) = {
let s = self.state.lock();
(s.task.memory_overrides.as_deref().cloned(), s.task.project_root.as_ref().map(|p| p.0.clone()))
};
let mut roots = Vec::new();
if let Some(tr) = task_root {
roots.push(tr);
}
roots.extend(policy.workspace_roots.iter().cloned());
roots.push(shared.paths.project_root.clone());
policy.workspace_roots = roots.clone();
(policy, overrides, shared.paths.home_dir.clone(), roots)
};
let farm = memory::farm_dir(&self.shared.paths.store_dir, &self.id);
let out_cwd = cwd.to_path_buf();
let provider = provider.to_owned();
match blocking(move || {
let entries = memory::discover_memories(&roots, home.as_deref());
let states = memory::resolve_entries(entries, overrides.as_ref(), &policy);
let (auto_mode, _) = memory::resolve_provider_auto_memory(&provider, overrides.as_ref(), &policy);
memory::stage(&farm, &provider, &states, auto_mode, &out_cwd, home.as_deref())
.map_err(|e| IdeError::internal(e.to_string()))
})
.await
{
Ok(delivery) => Some(delivery),
Err(e) => {
tracing::warn!("agent task {}: staging its memory failed: {e}", self.id);
None
}
}
}
/// A task whose conversation is at hand (a new task, a copy).
fn restore(mut file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
let adopt = file.entries.is_empty() && file.session_id.is_some();
@@ -3345,6 +3439,7 @@ impl Task {
idle_epoch: AtomicU64::new(0),
mcp_reload_pending: AtomicBool::new(false),
skills_reload_pending: AtomicBool::new(false),
memory_reload_pending: AtomicBool::new(false),
config_sent: Mutex::new(HashSet::new()),
dirty: Mutex::new(BTreeSet::new()),
streamed: Mutex::new(Streamed::default()),
@@ -3980,7 +4075,8 @@ impl Task {
self.emit_attention(AgentAttentionReason::Finished);
}
if (self.mcp_reload_pending.swap(false, Ordering::AcqRel)
|| self.skills_reload_pending.swap(false, Ordering::AcqRel))
|| self.skills_reload_pending.swap(false, Ordering::AcqRel)
|| self.memory_reload_pending.swap(false, Ordering::AcqRel))
&& self.state.lock().background_tasks.is_empty()
{
self.recycle_resumable_session();
@@ -4669,12 +4765,25 @@ impl Task {
if self.shared.shut_down_since(epoch) {
return Err(SessionOpenError { message: "The agent manager shut down.".into(), allow_acp_fallback: false });
}
let memory_delivery = self.stage_memory(provider_id, cwd).await;
if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(provider_id) {
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
for name in self.shared.mcp_servers_off_for_session(provider_id, &mcp_overrides) {
spec.args.push("--disable-mcp-server".into());
spec.args.push(name);
}
if let Some(mem) = memory_delivery.as_ref() {
if mem.copilot_enable_memory == Some(true) {
spec.args.push("--enable-memory".into());
}
if mem.copilot_exclude_store_memory {
spec.args.push("--excluded-tools".into());
spec.args.push("store_memory".into());
}
if mem.copilot_disable_custom_instructions {
spec.args.push("--no-custom-instructions".into());
}
}
}
self.stderr.lock().clear();
self.config_sent.lock().clear();
@@ -4730,7 +4839,8 @@ impl Task {
let cwd_s = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()).to_string_lossy().into_owned();
let pending_native_fork = self.state.lock().pending_native_fork.clone();
let mut opening_params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
let mut opening_params =
session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), memory_delivery.as_ref(), &roots);
if spec.driver == provider::Driver::Codex {
let s = self.state.lock();
let mut wanted = s.wanted.clone();
@@ -6132,7 +6242,13 @@ fn stage_key(driver: provider::Driver) -> &'static str {
/// servers, and the ones off for this session, so an agent that also loads its own
/// configuration (Claude Code) can keep a same-named server of it off too — plus the
/// session's staged skills for the drivers that take them, and the workspace's other roots.
fn session_params(cwd: &str, mcp: &McpForSession, skills: Option<&skills::Delivery>, roots: &[String]) -> Value {
fn session_params(
cwd: &str,
mcp: &McpForSession,
skills: Option<&skills::Delivery>,
memory: Option<&memory::Delivery>,
roots: &[String],
) -> Value {
let mut params = json!({ "cwd": cwd, "mcpServers": mcp.servers });
if !roots.is_empty() {
params["additionalDirectories"] = json!(roots);
@@ -6146,6 +6262,12 @@ fn session_params(cwd: &str, mcp: &McpForSession, skills: Option<&skills::Delive
{
meta["skills"] = v;
}
if let Some(memory) = memory
&& let Ok(v) = serde_json::to_value(memory)
&& v.as_object().is_some_and(|m| !m.is_empty())
{
meta["memory"] = v;
}
if !meta.is_null() && meta.as_object().is_some_and(|m| !m.is_empty()) {
params["_meta"] = json!({ "openidea": meta });
}
File diff suppressed because it is too large. Load diff
+226 -2
Переглянути файл
@@ -181,6 +181,10 @@ pub struct AgentTask {
/// Per-session skill modes (`skill name` -> mode), on top of the settings' policies.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
/// Per-session memory overrides (auto-memory mode and per-entry modes), boxed to keep `AgentEvent::Task` small.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub memory_overrides: Option<Box<AgentMemoryOverrides>>,
/// Token counts of the last turn and context compressions, when the agent reports them.
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
#[serde(default)]
@@ -834,6 +838,10 @@ pub struct NewAgentTask {
/// Per-session skill modes (`skill name` -> mode).
#[serde(default)]
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
/// Per-session memory overrides (auto-memory mode and per-entry modes).
#[serde(default)]
#[specta(optional)]
pub memory_overrides: Option<AgentMemoryOverrides>,
/// Creates the task without sending `prompt` (it only names the task): the composer's
/// `!` command runs in it first.
#[serde(default)]
@@ -975,7 +983,7 @@ pub enum AgentEvent {
pub use ide_core::settings::{AgentMcpServer, McpTransport};
/// Where an MCP server configuration is stored (`settings.toml` vs `.openidea/settings.toml`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum McpScope {
User,
@@ -1042,7 +1050,223 @@ fn default_true() -> bool {
true
}
pub use ide_core::settings::{AgentSkillMode, AgentSkillPolicy};
pub use ide_core::settings::{
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentProviderMemoryPolicy, AgentSkillMode,
AgentSkillPolicy, AutoMemoryMode,
};
/// Kind of discovered agent memory entry.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemoryKind {
/// Always-loaded instruction document (`AGENTS.md`, `CLAUDE.md`, `copilot-instructions.md`, `GEMINI.md`).
#[default]
Instruction,
/// Path-scoped or conditional rule (`.claude/rules/*.md`, `*.instructions.md`, `.cursor/rules/*.mdc`).
Rule,
/// Agent-authored cross-session memory note (`MEMORY.md`, Claude topic files, Codex summaries, Hermes `USER.md`).
AutoNote,
}
/// Which workspace, user, or CLI store a memory entry was discovered in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemorySource {
/// Portable workspace instructions: `AGENTS.md`, `AGENTS.override.md`.
#[default]
Workspace,
/// `CLAUDE.md`, `.claude/CLAUDE.md`, `CLAUDE.local.md`, `.claude/rules/**`.
ClaudeWorkspace,
/// `~/.claude/CLAUDE.md`, `~/.claude/rules/**`.
ClaudeUser,
/// `~/.claude/projects/<repo>/memory/**` (or custom `autoMemoryDirectory`).
ClaudeAuto,
/// `.github/copilot-instructions.md`, `.github/instructions/**/*.instructions.md`.
GithubWorkspace,
/// `~/.copilot/copilot-instructions.md`, `~/.copilot/instructions/**/*.instructions.md`.
CopilotUser,
/// `~/.codex/AGENTS.md`, `~/.codex/AGENTS.override.md`.
CodexUser,
/// `~/.codex/memories/**` / `~/.codex/memories_v2/**`.
CodexAuto,
/// `.cursor/rules/**/*.mdc`, `.cursorrules`.
CursorWorkspace,
/// `GEMINI.md`.
GeminiWorkspace,
/// `~/.gemini/GEMINI.md`.
GeminiUser,
/// `<hermes_profile>/memories/{MEMORY.md,USER.md}`.
HermesAuto,
}
impl AgentMemorySource {
/// True when the entry lives inside the current workspace and requires Workspace Trust.
pub fn is_workspace(self) -> bool {
matches!(
self,
Self::Workspace
| Self::ClaudeWorkspace
| Self::GithubWorkspace
| Self::CursorWorkspace
| Self::GeminiWorkspace
)
}
/// True when the entry is an agent's learned cross-session auto-memory store.
pub fn is_auto(self) -> bool {
matches!(self, Self::ClaudeAuto | Self::CodexAuto | Self::HermesAuto)
}
}
/// Which layer decided an [`AgentMemoryState::mode`] or [`AutoMemoryMode`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemoryOrigin {
#[default]
None,
Session,
Workspace,
User,
/// Locked `Off` because the workspace is untrusted.
Trust,
}
/// One discovered instruction file, rule file, or learned auto-memory note.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMemoryEntry {
/// Stable identifier (`"<source>::<rel_key>"`).
pub id: String,
pub title: String,
pub description: String,
pub kind: AgentMemoryKind,
pub source: AgentMemorySource,
/// Secondary sources whose symlink or `@AGENTS.md` import resolved to this same canonical file.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub also_in: Vec<AgentMemorySource>,
/// Canonical file path on disk.
pub path: IpcPath,
/// Normalized path-scoping globs (`paths:` in Claude, `applyTo:` in Copilot, `globs:` in Cursor).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub paths: Vec<String>,
/// Optional memory category (`user`, `feedback`, `project`, `reference`, `profile`).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub category: Option<String>,
/// Approximate prompt token cost (~4 chars/token).
pub approx_tokens: u32,
pub line_count: u32,
pub byte_len: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub modified_ms: Option<f64>,
/// True when OpenIDEA allows deleting or promoting-and-removing this file (auto-memory notes).
pub writable: bool,
pub valid: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
}
/// A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMemoryState {
pub entry: AgentMemoryEntry,
pub mode: AgentMemoryMode,
/// Optional provider filter from `[agents.memory.entries.<id>]`; empty means all agents.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub agents: Vec<String>,
pub origin: AgentMemoryOrigin,
}
/// Live auto-memory status and capability summary for one agent family.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentAutoMemoryStatus {
pub provider: String,
pub label: String,
pub mode: AutoMemoryMode,
pub origin: AgentMemoryOrigin,
pub note_count: u32,
pub rollout_count: u32,
pub approx_tokens: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub storage_path: Option<IpcPath>,
pub supports_auto_control: bool,
pub supports_file_exclusion: bool,
pub supports_reset: bool,
}
/// Full catalog returned to Settings › Agents › Memory and the Composer `MemoryPicker`.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMemoryCatalog {
pub entries: Vec<AgentMemoryState>,
pub providers: Vec<AgentAutoMemoryStatus>,
pub auto_memory: AutoMemoryMode,
pub auto_memory_origin: AgentMemoryOrigin,
}
/// Per-session memory overrides stored on an [`AgentTask`].
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentMemoryOverrides {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub auto_memory: Option<AutoMemoryMode>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub entries: BTreeMap<String, AgentMemoryMode>,
}
impl AgentMemoryOverrides {
pub fn is_empty(&self) -> bool {
self.auto_memory.is_none() && self.entries.is_empty()
}
}
/// Target format when creating a new memory or instruction file from Settings › Agents › Memory.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemoryCreateTarget {
/// `<workspace>/AGENTS.md` (or `~/.codex/AGENTS.md` in User scope).
#[default]
AgentsMd,
/// `<workspace>/.claude/rules/<slug>.md` or `~/.claude/rules/<slug>.md`.
ClaudeRule,
/// `<workspace>/.github/instructions/<slug>.instructions.md` or `~/.copilot/instructions/<slug>.instructions.md`.
CopilotInstruction,
/// `<workspace>/.cursor/rules/<slug>.mdc`.
CursorRule,
}
/// Payload for creating a new instruction or rule file.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CreateAgentMemoryInput {
pub scope: McpScope,
pub target: AgentMemoryCreateTarget,
#[serde(default)]
pub name: String,
#[serde(default)]
#[specta(optional)]
pub description: Option<String>,
#[serde(default)]
pub paths: Vec<String>,
pub content: String,
}
/// Payload for promoting an auto-memory note into `AGENTS.md`.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PromoteAgentMemoryInput {
pub source_id: String,
#[serde(default)]
#[specta(optional)]
pub heading: Option<String>,
#[serde(default)]
pub remove_source: bool,
}
/// Which CLI's own folders a skill was discovered in (Settings › Agents › Skills groups by it).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
+62 -6
Переглянути файл
@@ -174,10 +174,14 @@ struct Session {
mcp_off: Vec<String>,
/// The staged skills folder passed as `--add-dir` (its `.claude/skills` holds the copies).
skills_add_dir: Option<PathBuf>,
/// The staged memory rules folder passed as `--add-dir` (its `.claude/rules` holds shared rules).
memory_add_dir: Option<PathBuf>,
/// Load `.claude/rules` from `--add-dir` folders (`CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`).
additional_dirs_claude_md: bool,
/// The workspace's other roots, each passed as `--add-dir`.
additional_dirs: Vec<String>,
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
skills_settings: Option<String>,
/// Combined `--settings` JSON (`skillOverrides`, `autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`).
cli_settings: Option<String>,
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
ephemeral: bool,
shim: Weak<Shim>,
@@ -371,13 +375,20 @@ impl Shim {
}
});
let skills = params.pointer("/_meta/openidea/skills");
let memory = params.pointer("/_meta/openidea/memory");
let cli_settings = build_cli_settings(skills, memory);
let session = Arc::new(Session {
id: id.to_owned(),
mcp_config,
mcp_off,
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
memory_add_dir: memory.and_then(|m| m.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
additional_dirs_claude_md: memory
.and_then(|m| m.get("claudeAdditionalDirsClaudeMd"))
.and_then(Value::as_bool)
.unwrap_or(false),
additional_dirs: additional_dirs(params),
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
cli_settings,
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
shim: Arc::downgrade(self),
st: Mutex::new(State {
@@ -728,18 +739,28 @@ impl Session {
if let Some(dir) = &self.skills_add_dir {
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
}
if let Some(dir) = &self.memory_add_dir
&& self.skills_add_dir.as_ref() != Some(dir)
{
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
}
for dir in &self.additional_dirs {
args.extend(["--add-dir".to_owned(), dir.clone()]);
}
if let Some(settings) = &self.skills_settings {
if let Some(settings) = &self.cli_settings {
args.extend(["--settings".to_owned(), settings.clone()]);
}
if self.ephemeral {
args.push("--no-session-persistence".to_owned());
}
args.extend(start.args());
let launch =
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
let mut env = shim.config.env.clone();
if self.additional_dirs_claude_md
&& !env.iter().any(|(k, _)| k == "CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD")
{
env.push(("CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD".to_owned(), "1".to_owned()));
}
let launch = Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env };
let io = shim
.cli
.launch(&launch, shim.on_stderr.clone())
@@ -1601,6 +1622,41 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
/// Claude Code's own configuration stays off too.
/// Combines `skillOverrides` from `_meta.openidea.skills.claudeSettings` with memory
/// settings (`autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`) into one `--settings` JSON.
fn build_cli_settings(skills: Option<&Value>, memory: Option<&Value>) -> Option<String> {
let mut root = skills
.and_then(|s| s.get("claudeSettings"))
.and_then(Value::as_str)
.and_then(|raw| serde_json::from_str::<serde_json::Map<String, Value>>(raw).ok())
.unwrap_or_default();
if let Some(mem) = memory {
if let Some(auto) = mem.get("claudeAutoMemory").and_then(Value::as_bool) {
root.insert("autoMemoryEnabled".into(), json!(auto));
}
if let Some(excludes) = mem.get("claudeMdExcludes").and_then(Value::as_array) {
let clean: Vec<Value> =
excludes.iter().filter_map(Value::as_str).filter(|s| !s.is_empty()).map(|s| json!(s)).collect();
if !clean.is_empty() {
root.insert("claudeMdExcludes".into(), Value::Array(clean));
}
}
if let Some(inst) = mem.get("claudeInstructionFiles").and_then(Value::as_str).filter(|s| !s.is_empty()) {
root.insert(
"pluginConfigs".into(),
json!({
"cc-plugin-agents-md@builtin": {
"options": { "instructionFiles": inst }
}
}),
);
}
}
(!root.is_empty()).then(|| serde_json::to_string(&Value::Object(root)).expect("settings serialize"))
}
/// The session's `additionalDirectories`: the workspace's other roots.
fn additional_dirs(params: &Value) -> Vec<String> {
let dirs = params.get("additionalDirectories").and_then(Value::as_array);
+42
Переглянути файл
@@ -1442,3 +1442,45 @@ async fn an_ephemeral_session_is_not_saved() {
let args = cli.launched.lock()[0].clone();
assert!(args.contains(&"--no-session-persistence".to_owned()), "{args:?}");
}
#[tokio::test(flavor = "multi_thread")]
async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env() {
let cli = replay_cli(load_fixture("simple"));
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
let h =
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
let params = json!({
"cwd": h.cwd,
"mcpServers": [],
"_meta": {
"openidea": {
"skills": {
"claudeAddDir": "/tmp/farm-skills",
"claudeSettings": "{\"skillOverrides\":{\"tdd\":\"user-invocable-only\"}}"
},
"memory": {
"autoMemory": "readOnly",
"claudeAutoMemory": false,
"claudeMdExcludes": ["/repo/CLAUDE.local.md"],
"claudeInstructionFiles": "claude-md-and-agents-md",
"claudeAddDir": "/tmp/farm-memory",
"claudeAdditionalDirsClaudeMd": true
}
}
}
});
h.request("session/new", params).await.unwrap();
let args = cli.launched.lock()[0].clone();
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-skills"]), "{args:?}");
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-memory"]), "{args:?}");
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
assert_eq!(parsed["skillOverrides"]["tdd"], "user-invocable-only");
assert_eq!(parsed["autoMemoryEnabled"], false);
assert_eq!(parsed["claudeMdExcludes"], json!(["/repo/CLAUDE.local.md"]));
assert_eq!(
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
"claude-md-and-agents-md"
);
}
+14
Переглянути файл
@@ -20,6 +20,17 @@ pub(crate) const BUILTIN_COMMANDS: &[BuiltinCommandSpec] = &[
choices: &[("reconnect", "Reload and reconnect MCP servers.")],
},
BuiltinCommandSpec { name: "skills", description: "List available skills.", hint: None, choices: &[] },
BuiltinCommandSpec {
name: "memories",
description: "Show, enable, disable, or reset cross-session Codex memories.",
hint: Some("[show|on|off|reset]"),
choices: &[
("show", "Show consolidated memory summary for this thread."),
("on", "Enable memory generation for this thread."),
("off", "Disable memory generation for this thread."),
("reset", "Clear local Codex memory files and summaries."),
],
},
BuiltinCommandSpec {
name: "status",
description: "Display session configuration and token usage.",
@@ -79,6 +90,7 @@ pub(super) enum BuiltinCommand {
Plan,
Mcp,
Skills,
Memories,
Status,
Review,
ReviewBranch,
@@ -95,6 +107,7 @@ impl BuiltinCommand {
"plan" => Self::Plan,
"mcp" => Self::Mcp,
"skills" => Self::Skills,
"memories" => Self::Memories,
"status" => Self::Status,
"review" => Self::Review,
"review-branch" => Self::ReviewBranch,
@@ -150,6 +163,7 @@ mod tests {
"plan",
"mcp",
"skills",
"memories",
"status",
"review",
"review-branch",
+49
Переглянути файл
@@ -362,6 +362,23 @@ fn apply_thread_config(params: &Value, request: &mut Value) {
{
map.insert("skills".into(), json!({ "config": off }));
}
if let Some(mem) = params.pointer("/_meta/openidea/memory")
&& let Some(map) = config.as_object_mut()
{
let mut mem_cfg = serde_json::Map::new();
if let Some(use_m) = mem.get("codexUseMemories").and_then(Value::as_bool) {
mem_cfg.insert("use_memories".into(), json!(use_m));
}
if let Some(gen_m) = mem.get("codexGenerateMemories").and_then(Value::as_bool) {
mem_cfg.insert("generate_memories".into(), json!(gen_m));
}
if !mem_cfg.is_empty() {
map.insert("memories".into(), Value::Object(mem_cfg));
}
if let Some(dev) = mem.get("codexDeveloperInstructions").and_then(Value::as_str).filter(|s| !s.is_empty()) {
map.insert("developer_instructions".into(), json!(dev));
}
}
if !config.as_object().is_some_and(|m| m.is_empty()) {
request["config"] = config;
}
@@ -708,6 +725,7 @@ impl CodexShim {
let found = self.call("skills/list", json!({ "cwds": [cwd] })).await?;
self.say(session, skills_text(&found));
}
BuiltinCommand::Memories => self.memories_command(session, &command.rest).await?,
BuiltinCommand::Mcp => match command.rest.as_str() {
"" => self.say(session, self.mcp_text(session).await?),
rest if rest.eq_ignore_ascii_case("reconnect") => {
@@ -747,6 +765,36 @@ impl CodexShim {
Ok(json!({ "stopReason": "end_turn" }))
}
async fn memories_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
let arg = rest.trim().to_ascii_lowercase();
match arg.as_str() {
"" | "show" => {
let res = self.call("thread/memory/read", json!({ "threadId": session })).await?;
let summary = res
.get("summary")
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.unwrap_or("No consolidated memories for this thread yet.");
self.say(session, summary);
}
"on" => {
self.call("thread/memoryMode/set", json!({ "threadId": session, "mode": "enabled" })).await?;
self.say(session, "Memory generation enabled for this thread.");
}
"off" => {
self.call("thread/memoryMode/set", json!({ "threadId": session, "mode": "disabled" })).await?;
self.say(session, "Memory generation disabled for this thread.");
}
"reset" => {
self.call("memory/reset", Value::Null).await?;
self.say(session, "Reset local Codex memories.");
}
_ => self.say(session, command_usage(BuiltinCommand::Memories)),
}
Ok(())
}
async fn goal_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
let argument = rest.trim();
if argument.is_empty() {
@@ -1518,6 +1566,7 @@ fn command_usage(command: BuiltinCommand) -> String {
match command {
BuiltinCommand::Plan => "Command \"/plan\" accepts no arguments.".to_owned(),
BuiltinCommand::Mcp => "Command \"/mcp\" accepts no arguments, or `reconnect`.".to_owned(),
BuiltinCommand::Memories => "Command \"/memories\" accepts `[show|on|off|reset]`.".to_owned(),
BuiltinCommand::ReviewBranch => "Command \"/review-branch\" requires branch name.".to_owned(),
BuiltinCommand::ReviewCommit => "Command \"/review-commit\" requires commit sha.".to_owned(),
BuiltinCommand::Goal => "Command \"/goal\" requires [<objective>|clear|pause|resume].".to_owned(),
+75
Переглянути файл
@@ -1695,6 +1695,57 @@ async fn goal_commands_set_pause_resume_and_clear_through_app_server() {
}
}
#[tokio::test(flavor = "multi_thread")]
async fn memories_commands_read_toggle_and_reset_through_app_server() {
for (prompt, method, has_thread_id, expected_params, result, expected_text) in [
(
"/memories",
"thread/memory/read",
true,
json!({ "threadId": "s" }),
json!({ "summary": "Remembered: run targeted tests first." }),
"Remembered: run targeted tests first.",
),
(
"/memories show",
"thread/memory/read",
true,
json!({ "threadId": "s" }),
json!({ "summary": null }),
"No consolidated memories for this thread yet.",
),
(
"/memories on",
"thread/memoryMode/set",
true,
json!({ "threadId": "s", "mode": "enabled" }),
json!({}),
"Memory generation enabled for this thread.",
),
(
"/memories off",
"thread/memoryMode/set",
true,
json!({ "threadId": "s", "mode": "disabled" }),
json!({}),
"Memory generation disabled for this thread.",
),
("/memories reset", "memory/reset", false, Value::Null, json!({}), "Reset local Codex memories."),
] {
let (results, client, frames, _meta, _codex) =
replay_transcript(Scenario::Command(prompt), command_transcript(&[(method, result)])).await;
let session = session_of(&results, "new");
let sent = sent(&frames, method);
assert_eq!(sent.len(), 1, "{prompt}");
let mut expected = expected_params;
if has_thread_id {
expected["threadId"] = json!(session);
assert_eq!(sent[0]["params"], expected, "{prompt}");
}
assert_eq!(client.text(&session, "agent_message_chunk"), expected_text, "{prompt}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn missing_review_arguments_print_usage_without_starting_a_turn() {
for prompt in ["/review-branch", "/review-commit", "/rename", "/goal"] {
@@ -2087,6 +2138,8 @@ fn skills_become_commands_with_their_invocation_names() {
let builtins = builtin_commands();
let goal = builtins.iter().find(|c| c.name == "goal").unwrap();
assert_eq!(goal.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["clear", "pause", "resume"]);
let memories = builtins.iter().find(|c| c.name == "memories").unwrap();
assert_eq!(memories.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["show", "on", "off", "reset"]);
let mcp = builtins.iter().find(|c| c.name == "mcp").unwrap();
assert_eq!(mcp.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["reconnect"]);
assert!(skill_commands(&json!({"data": []})).unwrap()["availableCommands"].as_array().unwrap().is_empty());
@@ -2102,6 +2155,28 @@ fn workspace_roots_join_the_thread_roots() {
let mut request = json!({});
apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request);
assert!(request.get("runtimeWorkspaceRoots").is_none());
let mut mem_req = json!({});
apply_thread_config(
&json!({
"cwd": "/w/api",
"mcpServers": [],
"_meta": {
"openidea": {
"skills": { "codexOff": [["noisy", "/repo/.agents/skills/noisy/SKILL.md"]] },
"memory": {
"codexUseMemories": true,
"codexGenerateMemories": false,
"codexDeveloperInstructions": "## Memory (style)\nUse targeted selectors."
}
}
}
}),
&mut mem_req,
);
assert_eq!(mem_req["config"]["memories"], json!({ "use_memories": true, "generate_memories": false }));
assert_eq!(mem_req["config"]["developer_instructions"], "## Memory (style)\nUse targeted selectors.");
assert_eq!(mem_req["config"]["skills"]["config"][0]["enabled"], false);
}
#[tokio::test(flavor = "multi_thread")]
+34
Переглянути файл
@@ -462,6 +462,38 @@ fn apply_skills(params: &Value, req: &mut Value) {
}
}
/// Applies `_meta.openidea.memory` to Copilot's `session.create` / `session.resume` payload:
/// gates `store_memory` when auto-memory is `ReadOnly` or `Off`, disables custom instructions
/// when all workspace/user instructions are muted, and appends shared OpenIDEA memories.
fn apply_memory(params: &Value, req: &mut Value) {
let Some(mem) = params.pointer("/_meta/openidea/memory") else {
return;
};
if mem.get("copilotExcludeStoreMemory").and_then(Value::as_bool) == Some(true) {
let mut excluded: Vec<String> = req
.get("excludedTools")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
if !excluded.iter().any(|t| t == "store_memory") {
excluded.push("store_memory".into());
}
req["excludedTools"] = json!(excluded);
}
if mem.get("copilotDisableCustomInstructions").and_then(Value::as_bool) == Some(true) {
req["customInstructions"] = json!(false);
}
if let Some(sys) = mem.get("copilotSystemMessage").and_then(Value::as_str).filter(|s| !s.is_empty()) {
req["systemMessage"] = json!({
"mode": "append",
"content": sys,
});
}
}
fn invalid(message: impl Into<String>) -> ResponseError {
error(codes::INVALID_PARAMS, message)
}
@@ -588,6 +620,7 @@ impl CopilotShim {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
apply_memory(params, &mut req);
let created = self.call("session.create", req).await?;
let session_id = created
@@ -639,6 +672,7 @@ impl CopilotShim {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
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 {
+50
Переглянути файл
@@ -833,6 +833,56 @@ async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skil
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn session_new_and_load_apply_copilot_memory_gating_and_system_message() {
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 meta = json!({
"openidea": {
"memory": {
"autoMemory": "readOnly",
"copilotExcludeStoreMemory": true,
"copilotDisableCustomInstructions": true,
"copilotSystemMessage": "## Memory (shared)\nRun targeted tests."
}
}
});
let _: Value =
client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [], "_meta": meta }), None).await.unwrap();
let _: Value = client
.request(
"session/load",
json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [], "_meta": meta }),
None,
)
.await
.unwrap();
let calls = server.calls.lock();
for method in ["session.create", "session.resume"] {
let params = calls.iter().find_map(|(m, p)| (m == method).then_some(p)).expect(method);
assert_eq!(params["excludedTools"], json!(["store_memory"]), "{method}: {params}");
assert_eq!(params["customInstructions"], json!(false), "{method}: {params}");
assert_eq!(
params["systemMessage"],
json!({ "mode": "append", "content": "## Memory (shared)\nRun targeted tests." }),
"{method}: {params}"
);
}
}
#[test]
fn translates_context_attribution_without_double_counting_parent_rollups() {
let payload = json!({
+511 -96
Переглянути файл
@@ -15,6 +15,7 @@ use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_tools::Http;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::{HashMap, VecDeque};
use std::path::{Component, Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
@@ -106,6 +107,9 @@ pub struct InstallRemoteSkillRequest {
pub owner: String,
pub repo: String,
pub git_ref: String,
/// Root tree SHA returned by the preview. The install reads exactly this tree, so commits pushed
/// to `git_ref` after the user reviewed the preview are never installed.
pub tree_sha: String,
pub subpath: String,
pub scope: McpScope,
/// Must be `true` when the static security scan produces any warnings.
@@ -246,13 +250,13 @@ impl SkillSourceFetcher for GitHubHttpFetcher {
validate_repo_coord(owner, "owner")?;
validate_repo_coord(repo, "repository")?;
validate_git_ref(git_ref)?;
if blob_sha.is_empty() || !blob_sha.bytes().all(|b| b.is_ascii_hexdigit()) {
if !is_git_object_id(blob_sha) {
return Err(IdeError::invalid("invalid Git blob SHA"));
}
// Base64 expands by ~4/3 plus JSON wrapper.
let json_limit = max_bytes.saturating_mul(2).saturating_add(4096);
let blob_url = format!("https://api.github.com/repos/{owner}/{repo}/git/blobs/{blob_sha}");
match self.get_github_json(&blob_url, json_limit, cancel) {
let bytes = match self.get_github_json(&blob_url, json_limit, cancel) {
Ok(text) => {
let parsed: BlobResponse = serde_json::from_str(&text)
.map_err(|e| IdeError::new(ErrorKind::Protocol, format!("invalid Git blob JSON: {e}")))?;
@@ -269,7 +273,7 @@ impl SkillSourceFetcher for GitHubHttpFetcher {
if bytes.len() as u64 > max_bytes {
return Err(IdeError::invalid(format!("{repo_path}: exceeds {} KiB limit", max_bytes >> 10)));
}
Ok(bytes)
bytes
}
Err(api_err) => {
if cancel.is_cancelled() {
@@ -286,12 +290,34 @@ impl SkillSourceFetcher for GitHubHttpFetcher {
if bytes.len() as u64 > max_bytes {
return Err(IdeError::invalid(format!("{repo_path}: exceeds {} KiB limit", max_bytes >> 10)));
}
Ok(bytes)
bytes
}
};
// The raw fallback reads `git_ref`, which may have moved since the tree was listed.
if !git_blob_id(&bytes).eq_ignore_ascii_case(blob_sha) {
return Err(IdeError::new(
ErrorKind::Protocol,
format!("{repo_path}: downloaded content does not match Git blob {blob_sha}"),
));
}
Ok(bytes)
}
}
/// A 40-digit hex SHA-1 Git object id (GitHub does not host SHA-256 repositories).
fn is_git_object_id(id: &str) -> bool {
id.len() == 40 && id.bytes().all(|b| b.is_ascii_hexdigit())
}
/// Git's object id for a blob holding `bytes`.
fn git_blob_id(bytes: &[u8]) -> String {
use sha1::Digest as _;
let mut hasher = sha1::Sha1::new();
hasher.update(format!("blob {}\0", bytes.len()).as_bytes());
hasher.update(bytes);
hasher.finalize().iter().map(|b| format!("{b:02x}")).collect()
}
fn encode_url_segment(seg: &str) -> String {
let mut out = String::with_capacity(seg.len());
for b in seg.bytes() {
@@ -603,10 +629,12 @@ struct PreparedSkillBundle {
in_root_symlinks: Vec<(PathBuf, PathBuf)>,
}
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
fn fetch_and_scan_bundle(
fetcher: &dyn SkillSourceFetcher,
target: RepoRef<'_>,
subpath: &str,
pinned_tree_sha: Option<&str>,
cancel: &CancellationToken,
) -> IdeResult<PreparedSkillBundle> {
let RepoRef { owner, repo, git_ref } = target;
@@ -615,7 +643,23 @@ fn fetch_and_scan_bundle(
validate_git_ref(git_ref)?;
let normalized_subpath = normalize_subpath(subpath)?.unwrap_or_default();
let tree = fetcher.git_tree(target, cancel)?;
let tree = match pinned_tree_sha {
Some(sha) => {
if !is_git_object_id(sha) {
return Err(IdeError::invalid("Preview the skill again before installing it"));
}
// The Git trees API accepts a tree SHA in place of a ref.
let tree = fetcher.git_tree(RepoRef { owner, repo, git_ref: sha }, cancel)?;
if !tree.sha.eq_ignore_ascii_case(sha) {
return Err(IdeError::new(
ErrorKind::Protocol,
format!("{owner}/{repo}: GitHub returned tree {} instead of the previewed tree {sha}", tree.sha),
));
}
tree
}
None => fetcher.git_tree(target, cancel)?,
};
let prefix = if normalized_subpath.is_empty() { String::new() } else { format!("{normalized_subpath}/") };
let subtree_entries: Vec<&GitTreeEntry> = tree
@@ -647,7 +691,7 @@ fn fetch_and_scan_bundle(
let mut files = Vec::with_capacity(subtree_entries.len());
let mut scan_warnings = Vec::new();
let mut regular_files = Vec::new();
let mut in_root_symlinks = Vec::new();
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
let mut skill_markdown: Option<String> = None;
let mut actual_total = 0u64;
@@ -675,18 +719,7 @@ fn fetch_and_scan_bundle(
if is_symlink {
let target_raw = String::from_utf8_lossy(&bytes).trim().to_owned();
match resolve_in_root_symlink(&rel_path, &target_raw) {
Some(safe_target) => {
in_root_symlinks.push((rel_path.clone(), safe_target));
}
None => {
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::OutOfRootSymlink,
file: rel_str.to_owned(),
message: format!("Symlink target {target_raw:?} leaves the skill folder (omitted on install)"),
});
}
}
symlinks.push((rel_path, rel_str.to_owned(), target_raw));
files.push(RemoteSkillFile {
path: rel_str.to_owned(),
size: bytes.len() as u64,
@@ -734,6 +767,31 @@ fn fetch_and_scan_bundle(
files.sort_by(|a, b| a.path.cmp(&b.path));
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
// Symlinks are judged together: one link may point through another, and an entry placed beneath
// a symlink would be written wherever that link points.
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
if let Some(link) = graph.symlink_ancestor(path) {
return Err(IdeError::invalid(format!(
"Skill entry {:?} is inside symlink {link:?}; the repository tree is malformed",
path.display().to_string()
)));
}
}
let mut in_root_symlinks = Vec::new();
for (rel_path, rel_str, target_raw) in symlinks {
if graph.stays_inside(&rel_path, &target_raw) {
in_root_symlinks.push((rel_path, PathBuf::from(target_raw)));
} else {
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::OutOfRootSymlink,
file: rel_str,
message: format!("Symlink target {target_raw:?} leaves the skill folder (omitted on install)"),
});
}
}
in_root_symlinks.sort();
let Some(skill_markdown) = skill_markdown else {
return Err(IdeError::invalid("Selected folder does not contain a regular SKILL.md file"));
};
@@ -775,50 +833,30 @@ struct ParsedSkillMetadata {
fn parse_skill_markdown_metadata(folder_hint: &str, markdown: &str) -> IdeResult<ParsedSkillMetadata> {
let mut name: Option<String> = None;
let mut description: Option<String> = None;
let mut allowed_tools_raw: Vec<String> = Vec::new();
let normalized = markdown.strip_prefix('\u{feff}').unwrap_or(markdown);
if let Some(after_open) = normalized.strip_prefix("---\n").or_else(|| normalized.strip_prefix("---\r\n")) {
let mut current_list_key: Option<String> = None;
for raw_line in after_open.lines() {
let trimmed_end = raw_line.trim_end_matches('\r');
if matches!(trimmed_end.trim(), "---" | "...") {
break;
}
let trimmed = trimmed_end.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
if (trimmed_end.starts_with(' ') || trimmed_end.starts_with('\t'))
&& let Some(item) = trimmed.strip_prefix('-')
if trimmed.is_empty()
|| trimmed.starts_with('#')
|| trimmed_end.starts_with(' ')
|| trimmed_end.starts_with('\t')
{
if matches!(current_list_key.as_deref(), Some("allowed-tools" | "allowed_tools")) {
let val = unquote(item.trim());
if !val.is_empty() {
allowed_tools_raw.push(val.to_owned());
}
}
continue;
}
current_list_key = None;
if let Some((k, v)) = trimmed.split_once(':') {
let key = k.trim().to_ascii_lowercase();
let val = unquote(v.trim());
match key.as_str() {
"name" if !val.is_empty() => name = Some(val.to_owned()),
"description" if !val.is_empty() && !matches!(val, ">" | "|" | ">-" | "|-") => {
"description" if !val.is_empty() && !is_block_scalar_header(val) => {
description = Some(val.to_owned());
}
"allowed-tools" | "allowed_tools" => {
if val.is_empty() {
current_list_key = Some(key);
} else {
let inner = val.strip_prefix('[').and_then(|s| s.strip_suffix(']')).unwrap_or(val);
for token in split_allowed_tools(inner) {
allowed_tools_raw.push(token);
}
}
}
_ => {}
}
}
@@ -832,15 +870,86 @@ fn parse_skill_markdown_metadata(folder_hint: &str, markdown: &str) -> IdeResult
)));
}
let description = description.unwrap_or_default();
let shell_tools = allowed_tools_raw.into_iter().filter(|t| is_shell_tool_entry(t)).collect();
Ok(ParsedSkillMetadata { name: skill_name, description, shell_tools })
Ok(ParsedSkillMetadata { name: skill_name, description, shell_tools: frontmatter_shell_tools(markdown) })
}
fn split_allowed_tools(raw: &str) -> Vec<String> {
/// `|`, `>`, and their chomping/indentation variants (`>-`, `|+`, `|2-`, ...).
fn is_block_scalar_header(val: &str) -> bool {
let mut chars = val.chars();
matches!(chars.next(), Some('|' | '>')) && chars.all(|c| matches!(c, '+' | '-' | '1'..='9'))
}
/// Shell-capable entries granted by `allowed-tools` in the frontmatter.
///
/// This deliberately over-approximates YAML instead of parsing it: every token of the value — inline,
/// block scalar, flow or block sequence, continuation lines — is checked, and tokens a YAML loader could
/// turn into something else (aliases, escape sequences) count as grants. A false positive only adds a
/// warning; a missed grant hides one.
fn frontmatter_shell_tools(markdown: &str) -> Vec<String> {
let text = markdown.strip_prefix('\u{feff}').unwrap_or(markdown);
let mut lines = text.lines().skip_while(|l| l.trim().is_empty());
if lines.next().map(str::trim) != Some("---") {
return Vec::new();
}
let lines: Vec<&str> = lines.take_while(|l| !matches!(l.trim(), "---" | "...")).collect();
let mut tools: Vec<String> = Vec::new();
let mut i = 0;
while i < lines.len() {
let Some(rest) = after_allowed_tools_key(lines[i]) else {
i += 1;
continue;
};
let mut value = rest.to_owned();
i += 1;
while i < lines.len() && !is_plain_top_level_key(lines[i]) {
value.push('\n');
value.push_str(lines[i]);
i += 1;
}
for token in value_tokens(&value) {
let grants_shell = is_shell_tool_entry(&token) || token.starts_with('*') || token.contains('\\');
if grants_shell && !tools.contains(&token) {
tools.push(token);
}
}
}
tools
}
/// The text after an `allowed-tools` / `allowed_tools` / `allowedTools` key anywhere on `line`
/// (quoted keys and flow mappings included).
fn after_allowed_tools_key(line: &str) -> Option<&str> {
let lower = line.to_ascii_lowercase();
["allowed-tools", "allowed_tools", "allowedtools", "allowed tools"]
.iter()
.filter_map(|key| lower.find(key).map(|pos| pos + key.len()))
.min()
.map(|end| &line[end..])
}
/// An unindented `key:` line whose key is a plain word, which ends the previous key's value.
fn is_plain_top_level_key(line: &str) -> bool {
if !line.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_') {
return false;
}
let Some((key, rest)) = line.split_once(':') else { return false };
key.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | ' '))
&& (rest.is_empty() || rest.starts_with([' ', '\t']))
}
/// Splits a YAML value into candidate tool entries, keeping `Tool(args with spaces, commas)` whole.
fn value_tokens(value: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cur = String::new();
let mut depth = 0usize;
for ch in raw.chars() {
let mut flush = |cur: &mut String| {
let tok = cur.trim_start_matches([':', '-', '?', '&', '!', '|', '>']);
if !tok.is_empty() && !is_block_scalar_header(tok) {
out.push(tok.to_owned());
}
cur.clear();
};
for ch in value.chars() {
match ch {
'(' => {
depth += 1;
@@ -850,20 +959,13 @@ fn split_allowed_tools(raw: &str) -> Vec<String> {
depth = depth.saturating_sub(1);
cur.push(ch);
}
',' | ' ' if depth == 0 => {
let tok = unquote(cur.trim());
if !tok.is_empty() {
out.push(tok.to_owned());
}
cur.clear();
c if depth == 0 && (c.is_whitespace() || matches!(c, ',' | '[' | ']' | '{' | '}' | '"' | '\'')) => {
flush(&mut cur)
}
_ => cur.push(ch),
}
}
let tok = unquote(cur.trim());
if !tok.is_empty() {
out.push(tok.to_owned());
}
flush(&mut cur);
out
}
@@ -905,8 +1007,68 @@ fn validate_rel_skill_file(rel: &str) -> IdeResult<PathBuf> {
Ok(path.to_path_buf())
}
/// Returns `Some(target_path)` only when `target_raw` is a relative link that stays strictly inside the skill root.
fn resolve_in_root_symlink(link_rel: &Path, target_raw: &str) -> Option<PathBuf> {
/// The symlinks of one skill bundle, keyed by case-folded path so a link named `Dir` is also found as
/// `dir` (macOS and Windows file systems ignore case).
struct SymlinkGraph {
links: HashMap<Vec<String>, String>,
}
/// Maximum symlinks followed while resolving one target (Linux's `MAXSYMLINKS`).
const MAX_SYMLINK_HOPS: usize = 40;
impl SymlinkGraph {
fn new<'a>(links: impl Iterator<Item = (&'a Path, &'a str)>) -> Self {
Self { links: links.map(|(path, target)| (fold_path(path), target.to_owned())).collect() }
}
/// The nearest symlink among `path`'s ancestors, if any.
fn symlink_ancestor(&self, path: &Path) -> Option<String> {
let folded = fold_path(path);
(1..folded.len()).find(|&len| self.links.contains_key(&folded[..len])).map(|len| folded[..len].join("/"))
}
/// Whether `target_raw`, read from the link at `link_rel`, resolves strictly inside the skill root,
/// following every other symlink of the bundle it passes through.
fn stays_inside(&self, link_rel: &Path, target_raw: &str) -> bool {
let mut dir = fold_path(link_rel);
dir.pop();
let Some(mut pending) = relative_link_segments(target_raw) else { return false };
let mut hops = 0;
while let Some(seg) = pending.pop_front() {
if seg == ".." {
if dir.pop().is_none() {
return false;
}
continue;
}
dir.push(seg);
if let Some(next) = self.links.get(&dir) {
hops += 1;
let Some(mut next_segments) = relative_link_segments(next) else { return false };
if hops > MAX_SYMLINK_HOPS {
return false;
}
dir.pop();
next_segments.extend(pending);
pending = next_segments;
}
}
!dir.is_empty()
}
}
/// Case-folded normal components of a validated relative path.
fn fold_path(path: &Path) -> Vec<String> {
path.components()
.filter_map(|c| match c {
Component::Normal(s) => Some(s.to_string_lossy().to_lowercase()),
_ => None,
})
.collect()
}
/// Case-folded segments of a relative symlink target without `.`; `None` for absolute or Windows-style targets.
fn relative_link_segments(target_raw: &str) -> Option<VecDeque<String>> {
if target_raw.is_empty()
|| target_raw.starts_with('/')
|| target_raw.starts_with('~')
@@ -915,30 +1077,7 @@ fn resolve_in_root_symlink(link_rel: &Path, target_raw: &str) -> Option<PathBuf>
{
return None;
}
let mut stack: Vec<&std::ffi::OsStr> = link_rel
.parent()
.map(|p| {
p.components()
.filter_map(|c| match c {
Component::Normal(s) => Some(s),
_ => None,
})
.collect()
})
.unwrap_or_default();
for seg in target_raw.split('/') {
match seg {
"" | "." => {}
".." => {
stack.pop()?;
}
_ => stack.push(std::ffi::OsStr::new(seg)),
}
}
if stack.is_empty() {
return None;
}
Some(PathBuf::from(target_raw))
Some(target_raw.split('/').filter(|s| !s.is_empty() && *s != ".").map(str::to_lowercase).collect())
}
fn is_executable_or_script_path(rel: &Path) -> bool {
@@ -979,6 +1118,69 @@ fn scan_hidden_unicode(file: &str, text: &str, warnings: &mut Vec<SkillScanWarni
}
}
/// Creates the missing parent directories of `rel` under `root`, refusing to pass through a symlink or
/// anything else that is not a real directory.
fn create_parent_dirs_no_follow(root: &Path, rel: &Path) -> IdeResult<()> {
let mut dir = root.to_path_buf();
let Some(parent) = rel.parent() else { return Ok(()) };
for component in parent.components() {
dir.push(component);
match std::fs::symlink_metadata(&dir) {
Ok(meta) if meta.is_dir() => {}
Ok(_) => {
return Err(IdeError::invalid(format!(
"Skill path {:?} passes through a symlink or file",
rel.display().to_string()
)));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => std::fs::create_dir(&dir)?,
Err(e) => return Err(e.into()),
}
}
Ok(())
}
/// Whether the symlink at `link` resolves strictly inside `root` (canonical), following links on disk.
/// Components that do not exist are resolved lexically.
#[cfg(unix)]
fn link_resolves_inside(root: &Path, link: &Path) -> bool {
let (Some(parent), Ok(target)) = (link.parent(), std::fs::read_link(link)) else { return false };
let Ok(mut dir) = std::fs::canonicalize(parent) else { return false };
if !dir.starts_with(root) || target.is_absolute() {
return false;
}
let mut pending: VecDeque<PathBuf> = target.components().map(|c| PathBuf::from(c.as_os_str())).collect();
let mut hops = 0;
while let Some(seg) = pending.pop_front() {
match seg.to_str() {
Some(".") => continue,
Some("..") => {
if dir == root {
return false;
}
dir.pop();
continue;
}
_ => {}
}
let next = dir.join(&seg);
match std::fs::symlink_metadata(&next) {
Ok(meta) if meta.file_type().is_symlink() => {
hops += 1;
let Ok(next_target) = std::fs::read_link(&next) else { return false };
if hops > MAX_SYMLINK_HOPS || next_target.is_absolute() {
return false;
}
for c in next_target.components().rev() {
pending.push_front(PathBuf::from(c.as_os_str()));
}
}
_ => dir = next,
}
}
dir != root
}
/// Previews a single skill from `target` (`subpath`) and runs the static security scan.
pub fn preview_skill(
fetcher: &dyn SkillSourceFetcher,
@@ -989,7 +1191,7 @@ pub fn preview_skill(
cancel: &CancellationToken,
) -> IdeResult<RemoteSkillPreview> {
let RepoRef { owner, repo, git_ref } = target;
let bundle = fetch_and_scan_bundle(fetcher, target, subpath, cancel)?;
let bundle = fetch_and_scan_bundle(fetcher, target, subpath, None, cancel)?;
let already_installed_user = user_home.is_some_and(|h| h.join(".agents/skills").join(&bundle.skill_name).exists());
let already_installed_workspace =
workspace_root.is_some_and(|w| w.join(".agents/skills").join(&bundle.skill_name).exists());
@@ -1034,6 +1236,7 @@ pub fn install_skill(
fetcher,
RepoRef { owner: &req.owner, repo: &req.repo, git_ref: &req.git_ref },
&req.subpath,
Some(&req.tree_sha),
cancel,
)?;
if !bundle.scan_warnings.is_empty() && !req.confirm_warnings {
@@ -1056,10 +1259,8 @@ pub fn install_skill(
let write_res = (|| -> IdeResult<()> {
std::fs::create_dir_all(&staging)?;
for (rel_path, bytes, is_exec) in &bundle.regular_files {
create_parent_dirs_no_follow(&staging, rel_path)?;
let dest = staging.join(rel_path);
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&dest, bytes)?;
#[cfg(unix)]
if *is_exec {
@@ -1070,10 +1271,8 @@ pub fn install_skill(
let _ = is_exec;
}
for (rel_link, target) in &bundle.in_root_symlinks {
create_parent_dirs_no_follow(&staging, rel_link)?;
let dest = staging.join(rel_link);
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
#[cfg(unix)]
std::os::unix::fs::symlink(target, &dest)?;
#[cfg(not(unix))]
@@ -1084,6 +1283,20 @@ pub fn install_skill(
}
}
}
// Backstop for the scan's graph check: resolve every created link on disk, where the file
// system's own case and Unicode folding apply.
#[cfg(unix)]
{
let root = std::fs::canonicalize(&staging)?;
for (rel_link, _) in &bundle.in_root_symlinks {
if !link_resolves_inside(&root, &staging.join(rel_link)) {
return Err(IdeError::invalid(format!(
"Symlink {:?} leaves the skill folder",
rel_link.display().to_string()
)));
}
}
}
let backup = if final_dir.exists() {
let bak = target_root.join(format!(".old-{}-{nonce}", bundle.skill_name));
std::fs::rename(&final_dir, &bak)?;
@@ -1128,8 +1341,8 @@ mod tests {
fn add_tree(&mut self, git_ref: &str, entries: Vec<(&str, &str, &[u8])>) {
let mut tree_entries = Vec::new();
for (idx, (path, mode, content)) in entries.into_iter().enumerate() {
let sha = format!("{idx:040x}");
for (path, mode, content) in entries {
let sha = git_blob_id(content);
self.blobs.insert(sha.clone(), content.to_vec());
tree_entries.push(GitTreeEntry {
path: path.to_owned(),
@@ -1139,10 +1352,14 @@ mod tests {
size: Some(content.len() as u64),
});
}
self.trees.insert(
git_ref.to_owned(),
GitTree { sha: "deadbeef".repeat(5), truncated: false, tree: tree_entries },
);
let sha = git_blob_id(format!("{git_ref}:{}", self.trees.len()).as_bytes());
let tree = GitTree { sha: sha.clone(), truncated: false, tree: tree_entries };
self.trees.insert(sha.clone(), tree.clone());
self.trees.insert(git_ref.to_owned(), tree);
}
fn tree_sha(&self, git_ref: &str) -> String {
self.trees[git_ref].sha.clone()
}
}
@@ -1251,6 +1468,7 @@ mod tests {
owner: "acme".into(),
repo: "skills".into(),
git_ref: "main".into(),
tree_sha: fetcher.tree_sha("main"),
subpath: "skills/clean-skill".into(),
scope: McpScope::User,
confirm_warnings: false,
@@ -1273,6 +1491,7 @@ mod tests {
owner: "acme".into(),
repo: "skills".into(),
git_ref: "main".into(),
tree_sha: fetcher.tree_sha("main"),
subpath: "skills/clean-skill".into(),
scope: McpScope::User,
confirm_warnings: false,
@@ -1307,6 +1526,7 @@ mod tests {
owner: "acme".into(),
repo: "skills".into(),
git_ref: "main".into(),
tree_sha: fetcher.tree_sha("main"),
subpath: "skills/risky-skill".into(),
scope: McpScope::Workspace,
confirm_warnings: false,
@@ -1325,6 +1545,7 @@ mod tests {
owner: "acme".into(),
repo: "skills".into(),
git_ref: "main".into(),
tree_sha: fetcher.tree_sha("main"),
subpath: "skills/risky-skill".into(),
scope: McpScope::Workspace,
confirm_warnings: true,
@@ -1341,6 +1562,199 @@ mod tests {
assert!(!ws_installed.join("escape-link").exists(), "out-of-root symlink omitted on disk");
}
fn install_req(fetcher: &FakeFetcher, git_ref: &str, tree_sha: Option<String>) -> InstallRemoteSkillRequest {
InstallRemoteSkillRequest {
owner: "acme".into(),
repo: "skills".into(),
git_ref: git_ref.into(),
tree_sha: tree_sha.unwrap_or_else(|| fetcher.tree_sha(git_ref)),
subpath: String::new(),
scope: McpScope::User,
confirm_warnings: true,
overwrite: false,
}
}
fn preview_main(fetcher: &FakeFetcher, home: &Path) -> IdeResult<RemoteSkillPreview> {
preview_skill(
fetcher,
RepoRef { owner: "acme", repo: "skills", git_ref: "main" },
"",
Some(home),
None,
&CancellationToken::new(),
)
}
const SKILL_MD: &[u8] = b"---\nname: linky\ndescription: Links\n---\nBody\n";
#[test]
fn rejects_entries_nested_under_a_symlink() {
let mut fetcher = FakeFetcher::new();
fetcher.add_tree(
"main",
vec![
("SKILL.md", "100644", SKILL_MD),
("sub2/keep.md", "100644", b"x"),
("d1/d2/d3/sub", "120000", b"../../../sub2"),
("d1/d2/d3/sub/escape", "120000", b"../../../outside"),
("d1/d2/d3/sub/escape/deeper", "120000", b"x"),
],
);
let tmp = tempfile::tempdir().unwrap();
let err = preview_main(&fetcher, tmp.path()).unwrap_err();
assert!(err.message.contains("inside symlink"), "{err:?}");
let err = install_skill(
&fetcher,
&install_req(&fetcher, "main", None),
Some(tmp.path()),
None,
&CancellationToken::new(),
)
.unwrap_err();
assert!(err.message.contains("inside symlink"), "{err:?}");
assert!(!tmp.path().join(".agents/outside").exists());
// Case-only differences still count on case-insensitive file systems.
let mut fetcher = FakeFetcher::new();
fetcher.add_tree(
"main",
vec![("SKILL.md", "100644", SKILL_MD), ("Link", "120000", b"refs"), ("link/x", "120000", b"../..")],
);
assert!(preview_main(&fetcher, tmp.path()).unwrap_err().message.contains("inside symlink"));
}
#[test]
fn symlink_targets_are_resolved_through_other_links() {
let mut fetcher = FakeFetcher::new();
fetcher.add_tree(
"main",
vec![
("SKILL.md", "100644", SKILL_MD),
("a/b/doc.md", "100644", b"doc"),
("a/b/up", "120000", b".."),
("a/b/Up2", "120000", b".."),
("ok", "120000", b"a/b/up/b/doc.md"),
("escape", "120000", b"a/b/up/x/../../.."),
("escape-case", "120000", b"a/b/up2/x/../../.."),
("loop1", "120000", b"loop2/x"),
("loop2", "120000", b"loop1"),
],
);
let tmp = tempfile::tempdir().unwrap();
let preview = preview_main(&fetcher, tmp.path()).unwrap();
let mut flagged: Vec<&str> = preview
.scan_warnings
.iter()
.filter(|w| w.kind == SkillScanWarningKind::OutOfRootSymlink)
.map(|w| w.file.as_str())
.collect();
flagged.sort();
assert_eq!(flagged, ["escape", "escape-case", "loop1", "loop2"]);
let dir = install_skill(
&fetcher,
&install_req(&fetcher, "main", None),
Some(tmp.path()),
None,
&CancellationToken::new(),
)
.unwrap();
#[cfg(unix)]
assert_eq!(std::fs::read_to_string(dir.join("ok")).unwrap(), "doc");
for omitted in ["escape", "escape-case", "loop1", "loop2"] {
assert!(std::fs::symlink_metadata(dir.join(omitted)).is_err(), "{omitted}");
}
}
#[cfg(unix)]
#[test]
fn install_writes_refuse_to_pass_through_symlinks_on_disk() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
std::fs::create_dir_all(&root).unwrap();
std::os::unix::fs::symlink(tmp.path(), root.join("out")).unwrap();
let err = create_parent_dirs_no_follow(&root, Path::new("out/escaped/file")).unwrap_err();
assert!(err.message.contains("symlink"), "{err:?}");
assert!(!tmp.path().join("escaped").exists());
let canonical = std::fs::canonicalize(&root).unwrap();
std::fs::create_dir_all(root.join("a")).unwrap();
std::os::unix::fs::symlink("..", root.join("a/up")).unwrap();
std::os::unix::fs::symlink("up/a", root.join("a/ok")).unwrap();
std::os::unix::fs::symlink("up/a/up/..", root.join("a/bad")).unwrap();
assert!(link_resolves_inside(&canonical, &root.join("a/ok")));
assert!(!link_resolves_inside(&canonical, &root.join("a/up")), "link to the root itself");
assert!(!link_resolves_inside(&canonical, &root.join("a/bad")));
}
#[test]
fn allowed_tools_shell_grants_are_found_in_any_yaml_form() {
let shell = |fm: &str| frontmatter_shell_tools(&format!("---\nname: x\n{fm}\n---\nbody\n"));
for fm in [
"allowed-tools: >\n Bash",
"allowed-tools: |-\n Read\n Bash(git:*)",
"allowed-tools: >2+\n Bash",
"allowed-tools: Read\n Bash",
"allowed-tools: [Read,\n Bash]",
"allowed-tools:\n- Read\n- Bash",
"allowed-tools:\n - Read\n - \"Bash(git commit:*)\"",
"\"allowed-tools\": Bash",
"'allowed_tools':Bash",
"allowedTools: Read, Bash",
"allowed-tools: Read # comment\n Bash",
"tools: &t Bash\nallowed-tools: *t",
"allowed-tools: \"\\x42ash\"",
"allowed-tools: '*'",
] {
assert!(!shell(fm).is_empty(), "missed shell grant in {fm:?}");
}
for fm in ["allowed-tools: Read Grep", "allowed-tools:\n - Read\n - Edit\ndescription: >\n Bash in prose"] {
assert!(shell(fm).is_empty(), "false positive for {fm:?}: {:?}", shell(fm));
}
// Leniently opened fences still count.
assert!(!frontmatter_shell_tools("\n--- \nallowed-tools: >\n Bash\n---\n").is_empty());
let mut fetcher = FakeFetcher::new();
fetcher.add_tree(
"main",
vec![("SKILL.md", "100644", b"---\nname: benign\ndescription: x\nallowed-tools: >\n Bash\n---\n")],
);
let tmp = tempfile::tempdir().unwrap();
let preview = preview_main(&fetcher, tmp.path()).unwrap();
assert!(preview.scan_warnings.iter().any(|w| w.kind == SkillScanWarningKind::AllowedToolsShell));
}
#[test]
fn install_uses_the_previewed_tree_even_after_the_ref_moves() {
let mut fetcher = FakeFetcher::new();
fetcher.add_tree("main", vec![("SKILL.md", "100644", SKILL_MD)]);
let tmp = tempfile::tempdir().unwrap();
let preview = preview_main(&fetcher, tmp.path()).unwrap();
assert!(preview.scan_warnings.is_empty());
// `main` moves to a tree with a script after the user reviewed the preview.
fetcher.add_tree(
"main",
vec![("SKILL.md", "100644", SKILL_MD), ("scripts/payload.sh", "100755", b"#!/bin/sh\nid\n")],
);
assert_ne!(fetcher.tree_sha("main"), preview.tree_sha);
let mut req = install_req(&fetcher, "main", Some(preview.tree_sha.clone()));
req.confirm_warnings = false;
let dir = install_skill(&fetcher, &req, Some(tmp.path()), None, &CancellationToken::new()).unwrap();
assert!(dir.join("SKILL.md").is_file());
assert!(!dir.join("scripts").exists());
let bad = install_req(&fetcher, "main", Some("not-a-sha".into()));
assert!(install_skill(&fetcher, &bad, Some(tmp.path()), None, &CancellationToken::new()).is_err());
}
#[test]
fn git_blob_id_matches_git() {
assert_eq!(git_blob_id(b""), "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391");
assert_eq!(git_blob_id(b"hello\n"), "ce013625030ba8dba906f756967f9e9ca394464a");
}
#[test]
#[ignore = "hits live GitHub API"]
fn live_github_browse_preview_and_install_smoke() {
@@ -1369,6 +1783,7 @@ mod tests {
owner: browsed.owner,
repo: browsed.repo,
git_ref: browsed.git_ref,
tree_sha: preview.tree_sha,
subpath: browsed.skills[0].subpath.clone(),
scope: McpScope::User,
confirm_warnings: true,
+167 -4
Переглянути файл
@@ -69,6 +69,8 @@ struct FakeAgent {
prompts: Mutex<Vec<Value>>,
/// Queued errors returned on the next `session/prompt` calls before succeeding.
prompt_errors: Mutex<VecDeque<(i64, String)>>,
/// Recorded `(method, _meta.openidea.memory)` payloads across `session/new`, `session/load`, and `session/fork`.
memory_calls: Mutex<Vec<(String, Option<Value>)>>,
}
impl FakeAgent {
@@ -179,6 +181,7 @@ impl Handler for FakeAgent {
})
.unwrap_or_default();
self.mcp_calls.lock().push((method.to_owned(), names));
self.memory_calls.lock().push((method.to_owned(), params.pointer("/_meta/openidea/memory").cloned()));
if params.pointer("/_meta/openidea/ephemeral") == Some(&json!(true)) {
self.calls.lock().push("ephemeral".into());
}
@@ -1286,6 +1289,7 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
"plan",
"mcp",
"skills",
"memories",
"status",
"review",
"review-branch",
@@ -1325,6 +1329,7 @@ async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metada
"plan",
"mcp",
"skills",
"memories",
"status",
"review",
"review-branch",
@@ -5971,6 +5976,7 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
idle: false,
skill_overrides: BTreeMap::new(),
memory_overrides: None,
ephemeral: false,
})
.await
@@ -5999,6 +6005,127 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cursor_and_hermes() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::write(root.join("AGENTS.md"), "# Workspace Rules\nRun vitest first.\n").unwrap();
std::fs::write(root.join("CLAUDE.local.md"), "Noisy local draft\n").unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(root, agent.clone());
mgr.set_memory_policy_hook(Box::new({
let root = root.to_path_buf();
move || memory::MemoryPolicy {
user: AgentMemorySettings { auto_memory: AutoMemoryMode::ReadWrite, ..Default::default() },
workspace: AgentMemorySettings::default(),
workspace_trusted: true,
workspace_roots: vec![root.clone()],
}
}));
// 1. Claude task with initial `ReadOnly` + muted `CLAUDE.local.md`, then updated while idle, forked, and deleted.
let claude_task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
memory_overrides: Some(AgentMemoryOverrides {
auto_memory: Some(AutoMemoryMode::ReadOnly),
entries: BTreeMap::from([("claudeWorkspace::CLAUDE.local.md".into(), AgentMemoryMode::Off)]),
}),
idle: false,
ephemeral: false,
})
.await
.unwrap();
wait_for(&mgr, &claude_task.id, AgentStatus::Ready).await;
{
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
assert_eq!(method, "session/new");
let mem = payload.unwrap();
assert_eq!(mem["autoMemory"], "readOnly");
assert_eq!(mem["claudeAutoMemory"], false);
assert!(
mem["claudeMdExcludes"]
.as_array()
.unwrap()
.iter()
.any(|v| v.as_str().is_some_and(|s| s.ends_with("CLAUDE.local.md")))
);
}
// Updating `set_memory_overrides` while idle recycles the session so the next turn reloads (`session/load`) with `Off`.
let updated = mgr
.set_memory_overrides(
&claude_task.id,
AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off), entries: BTreeMap::new() },
)
.unwrap();
assert_eq!(updated.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::Off));
mgr.prompt(&claude_task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &claude_task.id, AgentStatus::Ready).await;
{
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
assert_eq!(method, "session/load");
assert_eq!(payload.unwrap()["autoMemory"], "off");
}
// Forking carries `memory_overrides` onto the forked task and sends `_meta.openidea.memory` on `session/fork`.
let forked = mgr.fork(&claude_task.id, None).await.unwrap();
assert_eq!(forked.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::Off));
{
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
assert_eq!(method, "session/fork");
assert_eq!(payload.unwrap()["autoMemory"], "off");
}
mgr.delete(&claude_task.id, false).await.unwrap();
assert!(!memory::farm_dir(&mgr.shared.paths.store_dir, &claude_task.id).exists());
// 2. Codex, Copilot, Cursor (ACP), and Hermes (ACP) each receive their normalized `_meta.openidea.memory`.
for (provider, expected_field) in [
("codex", Some("codexUseMemories")),
("copilot", Some("copilotEnableMemory")),
("cursor", None),
("hermes", None),
] {
let t = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: provider.into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
memory_overrides: Some(AgentMemoryOverrides {
auto_memory: Some(AutoMemoryMode::ReadOnly),
entries: BTreeMap::new(),
}),
idle: false,
ephemeral: false,
})
.await
.unwrap();
wait_for(&mgr, &t.id, AgentStatus::Ready).await;
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
assert_eq!(method, "session/new", "provider {provider}");
let mem = payload.expect("memory delivery present");
assert_eq!(mem["autoMemory"], "readOnly", "provider {provider}");
if let Some(field) = expected_field {
assert!(mem.get(field).is_some(), "provider {provider} missing {field}: {mem}");
}
}
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idle() {
let tmp = tempfile::tempdir().unwrap();
@@ -6034,6 +6161,7 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl
("tdd".into(), AgentSkillMode::Auto),
("noisy".into(), AgentSkillMode::Off),
]),
memory_overrides: None,
ephemeral: false,
})
.await
@@ -6178,6 +6306,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
memory_overrides: None,
ephemeral: false,
})
.await
@@ -6205,6 +6334,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
memory_overrides: None,
ephemeral: false,
})
.await
@@ -6284,20 +6414,20 @@ done
#[test]
fn session_params_name_the_servers_off() {
let mcp = McpForSession { servers: vec![json!({ "name": "docs" })], off: vec!["github".into()] };
let params = session_params("/p", &mcp, None, &[]);
let params = session_params("/p", &mcp, None, None, &[]);
assert_eq!(params["cwd"], "/p");
assert_eq!(params["mcpServers"][0]["name"], "docs");
assert_eq!(params["_meta"]["openidea"]["mcpServersOff"], json!(["github"]));
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
assert!(session_params("/p", &none, None, &[]).get("_meta").is_none());
assert!(session_params("/p", &none, None, None, &[]).get("_meta").is_none());
}
#[test]
fn session_params_offer_the_workspace_roots() {
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
let params = session_params("/w/api", &none, None, &["/w/web".to_owned()]);
let params = session_params("/w/api", &none, None, None, &["/w/web".to_owned()]);
assert_eq!(params["additionalDirectories"], json!(["/w/web"]));
assert!(session_params("/w/api", &none, None, &[]).get("additionalDirectories").is_none());
assert!(session_params("/w/api", &none, None, None, &[]).get("additionalDirectories").is_none());
}
#[tokio::test]
@@ -6798,3 +6928,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);
}
+2 -1
Переглянути файл
@@ -1,6 +1,6 @@
[package]
name = "ide-android"
description = "Android devices and logcat for the Logcat tool window, driven through the adb CLI"
description = "Android devices and iOS Simulators and their logs for the Logcat tool window, driven through adb and simctl"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -8,6 +8,7 @@ license.workspace = true
[dependencies]
ide-core.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
which = "8"
+199
Переглянути файл
@@ -0,0 +1,199 @@
//! iOS Simulators and their unified log, driven through `xcrun simctl` (macOS only).
//!
//! A simulator's log is followed with `simctl spawn <udid> log stream --style ndjson`
//! and parsed into the same [`LogcatLine`] the Android log uses, so the Logcat tool
//! window shows both with one level filter and one filter language.
use crate::model::{LogcatLevel, LogcatLine};
use crate::process;
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::process::Command;
use std::time::Duration;
const LIST: Duration = Duration::from_secs(20);
const BATCH_IDLE: Duration = Duration::from_millis(60);
const BATCH_MAX: usize = 300;
/// A booted simulator, as `simctl list devices booted -j` reports it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct BootedSimulator {
pub udid: String,
pub name: String,
/// e.g. `iOS 27.0`.
pub runtime: String,
}
/// Booted simulators; empty off macOS or without Xcode, so nothing iOS-related shows there.
pub fn booted_simulators() -> IdeResult<Vec<BootedSimulator>> {
if !cfg!(target_os = "macos") {
return Ok(Vec::new());
}
let mut cmd = Command::new("xcrun");
cmd.args(["simctl", "list", "devices", "booted", "-j"]);
match process::run(cmd, LIST, None) {
Ok(out) if out.success => Ok(parse_simulators(&out.stdout)),
// No Xcode (only the Command Line Tools, or none): there are no simulators.
_ => Ok(Vec::new()),
}
}
/// Parses `simctl list devices -j`, keeping booted devices.
pub fn parse_simulators(json: &str) -> Vec<BootedSimulator> {
#[derive(Deserialize)]
struct List {
devices: std::collections::BTreeMap<String, Vec<Device>>,
}
#[derive(Deserialize)]
struct Device {
udid: String,
name: String,
state: String,
}
let Ok(list) = serde_json::from_str::<List>(json) else {
return Vec::new();
};
let mut out = Vec::new();
for (runtime, devices) in list.devices {
// "com.apple.CoreSimulator.SimRuntime.iOS-27-0" → "iOS 27.0"
let short = runtime.rsplit('.').next().unwrap_or(&runtime);
let runtime = short.split_once('-').map_or(short.to_owned(), |(os, v)| format!("{os} {}", v.replace('-', ".")));
for d in devices.into_iter().filter(|d| d.state == "Booted") {
out.push(BootedSimulator { udid: d.udid, name: d.name, runtime: runtime.clone() });
}
}
out
}
/// Message type of the unified log → the logcat level the window filters and colors by.
fn level(message_type: &str) -> LogcatLevel {
match message_type {
"Debug" => LogcatLevel::Debug,
"Info" | "Default" => LogcatLevel::Info,
"Error" => LogcatLevel::Error,
"Fault" => LogcatLevel::Fatal,
_ => LogcatLevel::Verbose,
}
}
/// One NDJSON entry of `log stream --style ndjson`; `None` for anything that is not a
/// log message (activities, the trailing "terminated" notice). Unknown fields are ignored.
pub fn parse_ndjson(line: &str) -> Option<LogcatLine> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Entry {
event_type: String,
#[serde(default)]
message_type: String,
#[serde(default)]
timestamp: String,
#[serde(default)]
process_image_path: String,
#[serde(rename = "processID", default)]
pid: i64,
#[serde(rename = "threadID", default)]
tid: i64,
#[serde(default)]
subsystem: String,
#[serde(default)]
category: String,
#[serde(default)]
event_message: String,
}
let e: Entry = serde_json::from_str(line).ok()?;
if e.event_type != "logEvent" {
return None;
}
let process = e.process_image_path.rsplit('/').next().unwrap_or_default();
let tag = match (e.subsystem.is_empty(), e.category.is_empty()) {
(true, _) => process.to_owned(),
(false, true) => format!("{process} ({})", e.subsystem),
(false, false) => format!("{process} ({}:{})", e.subsystem, e.category),
};
// "2026-11-29 14:39:31.696480+0900" → "11-29 14:39:31.696", logcat's shape.
let time = e.timestamp.get(5..23).unwrap_or(&e.timestamp).to_owned();
Some(LogcatLine {
time,
pid: e.pid as i32,
tid: e.tid as i32,
level: level(&e.message_type),
tag,
message: e.event_message,
})
}
/// Follows simulator `udid`'s log until `cancel` fires or the simulator shuts down.
pub fn simulator_log(
udid: &str,
cancel: &CancellationToken,
on_batch: &mut dyn FnMut(Vec<LogcatLine>),
) -> IdeResult<()> {
let mut cmd = Command::new("xcrun");
cmd.args(["simctl", "spawn", udid, "log", "stream", "--style", "ndjson", "--level", "debug"]);
match process::stream_batched(cmd, cancel, BATCH_IDLE, BATCH_MAX, parse_ndjson, on_batch) {
Ok((ok, _)) if ok || cancel.is_cancelled() => Ok(()),
// `log stream` is killed when the simulator shuts down: that is an end, not a failure.
Ok((_, stderr)) if stderr.iter().any(|l| l.contains("terminated with signal")) => Ok(()),
Ok((_, stderr)) => Err(IdeError::unavailable(format!("log stream on {udid} stopped: {}", stderr.join("\n")))),
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => Ok(()),
Err(e) => Err(e),
}
}
#[cfg(test)]
mod tests {
use super::*;
const ENTRY: &str = r#"{"timezoneName":"","messageType":"Error","eventType":"logEvent","source":null,"subsystem":"com.apple.network","category":"endpoint","threadID":90176044,"processImagePath":"\/usr\/libexec\/remindd","timestamp":"2026-11-29 14:39:31.696480+0900","eventMessage":"endpoint has nothing to cleanup","processID":64339,"someFutureField":{"x":[1,2]}}"#;
#[test]
fn parses_an_entry_and_ignores_unknown_fields() {
let line = parse_ndjson(ENTRY).unwrap();
assert_eq!(line.time, "11-29 14:39:31.696");
assert_eq!(line.pid, 64339);
assert_eq!(line.tid, 90176044);
assert_eq!(line.level, LogcatLevel::Error);
assert_eq!(line.tag, "remindd (com.apple.network:endpoint)");
assert_eq!(line.message, "endpoint has nothing to cleanup");
}
#[test]
fn keeps_a_multi_line_message_whole() {
let entry = r#"{"eventType":"logEvent","messageType":"Default","processImagePath":"/a/MyApp","processID":7,"eventMessage":"first\nsecond"}"#;
let line = parse_ndjson(entry).unwrap();
assert_eq!(line.message, "first\nsecond");
assert_eq!(line.tag, "MyApp");
assert_eq!(line.level, LogcatLevel::Info);
}
#[test]
fn skips_what_is_not_a_log_message() {
assert!(parse_ndjson(r#"{"eventType":"activityCreateEvent","eventMessage":"x"}"#).is_none());
assert!(parse_ndjson("Child process terminated with signal 15: Terminated").is_none());
assert!(parse_ndjson("").is_none());
}
#[test]
fn maps_message_types_to_levels() {
assert_eq!(level("Debug"), LogcatLevel::Debug);
assert_eq!(level("Info"), LogcatLevel::Info);
assert_eq!(level("Default"), LogcatLevel::Info);
assert_eq!(level("Error"), LogcatLevel::Error);
assert_eq!(level("Fault"), LogcatLevel::Fatal);
assert_eq!(level("Signpost"), LogcatLevel::Verbose);
}
#[test]
fn reads_booted_simulators() {
let json = r#"{"devices":{"com.apple.CoreSimulator.SimRuntime.iOS-27-0":[
{"udid":"A","name":"iPhone Air","state":"Booted","isAvailable":true},
{"udid":"B","name":"iPhone 18","state":"Shutdown"}]}}"#;
assert_eq!(
parse_simulators(json),
vec![BootedSimulator { udid: "A".into(), name: "iPhone Air".into(), runtime: "iOS 27.0".into() }]
);
assert!(parse_simulators("not json").is_empty());
}
}
+2
Переглянути файл
@@ -7,9 +7,11 @@
//!
//! Every function blocks; callers run them off the UI / command threads.
mod ios;
mod model;
mod process;
pub use ios::{BootedSimulator, booted_simulators, parse_ndjson, parse_simulators, simulator_log};
pub use model::*;
use ide_core::process::{own_group, prepare};
+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();
+135
Переглянути файл
@@ -815,6 +815,74 @@ pub fn run(
})
}
/// Messages of an `xcodebuild` whose output arrives line by line (an Xcode run configuration),
/// each reported once: xcodebuild prints a message for every architecture and again on retries.
pub struct XcodebuildMessages {
parser: OutputParser,
cwd: PathBuf,
paths: PathMap,
lines: Lines,
seen: HashSet<(Option<PathBuf>, Option<Range>, String)>,
/// xcodebuild printed its result (`** BUILD SUCCEEDED **`); what follows is the app's console.
done: bool,
}
impl XcodebuildMessages {
/// Relative paths resolve against `cwd`; paths under `root`'s canonical form map back to `root`.
pub fn new(root: &Path, cwd: &Path) -> Self {
XcodebuildMessages {
parser: OutputParser::new(Format::Xcode),
cwd: cwd.to_path_buf(),
paths: PathMap::new(root),
lines: Lines::default(),
seen: HashSet::new(),
done: false,
}
}
/// Messages completed by `line` (without its line break).
pub fn feed(&mut self, line: &str) -> Vec<BuildMessage> {
if self.done {
return Vec::new();
}
let result = parse::strip_ansi(line);
let result = result.trim();
if result.len() > 6 && result.starts_with("** ") && result.ends_with(" **") {
self.done = true;
return self.finish();
}
let raws = self.parser.feed(line).messages;
self.resolve(raws)
}
/// The message still waiting for detail lines.
pub fn finish(&mut self) -> Vec<BuildMessage> {
let raws = self.parser.finish();
self.resolve(raws)
}
fn resolve(&mut self, raws: Vec<RawMessage>) -> Vec<BuildMessage> {
raws.into_iter()
.map(|raw| {
let mut m = resolve(raw, &self.cwd, &self.paths, &mut self.lines);
// xcodebuild prints the folder it was started in, which may be a symlink to the project.
if let Some(path) = m.path.clone().map(PathBuf::from)
&& !path.starts_with(&self.paths.root)
&& let Ok(real) = dunce::canonicalize(&path)
&& let Some(real) = real.to_str()
{
let mapped = self.paths.resolve(real, &self.cwd, None);
if mapped.starts_with(&self.paths.root) {
m.path = Some(mapped.into());
}
}
m
})
.filter(|m| self.seen.insert((m.path.clone().map(Into::into), m.range, m.text.clone())))
.collect()
}
}
/// Per-file editor / Problems diagnostics of the messages that have a position.
pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
diagnostics_from(messages, DIAGNOSTICS_SOURCE)
@@ -1336,6 +1404,73 @@ mod tests {
}
use super::*;
#[test]
fn xcodebuild_messages_once_per_build() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("Warn.swift");
std::fs::write(&file, "func f() -> Int {\n var count = 1\n return count\n}\n").unwrap();
let mut x = XcodebuildMessages::new(tmp.path(), tmp.path());
let warning = format!("{}:2:9: warning: variable 'count' was never mutated", file.display());
let mut out = Vec::new();
// One copy per architecture, then the linker's per-architecture lists.
for line in [
warning.as_str(),
"SwiftCompile normal arm64 Compiling\\ Warn.swift",
warning.as_str(),
"Undefined symbols for architecture x86_64:",
" \"_sym\", referenced from:",
"ld: symbol(s) not found for architecture x86_64",
"Undefined symbols for architecture arm64:",
" \"_sym\", referenced from:",
] {
out.extend(x.feed(line));
}
out.extend(x.finish());
assert_eq!(out.len(), 2, "{out:?}");
assert_eq!(out[0].path.clone().map(PathBuf::from), Some(file));
// `count`, 0-based, underlined.
assert_eq!(out[0].range, Some(Range::new(Pos::new(1, 8), Pos::new(1, 13))));
assert_eq!(
(out[1].path.is_none(), out[1].text.as_str()),
(true, "Undefined symbols\n\"_sym\", referenced from:")
);
}
#[test]
fn xcodebuild_messages_stop_at_the_build_result() {
let tmp = tempfile::tempdir().unwrap();
let mut x = XcodebuildMessages::new(tmp.path(), tmp.path());
let mut out = Vec::new();
// An Xcode run configuration's output: the build, then the app's own console.
for line in [
"/p/Demo/Demo.xcodeproj: Demo: ld: warning: Could not find or use auto-linked framework 'UIUtilities'",
"** BUILD SUCCEEDED **",
"error: request failed",
"warning: low memory",
"Demo/ContentView.swift:12: Fatal error: Unexpectedly found nil while unwrapping an Optional value",
] {
out.extend(x.feed(line));
}
out.extend(x.finish());
let texts: Vec<_> = out.iter().map(|m| m.text.as_str()).collect();
assert_eq!(texts, ["Could not find or use auto-linked framework 'UIUtilities'"]);
}
#[cfg(unix)]
#[test]
fn xcodebuild_paths_through_a_symlink_map_to_the_project() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("Demo");
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join("A.swift"), "let x = y\n").unwrap();
let link = tmp.path().join("link");
std::os::unix::fs::symlink(&root, &link).unwrap();
let mut x = XcodebuildMessages::new(&root, &root);
x.feed(&format!("{}/A.swift:1:9: error: cannot find 'y' in scope", link.display()));
let out = x.finish();
assert_eq!(out[0].path.clone().map(PathBuf::from), Some(root.join("A.swift")));
}
/// Launch outputs use the platform separator throughout, so they compare equal to
/// the same directories as JDT LS reports them.
#[test]
+158
Переглянути файл
@@ -27,6 +27,10 @@ pub(crate) enum Format {
Gcc,
/// MSBuild (`dotnet build`): `C:\p\A.cs(12,5): error CS1002: msg [C:\p\App.csproj]`.
Msbuild,
/// `xcodebuild`: swiftc / clang lines like [`Format::Gcc`], their notes (`path:3:6: note:` or
/// Swift's `` `- note: `` in the code excerpt), `App.xcodeproj: App: ld: warning: msg` and
/// `Undefined symbols for architecture arm64:` with its indented details.
Xcode,
}
/// What a printed column counts.
@@ -331,6 +335,59 @@ fn gcc_line(line: &str) -> Option<RawMessage> {
(!msg.is_empty()).then(|| RawMessage::new(severity, msg, ColUnit::Byte).at(path, ln, col))
}
const UNDEFINED_SYMBOLS: &str = "Undefined symbols";
/// An `xcodebuild` message: a compiler line, a linker / build-system line without a location, or
/// the start of an undefined symbols list. Its architecture is dropped: every one prints the same.
fn xcode_line(line: &str) -> Option<RawMessage> {
if let Some(m) = gcc_line(line) {
return Some(m);
}
if line.starts_with("Undefined symbols for architecture ") {
return Some(RawMessage::new(Severity::Error, UNDEFINED_SYMBOLS, ColUnit::Byte));
}
// `/p/App.xcodeproj: App: ld: warning: msg`, `error: msg`, `xcodebuild: error: msg`.
let rest = [".xcodeproj: ", ".xcworkspace: "]
.into_iter()
.find_map(|c| line.find(c).map(|i| &line[i + c.len()..]))
.or_else(|| (!line.starts_with(char::is_whitespace)).then_some(line))?;
let (severity, msg) =
[("error: ", Severity::Error), ("warning: ", Severity::Warning)].into_iter().find_map(|(word, severity)| {
let at = rest.match_indices(word).map(|(i, _)| i).find(|&i| i == 0 || rest[..i].ends_with(": "))?;
// Only `tool: ` / `target: ` words may come before the severity, not a sentence.
rest[..at].split(": ").all(|w| !w.contains(' ')).then(|| (severity, rest[at + word.len()..].trim()))
})?;
(!msg.is_empty()).then(|| RawMessage::new(severity, msg, ColUnit::Byte))
}
/// Whether `line` belongs to the pending `xcodebuild` message (and is folded into it).
fn xcode_detail(msg: &mut RawMessage, line: &str) -> bool {
let t = line.trim_start();
// A `note:` with a location, as clang and `-diagnostic-style llvm` print it.
if let Some((_, _, _, rest)) = path_line_col(line)
&& let Some(note) = rest.strip_prefix(':').and_then(|r| r.trim_start().strip_prefix("note:"))
{
msg.text.push_str("\nnote: ");
msg.text.push_str(note.trim());
return true;
}
// The code excerpt: ` 9 | switch s {`, ` | `- note: add missing case`.
let excerpt = t.trim_start_matches(|c: char| c.is_ascii_digit()).trim_start().starts_with('|');
if excerpt {
if let Some(i) = t.find("- note: ") {
msg.text.push_str("\nnote: ");
msg.text.push_str(t[i + "- note: ".len()..].trim());
}
return true;
}
if msg.text.starts_with(UNDEFINED_SYMBOLS) && t.len() < line.len() && !t.is_empty() {
msg.text.push('\n');
msg.text.push_str(t);
return true;
}
false
}
/// rustc's JSON diagnostic (`reason: compiler-message`) → message and its rendered text.
fn cargo_json(v: &Value) -> Option<(Option<RawMessage>, String)> {
if v.get("reason")?.as_str()? != "compiler-message" {
@@ -412,6 +469,9 @@ impl OutputParser {
.map_or(line, |r| r.strip_prefix(' ').unwrap_or(r)),
_ => line,
};
if format == Format::Xcode {
return xcode_detail(&mut p.msg, line);
}
if matches!(format, Format::Maven | Format::Gradle | Format::Tsc)
&& body.starts_with(" ")
&& !body.trim().is_empty()
@@ -447,6 +507,7 @@ impl OutputParser {
Format::Go => go_line(&line),
Format::Gcc => gcc_line(&line),
Format::Msbuild => msbuild_line(&line),
Format::Xcode => xcode_line(&line),
Format::Cargo => None,
};
if let Some(msg) = parsed {
@@ -678,6 +739,103 @@ mod tests {
assert_eq!(out[2].text, "'missing.h' file not found");
}
// Real `xcodebuild build` output (Xcode 27.1, iOS Simulator, two architectures), paths shortened.
#[test]
fn xcodebuild_swift_error_warning_and_note() {
let out = parse(
Format::Xcode,
"SwiftCompile normal x86_64 Compiling\\ Warn.swift /p/Demo/Warn.swift (in target 'Demo' from project 'Demo')\n\
/p/Demo/Warn.swift:2:9: warning: variable 'count' was never mutated; consider changing to 'let' constant [#VariableNeverMutated]\n\
\x201 | func warnMe() -> Int {\n\
\x202 | var count = 1\n\
\x20 | `- warning: variable 'count' was never mutated; consider changing to 'let' constant [#VariableNeverMutated]\n\
\x203 | return count\n\
\x204 | }\n\
\n\
/p/Demo/Warn.swift:9:5: error: switch must be exhaustive\n\
\x207 | \n\
\x208 | func name(_ s: Shade) -> String {\n\
\x209 | switch s {\n\
\x20 | |- error: switch must be exhaustive\n\
\x20 | `- note: add missing case: '.dark'\n\
10 | case .light: return \"light\"\n\
11 | }\n\
\n\
[#VariableNeverMutated]: <https://docs.swift.org/compiler/documentation/diagnostics/variable-never-mutated>\n\
Failed frontend command:\n\
note: Removed stale file '/p/dd/Demo.swiftmodule'\n",
);
assert_eq!(out.len(), 2, "{out:?}");
assert_eq!(out[0].severity, Severity::Warning);
assert_eq!((out[0].path.as_deref(), out[0].line, out[0].col), (Some("/p/Demo/Warn.swift"), Some(2), Some(9)));
assert!(out[0].text.starts_with("variable 'count' was never mutated"), "{}", out[0].text);
assert_eq!(out[1].severity, Severity::Error);
assert_eq!(out[1].text, "switch must be exhaustive\nnote: add missing case: '.dark'");
assert_eq!((out[1].line, out[1].col), (Some(9), Some(5)));
}
#[test]
fn xcodebuild_clang_errors_with_note() {
let out = parse(
Format::Xcode,
"/p/Demo/Legacy.m:2:29: error: use of undeclared identifier 'undeclared_thing'\n\
\x20 2 | void legacy(void) { int x = undeclared_thing; }\n\
\x20 | ^~~~~~~~~~~~~~~~\n\
/p/Demo/Legacy.m:4:6: error: redefinition of 'twice'\n\
\x20 4 | void twice(void) {}\n\
\x20 | ^\n\
/p/Demo/Legacy.m:3:6: note: previous definition is here\n\
\x20 3 | void twice(void) {}\n\
\x20 | ^\n\
2 errors generated.\n",
);
assert_eq!(out.len(), 2, "{out:?}");
assert_eq!(out[0].text, "use of undeclared identifier 'undeclared_thing'");
assert_eq!((out[0].line, out[0].col), (Some(2), Some(29)));
assert_eq!(out[1].text, "redefinition of 'twice'\nnote: previous definition is here");
assert_eq!((out[1].line, out[1].col), (Some(4), Some(6)));
}
#[test]
fn xcodebuild_linker_errors_without_location() {
let out = parse(
Format::Xcode,
"Ld /p/dd/Demo.debug.dylib normal arm64 (in target 'Demo' from project 'Demo')\n\
\x20 cd /p/Demo\n\
\x20 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -Xlinker -reproducible -target arm64-apple-ios16.0-simulator -ferror-limit 19\n\
/p/Demo/Demo.xcodeproj: Demo: ld: warning: Could not find or use auto-linked framework 'UIUtilities': framework 'UIUtilities' not found\n\
Undefined symbols for architecture arm64:\n\
\x20 \"_missing_symbol_xyz\", referenced from:\n\
\x20 Demo.callMissing() -> () in Missing.o\n\
ld: symbol(s) not found for architecture arm64\n\
/p/Demo/Demo.xcodeproj: Demo: clang: error: linker command failed with exit code 1 (use -v to see invocation)\n\
\n\
** BUILD FAILED **\n\
\n\
The following build commands failed:\n\
\tLd /p/dd/Demo.debug.dylib normal arm64 (in target 'Demo' from project 'Demo')\n\
xcodebuild: error: Unable to find a destination matching the provided destination specifier\n",
);
let found: Vec<_> = out.iter().map(|m| (m.severity, m.text.as_str(), m.path.is_none())).collect();
assert_eq!(
found,
[
(
Severity::Warning,
"Could not find or use auto-linked framework 'UIUtilities': framework 'UIUtilities' not found",
true
),
(
Severity::Error,
"Undefined symbols\n\"_missing_symbol_xyz\", referenced from:\nDemo.callMissing() -> () in Missing.o",
true
),
(Severity::Error, "linker command failed with exit code 1 (use -v to see invocation)", true),
(Severity::Error, "Unable to find a destination matching the provided destination specifier", true),
]
);
}
#[test]
fn go_errors() {
let out = parse(
+54
Переглянути файл
@@ -4461,4 +4461,58 @@ mod linkage_tests {
assert_eq!(poms, expected.map(|e| e.iter().map(|s| s.to_string()).collect::<Vec<_>>()), "{unlinked:?}");
}
}
#[test]
fn child_module_inherits_parent_declared_plugin_prefix_and_coordinates() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("child")).unwrap();
std::fs::write(
root.join("pom.xml"),
r#"<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules><module>child</module></modules>
<build>
<plugins>
<plugin>
<groupId>io.spring.javaformat</groupId>
<artifactId>spring-javaformat-maven-plugin</artifactId>
<version>0.0.38</version>
</plugin>
</plugins>
</build>
</project>"#,
)
.unwrap();
std::fs::write(
root.join("child/pom.xml"),
r#"<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example</groupId>
<artifactId>parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>child</artifactId>
</project>"#,
)
.unwrap();
let model = load_with_repo(root, None);
for pom in ["pom.xml", "child/pom.xml"] {
let proj = model.projects.iter().find(|p| p.pom == pom).expect(pom);
let plugin = proj
.plugins
.iter()
.find(|p| p.prefix == "spring-javaformat")
.unwrap_or_else(|| panic!("spring-javaformat plugin missing on {pom}: {:?}", proj.plugins));
assert_eq!(plugin.group_id, "io.spring.javaformat");
assert_eq!(plugin.artifact_id, "spring-javaformat-maven-plugin");
assert_eq!(plugin.version.as_deref(), Some("0.0.38"));
}
}
}
+53 -1
Переглянути файл
@@ -15,7 +15,9 @@ use std::sync::Arc;
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
/// `RunConfig`, its before launch tasks already done) in the Run tool window as the user's
/// Run would, answered the same way.
/// Run would, answered the same way. `DebugConfiguration` does the same in Debug mode, so
/// the window's own Debug action builds the launch. `Breakpoints` replaces the window's
/// breakpoints, which the editor owns, persists and mirrors to the backend.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum McpUiRequest {
@@ -41,6 +43,36 @@ pub enum McpUiRequest {
#[specta(type = specta_typescript::Unknown)]
config: serde_json::Value,
},
/// Start a run configuration in Debug mode as the IDE's Debug action would.
DebugConfiguration {
#[specta(type = specta_typescript::Unknown)]
config: serde_json::Value,
},
/// Sets one line breakpoint in the window's own list, by absolute editor path. The window
/// applies the edit to its current list, so a user's pending edit is not overwritten.
SetBreakpoint {
path: String,
breakpoint: McpBreakpoint,
},
/// Removes breakpoints from the window's own list. With no path, removes every line
/// breakpoint; with a path but no line, removes all of that file's breakpoints.
RemoveBreakpoints {
path: Option<String>,
line: Option<u32>,
},
/// Flushes the editor's pending breakpoint syncs before an agent reads the backend list.
FlushBreakpoints,
}
/// A line breakpoint in an MCP request, with a 1-based line like every other MCP tool.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct McpBreakpoint {
pub line: u32,
pub enabled: bool,
pub condition: Option<String>,
pub hit_condition: Option<String>,
pub log_message: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -123,6 +155,8 @@ pub enum IdeEvent {
DocDiskConflict {
doc: DocId,
path: String,
/// The file no longer exists: saving recreates it, and there is nothing to load.
deleted: bool,
},
/// A complete workspace edit can be undone as one operation.
WorkspaceEditApplied {
@@ -142,6 +176,15 @@ pub enum IdeEvent {
/// See `DocumentInfo::ui_mode`.
ui_mode: Option<String>,
},
/// A reload from disk changed an open document's encoding, BOM or line ending (the file
/// was rewritten by another program), which the editor only learns when it opens.
DocEncoding {
doc: DocId,
encoding: String,
has_bom: bool,
/// A `LineEnding` in its serialized form: `lf`, `crLf` or `cr`.
line_ending: String,
},
/// Full replacement of diagnostics for one file from one producer.
Diagnostics {
path: crate::IpcPath,
@@ -204,6 +247,15 @@ pub enum IdeEvent {
message: String,
actions: Vec<String>,
},
/// A language server asked to show a document (`window/showDocument`), e.g. the
/// expansion file of sourcekit-lsp's Expand Macro. `path` is set for a file to open in
/// an editor, at `selection` when given; without it `uri` is a web link for the browser.
LspShowDocument {
uri: String,
path: Option<crate::IpcPath>,
selection: Option<crate::Range>,
take_focus: bool,
},
/// The request was answered or timed out; every window drops its dialog.
LspMessageRequestDone {
id: u32,
+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");
+151 -1
Переглянути файл
@@ -165,6 +165,11 @@ pub struct AgentSettings {
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, AgentSkillPolicy>)]
pub skills: BTreeMap<String, AgentSkillPolicy>,
/// Agent memory policies (`[agents.memory]`): cross-session auto-memory mode, built-in
/// MCP memory bridge, and per-entry modes; tracked files on disk are never modified.
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentMemorySettings)]
pub memory: AgentMemorySettings,
}
impl Default for AgentSettings {
@@ -196,6 +201,7 @@ impl Default for AgentSettings {
defaults: BTreeMap::new(),
mcp_servers: BTreeMap::new(),
skills: BTreeMap::new(),
memory: AgentMemorySettings::default(),
}
}
}
@@ -279,6 +285,79 @@ impl Default for AgentSkillPolicy {
}
}
/// How an agent instruction, rule, or memory entry may load (`[agents.memory.entries.<id>] mode = …`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemoryMode {
/// Load according to its native rules (always for instructions, matching files for path-scoped rules).
#[default]
Auto,
/// Force-load into every session regardless of path scoping.
Always,
/// Exclude from sessions where the harness supports it.
Off,
}
/// How an agent's automatic cross-session memory runs (`[agents.memory] autoMemory = …`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AutoMemoryMode {
/// Leave the agent's own configuration untouched.
#[default]
Inherit,
/// Read past memories and record new ones.
ReadWrite,
/// Read past memories without recording new ones.
ReadOnly,
/// Neither read nor record cross-session auto-memories.
Off,
}
/// One memory or instruction entry's policy in Settings › Agents › Memory.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentMemoryEntryPolicy {
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentMemoryMode)]
pub mode: AgentMemoryMode,
/// Agent provider ids this entry applies to; empty means all agents.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub agents: Vec<String>,
}
impl Default for AgentMemoryEntryPolicy {
fn default() -> Self {
Self { mode: AgentMemoryMode::Auto, agents: Vec::new() }
}
}
/// Per-provider auto-memory policy (`[agents.memory.providers.<id>]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentProviderMemoryPolicy {
#[serde(deserialize_with = "or_default")]
#[specta(type = AutoMemoryMode)]
pub auto_memory: AutoMemoryMode,
}
/// Agent memory settings (`[agents.memory]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentMemorySettings {
/// Default cross-session auto-memory policy across agents.
#[serde(deserialize_with = "or_default")]
#[specta(type = AutoMemoryMode)]
pub auto_memory: AutoMemoryMode,
/// Optional per-provider auto-memory overrides (`[agents.memory.providers.<provider>]`).
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
#[specta(type = BTreeMap<String, AgentProviderMemoryPolicy>)]
pub providers: BTreeMap<String, AgentProviderMemoryPolicy>,
/// Per-entry modes (`[agents.memory.entries.<id>]`).
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
#[specta(type = BTreeMap<String, AgentMemoryEntryPolicy>)]
pub entries: BTreeMap<String, AgentMemoryEntryPolicy>,
}
/// A hand-edited value these settings don't know reads as the default, rather than
/// failing the whole settings file.
fn or_default<'de, D, T>(d: D) -> Result<T, D::Error>
@@ -1373,6 +1452,7 @@ pub struct LanguagesSettings {
pub arduino: ArduinoSettings,
pub zig: ZigSettings,
pub flutter: FlutterSettings,
pub swift: SwiftSettings,
}
impl Default for LanguagesSettings {
@@ -1406,6 +1486,7 @@ impl Default for LanguagesSettings {
arduino: ArduinoSettings::default(),
zig: ZigSettings::default(),
flutter: FlutterSettings::default(),
swift: SwiftSettings::default(),
}
}
}
@@ -1690,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")]
@@ -1896,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,
@@ -1903,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")]
@@ -2079,6 +2201,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();
@@ -2089,6 +2225,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() };
+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"
}
]
}
+1
Переглянути файл
@@ -17,6 +17,7 @@ ide-jvm-attach.workspace = true
ide-jvm-inspect.workspace = true
ide-jdwp.workspace = true
ide-heap.workspace = true
ide-run.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
+62 -5
Переглянути файл
@@ -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
}
@@ -391,9 +394,10 @@ pub const DEBUGPY_MISSING: &str = "debugpy is not installed";
/// `PYTHONPATH`. Neither: an `unavailable` error naming the interpreter.
pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
let (command, cwd) = (spec.command.clone(), spec.cwd.clone());
let Some(python) = tokio::task::spawn_blocking(move || resolve_binary(&command, &cwd)).await.ok().flatten() else {
let Some(python) = tokio::task::spawn_blocking(move || debugpy_python(&command, &cwd)).await.ok().flatten() else {
return Ok(()); // Reported as a missing adapter when it is started.
};
spec.command = python.to_string_lossy().into_owned();
let mut probe = Command::new(&python);
probe.current_dir(&spec.cwd);
ide_core::process::prepare(probe.as_std_mut());
@@ -426,6 +430,46 @@ pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
)))
}
/// The interpreter `<python> -m debugpy.adapter` runs with. On Windows a bare `python3` (the
/// built-in `python.toml`'s) or `python` may name an App Execution Alias in `WindowsApps`,
/// which only opens the Store unless the Store's Python is installed: every match on `PATH`
/// of the command, then `python`, then the `py` launcher, the first that is no alias or runs.
fn debugpy_python(command: &str, cwd: &Path) -> Option<PathBuf> {
let found = resolve_binary(command, cwd);
if !cfg!(windows) || !matches!(command, "python3" | "python") {
return found;
}
let pathext = std::env::var("PATHEXT").ok();
let dirs = search_dirs(cwd);
let mut candidates: Vec<PathBuf> = Vec::new();
for name in [command, "python", "py"] {
for dir in &dirs {
if let Some(p) = find_binary_in(name, cwd, std::slice::from_ref(dir), true, pathext.as_deref())
&& !candidates.contains(&p)
{
candidates.push(p);
}
}
}
let runs = |p: &Path| {
let mut c = std::process::Command::new(p);
ide_core::process::prepare(&mut c);
c.arg("--version").stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
c.status().is_ok_and(|s| s.success())
};
pick_python(candidates, runs).or(found)
}
/// The first candidate that is no App Execution Alias, or is one that `runs`.
fn pick_python(candidates: Vec<PathBuf>, runs: impl Fn(&Path) -> bool) -> Option<PathBuf> {
candidates.into_iter().find(|p| !is_app_execution_alias(p) || runs(p))
}
/// A Windows App Execution Alias (`%LOCALAPPDATA%\Microsoft\WindowsApps\python3.exe`).
fn is_app_execution_alias(path: &Path) -> bool {
path.parent().and_then(Path::file_name).is_some_and(|d| d.eq_ignore_ascii_case("WindowsApps"))
}
/// GDB's DAP interpreter (`-i dap`) shipped in GDB 14; older ones exit with
/// "Interpreter `dap' unrecognized".
const GDB_MIN_MAJOR: u32 = 14;
@@ -859,6 +903,19 @@ async fn connect_with_retries(
mod tests {
use super::*;
/// Windows: a Store alias on `PATH` before the real interpreter is skipped unless it runs
/// (the Store's Python is installed), so the Python Debug Server starts the real one.
#[test]
fn debugpy_skips_store_aliases_that_do_not_run() {
let alias = PathBuf::from("C:/Users/me/AppData/Local/Microsoft/WindowsApps/python3.exe");
let real = PathBuf::from("C:/Program Files/Python313/python.exe");
assert!(is_app_execution_alias(&alias) && !is_app_execution_alias(&real));
let both = vec![alias.clone(), real.clone()];
assert_eq!(pick_python(both.clone(), |_| false), Some(real.clone()));
assert_eq!(pick_python(both, |_| true), Some(alias.clone()));
assert_eq!(pick_python(vec![alias], |_| false), None);
}
/// A user's `languages/python.toml` `[debugger]` is the one debugpy runs with: no other
/// language (a template one) declares debugpy before Python.
#[test]
+46 -1
Переглянути файл
@@ -24,6 +24,7 @@ pub mod kotlin_lsp;
mod memory;
mod session;
mod stream_trace;
mod swiftpm;
pub mod unity;
use adapter::{AdapterIo, AdapterLauncher, AdapterSpec, ProcessLauncher};
@@ -613,6 +614,16 @@ pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult<Option<Debug
Ok(Some(DebugServer { host, port }))
}
/// A source served only through the `source` request whose `path` is no file, such as
/// 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).has_root() && !Path::new(path).exists()
}
/// DAP stack frame → [`StackFrame`] (1-based → 0-based).
pub(crate) fn frame_from(f: &Value) -> StackFrame {
let source = f.get("source");
@@ -625,7 +636,11 @@ pub(crate) fn frame_from(f: &Value) -> StackFrame {
StackFrame {
id: f.get("id").and_then(Value::as_i64).unwrap_or_default(),
name: f.get("name").and_then(Value::as_str).unwrap_or_default().to_owned(),
path: source.and_then(|s| s.get("path")).and_then(Value::as_str).map(Into::into),
path: source
.and_then(|s| s.get("path"))
.and_then(Value::as_str)
.filter(|p| !is_pseudo_path(source, p))
.map(Into::into),
line: (f.get("line").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
column: (f.get("column").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
presentation_hint: hint,
@@ -912,6 +927,30 @@ impl DebugManager {
.collect()
}
/// Whether `s` is live and currently suspended (a breakpoint, step or manual pause).
/// `None` when the session has ended.
pub fn session_suspended(&self, s: DebugSessionId) -> Option<bool> {
self.sessions.lock().get(&s).map(|session| session.suspended.get())
}
/// The thread of `s`'s most recent stop, when the adapter named one.
pub fn stopped_thread(&self, s: DebugSessionId) -> Option<i64> {
self.sessions.lock().get(&s).and_then(|session| session.suspended.stopped_thread())
}
/// All stored breakpoints of `owner`, for tools that list or edit them. Line breakpoints
/// are keyed by file; function and data breakpoints have no file.
pub fn breakpoints(
&self,
owner: &str,
) -> (BTreeMap<PathBuf, Vec<Breakpoint>>, Vec<FunctionBreakpoint>, Vec<DataBreakpoint>) {
let store = self.breakpoints.lock();
match store.get(owner) {
Some(owner) => (owner.lines.clone(), owner.functions.clone(), owner.data.clone()),
None => Default::default(),
}
}
/// Starts a session: spawns the adapter, `initialize`, `launch`/`attach`,
/// waits for `initialized`, sends breakpoints, then `configurationDone`.
/// Events of the session (including cargo build output) go to `owner` only.
@@ -1056,6 +1095,9 @@ impl DebugManager {
.await?;
arguments["program"] = json!(program);
}
if let Some(spm) = arguments.as_object_mut().and_then(|o| o.remove("swiftpm")) {
arguments["program"] = json!(swiftpm::program(&cwd, &spm, &cancel).await?);
}
// Attach to a Node process started without `--inspect`: open its inspector first.
if config.adapter == "js-debug" && config.request == "attach" && arguments.get("port").is_none() {
let pid = arguments.get("processId").and_then(|p| match p {
@@ -1374,6 +1416,9 @@ impl DebugManager {
.await?;
*s.caps.lock() = if caps.is_object() { caps } else { json!({}) };
if s.adapter == adapter::JAVA_ANALYZER && s.request == "launch" {
session::shorten_java_analyzer_classpath(s, &mut arguments)?;
}
// The Kotlin adapters ignore the resolved classpath and project runtime on launch.
let request = if kotlin::is_kotlin(&s.adapter) && s.request == "launch" {
session::start_kotlin_debuggee(s, &mut arguments).await?;
+156 -30
Переглянути файл
@@ -136,6 +136,16 @@ pub(crate) struct Session {
/// Used only by a kotlin-lsp session: see [`Session::kotlin_lsp_quirks`].
pub(crate) quirks: kotlin_lsp::Quirks,
pub(crate) unity_startup_activity: Mutex<Instant>,
/// Temporary pathing jars / argfiles created for this session; removed on stop/drop.
temp_files: Mutex<Vec<TempFile>>,
}
struct TempFile(PathBuf);
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
/// Which threads of the program are suspended: each from its `stopped` event until a
@@ -207,6 +217,14 @@ impl Suspension {
stops.all.is_some() || !stops.threads.is_empty()
}
/// The most recently stopped individual thread, when the stop named one. A stop of every
/// thread (`allThreadsStopped`) names none, so callers fall back to the adapter's first thread.
pub fn stopped_thread(&self) -> Option<i64> {
let stops = self.0.lock();
let latest = stops.latest()?;
stops.threads.iter().find(|&&(_, ticket)| ticket == latest).map(|&(id, _)| id)
}
/// A `stopped` event; `all`: its `allThreadsStopped`.
pub fn stopped(&self, thread: Option<i64>, all: bool) {
let mut stops = self.0.lock();
@@ -350,6 +368,7 @@ impl Session {
stream_trace_done: parking_lot::Mutex::new(None),
quirks: kotlin_lsp::Quirks::default(),
unity_startup_activity: Mutex::new(Instant::now()),
temp_files: Mutex::new(Vec::new()),
}
}
@@ -581,6 +600,7 @@ impl Session {
if let Some(mut program) = self.program.lock().take() {
program.kill();
}
self.temp_files.lock().clear();
}
}
@@ -1318,43 +1338,112 @@ fn kotlin_jvm_args(user: Vec<String>, windows: bool) -> Vec<String> {
args
}
fn json_string_list(args: &Value, key: &str) -> Vec<String> {
args.get(key)
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect())
.unwrap_or_default()
}
fn json_args_len(args: &Value, key: &str) -> usize {
match args.get(key) {
Some(Value::String(s)) => s.len() + 3,
Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(|s| s.len() + 3).sum(),
_ => 0,
}
}
/// Shortens `classPaths` for `java-analyzer dap` into a temporary manifest-only pathing jar when
/// the command line would exceed the OS limit (e.g. Windows `CreateProcessW` `os error 206` on
/// JDK 8 Spring Boot projects).
pub(crate) fn shorten_java_analyzer_classpath(s: &Arc<Session>, args: &mut Value) -> ide_core::IdeResult<()> {
let cwd = args.get("cwd").and_then(Value::as_str).map(PathBuf::from).unwrap_or_else(|| s.spec.cwd.clone());
if let Some(jar) =
shorten_java_analyzer_classpath_with(args, &cwd, cfg!(windows), &ide_run::java_cmdline::default_temp_dir())?
{
s.temp_files.lock().push(TempFile(jar));
}
Ok(())
}
fn shorten_java_analyzer_classpath_with(
args: &mut Value,
cwd: &Path,
windows: bool,
temp_dir: &Path,
) -> ide_core::IdeResult<Option<PathBuf>> {
let java = args.get("javaExec").and_then(Value::as_str).unwrap_or("java");
let class_paths = json_string_list(args, "classPaths");
let module_paths = json_string_list(args, "modulePaths");
let extra_len = json_args_len(args, "vmArgs")
+ json_args_len(args, "args")
+ args.get("mainClass").and_then(Value::as_str).map_or(0, |s| s.len() + 3);
let Some(jar) = ide_run::java_cmdline::shorten_classpath_to_jar(
Path::new(java),
&class_paths,
&module_paths,
extra_len,
cwd,
windows,
temp_dir,
)?
else {
return Ok(None);
};
args["classPaths"] = json!([jar.to_string_lossy()]);
Ok(Some(jar))
}
/// Launch with the IDE's resolved runtime and classpath; the adapter only attaches.
pub(crate) async fn start_kotlin_debuggee(s: &Arc<Session>, args: &mut Value) -> ide_core::IdeResult<()> {
use tokio::io::{AsyncBufReadExt, BufReader};
let java = args.get("javaExec").and_then(Value::as_str).unwrap_or("java");
let strings = |key: &str| -> Vec<String> {
args.get(key)
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect())
.unwrap_or_default()
};
let classpath =
std::env::join_paths(strings("classPaths")).map_err(|e| ide_core::IdeError::invalid(e.to_string()))?;
let classpath = std::env::join_paths(json_string_list(args, "classPaths"))
.map_err(|e| ide_core::IdeError::invalid(e.to_string()))?
.to_string_lossy()
.into_owned();
let mut java_args = kotlin_jvm_args(json_string_list(args, "vmArguments"), cfg!(windows));
// Let the JVM pick its own port (`:0`) and report it below: pre-picking a free
// port here races with other processes that may take it before the JVM binds.
java_args.push("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0".to_owned());
java_args.push("-cp".to_owned());
java_args.push(classpath);
let modules = json_string_list(args, "modulePaths");
if !modules.is_empty() {
java_args.push("--module-path".to_owned());
java_args.push(
std::env::join_paths(modules)
.map_err(|e| ide_core::IdeError::invalid(e.to_string()))?
.to_string_lossy()
.into_owned(),
);
}
java_args.push(
args.get("mainClass")
.and_then(Value::as_str)
.ok_or_else(|| ide_core::IdeError::invalid("Missing Kotlin main class"))?
.to_owned(),
);
java_args.extend(json_string_list(args, "programArgs"));
if let Some(shortened) = ide_run::java_cmdline::shorten(
Path::new(java),
&java_args,
&s.spec.cwd,
cfg!(windows),
&ide_run::java_cmdline::default_temp_dir(),
)? {
java_args = shortened.args;
s.temp_files.lock().push(TempFile(shortened.file));
}
let mut cmd = tokio::process::Command::new(java);
cmd.current_dir(&s.spec.cwd);
ide_core::process::prepare(cmd.as_std_mut());
cmd.args(kotlin_jvm_args(strings("vmArguments"), cfg!(windows)))
// Let the JVM pick its own port (`:0`) and report it below: pre-picking a free
// port here races with other processes that may take it before the JVM binds.
.arg("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0")
.arg("-cp")
.arg(classpath);
let modules = strings("modulePaths");
if !modules.is_empty() {
cmd.arg("--module-path")
.arg(std::env::join_paths(modules).map_err(|e| ide_core::IdeError::invalid(e.to_string()))?);
}
cmd.arg(
args.get("mainClass")
.and_then(Value::as_str)
.ok_or_else(|| ide_core::IdeError::invalid("Missing Kotlin main class"))?,
)
.args(strings("programArgs"))
.envs(ide_core::process::shell_env_in(&s.spec.cwd))
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
cmd.args(&java_args)
.envs(ide_core::process::shell_env_in(&s.spec.cwd))
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
if let Some(env) = args.get("env").and_then(Value::as_object) {
for (k, v) in env {
if let Some(v) = v.as_str() {
@@ -1673,4 +1762,41 @@ mod tests {
// SAFETY: signal 0 only checks whether the process exists.
assert_eq!(unsafe { libc::kill(pid, 0) }, -1);
}
#[test]
fn java_analyzer_long_windows_classpath_is_shortened_to_pathing_jar() {
let dir = tempfile::tempdir().unwrap();
let short_cp = vec![r"C:\app\target\classes".to_owned()];
let mut short_args = serde_json::json!({
"javaExec": r"E:\software\Java\jdk1.8.0_431\bin\java.exe",
"mainClass": "com.example.App",
"classPaths": short_cp,
"vmArgs": ["-Dspring.output.ansi.enabled=always"],
"args": [],
});
assert!(
super::shorten_java_analyzer_classpath_with(&mut short_args, dir.path(), true, dir.path())
.unwrap()
.is_none()
);
assert_eq!(short_args["classPaths"].as_array().unwrap().len(), 1);
let many: Vec<String> = (0..500)
.map(|i| format!(r"C:\Users\dev\.m2\repository\org\springframework\boot\dep-{i:04}\dep-{i:04}.jar"))
.collect();
let mut long_args = serde_json::json!({
"javaExec": r"E:\software\Java\jdk1.8.0_431\bin\java.exe",
"mainClass": "com.example.App",
"classPaths": many,
"vmArgs": ["-Dspring.output.ansi.enabled=always"],
"args": [],
});
let jar = super::shorten_java_analyzer_classpath_with(&mut long_args, dir.path(), true, dir.path())
.unwrap()
.expect("long Windows classpath must be shortened into a pathing jar");
assert!(jar.is_file());
let replaced = long_args["classPaths"].as_array().unwrap();
assert_eq!(replaced.len(), 1);
assert_eq!(replaced[0].as_str().unwrap(), jar.to_string_lossy());
}
}
+68
Переглянути файл
@@ -0,0 +1,68 @@
//! SwiftPM launch integration: a launch request may carry
//! `"swiftpm": {"product": "greet", "buildArgs": ["-c", "release"]}` instead of `program`.
//! The run configuration's before launch task has built the product; this asks
//! `swift build <buildArgs> --show-bin-path` where it went (`.build/<triple>/<configuration>`,
//! or wherever `--scratch-path` / `--build-path` put it) and launches it from there.
use crate::adapter::find_binary;
use ide_core::{IdeError, IdeResult};
use serde_json::Value;
use std::path::{Path, PathBuf};
use std::process::Stdio;
/// `swift build` arguments that print the bin path for `buildArgs` without building.
pub fn bin_path_args(swiftpm: &Value) -> Vec<String> {
let mut args = vec!["build".to_owned()];
if let Some(a) = swiftpm.get("buildArgs").and_then(Value::as_array) {
args.extend(a.iter().filter_map(|v| v.as_str().map(str::to_owned)));
}
args.push("--show-bin-path".into());
args
}
/// The built product of `swiftpm` (see the module docs).
pub async fn program(cwd: &Path, swiftpm: &Value, cancel: &ide_core::CancellationToken) -> IdeResult<PathBuf> {
let product = swiftpm
.get("product")
.and_then(Value::as_str)
.filter(|p| !p.is_empty())
.ok_or_else(|| IdeError::invalid("the SwiftPM launch names no product"))?;
let swift = find_binary("swift", cwd).ok_or_else(|| IdeError::unavailable("`swift` not found on PATH"))?;
let args = bin_path_args(swiftpm);
let mut cmd = tokio::process::Command::new(swift);
cmd.current_dir(cwd);
ide_core::process::prepare(cmd.as_std_mut());
cmd.args(&args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
let out = tokio::select! {
biased;
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
out = cmd.output() => out.map_err(|e| IdeError::unavailable(format!("failed to run swift: {e}")))?,
};
if !out.status.success() {
let err = String::from_utf8_lossy(&out.stderr);
return Err(IdeError::invalid(format!("swift {} failed: {}", args.join(" "), err.trim())));
}
// The bin path is the last line: SwiftPM may print warnings about the manifest first.
let stdout = String::from_utf8_lossy(&out.stdout);
let dir = stdout.lines().map(str::trim).rfind(|l| !l.is_empty()).unwrap_or_default();
if dir.is_empty() {
return Err(IdeError::invalid("swift build --show-bin-path printed no path"));
}
let exe = if cfg!(windows) { format!("{product}.exe") } else { product.to_owned() };
Ok(cwd.join(dir).join(exe))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn asks_swift_build_for_the_bin_path_of_the_run_configurations_build() {
assert_eq!(bin_path_args(&json!({"product": "greet"})), ["build", "--show-bin-path"]);
assert_eq!(
bin_path_args(&json!({"product": "greet", "buildArgs": ["-c", "release"]})),
["build", "-c", "release", "--show-bin-path"]
);
}
}
+15
Переглянути файл
@@ -2164,6 +2164,21 @@ fn frames_keep_their_instruction_pointer() {
assert!(json.get("instructionPointerReference").is_none());
}
#[test]
fn frames_drop_pseudo_paths_of_referenced_sources() {
let frame = |path: &str, reference: i64| {
frame_from(&json!({"id": 1, "name": "f", "line": 1,
"source": {"path": path, "sourceReference": reference}}))
.path
};
let lldb = "/usr/lib/swift/libswiftCore.dylib`swift_willThrow";
assert_eq!(frame(lldb, 1), None, "lldb-dap disassembly");
assert_eq!(frame(lldb, 0).as_deref(), Some(Path::new(lldb)), "no reference: kept as sent");
let here = env!("CARGO_MANIFEST_DIR");
assert_eq!(frame(here, 3).as_deref(), Some(Path::new(here)), "an existing file");
assert!(frame("jdt://contents/rt.jar/java.lang/String.class", 2).is_some(), "not a file path");
}
#[tokio::test]
async fn smart_step_into_and_reset_frame() {
let h = harness(Script::default());
+15 -1
Переглянути файл
@@ -423,11 +423,25 @@ pub struct CapabilityInfo {
pub optional: bool,
/// Currently granted.
pub granted: bool,
/// The plugin's own explanation (`[capabilities.reasons]`), shown below `description`.
#[serde(default)]
pub reason: Option<String>,
/// `reason` translated by the plugin's `locales/<tag>.json`, by language tag.
#[serde(default)]
pub reason_locales: std::collections::BTreeMap<String, String>,
}
impl CapabilityInfo {
pub fn new(cap: &Capability, optional: bool, granted: bool) -> Self {
Self { id: cap.to_string(), risk: cap.risk(), description: cap.describe(), optional, granted }
Self {
id: cap.to_string(),
risk: cap.risk(),
description: cap.describe(),
optional,
granted,
reason: None,
reason_locales: Default::default(),
}
}
}
+67 -4
Переглянути файл
@@ -29,12 +29,14 @@ use crate::capability::Capability;
use crate::plugin_point::PointDecl;
use crate::resolve::Dependency;
use serde::Deserialize;
use std::collections::BTreeSet;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path, PathBuf};
pub const MANIFEST_FILE: &str = "plugin.toml";
/// The plugin API (engine) version this host implements.
pub const ENGINE_VERSION: &str = "1.18.0";
pub const ENGINE_VERSION: &str = "1.19.0";
/// The longest `[capabilities.reasons]` entry, in characters: a sentence or two.
pub const MAX_CAPABILITY_REASON: usize = 500;
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
pub const LEGACY_API: &str = "0.1";
/// Marketplace categories, in the order they are shown.
@@ -84,6 +86,10 @@ pub struct Manifest {
pub struct Capabilities {
pub required: Vec<Capability>,
pub optional: Vec<Capability>,
/// `[capabilities.reasons]` (API 1.19): the plugin's own words on why it asks for a
/// declared capability, keyed by the capability as printed (`net:127.0.0.1`). Shown
/// below the host's description, never instead of it.
pub reasons: BTreeMap<String, String>,
}
impl Capabilities {
@@ -94,6 +100,11 @@ impl Capabilities {
pub fn is_optional(&self, cap: &Capability) -> bool {
self.optional.contains(cap) && !self.required.contains(cap)
}
/// The plugin's explanation of `cap`, if it gave one.
pub fn reason(&self, cap: &Capability) -> Option<&str> {
self.reasons.get(&cap.to_string()).map(String::as_str)
}
}
/// When a plugin's code is instantiated (plan 4.4). Contributions are live
@@ -251,6 +262,8 @@ struct RawCapabilities {
required: Vec<String>,
#[serde(default)]
optional: Vec<String>,
#[serde(default)]
reasons: BTreeMap<String, String>,
}
impl Manifest {
@@ -279,8 +292,18 @@ impl Manifest {
Ok(out)
};
let capabilities = match (raw.capabilities, raw.permissions) {
(Some(c), _) => Capabilities { required: parse_caps(c.required)?, optional: parse_caps(c.optional)? },
(None, Some(p)) => Capabilities { required: parse_caps(p)?, optional: Vec::new() },
(Some(c), _) => {
let mut reasons = BTreeMap::new();
for (key, text) in c.reasons {
// Keyed as the capability prints, so `net:Example.com` finds `net:example.com`.
let cap: Capability = key.parse().map_err(|e| format!("capabilities.reasons: {e}"))?;
reasons.insert(cap.to_string(), text);
}
Capabilities { required: parse_caps(c.required)?, optional: parse_caps(c.optional)?, reasons }
}
(None, Some(p)) => {
Capabilities { required: parse_caps(p)?, optional: Vec::new(), reasons: BTreeMap::new() }
}
(None, None) => Capabilities::default(),
};
let activation = match raw.activation {
@@ -365,6 +388,19 @@ impl Manifest {
self.needs_api("`change-notes-file`", 18)?;
check_relative(path, "change-notes-file")?;
}
if !self.capabilities.reasons.is_empty() {
self.needs_api("`capabilities.reasons`", 19)?;
}
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 text.trim().is_empty() || text.chars().count() > MAX_CAPABILITY_REASON {
return Err(format!(
"capabilities.reasons: the reason for {key:?} must be 1 to {MAX_CAPABILITY_REASON} characters"
));
}
}
for cap in self.capabilities.required.iter().chain(&self.capabilities.optional) {
if matches!(
cap,
@@ -780,6 +816,33 @@ required = [\"lsp:phoxite\"]
assert_eq!(m.capabilities.optional, [Capability::BuildRead]);
}
#[test]
fn capability_reasons_explain_declared_capabilities_from_api_1_19() {
let caps = "[capabilities]\nrequired = [\"net:Example.com\"]\noptional = [\"clipboard.read\"]\n\
[capabilities.reasons]\n\"net:Example.com\" = \"Fetches the schema.\"\n\
\"clipboard.read\" = \"Imports a log you copied.\"\n";
assert!(err(&format!("{}{caps}", BASE.replace("^1.2", "^1.18"))).contains("new in plugin API 1.19"));
let src = |caps: &str| format!("{}{caps}", BASE.replace("^1.2", "^1.19"));
let m = Manifest::parse(&src(caps)).unwrap();
// Keyed as the capability prints.
assert_eq!(m.capabilities.reason(&Capability::Net("example.com".into())), Some("Fetches the schema."));
assert_eq!(m.capabilities.reason(&Capability::ClipboardRead), Some("Imports a log you copied."));
assert_eq!(m.capabilities.reason(&Capability::ProjectRead), None);
let undeclared =
"[capabilities]\nrequired = [\"project.read\"]\n[capabilities.reasons]\n\"project.write\" = \"x\"\n";
assert!(err(&src(undeclared)).contains("not under `required` or `optional`"));
let invalid = "[capabilities]\nrequired = [\"project.read\"]\n[capabilities.reasons]\n\"teleport\" = \"x\"\n";
assert!(err(&src(invalid)).contains("capabilities.reasons"));
let empty = "[capabilities]\nrequired = [\"project.read\"]\n[capabilities.reasons]\n\"project.read\" = \" \"\n";
assert!(err(&src(empty)).contains("1 to 500 characters"));
let long = format!(
"[capabilities]\nrequired = [\"project.read\"]\n[capabilities.reasons]\n\"project.read\" = \"{}\"\n",
"x".repeat(MAX_CAPABILITY_REASON + 1)
);
assert!(err(&src(&long)).contains("1 to 500 characters"));
}
#[test]
fn the_clipboard_read_capability_needs_api_1_11() {
let caps = "[capabilities]\noptional = [\"clipboard.read\"]\n";
+76
Переглянути файл
@@ -14,6 +14,65 @@ pub const DATA_ENV: &str = "OPENIDEA_DATA_DIR";
/// Moves the logs.
pub const LOG_ENV: &str = "OPENIDEA_LOG_DIR";
/// A portable install's settings file, next to the executable: `NAME=value` lines setting the
/// variables above (and only those), so the install needs no environment. A variable already set
/// in the environment wins; a relative value is taken from the file's folder.
pub const PROPERTIES_FILE: &str = "openidea.properties";
/// The folder `openidea.properties` is read from: the executable's, the AppImage file's when run
/// from one, the folder holding the `.app` bundle on macOS.
fn install_dir() -> Option<PathBuf> {
let exe = std::env::current_exe().ok()?;
// `APPIMAGE` is inherited by everything started from inside one; only trust it for the
// executable it mounted.
let appdir = std::env::var_os("APPDIR").filter(|v| !v.is_empty());
if let (Some(image), Some(appdir)) = (std::env::var_os("APPIMAGE").filter(|v| !v.is_empty()), appdir)
&& exe.starts_with(appdir)
{
return PathBuf::from(image).parent().map(Path::to_path_buf);
}
let dir = exe.parent()?;
if cfg!(target_os = "macos")
&& let Some(bundle) = dir.ancestors().nth(2).filter(|b| b.extension().is_some_and(|e| e == "app"))
{
return bundle.parent().map(Path::to_path_buf);
}
Some(dir.to_path_buf())
}
/// The variables an `openidea.properties` in `dir` sets, made absolute, leaving out those
/// `is_set` reports the environment already has. Unknown keys and comments (`#`, `!`) are ignored.
fn properties_in(dir: &Path, text: &str, is_set: impl Fn(&str) -> bool) -> Vec<(&'static str, PathBuf)> {
let mut out: Vec<(&'static str, PathBuf)> = Vec::new();
for line in text.lines().map(str::trim) {
if line.starts_with(['#', '!']) {
continue;
}
let Some((key, value)) = line.split_once('=') else { continue };
let (key, value) = (key.trim(), value.trim());
let Some(name) = [CONFIG_ENV, DATA_ENV, LOCAL_DATA_ENV, LOG_ENV].into_iter().find(|n| *n == key) else {
continue;
};
if value.is_empty() || is_set(name) || out.iter().any(|(n, _)| *n == name) {
continue;
}
// An absolute value replaces `dir`.
out.push((name, dir.join(value)));
}
out
}
/// Applies the install's `openidea.properties` to the environment, so the directories below and
/// every process the IDE starts see the same locations. Call first thing in `main`.
pub fn load_properties_file() {
let Some(dir) = install_dir() else { return };
let Ok(text) = fs::read_to_string(dir.join(PROPERTIES_FILE)) else { return };
for (name, value) in properties_in(&dir, &text, |n| std::env::var_os(n).is_some_and(|v| !v.is_empty())) {
// SAFETY: called at the start of `main`, before any other thread exists.
unsafe { std::env::set_var(name, value) };
}
}
/// `$OPENIDEA_CONFIG_DIR/<identifier>` when set, else the OS configuration directory
/// (Tauri's `app_config_dir`). Like the local data, the identifier keeps release and
/// per-worktree debug builds apart under one root; a relative path is an error.
@@ -664,6 +723,23 @@ mod tests {
assert!(!tmp.path().join("copy/Default/Cache").exists());
}
#[test]
fn a_properties_file_sets_the_directory_variables_relative_to_its_folder() {
let dir = std::env::temp_dir().join("portable");
let abs = std::env::temp_dir().join("elsewhere");
let text = format!(
"# portable install\n! also a comment\nOPENIDEA_CONFIG_DIR = data\nOPENIDEA_DATA_DIR=data\n\
OPENIDEA_LOCAL_DATA_DIR={}\nOPENIDEA_LOG_DIR=\nOPENIDEA_CONFIG_DIR=ignored\nPATH=/bin\nnot a pair\n",
abs.display()
);
let set = properties_in(&dir, &text, |_| false);
assert_eq!(set, [(CONFIG_ENV, dir.join("data")), (DATA_ENV, dir.join("data")), (LOCAL_DATA_ENV, abs.clone())]);
// The environment wins over the file.
let set = properties_in(&dir, &text, |n| n == CONFIG_ENV);
assert_eq!(set.iter().map(|(n, _)| *n).collect::<Vec<_>>(), [DATA_ENV, LOCAL_DATA_ENV]);
assert!(set.iter().all(|(_, v)| v.is_absolute()));
}
#[test]
fn config_data_and_log_dirs_follow_the_os_unless_their_variable_is_set() {
let os = Some(PathBuf::from("/os"));
+15
Переглянути файл
@@ -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};
@@ -108,6 +110,7 @@ pub struct Host {
pub data_dir: PathBuf,
/// Machine-local tools and rebuildable caches.
pub local_data_dir: PathBuf,
home_dir: Option<PathBuf>,
pub languages: Arc<LanguageRegistry>,
syntax: Arc<OnceLock<Arc<Syntax>>>,
pub global_settings: SettingsStore,
@@ -206,6 +209,11 @@ impl Host {
self
}
/// User home directory used by agent memory discovery.
pub fn home_dir(&self) -> Option<PathBuf> {
self.home_dir.clone()
}
pub fn new(config: HostConfig) -> Self {
let HostConfig {
config_dir,
@@ -268,6 +276,7 @@ impl Host {
config_dir,
data_dir,
local_data_dir,
home_dir: dirs::home_dir(),
sink_for,
owner,
runtime,
@@ -456,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();
}
@@ -696,6 +708,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();
}
File diff suppressed because it is too large. Load diff
+19 -5
Переглянути файл
@@ -1,6 +1,7 @@
//! Built-in IDE tools. Transport and discovery live in `ide-mcp`.
mod background;
mod check;
mod debug;
mod edit;
mod editors;
mod requests;
@@ -43,6 +44,7 @@ fn tools() -> Vec<tool::Tool> {
tools.extend(search::tools());
tools.extend(editors::tools());
tools.push(check::check_files());
tools.extend(debug::tools());
tools.push(symbols::get_symbol_info());
tools.push(symbols::find_references());
tools.push(symbols::get_call_hierarchy());
@@ -58,6 +60,22 @@ fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
trusted || tool.read_only
}
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.into_iter().filter(|t| allowed(t, trusted)).collect()
}
/// 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) {
Some(project) => tools_for(host, &project.root, project.is_trusted()),
None => tools_for(host, Path::new(""), true),
}
}
impl Registry {
/// The window that answers for `root`: one with the root open, or one it is attached in.
fn window(&self, root: &Path) -> Result<Option<(String, Arc<crate::Project>)>, String> {
@@ -125,11 +143,7 @@ impl ToolRegistry for Registry {
}
fn tools(&self, root: &Path) -> Result<Vec<ide_mcp::Tool>, String> {
let trusted = self.lists_as_trusted(root)?;
let mut all: Vec<_> = tools().into_iter().map(|t| t.metadata).collect();
if let Some(plugins) = self.0.plugin_host() {
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| tool));
}
Ok(all.into_iter().filter(|t| allowed(t, trusted)).collect())
Ok(tools_for(&self.0, root, trusted))
}
fn call(
&self,
+24 -2
Переглянути файл
@@ -15,6 +15,7 @@ struct State {
struct Pending {
window: String,
answer: oneshot::Sender<Result<bool, String>>,
value: oneshot::Sender<Option<String>>,
}
impl Requests {
pub fn set_ready(&self, window: &str, ready: bool) {
@@ -30,11 +31,23 @@ impl Requests {
state.pending.retain(|_, p| p.window != window);
}
pub fn answer(&self, window: &str, id: u32, allow: bool, error: Option<String>) -> IdeResult<()> {
self.answer_with(window, id, allow, error, None)
}
/// A request can also answer with a value, e.g. the id of the debug session it started.
pub fn answer_with(
&self,
window: &str,
id: u32,
allow: bool,
error: Option<String>,
value: Option<String>,
) -> IdeResult<()> {
let mut state = self.0.lock();
if !state.pending.get(&id).is_some_and(|p| p.window == window) {
return Err(IdeError::invalid("MCP request expired or belongs to another window"));
}
let pending = state.pending.remove(&id).unwrap();
let _ = pending.value.send(value);
let _ = pending.answer.send(error.map_or(Ok(allow), Err));
Ok(())
}
@@ -44,14 +57,23 @@ impl Requests {
}
pub(super) async fn ask(&self, call: &Call, request: McpUiRequest) -> IdeResult<()> {
self.ask_inner(call, request).await.map(|_| ())
}
pub(super) async fn ask_value(&self, call: &Call, request: McpUiRequest) -> IdeResult<Option<String>> {
self.ask_inner(call, request).await
}
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 (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 });
state.pending.insert(id, Pending { window: call.window.clone(), answer: tx, value: value_tx });
}
struct Close<'a>(&'a Requests, &'a Call, u32);
impl Drop for Close<'_> {
@@ -68,7 +90,7 @@ impl Requests {
_ = call.cancel.cancelled() => return Err(IdeError::cancelled()),
};
match result {
Ok(true) => Ok(()),
Ok(true) => Ok(value_rx.await.unwrap_or(None)),
Ok(false) => Err(IdeError::invalid("MCP request denied by the user")),
Err(message) => Err(IdeError::unavailable(message)),
}
+19 -15
Переглянути файл
@@ -29,14 +29,14 @@ const MAX_PROCESS_OUTPUT_LENGTH: usize = 20_000;
/// A before-launch build gets this long.
const BEFORE_LAUNCH_BUILD_TIMEOUT: Duration = Duration::from_secs(3600);
async fn load_configs(call: &Call) -> IdeResult<Vec<RunConfig>> {
pub(crate) async fn load_configs(call: &Call) -> IdeResult<Vec<RunConfig>> {
let host = call.host();
let window = call.window().to_owned();
let h = host.clone();
host.blocking(move || crate::ops::run::configs(&h, &window)).await
}
fn supports_overrides(config: &RunConfig) -> bool {
pub(crate) fn supports_overrides(config: &RunConfig) -> bool {
config.extras.compound.is_empty() && !config.command.trim().is_empty()
}
@@ -178,13 +178,17 @@ in the file instead of project-wide run configurations.",
.param(Param::optional("offset", ParamType::Integer, OFFSET))
}
/// What `execute_run_configuration` runs.
enum ExecutionTarget {
/// What `execute_run_configuration` and `xdebug_start_debugger_session` run.
pub(crate) enum ExecutionTarget {
ByName(String),
ByContext(String, i64),
}
fn execution_target(name: Option<String>, file: Option<String>, line: Option<i64>) -> IdeResult<ExecutionTarget> {
pub(crate) fn execution_target(
name: Option<String>,
file: Option<String>,
line: Option<i64>,
) -> IdeResult<ExecutionTarget> {
let name = name.filter(|n| !n.trim().is_empty());
let file = file.filter(|f| !f.trim().is_empty());
match (name, file, line) {
@@ -203,7 +207,7 @@ fn execution_target(name: Option<String>, file: Option<String>, line: Option<i64
/// The temporary configuration of the run point at `file:line` (1-based): the innermost target
/// enclosing that line (as JetBrains walks up to the enclosing test), else the whole file's
/// (its tests, its main function).
async fn config_from_code_location(
pub(crate) async fn config_from_code_location(
call: &Call,
configs: Vec<RunConfig>,
file: &str,
@@ -234,7 +238,7 @@ filePath to find valid run locations."
/// Applies the one-off overrides (JetBrains' `prepareRunConfigurationForExecution`): a missing or
/// empty string keeps the value, a whitespace-only one clears it; `envs` merge over the configuration's.
fn apply_overrides(
pub(crate) fn apply_overrides(
config: &mut RunConfig,
root: &Path,
args: Option<String>,
@@ -413,13 +417,13 @@ fn process_output(mut f: impl FnMut(&str) + Send + 'static) -> crate::ops::Chann
/// What failed before launch (JetBrains' `RunConfigurationBuildErrors`): build errors as
/// `path:line: message`, else the output of before-launch processes that failed.
#[derive(Default)]
struct BuildErrors {
errors: Vec<String>,
process_outputs: Vec<String>,
pub(crate) struct BuildErrors {
pub(crate) errors: Vec<String>,
pub(crate) process_outputs: Vec<String>,
}
impl BuildErrors {
fn text(&self) -> Option<String> {
pub(crate) fn text(&self) -> Option<String> {
let mut seen = std::collections::HashSet::new();
let errors: Vec<&String> = self.errors.iter().filter(|e| seen.insert(*e)).collect();
if !errors.is_empty() {
@@ -573,7 +577,7 @@ async fn find_java_module(call: &Call, main: &str) -> IdeResult<Option<String>>
/// built per its before-launch build policy, with `${classpath}` / `${testClasspath}`, the
/// module path and the module's `java` resolved through jdtls. `Err` says why it cannot start
/// (compile errors are added to `errors`). Other configurations are returned as they are.
async fn resolve_jvm_application(
pub(crate) async fn resolve_jvm_application(
call: &Call,
mut config: RunConfig,
errors: &mut BuildErrors,
@@ -639,7 +643,7 @@ async fn resolve_jvm_application(
/// The configuration's before-launch tasks, as the Run tool window runs them; returns why
/// the launch is aborted, if it is. Tool windows are not activated.
async fn before_launch(
pub(crate) async fn before_launch(
call: &Call,
config: &RunConfig,
configs: &[RunConfig],
@@ -754,7 +758,7 @@ fn describe_before_launch(
/// or applies — before-launch tasks, the stored environment (for a configuration made from
/// code, the one of the configuration it derives from), `.env` files, the `envs` overrides
/// (`NODE_OPTIONS`, `PATH`, ...), the stop command and a remote run target.
fn confirmation_detail(
pub(crate) fn confirmation_detail(
config: &RunConfig,
cwd: &str,
stored_env: &std::collections::BTreeMap<String, String>,
@@ -797,7 +801,7 @@ fn confirmation_detail(
detail
}
fn execution_failed(details: &[Option<String>]) -> IdeError {
pub(crate) fn execution_failed(details: &[Option<String>]) -> IdeError {
let details: Vec<&str> = details.iter().flatten().map(String::as_str).collect();
IdeError::invalid(format!("Execution failed: {}", details.join("\n")))
}
+68
Переглянути файл
@@ -246,6 +246,29 @@ pub fn mcp_server_status(host: &Host, window: &str) -> IdeResult<McpServerStatus
})
}
/// Lists the tools advertised by OpenIDEA's built-in MCP server (core IDE tools plus
/// enabled plugin-contributed `mcpTools`) for the window's project.
#[command(trust = always)]
pub fn mcp_server_tools(host: &Host, window: &str) -> IdeResult<ide_agent::McpProbeResult> {
let started = Instant::now();
let tools = super::list_tools_for_window(host, window)
.into_iter()
.map(|tool| ide_agent::McpToolSummary {
name: tool.name,
description: (!tool.description.trim().is_empty()).then_some(tool.description),
})
.collect();
Ok(ide_agent::McpProbeResult {
ok: true,
server_name: Some("OpenIDEA".into()),
server_version: Some(env!("CARGO_PKG_VERSION").into()),
protocol_version: Some(ide_mcp::PROTOCOL_VERSION.into()),
tools,
duration_ms: u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX),
error: None,
})
}
/// Settings › Agents › IDE MCP Server › Regenerate Token: forgets the kept token, and restarts the
/// server with a new one. Clients configured with the old token stop working.
#[command(trust = outside_restricted)]
@@ -299,6 +322,19 @@ pub fn mcp_respond(host: &Host, window: &str, id: u32, allow: bool, error: Optio
host.mcp_requests.answer(host.owner_window(window), id, allow, error)
}
/// Like `mcp_respond`, with a value for requests that ask for one (the started debug session id).
#[command(trust = trusted)]
pub fn mcp_respond_with(
host: &Host,
window: &str,
id: u32,
allow: bool,
error: Option<String>,
value: Option<String>,
) -> IdeResult<()> {
host.mcp_requests.answer_with(host.owner_window(window), id, allow, error, value)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -315,6 +351,36 @@ mod tests {
assert_eq!(port_to_wait_for((local, 51234), Some(64342)), None);
assert_eq!(port_to_wait_for((local, 64342), None), None);
}
#[tokio::test]
async fn mcp_server_tools_lists_core_tools_and_respects_restricted_mode() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let project_dir = base.join("sample");
std::fs::create_dir_all(&project_dir).unwrap();
let host = Arc::new(Host::new(crate::HostConfig::for_test(&base)));
// Without an open project (e.g. Welcome screen Settings), all built-in tools are listed.
let without_project = mcp_server_tools(&host, "welcome").unwrap();
assert!(without_project.ok);
assert_eq!(without_project.server_name.as_deref(), Some("OpenIDEA"));
assert!(without_project.tools.iter().any(|t| t.name == "search_text"));
assert!(without_project.tools.iter().any(|t| t.name == "run_command"));
// Opening an untrusted project filters out write/run tools, matching Registry::tools.
host.open_project("main", &project_dir).unwrap();
let restricted = mcp_server_tools(&host, "main").unwrap();
assert!(restricted.ok);
assert!(restricted.tools.iter().any(|t| t.name == "search_text"));
assert!(!restricted.tools.iter().any(|t| t.name == "run_command"));
assert!(restricted.tools.len() < without_project.tools.len());
// Trusting the project restores the full tool set.
host.set_project_trust(&project_dir, true, false).await.unwrap();
let trusted = mcp_server_tools(&host, "main").unwrap();
assert_eq!(trusted.tools.len(), without_project.tools.len());
assert!(trusted.tools.iter().any(|t| t.name == "run_command"));
}
}
ide_command::domain!(
@@ -323,7 +389,9 @@ ide_command::domain!(
mcp_background_projects,
mcp_regenerate_token,
mcp_respond,
mcp_respond_with,
mcp_server_status,
mcp_server_tools,
mcp_ui_ready,
mcp_unload_background_project,
);
+4
Переглянути файл
@@ -70,6 +70,10 @@ impl Call {
pub async fn ask(&self, request: ide_core::event::McpUiRequest) -> IdeResult<()> {
self.host.mcp_requests.ask(self, request).await
}
/// A window request that answers with a value, e.g. the debug session it started.
pub async fn ask_value(&self, request: ide_core::event::McpUiRequest) -> IdeResult<Option<String>> {
self.host.mcp_requests.ask_value(self, request).await
}
/// Whether the project has a window to show what the tool starts (not one loaded for MCP alone).
pub fn has_window(&self) -> bool {
self.host.mcp_requests.window_ready(&self.window)
+27 -4
Переглянути файл
@@ -173,6 +173,21 @@ pub const DYNAMIC_PLUGIN_TOOLS: &str = "pluginTools";
pub const DYNAMIC_FLUTTER_BUILD: &str = "flutterBuild";
/// Id (and `menu.` label key) of the Build › Flutter submenu.
pub const FLUTTER_BUILD_MENU: &str = "build.flutter";
/// Build › Xcode: Clean Build Folder and Delete DerivedData, filled only when the project has
/// Xcode schemes. A submenu after Build › Flutter when it has items, like it.
pub const DYNAMIC_XCODE_BUILD: &str = "xcodeBuild";
/// Id (and `menu.` label key) of the Build › Xcode submenu.
pub const XCODE_BUILD_MENU: &str = "build.xcode";
/// The submenu (id, English label) a dynamic slot is shown as when it has items, followed by a
/// separator; `None`: its items are listed in place.
pub fn dynamic_submenu(slot: &str) -> Option<(&'static str, &'static str)> {
match slot {
DYNAMIC_FLUTTER_BUILD => Some((FLUTTER_BUILD_MENU, "Flutter")),
DYNAMIC_XCODE_BUILD => Some((XCODE_BUILD_MENU, "Xcode")),
_ => None,
}
}
/// The menu bar for `os`. Labels are English defaults; the frontend replaces
/// them with `menu.<id>` strings from the active locale catalog.
@@ -262,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"),
],
),
@@ -425,6 +441,11 @@ pub fn spec(os: Os) -> Vec<Entry> {
vec![
act("editor.toggleSoftWrap", "Soft-Wrap"),
act("editor.toggleRenderedDocs", "Render Documentation Comments"),
SEP,
act("editor.toggleLocalWhitespaces", "Show Whitespaces"),
act("editor.toggleLocalLineNumbers", "Show Line Numbers"),
act("editor.toggleLocalGutterIcons", "Show Gutter Icons"),
act("editor.toggleLocalIndentGuides", "Show Indent Guides"),
],
),
SEP,
@@ -464,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…"),
@@ -617,6 +639,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
"Build",
vec![
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD),
Entry::Dynamic(DYNAMIC_XCODE_BUILD),
act("build.buildProject", "Build Project"),
act("build.buildModule", "Build Module"),
act("build.compileFile", "Recompile"),
@@ -1293,12 +1316,12 @@ pub fn model(spec: &[Entry], recent: &[RecentItem], config: &MenuConfig) -> Vec<
}
}));
}
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD) => {
let items = config.dynamic_items(DYNAMIC_FLUTTER_BUILD);
Entry::Dynamic(slot) if let Some((id, label)) = dynamic_submenu(slot) => {
let items = config.dynamic_items(slot);
if !items.is_empty() {
out.push(MenuNode::Submenu {
id: FLUTTER_BUILD_MENU.into(),
label: "Flutter".into(),
id: id.into(),
label: label.into(),
current: None,
children: items.iter().map(DynamicItem::model).collect(),
});
+431 -31
Переглянути файл
@@ -6,11 +6,13 @@ use crate::agent_secrets::{AgentSecrets, Kept};
use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentModelCatalog,
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentRecoveryReport, AgentSkillMode, AgentSkillPolicy,
AgentSkillState, AgentTask, CopilotAuthStatus, CustomAgentInput, ExternalSession, InstallRemoteSkillRequest,
LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput,
McpTransport, NewAgentTask, RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentMemoryCatalog,
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemoryOverrides, AgentMemorySettings, AgentModelCatalog, AgentProbe,
AgentPrompt, AgentProvider, AgentProviderMemoryPolicy, AgentQueued, AgentRecoveryReport, AgentSkillMode,
AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode, CopilotAuthStatus, CreateAgentMemoryInput,
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource, McpImportSelection,
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput,
RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
};
use ide_command::command;
use ide_core::error::ErrorKind;
@@ -1113,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 {
@@ -1143,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
@@ -1216,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",
@@ -1224,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(
@@ -1295,6 +1304,17 @@ pub fn agent_set_skill_overrides(
host.project(window)?.agents.set_skill_overrides(&task, overrides)
}
/// Updates per-session memory overrides (auto-memory mode and per-entry modes) on `task`.
#[command(trust = always)]
pub fn agent_set_memory_overrides(
host: &Host,
window: &str,
task: String,
overrides: AgentMemoryOverrides,
) -> IdeResult<AgentTask> {
host.project(window)?.agents.set_memory_overrides(&task, overrides)
}
/// Every skill discovered in the project, the user's folders and enabled plugins, with
/// the mode a session runs it with (without any session's own overrides).
#[command(trust = always)]
@@ -1566,6 +1586,272 @@ fn host_skills_policy(host: &Host, project: Option<&crate::Project>) -> SkillsPo
}
}
fn host_memory_policy(host: &Host, project: Option<&crate::Project>) -> ide_agent::memory::MemoryPolicy {
match project {
Some(project) => ide_agent::memory::MemoryPolicy {
user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.memory.clone(),
workspace: project.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.memory.clone(),
workspace_trusted: project.trusted.load(std::sync::atomic::Ordering::Acquire),
workspace_roots: workspace_skill_roots(&project.root),
},
None => ide_agent::memory::MemoryPolicy {
user: host.global_settings.effective().agents.memory.clone(),
workspace: Default::default(),
workspace_trusted: true,
workspace_roots: Vec::new(),
},
}
}
fn memory_settings_layers(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
) -> (AgentMemorySettings, Option<AgentMemorySettings>) {
let user = host.global_settings.effective().agents.memory.clone();
let workspace =
project.map(|p| p.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.memory.clone());
(user, workspace)
}
fn is_default_memory_settings(s: &AgentMemorySettings) -> bool {
s.auto_memory == AutoMemoryMode::Inherit && s.providers.is_empty() && s.entries.is_empty()
}
fn persist_memory_settings(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
scope: McpScope,
settings: &AgentMemorySettings,
) -> IdeResult<()> {
let value = if is_default_memory_settings(settings) {
serde_json::Value::Null
} else {
serde_json::to_value(settings).map_err(|e| IdeError::invalid(e.to_string()))?
};
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
match scope {
McpScope::User => {
host.global_settings.set(ide_workspace::settings::SettingsScope::Global, "agents.memory", value)?;
for p in host.projects() {
p.settings.reload();
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
}
McpScope::Workspace => {
let p = project.ok_or_else(|| IdeError::invalid("Open a project to configure workspace memory"))?;
p.settings.set(ide_workspace::settings::SettingsScope::Project, "agents.memory", value)?;
p.agents.notify_mcp_servers_changed();
p.sink.emit(event);
}
}
Ok(())
}
async fn current_memory_catalog(host: &Host, project: Option<&crate::Project>) -> IdeResult<AgentMemoryCatalog> {
let policy = host_memory_policy(host, project);
let home = host.home_dir();
blocking(move || {
let entries = ide_agent::memory::discover_memories(&policy.workspace_roots, home.as_deref());
Ok(ide_agent::memory::resolve_catalog(entries, None, &policy, home.as_deref()))
})
.await
}
/// Discovers every agent instruction file, path-scoped rule, and learned auto-memory note
/// with resolved modes and per-provider auto-memory statuses.
#[command(trust = always)]
pub async fn agent_memory_list(host: &Host, window: &str) -> IdeResult<AgentMemoryCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
current_memory_catalog(host, project.as_deref()).await
}
/// Sets how memory entry `id` runs in `scope` (`settings.toml` vs `.openidea/settings.toml`),
/// never modifying the file on disk.
#[command(trust = always)]
pub async fn agent_memory_set_mode(
host: &Host,
window: &str,
id: String,
scope: McpScope,
mode: AgentMemoryMode,
agents: Vec<String>,
) -> IdeResult<AgentMemoryCatalog> {
let id = id.trim().to_owned();
if id.is_empty() {
return Err(IdeError::invalid("a memory entry needs an id"));
}
let clean_agents: Vec<String> = agents.into_iter().map(|a| a.trim().to_owned()).filter(|a| !a.is_empty()).collect();
let project = host.project(window).ok().filter(|p| !p.light);
let (mut user, mut workspace) = memory_settings_layers(host, project.as_ref());
let apply = |layer: &mut AgentMemorySettings| -> bool {
if mode == AgentMemoryMode::Auto && clean_agents.is_empty() {
layer.entries.remove(&id).is_some()
} else {
let next = AgentMemoryEntryPolicy { mode, agents: clean_agents.clone() };
layer.entries.insert(id.clone(), next.clone()).as_ref() != Some(&next)
}
};
match scope {
McpScope::User => {
if apply(&mut user) {
persist_memory_settings(host, None, scope, &user)?;
}
}
McpScope::Workspace => {
let ws =
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace memory"))?;
if apply(ws) {
let updated = ws.clone();
persist_memory_settings(host, project.as_ref(), scope, &updated)?;
}
}
}
current_memory_catalog(host, project.as_deref()).await
}
/// Sets the cross-session auto-memory policy (`Inherit`, `ReadWrite`, `ReadOnly`, `Off`)
/// globally or for one `provider` in `scope`.
#[command(trust = always)]
pub async fn agent_memory_set_auto(
host: &Host,
window: &str,
scope: McpScope,
provider: Option<String>,
mode: AutoMemoryMode,
) -> IdeResult<AgentMemoryCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
let (mut user, mut workspace) = memory_settings_layers(host, project.as_ref());
let prov_key = provider
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(|s| ide_agent::memory::normalize_provider_id(s).to_owned());
let apply = |layer: &mut AgentMemorySettings| -> bool {
match &prov_key {
None => {
let changed = layer.auto_memory != mode;
layer.auto_memory = mode;
changed
}
Some(key) => {
if mode == AutoMemoryMode::Inherit {
layer.providers.remove(key).is_some()
} else {
let next = AgentProviderMemoryPolicy { auto_memory: mode };
layer.providers.insert(key.clone(), next.clone()).as_ref() != Some(&next)
}
}
}
};
match scope {
McpScope::User => {
if apply(&mut user) {
persist_memory_settings(host, None, scope, &user)?;
}
}
McpScope::Workspace => {
let ws =
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace memory"))?;
if apply(ws) {
let updated = ws.clone();
persist_memory_settings(host, project.as_ref(), scope, &updated)?;
}
}
}
current_memory_catalog(host, project.as_deref()).await
}
/// Creates a new instruction or path-scoped rule file on disk.
#[command(trust = always)]
pub async fn agent_memory_create(
host: &Host,
window: &str,
input: CreateAgentMemoryInput,
) -> IdeResult<AgentMemoryCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
if input.scope == McpScope::Workspace {
host.require_trust(window)?;
}
let ws_root = project.as_ref().map(|p| p.root.clone());
let home = host.home_dir();
blocking(move || {
ide_agent::memory::create_memory(&input, ws_root.as_deref(), home.as_deref()).map_err(IdeError::invalid)
})
.await?;
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
current_memory_catalog(host, project.as_deref()).await
}
/// Promotes a learned auto-memory note into `<workspace>/AGENTS.md`.
#[command(trust = trusted)]
pub async fn agent_memory_promote(
host: &Host,
window: &str,
input: PromoteAgentMemoryInput,
) -> IdeResult<AgentMemoryCatalog> {
host.require_trust(window)?;
let project = host.project(window)?;
let ws_root = project.root.clone();
let roots = workspace_skill_roots(&ws_root);
let home = host.home_dir();
blocking(move || {
let entries = ide_agent::memory::discover_memories(&roots, home.as_deref());
ide_agent::memory::promote_memory(&input, &entries, &ws_root).map_err(IdeError::invalid)
})
.await?;
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
current_memory_catalog(host, Some(&project)).await
}
/// Deletes a writable memory entry (learned auto-memory note or OpenIDEA shared memory file).
#[command(trust = always)]
pub async fn agent_memory_delete(host: &Host, window: &str, id: String) -> IdeResult<AgentMemoryCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
if id.starts_with("workspace::") {
host.require_trust(window)?;
}
let roots = project.as_ref().map(|p| workspace_skill_roots(&p.root)).unwrap_or_default();
let home = host.home_dir();
blocking(move || {
let entries = ide_agent::memory::discover_memories(&roots, home.as_deref());
ide_agent::memory::delete_memory(&id, &entries).map_err(IdeError::invalid)
})
.await?;
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
current_memory_catalog(host, project.as_deref()).await
}
/// Clears local auto-memory files for `provider` (`claude`, `codex`, or `hermes`).
#[command(trust = always)]
pub async fn agent_memory_reset_provider(host: &Host, window: &str, provider: String) -> IdeResult<AgentMemoryCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
let roots = project.as_ref().map(|p| workspace_skill_roots(&p.root)).unwrap_or_default();
let home = host.home_dir();
blocking(move || {
ide_agent::memory::reset_provider_memory(&provider, &roots, home.as_deref()).map_err(IdeError::invalid)
})
.await?;
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
current_memory_catalog(host, project.as_deref()).await
}
fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::Path>) -> IdeResult<std::path::PathBuf> {
let Some(requested) = requested else {
return Ok(root.to_path_buf());
@@ -1587,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();
@@ -1744,6 +2136,13 @@ ide_command::domain!(
agent_mcp_save_json,
agent_mcp_set_enabled,
agent_mcp_test,
agent_memory_create,
agent_memory_delete,
agent_memory_list,
agent_memory_promote,
agent_memory_reset_provider,
agent_memory_set_auto,
agent_memory_set_mode,
agent_poke_network,
agent_preview_copilot_models,
agent_probe,
@@ -1768,6 +2167,7 @@ ide_command::domain!(
agent_set_config,
agent_set_env,
agent_set_mcp_overrides,
agent_set_memory_overrides,
agent_set_recovery_window,
agent_set_skill_overrides,
agent_skills_browse,
+20
Переглянути файл
@@ -600,6 +600,26 @@ pub fn debug_breakpoint_states(host: &Host, path: PathBuf) -> IdeResult<Vec<Brea
Ok(host.debugger.breakpoint_states(&path))
}
/// This window's stored breakpoints, with their full attributes (not just verification states).
/// Kept as a plain function: the MCP tools list and edit them under the window's owner, so they
/// are sent to this window's sessions just like breakpoints set in the editor.
pub fn debug_breakpoints(
host: &Host,
window: &str,
) -> (std::collections::BTreeMap<PathBuf, Vec<Breakpoint>>, Vec<FunctionBreakpoint>, Vec<DataBreakpoint>) {
host.debugger.breakpoints(host.owner_window(window))
}
/// Whether a live session is suspended; `None` once it has ended. Used by tools that wait for a pause.
pub fn debug_session_suspended(host: &Host, session: DebugSessionId) -> Option<bool> {
host.debugger.session_suspended(session)
}
/// The thread the session last stopped in, when the adapter named one. Frame tools default to it.
pub fn debug_stopped_thread(host: &Host, session: DebugSessionId) -> Option<i64> {
host.debugger.stopped_thread(session)
}
/// This window's live sessions, including adapter-started child sessions.
#[command(trust = always)]
pub fn debug_sessions(host: &Host, window: &str) -> IdeResult<Vec<SessionInfo>> {
+40
Переглянути файл
@@ -0,0 +1,40 @@
//! iOS Simulators for Xcode projects, through `xcrun simctl` on the project host.
use crate::Host;
use ide_command::command;
use ide_core::{IdeError, IdeResult};
use ide_run::simulator::{self, IosSimulator};
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
/// 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(move || simulator::list(&root)).await.map(Some)
}
/// Boots a simulator; returns once it is booted.
#[command(trust = trusted)]
pub async fn ios_simulator_boot(_host: &Host, udid: String) -> IdeResult<()> {
blocking(move || simulator::boot(&udid)).await
}
#[command(trust = trusted)]
pub async fn ios_simulator_shutdown(_host: &Host, udid: String) -> IdeResult<()> {
blocking(move || simulator::shutdown(&udid)).await
}
/// Opens Simulator.app.
#[command(trust = trusted)]
pub async fn ios_simulator_open_app(_host: &Host) -> IdeResult<()> {
blocking(simulator::open_app).await
}
ide_command::domain!(ios: ios_simulators, ios_simulator_boot, ios_simulator_shutdown, ios_simulator_open_app);
+118 -30
Переглянути файл
@@ -544,38 +544,24 @@ async fn resolve_launch_without_jdtls(
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
match from_server {
// The IDE's Java build gave the whole classpath; the server adds its JDK.
Some(server) if by_service => {
info.project_root = server.classpath.project_root;
info.java_home = server.jdk_home.map(Into::into);
}
None if by_service => {}
Some(server) => {
info.project_root = server.classpath.project_root;
info.module_paths = server.classpath.module_paths;
info.java_home = server.jdk_home.map(Into::into);
append_unique_class_paths(&mut class_paths, server.classpath.class_paths);
}
None => {
if !is_maven_module(root, &model, &module) {
return Err(IdeError::unavailable(
"Cannot resolve the classpath: the Java language server does not report it \
(java-analyzer/projectClasspath), and the module is not a Maven project",
));
}
let is_maven = is_maven_module(root, &model, &module);
let delegated_maven = !by_service && settings.languages.java.maven.delegate_build && is_maven;
apply_without_jdtls_classpath(
&mut class_paths,
&mut info,
from_server,
by_service,
is_maven,
delegated_maven,
|| {
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
let classpath = if aggregator && policy == BuildPolicy::NoBuild {
compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel)?
if aggregator && policy == BuildPolicy::NoBuild {
compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel)
} else {
compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?
};
append_unique_class_paths(
&mut class_paths,
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
);
}
}
compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)
}
},
)?;
info.class_paths = class_paths;
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
@@ -825,6 +811,59 @@ fn same_entry(a: &str, b: &str, windows: bool) -> bool {
a == b || entry_key(a, windows) == entry_key(b, windows)
}
/// Resolves the runtime/test classpath for a launch without jdtls (e.g. `java-analyzer` or
/// no Java language server). When `delegated_maven` is true (`delegateBuild = true` on a Maven
/// module), delegates classpath resolution to Maven itself (falling back to the language server's
/// classpath on error, matching the jdtls path) so child POM `<exclusions>` and Maven dependency
/// mediation are respected (#5586).
fn apply_without_jdtls_classpath(
class_paths: &mut Vec<String>,
info: &mut JavaLaunchInfo,
from_server: Option<ide_lsp::java_project::ServerClasspath>,
by_service: bool,
is_maven: bool,
delegated_maven: bool,
probe_maven: impl FnOnce() -> IdeResult<String>,
) -> IdeResult<()> {
match from_server {
// The IDE's Java build gave the whole classpath; the server adds its JDK.
Some(server) if by_service => {
info.project_root = server.classpath.project_root;
info.java_home = server.jdk_home.map(Into::into);
Ok(())
}
None if by_service => Ok(()),
Some(server) if delegated_maven => {
info.project_root = server.classpath.project_root;
info.module_paths = server.classpath.module_paths;
info.java_home = server.jdk_home.map(Into::into);
info.class_paths = server.classpath.class_paths;
merge_maven_launch_classpath(class_paths, info, probe_maven(), &[])
}
Some(server) => {
info.project_root = server.classpath.project_root;
info.module_paths = server.classpath.module_paths;
info.java_home = server.jdk_home.map(Into::into);
append_unique_class_paths(class_paths, server.classpath.class_paths);
Ok(())
}
None => {
if !is_maven {
return Err(IdeError::unavailable(
"Cannot resolve the classpath: the Java language server does not report it \
(java-analyzer/projectClasspath), and the module is not a Maven project",
));
}
let classpath = probe_maven()?;
append_unique_class_paths(
class_paths,
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
);
Ok(())
}
}
}
/// Merge the Maven launch classpath without turning a recoverable probe failure into a
/// failed launch. Cancellation still propagates; ordinary failures keep jdtls' classpath
/// and leave the reason in the run console. Maven lists the module's and its reactor
@@ -1259,6 +1298,55 @@ mod tests {
);
}
#[test]
fn delegated_maven_without_jdtls_prefers_maven_classpath_over_server_classpath() {
let server = ide_lsp::java_project::ServerClasspath {
classpath: ide_lsp::jdtls::JavaClasspath {
project_root: Some(PathBuf::from("/work/child").into()),
// Static server resolver kept an excluded parent transitive jar (#5586).
class_paths: vec![
"/work/child/target/classes".into(),
"/m2/log4j-slf4j-impl-2.12.1.jar".into(),
"/m2/logback-classic.jar".into(),
],
module_paths: vec![],
},
jdk_home: Some(PathBuf::from("/jdk8")),
};
let maven = std::env::join_paths(["/work/child/target/classes", "/m2/logback-classic.jar"])
.unwrap()
.to_string_lossy()
.into_owned();
let mut class_paths = vec!["/work/child/target/classes".to_owned()];
let mut info = JavaLaunchInfo::default();
apply_without_jdtls_classpath(&mut class_paths, &mut info, Some(server), false, true, true, || Ok(maven))
.unwrap();
assert_eq!(class_paths, ["/work/child/target/classes", "/m2/logback-classic.jar"]);
assert_eq!(info.project_root, Some(PathBuf::from("/work/child").into()));
assert_eq!(info.java_home, Some(PathBuf::from("/jdk8").into()));
assert!(info.hints.is_empty(), "{:?}", info.hints);
}
#[test]
fn delegated_maven_without_jdtls_falls_back_to_server_classpath_on_probe_error() {
let server = ide_lsp::java_project::ServerClasspath {
classpath: ide_lsp::jdtls::JavaClasspath {
project_root: Some(PathBuf::from("/work/child").into()),
class_paths: vec!["/m2/server-fallback.jar".into()],
module_paths: vec![],
},
jdk_home: None,
};
let mut class_paths = vec!["/work/child/target/classes".to_owned()];
let mut info = JavaLaunchInfo::default();
apply_without_jdtls_classpath(&mut class_paths, &mut info, Some(server), false, true, true, || {
Err(IdeError::internal("maven offline"))
})
.unwrap();
assert_eq!(class_paths, ["/work/child/target/classes", "/m2/server-fallback.jar"]);
assert!(info.hints[0].contains("maven offline"), "{:?}", info.hints);
}
#[test]
fn cancelled_maven_classpath_probe_propagates_without_fallback() {
let mut class_paths = vec!["snapshot.jar".to_owned()];
+110 -3
Переглянути файл
@@ -336,20 +336,36 @@ pub async fn lsp_inline_completion(
let plugin = match plugin_providers(host, window, doc, ProviderKind::InlineCompletion) {
Some((plugins, d)) if !matches!(&result, Ok(items) if !items.is_empty()) => {
let cancel = cancel.clone();
plugin_call(move || plugins.provide_inline_completion(&d, pos, &cancel)).await.flatten()
plugin_call(move || {
let offered = plugins.offers_inline_completion(&d.language);
(offered, plugins.provide_inline_completion(&d, pos, &cancel).map(|(_, s)| s))
})
.await
}
_ => None,
};
host.end_request(request);
inline_items(result, plugin)
}
/// The plugin's suggestion, else the servers'. When a plugin offers ghost text
/// for the document, "no server supports inline completion" is not returned:
/// the editor would stop asking while typing for 30 s, and a plugin that had
/// nothing this time (cancelled by the next keystroke) may have some next time.
fn inline_items(
servers: IdeResult<Vec<InlineCompletionItem>>,
plugin: Option<(bool, Option<ide_plugin::InlineSuggestion>)>,
) -> IdeResult<Vec<InlineCompletionItem>> {
match plugin {
Some((_, s)) => Ok(vec![InlineCompletionItem {
Some((_, Some(s))) => Ok(vec![InlineCompletionItem {
insert_text: s.insert_text,
range: s.replace,
filter_text: None,
command: None,
server: PLUGIN_SERVER,
}]),
None => result,
Some((true, None)) => provider_server(servers),
_ => servers,
}
}
@@ -639,6 +655,73 @@ pub async fn lsp_file_references(
result
}
/// The header of the document's source file or the source of its header (C, C++,
/// Objective-C) as clangd finds it; `None` without clangd or an answer. Cancel with
/// `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_switch_source_header(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
) -> IdeResult<Option<String>> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let result = tokio::select! {
result = lsp.switch_source_header(doc, cancel.clone()) => result,
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
};
host.end_request(request);
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)`.
@@ -2097,6 +2180,12 @@ pub async fn lsp_restart(host: &Host, window: &str, server: ServerId) -> IdeResu
Ok(())
}
/// Stops a language server; it starts again when a file it serves is opened.
#[command(trust = trusted)]
pub async fn lsp_stop(host: &Host, window: &str, server: ServerId) -> IdeResult<()> {
host.project(window)?.lsp.stop(server).await
}
/// Restarts the language servers named `name` in every open project, so a tool installed or
/// updated from one window is what all of them run (not only that window's project).
pub async fn lsp_restart_named(host: &Host, name: &str) -> IdeResult<()> {
@@ -2403,6 +2492,19 @@ pub fn plugin_formatters() -> IdeResult<Vec<crate::plugins::language_features::F
#[cfg(test)]
mod tests {
#[test]
fn a_plugin_offering_ghost_text_keeps_the_editor_asking() {
use super::*;
let none = || Err(ide_core::IdeError::unavailable("No server supports inline completion"));
// Nothing this time (cancelled by the next keystroke): an empty answer, not "unavailable".
assert!(inline_items(none(), Some((true, None))).unwrap().is_empty());
// No plugin for this language: the servers' answer as it is.
assert!(inline_items(none(), Some((false, None))).is_err());
assert!(inline_items(none(), None).is_err());
let s = ide_plugin::InlineSuggestion { insert_text: "a + b".into(), replace: None };
assert_eq!(inline_items(none(), Some((true, Some(s)))).unwrap()[0].insert_text, "a + b");
}
#[test]
fn a_completion_word_is_its_line_and_what_precedes_it() {
use super::*;
@@ -3288,6 +3390,10 @@ ide_command::domain!(
lsp_hover,
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,
@@ -3306,6 +3412,7 @@ ide_command::domain!(
lsp_resolve_command,
lsp_resolve_completion,
lsp_restart,
lsp_stop,
lsp_semantic_tokens,
lsp_servers,
lsp_signature_help,
+6
Переглянути файл
@@ -22,6 +22,7 @@ pub mod heap;
pub mod history;
pub mod host_metrics;
pub mod http;
pub mod ios;
pub mod java;
pub mod jvm_icons;
pub mod lsp;
@@ -51,6 +52,8 @@ pub mod tools;
pub mod vcs;
pub mod web;
pub mod xcode_bsp;
pub mod xcode_clean;
pub mod xcode_files;
use crate::Host;
use ide_core::{IdeError, IdeResult};
@@ -103,6 +106,7 @@ ide_command::domains!(
history: crate::ops::history,
host_metrics: crate::ops::host_metrics,
http: crate::ops::http,
ios: crate::ops::ios,
java: crate::ops::java,
jvm_icons: crate::ops::jvm_icons,
lsp: crate::ops::lsp,
@@ -138,6 +142,8 @@ ide_command::domains!(
vcs_commands: crate::ops::vcs::commands,
web: crate::ops::web,
xcode_bsp: crate::ops::xcode_bsp,
xcode_clean: crate::ops::xcode_clean,
xcode_files: crate::ops::xcode_files,
);
/// A blocking task that panicked or was cancelled, as the error a command returns.
+13 -2
Переглянути файл
@@ -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() {
@@ -483,8 +489,13 @@ pub fn set_settings(
project.agents.notify_mcp_servers_changed();
}
}
// A skill policy change re-resolves the modes; an idle session restarts to pick them up.
if key == "agents" || key == "agents.skills" || key.starts_with("agents.skills.") {
// A skill or memory policy change re-resolves the modes; an idle session restarts to pick them up.
if key == "agents"
|| key == "agents.skills"
|| key.starts_with("agents.skills.")
|| key == "agents.memory"
|| key.starts_with("agents.memory.")
{
for project in affected() {
project.agents.notify_mcp_servers_changed();
}
+56 -18
Переглянути файл
@@ -8,12 +8,12 @@ use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
/// Files handed out at most, and bytes in total: a project's controllers fit well
/// inside these, and the UI indexes them once.
const MAX_FILES: usize = 1024;
const MAX_BYTES: usize = 48 << 20;
/// Files handed out at most, and bytes in total: the controllers and HTTP clients of a
/// large multi-project tree fit well inside these, and the UI indexes them once.
const MAX_FILES: usize = 8192;
const MAX_BYTES: usize = 128 << 20;
/// A single source bigger than this is not a controller.
const MAX_FILE_BYTES: u64 = 4 << 20;
@@ -24,18 +24,27 @@ pub struct RouteSource {
pub text: String,
}
/// Which files a framework's routes can live in, and words one of which such a file names.
/// Which files a framework's routes can live in: a file names one of `words`, and one of
/// `owners` when there are any.
#[derive(Clone, Copy)]
pub(crate) struct RouteFiles {
extensions: &'static [&'static str],
words: &'static [&'static str],
owners: &'static [&'static str],
}
/// Spring mappings: Java and Kotlin sources that name a mapping annotation.
pub(crate) const SPRING: RouteFiles = RouteFiles { extensions: &["java", "kt", "kts"], words: &["Mapping"] };
/// Spring mappings: Java and Kotlin sources that name a request mapping annotation and a
/// controller or Feign client, the only classes the UI reads them from. Other `…Mapping`
/// names (MapStruct's `@Mapping`, mappers, DTOs) would otherwise fill the file budget in a
/// large tree and push real controllers out.
pub(crate) const SPRING: RouteFiles = RouteFiles {
extensions: &["java", "kt", "kts"],
words: &["RequestMapping", "GetMapping", "PostMapping", "PutMapping", "DeleteMapping", "PatchMapping"],
owners: &["Controller", "FeignClient"],
};
/// Flask and FastAPI routes: Python sources that import either (blueprints, routers and the
/// modules registering them all do).
pub(crate) const PYTHON: RouteFiles = RouteFiles { extensions: &["py"], words: &["flask", "fastapi"] };
pub(crate) const PYTHON: RouteFiles = RouteFiles { extensions: &["py"], words: &["flask", "fastapi"], owners: &[] };
impl RouteFiles {
fn declares_routes(&self, path: &Path) -> bool {
@@ -50,8 +59,13 @@ impl RouteFiles {
pub(crate) fn sources_in(root: &Path, excludes: &[String], kind: RouteFiles) -> Vec<RouteSource> {
let found: Mutex<Vec<RouteSource>> = Mutex::new(Vec::new());
let bytes = AtomicUsize::new(0);
let truncated = AtomicBool::new(false);
ide_vfs::walk_files(root, excludes, |path| {
if !kind.declares_routes(path) || bytes.load(Ordering::Relaxed) >= MAX_BYTES {
if !kind.declares_routes(path) {
return;
}
if bytes.load(Ordering::Relaxed) >= MAX_BYTES {
truncated.store(true, Ordering::Relaxed);
return;
}
if std::fs::metadata(path).map_or(true, |m| m.len() > MAX_FILE_BYTES) {
@@ -59,17 +73,25 @@ pub(crate) fn sources_in(root: &Path, excludes: &[String], kind: RouteFiles) ->
}
let Ok(text) = std::fs::read_to_string(path) else { return };
// Only a file that names a mapping annotation (or imports the framework) is worth parsing.
if !kind.words.iter().any(|w| text.contains(w)) {
if !kind.words.iter().any(|w| text.contains(w))
|| !(kind.owners.is_empty() || kind.owners.iter().any(|w| text.contains(w)))
{
return;
}
let Ok(mut found) = found.lock() else { return };
if found.len() >= MAX_FILES {
truncated.store(true, Ordering::Relaxed);
return;
}
bytes.fetch_add(text.len(), Ordering::Relaxed);
found.push(RouteSource { path: path.to_path_buf().into(), text });
});
let mut files = found.into_inner().unwrap_or_default();
if truncated.into_inner() {
tracing::warn!(
"routes: more than {MAX_FILES} files or {MAX_BYTES} bytes of route sources under {root:?}; the rest is left out"
);
}
files.sort_by(|a, b| a.path.cmp(&b.path));
files
}
@@ -162,13 +184,29 @@ mod tests {
fn files_that_name_no_mapping_are_left_out() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("src")).unwrap();
std::fs::write(tmp.path().join("src/Ctl.java"), "class Ctl { @GetMapping(\"/a\") void a() {} }").unwrap();
std::fs::write(
tmp.path().join("src/Ctl.java"),
"@RestController class Ctl { @GetMapping(\"/a\") void a() {} }",
)
.unwrap();
std::fs::write(
tmp.path().join("src/Client.java"),
"@FeignClient(\"b\") interface Client { @PostMapping(\"/b\") void b(); }",
)
.unwrap();
std::fs::write(tmp.path().join("src/Plain.java"), "class Plain { void a() {} }").unwrap();
std::fs::write(tmp.path().join("src/Notes.txt"), "@GetMapping(\"/a\")").unwrap();
std::fs::write(tmp.path().join("src/Notes.txt"), "@RestController @GetMapping(\"/a\")").unwrap();
// MapStruct mappers and other `…Mapping` names declare no route.
std::fs::write(
tmp.path().join("src/UserMapper.java"),
"@Mapper interface UserMapper { @Mapping(target = \"id\") Dto to(User u); }",
)
.unwrap();
std::fs::write(tmp.path().join("src/Dto.java"), "class Dto { RequestMapping meta; }").unwrap();
let files = sources_in(tmp.path(), &[], SPRING);
assert_eq!(files.len(), 1, "{:?}", files.iter().map(|f| &f.path).collect::<Vec<_>>());
assert!(files[0].path.ends_with("src/Ctl.java"), "{:?}", files[0].path);
assert!(files[0].text.contains("@GetMapping"));
let names: Vec<_> = files.iter().map(|f| f.path.file_name().unwrap().to_string_lossy().into_owned()).collect();
assert_eq!(names, ["Client.java", "Ctl.java"]);
assert!(files[1].text.contains("@GetMapping"));
}
#[test]
@@ -176,8 +214,8 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("module/src")).unwrap();
std::fs::create_dir_all(tmp.path().join("build")).unwrap();
std::fs::write(tmp.path().join("module/src/A.java"), "@RequestMapping(\"/a\")").unwrap();
std::fs::write(tmp.path().join("build/B.java"), "@RequestMapping(\"/b\")").unwrap();
std::fs::write(tmp.path().join("module/src/A.java"), "@Controller @RequestMapping(\"/a\")").unwrap();
std::fs::write(tmp.path().join("build/B.java"), "@Controller @RequestMapping(\"/b\")").unwrap();
let files = sources_in(tmp.path(), &["build/**".to_owned()], SPRING);
assert_eq!(files.len(), 1, "{:?}", files.iter().map(|f| &f.path).collect::<Vec<_>>());
assert!(files[0].path.ends_with("module/src/A.java"), "{:?}", files[0].path);
+139 -2
Переглянути файл
@@ -454,7 +454,10 @@ async fn start_inner(
if ide_run::is_python_kind(&config.kind) {
container_python_path(&mut config.env, &super::python::paths(&project), &project.root);
}
let config = container::prepare(host, &project.root, target, config).await?;
let (config, note) = container::prepare(host, &project.root, target, config).await?;
if let Some(note) = note {
on_output(OutputChunk::System { text: format!("{note}\n") });
}
let encoding = settings.console.encoding;
let options = StartOptions {
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
@@ -540,6 +543,9 @@ async fn start_inner(
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
}
let xcode_container = matches!(config.kind.as_str(), "xcode" | "xcode-test")
.then(|| xcode_container(&config).map(|c| run_dir.join(c)))
.flatten();
if config.kind == "xcode" {
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
config = host
@@ -549,6 +555,15 @@ async fn start_inner(
})
.await?;
}
if config.kind == ide_run::xcode_clean::KIND {
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
config = host
.blocking(move || {
ide_run::xcode_clean::prepare(&dir, &cache, &mut config)?;
Ok(config)
})
.await?;
}
if config.kind == "go" && config.extras.params.get("scope").is_some_and(|s| s == "file") {
let root = project.root.clone();
config = host
@@ -560,9 +575,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?;
@@ -600,9 +616,130 @@ async fn start_inner(
previous.emit(event);
});
}
let on_output = match xcode_container {
Some(container) => {
let (output, problems) = xcodebuild_problems(&project, &config.id, &run_dir, container, on_output, sink);
sink = problems;
output
}
None => on_output,
};
host.processes.start(&project.root, &config, &options, sink, Box::new(move |c| on_output(c)))
}
/// The `-project` / `-workspace` an Xcode configuration builds, relative to its folder.
fn xcode_container(config: &RunConfig) -> Option<String> {
config.extras.params.get("container").cloned().or_else(|| {
let at = config.args.iter().position(|a| a == "-project" || a == "-workspace")?;
config.args.get(at + 1).cloned()
})
}
const XCODEBUILD_SOURCE: &str = "xcodebuild";
/// Sends the compiler messages in an Xcode configuration's `xcodebuild` output to Problems as they
/// arrive, after clearing the ones its previous run reported. Messages without a location (linker
/// errors) are listed on the project file (`project.pbxproj` / `contents.xcworkspacedata`).
fn xcodebuild_problems(
project: &crate::project::Project,
config_id: &str,
cwd: &Path,
container: PathBuf,
on_output: Emit<OutputChunk>,
sink: ide_core::SharedSink,
) -> (Emit<OutputChunk>, ide_core::SharedSink) {
use ide_build::compile::{BuildMessage, XcodebuildMessages, diagnostics_from};
use ide_core::IdeEvent;
use std::collections::BTreeMap;
let project_file = container.join(if container.extension().is_some_and(|e| e == "xcworkspace") {
"contents.xcworkspacedata"
} else {
"project.pbxproj"
});
let reported = project.xcodebuild_problems.clone();
let previous = reported.lock().insert(config_id.to_owned(), Vec::new()).unwrap_or_default();
for path in previous {
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: XCODEBUILD_SOURCE.into(), items: Vec::new() });
}
struct State {
parser: XcodebuildMessages,
/// Unfinished lines of stdout and stderr.
partial: [String; 2],
files: BTreeMap<PathBuf, Vec<BuildMessage>>,
}
let state = Arc::new(parking_lot::Mutex::new(State {
parser: XcodebuildMessages::new(&project.root, cwd),
partial: Default::default(),
files: BTreeMap::new(),
}));
let config_id = config_id.to_owned();
let publish = {
let sink = sink.clone();
move |state: &mut State, messages: Vec<BuildMessage>| {
let mut changed = Vec::new();
for mut m in messages {
if m.path.is_none() {
m.path = Some(project_file.clone().into());
m.range = Some(ide_core::Range::default());
}
let Some(path) = m.path.clone().map(PathBuf::from) else { continue };
if !state.files.contains_key(&path) {
reported.lock().entry(config_id.clone()).or_default().push(path.clone());
}
state.files.entry(path.clone()).or_default().push(m);
if !changed.contains(&path) {
changed.push(path);
}
}
for path in changed {
let items = diagnostics_from(&state.files[&path], XCODEBUILD_SOURCE).remove(&path).unwrap_or_default();
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: XCODEBUILD_SOURCE.into(), items });
}
}
};
let publish = Arc::new(publish);
let output: Emit<OutputChunk> = {
let (state, publish) = (state.clone(), publish.clone());
Arc::new(move |chunk: OutputChunk| {
let stream = match &chunk {
OutputChunk::Stdout { text } => Some((0, text)),
OutputChunk::Stderr { text } => Some((1, text)),
OutputChunk::System { .. } => None,
};
if let Some((i, text)) = stream {
let mut guard = state.lock();
let s = &mut *guard;
s.partial[i].push_str(text);
let mut messages = Vec::new();
while let Some(end) = s.partial[i].find('\n') {
let line: String = s.partial[i].drain(..=end).collect();
messages.extend(s.parser.feed(line.trim_end_matches(['\n', '\r'])));
}
publish(s, messages);
}
on_output(chunk);
})
};
let problems: ide_core::SharedSink = Arc::new(move |event: IdeEvent| {
if matches!(event, IdeEvent::RunExited { .. }) {
let mut guard = state.lock();
let s = &mut *guard;
let mut messages = Vec::new();
for i in 0..2 {
let rest = std::mem::take(&mut s.partial[i]);
if !rest.is_empty() {
messages.extend(s.parser.feed(rest.trim_end_matches('\r')));
}
}
messages.extend(s.parser.finish());
publish(s, messages);
}
sink.emit(event);
});
(output, problems)
}
/// Plugins' Java agents (`[[contributes.javaAgents]]`, granted `java.agent`) for the JVM of an
/// Application, Spring Boot or JAR Application configuration started on this machine. A JVM on a
/// run target gets none; the console says so, and why an approved agent was left out. A launch
+2
Переглянути файл
@@ -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?;
+16 -8
Переглянути файл
@@ -6,8 +6,8 @@ use ide_core::remote_settings::{RunTarget, RunTargetKind};
use ide_core::{IdeError, IdeResult};
use ide_docker::DockerEndpoint;
use ide_remote::docker::{
ComposeService, ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, compose_container_root,
compose_service, container_config, container_name, default_container_root,
ComposeService, ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, NODE_DEBUG_FOLDER,
compose_container_root, compose_service, container_config, container_name, default_container_root, node_debug,
};
use ide_remote::target::DEBUG_PARAM;
use ide_run::RunConfig;
@@ -16,15 +16,21 @@ use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};
use std::time::SystemTime;
/// `config` rewritten to run in a new container of `target`'s image or service.
pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config: RunConfig) -> IdeResult<RunConfig> {
/// `config` rewritten to run in a new container of `target`'s image or service, and for a
/// Node.js debug run the line telling the debugger the project folder in the container.
pub(super) async fn prepare(
host: &Host,
root: &Path,
target: RunTarget,
config: RunConfig,
) -> IdeResult<(RunConfig, Option<String>)> {
if config.kind == "dotnet" || config.kind == "dotnet-test" {
return Err(IdeError::invalid(".NET Project requires the local machine"));
}
let debug = config.extras.params.get(DEBUG_PARAM).is_some_and(|v| v == "true");
if debug && config.debug_adapter.as_deref() != Some("debugpy") {
if debug && config.debug_adapter.as_deref() != Some("debugpy") && !node_debug(&config) {
return Err(IdeError::invalid(format!(
"'{}' can't be debugged in a container: only Python run configurations can",
"'{}' can't be debugged in a container: only Python and Node.js run configurations can",
config.name
)));
}
@@ -41,7 +47,8 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
let (service_env, service_ports) = server_context(&data_dir, &root, &target, &config);
let name = container_name(&config.id, &unique());
let debugging = if debug { Some(Debugging::prepare(&data_dir)?) } else { None };
container_config(
let note = (debug && node_debug(&config)).then(|| format!("{NODE_DEBUG_FOLDER}{container_root}"));
let config = container_config(
&config,
&ContainerRun {
target: &target,
@@ -60,7 +67,8 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
debugpy: d.debugpy.as_deref(),
}),
},
)
)?;
Ok((config, note))
})
.await
}
+52
Переглянути файл
@@ -0,0 +1,52 @@
//! Deleting an Xcode project's DerivedData (#6665 C6). Clean Build Folder is a run of
//! `ide_run::xcode_clean::KIND`; this is the part a run can't do: moving folders to the Trash.
use crate::Host;
use ide_command::command;
use ide_core::IdeResult;
use std::collections::BTreeMap;
use std::path::PathBuf;
async fn dirs(
host: &Host,
window: &str,
cwd: Option<String>,
params: BTreeMap<String, String>,
) -> IdeResult<Vec<PathBuf>> {
let project = host.project(window)?;
let dir = project.root.join(cwd.unwrap_or_default());
let cache = project.cache_dir.clone();
super::blocking(move || ide_run::xcode_clean::derived_data_dirs(&dir, &cache, &params)).await
}
/// The DerivedData folders [`xcode_delete_derived_data`] would delete for an `xcode`
/// configuration (its `cwd` and `params`), for the user to confirm.
#[command(trust = trusted)]
pub async fn xcode_derived_data(
host: &Host,
window: &str,
cwd: Option<String>,
params: BTreeMap<String, String>,
) -> IdeResult<Vec<String>> {
Ok(dirs(host, window, cwd, params).await?.iter().map(|d| d.to_string_lossy().into_owned()).collect())
}
/// Moves the configuration's DerivedData folders to the Trash, then restarts sourcekit-lsp: a
/// build server config (xcode-build-server's `build_root`) reads build logs and the index there.
#[command(trust = trusted)]
pub async fn xcode_delete_derived_data(
host: &Host,
window: &str,
cwd: Option<String>,
params: BTreeMap<String, String>,
) -> IdeResult<Vec<String>> {
let found = dirs(host, window, cwd, params).await?;
let deleted = found.clone();
super::blocking(move || found.iter().try_for_each(|d| ide_vfs::delete(d))).await?;
let project = host.project(window)?;
for server in project.lsp.servers().into_iter().filter(|s| s.name == "sourcekit-lsp") {
project.lsp.restart(server.id).await?;
}
Ok(deleted.iter().map(|d| d.to_string_lossy().into_owned()).collect())
}
ide_command::domain!(xcode_clean: xcode_derived_data, xcode_delete_derived_data);
+208
Переглянути файл
@@ -0,0 +1,208 @@
//! Source files created, renamed or deleted in an Xcode project (#6665 C7). `xcodebuild` compiles
//! only the files a target lists, so a new file in a classic `.xcodeproj` group is silently left
//! out. The IDE does not edit `project.pbxproj`: for XcodeGen / Tuist projects it offers to
//! regenerate the project, and for a classic project it says which new files the project doesn't
//! name, unless the project uses Xcode 16 synchronized folders, which pick new files up themselves.
use crate::Host;
use ide_command::command;
use ide_core::IdeResult;
use serde::Serialize;
use specta::Type;
use std::path::{Path, PathBuf};
/// Source files a target compiles; other files don't make `xcodebuild` miss code.
const SOURCE_EXTENSIONS: [&str; 9] = ["swift", "m", "mm", "h", "c", "cc", "cpp", "hpp", "metal"];
/// What the changed files need in their Xcode project.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum XcodeFileSync {
/// The project is generated from `project.yml` (`xcodegen`) or `Project.swift` (`tuist`) in `dir`.
#[serde(rename_all = "camelCase")]
Generated { dir: PathBuf, tool: String },
/// `files` (file names) are not named in `project`, a classic `.xcodeproj`.
#[serde(rename_all = "camelCase")]
NotInProject { project: PathBuf, files: Vec<String> },
}
fn is_source(path: &Path) -> bool {
path.extension().and_then(|e| e.to_str()).is_some_and(|e| SOURCE_EXTENSIONS.contains(&e))
}
/// Hidden folders and the bundles themselves are not project sources.
fn is_project_file(path: &Path, root: &Path) -> bool {
path.strip_prefix(root).is_ok_and(|rel| {
rel.components().all(|c| {
let name = c.as_os_str().to_string_lossy();
!name.starts_with('.') && !name.ends_with(".xcodeproj") && !name.ends_with(".xcworkspace")
})
})
}
enum Owner {
Generated(PathBuf, &'static str),
Classic(Vec<PathBuf>),
}
/// The nearest folder from `path` up to `root` with a project spec or `.xcodeproj` bundles.
fn owner(path: &Path, root: &Path) -> Option<Owner> {
let mut dir = path.parent()?;
loop {
if dir.join("project.yml").is_file() {
return Some(Owner::Generated(dir.to_path_buf(), "xcodegen"));
}
if dir.join("Project.swift").is_file() {
return Some(Owner::Generated(dir.to_path_buf(), "tuist"));
}
// A local Swift package builds its files from the folder layout, not from a project.
if dir.join("Package.swift").is_file() {
return None;
}
let mut projects: Vec<PathBuf> = std::fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "xcodeproj") && p.is_dir())
.collect();
if !projects.is_empty() {
projects.sort();
return Some(Owner::Classic(projects));
}
if dir == root {
return None;
}
dir = dir.parent()?;
}
}
/// Whether `text` names `file` as a whole name (`/* View.swift */`, `path = View.swift;`,
/// `"My View.swift"`), not as the end of another one (`AppView.swift`).
fn names(text: &str, file: &str) -> bool {
let part_of_name = |c: char| c.is_alphanumeric() || "_-.+".contains(c);
text.match_indices(file).any(|(at, _)| {
!text[..at].chars().next_back().is_some_and(part_of_name)
&& !text[at + file.len()..].chars().next().is_some_and(part_of_name)
})
}
/// What `created` (created or renamed to) and `removed` source files under `root` need; the
/// first Xcode project they belong to wins.
pub fn file_sync(root: &Path, created: &[PathBuf], removed: &[PathBuf]) -> Option<XcodeFileSync> {
let relevant = |p: &&PathBuf| is_source(p) && is_project_file(p, root);
let mut classic: Option<(Vec<PathBuf>, Vec<String>)> = None;
for (path, is_new) in
created.iter().filter(relevant).map(|p| (p, true)).chain(removed.iter().filter(relevant).map(|p| (p, false)))
{
match owner(path, root) {
Some(Owner::Generated(dir, tool)) => return Some(XcodeFileSync::Generated { dir, tool: tool.into() }),
// A deleted file is still named in the project; Xcode shows it in red.
Some(Owner::Classic(projects)) if is_new => {
let (owner_projects, files) = classic.get_or_insert_with(|| (projects.clone(), Vec::new()));
if *owner_projects == projects {
files.push(path.file_name()?.to_string_lossy().into_owned());
}
}
_ => {}
}
}
let (projects, files) = classic?;
// Plain string checks on project.pbxproj, no parsing; a project mixing groups and
// synchronized folders counts as synchronized, as does a name that's taken by another file.
let texts: Vec<String> =
projects.iter().filter_map(|p| std::fs::read_to_string(p.join("project.pbxproj")).ok()).collect();
if texts.is_empty() || texts.iter().any(|t| t.contains("PBXFileSystemSynchronizedRootGroup")) {
return None;
}
let mut files: Vec<String> = files.into_iter().filter(|f| !texts.iter().any(|t| names(t, f))).collect();
files.sort();
files.dedup();
(!files.is_empty()).then(|| XcodeFileSync::NotInProject { project: projects[0].clone(), files })
}
/// What source files created, renamed or deleted in the project need in their Xcode project;
/// `None` when they are in none, or it picks them up itself.
#[command(trust = trusted)]
pub async fn xcode_file_sync(
host: &Host,
window: &str,
created: Vec<PathBuf>,
removed: Vec<PathBuf>,
) -> IdeResult<Option<XcodeFileSync>> {
let root = host.project(window)?.root.clone();
host.blocking(move || Ok(file_sync(&root, &created, &removed))).await
}
ide_command::domain!(xcode_files: xcode_file_sync);
#[cfg(test)]
mod tests {
use super::*;
fn project(files: &[(&str, &str)]) -> tempfile::TempDir {
let dir = tempfile::tempdir().unwrap();
for (path, text) in files {
let path = dir.path().join(path);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
dir
}
const CLASSIC: &str = "/* Begin PBXFileReference section */ AppView.swift /* End */";
#[test]
fn names_new_sources_a_classic_project_does_not_mention() {
let dir = project(&[("App.xcodeproj/project.pbxproj", CLASSIC), ("App/AppView.swift", "")]);
let root = dir.path();
let created = [
root.join("App/AppView.swift"),
root.join("App/New.swift"),
root.join("App/View.swift"),
root.join("App/notes.md"),
];
assert_eq!(
file_sync(root, &created, &[]),
Some(XcodeFileSync::NotInProject {
project: root.join("App.xcodeproj"),
files: vec!["New.swift".into(), "View.swift".into()]
})
);
// Deleting a file needs nothing in a classic project.
assert_eq!(file_sync(root, &[], &[root.join("App/AppView.swift")]), None);
}
#[test]
fn trusts_synchronized_folders() {
let text = "/* Begin PBXFileSystemSynchronizedRootGroup section */";
let dir = project(&[("App.xcodeproj/project.pbxproj", text)]);
assert_eq!(file_sync(dir.path(), &[dir.path().join("App/New.swift")], &[]), None);
}
#[test]
fn offers_the_generator_of_the_nearest_spec() {
let dir =
project(&[("project.yml", ""), ("App.xcodeproj/project.pbxproj", CLASSIC), ("Mod/Project.swift", "")]);
let root = dir.path();
let generated = |dir: PathBuf, tool: &str| Some(XcodeFileSync::Generated { dir, tool: tool.into() });
assert_eq!(file_sync(root, &[], &[root.join("Sources/Old.swift")]), generated(root.into(), "xcodegen"));
assert_eq!(file_sync(root, &[root.join("Mod/A.m")], &[]), generated(root.join("Mod"), "tuist"));
}
#[test]
fn ignores_files_of_a_local_package_next_to_the_project() {
let dir = project(&[("App.xcodeproj/project.pbxproj", CLASSIC), ("Packages/Feature/Package.swift", "")]);
let root = dir.path();
assert_eq!(file_sync(root, &[root.join("Packages/Feature/Sources/Feature/New.swift")], &[]), None);
// Files of the app itself are still checked.
assert!(file_sync(root, &[root.join("App/New.swift")], &[]).is_some());
}
#[test]
fn ignores_files_outside_any_project() {
let dir = project(&[("App.xcodeproj/project.pbxproj", CLASSIC)]);
let root = dir.path();
assert_eq!(file_sync(&root.join("Sub"), &[root.join("Sub/A.swift")], &[]), None);
assert_eq!(file_sync(root, &[root.join(".build/A.swift"), PathBuf::from("/elsewhere/A.swift")], &[]), None);
}
}
+125 -45
Переглянути файл
@@ -9,8 +9,9 @@ use ide_extension::Package;
use ide_extension::ledger::{Ledger, Subject};
use ide_language::ProgramPin;
use ide_plugin::{
CommitChange, CommitDraft, EventKind, HostApi, HostError, HttpRequest, HttpResponse, NotificationLevel,
ProcessChunk, ProcessCommand, ProcessOptions, ProcessOutput, Prompt, RepositoryStatus, StatusItem,
CommitChange, CommitDraft, EventKind, HostApi, HostError, HttpRequest, HttpResponse, HttpStreamHead,
NotificationLevel, ProcessChunk, ProcessCommand, ProcessOptions, ProcessOutput, Prompt, RepositoryStatus,
SettingsTarget, StatusItem,
};
use parking_lot::{Mutex, RwLock};
use std::collections::{BTreeMap, BTreeSet, HashMap};
@@ -327,6 +328,14 @@ fn network_error(error: reqwest::Error) -> HostError {
HostError::Failed(ide_http::client::describe(&error))
}
fn response_headers(response: &reqwest::Response) -> Vec<(String, String)> {
response
.headers()
.iter()
.map(|(k, v)| (k.as_str().to_owned(), String::from_utf8_lossy(v.as_bytes()).into_owned()))
.collect()
}
fn redirect_capability(from: &reqwest::Url, to: &reqwest::Url) -> Result<Capability, String> {
if from.scheme() == "https" && to.scheme() == "http" {
ide_plugin::net_host(to.as_str()).map(Capability::NetHttp)
@@ -737,6 +746,7 @@ pub(super) struct Shared {
processes: Mutex<HashMap<(String, u64), Arc<Proc>>>,
next_process: AtomicU64,
connections: super::ipc::Connections,
http_streams: super::http_stream::HttpStreams,
pub loopbacks: RwLock<Arc<dyn super::auth::Service>>,
process_shutdowns: Mutex<Vec<std::thread::JoinHandle<()>>>,
pub(super) prompts: Mutex<HashMap<u64, PromptEntry>>,
@@ -850,6 +860,7 @@ impl Shared {
processes: Mutex::default(),
next_process: AtomicU64::new(1),
connections: super::ipc::Connections::default(),
http_streams: super::http_stream::HttpStreams::default(),
loopbacks: RwLock::new(Arc::new(super::auth::Loopbacks::default())),
process_shutdowns: Mutex::default(),
prompts: Mutex::default(),
@@ -1078,6 +1089,7 @@ impl Shared {
self.kill_processes(plugin);
self.connections.clear(plugin);
self.http_streams.clear(plugin);
self.websockets.disconnect_plugin(plugin);
self.setting_snapshots.lock().retain(|(_, p), _| p != plugin);
let channels: Vec<_> = {
@@ -1365,6 +1377,47 @@ impl PluginApi {
self.approved_program_in_project(program, None)
}
/// `request` with its secrets filled in and a redirect policy that checks
/// every hop against its grants; the caller sets the timeout.
fn http_request(&self, request: HttpRequest) -> Result<reqwest::RequestBuilder, HostError> {
let secrets = self.shared.secrets.read().clone();
let id = self.id().to_owned();
let mut headers = reqwest::header::HeaderMap::new();
for (name, value) in &request.headers {
let value = fill_secrets(value, |n| secrets.get(&id, n))?;
let name = reqwest::header::HeaderName::from_bytes(name.as_bytes())
.map_err(|e| HostError::Invalid(format!("header {name:?}: {e}")))?;
let mut value = reqwest::header::HeaderValue::from_str(&value)
.map_err(|e| HostError::Invalid(format!("header {name}: {e}")))?;
value.set_sensitive(true);
headers.append(name, value);
}
let method = reqwest::Method::from_bytes(request.method.to_ascii_uppercase().as_bytes())
.map_err(|_| HostError::Invalid(format!("method {:?}", request.method)))?;
let grants = request.grants.clone();
let policy = reqwest::redirect::Policy::custom(move |attempt| {
if attempt.previous().len() >= 10 {
return attempt.error("too many redirects");
}
let wanted = attempt.previous().last().map_or_else(
|| ide_plugin::net_capability(attempt.url().as_str()),
|from| redirect_capability(from, attempt.url()),
);
match wanted {
Ok(wanted) if grants.iter().any(|g| g.covers(&wanted)) => attempt.follow(),
Ok(wanted) => attempt.error(RedirectDenied(wanted.to_string())),
Err(error) => attempt.error(error),
}
});
let client = ide_http::client::build_with_redirect(&ide_core::proxy_settings::proxy(), policy)
.map_err(|e| HostError::Failed(e.message))?;
let builder = client.request(method, &request.url).headers(headers);
Ok(match request.body {
Some(body) => builder.body(body),
None => builder,
})
}
pub(super) fn approved_program_in_project(&self, program: &str, root: Option<&Path>) -> Result<PathBuf, HostError> {
if let Some(pin) = root.and_then(|root| {
self.shared.project_pins.read().get(&(self.id().into(), format!("process:{program}"), root.into())).cloned()
@@ -1990,8 +2043,14 @@ impl HostApi for PluginApi {
fn open_editors(&self, client: &str) -> Result<Vec<ide_plugin::OpenEditor>, HostError> {
self.shared.workspace().ok_or_else(|| HostError::NotFound("window project".into()))?.open_editors(client)
}
fn editor_open(&self, client: &str, path: &Path, selection: Option<ide_core::Range>) -> Result<(), HostError> {
self.shared.sink.emit(Some(client), PluginEvent::EditorOpen { path: path.into(), selection });
fn editor_open(
&self,
client: &str,
path: &Path,
selection: Option<ide_core::Range>,
as_text: bool,
) -> Result<(), HostError> {
self.shared.sink.emit(Some(client), PluginEvent::EditorOpen { path: path.into(), selection, as_text });
Ok(())
}
fn editor_ranges(
@@ -2450,6 +2509,31 @@ impl HostApi for PluginApi {
Ok(())
}
fn open_settings(&self, client: Option<&str>, target: SettingsTarget) -> Result<(), HostError> {
let client = from_window(client, "open Settings")?;
let (page, permissions) = match target {
SettingsTarget::Permissions => (None, true),
SettingsTarget::Page(page) => {
let decls = self.shared.ui.items(super::ui_points::SETTINGS, Some(self.id()));
let Some(decl) = decls.first().map(|i| &i.decl) else {
return Err(HostError::NotFound("the plugin declares no [contributes.settings]".into()));
};
if let Some(page) = &page {
let pages = decl.get("pages").and_then(|p| p.as_array());
if !pages.is_some_and(|ps| ps.iter().any(|p| p.get("id").and_then(|id| id.as_str()) == Some(page)))
{
return Err(HostError::NotFound(format!("the plugin declares no settings page {page:?}")));
}
}
(page, false)
}
};
self.shared
.sink
.emit(Some(client), PluginEvent::OpenSettings { plugin_id: self.id().to_owned(), page, permissions });
Ok(())
}
fn status_item(&self, id: &str, item: Option<StatusItem>) {
let key = (self.id().to_owned(), id.to_owned());
{
@@ -2813,52 +2897,14 @@ impl HostApi for PluginApi {
}
fn fetch(&self, request: HttpRequest, cancel: &CancellationToken) -> Result<HttpResponse, HostError> {
let secrets = self.shared.secrets.read().clone();
let id = self.id().to_owned();
let mut headers = reqwest::header::HeaderMap::new();
for (name, value) in &request.headers {
let value = fill_secrets(value, |n| secrets.get(&id, n))?;
let name = reqwest::header::HeaderName::from_bytes(name.as_bytes())
.map_err(|e| HostError::Invalid(format!("header {name:?}: {e}")))?;
let mut value = reqwest::header::HeaderValue::from_str(&value)
.map_err(|e| HostError::Invalid(format!("header {name}: {e}")))?;
value.set_sensitive(true);
headers.append(name, value);
}
let method = reqwest::Method::from_bytes(request.method.to_ascii_uppercase().as_bytes())
.map_err(|_| HostError::Invalid(format!("method {:?}", request.method)))?;
let grants = request.grants.clone();
let policy = reqwest::redirect::Policy::custom(move |attempt| {
if attempt.previous().len() >= 10 {
return attempt.error("too many redirects");
}
let wanted = attempt.previous().last().map_or_else(
|| ide_plugin::net_capability(attempt.url().as_str()),
|from| redirect_capability(from, attempt.url()),
);
match wanted {
Ok(wanted) if grants.iter().any(|g| g.covers(&wanted)) => attempt.follow(),
Ok(wanted) => attempt.error(RedirectDenied(wanted.to_string())),
Err(error) => attempt.error(error),
}
});
let client = ide_http::client::build_with_redirect(&ide_core::proxy_settings::proxy(), policy)
.map_err(|e| HostError::Failed(e.message))?;
let builder = client.request(method, &request.url).headers(headers).timeout(request.timeout);
let builder = match request.body {
Some(body) => builder.body(body),
None => builder,
};
let timeout = request.timeout;
let builder = self.http_request(request)?.timeout(timeout);
let cancel = cancel.clone();
net_runtime().block_on(async move {
let send = async {
let response = builder.send().await.map_err(network_error)?;
let status = response.status().as_u16();
let headers = response
.headers()
.iter()
.map(|(k, v)| (k.as_str().to_owned(), String::from_utf8_lossy(v.as_bytes()).into_owned()))
.collect();
let headers = response_headers(&response);
let mut body = Vec::new();
let mut response = response;
while let Some(chunk) = response.chunk().await.map_err(|e| HostError::Failed(e.to_string()))? {
@@ -2876,6 +2922,40 @@ impl HostApi for PluginApi {
})
}
fn fetch_stream(&self, request: HttpRequest, cancel: &CancellationToken) -> Result<HttpStreamHead, HostError> {
self.shared.http_streams.check(self.id())?;
// Only the wait for the headers is bounded: the body may keep coming.
let timeout = request.timeout;
let builder = self.http_request(request)?;
let cancel = cancel.clone();
let response = net_runtime().block_on(async move {
tokio::select! {
r = tokio::time::timeout(timeout, builder.send()) => r
.map_err(|_| HostError::Failed("timed out waiting for the response headers".into()))?
.map_err(network_error),
() = cancel.cancelled() => Err(HostError::Cancelled),
}
})?;
let status = response.status().as_u16();
let headers = response_headers(&response);
let id = self.shared.http_streams.insert(self.id(), response)?;
Ok(HttpStreamHead { id, status, headers })
}
fn http_stream_read(
&self,
id: u64,
max: usize,
timeout: Duration,
cancel: &CancellationToken,
) -> Result<(Vec<u8>, bool), HostError> {
self.shared.http_streams.read(self.id(), id, max, timeout, cancel)
}
fn http_stream_close(&self, id: u64) {
self.shared.http_streams.close(self.id(), id);
}
fn websocket_connect(
&self,
root: &Path,
+44
Переглянути файл
@@ -144,6 +144,24 @@ fn lookup_translation<'a>(catalog: &'a BTreeMap<String, String>, source: &str) -
None
}
/// Adds the plugin's own explanations (`[capabilities.reasons]`) to `capabilities`, with their
/// translations from the package's `locales/<tag>.json`.
pub fn explain_capabilities(capabilities: &mut [ide_extension::CapabilityInfo], pkg: &Package) {
let reasons = &pkg.manifest.capabilities.reasons;
if reasons.is_empty() {
return;
}
let catalogs = read_locale_catalogs(pkg);
for cap in capabilities.iter_mut() {
let Some(reason) = reasons.get(&cap.id) else { continue };
cap.reason_locales = catalogs
.iter()
.filter_map(|(tag, catalog)| Some((tag.clone(), lookup_translation(catalog, reason)?.to_owned())))
.collect();
cap.reason = Some(reason.clone());
}
}
/// Reads and validates a plugin package's Overview (`description` / `description-file`)
/// and What's New (`change-notes` / `change-notes-file`), along with their
/// per-locale translations from `locales/<tag>.json` and localized Markdown siblings.
@@ -234,6 +252,32 @@ mod tests {
assert!(docs.files.is_empty());
}
#[test]
fn capability_reasons_come_with_their_translations() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("locales")).unwrap();
std::fs::write(tmp.path().join("locales/zh-CN.json"), r#"{ "Imports a log you copied.": "导入复制的日志。" }"#)
.unwrap();
let src = "id = \"acme.docs\"\nname = \"Docs\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.19\"\n\
[capabilities]\nrequired = [\"project.read\"]\noptional = [\"clipboard.read\"]\n\
[capabilities.reasons]\n\"clipboard.read\" = \"Imports a log you copied.\"\n";
let pkg = Package::new(Manifest::parse(src).unwrap(), tmp.path().to_path_buf());
let m = &pkg.manifest;
let mut caps: Vec<_> = m
.capabilities
.all()
.map(|c| ide_extension::CapabilityInfo::new(c, m.capabilities.is_optional(c), false))
.collect();
explain_capabilities(&mut caps, &pkg);
let clipboard = caps.iter().find(|c| c.id == "clipboard.read").unwrap();
assert_eq!(clipboard.reason.as_deref(), Some("Imports a log you copied."));
assert_eq!(clipboard.reason_locales.get("zh-CN").map(String::as_str), Some("导入复制的日志。"));
// The host's own description stays.
assert_eq!(clipboard.description, ide_extension::Capability::ClipboardRead.describe());
let read = caps.iter().find(|c| c.id == "project.read").unwrap();
assert_eq!((read.reason.as_deref(), read.reason_locales.len()), (None, 0));
}
#[test]
fn markdown_files_and_localized_siblings_are_loaded_and_tracked() {
let tmp = tempfile::tempdir().unwrap();
+112
Переглянути файл
@@ -0,0 +1,112 @@
//! Plugin-owned HTTP response bodies read as they arrive (`net.fetch-stream`),
//! closed on resource drop and plugin shutdown.
use super::api::net_runtime;
use ide_core::CancellationToken;
use ide_plugin::HostError;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
/// Most response streams one plugin keeps open at once.
const MAX_STREAMS: usize = 8;
struct Body {
response: reqwest::Response,
/// The part of the last chunk the plugin hasn't read yet.
pending: Vec<u8>,
done: bool,
}
struct Stream {
body: tokio::sync::Mutex<Body>,
closed: CancellationToken,
}
#[derive(Default)]
pub(super) struct HttpStreams {
next: AtomicU64,
entries: Mutex<HashMap<(String, u64), Arc<Stream>>>,
}
impl HttpStreams {
/// Fails when `plugin` already has the most streams open.
pub fn check(&self, plugin: &str) -> Result<(), HostError> {
if self.entries.lock().keys().filter(|(p, _)| p == plugin).count() >= MAX_STREAMS {
Err(HostError::Invalid("at most eight response streams per plugin".into()))
} else {
Ok(())
}
}
pub fn insert(&self, plugin: &str, response: reqwest::Response) -> Result<u64, HostError> {
let mut entries = self.entries.lock();
if entries.keys().filter(|(p, _)| p == plugin).count() >= MAX_STREAMS {
return Err(HostError::Invalid("at most eight response streams per plugin".into()));
}
let id = self.next.fetch_add(1, Ordering::Relaxed);
let body = Body { response, pending: Vec::new(), done: false };
entries.insert(
(plugin.into(), id),
Arc::new(Stream { body: tokio::sync::Mutex::new(body), closed: CancellationToken::new() }),
);
Ok(id)
}
pub fn read(
&self,
plugin: &str,
id: u64,
max: usize,
timeout: Duration,
cancel: &CancellationToken,
) -> Result<(Vec<u8>, bool), HostError> {
let entry = self
.entries
.lock()
.get(&(plugin.into(), id))
.cloned()
.ok_or_else(|| HostError::NotFound("response stream".into()))?;
net_runtime().block_on(async {
let read = async {
let mut body = entry.body.lock().await;
// `chunk` takes nothing until it is ready, so a timeout that drops
// this future in the middle loses no bytes.
if body.pending.is_empty() && !body.done {
match body.response.chunk().await {
Ok(Some(chunk)) => body.pending = chunk.to_vec(),
Ok(None) => body.done = true,
Err(e) => return Err(HostError::Failed(ide_http::client::describe(&e))),
}
}
let count = body.pending.len().min(max);
let bytes: Vec<u8> = body.pending.drain(..count).collect();
Ok((bytes, body.done && body.pending.is_empty()))
};
tokio::select! {
biased;
() = cancel.cancelled() => Err(HostError::Cancelled),
() = entry.closed.cancelled() => Err(HostError::Cancelled),
r = read => r,
() = tokio::time::sleep(timeout) => Ok((Vec::new(), false)),
}
})
}
pub fn close(&self, plugin: &str, id: u64) {
if let Some(entry) = self.entries.lock().remove(&(plugin.into(), id)) {
entry.closed.cancel();
}
}
pub fn clear(&self, plugin: &str) {
self.entries.lock().retain(|(p, _), entry| {
if p != plugin {
return true;
}
entry.closed.cancel();
false
});
}
}
+44 -6
Переглянути файл
@@ -9,6 +9,22 @@ pub struct NavigationFiles {
pub paths: Vec<ide_core::IpcPath>,
pub indexing: bool,
pub extensions: Vec<String>,
/// In-scope files matching `extensions`; `paths` holds the first
/// `MAX_NAVIGATION_FILES` of them.
pub total: u32,
pub truncated: bool,
}
/// Discovery offers at most this many files; larger projects get navigation
/// on the first ones instead of none.
const MAX_NAVIGATION_FILES: usize = 20_000;
/// The first `limit` files `in_scope` accepts, and how many it accepts in all.
fn first_in_scope(files: Vec<PathBuf>, in_scope: impl Fn(&PathBuf) -> bool, limit: usize) -> (Vec<PathBuf>, usize) {
let mut files: Vec<_> = files.into_iter().filter(in_scope).collect();
let total = files.len();
files.truncate(limit);
(files, total)
}
#[command(trust = trusted)]
@@ -24,19 +40,25 @@ pub async fn plugin_navigation_files(
blocking(move || {
let extensions = plugins.navigation_extensions(&project.root);
if extensions.is_empty() {
return Ok(NavigationFiles { paths: vec![], indexing: false, extensions: vec![] });
return Ok(NavigationFiles {
paths: vec![],
indexing: false,
extensions: vec![],
total: 0,
truncated: false,
});
}
let indexing = project.index.status().indexing;
let files = project.index.files_with_extensions(&extensions, 20_001);
if files.len() > 20_000 {
return Err(IdeError::unavailable("plugin navigation supports up to 20,000 matching files"));
}
let files = project.index.files_with_extensions(&extensions, usize::MAX);
// A project window group's members are project scope: their files are
// in the group's index (the group root holds none of them).
let members = crate::project::workspace_member_roots(&project.root);
let in_scope = |p: &PathBuf| p.starts_with(&project.root) || members.iter().any(|m| p.starts_with(m));
let (files, total) = first_in_scope(files, in_scope, MAX_NAVIGATION_FILES);
Ok(NavigationFiles {
paths: files.into_iter().filter(in_scope).map(Into::into).collect(),
truncated: total > files.len(),
total: u32::try_from(total).unwrap_or(u32::MAX),
paths: files.into_iter().map(Into::into).collect(),
indexing,
extensions,
})
@@ -210,3 +232,19 @@ ide_command::domain!(
plugin_navigation_invalidate,
plugin_navigation_markers,
);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn discovery_keeps_the_first_in_scope_files_and_counts_them_all() {
let files: Vec<PathBuf> = (0..7).map(|i| PathBuf::from(format!("/p/{}/f{i}.xml", i % 2))).collect();
let (kept, total) = first_in_scope(files, |p| p.starts_with("/p/0"), 3);
// Out-of-scope files neither take a slot nor count toward the total.
assert_eq!(total, 4);
assert_eq!(kept, ["/p/0/f0.xml", "/p/0/f2.xml", "/p/0/f4.xml"].map(PathBuf::from));
let (kept, total) = first_in_scope(kept, |_| true, 20_000);
assert_eq!((kept.len(), total), (3, 3));
}
}
+38 -9
Переглянути файл
@@ -31,6 +31,7 @@ mod execution;
mod external_watch;
mod files_changed;
mod hover;
mod http_stream;
mod icon_extensions;
mod icon_patterns;
mod icon_settings;
@@ -66,7 +67,7 @@ mod websocket;
pub use api::{CredentialSecretStore, FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
pub use build_graph::{BuildGraph, GradleModule};
pub use docs::{MAX_PLUGIN_DOC, PluginDocs, plugin_docs};
pub use docs::{MAX_PLUGIN_DOC, PluginDocs, explain_capabilities, plugin_docs};
pub(crate) use hover::merge as merge_hover;
pub use icons::{
MAX_PLUGIN_ICON, map_asset as icon_theme_map_asset, plugin_icon, sanitize_svg, svg_prefix as icon_theme_svg_prefix,
@@ -421,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`.
@@ -540,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),
@@ -698,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()
@@ -950,6 +966,7 @@ impl PluginHost {
}
}
annotate_java_agent_vm_options(&mut capabilities, m);
explain_capabilities(&mut capabilities, &pkg);
capabilities.sort_by(|a, b| b.risk.cmp(&a.risk).then(a.id.cmp(&b.id)));
let signer_changed = self.signer_changed(&m.id, src);
let answered = |c: &CapabilityInfo| {
@@ -1811,7 +1828,12 @@ impl PluginHost {
client.as_deref(),
PluginEvent::ConsentRequested {
plugin_id: id.to_owned(),
capabilities: pending.iter().map(|c| CapabilityInfo::new(c, false, false)).collect(),
capabilities: {
let mut caps: Vec<CapabilityInfo> =
pending.iter().map(|c| CapabilityInfo::new(c, false, false)).collect();
explain_capabilities(&mut caps, &plugin.pkg);
caps
},
},
);
return Err(IdeError::new(
@@ -2765,13 +2787,12 @@ impl PluginHost {
.map(|w| format!("{} is missing; build the plugin first", w.display())),
};
let docs = plugin_docs(&pkg).unwrap_or_else(|_| PluginDocs::from_manifest(&m));
let mut capabilities: Vec<CapabilityInfo> =
m.capabilities.all().map(|c| CapabilityInfo::new(c, m.capabilities.is_optional(c), false)).collect();
explain_capabilities(&mut capabilities, &pkg);
out.push(CatalogPlugin {
has_code: m.wasm.is_some(),
capabilities: m
.capabilities
.all()
.map(|c| CapabilityInfo::new(c, m.capabilities.is_optional(c), false))
.collect(),
capabilities,
contributions: counts(&m),
id: m.id,
name: m.name,
@@ -3090,8 +3111,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);
}
@@ -3557,6 +3582,7 @@ impl PluginHost {
}
}
annotate_java_agent_vm_options(&mut capabilities, m);
explain_capabilities(&mut capabilities, &p.pkg);
// Hosts remembered through `net:ask` are grants of their own: listed
// separately so the user can revoke them one by one.
let net_hosts = grant
@@ -3718,6 +3744,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 == "*",
+5
Переглянути файл
@@ -653,6 +653,11 @@ impl PluginHost {
.collect()
}
/// Whether a usable plugin offers ghost text for `language`.
pub fn offers_inline_completion(&self, language: &str) -> bool {
!self.provider_plugins(ProviderKind::InlineCompletion, language).is_empty()
}
/// Ghost text from the first plugin that has some. Not bound by the
/// edit-path soft deadline (it may need the network) but by `cancel`:
/// the editor cancels a request as soon as the user types on.
+1
Переглянути файл
@@ -169,6 +169,7 @@ pub fn forwarded(event: &PluginEvent) -> bool {
| PluginEvent::PromptClosed { .. }
| PluginEvent::PromptWaiting { .. }
| PluginEvent::RevealView { .. }
| PluginEvent::OpenSettings { .. }
| PluginEvent::CommitRequested { .. }
| PluginEvent::ClipboardRequested { .. }
| PluginEvent::EndpointsChanged { .. }
+7 -2
Переглянути файл
@@ -277,8 +277,9 @@ pub enum PluginEvent {
/// Complete replacement of one plugin's console highlight rules (empty: none).
#[serde(rename_all = "camelCase")]
ConsoleRulesChanged { plugin_id: String, rules: Vec<ide_plugin::ConsoleRule> },
/// Open a file in the invoking window.
EditorOpen { path: ide_core::IpcPath, selection: Option<ide_core::Range> },
/// Open a file in the invoking window; `as_text` in the text editor even when a custom editor claims it.
#[serde(rename_all = "camelCase")]
EditorOpen { path: ide_core::IpcPath, selection: Option<ide_core::Range>, as_text: bool },
/// Change selection or scrolling only in this window's already open editor.
EditorRanges { path: ide_core::IpcPath, ranges: Vec<ide_core::Range>, reveal: bool },
/// A bounded output channel snapshot, or withdrawal when the plugin stops.
@@ -384,6 +385,10 @@ pub enum PluginEvent {
/// Bring the tool window of the plugin's view `view` to the front.
#[serde(rename_all = "camelCase")]
RevealView { plugin_id: String, view: String },
/// Open Settings at the plugin's own page: its settings node (`page` none), the declared
/// sub-page `page`, or (`permissions`) Settings › Plugins with its permissions in view.
#[serde(rename_all = "camelCase")]
OpenSettings { plugin_id: String, page: Option<String>, permissions: bool },
/// A command needs the window's Commit view: answer with
/// `plugin_answer_commit(request_id, …)`. Closed like a prompt (`PromptClosed`).
#[serde(rename_all = "camelCase")]
+30 -3
Переглянути файл
@@ -6,7 +6,8 @@
//! ```toml
//! [[contributes.menus]]
//! menu = "editor.context" # projectView.context, editorTab.context, tools, viewItem.context, commit.message,
//! # services.context / services.toolbar (API 1.18: the Services tree's own nodes)
//! # services.context / services.toolbar (API 1.18: the Services tree's own nodes),
//! # openIn (API 1.19: the Open In › submenu of the editor, its tab and the project view)
//! command = "check"
//! when = "editorLang == java"
//! # view = "<view id>" # required for (only allowed on) viewItem.context
@@ -116,7 +117,9 @@ const COMMIT_MESSAGE_MENU: &str = "commit.message";
/// The Services tool window's context menu and toolbar for the IDE's own nodes (run
/// configurations, Docker containers…): the command gets the selected services.
const SERVICES_MENUS: [&str; 2] = ["services.context", "services.toolbar"];
const MENU_IDS: [&str; 12] = [
/// The Open In › submenu of the editor, editor tab and project view menus: the command gets the file.
const OPEN_IN_MENU: &str = "openIn";
const MENU_IDS: [&str; 13] = [
"editor.context",
"projectView.context",
"editorTab.context",
@@ -129,6 +132,7 @@ const MENU_IDS: [&str; 12] = [
"searchResults.context",
SERVICES_MENUS[0],
SERVICES_MENUS[1],
OPEN_IN_MENU,
];
const MAX_TITLE: usize = 256;
const MAX_SETTINGS: usize = 200;
@@ -196,6 +200,9 @@ pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
if SERVICES_MENUS.contains(&d.menu.as_str()) {
pkg.manifest.needs_api(&format!("contributes.menus: {}", d.menu), 18)?;
}
if d.menu == OPEN_IN_MENU {
pkg.manifest.needs_api(&format!("contributes.menus: {OPEN_IN_MENU}"), 19)?;
}
if let Some(w) = &d.when {
validate_when(w).map_err(|e| format!("contributes.menus: {e}"))?;
}
@@ -1402,6 +1409,22 @@ mod tests {
assert!(menu(&pkg, toolbar).unwrap_err().contains("only for context menus"));
}
#[test]
fn open_in_menu_requires_api_1_19_and_takes_no_submenu() {
let pkg = |api: &str| {
let manifest = ide_extension::Manifest::parse(&format!(
"id='test'\nname='Test'\nversion='1.0.0'\nengines.openidea='{api}'\n[[contributes.commands]]\nid='show'\ntitle='Show'"
))
.unwrap();
Package::new(manifest, std::path::PathBuf::from("/unused"))
};
let decl = || toml::from_str("menu='openIn'\ncommand='show'\nwhen='editorLang == xml'").unwrap();
assert!(menu(&pkg("^1.18"), decl()).unwrap_err().contains("1.19"));
assert!(menu(&pkg("^1.19"), decl()).is_ok());
let grouped = toml::from_str("menu='openIn'\ncommand='show'\nsubmenu='BPMN'").unwrap();
assert!(menu(&pkg("^1.19"), grouped).unwrap_err().contains("only for context menus"));
}
#[test]
fn escape_bindings_need_api_1_10_and_a_when_clause() {
let pkg = |api: &str| {
@@ -1521,12 +1544,16 @@ mod tests {
#[test]
fn settings_pages_validate_manifest_files_commands_and_api() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/settings-pages");
let source = std::fs::read_to_string(root.join("plugin.toml")).unwrap();
let full = std::fs::read_to_string(root.join("plugin.toml")).unwrap();
let check = |source: &str| {
let manifest = ide_extension::Manifest::parse(source)?;
let decl = manifest.declarations(SETTINGS).into_iter().next().unwrap();
settings(&Package::new(manifest, root.clone()), decl)
};
check(&full).unwrap();
// Pages need API 1.3: without the fixture's 1.19 `[capabilities]`, that is the gate.
let (start, end) = (full.find("[capabilities]").unwrap(), full.find("[[contributes.commands]]").unwrap());
let source = format!("{}{}", &full[..start], &full[end..]).replace("^1.19", "^1.3");
let valid = check(&source).unwrap();
assert_eq!(valid.json["pages"].as_array().unwrap().len(), 2);
assert_eq!(valid.json["properties"].as_array().unwrap().len(), 3);
+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;
+31
Переглянути файл
@@ -57,6 +57,8 @@ pub struct Project {
pub(crate) java_launches: crate::ops::java::cache::Sessions,
/// Reasons this window was already told why Kotlin is debugged with kotlin-debug-adapter.
pub(crate) kotlin_debug_notices: Mutex<HashSet<&'static str>>,
/// Files each Xcode configuration's last `xcodebuild` reported problems in, by configuration id.
pub(crate) xcodebuild_problems: Arc<Mutex<HashMap<String, Vec<PathBuf>>>>,
/// The completion only some plugins asked to complete again ([`crate::ops::lsp::lsp_completion`]).
pub(crate) completion_session: Mutex<Option<crate::ops::lsp::CompletionSession>>,
/// Database tool window: data sources and their connections.
@@ -75,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.
@@ -220,6 +223,8 @@ impl Host {
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
let css_modules = ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit");
ide_sdk::apply::configure_css_modules(cfg, server_root, css_modules.as_deref());
let styled = ide_tools::managed_npm_plugin(&data_dir, "typescript-styled-plugin");
ide_sdk::apply::configure_styled(cfg, server_root, styled.as_deref());
// After the global plugins: they keep the IDE's copies.
ide_sdk::apply::configure_tsconfig_plugins(cfg, server_root, &data_dir);
let container_python = effective.languages.python.run_target().is_some();
@@ -415,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)?));
@@ -437,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();
@@ -466,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))
@@ -708,6 +717,7 @@ impl Host {
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launches: Default::default(),
kotlin_debug_notices: Mutex::default(),
xcodebuild_problems: Arc::default(),
completion_session: Mutex::default(),
db,
http_history,
@@ -715,6 +725,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),
@@ -768,6 +779,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);
@@ -779,6 +792,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);
}
@@ -874,6 +890,19 @@ impl Host {
plugin_dirs,
}
}));
let mem_settings = settings.clone();
let mem_root = root.clone();
let mem_trust = self.trust.clone();
agents.set_memory_policy_hook(Box::new(move || {
let layer = |scope| mem_settings.layer(scope).agents.memory.clone();
let workspace_trusted = mem_trust.window_trusted(&mem_root).unwrap_or(false);
ide_agent::memory::MemoryPolicy {
user: layer(ide_workspace::settings::SettingsScope::Global),
workspace: layer(ide_workspace::settings::SettingsScope::Project),
workspace_trusted,
workspace_roots: crate::ops::agent::workspace_skill_roots(&mem_root),
}
}));
agents.set_mcp_servers_hook(Box::new(move || {
crate::ops::agent::session_mcp_servers(&settings, &approvals, &secrets, &root)
}));
@@ -989,6 +1018,7 @@ impl Host {
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launches: Default::default(),
kotlin_debug_notices: Mutex::default(),
xcodebuild_problems: Arc::default(),
completion_session: Mutex::default(),
db,
http_history,
@@ -996,6 +1026,7 @@ impl Host {
notebooks,
kotlin_bridge: None,
phpstan: None,
swiftlint: None,
tsc_watch: None,
watcher: Arc::new(watcher),
content_watchers: Mutex::new(Vec::new()),
+2
Переглянути файл
@@ -375,6 +375,7 @@ pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool {
| IdeEvent::DocDiskConflict { .. }
| IdeEvent::WorkspaceEditApplied { .. }
| IdeEvent::DocLanguage { .. }
| IdeEvent::DocEncoding { .. }
| IdeEvent::Diagnostics { .. }
| IdeEvent::Task { .. }
| IdeEvent::IndexState { .. }
@@ -385,6 +386,7 @@ pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool {
| IdeEvent::LspRefresh { .. }
| IdeEvent::LspMessageRequest { .. }
| IdeEvent::LspMessageRequestDone { .. }
| IdeEvent::LspShowDocument { .. }
| IdeEvent::TerminalExited { .. }
| IdeEvent::RunExited { .. }
| IdeEvent::Debug { .. }
+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")));
}
}
+6
Переглянути файл
@@ -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) {
+3 -3
Переглянути файл
@@ -370,7 +370,7 @@ pub fn register(dispatcher: &mut Dispatcher, shell: Arc<WebShellState>) {
("window_toggle_zoom", Always),
("window_start_drag", Always),
("window_drag_files", Always),
("file_dialog_needs_gtk", Trusted),
("file_dialog_needs_gtk", Always),
("clipboard_has_files", Always),
("clipboard_has_image", Always),
] {
@@ -387,7 +387,7 @@ pub fn register(dispatcher: &mut Dispatcher, shell: Arc<WebShellState>) {
for (empty_list, trust) in [
("window_group_current", Always),
("system_font_families", Always),
("system_probe_hotkeys", Trusted),
("system_probe_hotkeys", Always),
("wsl_distros", Always),
("web_browsers", Always),
("plugin_catalog", Always),
@@ -414,7 +414,7 @@ pub fn register(dispatcher: &mut Dispatcher, shell: Arc<WebShellState>) {
});
// Caches & LSP & Web & Workspace & HTTP helpers already available through ide-host dependencies.
dispatcher.add("caches_local_data_info", TrustClass::Trusted, |c| async move {
dispatcher.add("caches_local_data_info", TrustClass::Always, |c| async move {
let current = c.host.local_data_dir.to_string_lossy().into_owned();
Ok(LocalDataInfo {
default_dir: current.clone(),
+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);
}
}
+176 -3
Переглянути файл
@@ -1166,8 +1166,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 +1221,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;
@@ -1744,3 +1751,169 @@ async fn a_run_started_without_confirmation_works_in_a_background_project_and_ho
let loaded = h.host.mcp_background.snapshot(&h.host, std::time::Instant::now()).remove(0);
assert_eq!(loaded.kept_open_by, None, "the call is over and the run has exited");
}
#[tokio::test(flavor = "multi_thread")]
async fn debugger_tools_are_registered_with_their_expected_metadata() {
let h = Harness::new();
h.trust().await;
let tools = Registry::new(h.host.clone()).tools(&h.root).unwrap();
let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
for name in [
"xdebug_get_debugger_status",
"xdebug_start_debugger_session",
"xdebug_control_session",
"xdebug_list_breakpoints",
"xdebug_set_breakpoint",
"xdebug_remove_breakpoint",
"xdebug_run_to_line",
"xdebug_get_threads",
"xdebug_get_stack",
"xdebug_get_frame_values",
"xdebug_get_value_by_path",
"xdebug_evaluate_expression",
"xdebug_set_variable",
] {
assert!(names.contains(&name), "{name} is not registered");
}
let status = tools.iter().find(|t| t.name == "xdebug_get_debugger_status").unwrap();
assert!(status.read_only && !status.destructive);
let start = tools.iter().find(|t| t.name == "xdebug_start_debugger_session").unwrap();
assert!(!start.read_only && !start.destructive);
let control = tools.iter().find(|t| t.name == "xdebug_control_session").unwrap();
assert_eq!(control.input_schema["required"], json!(["action"]));
let set = tools.iter().find(|t| t.name == "xdebug_set_breakpoint").unwrap();
assert_eq!(set.input_schema["required"], json!([]));
}
/// Answers the debugger's breakpoint requests the way the editor does: it applies the edit to
/// its current list and mirrors it to the backend.
fn debugger_window(h: &Harness) {
use ide_core::event::McpUiRequest;
h.host.mcp_requests.set_ready("main", true);
let (host, events) = (h.host.clone(), h.events.clone());
tokio::spawn(async move {
let mut handled = std::collections::HashSet::new();
loop {
let request = events.lock().unwrap().iter().find_map(|e| match e {
IdeEvent::McpRequest { id, request }
if !handled.contains(id)
&& matches!(
request,
McpUiRequest::SetBreakpoint { .. }
| McpUiRequest::RemoveBreakpoints { .. }
| McpUiRequest::FlushBreakpoints
) =>
{
Some((*id, request.clone()))
}
_ => None,
});
let Some((id, request)) = request else {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
continue;
};
handled.insert(id);
let owner = host.owner_window("main").to_owned();
let (mut files, _, _) = host.debugger.breakpoints(&owner);
match request {
McpUiRequest::SetBreakpoint { path, breakpoint } => {
let path = PathBuf::from(path);
let line = breakpoint.line - 1;
let bps = files.entry(path).or_default();
bps.retain(|b| b.line != line);
bps.push(ide_dap::Breakpoint {
line,
condition: breakpoint.condition,
hit_condition: breakpoint.hit_condition,
log_message: breakpoint.log_message,
enabled: breakpoint.enabled,
});
bps.sort_by_key(|b| b.line);
}
McpUiRequest::RemoveBreakpoints { path, line } => match path {
Some(path) => {
if let Some(bps) = files.get_mut(&PathBuf::from(path)) {
match line {
Some(line) => bps.retain(|b| b.line != line - 1),
None => bps.clear(),
}
}
}
None => files.clear(),
},
McpUiRequest::FlushBreakpoints => {}
_ => unreachable!(),
}
host.debugger.replace_breakpoints(&owner, files).await.unwrap();
let _ = host.mcp_requests.answer("main", id, true, None);
}
});
}
#[tokio::test(flavor = "multi_thread")]
async fn debugger_status_and_session_calls_without_a_session() {
let h = Harness::new();
h.trust().await;
assert_eq!(h.json("xdebug_get_debugger_status", json!({})).await, json!({"sessions": [], "activeSessionId": null}));
let err = h.error("xdebug_control_session", json!({"action": "RESUME"})).await;
assert!(err.contains("no active debug session"), "{err}");
let err = h.error("xdebug_start_debugger_session", json!({})).await;
assert!(err.contains("Pass either configurationName or filePath + line"), "{err}");
}
#[tokio::test(flavor = "multi_thread")]
async fn debugger_breakpoints_can_be_set_listed_and_removed() {
let h = Harness::new();
h.trust().await;
debugger_window(&h);
std::fs::write(h.root.join("src/main.py"), "first\nsecond\nthird\n").unwrap();
let set =
h.json("xdebug_set_breakpoint", json!({"filePath": "src/main.py", "line": 2, "condition": "x > 1"})).await;
assert_eq!(set["id"], "line:src/main.py:2");
assert_eq!(set["line"], 2);
assert_eq!(set["lineText"], "second");
assert_eq!(set["verified"], false);
let listed = h.json("xdebug_list_breakpoints", json!({"filePath": "src/main.py"})).await;
let breakpoints = listed["breakpoints"].as_array().unwrap();
assert_eq!(breakpoints.len(), 1);
assert_eq!(breakpoints[0]["condition"], "x > 1");
assert_eq!(breakpoints[0]["enabled"], true);
// Updating one field leaves the others alone.
h.json("xdebug_set_breakpoint", json!({"breakpointId": "line:src/main.py:2", "enabled": false})).await;
let listed = h.json("xdebug_list_breakpoints", json!({"filePath": "src/main.py"})).await;
let breakpoints = listed["breakpoints"].as_array().unwrap();
assert_eq!(breakpoints[0]["condition"], "x > 1");
assert_eq!(breakpoints[0]["enabled"], false);
let removed = h.json("xdebug_remove_breakpoint", json!({"breakpointId": "line:src/main.py:2"})).await;
assert_eq!(removed["removed"], true);
assert_eq!(removed["count"], 1);
let listed = h.json("xdebug_list_breakpoints", json!({})).await;
assert_eq!(listed["breakpoints"].as_array().unwrap().len(), 0);
// Removing a missing breakpoint is idempotent.
let removed = h.json("xdebug_remove_breakpoint", json!({"breakpointId": "line:src/main.py:2"})).await;
assert_eq!(removed["removed"], false);
}
#[tokio::test(flavor = "multi_thread")]
async fn debugger_breakpoints_update_by_id_and_clear_by_file() {
let h = Harness::new();
h.trust().await;
debugger_window(&h);
std::fs::write(h.root.join("src/main.py"), "first\nsecond\nthird\n").unwrap();
h.json("xdebug_set_breakpoint", json!({"filePath": "src/main.py", "line": 1})).await;
h.json("xdebug_set_breakpoint", json!({"filePath": "src/main.py", "line": 3})).await;
let updated = h
.json(
"xdebug_set_breakpoint",
json!({"breakpointId": "line:src/main.py:3", "enabled": false, "condition": null}),
)
.await;
assert_eq!(updated["line"], 3);
let listed = h.json("xdebug_list_breakpoints", json!({"filePath": "src/main.py"})).await;
let breakpoints = listed["breakpoints"].as_array().unwrap();
assert_eq!(breakpoints.len(), 2);
assert_eq!(breakpoints[1]["enabled"], false);
assert_eq!(breakpoints[1]["condition"], Value::Null);
let removed = h.json("xdebug_remove_breakpoint", json!({"owner": "agent"})).await;
assert_eq!(removed["count"], 2);
}
+143
Переглянути файл
@@ -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]
@@ -3027,6 +3049,38 @@ fn official_ai_completion_cancels_superseded_requests() {
assert!(times[9] < Duration::from_millis(500), "{times:?}");
}
/// Installed with the optional network permission refused (it is not ticked by
/// default), a suggestion request says so in the window instead of failing silently.
#[test]
fn official_ai_completion_explains_a_refused_network_permission() {
let f = fixture(Limits::default());
f.host.install_from_dir(&official("ai-completion"), &Consent::default()).unwrap();
let (port, seen) = http_server(r#"{"choices":[{"text":"a + b\n"}]}"#, |_| Duration::ZERO);
f.run("openidea.ai-completion", "set-endpoint", Some(&format!("http://localhost:{port}"))).unwrap();
f.take_events();
let doc = ide_plugin::ProviderDocument {
path: f.project.join("src/a.rs"),
language: "rust".into(),
version: 1,
text: "let x = ".into(),
};
for _ in 0..2 {
assert!(f.host.provide_inline_completion(&doc, ide_core::Pos::new(0, 8), &Default::default()).is_none());
}
assert!(seen.lock().is_empty(), "denied before connecting");
let notices: Vec<String> = f
.take_events()
.into_iter()
.filter_map(|(_, e)| match e {
PluginEvent::Notification { level: NotificationLevel::Warning, body, .. } => Some(body),
_ => None,
})
.collect();
assert_eq!(notices.len(), 1, "once: {notices:?}");
assert!(notices[0].contains("Settings › Plugins › AI Completion"), "{notices:?}");
assert_eq!(f.status("openidea.ai-completion"), PluginStatus::Active, "not a crash");
}
/// Checkstyle: a save runs the approved `checkstyle` and publishes
/// diagnostics; quick fixes come through the code-action provider; saving
/// again cancels the check still running.
@@ -3555,6 +3609,43 @@ fn settings_actions_choose_their_layer_without_losing_the_project() {
}
}
/// API 1.19: a plugin opens Settings at its own node, one of its declared pages or its
/// permissions, in the invoking window; it can't name a page it doesn't declare. Its
/// `[capabilities.reasons]` come with the permissions, translated.
#[test]
fn plugins_open_their_own_settings_and_explain_their_permissions() {
let f = fixture(Limits::default());
let info = f.install(&sample("settings-pages"));
let net = info.capabilities.iter().find(|c| c.id == "net:api.example.com").unwrap();
assert_eq!(net.reason.as_deref(), Some("Tests a model profile against the provider's API."));
assert_eq!(net.reason_locales.get("zh-CN").map(String::as_str), Some("用服务商的 API 测试模型配置。"));
assert!(net.description.contains("api.example.com"), "the host's description stays: {}", net.description);
let opened = |f: &Fixture| {
f.take_events().into_iter().find_map(|(client, e)| match e {
PluginEvent::OpenSettings { plugin_id, page, permissions } => Some((client, plugin_id, page, permissions)),
_ => None,
})
};
f.take_events();
let main = Some("main".to_owned());
let id = "settings-pages".to_owned();
f.run("settings-pages", "open-settings", None).unwrap();
assert_eq!(opened(&f), Some((main.clone(), id.clone(), None, false)));
f.run("settings-pages", "open-settings", Some("llm")).unwrap();
assert_eq!(opened(&f), Some((main.clone(), id.clone(), Some("llm".into()), false)));
f.run("settings-pages", "open-permissions", None).unwrap();
assert_eq!(opened(&f), Some((main, id, None, true)));
let err = f.run("settings-pages", "open-settings", Some("Plugins")).unwrap_err();
assert!(err.contains("declares no settings page"), "{err}");
assert_eq!(opened(&f), None);
// Without a window there is nowhere to open it.
let no_window = Invocation { client: None, ..f.inv() };
assert!(f.host.run_command("settings-pages", "open-permissions", None, no_window).is_err());
assert_eq!(opened(&f), None);
}
/// A tree filled from a pinned program's output, and a terminal for the
/// activated entry in the invoking window, titled and sized by the plugin's
/// settings (the `jobs` fixture).
@@ -6508,6 +6599,58 @@ fn api14_denies_new_privileges_and_requires_an_invoking_window() {
assert_eq!(f.host.declared_secret("api14", "token"), None);
}
/// `net.fetch-stream`: the body is read as it arrives, so a plugin gets the
/// first server-sent event while the server is still sending (here it never
/// finishes), and a short body ends with `done`. The same grants as `fetch`.
#[test]
fn fetch_stream_reads_events_before_the_body_ends() {
use std::io::{BufRead, BufReader, Write};
let f = fixture(Limits::default());
f.host.install_from_dir(&sample("api14"), &Consent::default()).unwrap();
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
for (n, stream) in listener.incoming().flatten().enumerate() {
std::thread::spawn(move || {
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut line = String::new();
while reader.read_line(&mut line).unwrap_or(0) > 0 && line != "\r\n" {
line.clear();
}
let mut stream = stream;
let chunk = |stream: &mut std::net::TcpStream, s: &str| {
write!(stream, "{:x}\r\n{s}\r\n", s.len()).and_then(|()| stream.flush())
};
let _ = write!(
stream,
"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\n\r\n"
);
let _ = chunk(&mut stream, "data: one\n\nevent: delta\ndata: t");
if n == 0 {
// Never ends: only streaming lets the plugin see "one" in time.
std::thread::sleep(Duration::from_secs(30));
return;
}
let _ = chunk(&mut stream, "wo\n\n");
let _ = write!(stream, "0\r\n\r\n");
});
}
});
let url = format!("http://localhost:{port}/events");
let err = f.run("api14", "fetch-stream", Some(&format!("1 {url}"))).unwrap_err();
assert!(err.contains("net:localhost") && err.contains("not granted"), "{err}");
f.host.set_capability("api14", "net:localhost", true).unwrap();
let started = std::time::Instant::now();
let out = f.run("api14", "fetch-stream", Some(&format!("1 {url}"))).unwrap();
assert_eq!(out.as_deref(), Some("200|message:one"));
assert!(started.elapsed() < Duration::from_secs(10), "{:?}", started.elapsed());
let out = f.run("api14", "fetch-stream", Some(&format!("3 {url}"))).unwrap();
assert_eq!(out.as_deref(), Some("200|message:one|delta:two|done"));
}
/// `net:ask`: a first request to a host outside the manifest asks the user
/// from an invoking window ("once" allows this request, "always" remembers
/// the host, refusal and dismissal deny). Background calls are denied without
+2
Переглянути файл
@@ -12,6 +12,8 @@ pub mod exec;
pub mod history;
#[cfg(target_os = "macos")]
mod pac;
#[cfg(target_os = "macos")]
pub use pac::system_pac_route;
pub mod parse;
pub mod tunnel;
+112 -3
Переглянути файл
@@ -50,15 +50,41 @@ fn with_pac_from(
no_proxy: &str,
slot_for: impl FnOnce(String) -> Arc<ScriptSlot>,
) -> reqwest::ClientBuilder {
let Some((settings, url)) =
(!has_env_proxy).then(read_settings).flatten().and_then(|s| configured_pac(&s).map(|u| (s, u)))
else {
let Some((settings, url)) = active_pac(has_env_proxy, read_settings) else {
return builder;
};
let resolver = PacResolver::new(slot_for(url), manual_matcher(&settings, no_proxy), no_proxy);
builder.proxy(reqwest::Proxy::custom(move |url| resolver.resolve(url)))
}
fn active_pac(
has_env_proxy: bool,
read_settings: impl FnOnce() -> Option<CFRetained<CFDictionary>>,
) -> Option<(CFRetained<CFDictionary>, String)> {
(!has_env_proxy).then(read_settings).flatten().and_then(|s| configured_pac(&s).map(|u| (s, u)))
}
/// The route `with_system_pac` would give `url`, for one-shot callers such as `curl`, or `None`
/// when no PAC applies. A script still loading or failed never waits: the resolver then answers
/// with the manual proxy, i.e. the route `Matcher::from_system` gives.
pub fn system_pac_route(url: &str) -> Option<ProxyRoute> {
pac_route_from(url, env_proxy_set(), system_settings, &env_no_proxy(), ScriptSlot::shared)
}
fn pac_route_from(
url: &str,
has_env_proxy: bool,
read_settings: impl FnOnce() -> Option<CFRetained<CFDictionary>>,
no_proxy: &str,
slot_for: impl FnOnce(String) -> Arc<ScriptSlot>,
) -> Option<ProxyRoute> {
let url = reqwest::Url::parse(url).ok()?;
let (settings, pac) = active_pac(has_env_proxy, read_settings)?;
let slot = slot_for(pac);
let resolver = PacResolver::new(slot, manual_matcher(&settings, no_proxy), no_proxy);
Some(resolver.resolve(&url).map_or(ProxyRoute::Direct, ProxyRoute::Via))
}
/// Fingerprint of the active macOS PAC URL, or `None`.
pub(crate) fn system_pac_fingerprint() -> Option<String> {
(!env_proxy_set()).then(system_settings).flatten().and_then(|s| pac_fingerprint(&s))
@@ -447,6 +473,89 @@ mod tests {
}
}
/// Like `serve_pac`, but holds the answer until `gate` is set, so the script stays pending.
fn serve_gated_pac(body: String, gate: Arc<AtomicBool>) -> u16 {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut stream) = stream else { continue };
let mut reader = BufReader::new(stream.try_clone().unwrap());
loop {
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {
break;
}
}
while !gate.load(Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(5));
}
let head = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
let _ = stream.write_all(head.as_bytes());
let _ = stream.write_all(body.as_bytes());
}
});
port
}
#[test]
fn one_shot_route_keeps_the_manual_route_until_the_script_loads() {
let pac_proxy = "http://127.0.0.1:3128";
let pac_script = r#"function FindProxyForURL(url, host) {
if (host == "github.com") return "PROXY 127.0.0.1:3128";
return "DIRECT";
}"#
.to_owned();
let gate = Arc::new(AtomicBool::new(false));
let pac_url = format!("http://127.0.0.1:{}/proxy.pac", serve_gated_pac(pac_script, Arc::clone(&gate)));
let slot = ScriptSlot::new(pac_url.clone(), SCRIPT_TTL, RETRY_BACKOFF, ROUTE_TTL);
let route = |url: &str, env: bool, enabled: bool, manual: bool| {
let settings = || {
let mut entries = vec![
(
unsafe { cf::kCFNetworkProxiesProxyAutoConfigEnable },
as_cf_type(CFNumber::new_i32(i32::from(enabled))),
),
(
unsafe { cf::kCFNetworkProxiesProxyAutoConfigURLString },
as_cf_type(CFString::from_str(&pac_url)),
),
];
if manual {
entries.push((unsafe { cf::kCFNetworkProxiesHTTPSEnable }, as_cf_type(CFNumber::new_i32(1))));
entries.push((
unsafe { cf::kCFNetworkProxiesHTTPSProxy },
as_cf_type(CFString::from_str("127.0.0.1")),
));
entries.push((unsafe { cf::kCFNetworkProxiesHTTPSPort }, as_cf_type(CFNumber::new_i32(7890))));
}
Some(settings_dict(entries))
};
pac_route_from(url, env, settings, "", |_| Arc::clone(&slot))
};
let github = "https://github.com/o/r/releases/download/v1/x.zip";
let manual = Some(ProxyRoute::Via("http://127.0.0.1:7890/".into()));
// Pending: no waiting, the manual proxy main used is answered.
let started = Instant::now();
assert_eq!(route(github, false, true, true), manual);
assert!(started.elapsed() < Duration::from_secs(2), "must not wait for the script");
gate.store(true, Ordering::SeqCst);
let deadline = Instant::now() + Duration::from_secs(5);
while slot.script().is_none() {
assert!(Instant::now() < deadline, "PAC script did not finish loading in time");
std::thread::sleep(Duration::from_millis(5));
}
assert_eq!(route(github, false, true, true), Some(ProxyRoute::Via(pac_proxy.into())));
// A DIRECT answer falls through to the manual proxy as in the HTTP client, else goes direct.
assert_eq!(route("https://elsewhere.example/x", false, true, true), manual);
assert_eq!(route("https://elsewhere.example/x", false, true, false), Some(ProxyRoute::Direct));
// No PAC applies: the caller keeps its own lookup.
assert_eq!(route(github, false, false, true), None);
assert_eq!(route(github, true, true, true), None);
}
#[tokio::test]
async fn pac_file_urls_read_the_original_script() {
let dir = tempfile::tempdir().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");
+3 -1
Переглянути файл
@@ -258,7 +258,8 @@ impl ProjectIndex {
}
/// Bounded file inventory for background plugin indexers; honors the same
/// project/exclude scope as search and never walks the filesystem.
/// project/exclude scope as search, leaves VCS-ignored files out and never
/// walks the filesystem.
pub fn files_with_extensions(&self, extensions: &[String], limit: usize) -> Vec<PathBuf> {
self.shared
.data
@@ -266,6 +267,7 @@ impl ProjectIndex {
.files
.iter()
.flatten()
.filter(|f| !f.ignored)
.filter(|f| f.path.extension().and_then(|e| e.to_str()).is_some_and(|e| extensions.iter().any(|x| x == e)))
.take(limit)
.map(|f| f.path.clone())
+4 -2
Переглянути файл
@@ -421,8 +421,10 @@ mod tests {
// `pip install`: a new top-level entry changes the folder's modification time.
std::thread::sleep(Duration::from_millis(20));
write(dir.path(), "newpkg/__init__.py", "def installed_later(): pass\n");
let file = fs::File::open(dir.path()).unwrap();
file.set_modified(SystemTime::now() + Duration::from_secs(5)).ok();
// Coarse file system clocks may not move within the test; push it forward. Windows can't
// open a directory as a plain file (it needs backup semantics), and NTFS keeps fine times.
#[cfg(unix)]
fs::File::open(dir.path()).unwrap().set_modified(SystemTime::now() + Duration::from_secs(5)).ok();
let second = libraries.index(&roots, &syntax, &cancel).unwrap();
assert!(!Arc::ptr_eq(&first, &second));
assert_eq!(candidates(&second, "installed_later"), ["from newpkg import installed_later"]);
+5 -1
Переглянути файл
@@ -895,15 +895,19 @@ fn workspace_scope_excludes_state_from_scans_updates_and_cached_results() {
}
#[test]
fn plugin_inventory_respects_excludes_and_symbols_require_matching_text() {
fn plugin_inventory_respects_excludes_and_ignores_and_symbols_require_matching_text() {
let java = "package demo; interface UserMapper { void find(); }";
let f = Fixture::new(&[
("src/UserMapper.java", java),
("src/mapper.xml", "<mapper/>"),
("target/Generated.java", "class Generated {}"),
("other.txt", "ignored"),
(".gitignore", "gen/\n"),
("gen/Ignored.java", "class Ignored {}"),
]);
let index = f.open();
// Go to File lists the git-ignored file; plugin navigation leaves it out.
assert_eq!(files(&index, "Ignored"), ["gen/Ignored.java"]);
let paths = index.files_with_extensions(&["java".into(), "xml".into()], 100);
assert_eq!(paths.len(), 2);
assert!(paths.iter().all(|p| p.starts_with(f.root.join("src"))));
+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)
+7
Переглянути файл
@@ -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")),
@@ -1277,6 +1279,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"),
Loaded 100 of 811 files, more files were not shown because too many files have changed in this diff. Show more