Compare commits

...
Author SHA1 Message Date
l0ng-ai b7b97f5b79 feat(agents): drop the leading cd from command titles
Agents start most shell commands with `cd <dir> &&`, which pushes the command itself out of the row. Command titles now show only the command; when it ran in a folder other than the task's, that folder appears as a small tag before it (full path on hover). The running-command hint in a grouped run's summary uses the same title.
2026-11-25 19:41:28 +08:00
l0ng-ai 735fe5dd30 feat(agents): show task status marks in a column beside the age (#5885)
The status mark (spinner, usage-limit clock, needs-input warning, ...) moves from right after the title to a fixed slot just before the age, so marks line up across rows regardless of title length. The age gets a minimum width so the column stays put between "now", "3m" and "12d".
2026-11-25 19:37:53 +08:00
l0ng-ai 0cfd17979b fix(agents): use spacing tokens for the session asset pill gaps (#5886)
The three gaps added to Session.module.css were raw 6px values, which the spacing-scale test rejects on main; they now use --space-1-5.
2026-11-25 19:30:01 +08:00
Deng Liuanddengliu 41165bb8c0 fix(ssh): migrate legacy saved credentials at startup (#5786)
Host startup now moves legacy plaintext SSH passwords and key passphrases from
ssh-passwords.json into the OS credential store, without waiting for the next
SSH connection. When the move cannot finish, each workbench shows a sticky
warning with Retry migration and a confirmed Remove plaintext copy, which keeps
credentials already moved. A credential that cannot be saved stays for the
session and the requesting window is warned. An unreadable ssh-passwords.json
is set aside (renamed, never deleted) like the other secret files, so it no
longer blocks saving new credentials.

Co-authored-by: dengliu <[email protected]>
2026-11-25 19:27:09 +08:00
l0ng-ai 91264713e7 fix(linux): use X11 under WSLg (#5748)
Started from a WSL shell, GTK opens WSLg's Wayland display, where Mesa has no usable GPU driver for WebKitGTK and the window stays blank. Under WSL (WSL_DISTRO_NAME or WSL_INTEROP set) with an X display available, OpenIDEA now sets GDK_BACKEND=x11 before GTK starts; an explicit GDK_BACKEND is kept, and nothing changes outside WSL.

Fixes #5178
2026-11-25 18:54:43 +08:00
l0ng-ai 71a4f7cb63 fix(windows): keep the WebView profile and logs in a custom data location (#5838)
With a custom local data directory (Settings > System Settings > Caches), the WebView2 profile and the logs now move there too. On Windows both window builders pass the local data directory, so all windows share one profile; an existing EBWebView profile is moved before the first window opens (rename on the same volume, otherwise a copy that skips browser caches), and a profile already in place is never replaced. Outside macOS logs go to <local data>/logs; OPENIDEA_LOG_DIR still wins.

Fixes #5776
2026-11-25 18:53:59 +08:00
l0ng-aiandenenH dfa632cf18 fix(terminal): bundle the ConPTY runtime on Windows (#5752)
Windows builds embed Microsoft's MIT-licensed ConPTY runtime (Microsoft.Windows.Console.ConPTY 1.25.260930003, pinned and unmodified, checksums tested), because the system ConPTY on Windows 10 19045 drops alternate-screen transitions and full-screen programs leave duplicate rows in scrollback. The runtime is written to a versioned user cache and conpty.dll is preloaded from that absolute path; terminals, Run consoles and debugger launchers share the PTY factory. Older builds or a load failure keep the system ConPTY.

Fixes #2692

Co-authored-by: enenH <[email protected]>
2026-11-25 18:53:47 +08:00
l0ng-ai f1425854fb fix(linux): paste files copied in the file manager into the project view (#5834)
On Linux the project view now reads and writes the clipboard's file list: text/uri-list (Dolphin, Nautilus and most file managers) with a fallback to GNOME's x-special/gnome-copied-files, through the GTK clipboard on X11 and Wayland. Copy offers both lists and the file names as text. file:// URIs are decoded as raw bytes; other hosts and schemes are skipped.

Fixes #5737
2026-11-25 18:53:34 +08:00
l0ng-ai 752650b971 fix(windows): show the WebView2 recovery prompt reliably and let windows close (#5705)
When the WebView2 browser process exits, the recovery prompt is now a native, topmost message box on its own thread with no owner window, so it no longer depends on the main thread or the failed window. Restart falls back to restarting the process itself if the event loop doesn't act within 10 s. Once the browser has failed, closing a window destroys it without asking the page. The log records the failure reason and process description.

Fixes #5369
2026-11-25 18:53:27 +08:00
l0ng-ai d33ee53c92 fix(windows): open a project window no larger than the screen's work area (#5817)
On Windows a project window opened at the configured 1440x900 and Restore Down returned to it, which ran under the taskbar on small or scaled screens (1920x1080 at 150%). The new window's size and minimum size are now shrunk to the primary monitor's work area.

Fixes #5750
2026-11-25 18:53:21 +08:00
l0ng-ai 57eac70018 fix(agents): drop the model settings chip's removed CSS class (#5881)
The composer's dynamic overflow (#5827) removed .modelDetail from Composer.module.css, but the model settings chip still read it, which failed the CSS module check. The chip now uses .chip alone.
2026-11-25 18:52:29 +08:00
l0ng-ai 497948eeff fix(flutter): compile the Flutter tests on Windows (#5880)
The process tests that use FlutterDaemon::with_executable and ToolServer::is_stopped only run on Unix, so on Windows both helpers were dead code and the ide-flutter test build failed under -D warnings. They are now compiled only for Unix tests.
2026-11-25 18:50:59 +08:00
Vladislav Kuzmin 834846840b test(run): use the native path in the JVM JSON thread-dump assertion (#5837)
The JSON thread-dump test built its expected path with a forward slash, so it failed on Windows where the path uses backslashes. Join the file name onto the directory instead.

Co-authored-by: principalwater <[email protected]>
2026-11-25 18:47:05 +08:00
Muuandmuutot a393bcdcc2 fix(search): keep focus in the search field when clicking a Find in Files scope tab (#5868)
Clicking In Project / Module / Directory / Scope in the Find in Files popup moved focus onto the tab button. The shared Tabs strip gains a keepFocusOnClick option (mousedown no longer focuses the tab) used by the scope strip; keyboard navigation of a focused strip and Tab traversal out of the search field are unchanged.

Co-authored-by: muutot <[email protected]>
2026-11-25 18:43:30 +08:00
Muuandmuutot 08f6079316 fix(vcs): align Push dialog footer checkbox with buttons (#5876)
The Force (with lease) checkbox sat in a bare inline span (the protected-branch tooltip), so it lined up on the text baseline about 2px above the other footer controls. The wrapper is now an inline-flex box centred like its siblings.

Co-authored-by: muutot <[email protected]>
2026-11-25 18:43:20 +08:00
l0ng-ai 0db493b944 feat(project-tree): paste Java code into a folder as a class file (#5878)
Pasting text that declares a Java type into a Project view folder creates <Class>.java there, named after its first public top-level type (else its first), and opens it. Inside a Java source or test root the file declares the folder's package. An existing file is replaced only after asking. Paste is enabled while the clipboard holds such code.

Fixes #5821
2026-11-25 18:29:24 +08:00
l0ng-ai 2a90677e4f test(e2e): pick effort and context from the model settings lists (#5870)
#5806 replaced the Effort Level and Context Size radio groups with listboxes. agentCycleEffort.spec.ts still looked for radio groups, and five of its tests failed on main; they now use listbox / option.
2026-11-25 18:14:04 +08:00
l0ng-ai fed9a00dd9 fix(agents): lay out a chat row again when it loses its author header off-screen (#5869)
History loads in front of the first row shown, which carries the agent's author header. Once earlier rows arrive the header moves, but an off-screen row already marked as measured kept the height it had with the header (content-visibility: auto). Jumping through a long chat therefore changed the scroll height by one header. Rows whose data-author changes are now laid out again.

The agent e2e specs now follow #5804's defaults (turns unfolded; only reasoning and read-only calls join a run). agentScroll counts six rows per turn and folds turns only for the folded-turn test. agentMarkdown opens the latest turn's reasoning directly, finds a command as its own row, and builds its run-layout fixture from read-only calls.
2026-11-25 18:11:29 +08:00
l0ng-ai f034d96ed4 fix(ui): prevent WebKit height: 100% overflow in flex-basis dialogs (#5864) 2026-11-25 18:00:43 +08:00
l0ng-aiandCursor eead66df7d fix(agents): align session composer and asset pills with Islands style (#5863)
Co-authored-by: Cursor <[email protected]>
2026-11-25 17:50:42 +08:00
l0ng-ai 0dccfafa90 fix(ci): run language smoke when the build feature changes (#5865)
Since #5801, the frontend smoke loads src/features/build through run/store.ts, but that folder was not among the Language smoke triggers, so scripts/smoke-paths.test.ts failed on main. This adds src/features/build/** to the workflow's paths and to the Changes step's smoke pattern.
2026-11-25 17:50:00 +08:00
guiqingle520 6fba7e9424 fix(maven): skip help:effective-pom during offline sync without cached help plugin (#5856)
Offline sync named the pinned maven-help-plugin 3.5.1 when the local repository held no 3.x maven-help-plugin. Repositories filled by ordinary builds often lack it, so mvn -o failed with a plugin resolution error before dependency:tree could run.

Offline without a cached 3.x maven-help-plugin, the sync now runs only dependency:tree -Dverbose. The effective-POM consumers already fall back to the static POM model when the file is missing.

Closes #5844

Co-authored-by: guiqingle520 <[email protected]>
2026-11-25 17:40:34 +08:00
l0ng-ai 475e35281b fix(run): apply a plugin's JetBrains-only JVM options when the configuration runs a bare java (#5860)
The jdk filter of a plugin's javaAgents.vmOptions looked at the configuration's command before the project's JDK was resolved. A bare java, which generated configurations use, never matched jdk = "jetbrains", so those options were dropped.

Local runs now add agents after the project settings and run-command resolution. A bare java is resolved the way the launch finds it: the run's PATH in its working directory. When the java found there is not a JDK launcher, such as the macOS stub, JAVA_HOME is used instead. Runs on a target keep the existing notice.

Fixes #5807
2026-11-25 17:39:26 +08:00
LU XIANGRUIandwildcatDownstairs 387670573f feat(flutter): add the Flutter Widget Preview tool window (#5843)
Flutter projects get a Flutter Widget Preview tool window that shows the project's @Preview widgets and updates them as files are saved. The first time the window opens, it runs flutter widget-preview start --machine --web-server in the project root, passing the project's DevTools server for the preview inspector. It then embeds the page reported by widget_preview.started on 127.0.0.1, in the IDE's light or dark theme.

The server stops when the project closes or loses trust, and it is killed with the app. Refresh reloads the page, or restarts a server that exited or failed. An older flutter without widget-preview reports that Flutter 3.38 or later is needed. Remote windows say it is not available yet.

DevTools and Widget Preview now share one ToolServer, which starts, waits for and stops these processes. Both take the configured Flutter SDK (dart / flutter) before the search path.

Related to #4096.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 17:34:48 +08:00
LU XIANGRUIandwildcatDownstairs 48aac102e1 feat(run): hot reload and DevTools for Flutter apps started by Run (#5839)
Flutter apps started with Run now run through flutter run --machine. Hot Reload and Hot Restart send app.restart requests with the app's id instead of typing r / R into the process. The buttons are enabled once the app reports app.started and supportsRestart.

The JSON protocol on stdout is decoded into plain console lines (app.log, progress, daemon messages, failed restarts). Lines outside the protocol show unchanged, and these runs never go through a terminal emulator.

Run-mode apps are kept in a workbench store, so the Flutter Inspector, DevTools and Extensions windows connect to them through the wsUri of app.debugPort, the same way they connect to Debug sessions. The Inspector lists Debug and Run apps together.

Part of #4096.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 17:29:13 +08:00
faysouandfaysou 2d7353e39f perf(tree): keep virtual rows painted while switching panes and scrolling (#5850)
Hiding a tool window reset the tree's measured viewport, so switching panes could briefly blank a populated tree. Large wheel jumps could also paint the new offset before the virtualizer mounted its rows.

Trees now keep their last viewport and offset while hidden. They scroll wheel jumps in the same event that updates the virtual rows, and they use the DOM scrollbar that already serves the commit list. Tool window content is no longer recreated on every frame re-render.

Co-authored-by: faysou <[email protected]>
2026-11-25 17:26:33 +08:00
faysouandfaysou 912da2551b fix(project-tree): restore folders faster and expand selected subtrees (#5851)
Restoring many open folders rebuilt the tree model for every directory reply. Replies that arrive in the same frame are now applied in one update, so deep files appear sooner.

The Project view header's Expand All becomes Expand Selected. It opens each selected subtree as its folders load, and stays disabled without a visible selection. Collapse All now also closes the root rows and cancels a queued expansion. Expand All remains available as an action.

Co-authored-by: faysou <[email protected]>
2026-11-25 17:20:57 +08:00
l0ng-ai 06bd43e46f fix(agents): optically center the full-page New Task prompt (#5849) 2026-11-25 17:20:44 +08:00
l0ng-ai b9a5b8d90b fix(color-scheme): import the default Interface name as TypeScript's interface colour (#5852)
DEFAULT_INTERFACE_NAME only targeted Class name, where JS.CLASS outranks it, so a scheme without JS./TS. interface keys lost its interface colour on import. It now also colours JavaScript and TypeScript › Interface name as its fallback; an explicit JS./TS.INTERFACE still wins.

Fixes #5619
2026-11-25 17:13:15 +08:00
l0ng-ai 92917d1c26 fix(index): give the indexing threads a 32 MiB stack (#5848)
Indexing a large project crashed the IDE on Windows with a stack overflow (0xc00000fd) during the initial scan: parsing and outlining a deeply nested file recurse as deep as it nests, and the index pool and worker thread ran on Rust's default 2 MiB stack. Both now reserve 32 MiB; only touched pages are committed.

Fixes #5739
2026-11-25 17:11:44 +08:00
l0ng-ai 4f0ab6c968 fix(debugger): bound the debug console's output backlog under a log flood (#5847)
Debug output arriving faster than the console parsed it piled up in the per-frame queue, and each frame re-measured the widest line of all 50,000 lines because the growing last line is replaced by a copy. Pending output is now capped at 4 MiB per session (oldest whole lines first), the widest-line measure resumes by line id, lines over 8,000 characters are broken up as in the Run console, and dropped lines are counted and shown as "N earlier lines were discarded".

Fixes #5769
2026-11-25 17:09:51 +08:00
LU XIANGRUIandwildcatDownstairs 43fdb0aba7 feat(flutter): add a Flutter SDK setting for the Dart server, debugger, runs and devices (#5831)
Settings › Languages & Frameworks › Flutter › Flutter SDK path chooses the SDK whose flutter and Dart the Dart language server, the debugger, run configurations, pub commands, the device list (flutter daemon) and DevTools use; empty keeps PATH. The page shows flutter --version --machine for the chosen SDK and lists detected SDKs (PATH, ~/flutter, ~/development/flutter, ~/sdk/flutter, fvm). Changing it restarts the daemon and stops DevTools.

Part of #4096.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 17:05:12 +08:00
l0ng-aiandCursor d65d58a4e8 feat(agents): polish session status meters with context ring and grouped limits (#5840)
* feat(agents): polish session status meters with context ring, grouped limits, and severity tones

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

* chore(i18n): update text catalogs for status meters and removed work time

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

---------

Co-authored-by: Cursor <[email protected]>
2026-11-25 17:02:55 +08:00
l0ng-ai d3792e5667 fix(build-tools): import a Gradle build or a plain folder from Import Module from Existing Sources (#5835)
Import Module from Existing Sources only accepted a directory with pom.xml. It now takes any directory: pom.xml is linked as a Maven project, a Gradle settings or build script as a Gradle build, and a folder with neither is attached as another root after asking. A folder inside the opened project is reported as already part of it.

Fixes #5781
2026-11-25 16:47:50 +08:00
l0ng-ai d0bffb5e90 fix(project-tree): ask before overwriting a dropped or pasted file with the same name (#5833)
Files dropped or pasted from outside the project were always saved under a new name when the name was taken. Each conflict now asks: Overwrite (files only; the replaced file goes to Local History), Skip, or Create Copy, optionally for the remaining conflicts. Cancelling stops the import.

Fixes #5740
2026-11-25 16:39:29 +08:00
LU XIANGRUIandwildcatDownstairs 8e26003894 feat(flutter): add the Flutter Property Editor tool window (#5823)
Flutter projects get a Flutter Property Editor tool window. With the caret in a widget constructor call in a Dart file, it lists that call's arguments (name, type, required marker, current value or the expression passed, the default as placeholder, the constructor's documentation) and edits them: text fields for String, int and double, dropdowns for bool and enums. The data comes from the Dart analysis server's dart/textDocument/editableArguments and dart/textDocument/editArgument requests; the edit comes back as workspace/applyEdit, so the editor's Undo reverts it. Values keep their type, since the server rejects 1.0 for an int parameter. Flags an older Dart SDK leaves out default to false, and isEditable to true.

Part of #4096

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 16:34:52 +08:00
guiqingle520 372d23b7e4 fix(windows): link the app with an 8 MB main-thread stack (#5830)
Windows gives the main thread a 1 MB stack by default, where macOS and Linux give 8 MB. Unoptimized debug frames overflowed it (STATUS_STACK_OVERFLOW, 0xc00000fd) after opening a Java project and clicking Settings. The MSVC build now links with /STACK:8388608, so the main thread gets the same 8 MB as elsewhere; other threads are unchanged.

Closes #5825

Co-authored-by: guiqingle520 <[email protected]>
2026-11-25 16:30:05 +08:00
RuyimgByCN dc35952cf4 feat(vcs): group Commit changes by module (#5789)
Adds View Options › Group By › Module to the Commit and Local Changes trees. Changes are grouped under the innermost module holding them: Maven and Gradle modules (named by their display name, artifactId or Gradle name), sbt projects, modules detected from build files, and attached workspace members. Files outside every module stay at the top level. Under Group By › Repository the module nodes sit inside each repository. The choice is remembered, F7 / Shift+F7 follow the grouped tree, and a module node can't be ignored as a whole. The option shows only when the project has modules.

Co-authored-by: RuyimgByCN <[email protected]>
2026-11-25 16:29:24 +08:00
RuyimgByCN 2622c9d778 feat(vcs): use Project-tree folder, module and attached-member file icons in Commit (#5816)
The Commit changes tree showed every directory with a plain folder icon and resolved file icons against the main project only. Directory rows now get the Project view's icons (source, test, resources, package, excluded, output, module, .github) from a folder presentation shared by both trees, and files of an attached workspace member resolve their test and Spring icons against that member's roots. Repository rows keep their folder icon and grey branch text.

The shared JVM package check keeps the Gradle sync and Eclipse .classpath source-set markers, so those folders keep their package icon in the Project tree.

Co-authored-by: RuyimgByCN <[email protected]>
2026-11-25 16:26:38 +08:00
l0ng-aiandCursor c878fb1edc fix(agents): keep composer toolbar on one row with dynamic overflow (#5827)
Co-authored-by: Cursor <[email protected]>
2026-11-25 16:25:22 +08:00
l0ng-ai 9ca7a297e1 fix(search): keep search history per project (#5829)
Search Everywhere history and the find / replace history shared by the
editor's find bar and Find in Files were kept in one store for every
project, so one project's class names and search strings showed up in
another project's history dropdowns.

Each project now keeps its own history, keyed by its root (IntelliJ IDEA
keeps it in the project's workspace); a window without a project keeps the
shared one. File masks stay one list for all projects, as in IDEA. Earlier
history isn't carried over, since it can't be told apart by project.

Fixes #5758
2026-11-25 16:23:06 +08:00
l0ng-ai b748a4cfbc fix(vcs): scroll the merge panes together sideways and say when every change is processed (#5828)
The merge editor's three panes followed each other only vertically: scrolling
one sideways left the other two where they were. Each pane now gives the
others its horizontal offset, telling a scroll's direction by comparing with
its last position, and ignoring the scroll events its own moves cause.

When the last change is resolved, a notice under the toolbar says that all
changes have been processed and offers Save changes and finish merging, which
writes and stages the result.

Fixes #5731
2026-11-25 16:18:31 +08:00
l0ng-ai 5be5487ac6 fix(agents): translate the per-model Default (fallback) label (#5826)
#5806 added the "Default ({fallback})" option label to the agent model
settings without catalog entries, which failed the source-text catalog test
on main. Adds it next to "Agent's default ({fallback})" in every catalog
that has that key.
2026-11-25 16:17:47 +08:00
guiqingle520 f597ae8c81 fix(project-tree): keep the error wavy underline from being clipped (#5820)
The Project view's label and label group hide overflow for the ellipsis, and the error label reserved only 2px below its text for an underline offset by 3px, so WebView2 clipped the wave into faint dots. The label group and the error label now reserve 4px above and below with a matching negative margin, which leaves the row height unchanged.

Closes #5802

Co-authored-by: guiqingle520 <[email protected]>
2026-11-25 16:11:42 +08:00
l0ng-ai eb036f2b67 fix(mcp): ask agents to read the workspace roots before their first project task (#5822)
The MCP server's instructions and get_workspace_roots only asked for the
roots when the user asked about directories or a change looked like it might
span projects. An agent that took its working directory for the whole
workspace never got there, and missed the projects attached in the IDE.

Both now say to call get_workspace_roots before the first project-related
operation in a session, and spell out what the answer means: projectRoot is
the project the connection serves and the default base for paths, roots is
the workspace scope to search and read rather than a list of projects to
change, and neither changes the agent's working directory or permissions.
The instructions also say to ask again after the user switches or attaches
a project. Clients that load tool descriptions lazily still see the rule in
the initialize instructions.

Fixes #5751
2026-11-25 16:10:45 +08:00
l0ng-ai ad95695588 fix(new-project): name a .NET project's top folder after its solution (#5819)
With "Create solution" checked and a solution name that differs from the
project name, the new project's top folder was still named after the project
(MyProject/MySolution.slnx, MyProject/MyProject/MyProject.csproj).

Generators can now give the project folder its own name with a `directory`
template; .NET uses the solution name, so the result is
MySolution/MySolution.slnx and MySolution/MyProject/MyProject.csproj. Without
a solution, or with an empty name, the folder is the project's as before. The
New Project dialog shows that folder in its path hint and checks it for an
existing non-empty folder.

Fixes #5732
2026-11-25 16:08:44 +08:00
l0ng-ai 9e6c29a7b7 fix(editor): highlight <style lang="less"> in Vue files with the Less grammar (#5818)
A Vue file's <style> block switched grammar only for lang="scss" and
lang="sass"; lang="less" was parsed as plain CSS, so Less variables,
nested rules and mixin calls lost their highlighting. It now uses
@codemirror/lang-less, which was already in the lockfile through
@codemirror/language-data and is now a direct dependency.

Fixes #5745
2026-11-25 16:03:55 +08:00
l0ng-ai 89fa6cb02c fix(maven): run the IDE's own Maven goals by plugin coordinates (#5814)
Offline, Maven resolves a plugin prefix (help:, dependency:) only from the
org.apache.maven.plugins group metadata in the local repository. A repository
filled from a private mirror often lacks it even when the plugin jar is there,
so every offline reload failed with "No plugin found for prefix 'help'".

The sync's effective POM and dependency tree, the resource and web build
probes (help:evaluate) and the single-file classpath probe
(dependency:build-classpath) now name the plugin by its coordinates: the
newest 3.x version already in the local repository the run resolves into
(-Dmaven.repo.local, then the -s settings, then the user's default), else a
pinned version. Offline with no cached dependency plugin, the tree still
falls back to the project's own version.

Fixes #5757
2026-11-25 15:57:02 +08:00
l0ng-ai 6f284741b3 fix(index): reconcile a changed folder one level deep and throttle snapshot refreshes (#5813)
A file changing at the project root put the root on the reconcile list, and the
reconcile walked it whole: every couple of seconds while a program wrote a log
there, the index re-read the entire project and rewrote its snapshot.

A reported folder the index already has files below is now listed one level
deep: its own files, plus subfolders that appeared (walked whole) or are gone
(their files dropped). Unknown folders are still walked whole. Snapshot
refreshes keep at least 10s apart; any index write drops the snapshot anyway,
so this only affects how fast the next startup is.

Fixes #5749
2026-11-25 15:51:23 +08:00
l0ng-ai 4b253d368e fix(index): don't show Indexing while a program writes its log in the project (#5812)
Every change the watcher reports queues its folder for a reconcile scan two seconds later, and every scan raised the Indexing flag and task. A debugged app writing to logs/ inside the project therefore kept Indexing in the status bar for as long as it ran. Subtree scans now run quietly and only show Indexing once they find 200 or more files to parse; full scans show it as before.

Part of #5792
2026-11-25 15:44:47 +08:00
l0ng-ai f274189c92 fix(plugins): keep the applied plugin theme over an older plugin list (#5811)
refreshPlugins' generation guard drops a list answered after a newer refresh, but not one answered after a themeChanged event. Opening a project refreshes the list while the plugin theme is being re-applied: the event set the plugin theme, then the earlier list arrived without an active theme and the editor fell back to the built-in dark theme while the menu still showed the plugin theme checked. Theme events and theme choices now go through setActivePluginTheme, which stamps them; a list requested before the latest stamp keeps the current active theme.

Fixes #5793
2026-11-25 15:42:36 +08:00
l0ng-aiandCursor 5f17748295 fix(agents): unify per-model defaults and model settings list UI (#5806)
Co-authored-by: Cursor <[email protected]>
2026-11-25 15:40:42 +08:00
l0ng-ai 2d94628d1d fix(editor): Enter in an empty find bar no longer opens a second one (#5809)
CodeMirror's findNext / replaceNext / replaceAll open its own search panel when the query is empty or invalid. The find bar's Enter, F3, arrows and Replace buttons call them, so pressing Enter before typing showed CodeMirror's panel under ours. The wrappers in cm/find.ts now do nothing without a usable query, as findPrevious already did.

Fixes #5800
2026-11-25 15:40:38 +08:00
l0ng-ai 26aabf5229 fix(project): copy absolute Windows paths with backslashes (#5808)
Copy Absolute Path returned the UI's /-separated form, so C:/work/a.md went to the clipboard and cmd, robocopy and the Explorer address bar rejected it. pathToCopy now writes absolute drive and UNC paths with backslashes (new nativePath, the inverse of ipcPath); paths relative to a content or source root keep /. The editor's Absolute Path action and Search Everywhere's Copy Path go through the same conversion.

Fixes #5805
2026-11-25 15:38:15 +08:00
l0ng-ai 87ce01d251 fix(agents): use default arrow cursors on controls and refine tool call folding (#5804)
Keep the default arrow cursor on non-link controls and disclosure summaries across src/features/agents/, reserving pointer cursors for links.

Refine conversation folding so edits, commands, and interim messages remain visible by default:
- Default agents.foldTurns (fold_turns) to false across Rust and frontend settings
- Restrict grouped ProcessRun folding to consecutive reasoning and read-only exploration tool calls (read, search, fetch, think without diffs)
- When foldTurns is enabled, fold only earlier turns (leaving the latest turn open) and flatten grouped runs inside a folded turn to avoid nested folds
- Keep turn-folding test coverage active in unit, E2E, and Rust settings tests
2026-11-25 15:12:37 +08:00
Shohruh Ismoilovandshohruh-genius 3dd918c5b2 fix(editor): fold short Go error guards and cases inline (#5633)
Go files now open with one-statement error guards (if err != nil / xxxErr != nil with the body on the next line) and one-statement case/default clauses folded onto their header line, showing the statement with its syntax colours, when the joined line fits the right margin. The syntax pass has no type information, so only conventional error names are treated as guards. Editing the hidden statement unfolds it. Code Folding gets a Short Go error guards and case clauses option (on by default) to turn it off.

Co-authored-by: shohruh-genius <[email protected]>
2026-11-25 14:52:39 +08:00
ntbang0901 9a74fe4418 feat(run): show virtual threads and their deadlocks in thread dumps (#5596)
Thread.print lists only platform threads, so Dump Threads never showed virtual threads or deadlocks between them. On Java 21+ it now also takes the JSON thread dump (Thread.dump_to_file -format=json into an owner-only directory under the heap snapshot root, read with a size cap and always removed) and lists the virtual threads in a Virtual threads (n) group by container. On Java 25 the JSON carries lock owners, so monitor deadlocks between virtual threads show in the deadlock banner; on 21-24 the viewer says lock owners need Java 25. The JSON request is skipped while a debugger holds the JVM suspended, since it would hang the attach listener until resume.

Part of #5593.

Co-authored-by: ntbang0901 <[email protected]>
2026-11-25 14:46:31 +08:00
Deng Liuanddengliu a70a0ae6f1 feat(terminal): move and drag editor terminal tabs back to Terminal (#5753)
A terminal tab moved into the editor can now return to the Terminal tool window with its running session: Move to Terminal in the editor tab menu and Find Action, or dragging the tab onto the Terminal stripe button, a terminal tab strip (at a position) or a split edge. The tab keeps its PTY, scrollback, custom name and shell; an unstarted restored tab starts a fresh session there. Also passes the action argument correctly to Move to Editor.

Co-authored-by: dengliu <[email protected]>
2026-11-25 14:36:58 +08:00
l0ng-ai 9be4803462 feat(run): stream the Java before-launch build to the status bar and Build window (#5801)
The before-launch build of a Java Run / Debug launch now streams its output, messages and progress: java_resolve_launch takes a BuildEvent channel, launches joining a shared Maven build receive its events, and the frontend shows a cancellable status bar task, the build's commands in the run console and the full output in the Build tool window.

Closes #5780
Refs #4078
2026-11-25 14:36:43 +08:00
audichuang 8122127dde perf(vcs): share a passing lane's straight Git Log graph segment between rows (#5724)
Laying out the Git Log graph built a new tracked segment for every lane in every row it passed, and CommitList lays out the whole loaded list again on each page, so wide histories paid rows x lanes allocations. A lane keeps its slot until it reaches its target, so its straight segment is identical in every row: computeGraph now builds it once per lane and reuses it (the post-passes already copy a segment before changing it). Untracked layouts and single-row lanes are unchanged.

Co-authored-by: audichuang <[email protected]>
2026-11-25 14:27:48 +08:00
audichuang cdcce048fe perf(search): pass each long-line window only the ranges that start in it (#5754)
On a line cut into windows, every window was handed all the matches left on the line and in_window reserved room for each, so the reservation added up to windows x matches: searching a 5 MB minified line asked the allocator for about 5 GiB. Each window now gets only the ranges that start in it (partition_point on the sorted ranges); in_window and the matches it returns are unchanged.

Co-authored-by: audichuang <[email protected]>
2026-11-25 14:25:10 +08:00
Shohruh Ismoilovandshohruh-genius 1cea43694e fix(editor): use existing syntax tags for Go symbols (#5797)
@lezer/go reports method declarations and selector calls as fields and leaves package names, constants and the make/new builtins untagged, so before gopls attaches they all drew in the default colour. Map them to the existing namespace, function declaration, function call, constant and builtin function tags so the colour scheme styles them as it does under semantic highlighting.

Co-authored-by: shohruh-genius <[email protected]>
2026-11-25 14:23:57 +08:00
l0ng-ai 260ac4efbf feat(agents): open a task's changes in an editor tab (#5721)
The changed-files chip under the composer opens the task's changes in an
editor tab of their own: the file tree beside one scrolling diff of every
file, with the scope, accept and rollback controls in the diff's toolbar.
The conversation keeps its layout instead of gaining a side pane.

Added and deleted files show their one side alone, and selecting a file
no longer renders every mounted diff again.
2026-11-25 14:22:30 +08:00
Deng Liuanddengliu 9805fb42b8 feat(terminal): turn existing files and folders into links on Command+hover (#5784)
Holding Cmd (Ctrl on Windows/Linux) over terminal output now underlines paths that resolve to an existing file or folder relative to the session's working directory or project root; clicking opens the file (with line:column) or selects the folder in the Project view. Results are cached per buffer write and cleared on output, scroll and buffer switches; window key listeners are removed on dispose.

Co-authored-by: dengliu <[email protected]>
2026-11-25 14:20:50 +08:00
Akbar Husain 4a18d4d205 perf(mid): resolve no-await-in-loop in five feature groups (#5774)
Clears the no-await-in-loop diagnostics in analysis, platform, project-tree, http-client and debugger and turns the rule on there. Independent directory walks (Reformat/cleanup targets, batches of 8; the result is sorted as before), Spring config reads (parsed in candidate order, so the first file with a value still wins) and Python package __init__.py creation now run in parallel; every other loop is intentionally sequential and carries a documented suppression.

Co-authored-by: akbar1214 <[email protected]>
2026-11-25 14:17:57 +08:00
Mansur Akhmadiandmansur-akhmadi 9ecef0ef0f feat(database): Diagrams › Show Diagram for the selected tables (#5779)
The Database tree gets Diagrams › Show Diagram (ShowUmlDiagram, ⌥⇧⌘U / Ctrl+Alt+Shift+U): selected tables, a schema (its tables) or a tables / views folder open as a read-only ER diagram tab with columns, PK / FK markers and the foreign keys between the shown tables. It is a Mermaid erDiagram built from the table details the tree already loads, rendered with the Markdown preview's renderer (theme colours, zoom, full screen, download). Names are written as entity codes so no character can break the source; at most 50 tables and Mermaid's 50,000-character limit, with a notification when tables are left out. The tree store now keeps the multi-selection.

Closes #5778

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 14:16:00 +08:00
LU XIANGRUIandwildcatDownstairs aec80ced53 feat(flutter): Build APK / App Bundle / iOS / Web and open the native modules (#5790)
Flutter projects get a Build › Flutter submenu first in the Build menu: Build APK, Build App Bundle, Build iOS, Build Web (flutter build <target> in the selected Flutter configuration's package, output in the Run tool window), and on macOS Open iOS/macOS Module in Xcode (running flutter build ios --config-only first when the module isn't configured) and Open Android Module in Android Studio. The submenu is a dynamic native-menu slot filled only while flutterProject holds; all six are also in Find Action. iOS builds and the Open actions are macOS only.

Part of #4096

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 14:13:23 +08:00
405 changed files with 15611 additions and 2762 deletions

No files matched your search

+2 -1
View File
@@ -23,6 +23,7 @@ on:
- "Cargo.lock"
- "src/features/run/**"
- "src/features/debugger/**"
- "src/features/build/**"
- "src/features/build-tools/**"
- "src/platform/**"
- "src/workbench/**"
@@ -105,7 +106,7 @@ jobs:
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|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-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.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|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.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
+11 -1
View File
@@ -158,7 +158,17 @@
"src/features/run/**/*.ts",
"src/features/run/**/*.tsx",
"src/features/database/**/*.ts",
"src/features/database/**/*.tsx"
"src/features/database/**/*.tsx",
"src/features/analysis/**/*.ts",
"src/features/analysis/**/*.tsx",
"src/features/project-tree/**/*.ts",
"src/features/project-tree/**/*.tsx",
"src/features/http-client/**/*.ts",
"src/features/http-client/**/*.tsx",
"src/platform/**/*.ts",
"src/platform/**/*.tsx",
"src/features/debugger/**/*.ts",
"src/features/debugger/**/*.tsx"
],
"rules": {
"no-await-in-loop": "error"
Generated
+4
View File
@@ -4252,16 +4252,20 @@ name = "ide-core"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
"dunce",
"encoding_rs",
"libc",
"portable-pty",
"serde",
"serde_json",
"sha2 0.10.9",
"specta",
"specta-typescript",
"tempfile",
"thiserror 2.0.21",
"tokio-util",
"tracing",
"windows-sys 0.61.2",
]
+8 -1
View File
@@ -6,6 +6,13 @@
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
## Microsoft ConPTY
`crates/ide-core/resources/conpty/` contains the unmodified Microsoft Windows Console
ConPTY runtime 1.25.260930003, embedded in Windows builds. Copyright (c) Microsoft
Corporation. Licensed under MIT; see its [license](crates/ide-core/resources/conpty/LICENSE)
and [package provenance](crates/ide-core/resources/conpty/README.md).
## Project Lombok
`java/lombok/lombok-1.18.48-openidea.3.jar` contains Project Lombok v1.18.48 with the Equinox
@@ -66,7 +73,7 @@ At render time `src/ui/icons.tsx` may recolour monochrome icons to `currentColor
These icons of [flutter-intellij](https://github.com/flutter/flutter-intellij) (commit `d02813ad5890`) are used
under the BSD 3-Clause License:
- `src/ui/expui/flutter/*.svg`: the DevTools tool window icons, copied unmodified from
- `src/ui/expui/flutter/*.svg`: the Flutter tool window icons, copied unmodified from
`resources/icons/expui/`.
- `src/ui/expui/flutter/[email protected]` and `[email protected]`: the Flutter outline's widget
icons, `resources/icons/custom/[email protected]` and `[email protected]`, renamed, content unmodified.
+2 -2
View File
@@ -196,11 +196,11 @@ fn levels_for_model_from_slice(options: &[AgentConfigOption]) -> Vec<AgentConfig
.filter(|o| config::is_per_model_option(o))
.cloned()
.map(|mut o| {
if config::is_context_option(&o.id) {
if config::is_context_option(&o.id) || config::is_fast_option(&o.id) {
if o.category.is_none() {
o.category = Some("model_config".into());
}
} else if o.category.as_deref() != Some("thought_level") {
} else if o.category.is_none() {
o.category = Some("thought_level".into());
}
o
+4 -3
View File
@@ -168,11 +168,12 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
assert_eq!(calls.iter().map(|(m, _)| m.as_str()).collect::<Vec<_>>(), ["initialize", "session/new"]);
assert_eq!(calls[1].1["mcpServers"], json!([]));
let cursor = mgr.providers().into_iter().find(|p| p.id == "cursor").unwrap();
let fast = cursor.config.iter().find(|o| o.id == "fast").expect("fast option");
// Per-model options (`effort`, `fast`, `context`) belong to the session's model, not provider-wide config.
assert!(!cursor.config.iter().any(|o| o.id == "fast"));
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
let fast = cursor.thought_levels["m1"].iter().find(|o| o.id == "fast").expect("fast option");
assert_eq!(fast.category.as_deref(), Some("model_config"));
assert_eq!(fast.current.as_deref(), Some("false"));
// The effort option belongs to the session's model; m2 may offer other levels.
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
assert!(cursor.thought_levels["m1"].iter().any(|o| o.category.as_deref() == Some("thought_level")));
}
+24 -6
View File
@@ -15,6 +15,8 @@ use tokio::time::Instant;
const FRESH_FOR: Duration = Duration::from_secs(15 * 60);
const COOLDOWN: Duration = Duration::from_secs(30);
/// Persisted catalog layout version; bump when option classification changes so stale per-model entries re-discover.
const CATALOG_SCHEMA: u8 = 2;
type Store = Arc<Mutex<HashMap<String, Known>>>;
type Key = (PathBuf, PathBuf, String);
@@ -80,6 +82,8 @@ impl CatalogData {
pub(crate) struct SavedCatalog {
/// An opaque cryptographic digest, never raw launch arguments or credentials.
fingerprint: String,
#[serde(default)]
schema: u8,
#[serde(flatten)]
catalog: CatalogData,
}
@@ -111,7 +115,7 @@ impl LaunchContext {
hash.update(&(value.len() as u64).to_le_bytes());
hash.update(value);
}
field(&mut hash, b"openidea-model-catalog-v1");
field(&mut hash, b"openidea-model-catalog-v2");
field(
&mut hash,
match self.spec.driver {
@@ -200,7 +204,14 @@ impl AgentCatalogs {
cache
.get(provider)
.and_then(|known| known.catalogs.get(&shared.root_key()))
.map(|saved| saved.catalog.clone())
.map(|saved| {
let mut catalog = saved.catalog.clone();
if saved.schema < CATALOG_SCHEMA {
catalog.refreshed_at_ms = None;
catalog.thought_levels.clear();
}
catalog
})
.unwrap_or_default()
}
@@ -228,7 +239,8 @@ impl AgentCatalogs {
}
drop(state);
let cache = shared.known.lock();
cache.get(provider)?.catalogs.get(&shared.root_key())?.catalog.thought_levels.get(model).cloned()
let saved = cache.get(provider)?.catalogs.get(&shared.root_key())?;
(saved.schema >= CATALOG_SCHEMA).then(|| saved.catalog.thought_levels.get(model).cloned()).flatten()
}
pub(super) async fn load_levels(
@@ -281,7 +293,7 @@ impl AgentCatalogs {
AgentModelCatalog {
provider: provider.to_owned(),
config: shared.config_for_new_task(catalog.config, provider),
thought_levels: catalog.thought_levels,
thought_levels: shared.thought_levels_for_new_task(catalog.thought_levels, provider),
refreshing: entry.flight.is_some(),
refreshed_at_ms: catalog.refreshed_at_ms,
retry_at_ms: model_failure
@@ -318,7 +330,9 @@ impl AgentCatalogs {
let generation = state.generation;
let saved =
shared.known.lock().get(&spec.id).and_then(|known| known.catalogs.get(&shared.root_key())).cloned();
let matching = saved.as_ref().is_some_and(|saved| saved.fingerprint == context.fingerprint());
let matching = saved
.as_ref()
.is_some_and(|saved| saved.schema >= CATALOG_SCHEMA && saved.fingerprint == context.fingerprint());
let age = saved
.as_ref()
.filter(|_| matching)
@@ -489,7 +503,11 @@ impl AgentCatalogs {
}
known.catalogs.insert(
shared.root_key(),
SavedCatalog { fingerprint: entry.context.fingerprint(), catalog: catalog.clone() },
SavedCatalog {
fingerprint: entry.context.fingerprint(),
schema: CATALOG_SCHEMA,
catalog: catalog.clone(),
},
);
entry.catalog = Some(catalog);
shared.persist_known(&cache);
+99 -27
View File
@@ -65,7 +65,7 @@ fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
}
/// Moves options that approve everything without asking to a value that asks: the agent's
/// default or ask mode, else its first one that asks.
/// own default (when it asks), else `default` or `ask`, else its first one that asks.
pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
for option in config {
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
@@ -73,9 +73,15 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
continue;
}
let asks = |v: &&AgentConfigValue| !bypass(&v.value);
let value = ["default", "ask"]
.iter()
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
let value = option
.default_value
.as_deref()
.and_then(|def| option.values.iter().filter(asks).find(|v| v.value == def))
.or_else(|| {
["default", "ask"]
.iter()
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
})
.or_else(|| option.values.iter().find(asks));
if let Some(value) = value {
option.current = Some(value.value.clone());
@@ -83,11 +89,26 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
}
}
/// The mode that approves everything without asking (`bypassPermissions`, `yolo`, `full-access`…), if the agent has one.
pub(crate) fn bypass_mode(options: &[AgentConfigOption]) -> Option<(&AgentConfigOption, &AgentConfigValue)> {
let option = options.iter().find(|o| o.category.as_deref() == Some("mode"))?;
let value = option.values.iter().find(|v| is_bypass_mode(&v.value))?;
Some((option, value))
/// Moves approval-bearing options (`mode`, `permissions`, `approval`) to their approving value.
pub(crate) fn apply_bypass_approvals(config: &mut [AgentConfigOption]) {
for option in config {
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
if let Some(value) = option.values.iter().find(|v| bypass(&v.value)) {
option.current = Some(value.value.clone());
}
}
}
/// Applies provider-specific defaults to per-model options for new tasks without altering `default_value`.
pub(crate) fn apply_model_defaults(provider: &str, options: &mut [AgentConfigOption]) {
if provider != "cursor" {
return;
}
if let Some(fast) = options.iter_mut().find(|o| is_fast_option(&o.id))
&& fast.values.iter().any(|v| v.value == "false")
{
fast.current = Some("false".into());
}
}
fn is_bypass_mode(mode: &str) -> bool {
@@ -126,14 +147,20 @@ pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
}
pub(crate) fn is_context_option(id: &str) -> bool {
matches!(id, "context_tier" | "contextTier")
matches!(id, "context" | "context_tier" | "contextTier")
}
pub(crate) fn is_fast_option(id: &str) -> bool {
id == "fast"
}
/// Whether an option's available values and default belong to the selected model
/// (`thought_level` and model context-tier options) rather than the provider as a whole.
/// (`thought_level`, `context_tier`, and `model_config` options like `context` and `fast`)
/// rather than the provider as a whole.
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
matches!(o.category.as_deref(), Some("thought_level" | "context_tier"))
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|| is_fast_option(&o.id)
|| is_context_option(&o.id)
}
@@ -164,7 +191,7 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
matches!(id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
.then(|| "thought_level".into())
})
.or_else(|| (id == "fast" || is_context_option(&id)).then(|| "model_config".into()))
.or_else(|| (is_fast_option(&id) || is_context_option(&id)).then(|| "model_config".into()))
}),
current,
default_value,
@@ -337,6 +364,11 @@ fn legacy(
}
}
fn clean_label(s: String, fallback: &str) -> String {
let trimmed = s.trim_matches(|c: char| c.is_whitespace() || matches!(c, '\u{200B}'..='\u{200D}' | '\u{FEFF}'));
if trimmed.is_empty() { fallback.to_owned() } else { trimmed.to_owned() }
}
fn value_of(v: &Value) -> Option<AgentConfigValue> {
let value = v.get("value")?.as_str()?.to_owned();
let meta = v.get("_meta");
@@ -352,7 +384,7 @@ fn value_of(v: &Value) -> Option<AgentConfigValue> {
.filter(|s| !s.is_empty())
.map(str::to_owned);
Some(AgentConfigValue {
name: str_of(v, "name").unwrap_or_else(|| value.clone()),
name: str_of(v, "name").map(|n| clean_label(n, &value)).unwrap_or_else(|| value.clone()),
description: str_of(v, "description"),
cost_category,
usage_multiplier,
@@ -434,19 +466,16 @@ mod tests {
]}
}));
assert!(bypass_approvals(&full_access));
assert_eq!(bypass_mode(&full_access).map(|(_, v)| v.value.as_str()), Some("full-access"));
let asking = options_of(&json!({
let mut asking = options_of(&json!({
"modes": {"currentModeId": "ask", "availableModes": [
{"id": "ask", "name": "Ask"}, {"id": "full-access", "name": "Full Access"}
]}
}));
assert!(!bypass_approvals(&asking));
assert_eq!(
bypass_mode(&asking).map(|(_, v)| v.value.as_str()),
Some("full-access"),
"the offered bypass mode stays available"
);
apply_bypass_approvals(&mut asking);
assert_eq!(asking[0].current.as_deref(), Some("full-access"));
assert!(bypass_approvals(&asking));
let permissions = |current: &str| {
options_of(&json!({"configOptions": [{
@@ -503,7 +532,7 @@ mod tests {
}
#[test]
fn effort_and_fast_categories_are_inferred_from_ids() {
fn effort_context_and_fast_are_per_model_options() {
let mut c = options_of(&json!({
"configOptions": [
{"id": "model", "type": "select", "currentValue": "gemini-4-carbon",
@@ -512,19 +541,39 @@ mod tests {
"_meta": {"copilotPriceCategory": "Medium", "copilotUsage": "1x"}}]},
{"id": "effort", "type": "select", "currentValue": "medium",
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
{"id": "context", "type": "select", "currentValue": "256k",
"options": [{"value": "256k", "name": "256K"}, {"value": "500k", "name": "500K"}]},
{"id": "contextTier", "type": "select", "currentValue": "default",
"options": [{"value": "default", "name": "200K"}, {"value": "long_context", "name": "1M"}]},
{"id": "fast", "type": "select", "currentValue": "false",
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "On"}]}
{"id": "fast", "type": "select", "currentValue": "true",
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "Fast\u{200b}\u{200b}"}]}
]
}));
assert_eq!(c.len(), 4);
assert_eq!(c.len(), 5);
assert_eq!(c[0].values[0].cost_category.as_deref(), Some("medium"));
assert_eq!(c[0].values[0].usage_multiplier.as_deref(), Some("1x"));
assert_eq!(c[1].category.as_deref(), Some("thought_level"));
assert_eq!(c[1].default_value.as_deref(), Some("medium"));
assert_eq!(c[2].category.as_deref(), Some("model_config"));
assert!(is_per_model_option(&c[1]) && is_per_model_option(&c[2]) && !is_per_model_option(&c[3]));
assert_eq!(c[3].category.as_deref(), Some("model_config"));
assert_eq!(c[4].category.as_deref(), Some("model_config"));
assert_eq!(c[4].values[1].name, "Fast");
assert!(
is_per_model_option(&c[1])
&& is_per_model_option(&c[2])
&& is_per_model_option(&c[3])
&& is_per_model_option(&c[4])
);
assert!(!is_per_model_option(&c[0]));
// Cursor defaults fast off for new tasks while preserving the agent's own default_value.
let mut cursor_opts = c.clone();
apply_model_defaults("cursor", &mut cursor_opts);
let fast = cursor_opts.iter().find(|o| o.id == "fast").unwrap();
assert_eq!((fast.current.as_deref(), fast.default_value.as_deref()), (Some("false"), Some("true")));
let mut other_opts = c.clone();
apply_model_defaults("claude", &mut other_opts);
assert_eq!(other_opts.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("true"));
// Editing effort on the same model preserves its initial `default_value` for Reset.
merge_update(
@@ -546,11 +595,34 @@ mod tests {
{"id": "model", "type": "select", "currentValue": "gpt-6-sol",
"options": [{"value": "gemini-4-carbon"}, {"value": "gpt-6-sol"}]},
{"id": "effort", "type": "select", "currentValue": "low",
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]}
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
{"id": "context", "type": "select", "currentValue": "1m",
"options": [{"value": "300k", "name": "300K"}, {"value": "1m", "name": "1M"}]}
]),
);
let effort = c.iter().find(|o| o.id == "effort").unwrap();
assert_eq!((effort.current.as_deref(), effort.default_value.as_deref()), (Some("low"), Some("low")));
let context = c.iter().find(|o| o.id == "context").unwrap();
assert_eq!((context.current.as_deref(), context.default_value.as_deref()), (Some("1m"), Some("1m")));
}
#[test]
fn apply_bypass_approvals_covers_mode_permissions_and_approval() {
let mut c = options_of(&json!({"configOptions": [
{"id": "mode", "category": "mode", "type": "select", "currentValue": "ask",
"options": [{"value": "ask"}, {"value": "full-access"}]},
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "off",
"options": [{"value": "off"}, {"value": "on"}]},
{"id": "approval", "category": "approval", "type": "select", "currentValue": "ask",
"options": [{"value": "ask"}, {"value": "bypass"}]}
]}));
apply_bypass_approvals(&mut c);
assert_eq!(ids(&c), [("mode", Some("full-access")), ("allow_all", Some("on")), ("approval", Some("bypass"))]);
// Original agent default_values stay intact.
assert_eq!(
c.iter().map(|o| o.default_value.as_deref()).collect::<Vec<_>>(),
[Some("ask"), Some("off"), Some("ask")]
);
}
#[test]
+27 -12
View File
@@ -331,19 +331,23 @@ impl Shared {
let hook = self.new_task_approvals.read().clone();
if hook.is_some_and(|ask| ask() == ide_core::settings::NewTaskApprovals::Ask) {
config::ask_for_approvals(&mut config);
return config;
}
if let Some((o, v)) = config::bypass_mode(&config).map(|(o, v)| (o.id.clone(), v.value.clone()))
&& let Some(o) = config.iter_mut().find(|c| c.id == o)
{
o.current = Some(v);
}
if let Some(o) = config.iter_mut().find(|o| o.id == config::CURSOR_APPROVAL) {
o.current = Some("bypass".into());
} else {
config::apply_bypass_approvals(&mut config);
}
config
}
pub(crate) fn thought_levels_for_new_task(
&self,
mut levels: BTreeMap<String, Vec<AgentConfigOption>>,
provider: &str,
) -> BTreeMap<String, Vec<AgentConfigOption>> {
for options in levels.values_mut() {
config::apply_model_defaults(provider, options);
}
levels
}
/// The commands the agent offered last time in this project.
fn known_commands(&self, provider: &str) -> Vec<AgentCommand> {
let cache = self.known.lock();
@@ -375,8 +379,19 @@ impl Shared {
}
}
// Discovery reads one model's options; a session on another model reports that model's.
// Restore each option's agent default so a session's manual overrides never pollute the catalog.
if acp && let Some((model, config)) = model.zip(config) {
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
let levels: Vec<_> = config
.iter()
.filter(|o| config::is_per_model_option(o))
.cloned()
.map(|mut o| {
if let Some(def) = o.default_value.clone().filter(|d| o.values.iter().any(|v| v.value == *d)) {
o.current = Some(def);
}
o
})
.collect();
if !levels.is_empty() {
self.paths.catalogs.learn_levels(self, provider, model, levels);
}
@@ -736,7 +751,7 @@ impl AgentManager {
let mut info = provider::describe(p);
let catalog = self.shared.paths.catalogs.cached(&self.shared, &p.id);
info.config = self.shared.config_for_new_task(catalog.config, &p.id);
info.thought_levels = catalog.thought_levels;
info.thought_levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &p.id);
info.commands = self.shared.known_commands(&p.id);
info
})
@@ -1059,7 +1074,7 @@ impl AgentManager {
};
// Until the session reports its own, show what the agent offered last time with the choices applied.
let catalog = self.shared.paths.catalogs.cached(&self.shared, &spec.id);
let mut levels = catalog.thought_levels;
let mut levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &spec.id);
let mut config = self.shared.config_for_new_task(catalog.config, &spec.id);
for choice in &req.config {
if let Some(o) = config.iter_mut().find(|o| o.id == choice.id) {
+4 -8
View File
@@ -3942,14 +3942,10 @@ async fn composer_commands_discover_cursor_effort_and_fast() {
assert!(calls.iter().any(|m| m.as_str() == "session/new"));
assert_eq!(calls.iter().filter(|m| m.as_str() == "initialize").count(), 1);
let cursor = mgr.providers().into_iter().find(|p| p.id == "cursor").unwrap();
assert_eq!(cursor.config.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("false"));
assert!(
cursor
.thought_levels
.values()
.next()
.is_some_and(|levels| { levels.iter().any(|o| o.category.as_deref() == Some("thought_level")) })
);
assert!(!cursor.config.iter().any(|o| o.id == "fast"));
let levels = cursor.thought_levels.values().next().expect("discovered model options");
assert_eq!(levels.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("false"));
assert!(levels.iter().any(|o| o.category.as_deref() == Some("thought_level")));
}
#[tokio::test(flavor = "multi_thread")]
+2 -1
View File
@@ -26,9 +26,10 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
let module = dunce::canonicalize(root.join(module))?;
if let Some(p) = model.maven.as_ref().and_then(|m| m.projects.iter().find(|p| root.join(&p.dir) == module)) {
let mut args = p.options.clone();
let repo = crate::maven::local_repository_for(&p.options);
args.extend([
"process-resources".into(),
"help:evaluate".into(),
crate::maven::plugin_goal("help:evaluate", repo.as_deref()),
"-Dexpression=project.build.outputDirectory".into(),
format!("-Doutput={}", manifest.display()),
]);
+30 -10
View File
@@ -965,6 +965,7 @@ pub struct LaunchBuild {
/// Compiles the module at `module` with its build system before a JVM launch and
/// returns the class directories it wrote, to put ahead of the jdtls classpath.
/// The build's console, messages and progress stream to `on_event` as it runs.
pub fn build_for_launch(
root: &Path,
model: &BuildModel,
@@ -972,8 +973,9 @@ pub fn build_for_launch(
test: bool,
kind: BuildKind,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<LaunchBuild> {
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel)?;
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel, on_event)?;
Ok(built.pop().unwrap())
}
@@ -986,9 +988,10 @@ pub fn build_for_launches(
test: bool,
kind: BuildKind,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<Vec<LaunchBuild>> {
let plan = merged_launch_plan(root, model, modules, test, kind, cancel)?;
let result = run(root, &plan, cancel, &|_| {})?;
let result = run(root, &plan, cancel, on_event)?;
let failure = if !result.success {
let errors: Vec<String> = result
.messages
@@ -1822,8 +1825,16 @@ mod tests {
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut model = reactor_model();
model.maven.as_mut().unwrap().projects[0].command = wrapper.to_string_lossy().into_owned();
let dirs = build_for_launch(root, &model, &root.join("app"), true, BuildKind::Build, &CancellationToken::new())
.unwrap();
let dirs = build_for_launch(
root,
&model,
&root.join("app"),
true,
BuildKind::Build,
&CancellationToken::new(),
&|_| {},
)
.unwrap();
assert_eq!(
dirs.class_dirs,
["app/target/test-classes", "app/target/classes", "middle/target/classes", "lib/target/classes"]
@@ -1834,16 +1845,25 @@ mod tests {
"mvnw",
"#!/bin/sh\necho '[ERROR] Kotlin compilation failed: unresolved reference broken' >&2\nexit 1\n",
);
let error =
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &CancellationToken::new())
.unwrap()
.failure
.unwrap();
let error = build_for_launch(
root,
&model,
&root.join("app"),
false,
BuildKind::Build,
&CancellationToken::new(),
&|_| {},
)
.unwrap()
.failure
.unwrap();
assert!(error.contains("Kotlin compilation failed"), "{error}");
let cancel = CancellationToken::new();
cancel.cancel();
assert_eq!(
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel).unwrap_err().kind,
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel, &|_| {})
.unwrap_err()
.kind,
ide_core::error::ErrorKind::Cancelled
);
}
+3 -1
View File
@@ -361,7 +361,9 @@ fn classpaths(
if compile_first {
args.push("compile");
}
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
let build_classpath =
maven::plugin_goal("dependency:build-classpath", maven::local_repository_for(&top.options).as_deref());
args.extend([build_classpath.as_str(), output_arg.as_str(), scope_arg.as_str(), "-q"]);
let top_dir = subdir(root, &top.dir);
let owned_args: Vec<String> = args.into_iter().map(str::to_owned).collect();
let out = process::run_bounded(&top.command, &owned_args, &top_dir, &top.env, cancel, |_, _| {}).map_err(|e| {
+71
View File
@@ -517,6 +517,59 @@ pub fn local_repository_of(settings: &Path) -> Option<PathBuf> {
Some(PathBuf::from(repo.replace("${user.home}", &home)))
}
/// The local repository a Maven run with these options resolves into: `-Dmaven.repo.local=`
/// first, then `<localRepository>` of the `-s` settings, then the user's default.
pub fn local_repository_for(options: &[String]) -> Option<PathBuf> {
if let Some(repo) = options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")) {
return Some(PathBuf::from(repo));
}
let mut args = options.iter();
while let Some(arg) = args.next() {
let path = match arg.as_str() {
"-s" | "--settings" => args.next().map(String::as_str),
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
};
if let Some(path) = path {
return local_repository_of(Path::new(path)).or_else(default_local_repo);
}
}
default_local_repo()
}
/// A goal of the IDE's own (`help:evaluate`, `dependency:build-classpath`, …) by its plugin's
/// coordinates rather than its prefix: offline, Maven resolves a prefix only from group metadata
/// in the local repository, which a repository filled from a private mirror often lacks even when
/// the plugin itself is there. Uses the newest 3.x version already in `repo`, so nothing is
/// downloaded, else a pinned one.
pub fn plugin_goal(goal: &str, repo: Option<&Path>) -> String {
let (prefix, goal) = goal.split_once(':').expect("prefix:goal");
let (artifact, pinned) = match prefix {
"help" => ("maven-help-plugin", "3.5.1"),
"dependency" => ("maven-dependency-plugin", "3.8.1"),
_ => unreachable!("not a goal of the IDE's own: {prefix}"),
};
let version = repo.and_then(|repo| newest_local_plugin(repo, artifact, 3)).unwrap_or_else(|| pinned.to_owned());
format!("org.apache.maven.plugins:{artifact}:{version}:{goal}")
}
/// The newest release of `org.apache.maven.plugins:<artifact>` whose jar is in `repo`,
/// from major version `min_major` up.
pub(crate) fn newest_local_plugin(repo: &Path, artifact: &str, min_major: u64) -> Option<String> {
let dir = repo.join("org/apache/maven/plugins").join(artifact);
let parse = |v: &str| v.split('.').map(|n| n.parse::<u64>().ok()).collect::<Option<Vec<u64>>>();
std::fs::read_dir(&dir)
.ok()?
.flatten()
.filter_map(|e| e.file_name().into_string().ok())
.filter_map(|v| parse(&v).map(|n| (n, v)))
.filter(|(n, v)| {
n.first().is_some_and(|&major| major >= min_major)
&& dir.join(v).join(format!("{artifact}-{v}.jar")).is_file()
})
.max()
.map(|(_, v)| v)
}
impl Resolver {
fn new(local_repo: Option<PathBuf>, profiles: &[String]) -> Self {
Self::new_with_jdk(local_repo, profiles, None)
@@ -2557,6 +2610,24 @@ mod tests {
assert!(local_repository_of(&tmp.path().join("missing.xml")).is_none());
}
#[test]
fn ide_goals_resolve_from_the_repository_the_run_uses() {
let tmp = tempfile::tempdir().unwrap();
let settings = tmp.path().join("settings.xml");
std::fs::write(&settings, "<settings><localRepository>/srv/m2</localRepository></settings>").unwrap();
let s = settings.to_string_lossy().into_owned();
let opts = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(local_repository_for(&opts(&["-s", &s])), Some(PathBuf::from("/srv/m2")));
assert_eq!(local_repository_for(&opts(&[&format!("--settings={s}")])), Some(PathBuf::from("/srv/m2")));
let explicit = opts(&["-s", &s, "-Dmaven.repo.local=/tmp/r"]);
assert_eq!(local_repository_for(&explicit), Some(PathBuf::from("/tmp/r")));
// No repository known: a pinned version, still by coordinates.
assert_eq!(
plugin_goal("dependency:build-classpath", None),
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:build-classpath"
);
}
#[test]
fn effective_pom_goals_come_from_the_local_repository_it_is_given() {
let tmp = tempfile::tempdir().unwrap();
+54 -36
View File
@@ -86,22 +86,37 @@ const MAVEN_CACHE_VERSION: u32 = 1;
/// `dependency:tree` of a plugin version whose `-Dverbose` lists the occurrences Maven
/// omitted (conflicts, duplicates): verbose output was dropped in 3.0 and is back since 3.2.
/// Offline, it is used only when an earlier sync downloaded it; otherwise the project's own
/// plugin version is, which may be cached instead.
/// Offline, it is used only when an earlier sync downloaded it; otherwise the newest version
/// in the local repository is.
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
const DEPENDENCY_TREE_JAR: &str =
"org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar";
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
/// `repo` is the local repository the build resolves from.
/// `repo` is the local repository the build resolves from. Both goals name their plugin by
/// coordinates: offline, a prefix resolves only from group metadata the repository may lack.
/// Offline without a cached 3.x `maven-help-plugin`, `effective-pom` is skipped so `mvn -o`
/// still resolves the dependency tree instead of failing to download the help plugin.
fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec<String> {
let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file());
vec![
"help:effective-pom".into(),
format!("-Doutput={}", effective.to_string_lossy()),
if pinned { DEPENDENCY_TREE.into() } else { "dependency:tree".into() },
"-Dverbose".into(),
]
let tree = if pinned {
DEPENDENCY_TREE.to_owned()
} else {
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2)).map_or_else(
|| "dependency:tree".to_owned(),
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
)
};
let has_help =
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3).is_some());
let mut goals = Vec::with_capacity(4);
if has_help {
goals.push(maven::plugin_goal("help:effective-pom", repo));
goals.push(format!("-Doutput={}", effective.to_string_lossy()));
}
goals.push(tree);
goals.push("-Dverbose".into());
goals
}
/// The settings' Maven options for the sync runs: the thread count (`-T`, also
@@ -367,25 +382,8 @@ pub fn sync_maven(
verbose: true,
..MavenCache::default()
};
// Where the build resolves its jars, and therefore where the plugin goals are read
// from: `-Dmaven.repo.local=` first, then `<localRepository>` of the `-s` settings,
// then the user's default repository (which `plugin()` resolves itself).
let local_repo: Option<PathBuf> =
options.maven_options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")).map(PathBuf::from).or_else(
|| {
let mut args = options.maven_options.iter();
while let Some(arg) = args.next() {
let path = match arg.as_str() {
"-s" | "--settings" => args.next().map(String::as_str),
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
};
if let Some(path) = path {
return maven::local_repository_of(Path::new(path));
}
}
None
},
);
// Where the build resolves its jars, and therefore where the plugin goals are read from.
let repo = maven::local_repository_for(&options.maven_options);
let mut errors: Vec<String> = Vec::new();
for (n, top) in model.projects.iter().filter(|p| !p.aggregated).enumerate() {
let effective = cache_dir.join(format!("effective-pom-{n}.xml"));
@@ -407,7 +405,6 @@ pub fn sync_maven(
if !options.profiles.is_empty() {
args.push(format!("-P{}", options.profiles.join(",")));
}
let repo = local_repo.clone().or_else(maven::default_local_repo);
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref()));
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
let command = options.maven_command.as_deref().unwrap_or(&top.command);
@@ -425,7 +422,7 @@ pub fn sync_maven(
}
})?;
let effective_projects = std::fs::read_to_string(&effective)
.map(|t| maven::parse_effective_pom_in(&t, local_repo.as_deref()))
.map(|t| maven::parse_effective_pom_in(&t, repo.as_deref()))
.unwrap_or_default();
let trees = maven::parse_dependency_tree(&out.text);
for (key, plugins, deps) in effective_projects {
@@ -953,11 +950,32 @@ mod tests {
#[test]
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline_without_it() {
let tmp = tempfile::tempdir().unwrap();
let online = maven_sync_goals(Path::new("e.xml"), false, None);
assert_eq!(online, ["help:effective-pom", "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom";
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()));
assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
// Offline with neither plugin cached: `effective-pom` is skipped so `mvn -o` does not fail
// on an uncached `maven-help-plugin`, and the tree falls back to the project's own version.
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline[2], "dependency:tree");
assert!(offline.contains(&"-Dverbose".to_owned()));
assert_eq!(offline, ["dependency:tree", "-Dverbose"]);
// #5757 / #5844: offline, plugins in the local repository are named by their coordinates,
// since the prefix needs group metadata a repository filled from a private mirror may lack;
// a repository with `maven-dependency-plugin` but no 3.x `maven-help-plugin` runs only the tree.
for (artifact, version) in [("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")] {
let jar =
tmp.path().join(format!("org/apache/maven/plugins/{artifact}/{version}/{artifact}-{version}.jar"));
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
std::fs::write(&jar, "").unwrap();
}
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline, ["org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree", "-Dverbose"]);
let help_jar = tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.4.0/maven-help-plugin-3.4.0.jar");
std::fs::create_dir_all(help_jar.parent().unwrap()).unwrap();
std::fs::write(&help_jar, "").unwrap();
// A version folder without its jar (only the POM was fetched) doesn't count.
std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap();
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline[0], "org.apache.maven.plugins:maven-help-plugin:3.4.0:effective-pom");
assert_eq!(offline[2], "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree");
// Downloaded by an online sync: offline keeps using it, the project's version may be missing.
let jar = tmp.path().join(DEPENDENCY_TREE_JAR);
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
@@ -1029,7 +1047,7 @@ mod tests {
let cache = tmp.path().join("cache");
sync_maven(&root, &cache, &SyncOptions::default(), &CancellationToken::new(), &|_| {}).unwrap();
let args = std::fs::read_to_string(root.join("mvnw-args")).unwrap();
assert!(args.contains("help:effective-pom"), "args: {args}");
assert!(args.contains("maven-help-plugin:"), "args: {args}");
let loaded = crate::load_linked(&root, &cache, None, &Default::default(), &Default::default());
let maven = loaded.maven.unwrap();
assert!(maven.synced_at.is_some() && maven.sync_error.is_none(), "{:?}", maven.sync_error);
@@ -1054,6 +1072,6 @@ mod tests {
let args = std::fs::read_to_string(root.join("mvnd-args")).unwrap();
// `-T1` pins the daemon serial so the dependency trees stay parseable.
assert!(args.contains("-T1"), "args: {args}");
assert!(args.contains("help:effective-pom"), "args: {args}");
assert!(args.contains("maven-help-plugin:"), "args: {args}");
}
}
+4 -7
View File
@@ -137,19 +137,16 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
// POM's effective identity first; profiles and -D options can change its GAV.
let output = cache.join("artifact-project.txt");
let mut probe = top.options.clone();
let evaluate =
crate::maven::plugin_goal("help:evaluate", crate::maven::local_repository_for(&top.options).as_deref());
probe.extend([
"-f".into(),
root.join(&p.pom).to_string_lossy().into_owned(),
"help:evaluate".into(),
evaluate.clone(),
"-Dexpression=project.id".into(),
format!("-Doutput={}", output.display()),
]);
args.extend([
"-DskipTests".into(),
"package".into(),
"help:evaluate".into(),
format!("-Doutput={}", manifest.display()),
]);
args.extend(["-DskipTests".into(), "package".into(), evaluate, format!("-Doutput={}", manifest.display())]);
return Ok(WebBuild {
command: top.command.clone(),
args,
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "ide-clipboard"
description = "The OS clipboard's file list (Explorer <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB or macOS NSPasteboard, no window or message loop"
description = "The OS clipboard's file list (file manager <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB, macOS NSPasteboard, Linux text/uri-list via GTK"
version.workspace = true
edition.workspace = true
license.workspace = true
+151 -4
View File
@@ -16,8 +16,12 @@
//! thread: AppKit and WebKit also access the general pasteboard there, and its
//! mutable type cache cannot be protected by a mutex in this crate.
//!
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
//! empty and [`set_files`] fails there.
//! Linux keeps it as `text/uri-list` (Dolphin, Nautilus and most file
//! managers) or GNOME's `x-special/gnome-copied-files` (`copy` or `cut`, then
//! one URI per line), read and written through the GTK clipboard on X11 and
//! Wayland alike; [`request_files`] reads it without blocking the main loop.
//! Other platforms are not wired up: [`files`] is empty and [`set_files`]
//! fails there.
//!
//! [`png`] reads an image (a screenshot) for the project view's Paste, which
//! saves it as a file: `public.png` or `public.tiff` on macOS, the registered
@@ -79,6 +83,7 @@ const HEADER: usize = 20;
/// The absolute paths on the clipboard, empty when it holds no file list.
/// Read failures remain errors so callers can retain an internal copy.
/// Empty on Linux, where [`request_files`] reads it.
pub fn files() -> std::io::Result<Vec<PathBuf>> {
imp::files()
}
@@ -101,7 +106,7 @@ pub fn set_files(paths: &[PathBuf]) -> bool {
/// line. An editor paste inserts names, not the absolute paths the file list
/// keeps for Explorer (#1878; IDEA's text flavor is names too). A path with no
/// file name (a root like `C:\`) keeps its whole path.
#[cfg(any(windows, target_os = "macos", test))]
#[cfg(any(windows, target_os = "macos", target_os = "linux", test))]
fn names_text(paths: &[PathBuf], separator: &str) -> String {
paths
.iter()
@@ -112,6 +117,82 @@ fn names_text(paths: &[PathBuf], separator: &str) -> String {
.join(separator)
}
/// The `file://` URIs in a `text/uri-list` or `x-special/gnome-copied-files`
/// payload as local paths: comments, the `copy`/`cut` line and URIs for other
/// hosts or schemes are skipped.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn uri_list_paths(text: &str) -> Vec<PathBuf> {
text.lines().map(str::trim).filter(|line| !line.starts_with('#')).filter_map(uri_to_path).collect()
}
/// A local `file://` URI (`file:///a%20b` or `file://localhost/a%20b`) as a
/// path; its percent-escapes are raw bytes, as GLib writes them.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn uri_to_path(uri: &str) -> Option<PathBuf> {
use std::os::unix::ffi::OsStringExt;
let rest = uri.strip_prefix("file://")?;
let path = if rest.starts_with('/') { rest } else { rest.strip_prefix("localhost")? };
let path = path.split(['?', '#']).next()?;
if !path.starts_with('/') {
return None;
}
let hex = |b: u8| (b as char).to_digit(16).map(|d| d as u8);
let bytes = path.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
let escaped =
(bytes[i] == b'%').then(|| Some((hex(*bytes.get(i + 1)?)? << 4) | hex(*bytes.get(i + 2)?)?)).flatten();
match escaped {
Some(b) => {
out.push(b);
i += 3;
}
None => {
out.push(bytes[i]);
i += 1;
}
}
}
Some(PathBuf::from(std::ffi::OsString::from_vec(out)))
}
/// `path` as a `file://` URI, every byte outside the unreserved set and `/`
/// percent-escaped.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn file_uri(path: &std::path::Path) -> String {
use std::fmt::Write;
use std::os::unix::ffi::OsStrExt;
let mut uri = String::from("file://");
for &b in path.as_os_str().as_bytes() {
if b.is_ascii_alphanumeric() || b"/-._~".contains(&b) {
uri.push(b as char);
} else {
let _ = write!(uri, "%{b:02X}");
}
}
uri
}
/// Reads the clipboard's file list without blocking: `text/uri-list` first,
/// then GNOME's list, and calls `done` with the paths (empty without a list).
/// Call on the main thread; `done` runs there later.
#[cfg(target_os = "linux")]
pub fn request_files(done: impl FnOnce(Vec<PathBuf>) + 'static) {
use gtk::gdk::{Atom, SELECTION_CLIPBOARD};
fn paths_in(data: &gtk::SelectionData) -> Vec<PathBuf> {
// A failed request has a negative length and no data.
if data.length() <= 0 { Vec::new() } else { uri_list_paths(&String::from_utf8_lossy(&data.data())) }
}
gtk::Clipboard::get(&SELECTION_CLIPBOARD).request_contents(&Atom::intern(imp::URI_LIST), move |board, data| {
let paths = paths_in(data);
if !paths.is_empty() {
return done(paths);
}
board.request_contents(&Atom::intern(imp::GNOME_COPIED), move |_, data| done(paths_in(data)));
});
}
/// `DROPFILES` for `paths`, in the wide form so names outside the ANSI code
/// page survive. Empty paths are skipped.
pub fn encode(paths: &[PathBuf]) -> Vec<u8> {
@@ -728,8 +809,25 @@ mod imp {
}
}
#[cfg(target_os = "linux")]
pub const URI_LIST: &str = "text/uri-list";
#[cfg(target_os = "linux")]
pub const GNOME_COPIED: &str = "x-special/gnome-copied-files";
pub fn has_files() -> bool {
false
#[cfg(target_os = "linux")]
{
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).wait_for_targets().is_some_and(|targets| {
targets.into_iter().any(|target| {
let name = target.name();
name == URI_LIST || name == GNOME_COPIED
})
})
}
#[cfg(not(target_os = "linux"))]
{
false
}
}
pub fn has_image() -> bool {
@@ -747,6 +845,33 @@ mod imp {
Ok(Vec::new())
}
/// Offers `paths` as `text/uri-list` (KDE and most file managers), GNOME's
/// list (Nautilus, Thunar) and their names as text, rendered on request.
#[cfg(target_os = "linux")]
pub fn set_files(paths: &[PathBuf]) -> bool {
use gtk::{TargetEntry, TargetFlags};
let uris: Vec<String> = paths.iter().map(|p| super::file_uri(p)).collect();
let uri_list: String = uris.iter().map(|uri| format!("{uri}\r\n")).collect();
let gnome = format!("copy\n{}", uris.join("\n"));
let names = super::names_text(paths, "\n");
let entry = |name: &str, info: u32| TargetEntry::new(name, TargetFlags::empty(), info);
let targets = [
entry(URI_LIST, 0),
entry(GNOME_COPIED, 1),
entry("UTF8_STRING", 2),
entry("text/plain;charset=utf-8", 2),
entry("text/plain", 2),
];
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).set_with_data(&targets, move |_, data, info| match info {
0 => data.set(&data.target(), 8, uri_list.as_bytes()),
1 => data.set(&data.target(), 8, gnome.as_bytes()),
_ => {
let _ = data.set_text(&names);
}
})
}
#[cfg(not(target_os = "linux"))]
pub fn set_files(_paths: &[PathBuf]) -> bool {
false
}
@@ -769,6 +894,28 @@ mod tests {
list.iter().map(PathBuf::from).collect()
}
#[cfg(unix)]
#[test]
fn file_manager_uri_lists_become_paths() {
// Dolphin: CRLF-separated `text/uri-list`, with a comment line.
let kde = "# copied\r\nfile:///home/u/a%20b.txt\r\nfile://localhost/home/u/%E6%A1%8C%E9%9D%A2\r\n";
assert_eq!(uri_list_paths(kde), paths(&["/home/u/a b.txt", "/home/u/桌面"]));
// Nautilus/Thunar: `copy` or `cut`, then one URI per line.
assert_eq!(uri_list_paths("cut\nfile:///tmp/x\nfile:///tmp/y"), paths(&["/tmp/x", "/tmp/y"]));
// Other hosts and schemes are not local files.
assert!(uri_list_paths("file://server/share/x\nhttps://example.com/x\nsmb:///x").is_empty());
}
#[cfg(unix)]
#[test]
fn written_uris_read_back_as_the_same_paths() {
let list = paths(&["/home/u/a b#1%.txt", "/home/u/桌面/项目", "/tmp/plain-name_1.~"]);
let uris: Vec<String> = list.iter().map(|p| file_uri(p)).collect();
assert_eq!(uris[0], "file:///home/u/a%20b%231%25.txt");
assert_eq!(uris[2], "file:///tmp/plain-name_1.~");
assert_eq!(uri_list_paths(&uris.join("\r\n")), list);
}
#[test]
fn a_written_list_reads_back_unchanged() {
let list = paths(&["C:/work/project/a.txt", "C:/work/project/sub"]);
+5 -1
View File
@@ -15,12 +15,16 @@ specta.workspace = true
specta-typescript.workspace = true
thiserror.workspace = true
tokio-util.workspace = true
portable-pty.workspace = true
[dev-dependencies]
sha2 = "0.10"
tempfile.workspace = true
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
dirs.workspace = true
tracing.workspace = true
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
+21
View File
@@ -0,0 +1,21 @@
Copyright (c) Microsoft Corporation. All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,39 @@
# Bundled Windows console host
Unmodified files from Microsoft's MIT-licensed
[Microsoft.Windows.Console.ConPTY 1.25.260930003](https://www.nuget.org/packages/Microsoft.Windows.Console.ConPTY/1.25.260930003).
The system ConPTY on Windows 10 build 19045 consumes alternate-screen transitions; xterm then
puts full-screen applications' redraws in normal scrollback. A current console host
preserves those transitions, including while resizing and updating a running TUI.
The package is pinned, checked in and embedded by `ide-core`, so desktop, server,
Run and debugger builds work offline and do not depend on another installed IDE.
Only the target architecture is embedded, along with its MIT license. `src/pty.rs`
extracts them atomically to a versioned user cache and preloads the DLL's absolute
path before portable-pty initializes.
Windows reuses that module when portable-pty loads `conpty.dll` by name. Loading
failure is logged and falls back to the system backend. Windows builds before
19041 also retain the system backend.
Source archive:
`https://api.nuget.org/v3-flatcontainer/microsoft.windows.console.conpty/1.25.260930003/microsoft.windows.console.conpty.1.25.260930003.nupkg`
Archive SHA-256: `02b07b349af66d801159bdf9e440d4a1ce78bb951f37fc8609731665afdae7ee`
For each architecture, `conpty.dll` comes from
`runtimes/win-<arch>/native/conpty.dll`, and `OpenConsole.exe` from
`build/native/runtimes/<arch>/OpenConsole.exe` in that archive. Preserve the pair and
the license when updating; update `VERSION` in `src/pty.rs` and these checksums too.
| File | SHA-256 |
| --------------------- | ------------------------------------------------------------------ |
| arm64/conpty.dll | `151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf` |
| arm64/OpenConsole.exe | `4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f` |
| x64/conpty.dll | `feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a` |
| x64/OpenConsole.exe | `3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586` |
| x86/conpty.dll | `d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93` |
| x86/OpenConsole.exe | `e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3` |
Verification: `cargo test -p ide-core pty::`. `pty::checksums` checks the embedded files against the table above on every platform. The native PTY test launches a child
console application and requires alternate-screen entry and exit to reach the
reader; a system ConPTY that consumes them fails this check.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+2
View File
@@ -201,6 +201,7 @@ pub struct FoldingSettings {
pub file_header: bool,
pub imports: bool,
pub doc_comments: bool,
pub go_short_blocks: bool,
}
impl Default for FoldingSettings {
@@ -211,6 +212,7 @@ impl Default for FoldingSettings {
file_header: true,
imports: true,
doc_comments: false,
go_short_blocks: true,
}
}
}
+1
View File
@@ -25,6 +25,7 @@ pub mod project_dir;
pub mod project_env;
pub mod project_roots;
pub mod proxy_settings;
pub mod pty;
pub mod real_path;
pub mod remote_settings;
pub mod settings;
+254
View File
@@ -0,0 +1,254 @@
//! The PTY backend shared by terminals, Run consoles and debugger launchers.
pub fn native_pty_system() -> Box<dyn portable_pty::PtySystem + Send> {
#[cfg(windows)]
windows::initialize();
portable_pty::native_pty_system()
}
#[cfg(windows)]
mod windows {
use std::fs;
use std::io::{self, Write};
use std::os::windows::ffi::OsStrExt;
use std::path::Path;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU64, Ordering};
use windows_sys::Win32::Foundation::FreeLibrary;
use windows_sys::Win32::System::LibraryLoader::{
GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
};
const VERSION: &str = "1.25.260930003";
#[cfg(target_arch = "x86_64")]
const RUNTIME: (&str, &[u8], &[u8]) = (
"x64",
include_bytes!("../resources/conpty/x64/conpty.dll"),
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
);
#[cfg(target_arch = "aarch64")]
const RUNTIME: (&str, &[u8], &[u8]) = (
"arm64",
include_bytes!("../resources/conpty/arm64/conpty.dll"),
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
);
#[cfg(target_arch = "x86")]
const RUNTIME: (&str, &[u8], &[u8]) = (
"x86",
include_bytes!("../resources/conpty/x86/conpty.dll"),
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
);
pub(super) fn initialize() -> bool {
static BUNDLED: OnceLock<bool> = OnceLock::new();
*BUNDLED.get_or_init(|| {
if !crate::platform::windows_build_number().is_some_and(|build| build >= 19041) {
return false;
}
match load() {
Ok(()) => true,
Err(error) => {
tracing::warn!(%error, "bundled ConPTY unavailable; using the system terminal backend");
false
}
}
})
}
fn load() -> io::Result<()> {
let cache = dirs::cache_dir().ok_or_else(|| io::Error::other("no user cache directory"))?;
let directory = cache.join("OpenIDEA").join("conpty").join(VERSION).join(RUNTIME.0);
fs::create_dir_all(&directory)?;
install(&directory.join("LICENSE.txt"), include_bytes!("../resources/conpty/LICENSE"))?;
install(&directory.join("OpenConsole.exe"), RUNTIME.2)?;
let library = directory.join("conpty.dll");
install(&library, RUNTIME.1)?;
let wide: Vec<u16> = library.as_os_str().encode_wide().chain(Some(0)).collect();
// portable-pty 0.9 opens conpty.dll by name. Preload our verified absolute path:
// Windows reuses this module, without adding the project directory to DLL search.
// SAFETY: the path is terminated and the module is retained for the process lifetime.
let module = unsafe {
LoadLibraryExW(
wide.as_ptr(),
std::ptr::null_mut(),
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32,
)
};
if module.is_null() {
return Err(io::Error::last_os_error());
}
for name in [c"CreatePseudoConsole", c"ResizePseudoConsole", c"ClosePseudoConsole"] {
// SAFETY: `module` is loaded and each name is a terminated export name.
if unsafe { GetProcAddress(module, name.as_ptr().cast()) }.is_none() {
// SAFETY: no PTY uses this rejected module yet; release our load reference.
unsafe { FreeLibrary(module) };
return Err(io::Error::other("bundled ConPTY lacks the portable-pty exports"));
}
}
// Keep this reference for the process lifetime, including between PTY sessions.
tracing::info!(path = %library.display(), version = VERSION, "loaded bundled ConPTY");
Ok(())
}
fn install(path: &Path, data: &[u8]) -> io::Result<()> {
if fs::read(path).is_ok_and(|existing| existing == data) {
return Ok(());
}
static NEXT: AtomicU64 = AtomicU64::new(0);
let pending =
path.with_extension(format!("{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let result = (|| {
let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&pending)?;
file.write_all(data)?;
file.sync_all()?;
drop(file);
match fs::rename(&pending, path) {
Ok(()) => Ok(()),
Err(_) if fs::read(path).is_ok_and(|existing| existing == data) => Ok(()),
Err(error) => Err(error),
}
})();
let _ = fs::remove_file(pending);
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn installs_atomically_and_repairs_incomplete_files() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("conpty.dll");
fs::write(&path, b"partial").unwrap();
std::thread::scope(|scope| {
for _ in 0..8 {
let path = &path;
scope.spawn(move || install(path, b"complete runtime").unwrap());
}
});
assert_eq!(fs::read(&path).unwrap(), b"complete runtime");
assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
}
#[test]
fn loads_the_bundled_backend() {
assert!(initialize());
}
#[test]
fn conpty_output_child() {
if std::env::var_os("OPENIDEA_CONPTY_TEST_CHILD").is_none() {
return;
}
use windows_sys::Win32::System::Console::{
ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleMode, GetStdHandle, STD_OUTPUT_HANDLE, SetConsoleMode,
};
// SAFETY: the inherited console output handle and a local writable mode word.
unsafe {
let output = GetStdHandle(STD_OUTPUT_HANDLE);
let mut mode = 0;
assert_ne!(GetConsoleMode(output, &mut mode), 0);
assert_ne!(SetConsoleMode(output, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING), 0);
}
std::io::stdout()
.write_all(b"\x1b[?1049h\x1b[2J\x1b[HWorking (3m 19s)\x1b[1;1H\x1b[2KWorking (2m 59s)\x1b[?1049l\r\nVT_DONE\r\n")
.unwrap();
std::io::stdout().flush().unwrap();
}
#[test]
fn conpty_preserves_alternate_screen_transitions() {
use std::io::Read;
use std::sync::mpsc;
use std::time::{Duration, Instant};
let pair = super::super::native_pty_system().openpty(portable_pty::PtySize::default()).unwrap();
let mut reader = pair.master.try_clone_reader().unwrap();
let mut writer = pair.master.take_writer().unwrap();
let mut command = portable_pty::CommandBuilder::new(std::env::current_exe().unwrap());
command.args(["--exact", "pty::windows::tests::conpty_output_child", "--nocapture"]);
command.env("OPENIDEA_CONPTY_TEST_CHILD", "1");
let mut child = pair.slave.spawn_command(command).unwrap();
drop(pair.slave);
let (tx, rx) = mpsc::channel();
let reading = std::thread::spawn(move || {
let mut bytes = [0; 4096];
while let Ok(count) = reader.read(&mut bytes) {
if count == 0 || tx.send(bytes[..count].to_vec()).is_err() {
break;
}
}
});
let deadline = Instant::now() + Duration::from_secs(10);
let mut output = Vec::new();
let mut cursor_replied = false;
while Instant::now() < deadline {
if let Ok(bytes) = rx.recv_timeout(Duration::from_millis(50)) {
output.extend_from_slice(&bytes);
if !cursor_replied && output.windows(4).any(|s| s == b"\x1b[6n") {
writer.write_all(b"\x1b[1;1R").unwrap();
cursor_replied = true;
}
if output.windows(7).any(|s| s == b"VT_DONE") {
break;
}
}
}
let _ = child.kill();
let _ = child.wait();
drop(writer);
drop(pair.master);
reading.join().unwrap();
let output = String::from_utf8_lossy(&output);
assert!(output.contains("\x1b[?1049h"), "alternate screen entry missing: {output:?}");
assert!(output.contains("\x1b[?1049l"), "alternate screen exit missing: {output:?}");
}
}
}
/// The embedded runtime is the pinned NuGet package's files (`resources/conpty/README.md`).
#[cfg(test)]
mod checksums {
use sha2::{Digest, Sha256};
const FILES: [(&str, &[u8], &str); 6] = [
(
"arm64/conpty.dll",
include_bytes!("../resources/conpty/arm64/conpty.dll"),
"151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf",
),
(
"arm64/OpenConsole.exe",
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
"4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f",
),
(
"x64/conpty.dll",
include_bytes!("../resources/conpty/x64/conpty.dll"),
"feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a",
),
(
"x64/OpenConsole.exe",
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
"3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586",
),
(
"x86/conpty.dll",
include_bytes!("../resources/conpty/x86/conpty.dll"),
"d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93",
),
(
"x86/OpenConsole.exe",
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
"e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3",
),
];
#[test]
fn embedded_runtime_matches_the_pinned_package() {
for (name, bytes, expected) in FILES {
let actual: String = Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(actual, expected, "{name}");
}
}
}
+14 -1
View File
@@ -145,7 +145,7 @@ impl Default for AgentSettings {
show_work_time: true,
show_usage_limits: true,
show_cost: false,
fold_turns: true,
fold_turns: false,
smooth_text: true,
fit_window_width: false,
thinking: ThinkingDisplay::Auto,
@@ -1218,6 +1218,7 @@ pub struct LanguagesSettings {
pub markdown: MarkdownSettings,
pub arduino: ArduinoSettings,
pub zig: ZigSettings,
pub flutter: FlutterSettings,
}
impl Default for LanguagesSettings {
@@ -1249,6 +1250,7 @@ impl Default for LanguagesSettings {
markdown: MarkdownSettings::default(),
arduino: ArduinoSettings::default(),
zig: ZigSettings::default(),
flutter: FlutterSettings::default(),
}
}
}
@@ -1515,6 +1517,15 @@ pub struct ZigSettings {
pub zig: String,
}
/// The Flutter plugin's "Flutter SDK path".
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct FlutterSettings {
/// Flutter SDK root (holding `bin/flutter`); its `flutter` and Dart replace the ones on
/// `PATH`. Empty = `PATH`.
pub sdk: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GoSettings {
@@ -2113,8 +2124,10 @@ mod tests {
assert!(old.agents.show_cost);
assert!(old.agents.show_context_usage && old.agents.show_work_time && old.agents.show_usage_limits);
assert!(!old.agents.fit_window_width);
assert!(!old.agents.fold_turns);
assert!(!Settings::default().agents.show_cost);
assert!(!Settings::default().agents.fit_window_width);
assert!(!Settings::default().agents.fold_turns);
let mut settings = Settings::default();
settings.agents.show_usage_limits = false;
settings.agents.fit_window_width = true;
+1 -1
View File
@@ -30,7 +30,7 @@ pub(crate) use inspect::{fields, instances, referrers, set_inspector, vm_target,
pub(crate) use scan::watch_for_attached_jvm;
pub(crate) use scan::{JvmFinder, attach_target, find_attached_jvm, find_local_jvm, local_jdwp_port};
use snapshot::{AttachProbe, JdkProbe, take_snapshot};
pub use threads::{JvmThreadDump, JvmThreadsResult, JvmThreadsUnavailable, run_jvm_thread_dump};
pub use threads::{JvmThreadDump, JvmThreadsResult, JvmThreadsUnavailable, VirtualThreadsNote, run_jvm_thread_dump};
pub(crate) use threads::{debugged_run_thread_dump, session_thread_dump};
pub const JVM_MEMORY_ADAPTERS: &[&str] = &["java-debug", crate::kotlin::ADAPTER, crate::kotlin_lsp::ADAPTER];
@@ -33,6 +33,7 @@ pub(crate) trait AttachProbe: Send + Sync {
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError>;
/// Confirmed HotSpot and not one of Gradle's own JVMs; asks the JVM nothing.
fn is_application_jvm(&self, pid: u32) -> bool;
fn thread_dump_json(&self, pid: u32, dir: &Path) -> Result<String, AttachError>;
}
pub(super) struct JdkProbe {
@@ -91,6 +92,10 @@ impl AttachProbe for JdkProbe {
fn is_application_jvm(&self, pid: u32) -> bool {
ide_jvm_attach::is_application_jvm(pid)
}
fn thread_dump_json(&self, pid: u32, dir: &Path) -> Result<String, AttachError> {
ide_jvm_attach::thread_dump_json(pid, dir, ide_jvm_attach::THREAD_DUMP_TIMEOUT)
}
}
fn alive(pid: u32) -> bool {
+189 -29
View File
@@ -47,6 +47,8 @@ struct FakeProbe {
application_jvms: Vec<u32>,
/// Pids `ensure_listener` was asked for.
ensured: parking_lot::Mutex<Vec<u32>>,
json_dumps: parking_lot::Mutex<VecDeque<Result<String, AttachError>>>,
json_dirs: parking_lot::Mutex<Vec<PathBuf>>,
}
type StopHook = Box<dyn Fn() + Send + Sync>;
@@ -109,6 +111,8 @@ impl FakeProbe {
listener_starts: parking_lot::Mutex::new(VecDeque::new()),
application_jvms: Vec::new(),
ensured: parking_lot::Mutex::new(Vec::new()),
json_dumps: parking_lot::Mutex::new(VecDeque::new()),
json_dirs: parking_lot::Mutex::new(Vec::new()),
}
}
@@ -193,6 +197,12 @@ impl AttachProbe for FakeProbe {
fn is_application_jvm(&self, pid: u32) -> bool {
self.application_jvms.contains(&pid)
}
fn thread_dump_json(&self, _pid: u32, dir: &Path) -> Result<String, AttachError> {
self.enter("thread_dump_json");
self.json_dirs.lock().push(dir.to_owned());
self.leave();
self.json_dumps.lock().pop_front().expect("unexpected JSON thread dump request")
}
}
const FLAGS: &str = "-XX:+UseCompressedOops -XX:+StartAttachListener";
@@ -1205,10 +1215,95 @@ fn threads_jvm(reason: JvmMemoryUnavailable) -> JvmThreadsUnavailable {
JvmThreadsUnavailable::Jvm { reason }
}
/// The text dump alone: without a directory no JSON dump is asked for.
fn dump_text(fake: &FakeProbe, pid: u32, suspended: bool) -> JvmThreadsResult {
dump_threads(fake, pid, suspended, None, &|| suspended)
}
fn ready_dump(r: JvmThreadsResult) -> JvmThreadDump {
match r {
JvmThreadsResult::Ready { dump } => dump,
other => panic!("{other:?}"),
}
}
const VIRTUAL_JSON: &str = r#"{"threadDump":{"threadContainers":[]}}"#;
fn json_dir() -> &'static Path {
Path::new("/data/cache/heap-snapshots/x")
}
#[test]
fn threads_below_21_ask_for_no_json() {
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
assert_eq!((dump.virtual_json, dump.virtual_note), (None, None));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn threads_on_21_add_the_json_after_the_text() {
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
assert_eq!(dump.text, THREADS);
assert_eq!((dump.virtual_json.as_deref(), dump.virtual_note), (Some(VIRTUAL_JSON), None));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print", "thread_dump_json"]);
assert_eq!(*fake.json_dirs.lock(), [json_dir()]);
}
#[test]
fn a_failed_json_dump_keeps_the_text_dump() {
let cases = [
(AttachError::TooLarge, VirtualThreadsNote::TooLarge),
(AttachError::Timeout, VirtualThreadsNote::Failed),
(AttachError::Protocol("no thread dump file".into()), VirtualThreadsNote::Failed),
];
for (error, note) in cases {
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
*fake.json_dumps.lock() = vec![Err(error)].into();
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
assert_eq!((dump.text.as_str(), dump.virtual_json, dump.virtual_note), (THREADS, None, Some(note)));
}
// No directory to write the file into.
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
let dump = ready_dump(dump_text(&fake, 12, false));
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::Failed)));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn a_failed_text_dump_asks_for_no_json() {
let fake = dumping_threads(99, vec![Err(AttachError::Timeout)]);
let r = dump_threads(&fake, 12, false, Some(json_dir()), &|| false);
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::TimedOut));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn threads_while_suspended_on_21_skip_the_json() {
let fake = dumping_threads(12, vec![Ok(THREADS.into())]);
let dump = ready_dump(dump_threads(&fake, 12, true, Some(json_dir()), &|| true));
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["thread_print"]);
// The program hits a breakpoint while the text dump is taken.
let stopped = Arc::new(AtomicBool::new(false));
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
let stop = stopped.clone();
fake.stops_on = Some(("thread_print", Box::new(move || stop.store(true, Ordering::SeqCst))));
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| stopped.load(Ordering::SeqCst)));
assert!(!dump.taken_while_suspended);
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn threads_while_running_start_the_listener() {
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
let r = dump_threads(&fake, 12, false);
let r = dump_text(&fake, 12, false);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!((dump.text.as_str(), dump.pid, dump.java_version.as_str()), (THREADS, 12, "21.0.5"));
assert!(!dump.taken_while_suspended);
@@ -1218,10 +1313,7 @@ fn threads_while_running_start_the_listener() {
#[test]
fn threads_while_suspended_without_listener_do_not_attach() {
let fake = dumping_threads(99, Vec::new());
assert_eq!(
threads_unavailable(dump_threads(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::ListenerNotRunning)
);
assert_eq!(threads_unavailable(dump_text(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
}
@@ -1230,12 +1322,12 @@ fn threads_while_suspended_on_11_are_refused() {
let mut fake = dumping_threads(12, Vec::new());
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
assert_eq!(
threads_unavailable(dump_threads(&fake, 12, true)),
threads_unavailable(dump_text(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 })
);
fake.version = None;
assert_eq!(
threads_unavailable(dump_threads(&fake, 12, true)),
threads_unavailable(dump_text(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 0 })
);
assert!(fake.commands.lock().is_empty());
@@ -1245,7 +1337,7 @@ fn threads_while_suspended_on_11_are_refused() {
fn threads_while_suspended_on_17_use_the_running_listener() {
let mut fake = dumping_threads(12, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let r = dump_threads(&fake, 12, true);
let r = dump_text(&fake, 12, true);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert!(dump.taken_while_suspended);
assert_eq!(dump.java_version, "17.0.13");
@@ -1257,7 +1349,7 @@ fn threads_of_a_tree_without_a_listener_go_to_its_first_application_jvm() {
// A shell (10) started a Gradle client (11) that started the program's JVM (12).
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
fake.application_jvms = vec![12];
let r = dump_tree(&fake, &[10, 11, 12], false);
let r = dump_tree(&fake, &[10, 11, 12], false, None, &|| false);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, 12);
assert_eq!(*fake.ensured.lock(), [12]);
@@ -1266,7 +1358,7 @@ fn threads_of_a_tree_without_a_listener_go_to_its_first_application_jvm() {
let fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm)].into();
assert_eq!(
threads_unavailable(dump_tree(&fake, &[10, 11], false)),
threads_unavailable(dump_tree(&fake, &[10, 11], false, None, &|| false)),
threads_jvm(JvmMemoryUnavailable::NoJvmProcess)
);
assert_eq!(*fake.ensured.lock(), [10]);
@@ -1290,7 +1382,7 @@ async fn launched_thread_dump_without_a_listener_finds_the_jvm_below_the_reporte
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let target = JvmTarget::Launched(std::process::id() as i32);
let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
let r = thread_dump(&state, || false, |_| probe, target, None).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, jvm);
assert_eq!(*fake.ensured.lock(), [jvm]);
@@ -1340,7 +1432,7 @@ async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
let bare = stopped_attach(0);
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
let r = known_pid_dump(&bare.session, |_| probe, 555, None).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
@@ -1348,7 +1440,7 @@ async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
let bare = bare_session("attach");
let fake = Arc::new(dumping_threads(99, vec![Ok(THREADS.into())]));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
let r = known_pid_dump(&bare.session, |_| probe, 555, None).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!((dump.pid, dump.taken_while_suspended), (555, false));
assert_eq!(*fake.ensured.lock(), [555]);
@@ -1369,26 +1461,71 @@ async fn run_dump_of_a_suspended_debugged_jvm_takes_the_suspended_path() {
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 }));
assert!(fake.commands.lock().is_empty());
// No listener: none is started, the JVM's Signal Dispatcher being stopped.
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert!(dump.taken_while_suspended);
assert_eq!(dump.pid, 4242);
}
#[tokio::test]
async fn run_dump_of_a_debugged_jvm_asks_for_no_json_while_the_session_holds_it() {
let bare = stopped_attach(4242);
let fake = Arc::new(dumping_threads(4242, vec![Ok(THREADS.into())]));
let probe: Arc<dyn AttachProbe> = fake.clone();
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 4242, Some(json_dir().into())).await.unwrap());
assert!(dump.taken_while_suspended);
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["thread_print"]);
// Running at first, the program hits a breakpoint while the text dump is taken.
let bare = bare_session("attach");
bare.session.jvm_pid.store(4242, Ordering::Release);
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
let session = bare.session.clone();
fake.stops_on = Some(("thread_print", Box::new(move || session.suspended.stopped(None, true))));
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 4242, Some(json_dir().into())).await.unwrap());
assert!(!dump.taken_while_suspended);
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[tokio::test]
async fn run_dump_through_a_linked_session_whose_jvm_is_not_located_asks_for_no_json_while_stopped() {
// Gradle bootRun Debug after an earlier run dump opened the listener: the session's pid is still 0.
let bare = stopped_attach(0);
let fake = Arc::new(dumping_threads(555, vec![Ok(THREADS.into())]));
let probe: Arc<dyn AttachProbe> = fake.clone();
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 555, Some(json_dir().into())).await.unwrap());
assert_eq!((dump.pid, dump.taken_while_suspended), (555, true));
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["thread_print"]);
// Running, the same session gets the JSON dump too.
let bare = bare_session("attach");
let fake = Arc::new(dumping_threads(555, vec![Ok(THREADS.into())]));
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
let probe: Arc<dyn AttachProbe> = fake.clone();
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 555, Some(json_dir().into())).await.unwrap());
assert_eq!((dump.virtual_json.as_deref(), dump.virtual_note), (Some(VIRTUAL_JSON), None));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print", "thread_dump_json"]);
}
#[tokio::test]
async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() {
let bare = bare_session("attach");
@@ -1397,7 +1534,7 @@ async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() {
let probe: Arc<dyn AttachProbe> = fake.clone();
let histogram = bare.session.jvm_memory.lock().await;
let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242));
let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242, None));
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
// The program hits a breakpoint while the dump waits behind the session's histogram.
bare.session.suspended.stopped(None, true);
@@ -1411,28 +1548,28 @@ fn threads_of_an_exited_program() {
let mut fake = dumping_threads(99, Vec::new());
fake.alive = false;
*fake.listener_starts.lock() = vec![Err(AttachError::NoListener)].into();
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
assert_eq!(threads_unavailable(dump_threads(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
assert_eq!(threads_unavailable(dump_text(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
}
#[test]
fn thread_dump_errors_map_to_reasons() {
let fake = dumping_threads(12, vec![Err(AttachError::Timeout)]);
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::TimedOut));
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::TimedOut));
let fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::ListenerDidNotStart)].into();
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), JvmThreadsUnavailable::ListenerDidNotStart);
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), JvmThreadsUnavailable::ListenerDidNotStart);
assert_eq!(*fake.commands.lock(), ["ensure_listener"]);
let mut fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm), Err(AttachError::NotAJvm)].into();
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess));
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess));
fake.alive = false;
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
let fake = dumping_threads(12, vec![Err(AttachError::Command { code: 1, message: "no".into() })]);
let JvmThreadsUnavailable::Failed { message } = threads_unavailable(dump_threads(&fake, 12, false)) else {
let JvmThreadsUnavailable::Failed { message } = threads_unavailable(dump_text(&fake, 12, false)) else {
panic!("not a failure")
};
assert!(message.contains("no"), "{message}");
@@ -1456,14 +1593,20 @@ fn thread_results_serialize_with_camel_case_tags() {
java_version: String::new(),
taken_while_suspended: true,
elapsed_ms: 3,
virtual_json: None,
virtual_note: Some(VirtualThreadsNote::WhileSuspended),
};
assert_eq!(
serde_json::to_value(JvmThreadsResult::Ready { dump }).unwrap(),
serde_json::json!({
"status": "ready",
"dump": {"text": "t", "pid": 7, "javaVersion": "", "takenWhileSuspended": true, "elapsedMs": 3}
"dump": {
"text": "t", "pid": 7, "javaVersion": "", "takenWhileSuspended": true, "elapsedMs": 3,
"virtualJson": null, "virtualNote": "whileSuspended"
}
})
);
assert_eq!(serde_json::to_value(VirtualThreadsNote::TooLarge).unwrap(), serde_json::json!("tooLarge"));
}
#[cfg(unix)]
@@ -1479,7 +1622,7 @@ async fn threads_take_the_memory_lock() {
let running = Suspension::default();
let (classes, threads) = tokio::join!(
snapshot(&state, &running, |_| probe.clone(), JvmTarget::Launched(pid as i32), None),
thread_dump(&state, || false, |_| probe.clone(), JvmTarget::Launched(pid as i32))
thread_dump(&state, || false, |_| probe.clone(), JvmTarget::Launched(pid as i32), None)
);
assert!(matches!(classes.unwrap(), JvmMemoryResult::Ready { .. }));
let threads = threads.unwrap();
@@ -1493,12 +1636,14 @@ async fn threads_take_the_memory_lock() {
async fn queued_thread_dump_reads_suspension_under_the_lock() {
let pid = std::process::id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let suspended = Suspension::default();
let suspended = Arc::new(Suspension::default());
let fake = Arc::new(dumping_threads(0, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let running = state.lock().await;
let mut queued = Box::pin(thread_dump(&state, || suspended.get(), |_| probe, JvmTarget::Launched(pid as i32)));
let stopped = suspended.clone();
let target = JvmTarget::Launched(pid as i32);
let mut queued = Box::pin(thread_dump(&state, move || stopped.get(), |_| probe, target, Some(json_dir().into())));
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
// The program hits a breakpoint while the dump waits behind a class-table request.
suspended.stopped(None, true);
@@ -1515,12 +1660,27 @@ async fn attached_thread_dump_keeps_the_scanned_jvm() {
fake.jdwp = Some((5005, 4242));
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
let target = JvmTarget::Attached { pid: &jvm_pid, jdwp_port: Some(5005) };
let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
let r = thread_dump(&state, || false, |_| probe, target, None).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, 4242);
assert_eq!(jvm_pid.load(Ordering::SeqCst), 4242);
}
#[cfg(unix)]
#[tokio::test]
async fn session_thread_dump_writes_the_json_into_the_given_directory() {
let pid = std::process::id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let fake = dumping_threads(pid, vec![Ok(THREADS.into())]);
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let target = JvmTarget::Launched(pid as i32);
let r = thread_dump(&state, || false, |_| probe, target, Some(json_dir().into())).await.unwrap();
assert_eq!(ready_dump(r).virtual_json.as_deref(), Some(VIRTUAL_JSON));
assert_eq!(*fake.json_dirs.lock(), [json_dir()]);
}
#[tokio::test]
async fn capability_matches_memory() {
for adapter in JVM_MEMORY_ADAPTERS.iter().copied().chain(["debugpy"]) {
+96 -17
View File
@@ -8,11 +8,15 @@ use super::{
};
use crate::session::Session;
use ide_core::{IdeError, IdeResult};
use ide_jvm_attach::AttachError;
use ide_jvm_attach::{AttachError, JavaVersion};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// The first release whose virtual threads are final and that writes the JSON dump.
const VIRTUAL_THREADS_MAJOR: u32 = 21;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct JvmThreadDump {
@@ -23,6 +27,20 @@ pub struct JvmThreadDump {
pub taken_while_suspended: bool,
/// Wall time of the `Thread.print` request.
pub elapsed_ms: u32,
/// `Thread.dump_to_file -format=json`, which also lists virtual threads; JDK 21+ only.
pub virtual_json: Option<String>,
/// Why `virtual_json` is missing from a JDK 21+ dump; none below 21.
pub virtual_note: Option<VirtualThreadsNote>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum VirtualThreadsNote {
/// A debugger holds the VM, which would hang the JSON request until it resumes.
WhileSuspended,
/// Over the attach reply limit (64 MiB).
TooLarge,
Failed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -48,13 +66,17 @@ pub enum JvmThreadsResult {
Unavailable { reason: JvmThreadsUnavailable },
}
/// A thread dump of `pid`, a JVM no debugger holds. Blocking for up to the listener start and
/// A thread dump of `pid`, a JVM no debugger holds; `json_dir` is an absolute, owner-only
/// directory the JVM may write the JSON dump into. Blocking for up to the listener start and
/// dump timeouts, so callers run it in `spawn_blocking`.
pub fn run_jvm_thread_dump(pid: u32) -> JvmThreadsResult {
dump_threads(&JdkProbe { suspended: false }, pid, false)
pub fn run_jvm_thread_dump(pid: u32, json_dir: Option<&Path>) -> JvmThreadsResult {
dump_threads(&JdkProbe { suspended: false }, pid, false, json_dir, &|| false)
}
pub(crate) async fn session_thread_dump(session: Arc<Session>) -> IdeResult<JvmThreadsResult> {
pub(crate) async fn session_thread_dump(
session: Arc<Session>,
json_dir: Option<PathBuf>,
) -> IdeResult<JvmThreadsResult> {
until_located(&session).await;
let launched = histogram_pid(&session);
// Detached, so a caller that gives up cannot release the lock while the JVM is still
@@ -62,7 +84,9 @@ pub(crate) async fn session_thread_dump(session: Arc<Session>) -> IdeResult<JvmT
tokio::spawn(async move {
let target = session_target(&session, launched);
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
thread_dump(&session.jvm_memory, || capture_suspended(&session), probe, target).await
let stopped = session.clone();
let suspended = move || capture_suspended(&stopped);
thread_dump(&session.jvm_memory, suspended, probe, target, json_dir).await
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
@@ -70,43 +94,53 @@ pub(crate) async fn session_thread_dump(session: Arc<Session>) -> IdeResult<JvmT
/// A thread dump of `pid`, a run's JVM that `session` debugs, taken as the session's own dump
/// is: a JVM the debugger holds suspended is never asked to open a listener.
pub(crate) async fn debugged_run_thread_dump(session: Arc<Session>, pid: u32) -> IdeResult<JvmThreadsResult> {
pub(crate) async fn debugged_run_thread_dump(
session: Arc<Session>,
pid: u32,
json_dir: Option<PathBuf>,
) -> IdeResult<JvmThreadsResult> {
// Detached for the same reason as `session_thread_dump`.
tokio::spawn(async move {
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
known_pid_dump(&session, probe, pid).await
known_pid_dump(&session, probe, pid, json_dir).await
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
}
/// The session's suspension decides the JSON dump too: it is read again before that request.
pub(super) async fn known_pid_dump(
session: &Session,
session: &Arc<Session>,
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
pid: u32,
json_dir: Option<PathBuf>,
) -> IdeResult<JvmThreadsResult> {
let target =
i32::try_from(pid).map_or(JvmTarget::Unavailable(JvmMemoryUnavailable::NoJvmProcess), JvmTarget::Known);
thread_dump(&session.jvm_memory, || capture_suspended(session), probe, target).await
let stopped = session.clone();
let suspended = move || capture_suspended(&stopped);
thread_dump(&session.jvm_memory, suspended, probe, target, json_dir).await
}
/// Takes the class-table lock, so a dump never runs beside a histogram or heap dump of the same
/// session; `suspended` and then `probe` are read once it is held.
/// session; `suspended_now` and then `probe` are read once it is held, and `suspended_now` again
/// before the JSON dump.
pub(super) async fn thread_dump(
state: &tokio::sync::Mutex<JvmMemoryState>,
suspended: impl FnOnce() -> bool,
suspended_now: impl Fn() -> bool + Send + Sync + 'static,
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
target: JvmTarget<'_>,
json_dir: Option<PathBuf>,
) -> IdeResult<JvmThreadsResult> {
let _turn = state.lock().await;
let suspended = suspended();
let suspended = suspended_now();
let lookup = match lookup(target) {
Ok(lookup) => lookup,
Err(reason) => return Ok(jvm(reason)),
};
let probe = probe(suspended);
let (found, outcome) = tokio::task::spawn_blocking(move || match resolve_jvm(lookup, &*probe, suspended) {
Ok((tree, found)) => (found, dump_tree(&*probe, &tree, suspended)),
Ok((tree, found)) => (found, dump_tree(&*probe, &tree, suspended, json_dir.as_deref(), &suspended_now)),
Err(reason) => (None, jvm(reason)),
})
.await
@@ -118,19 +152,32 @@ pub(super) async fn thread_dump(
/// `tree` starts with the session's reported pid, followed by its descendants: the JVM is the
/// first with a listener, else the first application JVM (the reported pid may be a shell or a
/// Gradle client), else the reported pid.
pub(super) fn dump_tree(probe: &dyn AttachProbe, tree: &[i32], suspended: bool) -> JvmThreadsResult {
pub(super) fn dump_tree(
probe: &dyn AttachProbe,
tree: &[i32],
suspended: bool,
json_dir: Option<&Path>,
suspended_now: &dyn Fn() -> bool,
) -> JvmThreadsResult {
let jvm_pid = pick_jvm_pid(tree, |p| probe.has_listener(p))
.or_else(|| pick_jvm_pid(tree, |p| probe.is_application_jvm(p)))
.or_else(|| tree.first().and_then(|&p| u32::try_from(p).ok()).filter(|&p| p > 0));
match jvm_pid {
Some(pid) => dump_threads(probe, pid, suspended),
Some(pid) => dump_threads(probe, pid, suspended, json_dir, suspended_now),
None => jvm(JvmMemoryUnavailable::NoJvmProcess),
}
}
/// Blocking. A JVM a debugger holds suspended cannot open a listener (its Signal Dispatcher is
/// stopped), and one below 17 hangs even with one, so it is asked only when both are ruled out.
pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -> JvmThreadsResult {
/// The JSON dump follows a text dump that succeeded; its failure only sets the note.
pub(crate) fn dump_threads(
probe: &dyn AttachProbe,
pid: u32,
suspended: bool,
json_dir: Option<&Path>,
suspended_now: &dyn Fn() -> bool,
) -> JvmThreadsResult {
if suspended {
if !probe.has_listener(pid) {
return jvm(gone(probe, pid));
@@ -149,6 +196,8 @@ pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -
Err(e) => return failure(probe, pid, e),
};
let elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
let (virtual_json, virtual_note) =
virtual_threads(probe, pid, version.as_ref(), suspended, json_dir, suspended_now);
JvmThreadsResult::Ready {
dump: JvmThreadDump {
text,
@@ -156,10 +205,40 @@ pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -
java_version: version.map(|v| v.text).unwrap_or_default(),
taken_while_suspended: suspended,
elapsed_ms,
virtual_json,
virtual_note,
},
}
}
/// The program may have stopped during the text dump, so the suspension is read again.
fn virtual_threads(
probe: &dyn AttachProbe,
pid: u32,
version: Option<&JavaVersion>,
suspended: bool,
json_dir: Option<&Path>,
suspended_now: &dyn Fn() -> bool,
) -> (Option<String>, Option<VirtualThreadsNote>) {
if version.is_none_or(|v| v.major < VIRTUAL_THREADS_MAJOR) {
return (None, None);
}
if suspended || suspended_now() {
return (None, Some(VirtualThreadsNote::WhileSuspended));
}
let Some(dir) = json_dir else {
return (None, Some(VirtualThreadsNote::Failed));
};
match probe.thread_dump_json(pid, dir) {
Ok(json) => (Some(json), None),
Err(AttachError::TooLarge) => (None, Some(VirtualThreadsNote::TooLarge)),
Err(e) => {
tracing::warn!("JSON thread dump of JVM {pid}: {e}");
(None, Some(VirtualThreadsNote::Failed))
}
}
}
fn failure(probe: &dyn AttachProbe, pid: u32, error: AttachError) -> JvmThreadsResult {
let reason = match error {
AttachError::ListenerDidNotStart => JvmThreadsUnavailable::ListenerDidNotStart,
+30 -22
View File
@@ -897,6 +897,21 @@ impl DebugManager {
if config.adapter == "rdbg" {
rdbg_command_line(&mut spec, &config, &cwd)?;
}
// Flutter: a project depending on the Flutter SDK needs `flutter debug_adapter`
// (the Dart adapter cannot start a program importing `dart:ui`, and hot reload
// is Flutter-only). Plain Dart projects keep the configured `dart`. Before
// `custom_command`, which picks the Flutter SDK setting's `flutter`.
if config.adapter == "dart" {
let program = arguments.get("program").and_then(Value::as_str).map(Path::new);
if force_flutter || is_flutter_project(&cwd, program) {
if spec.command == "dart" {
spec.command = "flutter".into();
}
if let Some(device) = flutter_device {
add_flutter_device(&mut arguments, device);
}
}
}
if let Some(command) = custom_command(&spec.command) {
spec.command = command;
}
@@ -912,20 +927,6 @@ impl DebugManager {
spec.command = python;
}
}
// Flutter: a project depending on the Flutter SDK needs `flutter debug_adapter`
// (the Dart adapter cannot start a program importing `dart:ui`, and hot reload
// is Flutter-only). Plain Dart projects keep the configured `dart`.
if config.adapter == "dart" {
let program = arguments.get("program").and_then(Value::as_str).map(Path::new);
if force_flutter || is_flutter_project(&cwd, program) {
if spec.command == "dart" {
spec.command = "flutter".into();
}
if let Some(device) = flutter_device {
add_flutter_device(&mut arguments, device);
}
}
}
let id = DebugSessionId::next();
let debug_server = take_debug_server(&mut arguments)?;
if let Some(server) = &debug_server {
@@ -1977,20 +1978,27 @@ impl DebugManager {
jvm_memory::session_heap_dump(session, dir, cancel).await
}
/// `Thread.print -l` of the session's JVM, taking the session's class-table turn. A JVM the
/// debugger holds suspended is asked only when it is 17 or later and its listener already
/// runs: otherwise the request would hang until the program resumes.
pub async fn jvm_thread_dump(&self, s: DebugSessionId) -> IdeResult<JvmThreadsResult> {
/// `Thread.print -l` of the session's JVM, taking the session's class-table turn, and on JDK
/// 21+ the JSON dump written into `json_dir`. A JVM the debugger holds suspended is asked
/// only when it is 17 or later and its listener already runs: otherwise the request would hang
/// until the program resumes.
pub async fn jvm_thread_dump(&self, s: DebugSessionId, json_dir: Option<PathBuf>) -> IdeResult<JvmThreadsResult> {
let session = self.session(s)?;
jvm_memory::session_thread_dump(session).await
jvm_memory::session_thread_dump(session, json_dir).await
}
/// `Thread.print -l` of `pid`, the JVM of `run`, when a live session debugs it (a build
/// tool's run started for Debug, Attach to Process): taken as [`Self::jvm_thread_dump`] takes
/// it, under that session's turn and suspension. `None` when no session debugs `pid`.
pub async fn debugged_jvm_thread_dump(&self, run: RunId, pid: u32) -> Option<IdeResult<JvmThreadsResult>> {
/// it, under that session's turn and suspension, so a suspended JVM is not asked for the JSON
/// dump either. `None` when no session debugs `pid`.
pub async fn debugged_jvm_thread_dump(
&self,
run: RunId,
pid: u32,
json_dir: Option<PathBuf>,
) -> Option<IdeResult<JvmThreadsResult>> {
let session = self.jvm_session_of(run, pid)?;
Some(jvm_memory::debugged_run_thread_dump(session, pid).await)
Some(jvm_memory::debugged_run_thread_dump(session, pid, json_dir).await)
}
/// A session attached to `run` first: one whose JVM is not located yet (its attach-time scan
+2 -1
View File
@@ -1061,7 +1061,8 @@ fn reap_on_exit(mut child: Box<dyn portable_pty::Child + Send + Sync>, exited: A
/// starts a launcher that gives the program its terminal, and the program reads input only from
/// a terminal), forwards its output to the console, and keeps the terminal for typed input.
pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, String> {
use portable_pty::{CommandBuilder, PtySize, native_pty_system};
use ide_core::pty::native_pty_system;
use portable_pty::{CommandBuilder, PtySize};
let argv: Vec<String> = args
.get("args")
.and_then(Value::as_array)
+2 -2
View File
@@ -3096,7 +3096,7 @@ async fn a_run_dump_goes_through_the_session_attached_to_the_run() {
let pid = jvm.id();
assert_eq!(h.manager.jvm_session_of(RunId(7), pid).map(|s| s.id), Some(id));
assert!(h.manager.jvm_session_of(RunId(8), pid).is_none());
let dump = h.manager.debugged_jvm_thread_dump(RunId(7), pid).await.unwrap().unwrap();
let dump = h.manager.debugged_jvm_thread_dump(RunId(7), pid, None).await.unwrap().unwrap();
let alive = jvm.try_wait().unwrap().is_none();
let _ = jvm.kill();
let _ = jvm.wait();
@@ -3120,7 +3120,7 @@ async fn a_run_jvm_is_found_by_the_session_attached_to_it() {
let id = h.start(cfg).await.unwrap();
assert_eq!(h.manager.jvm_session_of(RunId(1), 4242).map(|s| s.id), Some(id));
assert!(h.manager.jvm_session_of(RunId(1), 4243).is_none());
assert!(h.manager.debugged_jvm_thread_dump(RunId(1), 4243).await.is_none());
assert!(h.manager.debugged_jvm_thread_dump(RunId(1), 4243, None).await.is_none());
}
#[cfg(unix)]
+4 -3
View File
@@ -658,8 +658,7 @@ impl DbManager {
let config = self.sources()?.into_iter().find(|s| s.id == id).and_then(|s| s.ssh).map(|s| s.config);
if let Some(c) = config.filter(|c| !c.trim().is_empty()) {
let save = self.ssh.config(&c).map(|c| c.save_secret).unwrap_or(save);
self.ssh.set_secret(&c, secret, save);
return Ok(());
return self.ssh.set_secret(&c, secret, save);
}
self.remember(self.saved_for(id), secrets::ssh_key(id), secret, save).await
}
@@ -760,7 +759,9 @@ impl DbManager {
} else {
if let Some(s) = ssh_secret {
let save = self.ssh.config(config)?.save_secret;
self.ssh.set_secret(config, Some(s), save);
if let Err(e) = self.ssh.set_secret(config, Some(s), save) {
tracing::warn!("could not save the SSH credential: {}", e.message);
}
}
self.ssh.session(config).await?
})
+43 -194
View File
@@ -1,23 +1,34 @@
//! One `dart devtools` server per project window, started when first asked for. In `--machine`
//! mode it reports its port as a `server.started` line on stdout. A server that fails or exits
//! is not restarted on its own: the next request starts a new one.
//! One `dart devtools` server per project window. In `--machine` mode it reports its port as a
//! `server.started` line on stdout.
use crate::{KILL_GRACE, OUTPUT_TAIL, keep_output, read_lines, spawn_watched};
use ide_core::process::{kill_tree, terminate_tree};
use crate::flutter_executable;
use crate::server::{Line, Spec, ToolServer};
use ide_core::tool_path::{find_command, search_path_in};
use parking_lot::{Condvar, Mutex};
use serde_json::Value;
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::process::Child;
use std::sync::Arc;
use std::time::{Duration, Instant};
use std::time::Duration;
const START_TIMEOUT: Duration = Duration::from_secs(60);
/// The address embedded pages are allowed to come from, so never `localhost`.
const HOST: &str = "127.0.0.1";
pub(crate) const HOST: &str = "127.0.0.1";
const ARGS: [&str; 7] = ["devtools", "--machine", "--allow-embedding", "--host", HOST, "--port", "0"];
pub(crate) static DEVTOOLS: Spec = Spec {
name: "Flutter DevTools",
args: &ARGS,
timeout: Duration::from_secs(60),
executable: dart_executable,
not_found: "Dart SDK not found: install Flutter or add it to PATH",
line,
failed: |message| if message.is_empty() { "dart devtools exited".into() } else { message },
};
impl ToolServer {
/// `dart` is the configured one, else the one of the `flutter` on the search path.
pub fn devtools(root: PathBuf, dart: crate::Configured) -> Self {
Self::new(root, &DEVTOOLS, dart)
}
}
fn started_port(line: &str) -> Option<u16> {
let message: Value = serde_json::from_str(line.trim()).ok()?;
if message.get("event")?.as_str()? != "server.started" {
@@ -26,186 +37,23 @@ fn started_port(line: &str) -> Option<u16> {
u16::try_from(message.get("params")?.get("port")?.as_u64()?).ok()
}
fn line(line: &str) -> Line {
match started_port(line) {
Some(port) => Line::Url(format!("http://{HOST}:{port}")),
None => Line::Output(line.to_owned()),
}
}
/// The `dart` of the SDK `flutter` belongs to, so that DevTools matches the debugged app.
fn dart_executable(root: &Path) -> Option<PathBuf> {
let path = search_path_in(root);
find_command("flutter", &path, root)
flutter_executable(root)
.and_then(|flutter| {
// On the search path `flutter` is often a link into the SDK.
let flutter = if cfg!(unix) { std::fs::canonicalize(&flutter).unwrap_or(flutter) } else { flutter };
let dart = flutter.with_file_name(if cfg!(windows) { "dart.bat" } else { "dart" });
dart.is_file().then_some(dart)
})
.or_else(|| find_command("dart", &path, root))
}
#[derive(Default)]
enum Status {
#[default]
Stopped,
Starting,
Ready(String),
Failed(String),
}
#[derive(Default)]
struct State {
/// Bumped by every start and stop: a reader of an older process no longer has a say.
generation: u64,
child: Option<Child>,
status: Status,
}
impl State {
fn shut_down(&mut self) {
self.generation += 1;
if let Some(mut child) = self.child.take() {
std::thread::spawn(move || terminate_tree(&mut child, KILL_GRACE));
}
}
}
struct Shared {
root: PathBuf,
/// Replaces the lookup on the search path (tests).
executable: Option<PathBuf>,
timeout: Duration,
state: Mutex<State>,
changed: Condvar,
}
impl Shared {
/// Applies `status` unless this process was replaced or stopped; false if it was.
fn set(&self, generation: u64, status: Status) -> bool {
let mut state = self.state.lock();
if state.generation != generation {
return false;
}
state.status = status;
self.changed.notify_all();
true
}
}
pub struct DevToolsServer(Arc<Shared>);
impl DevToolsServer {
pub fn new(root: PathBuf) -> Self {
Self::with_executable(root, None, START_TIMEOUT)
}
fn with_executable(root: PathBuf, executable: Option<PathBuf>, timeout: Duration) -> Self {
Self(Arc::new(Shared { root, executable, timeout, state: Mutex::default(), changed: Condvar::new() }))
}
/// The server's address, starting it if none runs. Blocks until it is known.
pub fn url(&self) -> Result<String, String> {
let shared = &self.0;
let deadline = Instant::now() + shared.timeout;
let mut state = shared.state.lock();
if matches!(state.status, Status::Stopped | Status::Failed(_)) {
state.generation += 1;
state.status = Status::Starting;
let (shared, generation) = (shared.clone(), state.generation);
std::thread::spawn(move || run(&shared, generation));
}
loop {
match &state.status {
Status::Ready(url) => return Ok(url.clone()),
Status::Failed(message) => return Err(message.clone()),
Status::Stopped => return Err("Flutter DevTools was stopped".into()),
Status::Starting => {}
}
if shared.changed.wait_until(&mut state, deadline).timed_out() {
state.shut_down();
let message = "Flutter DevTools did not start in time".to_owned();
state.status = Status::Failed(message.clone());
shared.changed.notify_all();
return Err(message);
}
}
}
/// Ends the server (project closed, or no longer trusted).
pub fn stop(&self) {
let mut state = self.0.state.lock();
state.shut_down();
state.status = Status::Stopped;
self.0.changed.notify_all();
}
/// Ends the server before returning, for a process about to exit.
pub fn kill(&self) {
let mut state = self.0.state.lock();
state.generation += 1;
state.status = Status::Stopped;
if let Some(mut child) = state.child.take() {
kill_tree(&mut child);
}
self.0.changed.notify_all();
}
}
/// One server's whole life, on its own thread.
fn run(shared: &Arc<Shared>, generation: u64) {
let fail = |message: String| {
shared.set(generation, Status::Failed(message));
};
let Some(executable) = shared.executable.clone().or_else(|| dart_executable(&shared.root)) else {
return fail("Dart SDK not found: install Flutter or add it to PATH".into());
};
let mut child = match spawn_watched(&executable, &ARGS, &shared.root) {
Ok(child) => child,
Err(e) => return fail(format!("could not run {}: {e}", executable.display())),
};
let (Some(stdout), Some(stderr)) = (child.stdout.take(), child.stderr.take()) else {
terminate_tree(&mut child, Duration::ZERO);
return fail("no output pipe".into());
};
{
let mut state = shared.state.lock();
if state.generation != generation {
drop(state);
terminate_tree(&mut child, KILL_GRACE);
return;
}
state.child = Some(child);
}
let tail = Arc::new(Mutex::new(VecDeque::with_capacity(OUTPUT_TAIL)));
let errors = {
let tail = tail.clone();
std::thread::spawn(move || {
read_lines(stderr, |line| {
keep_output(&tail, line);
true
});
})
};
read_lines(stdout, |line| match started_port(line) {
Some(port) => shared.set(generation, Status::Ready(format!("http://{HOST}:{port}"))),
None => {
keep_output(&tail, line);
true
}
});
let _ = errors.join();
let mut state = shared.state.lock();
if state.generation != generation {
return;
}
let child = state.child.take();
state.status = if matches!(state.status, Status::Ready(_)) {
Status::Stopped
} else {
let message = Vec::from(std::mem::take(&mut *tail.lock())).join("\n");
Status::Failed(if message.is_empty() { "dart devtools exited".into() } else { message })
};
shared.changed.notify_all();
drop(state);
if let Some(mut child) = child {
std::thread::spawn(move || terminate_tree(&mut child, Duration::ZERO));
}
.or_else(|| find_command("dart", &search_path_in(root), root))
}
#[cfg(test)]
@@ -225,14 +73,15 @@ mod tests {
mod process {
use super::*;
use std::os::unix::fs::PermissionsExt;
use std::time::Instant;
const STARTED: &str = r#"echo '{"event":"server.started","params":{"port":4242}}'"#;
fn server(dir: &Path, script: &str, timeout: Duration) -> DevToolsServer {
fn server(dir: &Path, script: &str, timeout: Duration) -> ToolServer {
let path = dir.join("dart");
std::fs::write(&path, format!("#!/bin/sh\necho run >> runs\n{script}")).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
DevToolsServer::with_executable(dir.to_owned(), Some(path), timeout)
ToolServer::with_executable(dir.to_owned(), &DEVTOOLS, Box::new(move || Some(path.clone())), timeout)
}
fn runs(dir: &Path) -> usize {
@@ -252,8 +101,8 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
let script = format!("echo \"$*\" > args\necho $$ > pid\n{STARTED}\nexec sleep 30");
let devtools = server(dir.path(), &script, Duration::from_secs(10));
assert_eq!(devtools.url().unwrap(), "http://127.0.0.1:4242");
assert_eq!(devtools.url().unwrap(), "http://127.0.0.1:4242");
assert_eq!(devtools.url(&[]).unwrap(), "http://127.0.0.1:4242");
assert_eq!(devtools.url(&[]).unwrap(), "http://127.0.0.1:4242");
assert_eq!(runs(dir.path()), 1);
let args = std::fs::read_to_string(dir.path().join("args")).unwrap();
assert_eq!(args.trim(), ARGS.join(" "));
@@ -271,10 +120,10 @@ mod tests {
fn a_failure_is_reported_and_only_a_new_request_retries() {
let dir = tempfile::tempdir().unwrap();
let devtools = server(dir.path(), "echo boom >&2\nexit 3", Duration::from_secs(10));
assert_eq!(devtools.url().unwrap_err(), "boom");
assert_eq!(devtools.url(&[]).unwrap_err(), "boom");
std::thread::sleep(Duration::from_millis(100));
assert_eq!(runs(dir.path()), 1);
assert_eq!(devtools.url().unwrap_err(), "boom");
assert_eq!(devtools.url(&[]).unwrap_err(), "boom");
assert_eq!(runs(dir.path()), 2);
}
@@ -282,10 +131,10 @@ mod tests {
fn a_server_that_exits_is_not_restarted_until_asked() {
let dir = tempfile::tempdir().unwrap();
let devtools = server(dir.path(), STARTED, Duration::from_secs(10));
devtools.url().unwrap();
wait_for("the exit to be noticed", || matches!(devtools.0.state.lock().status, Status::Stopped));
devtools.url(&[]).unwrap();
wait_for("the exit to be noticed", || devtools.is_stopped());
assert_eq!(runs(dir.path()), 1);
devtools.url().unwrap();
devtools.url(&[]).unwrap();
assert_eq!(runs(dir.path()), 2);
}
@@ -293,7 +142,7 @@ mod tests {
fn a_server_that_never_reports_times_out() {
let dir = tempfile::tempdir().unwrap();
let devtools = server(dir.path(), "exec sleep 30", Duration::from_millis(200));
assert_eq!(devtools.url().unwrap_err(), "Flutter DevTools did not start in time");
assert_eq!(devtools.url(&[]).unwrap_err(), "Flutter DevTools did not start in time");
}
}
}
+27 -8
View File
@@ -10,8 +10,10 @@
//! daemon that fails stays failed until the user restarts it.
mod devtools;
mod server;
mod widget_preview;
pub use devtools::DevToolsServer;
pub use server::ToolServer;
use ide_android::AndroidDevice;
use ide_core::event::{FlutterDaemonStatus, FlutterDevice, FlutterDeviceList, FlutterEmulator};
@@ -189,8 +191,7 @@ impl State {
struct Shared {
root: PathBuf,
sink: SharedSink,
/// Replaces the lookup on the search path (tests).
executable: Option<PathBuf>,
executable: Configured,
state: Mutex<State>,
}
@@ -200,16 +201,21 @@ impl Shared {
}
}
/// The configured `flutter` / `dart` (the Flutter SDK setting), asked at each start; `None`
/// looks it up on the search path.
pub type Configured = Box<dyn Fn() -> Option<PathBuf> + Send + Sync>;
/// One project window's `flutter daemon`, started on first use.
pub struct FlutterDaemon(Arc<Shared>);
impl FlutterDaemon {
pub fn new(root: PathBuf, sink: SharedSink) -> Self {
Self::with_executable(root, sink, None)
pub fn new(root: PathBuf, sink: SharedSink, executable: Configured) -> Self {
Self(Arc::new(Shared { root, sink, executable, state: Mutex::default() }))
}
#[cfg(all(test, unix))]
fn with_executable(root: PathBuf, sink: SharedSink, executable: Option<PathBuf>) -> Self {
Self(Arc::new(Shared { root, sink, executable, state: Mutex::default() }))
Self::new(root, sink, Box::new(move || executable.clone()))
}
/// The current list; starts the daemon unless it already ran. Never blocks on the process.
@@ -271,6 +277,15 @@ impl FlutterDaemon {
}
}
/// Starts a running daemon again, with the SDK the settings now choose.
pub fn sdk_changed(&self) {
let mut state = self.0.state.lock();
if state.status != FlutterDaemonStatus::Stopped {
state.shut_down();
start(&self.0, &mut state);
}
}
/// Ends the daemon (project closed, or no longer trusted).
pub fn stop(&self) {
let mut state = self.0.state.lock();
@@ -385,10 +400,14 @@ fn read_lines(pipe: impl Read, mut on_line: impl FnMut(&str) -> bool) {
}
}
/// The `flutter` that commands run in `root` use.
fn flutter_executable(root: &Path) -> Option<PathBuf> {
find_command("flutter", &search_path_in(root), root)
}
/// One daemon's whole life, on its own thread.
fn run(shared: &Arc<Shared>, generation: u64) {
let executable =
shared.executable.clone().or_else(|| find_command("flutter", &search_path_in(&shared.root), &shared.root));
let executable = (shared.executable)().or_else(|| flutter_executable(&shared.root));
let Some(executable) = executable else {
return finish(shared, generation, FlutterDaemonStatus::NotInstalled);
};
+218
View File
@@ -0,0 +1,218 @@
//! A Flutter tool serving pages for the IDE to embed, one per project window, started when first
//! asked for. It reports its address on stdout. A server that fails or exits is not restarted on
//! its own: the next request starts a new one.
use crate::{KILL_GRACE, OUTPUT_TAIL, keep_output, read_lines, spawn_watched};
use ide_core::process::{kill_tree, terminate_tree};
use parking_lot::{Condvar, Mutex};
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::process::Child;
use std::sync::Arc;
use std::time::{Duration, Instant};
/// What one line of the tool's output says.
pub(crate) enum Line {
/// The page's address: the server is ready.
Url(String),
/// Text worth showing if the server fails.
Output(String),
/// Nothing worth keeping.
Skip,
}
/// How to run one kind of server.
pub(crate) struct Spec {
/// For messages, e.g. "Flutter DevTools".
pub name: &'static str,
pub args: &'static [&'static str],
pub timeout: Duration,
pub executable: fn(&Path) -> Option<PathBuf>,
pub not_found: &'static str,
pub line: fn(&str) -> Line,
/// The failure to report, from the output kept until the tool exited.
pub failed: fn(String) -> String,
}
#[derive(Default)]
enum Status {
#[default]
Stopped,
Starting,
Ready(String),
Failed(String),
}
#[derive(Default)]
struct State {
/// Bumped by every start and stop: a reader of an older process no longer has a say.
generation: u64,
child: Option<Child>,
status: Status,
}
impl State {
fn shut_down(&mut self) {
self.generation += 1;
if let Some(mut child) = self.child.take() {
std::thread::spawn(move || terminate_tree(&mut child, KILL_GRACE));
}
}
}
struct Shared {
root: PathBuf,
spec: &'static Spec,
/// The configured executable; the spec's lookup on the search path without one.
executable: crate::Configured,
timeout: Duration,
state: Mutex<State>,
changed: Condvar,
}
impl Shared {
/// Applies `status` unless this process was replaced or stopped; false if it was.
fn set(&self, generation: u64, status: Status) -> bool {
let mut state = self.state.lock();
if state.generation != generation {
return false;
}
state.status = status;
self.changed.notify_all();
true
}
}
pub struct ToolServer(Arc<Shared>);
impl ToolServer {
pub(crate) fn new(root: PathBuf, spec: &'static Spec, executable: crate::Configured) -> Self {
Self::with_executable(root, spec, executable, spec.timeout)
}
pub(crate) fn with_executable(
root: PathBuf,
spec: &'static Spec,
executable: crate::Configured,
timeout: Duration,
) -> Self {
Self(Arc::new(Shared { root, spec, executable, timeout, state: Mutex::default(), changed: Condvar::new() }))
}
/// The server's address, starting it with `extra` arguments if none runs. Blocks until it is known.
pub fn url(&self, extra: &[String]) -> Result<String, String> {
let shared = &self.0;
let deadline = Instant::now() + shared.timeout;
let mut state = shared.state.lock();
if matches!(state.status, Status::Stopped | Status::Failed(_)) {
state.generation += 1;
state.status = Status::Starting;
let (shared, generation, extra) = (shared.clone(), state.generation, extra.to_vec());
std::thread::spawn(move || run(&shared, generation, &extra));
}
loop {
match &state.status {
Status::Ready(url) => return Ok(url.clone()),
Status::Failed(message) => return Err(message.clone()),
Status::Stopped => return Err(format!("{} was stopped", shared.spec.name)),
Status::Starting => {}
}
if shared.changed.wait_until(&mut state, deadline).timed_out() {
state.shut_down();
let message = format!("{} did not start in time", shared.spec.name);
state.status = Status::Failed(message.clone());
shared.changed.notify_all();
return Err(message);
}
}
}
/// Ends the server (project closed, or no longer trusted).
pub fn stop(&self) {
let mut state = self.0.state.lock();
state.shut_down();
state.status = Status::Stopped;
self.0.changed.notify_all();
}
/// Ends the server before returning, for a process about to exit.
pub fn kill(&self) {
let mut state = self.0.state.lock();
state.generation += 1;
state.status = Status::Stopped;
if let Some(mut child) = state.child.take() {
kill_tree(&mut child);
}
self.0.changed.notify_all();
}
#[cfg(all(test, unix))]
pub(crate) fn is_stopped(&self) -> bool {
matches!(self.0.state.lock().status, Status::Stopped)
}
}
/// One server's whole life, on its own thread.
fn run(shared: &Arc<Shared>, generation: u64, extra: &[String]) {
let spec = shared.spec;
let fail = |message: String| {
shared.set(generation, Status::Failed(message));
};
let Some(executable) = (shared.executable)().or_else(|| (spec.executable)(&shared.root)) else {
return fail(spec.not_found.into());
};
let args: Vec<&str> = spec.args.iter().copied().chain(extra.iter().map(String::as_str)).collect();
let mut child = match spawn_watched(&executable, &args, &shared.root) {
Ok(child) => child,
Err(e) => return fail(format!("could not run {}: {e}", executable.display())),
};
let (Some(stdout), Some(stderr)) = (child.stdout.take(), child.stderr.take()) else {
terminate_tree(&mut child, Duration::ZERO);
return fail("no output pipe".into());
};
{
let mut state = shared.state.lock();
if state.generation != generation {
drop(state);
terminate_tree(&mut child, KILL_GRACE);
return;
}
state.child = Some(child);
}
let tail = Arc::new(Mutex::new(VecDeque::with_capacity(OUTPUT_TAIL)));
let errors = {
let tail = tail.clone();
std::thread::spawn(move || {
read_lines(stderr, |line| {
keep_output(&tail, line);
true
});
})
};
read_lines(stdout, |line| match (spec.line)(line) {
Line::Url(url) => shared.set(generation, Status::Ready(url)),
Line::Output(text) => {
keep_output(&tail, &text);
true
}
Line::Skip => true,
});
let _ = errors.join();
let mut state = shared.state.lock();
if state.generation != generation {
return;
}
let child = state.child.take();
state.status = if matches!(state.status, Status::Ready(_)) {
Status::Stopped
} else {
let message = Vec::from(std::mem::take(&mut *tail.lock())).join("\n");
Status::Failed((spec.failed)(message))
};
shared.changed.notify_all();
drop(state);
if let Some(mut child) = child {
std::thread::spawn(move || terminate_tree(&mut child, Duration::ZERO));
}
}
+118
View File
@@ -0,0 +1,118 @@
//! One `flutter widget-preview` server per project window: the `@Preview` widgets of the project,
//! served as a web page that reloads as they change. Like the Flutter plugins of Android Studio
//! and VS Code it runs on the `web-server` device, in `--machine` mode, where it reports events
//! as bracketed JSON lines and the page's address with `widget_preview.started`. Without
//! `--dtd-url` it starts its own analysis server and Dart Tooling Daemon to find the previews.
use crate::devtools::HOST;
use crate::flutter_executable;
use crate::server::{Line, Spec, ToolServer};
use serde_json::Value;
use std::path::PathBuf;
use std::time::Duration;
/// The release whose `widget-preview start` has the options used here.
const MIN_FLUTTER: &str = "3.38";
static WIDGET_PREVIEW: Spec = Spec {
name: "Flutter Widget Preview",
args: &["widget-preview", "start", "--machine", "--web-server"],
// The first start runs `pub get` and compiles the preview environment.
timeout: Duration::from_secs(300),
executable: flutter_executable,
not_found: "Flutter SDK not found: install Flutter or add it to PATH",
line,
failed,
};
impl ToolServer {
/// `flutter` is the configured one, else the one on the search path.
pub fn widget_preview(root: PathBuf, flutter: crate::Configured) -> Self {
Self::new(root, &WIDGET_PREVIEW, flutter)
}
}
fn line(line: &str) -> Line {
let Ok(Value::Array(messages)) = serde_json::from_str(line.trim()) else {
return Line::Output(line.to_owned());
};
let Some(message) = messages.first() else { return Line::Skip };
let params = &message["params"];
match message["event"].as_str() {
// The server listens on every interface; embedded pages may only come from `HOST`.
Some("widget_preview.started") => params["url"]
.as_str()
.map_or(Line::Skip, |url| Line::Url(url.replacen("//localhost:", &format!("//{HOST}:"), 1))),
Some("widget_preview.logMessage") if matches!(params["level"].as_str(), Some("error" | "warning")) => {
params["message"].as_str().map_or(Line::Skip, |text| Line::Output(text.to_owned()))
}
_ => Line::Skip,
}
}
fn failed(message: String) -> String {
// What an older `flutter` says of a command or an option it doesn't know.
if message.contains("Could not find a") && message.contains(" named \"") {
format!(
"Flutter Widget Preview needs Flutter {MIN_FLUTTER} or later. Upgrade Flutter, then refresh the window."
)
} else if message.is_empty() {
"flutter widget-preview exited".into()
} else {
message
}
}
#[cfg(test)]
mod tests {
use super::*;
fn url(line: &str) -> Option<String> {
match super::line(line) {
Line::Url(url) => Some(url),
_ => None,
}
}
fn output(line: &str) -> Option<String> {
match super::line(line) {
Line::Output(text) => Some(text),
_ => None,
}
}
#[test]
fn started_gives_the_address_on_the_embeddable_host() {
let line = r#"[{"event":"widget_preview.started","params":{"url":"http://localhost:56207"}}]"#;
assert_eq!(url(line).as_deref(), Some("http://127.0.0.1:56207"));
let launch =
r#"[{"event":"widget_preview.app.webLaunchUrl","params":{"url":"http://localhost:1","launched":false}}]"#;
assert_eq!(url(launch), None);
}
#[test]
fn only_errors_warnings_and_plain_text_are_kept() {
let log = |level: &str| {
format!(r#"[{{"event":"widget_preview.logMessage","params":{{"level":"{level}","message":"m"}}}}]"#)
};
assert_eq!(output(&log("error")).as_deref(), Some("m"));
assert_eq!(output(&log("warning")).as_deref(), Some("m"));
assert_eq!(output(&log("status")), None);
assert_eq!(output(r#"[{"event":"widget_preview.initializing","params":{"pid":1}}]"#), None);
assert_eq!(
output("Could not find a command named \"widget-preview\".").as_deref(),
Some("Could not find a command named \"widget-preview\".")
);
}
#[test]
fn an_older_flutter_is_named_as_the_cause() {
for message in
[r#"Could not find a command named "widget-preview"."#, r#"Could not find an option named "--web-server"."#]
{
assert!(failed(message.into()).starts_with("Flutter Widget Preview needs Flutter 3.38"));
}
assert_eq!(failed("pub get failed".into()), "pub get failed");
assert_eq!(failed(String::new()), "flutter widget-preview exited");
}
}
+121 -9
View File
@@ -27,17 +27,21 @@ pub fn data_dir(identifier: &str) -> Result<PathBuf, String> {
}
/// `$OPENIDEA_LOG_DIR/<identifier>` when set, else `~/Library/Logs/<identifier>` on macOS and
/// `<local data>/<identifier>/logs` elsewhere (Tauri's `app_log_dir`).
/// `logs` in the local data directory elsewhere (Tauri's `app_log_dir`), so a custom location
/// from Settings › System Settings › Caches moves the logs too.
pub fn log_dir(identifier: &str) -> Result<PathBuf, String> {
let os = if cfg!(target_os = "macos") {
dirs::home_dir().map(|home| home.join("Library/Logs").join(identifier))
} else {
dirs::data_local_dir().map(|dir| dir.join(identifier).join("logs"))
};
match std::env::var_os(LOG_ENV).filter(|v| !v.is_empty()) {
Some(var) => resolve_env(LOG_ENV, Some(var), None, identifier),
None => os.ok_or_else(|| "cannot find the log directory".into()),
if let Some(var) = std::env::var_os(LOG_ENV).filter(|v| !v.is_empty()) {
return resolve_env(LOG_ENV, Some(var), None, identifier);
}
if cfg!(target_os = "macos") {
return dirs::home_dir()
.map(|home| home.join("Library/Logs").join(identifier))
.ok_or_else(|| "cannot find the log directory".into());
}
startup_local_data_dir(identifier)
.or_else(|_| local_data_dir(identifier))
.map(|dir| dir.join("logs"))
.map_err(|_| "cannot find the log directory".into())
}
/// The directory under `$<env>` when set (absolute, not created here), else under the OS directory.
@@ -217,6 +221,74 @@ fn apply_custom_migration_in(path: &Path, local: &Path) {
}
}
/// WebView2's profile (localStorage, IndexedDB, cookies) inside the directory the windows
/// are given, which on Windows is the local data directory.
pub const WEBVIEW_PROFILE: &str = "EBWebView";
/// Browser caches in a WebView2 profile: rebuilt on demand, so not copied across volumes.
const WEBVIEW_CACHES: [&str; 6] = ["Cache", "Code Cache", "GPUCache", "DawnCache", "GrShaderCache", "ShaderCache"];
/// Brings WebView2's profile into `local` before the first window opens: from a scheduled
/// move's source (Settings › System Settings › Caches), else from the default directory, where
/// windows kept it before they followed a custom location. Runs synchronously, as a window
/// started meanwhile would create an empty profile; a profile already in `local` is never
/// merged into or replaced, and a failed move leaves the old one in place.
pub fn adopt_webview_profile(identifier: &str, local: &Path) {
let scheduled = migration_path(identifier)
.and_then(|path| fs::read(path).ok())
.and_then(|bytes| serde_json::from_slice::<CustomMigration>(&bytes).ok())
.filter(|job| job.to == local)
.map(|job| job.from);
adopt_webview_profile_from(scheduled.into_iter().chain(local_data_dir(identifier).ok()), local);
}
fn adopt_webview_profile_from(sources: impl IntoIterator<Item = PathBuf>, local: &Path) {
let target = local.join(WEBVIEW_PROFILE);
if target.try_exists().unwrap_or(true) {
return;
}
let Some(source) = sources
.into_iter()
.filter(|dir| dir != local)
.map(|dir| dir.join(WEBVIEW_PROFILE))
.find(|profile| fs::symlink_metadata(profile).is_ok_and(|m| m.is_dir()))
else {
return;
};
let result = fs::create_dir_all(local).and_then(|()| match rename_missing(&source, &target) {
Err(error) if rename_failure(&error) == RenameFailure::Copy => {
let staging = local.join(format!(".migration-{}", uuid::Uuid::new_v4()));
let copied = copy_profile(&source, &staging).and_then(|()| rename_missing(&staging, &target));
if staging.exists() {
let _ = remove_entry(&staging);
}
copied.and_then(|()| remove_entry(&source))
}
other => other,
});
match result {
Ok(()) => tracing::info!(?source, ?target, "moved the WebView profile to the local data directory"),
Err(error) => tracing::warn!(?source, ?target, %error, "cannot move the WebView profile; starting a new one"),
}
}
/// [`copy_tree`] without the profile's browser caches.
fn copy_profile(source: &Path, target: &Path) -> io::Result<()> {
let metadata = fs::symlink_metadata(source)?;
if !metadata.is_dir() {
return copy_tree(source, target);
}
fs::create_dir(target)?;
for entry in fs::read_dir(source)? {
let entry = entry?;
if WEBVIEW_CACHES.iter().any(|name| entry.file_name() == *name) {
continue;
}
copy_profile(&entry.path(), &target.join(entry.file_name()))?;
}
Ok(())
}
/// Entries of a local-data tree that move to a newly chosen directory.
/// Non-relocatable tool installs (virtual environments with absolute interpreter
/// paths) stay behind and are reinstalled on demand, as in `migrate_entries`;
@@ -552,6 +624,46 @@ fn relative_wrapper(text: &str, source: &Path) -> String {
mod tests {
use super::*;
#[test]
fn the_webview_profile_moves_into_a_custom_local_directory_once() {
let tmp = tempfile::tempdir().unwrap();
let (default, custom) = (tmp.path().join("default"), tmp.path().join("custom"));
let storage = default.join(WEBVIEW_PROFILE).join("Default/Local Storage");
fs::create_dir_all(&storage).unwrap();
fs::write(storage.join("leveldb"), "history").unwrap();
adopt_webview_profile_from([default.clone()], &custom);
let moved = custom.join(WEBVIEW_PROFILE).join("Default/Local Storage/leveldb");
assert_eq!(fs::read_to_string(&moved).unwrap(), "history");
assert!(!default.join(WEBVIEW_PROFILE).exists());
// A profile already in place is never replaced by an older one.
fs::create_dir_all(default.join(WEBVIEW_PROFILE)).unwrap();
adopt_webview_profile_from([default.clone()], &custom);
assert!(default.join(WEBVIEW_PROFILE).exists());
assert_eq!(fs::read_to_string(&moved).unwrap(), "history");
}
#[test]
fn the_default_directory_keeps_its_own_profile() {
let tmp = tempfile::tempdir().unwrap();
let profile = tmp.path().join(WEBVIEW_PROFILE);
fs::create_dir_all(&profile).unwrap();
adopt_webview_profile_from([tmp.path().to_path_buf()], tmp.path());
assert!(profile.is_dir());
}
#[test]
fn a_copied_profile_leaves_the_browser_caches_behind() {
let tmp = tempfile::tempdir().unwrap();
let source = tmp.path().join("source");
fs::create_dir_all(source.join("Default/Cache/Cache_Data")).unwrap();
fs::create_dir_all(source.join("Default/IndexedDB")).unwrap();
fs::write(source.join("Default/Cache/Cache_Data/f_1"), "x").unwrap();
fs::write(source.join("Default/IndexedDB/db"), "kept").unwrap();
copy_profile(&source, &tmp.path().join("copy")).unwrap();
assert_eq!(fs::read_to_string(tmp.path().join("copy/Default/IndexedDB/db")).unwrap(), "kept");
assert!(!tmp.path().join("copy/Default/Cache").exists());
}
#[test]
fn config_data_and_log_dirs_follow_the_os_unless_their_variable_is_set() {
let os = Some(PathBuf::from("/os"));
+5
View File
@@ -190,6 +190,8 @@ impl Host {
let sink_for: SinkFactory = diagnostics_store::recording_sink_factory(diagnostics.clone(), sink_for);
let global_settings = SettingsStore::load(&config_dir, None);
let ssh = Arc::new(ide_ssh::SshManager::new(data_dir.join("ssh-passwords.json")));
let migration = ssh.clone();
runtime.spawn_blocking(move || migration.start_password_migration());
ssh.set_configs(global_settings.effective().ssh.configs);
let host = Self {
plugin_host: RwLock::default(),
@@ -399,6 +401,7 @@ impl Host {
project.agents.shutdown();
project.flutter.stop();
project.devtools.stop();
project.widget_preview.stop();
project.notebooks.stop_admission();
// What the closing window started goes with it — the builds and searches it
// asked for, its runs, its shells and its debug sessions — and its language
@@ -528,6 +531,7 @@ impl Host {
for project in self.projects() {
project.flutter.kill();
project.devtools.kill();
project.widget_preview.kill();
}
}
@@ -570,6 +574,7 @@ impl Host {
project.files_events_active.store(false, std::sync::atomic::Ordering::Release);
project.flutter.kill();
project.devtools.kill();
project.widget_preview.kill();
}
for project in &projects {
project.plugin_diagnostics.close();
+4 -2
View File
@@ -33,8 +33,10 @@ fn get_workspace_roots() -> Tool {
"get_workspace_roots",
"Returns the root directories of the IDE workspace: this project and the trusted projects attached to it
in the same window, as absolute paths. A task works in one directory, but its workspace can hold several projects.
Call this when asked about the workspace, project or working directories, and before planning a change that may span
projects. Other tools reach an attached project by its root as `projectPath`.",
Call this before the first project-related operation in a session, and when asked about the workspace, project or
working directories. `projectRoot` is the project this connection serves, the default base for paths; `roots` is
every project in the workspace, the scope to search and read, not a list of projects to change. It doesn't change the
working directory or permissions. Other tools reach an attached project by its root as `projectPath`.",
|call| async move {
let root = call.root().to_path_buf();
let mut roots = vec![root.clone()];
+1
View File
@@ -515,6 +515,7 @@ async fn resolve_jvm_application(
test == Some(true),
policy,
&cancel,
None,
)
.await?;
use ide_lsp::jdtls::JavaBuildStatus;
+12 -2
View File
@@ -717,11 +717,21 @@ pub async fn debug_jvm_memory_classes(
host.debugger.jvm_memory_classes(session).await
}
/// A `Thread.print -l` of the debuggee JVM, or why it cannot be taken.
/// A `Thread.print -l` of the debuggee JVM (with the JSON dump on JDK 21+), or why it cannot be
/// taken.
#[command(trust = trusted)]
pub async fn debug_jvm_thread_dump(host: &Host, window: &str, session: DebugSessionId) -> IdeResult<JvmThreadsResult> {
host.require_trust(window)?;
host.debugger.jvm_thread_dump(session).await
let heap_root = host.heap.root().to_path_buf();
let dir = host.blocking(move || Ok(super::thread_dump::json_dir(&heap_root))).await?;
let result = host.debugger.jvm_thread_dump(session, dir.clone()).await;
let _ = host
.blocking(move || {
super::thread_dump::discard_json_dir(dir);
Ok(())
})
.await;
result
}
/// Up to `limit` live instances of the class in the stopped JVM.
+18 -2
View File
@@ -40,11 +40,27 @@ pub async fn flutter_emulator_launch(host: &Host, window: &str, id: String) -> I
#[command(trust = trusted)]
pub async fn flutter_devtools_url(host: &Host, window: &str) -> IdeResult<String> {
let project = host.project(window)?;
tokio::task::spawn_blocking(move || project.devtools.url())
tokio::task::spawn_blocking(move || project.devtools.url(&[]))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
.map_err(IdeError::unavailable)
}
/// The address of the project's Widget Preview page, its server started on first use with the
/// project's DevTools for its inspector. A server that failed or exited is only started again by
/// the next request.
#[command(trust = trusted)]
pub async fn flutter_widget_preview_url(host: &Host, window: &str) -> IdeResult<String> {
let project = host.project(window)?;
tokio::task::spawn_blocking(move || {
// Without it the tool starts a DevTools of its own.
let devtools = project.devtools.url(&[]).map(|url| format!("--devtools-server-address={url}"));
project.widget_preview.url(&Vec::from_iter(devtools.ok()))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
.map_err(IdeError::unavailable)
}
ide_command::domain!(flutter: flutter_devices, flutter_devices_refresh, flutter_daemon_restart, flutter_emulator_launch,
flutter_devtools_url);
flutter_devtools_url, flutter_widget_preview_url);
+43 -8
View File
@@ -4,9 +4,11 @@ pub(crate) mod cache;
use crate::Host;
use ide_command::command;
use super::Channel;
use super::build::{load, with_profiles, workspace};
use cache::LaunchEvents;
use ide_build::BuildModel;
use ide_build::compile;
use ide_build::compile::{self, BuildEvent};
use ide_core::error::ErrorKind;
use ide_core::settings::Settings;
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
@@ -18,6 +20,8 @@ use std::path::{Path, PathBuf};
/// Builds according to `policy`, then resolves the runtime (or test)
/// classpath and the JDK of the module at `module` (absolute, or relative to the project root).
/// A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first.
/// The build streams its console, messages and progress on `on_event` while it runs; a launch
/// whose build another launch's build joins receives that build's events.
#[command(trust = trusted)]
pub async fn java_resolve_launch(
host: &Host,
@@ -26,12 +30,16 @@ pub async fn java_resolve_launch(
test: bool,
policy: BuildPolicy,
request: RequestId,
on_event: Channel<BuildEvent>,
) -> IdeResult<JavaLaunchInfo> {
// Resources a Gradle build filters or renames are processed by Gradle, replacing the language
// server's plain copies.
host.require_trust(window)?;
let cancel = host.begin_project_request(window, request);
let result = resolve_launch(host, window, module, test, policy, &cancel).await;
let events: LaunchEvents = std::sync::Arc::new(move |event| {
let _ = on_event.send(event);
});
let result = resolve_launch(host, window, module, test, policy, &cancel, Some(events)).await;
host.end_request(request);
result
}
@@ -43,8 +51,15 @@ pub(crate) async fn resolve_launch(
test: bool,
policy: BuildPolicy,
cancel: &CancellationToken,
events: Option<LaunchEvents>,
) -> IdeResult<JavaLaunchInfo> {
let started = std::time::Instant::now();
let progress = |message: &str| {
if let Some(events) = &events {
events(BuildEvent::Progress { message: message.to_owned(), fraction: None });
}
};
progress("Resolving the module");
let project = host.project(window)?;
let module = ide_core::project_roots::resolve(&project.root, &module);
let scope = {
@@ -54,11 +69,11 @@ pub(crate) async fn resolve_launch(
.map_err(|e| IdeError::internal(e.to_string()))??
};
if !project.lsp.java_served_by_jdtls(&module) {
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel).await;
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel, events).await;
}
let scope = std::sync::Arc::new(scope);
let launches = project.java_launches.for_cache(&scope.cache);
let waiting = launches.waiting.add(module.clone(), test, policy);
let waiting = launches.waiting.add(module.clone(), test, policy, events.clone());
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
let build = policy != BuildPolicy::NoBuild;
@@ -90,6 +105,9 @@ pub(crate) async fn resolve_launch(
};
let mut external_build =
if delegated { Some(project.lsp.java_external_build(&module, cancel).await?) } else { None };
if build && !delegated {
progress("Compiling with the Java language server");
}
let mut info = project.lsp.java_launch(&module, test, build && !delegated, full, delegated, cancel).await?;
if info.errors.iter().any(|e| processor_recreated_a_file(&e.message)) {
if build && !delegated && is_maven {
@@ -118,6 +136,11 @@ pub(crate) async fn resolve_launch(
tokio::task::spawn_blocking(move || {
let _external_build = external_build;
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
let on_event = |event: BuildEvent| {
if let Some(events) = &events {
events(event);
}
};
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
// Module outputs the launch runs from a snapshot of: the originals must not come back.
let mut snapshotted = Vec::new();
@@ -130,7 +153,7 @@ pub(crate) async fn resolve_launch(
root,
&model,
&module,
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members },
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members, events: events.clone() },
local_repo.clone(),
&cancel,
)?;
@@ -140,7 +163,7 @@ pub(crate) async fn resolve_launch(
snapshotted = outputs.originals;
copies
} else if external {
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel)?;
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel, &on_event)?;
if let Some(failure) = built.failure {
if policy != BuildPolicy::MakeAndContinueOnErrors {
return Err(IdeError::internal(failure));
@@ -154,6 +177,7 @@ pub(crate) async fn resolve_launch(
};
let mut class_paths: Vec<String> = built.iter().map(|p| p.to_string_lossy().into_owned()).collect();
if delegated {
on_event(BuildEvent::Progress { message: "Resolving the classpath".into(), fraction: None });
// m2e runs inside jdtls on the server JDK and can resolve a different
// Maven profile/classifier than the module build. Ask the same Maven
// process that built the module for its runtime/test dependencies.
@@ -203,6 +227,7 @@ fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
/// build tool compiles it, and the classpath comes from that server, else from Maven.
#[allow(clippy::too_many_arguments)]
async fn resolve_launch_without_jdtls(
host: &Host,
project: &std::sync::Arc<crate::Project>,
@@ -211,18 +236,24 @@ async fn resolve_launch_without_jdtls(
test: bool,
policy: BuildPolicy,
cancel: &CancellationToken,
events: Option<LaunchEvents>,
) -> IdeResult<JavaLaunchInfo> {
let started = std::time::Instant::now();
let scope = std::sync::Arc::new(scope);
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, built) = {
let (scope, module, cancel) = (scope.clone(), module.clone(), cancel.clone());
let (scope, module, cancel, events) = (scope.clone(), module.clone(), cancel.clone(), events.clone());
tokio::task::spawn_blocking(move || {
let model = load_launch_model(&scope);
let on_event = |event: BuildEvent| {
if let Some(events) = &events {
events(event);
}
};
let built = if policy == BuildPolicy::NoBuild {
None
} else {
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel))
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event))
};
(model, built)
})
@@ -254,6 +285,9 @@ async fn resolve_launch_without_jdtls(
}
}
let build_ms = started.elapsed().as_millis();
if let Some(events) = &events {
events(BuildEvent::Progress { message: "Resolving the classpath".into(), fraction: None });
}
let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?;
let data_dir = host.local_data_dir.clone();
let cancel = cancel.clone();
@@ -474,6 +508,7 @@ async fn build_members(
members.push(cache::Member {
module: launch.module.clone(),
rebuild_on_jdt_errors: rebuild_on_jdt_errors(launch.policy, prefer_maven, errors),
events: launch.events.clone(),
});
}
Ok(members)
+61 -19
View File
@@ -1,5 +1,5 @@
//! Immutable Maven outputs retained in the project cache, including across close/reopen.
use ide_build::compile::{self, LaunchFingerprint};
use ide_build::compile::{self, BuildEvent, LaunchFingerprint};
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_run::BuildPolicy;
use parking_lot::Mutex;
@@ -131,6 +131,10 @@ pub(super) fn has_record(root: &Path, cache: &Path, module: &Path) -> bool {
[false, true].into_iter().any(|test| record_path(root, cache, module, test).is_some_and(|record| record.is_file()))
}
/// Where the build of a launch streams its console, messages and progress: the run
/// console, the status bar and the Build tool window of the launch's request.
pub(in crate::ops) type LaunchEvents = Arc<dyn Fn(BuildEvent) + Send + Sync>;
#[derive(Default)]
pub(super) struct BuildOptions {
pub test: bool,
@@ -142,13 +146,15 @@ pub(super) struct BuildOptions {
/// together, #3971): their modules join this Maven run, and their launches then reuse
/// the snapshots recorded here instead of running Maven again.
pub members: Vec<Member>,
/// The launch's own events; members that join the build get them too.
pub events: Option<LaunchEvents>,
}
/// A launch module joining another launch's build; see [`BuildOptions::members`].
#[derive(Debug)]
pub(super) struct Member {
pub module: PathBuf,
pub rebuild_on_jdt_errors: bool,
pub events: Option<LaunchEvents>,
}
/// Launches share a build only within the same workspace project's cache.
@@ -180,11 +186,12 @@ impl Sessions {
#[derive(Default)]
pub(crate) struct Waiting(Arc<Mutex<Vec<Arc<WaitingLaunch>>>>);
#[derive(Debug)]
pub(super) struct WaitingLaunch {
pub module: PathBuf,
pub test: bool,
pub policy: BuildPolicy,
/// The launch's build events, for a build it joins.
pub events: Option<LaunchEvents>,
}
/// Leaves [`Waiting`] when dropped.
@@ -194,8 +201,14 @@ pub(super) struct WaitingGuard {
}
impl Waiting {
pub(super) fn add(&self, module: PathBuf, test: bool, policy: BuildPolicy) -> WaitingGuard {
let launch = Arc::new(WaitingLaunch { module, test, policy });
pub(super) fn add(
&self,
module: PathBuf,
test: bool,
policy: BuildPolicy,
events: Option<LaunchEvents>,
) -> WaitingGuard {
let launch = Arc::new(WaitingLaunch { module, test, policy, events });
self.0.lock().push(launch.clone());
WaitingGuard { all: self.0.clone(), launch }
}
@@ -266,7 +279,7 @@ impl Session {
cancel: &CancellationToken,
) -> IdeResult<Outputs> {
self.initialize();
let BuildOptions { test, policy, rebuild_on_jdt_errors, members } = options;
let BuildOptions { test, policy, rebuild_on_jdt_errors, members, events } = options;
let mut lead = match self.prepare(root, model, module, test, policy, &local_repo, cancel)? {
Ok(outputs) => return Ok(outputs),
Err(pending) => pending,
@@ -284,11 +297,13 @@ impl Session {
let policy = if rebuild_on_jdt_errors { BuildPolicy::Rebuild } else { policy };
let mut joined = Vec::new();
let mut rebuild = policy == BuildPolicy::Rebuild;
let mut sinks: Vec<LaunchEvents> = events.into_iter().collect();
for member in members {
if let Err(pending) =
self.prepare(root, model, &member.module, test, BuildPolicy::Make, &local_repo, cancel)?
{
rebuild |= member.rebuild_on_jdt_errors;
sinks.extend(member.events);
joined.push(pending);
}
}
@@ -298,7 +313,13 @@ impl Session {
tracing::info!(?modules, "Building the launch modules in one Maven run");
}
let kind = if rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let mut built = compile::build_for_launches(root, model, &modules, test, kind, cancel)?.into_iter();
// Every launch waiting for this build follows it.
let on_event = |event: BuildEvent| {
for sink in &sinks {
sink(event.clone());
}
};
let mut built = compile::build_for_launches(root, model, &modules, test, kind, cancel, &on_event)?.into_iter();
let lead_built = built.next().unwrap();
for (pending, built) in joined.into_iter().zip(built) {
match built.failure {
@@ -648,10 +669,31 @@ mod tests {
let mut session = Session::new(root.join("cache"));
let (a, b) = (root.join("a"), root.join("b"));
let with = |rebuild_on_jdt_errors: bool| BuildOptions {
members: vec![Member { module: b.clone(), rebuild_on_jdt_errors }],
members: vec![Member { module: b.clone(), rebuild_on_jdt_errors, events: None }],
..Default::default()
};
let lead = session.build(root, &model, &a, with(false), None, &cancel).unwrap();
// The lead's and the member's launches both follow the shared build.
let seen = Arc::new(Mutex::new(Vec::new()));
let sink = |name: &'static str| -> LaunchEvents {
let seen = seen.clone();
Arc::new(move |event| {
if let BuildEvent::Step { command, .. } = event {
seen.lock().push(format!("{name}: {command}"));
}
})
};
let options = BuildOptions {
members: vec![Member { module: b.clone(), rebuild_on_jdt_errors: false, events: Some(sink("b")) }],
events: Some(sink("a")),
..Default::default()
};
let lead = session.build(root, &model, &a, options, None, &cancel).unwrap();
let seen = seen.lock().clone();
assert_eq!(seen.len(), 2, "{seen:?}");
assert!(
seen[0].starts_with("a: ") && seen[1].starts_with("b: ") && seen[0].contains("-pl a,b -am"),
"{seen:?}"
);
assert_eq!(fs::read_to_string(lead.snapshot.join("0/Main.class")).unwrap(), "a");
assert_eq!(fs::read_to_string(lead.snapshot.join("1/Main.class")).unwrap(), "lib");
// b's own launch runs from the snapshot the shared build recorded for it.
@@ -690,17 +732,17 @@ mod tests {
let root = dir.path();
let model = reactor_fixture(root);
let waiting = Waiting::default();
let lead = waiting.add(root.join("a"), false, BuildPolicy::Automatic);
let lead = waiting.add(root.join("a"), false, BuildPolicy::Automatic, None);
let _guards = [
waiting.add(root.join("b"), false, BuildPolicy::Make),
waiting.add(root.join("lib"), false, BuildPolicy::Automatic),
waiting.add(root.join("b"), false, BuildPolicy::Automatic),
waiting.add(root.join("a"), false, BuildPolicy::Automatic),
waiting.add(root.join("lib"), true, BuildPolicy::Automatic),
waiting.add(root.join("lib"), false, BuildPolicy::Rebuild),
waiting.add(root.join("lib"), false, BuildPolicy::MakeAndContinueOnErrors),
waiting.add(root.join("lib"), false, BuildPolicy::NoBuild),
waiting.add(root.join("other"), false, BuildPolicy::Automatic),
waiting.add(root.join("b"), false, BuildPolicy::Make, None),
waiting.add(root.join("lib"), false, BuildPolicy::Automatic, None),
waiting.add(root.join("b"), false, BuildPolicy::Automatic, None),
waiting.add(root.join("a"), false, BuildPolicy::Automatic, None),
waiting.add(root.join("lib"), true, BuildPolicy::Automatic, None),
waiting.add(root.join("lib"), false, BuildPolicy::Rebuild, None),
waiting.add(root.join("lib"), false, BuildPolicy::MakeAndContinueOnErrors, None),
waiting.add(root.join("lib"), false, BuildPolicy::NoBuild, None),
waiting.add(root.join("other"), false, BuildPolicy::Automatic, None),
];
let join = |prefer_maven| {
super::super::joining_launches(
+27
View File
@@ -413,6 +413,31 @@ pub async fn lsp_signature_help(host: &Host, window: &str, doc: DocId, pos: Pos)
}
}
/// The Flutter Property Editor's arguments of the call at `pos`.
#[command(trust = trusted)]
pub async fn lsp_editable_arguments(
host: &Host,
window: &str,
doc: DocId,
pos: Pos,
) -> IdeResult<Option<EditableArguments>> {
host.project(window)?.lsp.editable_arguments(doc, pos).await
}
/// Sets an argument of the call at `pos`; the edit reaches the document as the server's
/// `workspace/applyEdit`, undoable like any other.
#[command(trust = trusted)]
pub async fn lsp_edit_argument(
host: &Host,
window: &str,
doc: DocId,
pos: Pos,
name: String,
value: Option<ArgumentValue>,
) -> IdeResult<()> {
host.project(window)?.lsp.edit_argument(doc, pos, name, value).await
}
#[command(trust = trusted)]
pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: GotoKind) -> IdeResult<Vec<Location>> {
let target = position_document(host, window, doc, pos).await?;
@@ -3200,6 +3225,8 @@ ide_command::domain!(
lsp_completion,
lsp_document_colors,
lsp_document_highlights,
lsp_edit_argument,
lsp_editable_arguments,
lsp_document_links,
lsp_exception_class_at,
lsp_execute_code_action,
+7
View File
@@ -407,6 +407,13 @@ pub fn set_settings(
if key == "vcs" || key == "vcs.git" || key == "vcs.git.executable" {
host.apply_git_executable();
}
// `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() {
project.flutter.sdk_changed();
project.devtools.stop();
}
}
if is_proxy {
host.apply_proxy();
}
+20 -6
View File
@@ -391,8 +391,10 @@ async fn start_inner(
if config.command.is_empty() {
return Err(IdeError::invalid("run configuration has no command"));
}
let on_target = config.extras.target.as_deref().is_some_and(|t| !t.is_empty());
add_java_agents(&mut config, &on_output, !on_target);
// A JVM on a run target gets no plugin agents; a local one gets them once its JDK is resolved.
if config.extras.target.as_deref().is_some_and(|t| !t.is_empty()) {
add_java_agents(&mut config, &on_output, None);
}
// Settings › Run Targets: over SSH, or in a container.
if config.kind == "tomcat" && config.extras.target.as_deref().is_some_and(|t| !t.is_empty()) {
return Err(IdeError::invalid("Tomcat Local requires the local machine"));
@@ -483,6 +485,8 @@ async fn start_inner(
);
ide_sdk::go::apply_to_run(&mut config, &settings.languages.go.build_tags);
}
let run_dir = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
add_java_agents(&mut config, &on_output, Some(&run_dir));
if config.command == ide_sdk::godot::COMMAND {
return Err(IdeError::unavailable(ide_sdk::godot::NOT_FOUND));
}
@@ -555,14 +559,24 @@ async fn start_inner(
/// 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.
fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, local: bool) {
fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, run_dir: Option<&Path>) {
if !ide_run::java_agent::applies(&config.kind) {
return;
}
let java = std::path::Path::new(&config.command);
let agents = ide_run::java_agent::current_for(Some(java));
// The JVM the launch starts: a bare `java` (what generated configurations name) is looked
// up the way the process start finds it, so the `jdk` filter of `vmOptions` sees that JDK.
let java = run_dir.and_then(|dir| {
let search = ide_run::wrap::search_path_in(config, dir);
let home = config
.env
.get("JAVA_HOME")
.map(std::path::PathBuf::from)
.or_else(|| std::env::var_os("JAVA_HOME").map(std::path::PathBuf::from));
ide_run::java_agent::launched_java(&config.command, &search, home.as_deref())
});
let agents = ide_run::java_agent::current_for(java.as_deref());
let say = |text: &str| on_output(OutputChunk::System { text: format!("{text}\n") });
if !local {
if run_dir.is_none() {
if !agents.options.is_empty() {
say(
"Plugin Java agents were not added: they load only into JVMs started on this machine, not on a run target.",
+22
View File
@@ -470,6 +470,27 @@ pub async fn sdk_jdk_at(path: String) -> IdeResult<Option<Sdk>> {
blocking_value(move || ide_sdk::java::jdk_at(std::path::Path::new(&path)).map(|j| ide_sdk::jdk_sdk(&j))).await
}
/// `flutter --version --machine` of the Flutter SDK at `path`, or of the `flutter` on the
/// search path when `path` is empty; `None` when there is no Flutter SDK.
#[command(trust = trusted)]
pub async fn sdk_flutter_at(
host: &Host,
window: &str,
path: String,
) -> IdeResult<Option<ide_sdk::flutter::FlutterVersion>> {
let root = host.project(window).ok().map(|p| p.root.clone());
blocking_value(move || {
let root = root.unwrap_or_default();
let sdk = match ide_sdk::apply::setting_path(&root, &path) {
Some(sdk) => Some(sdk),
None => ide_core::tool_path::find_command("flutter", &ide_core::tool_path::search_path_in(&root), &root)
.and_then(|f| ide_sdk::flutter::sdk_of(&f)),
};
sdk.and_then(|sdk| ide_sdk::flutter::version(&sdk))
})
.await
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
@@ -628,6 +649,7 @@ mod tests {
ide_command::domain!(
sdk:
sdk_detect,
sdk_flutter_at,
sdk_jdk_at,
sdk_locate_tools,
sdk_php_composer_install,
+21 -3
View File
@@ -4,8 +4,10 @@
//! given belong to the server's [`ide_ssh::SshManager`], not the desktop's.
use crate::Host;
use ide_command::command;
use ide_core::IdeResult;
use ide_core::event::NotifyLevel;
use ide_core::remote_settings::SshConfiguration;
use ide_core::{IdeError, IdeEvent, IdeResult};
use ide_ssh::secrets::LegacyPasswordAction;
/// Test Connection: connects with `config` as edited (not necessarily saved).
#[command(trust = always)]
@@ -15,8 +17,23 @@ pub async fn ssh_test(host: &Host, config: SshConfiguration, secret: Option<Stri
/// Remembers the password / passphrase of configuration `id` (`None` forgets it).
#[command(trust = always)]
pub fn ssh_set_secret(host: &Host, id: String, secret: Option<String>, save: bool) {
host.ssh.set_secret(&id, secret, save);
pub fn ssh_set_secret(host: &Host, window: &str, id: String, secret: Option<String>, save: bool) {
if let Err(e) = host.ssh.set_secret(&id, secret, save) {
host.window_sink(window).emit(IdeEvent::Notify {
level: NotifyLevel::Warning,
title: "Could not save credential".into(),
body: Some(e.message),
});
}
}
/// `Some` means legacy credentials remain in plaintext on this host.
#[command(trust = always)]
pub async fn ssh_legacy_passwords(host: &Host, action: LegacyPasswordAction) -> IdeResult<Option<String>> {
let ssh = host.ssh.clone();
tokio::task::spawn_blocking(move || ssh.resolve_legacy_passwords(action))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Whether a password is saved under `key` (an FTP deployment server's).
@@ -52,6 +69,7 @@ ide_command::domain!(
ssh:
ssh_connected,
ssh_disconnect,
ssh_legacy_passwords,
ssh_needs_secret,
ssh_password_saved,
ssh_set_secret,
+59 -4
View File
@@ -3,6 +3,7 @@ use ide_command::command;
use ide_core::{IdeResult, RunId};
use ide_dap::{JvmMemoryUnavailable, JvmThreadsResult, JvmThreadsUnavailable};
use ide_jvm_attach::{ProcEntry, is_hotspot, process_table, select_run_jvm};
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// A `Thread.print -l` of the JVM a run started: the deepest HotSpot JVM of the run's process
@@ -22,13 +23,43 @@ pub async fn run_jvm_thread_dump(
Ok(pid) => pid,
Err(refused) => return Ok(refused),
};
let heap_root = host.heap.root().to_path_buf();
let dir = host.blocking(move || Ok(json_dir(&heap_root))).await?;
// A debugger attached to this run or JVM (Debug of a build tool's run, Attach to Process)
// may hold it suspended, which only its session knows.
if let Some(dump) = host.debugger.debugged_jvm_thread_dump(id, pid).await {
return dump;
let result = match host.debugger.debugged_jvm_thread_dump(id, pid, dir.clone()).await {
Some(dump) => dump,
None => {
let json = dir.clone();
// The attach handshake blocks for seconds.
host.blocking(move || Ok(ide_dap::run_jvm_thread_dump(pid, json.as_deref()))).await
}
};
let _ = host
.blocking(move || {
discard_json_dir(dir);
Ok(())
})
.await;
result
}
/// A fresh owner-only directory for the JVM's JSON dump under the heap snapshot root, whose
/// stale-directory sweep also removes a file a JVM writes after its request timed out. `None`
/// when it cannot be created: the dump then goes without virtual threads.
pub(crate) fn json_dir(heap_root: &Path) -> Option<PathBuf> {
ide_heap::create_snapshot_dir(heap_root)
.inspect_err(|e| tracing::warn!("no directory for the JSON thread dump under {}: {e}", heap_root.display()))
.ok()
}
pub(crate) fn discard_json_dir(dir: Option<PathBuf>) {
if let Some(dir) = dir
&& let Err(e) = std::fs::remove_dir_all(&dir)
&& e.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!("could not delete thread dump directory {}: {e}", dir.display());
}
// The attach handshake blocks for seconds.
host.blocking(move || Ok(ide_dap::run_jvm_thread_dump(pid))).await
}
fn unavailable(reason: JvmThreadsUnavailable) -> JvmThreadsResult {
@@ -100,6 +131,30 @@ mod tests {
assert_eq!(run_jvm(false, Some(10), None, table, |pid| pid == 11), Ok(11));
}
#[cfg(unix)]
#[test]
fn json_dir_is_private_and_removed_afterwards() {
use std::os::unix::fs::PermissionsExt;
let root = tempfile::tempdir().unwrap();
let heap_root = root.path().join("heap-snapshots");
let dir = json_dir(&heap_root).expect("a directory");
assert_eq!(dir.parent(), Some(heap_root.as_path()));
assert_eq!(std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777, 0o700);
// A file the JVM wrote after its request timed out goes with the directory.
std::fs::write(dir.join("threads-1-2.json"), "{}").unwrap();
discard_json_dir(Some(dir.clone()));
assert!(!dir.exists());
discard_json_dir(None);
}
#[test]
fn json_dir_is_none_when_it_cannot_be_created() {
let root = tempfile::tempdir().unwrap();
let blocked = root.path().join("file");
std::fs::write(&blocked, "").unwrap();
assert_eq!(json_dir(&blocked), None);
}
#[cfg(not(unix))]
#[test]
fn unsupported_without_reading_the_process_table() {
+29 -5
View File
@@ -68,7 +68,9 @@ pub struct Project {
/// Flutter's devices; its daemon starts when the UI first asks for them.
pub(crate) flutter: ide_flutter::FlutterDaemon,
/// Flutter DevTools; its server starts when the UI first asks for it.
pub(crate) devtools: ide_flutter::DevToolsServer,
pub(crate) devtools: ide_flutter::ToolServer,
/// Flutter Widget Preview; its server starts when its tool window first opens.
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) watcher: Arc<Watcher>,
@@ -644,8 +646,16 @@ impl Host {
let project = Arc::new(Project {
plugin_diagnostics,
trusted,
flutter: ide_flutter::FlutterDaemon::new(root.clone(), sink.clone()),
devtools: ide_flutter::DevToolsServer::new(root.clone()),
flutter: ide_flutter::FlutterDaemon::new(
root.clone(),
sink.clone(),
flutter_tool(&root, &settings, "flutter"),
),
devtools: ide_flutter::ToolServer::devtools(root.clone(), flutter_tool(&root, &settings, "dart")),
widget_preview: ide_flutter::ToolServer::widget_preview(
root.clone(),
flutter_tool(&root, &settings, "flutter"),
),
root,
sink,
languages,
@@ -895,8 +905,16 @@ impl Host {
let project = Arc::new(Project {
plugin_diagnostics,
trusted: Arc::new(AtomicBool::new(false)),
flutter: ide_flutter::FlutterDaemon::new(dir.clone(), sink.clone()),
devtools: ide_flutter::DevToolsServer::new(dir.clone()),
flutter: ide_flutter::FlutterDaemon::new(
dir.clone(),
sink.clone(),
flutter_tool(&dir, &settings, "flutter"),
),
devtools: ide_flutter::ToolServer::devtools(dir.clone(), flutter_tool(&dir, &settings, "dart")),
widget_preview: ide_flutter::ToolServer::widget_preview(
dir.clone(),
flutter_tool(&dir, &settings, "flutter"),
),
sink,
languages,
settings,
@@ -1024,6 +1042,12 @@ fn light_watcher(
)
}
/// `flutter` / `dart` as Settings › Flutter chooses them, read each time the daemon or DevTools starts.
fn flutter_tool(root: &Path, settings: &Arc<SettingsStore>, command: &'static str) -> ide_flutter::Configured {
let (root, settings) = (root.to_path_buf(), settings.clone());
Box::new(move || ide_sdk::apply::tool_command(&root, &settings.effective(), command))
}
/// Looks for repositories nested below the project (and the one containing it);
/// emits `VcsChanged` when the set of roots changed.
fn scan_repositories(
+1
View File
@@ -287,6 +287,7 @@ impl crate::Host {
project.agents.shutdown();
project.flutter.stop();
project.devtools.stop();
project.widget_preview.stop();
self.processes.kill_project(&project.root);
project.notebooks.restrict().await;
let windows: Vec<_> = self
+20
View File
@@ -2,6 +2,26 @@ mod common;
use ide_host::{Host, HostConfig, ops};
#[tokio::test]
async fn startup_moves_legacy_ssh_credentials_without_opening_a_project_or_connection() {
use ide_ssh::secrets::testing::{files_containing, use_memory_store};
use_memory_store();
let tmp = tempfile::tempdir().unwrap();
let config = common::host_config(tmp.path());
std::fs::create_dir_all(&config.data_dir).unwrap();
std::fs::write(config.data_dir.join("ssh-passwords.json"), r#"{"box":"legacy-fixture"}"#).unwrap();
let host = Host::new(config);
tokio::time::timeout(std::time::Duration::from_secs(5), async {
while !files_containing(tmp.path(), "legacy-fixture").is_empty() {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.expect("startup migration");
assert_eq!(host.ssh.password("box").as_deref(), Some("legacy-fixture"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn split_storage_keeps_user_history_and_uses_local_tools_and_caches() {
let tmp = tempfile::tempdir().unwrap();
+2 -1
View File
@@ -136,7 +136,8 @@ async fn ssh_server(home: &Path, server_home: &Path, project: &Path) -> Arc<ide_
save_secret: true,
..Default::default()
}]);
ssh.set_secret("local-test", Some("secret".into()), true);
ide_ssh::secrets::testing::use_memory_store();
ssh.set_secret("local-test", Some("secret".into()), true).unwrap();
assert!(ssh.session("local-test").await.is_err(), "unknown host key first");
ssh.trust_host("local-test").await.unwrap();
ssh.session("local-test").await.unwrap()
+26 -1
View File
@@ -10,6 +10,30 @@ use std::path::Path;
use std::sync::{Arc, Mutex, mpsc};
use std::time::Duration;
#[tokio::test]
async fn a_failed_credential_save_warns_the_window_but_keeps_the_session_password() {
let tmp = tempfile::tempdir().unwrap();
let config = common::host_config(tmp.path());
std::fs::create_dir_all(config.data_dir.join("ssh-passwords.json")).unwrap();
let (tx, rx) = mpsc::channel();
let host = Host::new(HostConfig {
sink_for: Box::new(move |_| {
let tx = tx.clone();
Arc::new(move |e| tx.send(e).unwrap())
}),
..config
});
ide_host::ops::ssh::ssh_set_secret(&host, "main", "box".into(), Some("test-value".into()), true);
let warning = rx.try_iter().find_map(|e| match e {
IdeEvent::Notify { level: ide_core::event::NotifyLevel::Warning, body, .. } => body,
_ => None,
});
let warning = warning.expect("the window should be told saving failed");
assert!(warning.contains("session only"));
assert!(!warning.contains("test-value"));
assert_eq!(host.ssh.password("box").as_deref(), Some("test-value"));
}
fn read_until(rx: &mpsc::Receiver<String>, needle: &str) -> String {
let mut all = String::new();
while !all.contains(needle) {
@@ -38,7 +62,8 @@ async fn host_with_ssh_box(tmp: &Path, exec: ide_ssh::testing::ExecFn) -> (Arc<H
save_secret: true,
..Default::default()
}]);
ssh.set_secret("box", Some("secret".into()), true);
ide_ssh::secrets::testing::use_memory_store();
ssh.set_secret("box", Some("secret".into()), true).unwrap();
assert!(ssh.session("box").await.is_err(), "unknown host key first");
ssh.trust_host("box").await.unwrap();
+1 -1
View File
@@ -80,7 +80,7 @@ async fn welcome_window_browses_selected_ssh_host_without_executing_commands() {
auth: SshAuth::Password,
..Default::default()
}]);
ssh.set_secret("selected-host", Some("secret".into()), false);
ssh.set_secret("selected-host", Some("secret".into()), false).unwrap();
assert!(ssh.session("selected-host").await.is_err());
ssh.trust_host("selected-host").await.unwrap();
+21 -4
View File
@@ -85,9 +85,26 @@ done
for (index, root) in roots.into_iter().enumerate() {
let module = if root == &sibling { root.join("app") } else { root.strip_prefix(&primary).unwrap().join("app") };
let test = index != 0;
let info = ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next())
.await
.unwrap();
let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let sink = events.clone();
let channel = ops::Channel::new(move |event: ide_build::compile::BuildEvent| sink.lock().unwrap().push(event));
let info =
ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next(), channel)
.await
.unwrap();
// The build streams its command and progress while it runs.
use ide_build::compile::BuildEvent;
let events = events.lock().unwrap();
assert!(
events.iter().any(|e| matches!(e, BuildEvent::Step { command, .. } if command.contains("-pl app -am"))),
"{events:?}"
);
assert!(
events
.iter()
.any(|e| matches!(e, BuildEvent::Progress { message, .. } if message == "Resolving the classpath")),
"{events:?}"
);
let out = root.join("app/target").join(if test { "test-classes" } else { "classes" });
let jar = root.join("app").join(if test { "test.jar" } else { "runtime.jar" });
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
@@ -95,7 +112,7 @@ done
let calls = fs::read_to_string(root.join("calls")).unwrap();
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
assert!(calls.contains("dependency:build-classpath"), "{calls}");
assert!(calls.contains(":build-classpath"), "{calls}");
}
}
+12
View File
@@ -305,6 +305,18 @@ impl PathFilter {
builder.build().flatten().filter(|e| e.file_type().is_some_and(|t| t.is_dir())).map(|e| e.into_path()).collect()
}
/// The folders directly in `dir` that the index would walk.
pub(crate) fn child_dirs(&self, dir: &Path) -> Vec<PathBuf> {
let Some(mut builder) = self.walker(dir) else { return Vec::new() };
builder
.max_depth(Some(1))
.build()
.flatten()
.filter(|e| e.depth() == 1 && e.file_type().is_some_and(|t| t.is_dir()))
.map(|e| e.into_path())
.collect()
}
pub(crate) fn directories_with_names(&self, names: &HashSet<&OsStr>) -> Vec<PathBuf> {
let matches = parking_lot::Mutex::new(Vec::new());
for root in self.roots() {
+7
View File
@@ -26,6 +26,12 @@ pub use filter::walk_skips;
pub use worker::MAX_SYMBOL_FILE;
use worker::{Job, MAX_RECENT, Shared};
/// Stack of the indexing threads. Parsing and outlining a deeply nested file (generated
/// code, a big JSON or minified script) recurse as deep as the file nests; the 2 MiB a Rust
/// thread gets by default overflowed on Windows and took the whole IDE down (#5739). Only
/// what a thread touches is committed, so the reservation costs address space, not memory.
const INDEX_STACK: usize = 32 * 1024 * 1024;
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FileMatch {
@@ -150,6 +156,7 @@ impl ProjectIndex {
let shared = shared.clone();
std::thread::Builder::new()
.name("openidea-index".into())
.stack_size(INDEX_STACK)
.spawn(move || shared.run(scan))
.map_err(|e| ide_core::IdeError::internal(format!("cannot start indexer: {e}")))?
};
+63
View File
@@ -1246,3 +1246,66 @@ fn queries_during_streaming_scan_do_not_deadlock() {
done_rx.recv_timeout(Duration::from_secs(60)).expect("concurrent index queries deadlocked with streaming scan");
}
#[test]
fn reconciling_a_few_changed_files_does_not_show_indexing() {
let fx = sample();
let events = Arc::new(Mutex::new(Vec::new()));
let sink: SharedSink = {
let events = events.clone();
Arc::new(move |e: IdeEvent| events.lock().push(e))
};
let idx = fx.open_with(sink);
let announced = |events: &Mutex<Vec<IdeEvent>>| {
events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::IndexState { indexing: true, .. } | IdeEvent::Task { done: false, .. }))
.count()
};
let settle = || {
assert!(idx.wait_idle(WAIT));
// The touched folders are reconciled once the snapshot delay has passed.
std::thread::sleep(Duration::from_millis(300));
assert!(idx.wait_idle(WAIT));
};
// A program appending to its log in the project, as a debugged Spring app does.
events.lock().clear();
let log = fx.write("logs/app.log", "start\n");
for i in 0..3 {
std::fs::write(&log, format!("line {i}\n").repeat(i + 1)).unwrap();
idx.update(std::slice::from_ref(&log), &[]);
settle();
}
assert_eq!(announced(&events), 0, "a log being written must not show Indexing");
assert!(files(&idx, "app.log").contains(&"logs/app.log".to_owned()), "the log is still indexed");
}
/// #5749: a file at the project root changing must not re-walk the whole project when the
/// touched folders are reconciled, yet folders that appear or vanish there are still picked up.
#[test]
fn reconciling_a_root_change_lists_only_that_folder() {
let fx = sample();
let idx = fx.open();
// Written behind the index's back, deep in a folder it already knows.
fx.write("src/order/Unreported.java", "class Unreported {}\n");
// A new folder, a vanished one and an unreported file next to the changed root file.
fx.write("fresh/deep/Fresh.java", "class Fresh {}\n");
std::fs::remove_dir_all(fx.root.join("docs")).unwrap();
fx.write("Unlisted.txt", "x\n");
let log = fx.write("app.log", "line\n");
idx.update(std::slice::from_ref(&log), &[]);
assert!(idx.wait_idle(WAIT));
// The touched folders are reconciled once the snapshot delay has passed.
std::thread::sleep(Duration::from_millis(300));
assert!(idx.wait_idle(WAIT));
assert!(files(&idx, "app.log").contains(&"app.log".to_owned()), "the changed file is indexed");
assert!(files(&idx, "Unlisted").contains(&"Unlisted.txt".to_owned()), "the root folder is listed");
assert!(files(&idx, "Fresh").contains(&"fresh/deep/Fresh.java".to_owned()), "a new folder is walked");
assert!(files(&idx, "maintenance").is_empty(), "a vanished folder's files are dropped");
assert!(files(&idx, "main.rs").contains(&"src/main.rs".to_owned()), "other folders keep their files");
assert!(files(&idx, "Unreported").is_empty(), "known subfolders are not re-walked");
}
+128 -32
View File
@@ -22,6 +22,7 @@ use std::time::{Duration, Instant, SystemTime};
static INDEX_POOL: LazyLock<rayon::ThreadPool> = LazyLock::new(|| {
rayon::ThreadPoolBuilder::new()
.thread_name(|i| format!("openidea-index-{i}"))
.stack_size(crate::INDEX_STACK)
.build()
.expect("cannot build index thread pool")
});
@@ -36,6 +37,15 @@ const PROGRESS_EVERY: Duration = Duration::from_millis(250);
const SNAPSHOT_DELAY: Duration = Duration::from_secs(2);
#[cfg(test)]
const SNAPSHOT_DELAY: Duration = Duration::from_millis(50);
/// The shortest gap between two snapshot refreshes. Any index write drops the snapshot (see
/// `Store::apply`), so a later refresh only makes the next startup faster; a project whose files
/// keep changing (a log written inside it) would otherwise rewrite it every couple of seconds.
#[cfg(not(test))]
const SNAPSHOT_EVERY: Duration = Duration::from_secs(10);
#[cfg(test)]
const SNAPSHOT_EVERY: Duration = Duration::ZERO;
/// A subtree scan with fewer files to parse runs without showing "Indexing" (see `scan`).
const QUIET_SCAN_FILES: usize = 200;
pub(crate) const MAX_RECENT: usize = 50;
pub(crate) enum Job {
@@ -75,6 +85,8 @@ pub(crate) struct Shared {
idle: Condvar,
/// Coalesced post-update snapshot refresh.
snapshot_due: Mutex<Option<Instant>>,
/// When the snapshot was last refreshed (see [`SNAPSHOT_EVERY`]).
snapshot_saved: Mutex<Option<Instant>>,
/// Directories whose watcher events still need reconciliation before a
/// refreshed snapshot can be trusted.
pending_dirs: Mutex<HashSet<PathBuf>>,
@@ -103,6 +115,7 @@ impl Shared {
wake: Condvar::new(),
idle: Condvar::new(),
snapshot_due: Mutex::default(),
snapshot_saved: Mutex::default(),
pending_dirs: Mutex::default(),
}
}
@@ -444,7 +457,8 @@ impl Shared {
}
/// A cancelled scan (project closed) still ends its progress task and the indexing state.
fn end_scan(&self, task: TaskId) {
fn end_scan(&self, task: Option<TaskId>) {
let Some(task) = task else { return };
self.indexing.store(false, Ordering::SeqCst);
self.sink.emit(IdeEvent::Task {
id: task,
@@ -471,13 +485,13 @@ impl Shared {
}
fn full_scan(&self, found: Option<Vec<Found>>, guard: SystemTime) {
self.scan(None, found, guard);
self.scan(None, &[], found, guard);
// Parsing every file churns through far more memory than the index keeps.
ide_core::memory::release_free_pages();
}
fn scan(&self, dirs: Option<&[PathBuf]>, prewalked: Option<Vec<Found>>, guard: SystemTime) -> Option<ScanCounts> {
let started = Instant::now();
/// Shows "Indexing" (the status flag and a background task) for a scan.
fn start_scan(&self) -> TaskId {
self.indexing.store(true, Ordering::SeqCst);
self.emit_state();
let task = TaskId::next();
@@ -489,6 +503,25 @@ impl Shared {
done: false,
cancellable: false,
});
task
}
/// A full scan shows "Indexing" from the start. A subtree scan (folders the watcher reported,
/// reconciled after each burst of changes) shows it only once it has
/// [`QUIET_SCAN_FILES`] or more files to parse: a program writing its log inside the project
/// would otherwise keep "Indexing" in the status bar for as long as it runs.
///
/// Indexed files the walk didn't see are dropped when they are below one of `dirs` (all of
/// them for a full scan) or directly in one of `shallow`.
fn scan(
&self,
dirs: Option<&[PathBuf]>,
shallow: &[PathBuf],
prewalked: Option<Vec<Found>>,
guard: SystemTime,
) -> Option<ScanCounts> {
let started = Instant::now();
let mut task = dirs.is_none().then(|| self.start_scan());
let filter = self.filter();
let walk_started = Instant::now();
@@ -507,7 +540,10 @@ impl Shared {
found.iter().filter_map(|f| prev_hash_if_stale(&d, f).map(|h| (f, h))).collect();
let stale: Vec<PathBuf> = d
.paths()
.filter(|p| dirs.is_none_or(|dirs| dirs.iter().any(|dir| p.starts_with(dir))))
.filter(|p| {
dirs.is_none_or(|dirs| dirs.iter().any(|dir| p.starts_with(dir)))
|| p.parent().is_some_and(|parent| shallow.iter().any(|dir| dir == parent))
})
.filter(|p| !seen.contains(p.as_path()))
.cloned()
.collect();
@@ -524,6 +560,9 @@ impl Shared {
self.persist(&[], &stale, false);
let total = todo.len();
if task.is_none() && total >= QUIET_SCAN_FILES {
task = Some(self.start_scan());
}
let update_started = Instant::now();
let mut laps = ChunkLaps::default();
{
@@ -564,7 +603,9 @@ impl Shared {
}
done += batch.len();
laps.add(self.publish(batch.drain(..)));
if last_progress.elapsed() >= PROGRESS_EVERY {
if let Some(task) = task
&& last_progress.elapsed() >= PROGRESS_EVERY
{
last_progress = Instant::now();
self.sink.emit(IdeEvent::Task {
id: task,
@@ -606,15 +647,19 @@ impl Shared {
}
let snapshot_elapsed = snapshot_started.elapsed();
*self.snapshot_due.lock() = None;
self.indexing.store(false, Ordering::SeqCst);
self.sink.emit(IdeEvent::Task {
id: task,
title: "Indexing".into(),
message: None,
fraction: Some(1.0),
done: true,
cancellable: false,
});
*self.snapshot_saved.lock() = Some(Instant::now());
if let Some(task) = task {
self.indexing.store(false, Ordering::SeqCst);
self.sink.emit(IdeEvent::Task {
id: task,
title: "Indexing".into(),
message: None,
fraction: Some(1.0),
done: true,
cancellable: false,
});
}
// The counts may have changed either way.
self.emit_state();
if self.is_cancelled() {
return None;
@@ -757,17 +802,67 @@ impl Shared {
}
let mut due = self.snapshot_due.lock();
if due.is_none() {
*due = Some(Instant::now() + SNAPSHOT_DELAY);
let soonest = self.snapshot_saved.lock().map(|saved| saved + SNAPSHOT_EVERY);
*due = Some((Instant::now() + SNAPSHOT_DELAY).max(soonest.unwrap_or(Instant::now())));
}
}
/// Reconciles the folders the watcher reported since the last snapshot, then refreshes it.
/// A folder the index already has files below is listed one level deep: its own files, plus
/// any subfolder that appeared (walked whole) or is gone (its files dropped). A folder it
/// knows nothing below is walked whole. Walking known folders whole would re-read the entire
/// project after every change to a file at its root.
fn reconcile(&self, dirs: &[PathBuf]) {
let filter = self.filter();
// The subfolders each reported folder has indexed files in; absent when it has none.
let mut known: HashMap<&Path, HashSet<PathBuf>> = HashMap::new();
{
let d = self.data.read();
for path in d.paths() {
for dir in dirs {
let Ok(rest) = path.strip_prefix(dir) else { continue };
let subdirs = known.entry(dir.as_path()).or_default();
let mut parts = rest.components();
if let (Some(first), Some(_)) = (parts.next(), parts.next()) {
subdirs.insert(dir.join(first));
}
}
}
}
let mut found = Vec::new();
let mut trees = Vec::new();
let mut shallow = Vec::new();
for dir in dirs {
let Some(indexed) = known.get(dir.as_path()) else {
found.extend(filter.walk(dir, &self.cancelled));
trees.push(dir.clone());
continue;
};
found.extend(filter.list_dir(dir));
shallow.push(dir.clone());
for sub in filter.child_dirs(dir) {
if !indexed.contains(&sub) {
found.extend(filter.walk(&sub, &self.cancelled));
trees.push(sub);
}
}
// Gone from disk; a subfolder only hidden from the listing (an extra content root
// or a newly excluded folder) is handled by its own root or the rule-change rescan.
trees.extend(indexed.iter().filter(|sub| std::fs::symlink_metadata(sub).is_err()).cloned());
}
// Reported folders may nest; parse each file once.
let mut unique = HashSet::new();
found.retain(|f| unique.insert(f.path.clone()));
self.scan(Some(&trees), &shallow, Some(found), SystemTime::now());
}
fn save_snapshot_now(&self) {
let dirs: Vec<PathBuf> = self.pending_dirs.lock().drain().collect();
if !dirs.is_empty() {
// Reconcile the directories touched since the last scan before
// recording their mtimes; otherwise a missed watcher event could be
// blessed into the manifest.
self.scan(Some(&dirs), None, SystemTime::now());
self.reconcile(&dirs);
return;
}
if let Some(store) = &self.store {
@@ -779,6 +874,7 @@ impl Shared {
}
}
*self.snapshot_due.lock() = None;
*self.snapshot_saved.lock() = Some(Instant::now());
}
fn persist(&self, puts: &[(String, FileRecord)], deletes: &[String], durable: bool) {
@@ -884,7 +980,7 @@ impl Shared {
}
}
if !rescan {
self.scan(Some(&roots), None, SystemTime::now());
self.scan(Some(&roots), &[], None, SystemTime::now());
changed.retain(|p| !roots.iter().any(|root| p.starts_with(root)));
removed.retain(|p| !roots.iter().any(|root| p.starts_with(root)));
}
@@ -1174,7 +1270,7 @@ mod metric_tests {
batch.extend([sub.join(format!("f{i}.txt")), sub, root.join("gone")]);
}
std::fs::write(root.join("keep.txt"), "x").unwrap();
shared.scan(None, None, SystemTime::now()).unwrap();
shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!(shared.data.read().file_count, 41);
std::fs::remove_dir_all(root.join("gone")).unwrap();
@@ -1198,7 +1294,7 @@ mod metric_tests {
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, "x").unwrap();
}
shared.scan(None, None, SystemTime::now()).unwrap();
shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!(shared.data.read().file_count, 7);
std::fs::remove_dir_all(root.join("gone")).unwrap();
@@ -1233,11 +1329,11 @@ mod metric_tests {
for i in 0..count {
std::fs::write(root.join(format!("file_{i}.unknown")), "plain").unwrap();
}
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
let cold = shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (count, 0, count));
assert_eq!(cold.outcomes, ExtractionCounts { unsupported: count, ..Default::default() });
assert_eq!(shared.data.read().file_count as usize, count);
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
let hot = shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (count, count, 0));
assert_eq!(hot.outcomes.total(), 0);
}
@@ -1249,7 +1345,7 @@ mod metric_tests {
let shared = shared(&root);
let path = root.join("main.rs");
std::fs::write(&path, "fn main() {}").unwrap();
shared.scan(None, None, SystemTime::now()).unwrap();
shared.scan(None, &[], None, SystemTime::now()).unwrap();
let (found, hash) = {
let data = shared.data.read();
let e = data.get(&path).unwrap();
@@ -1269,10 +1365,10 @@ mod metric_tests {
let path = root.join("main.rs");
std::fs::write(&path, "fn main() {}\n").unwrap();
let shared = shared(&root);
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
let cold = shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (1, 0, 1));
assert_eq!(cold.outcomes, ExtractionCounts { symbol_extractions: 1, ..Default::default() });
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
let hot = shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (1, 1, 0));
assert_eq!(hot.outcomes, ExtractionCounts::default());
// Force a metadata mismatch without a timestamp-resolution-dependent sleep.
@@ -1283,7 +1379,7 @@ mod metric_tests {
rec.mtime = rec.mtime.wrapping_add(1);
let (entry, symbols) = FileEntry::new(path.clone(), "main.rs".into(), rec);
shared.data.write().insert(entry, symbols);
let touched = shared.scan(None, None, SystemTime::now()).unwrap();
let touched = shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!((touched.discovered, touched.metadata_reused, touched.scheduled), (1, 0, 1));
assert_eq!(touched.outcomes, ExtractionCounts { hash_reused: 1, ..Default::default() });
assert_eq!(shared.data.read().symbol_count, 1);
@@ -1339,13 +1435,13 @@ mod metric_tests {
{
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
assert_eq!(index.scan(None, &[], None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
}
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
let found = index.walk_roots(None);
index.load_persisted(&found);
let counts = index.scan(None, Some(found), SystemTime::now()).unwrap();
let counts = index.scan(None, &[], Some(found), SystemTime::now()).unwrap();
assert_eq!((counts.discovered, counts.metadata_reused, counts.scheduled), (1, 1, 0));
assert_eq!(counts.outcomes, ExtractionCounts::default());
assert_eq!(index.data.read().symbol_count, 1);
@@ -1362,7 +1458,7 @@ mod metric_tests {
{
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
assert_eq!(index.scan(None, &[], None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
}
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
@@ -1411,7 +1507,7 @@ mod metric_tests {
{
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
index.scan(None, None, SystemTime::now()).unwrap();
index.scan(None, &[], None, SystemTime::now()).unwrap();
}
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
@@ -1462,7 +1558,7 @@ mod metric_tests {
});
index
});
assert!(index.scan(None, None, SystemTime::now()).is_none());
assert!(index.scan(None, &[], None, SystemTime::now()).is_none());
assert!(index.is_cancelled());
assert!(!index.indexing.load(Ordering::Relaxed));
assert_eq!(index.data.read().file_count, 1);
@@ -1473,7 +1569,7 @@ mod metric_tests {
let dir = tempfile::tempdir().unwrap();
let shared = shared(dir.path());
shared.cancel();
assert!(shared.scan(None, None, SystemTime::now()).is_none());
assert!(shared.scan(None, &[], None, SystemTime::now()).is_none());
assert!(!shared.indexing.load(Ordering::Relaxed));
}
}
+8 -3
View File
@@ -18,11 +18,16 @@ const DUMP_BASE_TIMEOUT: Duration = Duration::from_secs(30);
/// Only `-all` and a quoted path: any argument the DCmd rejects while the VM is suspended
/// hangs the attach listener (17/21/25) until resume, and so does an unquoted path with a space.
pub fn heap_dump_command(path: &Path) -> Result<String, AttachError> {
let text = path.to_str().ok_or_else(|| AttachError::Protocol(format!("heap dump path {path:?} is not UTF-8")))?;
Ok(format!("GC.heap_dump -all {}", quoted_path(path, "heap dump")?))
}
/// `path` in double quotes, as a DCmd argument; `what` names the file in errors.
pub(crate) fn quoted_path(path: &Path, what: &str) -> Result<String, AttachError> {
let text = path.to_str().ok_or_else(|| AttachError::Protocol(format!("{what} path {path:?} is not UTF-8")))?;
if text.contains(['"', '\0', '\n', '\r']) {
return Err(AttachError::Protocol(format!("heap dump path {text:?} cannot be quoted for the JVM")));
return Err(AttachError::Protocol(format!("{what} path {text:?} cannot be quoted for the JVM")));
}
Ok(format!("GC.heap_dump -all \"{text}\""))
Ok(format!("\"{text}\""))
}
/// The JVM answers result code 0 for IO failures too, so success is told apart by its text.
+2 -1
View File
@@ -20,5 +20,6 @@ pub use listener::{LISTENER_START_TIMEOUT, ensure_listener, is_hotspot};
pub use properties::{jdwp_port, parse_properties};
pub use socket::{AttachError, MAX_OUTPUT, agent_properties, has_listener, jcmd, temp_dir};
pub use threads::{
ProcEntry, RUN_TOKEN_PROPERTY, THREAD_DUMP_TIMEOUT, is_application_jvm, process_table, select_run_jvm, thread_print,
ProcEntry, RUN_TOKEN_PROPERTY, THREAD_DUMP_TIMEOUT, is_application_jvm, process_table, select_run_jvm,
thread_dump_json, thread_print,
};
+126 -2
View File
@@ -1,9 +1,12 @@
use std::collections::{HashMap, HashSet, VecDeque};
use std::io::Read;
use std::path::Path;
use std::process::Command;
use std::time::Duration;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::heap_dump::quoted_path;
use crate::listener::is_hotspot;
use crate::socket::{AttachError, jcmd};
use crate::socket::{AttachError, MAX_OUTPUT, jcmd};
/// Default budget for `thread_print`; a dump of a healthy JVM takes milliseconds, so this only
/// bounds a JVM stuck at a safepoint.
@@ -30,6 +33,55 @@ pub fn thread_print(pid: u32, timeout: Duration) -> Result<String, AttachError>
jcmd(pid, "Thread.print -l", timeout)
}
/// `Thread.dump_to_file -format=json`, the only dump that lists virtual threads (JDK 21+). The
/// JVM writes it into `dir`, an absolute directory; the file is read up to [`MAX_OUTPUT`] and
/// deleted whatever the outcome. Never send it to a VM a debugger holds suspended: 21 and 25 hang
/// the request, and every later attach request behind it, until the VM resumes.
pub fn thread_dump_json(pid: u32, dir: &Path, timeout: Duration) -> Result<String, AttachError> {
dump_json_with(pid, dir, MAX_OUTPUT, |command| jcmd(pid, command, timeout))
}
fn dump_json_with(
pid: u32,
dir: &Path,
max: usize,
send: impl FnOnce(&str) -> Result<String, AttachError>,
) -> Result<String, AttachError> {
// The JVM resolves a relative path against its own working directory.
if !dir.is_absolute() {
return Err(AttachError::Protocol(format!("thread dump directory {dir:?} is not absolute")));
}
// JDK 21 has no `-overwrite` and writes nothing when the file exists.
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |since| since.as_nanos());
let path = dir.join(format!("threads-{pid}-{nanos}.json"));
let command = format!("Thread.dump_to_file -format=json {}", quoted_path(&path, "thread dump")?);
let _delete = DeleteOnDrop(&path);
let reply = send(&command)?;
read_capped(&path, max).map_err(|e| match e {
AttachError::Io(e) if e.kind() == std::io::ErrorKind::NotFound => {
AttachError::Protocol(format!("the JVM wrote no thread dump: {}", reply.trim()))
}
e => e,
})
}
fn read_capped(path: &Path, max: usize) -> Result<String, AttachError> {
let mut bytes = Vec::new();
std::fs::File::open(path)?.take(max as u64 + 1).read_to_end(&mut bytes)?;
if bytes.len() > max {
return Err(AttachError::TooLarge);
}
String::from_utf8(bytes).map_err(|_| AttachError::Protocol("the thread dump is not UTF-8".into()))
}
struct DeleteOnDrop<'a>(&'a Path);
impl Drop for DeleteOnDrop<'_> {
fn drop(&mut self) {
let _ = std::fs::remove_file(self.0);
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ProcEntry {
pub pid: u32,
@@ -119,6 +171,7 @@ fn deepest_jvm_in_tree(table: &[ProcEntry], root: u32, is_hotspot: &dyn Fn(u32)
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn entry(pid: u32, ppid: u32, command: &str) -> ProcEntry {
ProcEntry { pid, ppid, command: command.to_string() }
@@ -239,6 +292,77 @@ mod tests {
assert_eq!(select_run_jvm(&table, 10, None, not_the_shell), Some(11));
}
/// The path the fake JVM is asked to write, from `Thread.dump_to_file … "<path>"`.
fn requested_path(command: &str) -> PathBuf {
PathBuf::from(command.split('"').nth(1).expect("quoted path"))
}
fn is_empty(dir: &Path) -> bool {
std::fs::read_dir(dir).unwrap().next().is_none()
}
/// `<tmp>/a b`: the space is what an unquoted path would break on.
fn dir_with_space() -> (tempfile::TempDir, PathBuf) {
let root = tempfile::tempdir().unwrap();
let dir = root.path().join("a b");
std::fs::create_dir(&dir).unwrap();
(root, dir)
}
#[test]
fn json_dump_reads_the_file_and_deletes_it() {
let (_root, dir) = dir_with_space();
let mut sent = String::new();
let json = dump_json_with(42, &dir, 1024, |command| {
sent = command.to_owned();
std::fs::write(requested_path(command), "{\"threadDump\":{}}").unwrap();
Ok(format!("Created {}\n", requested_path(command).display()))
})
.unwrap();
assert_eq!(json, "{\"threadDump\":{}}");
let prefix = format!("Thread.dump_to_file -format=json \"{}", dir.join("threads-42-").display());
assert!(sent.starts_with(&prefix) && sent.ends_with(".json\""), "{sent}");
assert!(is_empty(&dir));
}
#[test]
fn json_dump_file_is_deleted_when_it_is_too_large() {
let (_root, dir) = dir_with_space();
let result = dump_json_with(42, &dir, 1024, |command| {
std::fs::write(requested_path(command), vec![b' '; 1025]).unwrap();
Ok(String::new())
});
assert!(matches!(result, Err(AttachError::TooLarge)), "{result:?}");
assert!(is_empty(&dir));
}
#[test]
fn json_dump_file_is_deleted_when_the_request_fails() {
let (_root, dir) = dir_with_space();
let result = dump_json_with(42, &dir, 1024, |command| {
// The JVM wrote the file but the reply came too late.
std::fs::write(requested_path(command), "{}").unwrap();
Err(AttachError::Timeout)
});
assert!(matches!(result, Err(AttachError::Timeout)), "{result:?}");
assert!(is_empty(&dir));
}
#[test]
fn json_dump_without_a_file_reports_the_reply() {
let (_root, dir) = dir_with_space();
// JDK 21 answers result code 0 when it writes nothing.
let result = dump_json_with(42, &dir, 1024, |_| Ok("/x.json exists, use -overwrite to overwrite\n".into()));
let Err(AttachError::Protocol(message)) = result else { panic!("{result:?}") };
assert!(message.contains("exists"), "{message}");
}
#[test]
fn json_dump_refuses_a_relative_directory() {
let result = dump_json_with(42, Path::new("dumps"), 1024, |_| panic!("sent a relative path"));
assert!(matches!(result, Err(AttachError::Protocol(_))), "{result:?}");
}
#[test]
fn select_skips_gradle_workers_and_the_kotlin_daemon() {
// `--no-daemon`: the build's helper JVMs sit beside the application in the run's tree.
+50 -1
View File
@@ -11,7 +11,7 @@ use ide_jvm_attach::{
AttachError, HeapDumpReply, LISTENER_START_TIMEOUT, THREAD_DUMP_TIMEOUT, agent_properties, ensure_listener,
find_jvm_by_jdwp_port, has_listener, heap_dump, heap_dump_command, histogram_safe_while_suspended, is_hotspot,
java_version_of, jcmd, jdwp_port, parse_class_histogram, parse_heap_dump_reply, parse_release, process_table,
select_run_jvm, temp_dir, thread_print, vm_flags,
select_run_jvm, temp_dir, thread_dump_json, thread_print, vm_flags,
};
/// Two threads that each hold one monitor and wait for the other's after 200 ms.
@@ -33,6 +33,25 @@ public class Deadlock {
}
"#;
/// Two virtual threads in a monitor deadlock, which `Thread.print` does not list.
const VIRTUAL_DEADLOCK_JAVA: &str = r#"
public class VirtualDeadlock {
static final Object A = new Object(), B = new Object();
static void sleep(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); }
}
public static void main(String[] args) {
Thread.ofVirtual().name("v-sync-1").start(() -> { synchronized (A) { sleep(200); synchronized (B) { } } });
Thread.ofVirtual().name("v-sync-2").start(() -> { synchronized (B) { sleep(200); synchronized (A) { } } });
System.out.println("READY");
System.out.flush();
sleep(60_000);
}
}
"#;
const MAIN_JAVA: &str = r#"
import java.util.ArrayList;
import java.util.List;
@@ -386,3 +405,33 @@ fn thread_print_reports_a_deadlock() {
assert!(table.iter().any(|entry| entry.pid == pid && entry.command.contains("Deadlock")));
assert_eq!(select_run_jvm(&table, pid, None, is_hotspot), Some(pid));
}
#[test]
#[ignore = "needs a real JDK >= 21: set OPENIDEA_TEST_JAVA to its bin/java"]
fn thread_dump_json_lists_virtual_threads() {
let Some(java) = std::env::var_os("OPENIDEA_TEST_JAVA").map(PathBuf::from) else {
eprintln!("OPENIDEA_TEST_JAVA is not set; skipping");
return;
};
let major = reported_major(&java);
if major < 21 {
eprintln!("JDK {major} has no virtual threads; skipping");
return;
}
let dir = tempfile::tempdir().unwrap();
let mut guard =
launch_class(&java, dir.path(), "VirtualDeadlock", VIRTUAL_DEADLOCK_JAVA, &["-XX:+StartAttachListener"]);
let pid = guard.0.id();
wait_for_ready(&output_lines(&mut guard.0));
wait_for_listener(pid);
std::thread::sleep(Duration::from_secs(1));
let dumps = dir.path().join("a b");
std::fs::create_dir(&dumps).unwrap();
let started = Instant::now();
let json = thread_dump_json(pid, &dumps, THREAD_DUMP_TIMEOUT).unwrap();
eprintln!("JDK {major} JSON thread dump: {} bytes in {:?}", json.len(), started.elapsed());
assert!(json.contains("\"threadContainers\""), "{json}");
assert!(json.contains("\"v-sync-1\"") && json.contains("\"v-sync-2\""), "{json}");
assert!(std::fs::read_dir(&dumps).unwrap().next().is_none(), "dump file left in {dumps:?}");
}
+1
View File
@@ -358,6 +358,7 @@ pub enum FoldKind {
Region,
Comment,
Imports,
Compact,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
+70 -1
View File
@@ -144,7 +144,11 @@ pub(super) fn folding(
if !node.is_named() {
return true;
}
if let Some(close_row) = kinds.bracket_close_row(&node) {
if spec.name == "go"
&& let Some(end) = go_compact_end(&node, text)
{
push(&mut out, start, end, FoldKind::Compact);
} else if let Some(close_row) = kinds.bracket_close_row(&node) {
push(&mut out, start, close_row, FoldKind::Region);
} else if kinds.has(&node, FOLD_NODE) {
push(&mut out, start, last_content_row(&node, text), FoldKind::Region);
@@ -157,6 +161,71 @@ pub(super) fn folding(
out
}
// Only join a single statement on the next line. Comments, blank lines and
// nested multi-line statements must keep their own lines.
fn go_compact_end(node: &Node, text: &str) -> Option<usize> {
let start = node.start_position().row;
let braced = match node.kind() {
"block" => {
let parent = node.parent()?;
if parent.kind() != "if_statement"
|| parent.child_by_field_name("consequence") != Some(*node)
|| !go_error_guard(parent.child_by_field_name("condition")?, text)
{
return None;
}
true
}
"expression_case" | "type_case" | "communication_case" | "default_case" => false,
_ => return None,
};
let body = node.named_child(node.named_child_count().checked_sub(1)?)?;
if body.kind() != "statement_list" || body.named_child_count() != 1 {
return None;
}
let header_end = body.prev_sibling()?;
if header_end.kind() != if braced { "{" } else { ":" } || header_end.end_position().row != start {
return None;
}
let statement = body.named_child(0)?;
let position = statement.start_position();
if statement.has_error()
|| statement.is_extra()
|| position.row != start + 1
|| statement.end_position().row != position.row
|| !own_line(text, statement.start_byte(), position.column)
|| !text.get(header_end.end_byte()..statement.start_byte())?.trim().is_empty()
{
return None;
}
let tail = text.get(statement.end_byte()..)?.split('\n').next()?.trim();
if !matches!(tail, "" | ";") {
return None;
}
let end = start + if braced { 2 } else { 1 };
(!braced || node.end_position().row == end).then_some(end)
}
// Folding runs without Go type information. Recognize conventional error
// guards and leave other nil checks alone.
fn go_error_guard(condition: Node, text: &str) -> bool {
if condition.kind() != "binary_expression"
|| !condition.child_by_field_name("operator").is_some_and(|op| op.kind() == "!=")
{
return false;
}
let (Some(left), Some(right)) = (condition.child_by_field_name("left"), condition.child_by_field_name("right"))
else {
return false;
};
let name = match (left.kind(), right.kind()) {
("identifier", "nil") => left,
("nil", "identifier") => right,
_ => return false,
};
name.utf8_text(text.as_bytes()).is_ok_and(|name| name == "err" || name.ends_with("Err"))
}
fn push(out: &mut Vec<FoldRange>, start: usize, end: usize, kind: FoldKind) {
if end > start {
out.push(FoldRange { start_line: start as u32, end_line: end as u32, kind });
+50
View File
@@ -1206,6 +1206,56 @@ fn folding_go_imports_and_ruby_ends() {
);
}
#[test]
fn go_compact_folds_keep_only_single_line_statements_inline() {
let src = r#"package main
func f() {
if err != nil {
return err
}
if err != nil {
return err // keep the comment on its own line
}
switch mode {
case "compact":
run()
case "multi":
run()
stop()
default:
return err
}
if err != nil {
return fmt.Errorf(
"keep both lines")
}
}
"#;
let found = folds("go", src);
let compact: Vec<_> = found.iter().copied().filter(|r| r.2 == FoldKind::Compact).collect();
assert_eq!(compact, [(3, 5, FoldKind::Compact), (10, 11, FoldKind::Compact), (15, 16, FoldKind::Compact)]);
assert!(found.contains(&(6, 8, FoldKind::Region)));
assert!(found.contains(&(18, 21, FoldKind::Region)));
}
#[test]
fn go_compact_if_folds_are_limited_to_conventional_error_guards() {
for (guard, kind) in [
("err != nil", FoldKind::Compact),
("nil != err", FoldKind::Compact),
("parseErr := parse(); parseErr != nil", FoldKind::Compact),
("cfg != nil", FoldKind::Region),
("err == nil", FoldKind::Region),
("invalid", FoldKind::Region),
] {
let source = format!(
"package main\nfunc f() error {{\n if {guard} {{\n return err\n }}\n return nil\n}}\n"
);
assert!(folds("go", &source).contains(&(2, 4, kind)), "unexpected fold for {guard}");
}
}
#[test]
fn folding_swift_control_flow_and_haskell_binds() {
assert_eq!(
+29
View File
@@ -87,6 +87,7 @@ use std::time::Duration;
use text::{DocText, Encoding};
use types::*;
const DART_SERVER: &str = "dart";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
const COMPLETION_TIMEOUT: Duration = Duration::from_secs(5);
const LONG_TIMEOUT: Duration = Duration::from_secs(30);
@@ -2448,6 +2449,34 @@ impl LspManager {
.then(|| outline.items.clone())
}
/// The arguments of the call at `pos` the Flutter Property Editor shows; `None` outside a
/// call, or when no Dart server serves the document.
pub async fn editable_arguments(&self, doc: DocId, pos: Pos) -> IdeResult<Option<EditableArguments>> {
let (snap, targets) = self.doc_targets(doc, "the property editor", |_| true).await?;
let Some(t) = targets.iter().find(|t| t.server.name == DART_SERVER) else { return Ok(None) };
self.call(t, "dart/textDocument/editableArguments", snap.pos_params(t, pos), None, DEFAULT_TIMEOUT).await
}
/// Sets the argument `name` of the call at `pos` to `value` (`None` passes null). The server
/// sends the edit back as `workspace/applyEdit`, which the apply-edit hook applies.
pub async fn edit_argument(
&self,
doc: DocId,
pos: Pos,
name: String,
value: Option<ArgumentValue>,
) -> IdeResult<()> {
let (snap, targets) = self.doc_targets(doc, "the property editor", |_| true).await?;
let t = targets
.iter()
.find(|t| t.server.name == DART_SERVER)
.ok_or_else(|| IdeError::unavailable("no Dart language server serves this document"))?;
let mut params = snap.pos_params(t, pos);
params["edit"] = json!({ "name": name, "newValue": value });
let _: Value = self.call(t, "dart/textDocument/editArgument", params, None, DEFAULT_TIMEOUT).await?;
Ok(())
}
/// Records a published outline; whether what the open documents of `path` show changed.
fn set_flutter_outline(
&self,
+54
View File
@@ -654,3 +654,57 @@ pub struct ClassifiedReference {
#[specta(optional)]
pub text: Option<String>,
}
/// The arguments the Flutter Property Editor edits: those of the widget (or other) call at a
/// position, as the Dart server's `dart/textDocument/editableArguments` reports them.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct EditableArguments {
/// The widget's (or callee's) name.
pub name: Option<String>,
pub documentation: Option<String>,
pub arguments: Vec<EditableArgument>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct EditableArgument {
pub name: String,
pub documentation: Option<String>,
/// How to edit it: `string`, `int`, `double`, `bool` or `enum`.
#[serde(rename = "type")]
pub kind: String,
/// The literal value in the code (only while `has_argument`); an expression has `display_value`.
pub value: Option<ArgumentValue>,
#[serde(default)]
pub has_argument: bool,
pub default_value: Option<ArgumentValue>,
pub display_value: Option<String>,
// Absent from older Dart SDKs (`isDeprecated` came later): read as false rather than
// failing the whole list.
#[serde(default)]
pub is_required: bool,
#[serde(default)]
pub is_nullable: bool,
#[serde(default)]
pub is_deprecated: bool,
#[serde(default = "editable_by_default")]
pub is_editable: bool,
pub not_editable_reason: Option<String>,
/// An enum's values, as `EnumName.value`.
pub options: Option<Vec<String>>,
}
fn editable_by_default() -> bool {
true
}
/// A literal argument value. Ints stay ints: the server rejects `1.0` for an `int` parameter.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(untagged)]
pub enum ArgumentValue {
Bool(bool),
Int(i64),
Double(f64),
Text(String),
}
+79
View File
@@ -1549,6 +1549,85 @@ async fn flutter_outline_follows_the_document_and_the_server_instance() {
assert!(h.mgr.flutter_outline(reopened).is_none());
}
#[tokio::test(flavor = "multi_thread")]
async fn property_editor_lists_the_dart_servers_arguments_and_applies_its_edit() {
let h = harness(&[("dart", incremental_caps())]);
let (doc, path) = h.open("a.mk", "Text('x')\n");
h.wait_status("dart", ServerStatus::Ready).await;
let s = h.launcher.state("dart");
let arg = |name: &str, extra: Value| {
let mut a = json!({ "name": name, "hasArgument": false, "isRequired": false, "isNullable": true,
"isDeprecated": false, "isEditable": true });
a.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
a
};
let at = json!({"start":{"line":0,"character":0},"end":{"line":0,"character":9}});
s.respond(
"dart/textDocument/editableArguments",
json!({ "textDocument": { "uri": uri_of(&path), "version": 1 }, "name": "Text", "range": at, "arguments": [
arg("data", json!({ "type": "string", "value": "x", "hasArgument": true, "isRequired": true, "isNullable": false })),
arg("textAlign", json!({ "type": "enum", "options": ["TextAlign.left", "TextAlign.center"] })),
arg("maxLines", json!({ "type": "int", "value": 2, "hasArgument": true })),
// An older SDK leaves out flags it doesn't know yet.
json!({ "name": "softWrap", "type": "bool", "hasArgument": false }),
]}),
);
let args = h.mgr.editable_arguments(doc, Pos::new(0, 2)).await.unwrap().unwrap();
assert_eq!(args.name.as_deref(), Some("Text"));
assert_eq!(
(args.arguments[0].kind.as_str(), args.arguments[0].value.clone()),
("string", Some(ArgumentValue::Text("x".into())))
);
assert_eq!(args.arguments[1].options.as_ref().unwrap()[1], "TextAlign.center");
assert_eq!(args.arguments[1].value, None);
assert!(args.arguments[3].is_editable && !args.arguments[3].is_deprecated && !args.arguments[3].is_required);
assert_eq!(args.arguments[2].value, Some(ArgumentValue::Int(2)));
let asked = s.requested("dart/textDocument/editableArguments");
assert_eq!(asked[0]["position"], json!({"line":0,"character":2}));
// The server answers editArgument with null and sends the edit as workspace/applyEdit.
let applied: Arc<Mutex<Vec<WorkspaceEdit>>> = Arc::default();
let received = applied.clone();
h.mgr.set_apply_edit_hook(Box::new(move |e| {
received.lock().push(e);
true
}));
let uri = uri_of(&path);
*s.responder.lock() = Some(Arc::new(move |s, method, _| {
(method == "dart/textDocument/editArgument").then(|| {
let edit = json!({ "changes": { uri.clone(): [{ "range":
{"start":{"line":0,"character":5},"end":{"line":0,"character":8}}, "newText": "'y'" }] } });
let reply: Value = tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(s.peer().request(
"workspace/applyEdit",
json!({ "edit": edit }),
None,
))
})
.unwrap();
assert_eq!(reply, json!({"applied": true}));
Value::Null
})
}));
h.mgr.edit_argument(doc, Pos::new(0, 2), "data".into(), Some(ArgumentValue::Text("y".into()))).await.unwrap();
let sent = s.requested("dart/textDocument/editArgument");
assert_eq!(sent[0]["edit"], json!({ "name": "data", "newValue": "y" }));
assert_eq!(sent[0]["position"], json!({"line":0,"character":2}));
let edits = applied.lock().clone();
assert!(
matches!(&edits[..], [e] if matches!(&e.files[0], FileEdit::Edit { edits, .. } if edits[0].new_text == "'y'"))
);
}
#[tokio::test(flavor = "multi_thread")]
async fn property_editor_has_nothing_without_a_dart_server() {
let h = harness(&[("mock", incremental_caps())]);
let (doc, _) = h.open("a.mk", "Text('x')\n");
h.wait_status("mock", ServerStatus::Ready).await;
assert!(h.mgr.editable_arguments(doc, Pos::new(0, 2)).await.unwrap().is_none());
assert!(h.launcher.state("mock").requested("dart/textDocument/editableArguments").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn closing_labels_join_the_inlay_hints_until_the_next_edit() {
let h = harness(&[("mock", incremental_caps())]);
+7 -2
View File
@@ -168,8 +168,13 @@ impl Session<'_> {
"instructions": format!(
"Built-in OpenIDEA tools for {about}: they see the files as the IDE has them and, \
for a project open in a window, its editors. The project's workspace can include other \
projects attached to it: call `get_workspace_roots` to list them before answering about \
workspace directories or planning a change across projects."
projects attached to it, which a session's working directory doesn't show. Before the \
first project-related operation in a session, call `get_workspace_roots`: its \
`projectRoot` is the project this connection serves and the default base for paths, and \
its `roots` are every project in the IDE workspace. That is the scope to search and read, \
not a list of projects to change; it doesn't change your working directory or \
permissions. Pass another root as `projectPath` to reach that project. Call it again \
when the user switches projects or attaches one."
),
})
}
+2
View File
@@ -282,6 +282,8 @@ async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
let init = rpc_for(&s, &inside, "initialize", json!({})).await;
let instructions = init["result"]["instructions"].as_str().unwrap();
assert!(instructions.contains(inventory.to_str().unwrap()), "{instructions}");
// Clients that load tool descriptions lazily still learn to establish the workspace first (#5751).
assert!(instructions.contains("first project-related operation in a session, call `get_workspace_roots`"));
let list = rpc_for(&s, &inside, "tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", inventory.display()), "{list}");
let call = rpc_for(&s, &inside, "tools/call", json!({ "name": "where" })).await;
+57
View File
@@ -123,6 +123,27 @@ fn is_jetbrains_jdk(java: &Path) -> bool {
release_field(java, "IMPLEMENTOR").is_some_and(|v| v.to_ascii_lowercase().contains("jetbrains"))
}
/// The JVM a configuration whose command is `command` starts, for the JDK filter. A path is
/// itself. A bare `java` is the first one on `search`, as the launch finds it; when that is
/// no JDK's own launcher (macOS's `/usr/bin/java` stub, which runs `JAVA_HOME`'s), it is
/// `java_home`'s. `None` when neither is found.
pub fn launched_java(command: &str, search: &std::ffi::OsStr, java_home: Option<&Path>) -> Option<PathBuf> {
let path = Path::new(command);
if path.components().count() > 1 {
return Some(path.to_path_buf());
}
let windows = cfg!(windows);
let found =
ide_core::process::find_executable_in(command, search, windows, std::env::var("PATHEXT").ok().as_deref());
if let Some(java) = &found
&& release_field(java, "JAVA_VERSION").is_some()
{
return found;
}
let java = java_home.map(|home| home.join("bin").join(if windows { "java.exe" } else { "java" }));
java.filter(|java| java.is_file()).or(found)
}
/// `KEY="value"` from the JDK `release` file next to `bin/java` (or JDK 8's `jre/bin/java`).
fn release_field(java: &Path, key: &str) -> Option<String> {
let java = std::fs::canonicalize(java).unwrap_or_else(|_| java.to_path_buf());
@@ -226,6 +247,42 @@ fn split_text(text: &str) -> Vec<String> {
mod tests {
use super::*;
/// A JDK home with `bin/java` and a `release` file naming `implementor`.
#[cfg(unix)]
fn jdk(root: &Path, name: &str, implementor: &str) -> PathBuf {
let home = root.join(name);
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::write(home.join("bin/java"), "#!/bin/sh\n").unwrap();
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(home.join("bin/java"), std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::write(home.join("release"), format!("JAVA_VERSION=\"21\"\nIMPLEMENTOR=\"{implementor}\"\n")).unwrap();
home
}
#[cfg(unix)]
#[test]
fn a_bare_java_is_the_one_the_launch_finds() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let jbr = jdk(dir.path(), "jbr", "JetBrains s.r.o.");
let openjdk = jdk(dir.path(), "openjdk", "Eclipse Adoptium");
// A JDK's own launcher on the search path is what runs, whatever JAVA_HOME says.
let search = std::env::join_paths([jbr.join("bin")]).unwrap();
let java = launched_java("java", &search, Some(&openjdk)).unwrap();
assert!(jdk_allows(Some(&java), Some("jetbrains")));
// A stub outside any JDK (macOS /usr/bin/java) runs JAVA_HOME's.
let stub = dir.path().join("usr/bin");
std::fs::create_dir_all(&stub).unwrap();
std::fs::write(stub.join("java"), "#!/bin/sh\n").unwrap();
std::fs::set_permissions(stub.join("java"), std::fs::Permissions::from_mode(0o755)).unwrap();
let search = std::env::join_paths([stub]).unwrap();
let java = launched_java("java", &search, Some(&jbr)).unwrap();
assert!(jdk_allows(Some(&java), Some("jetbrains")));
assert!(!jdk_allows(launched_java("java", &search, Some(&openjdk)).as_deref(), Some("jetbrains")));
// A path is itself.
assert_eq!(launched_java("/opt/jdk/bin/java", &search, Some(&jbr)), Some(PathBuf::from("/opt/jdk/bin/java")));
}
fn strings(a: &[&str]) -> Vec<String> {
a.iter().map(|s| (*s).to_owned()).collect()
}
+2 -1
View File
@@ -3,9 +3,10 @@
use crate::utf8::OutputDecoder;
use crate::{OutputChunk, RunAttach, RunConfig, RunInfo};
use ide_core::pty::native_pty_system;
use ide_core::{IdeError, IdeEvent, IdeResult, RunId, SharedSink};
use parking_lot::Mutex;
use portable_pty::{CommandBuilder, MasterPty, PtySize, native_pty_system};
use portable_pty::{CommandBuilder, MasterPty, PtySize};
use std::collections::{BTreeMap, VecDeque};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
+1
View File
@@ -127,6 +127,7 @@ pub(crate) fn info(def: &Def) -> GeneratorInfo {
description: def.description.clone(),
git: def.git,
fields: def.fields.iter().map(field).collect(),
directory: def.directory.clone(),
dynamic: def.service.is_some(),
}
}
+18 -4
View File
@@ -57,6 +57,16 @@ fn with_defaults(def: &Def, name: &str, values: &Values) -> Values {
out
}
/// The project folder's name: the generator's `directory` template (the solution name of a
/// .NET project with a solution), or the project name.
fn project_folder(def: &Def, name: &str, values: &Values) -> String {
def.directory
.as_deref()
.map(|t| render(t, values).trim().to_owned())
.filter(|folder| !folder.is_empty())
.unwrap_or_else(|| name.to_owned())
}
/// The fields a project service adds to the form (its metadata); empty for other generators.
pub fn options(id: &str, values: &Values, cancel: &CancellationToken) -> IdeResult<Vec<Field>> {
let def = def(id).ok_or_else(|| unknown(id))?;
@@ -398,15 +408,19 @@ pub(crate) fn create_with(
if let Some(e) = name_error(name) {
return Err(IdeError::invalid(e));
}
let values = with_defaults(def, name, &req.values);
let folder = project_folder(def, name, &values);
if let Some(e) = name_error(&folder) {
return Err(IdeError::invalid(e));
}
let location = req.location.to_path_buf();
if !location.is_dir() {
std::fs::create_dir_all(&location)?;
}
let target = location.join(name);
let target = location.join(&folder);
if target_taken(&target) {
return Err(IdeError::invalid(format!("{} already exists and is not empty", target.display())));
}
let values = with_defaults(def, name, &req.values);
let search = search_path();
let mut missing = def
@@ -420,10 +434,10 @@ pub(crate) fn create_with(
return Err(IdeError::unavailable(format!("`{}`{need} is required to create this project", r.program)));
}
let staging = Staging(location.join(format!(".{name}.openidea-new-{}", std::process::id())));
let staging = Staging(location.join(format!(".{folder}.openidea-new-{}", std::process::id())));
let _ = std::fs::remove_dir_all(&staging.0);
std::fs::create_dir_all(&staging.0)?;
let project = staging.0.join(name);
let project = staging.0.join(&folder);
download_service(def, &values, &staging.0, &project, cancel, emit)?;
let creates_dir = def.steps.iter().any(|s| s.cwd == Cwd::Parent && s.applies(&values));
+16
View File
@@ -169,6 +169,17 @@ fn dotnet_pins_the_sdk_and_creates_a_solution() {
let (pin, lines) = render(&[("solution", "false")]);
assert_eq!(pin, None);
assert_eq!(lines, ["dotnet new console --name Shop --output . --language C#", "dotnet new gitignore"]);
// #5732: the top folder is the solution's (Store/Store.slnx, Store/Shop/Shop.csproj), as in
// Rider and Visual Studio; without a solution `solution-name` isn't sent and it is the project's.
let folder = |pairs: &[(&str, &str)]| {
let given = pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
project_folder(def, "Shop", &with_defaults(def, "Shop", &given))
};
assert_eq!(folder(&[("solution-name", "Store")]), "Store");
assert_eq!(folder(&[]), "Shop");
assert_eq!(folder(&[("solution", "false")]), "Shop");
assert_eq!(folder(&[("solution-name", " ")]), "Shop");
}
#[cfg(unix)]
@@ -198,6 +209,11 @@ fn dotnet_templates_see_the_selected_sdk_before_running() {
let pin: serde_json::Value = serde_json::from_slice(&std::fs::read(project.join("global.json")).unwrap()).unwrap();
assert_eq!(pin["sdk"]["version"], "10.0.400");
assert_eq!(std::fs::read_to_string(parent_pin).unwrap(), inherited);
// A solution named apart from the project names the folder.
let req = request("dotnet", tmp.path(), "Api", &[("sdk", "10.0.400"), ("solution-name", "Store")]);
let project = create_with(&def, &req, &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(project, tmp.path().join("Store"));
assert!(project.join("global.json").is_file());
}
/// `dotnet` of a runtime-only install: `--version` fails ("No .NET SDKs were found").
+8
View File
@@ -30,6 +30,11 @@ pub(crate) struct Def {
pub requires: Vec<RequireDef>,
#[serde(default)]
pub fields: Vec<FieldDef>,
/// The project folder's name, when it isn't the project name: a template over the fields
/// (.NET's solution name). Steps that create the folder themselves (`cwd = "parent"`) can't
/// use it.
#[serde(default)]
pub directory: Option<String>,
#[serde(default)]
pub service: Option<ServiceDef>,
/// Generation runs: the service's zip, `steps`, `files`, then `after`.
@@ -280,6 +285,9 @@ pub struct GeneratorInfo {
/// Offer "Create Git repository".
pub git: bool,
pub fields: Vec<Field>,
/// The project folder's name when it isn't the project name: a template over the fields
/// shown (a hidden field has its default), like [`Field::default`]; empty renders the name.
pub directory: Option<String>,
/// More fields come from `scaffold_options` (a project service's metadata).
pub dynamic: bool,
}
+27 -6
View File
@@ -1184,13 +1184,31 @@ pub fn tool_command(root: &Path, s: &Settings, command: &str) -> Option<PathBuf>
if command == godot::COMMAND {
return godot::find(custom);
}
custom
custom.or_else(|| flutter_sdk_tool(root, s, command))
}
/// `flutter` / `dart` of the Flutter SDK in Settings › Languages & Frameworks › Flutter, else
/// `None` (the search path). Dart is the SDK's own (`bin/cache/dart-sdk`), else its `bin/dart`
/// wrapper, which downloads it on first use.
pub fn flutter_sdk_tool(root: &Path, s: &Settings, command: &str) -> Option<PathBuf> {
let bin = setting_path(root, &s.languages.flutter.sdk)?.join("bin");
let script = |name: &str| bin.join(if cfg!(windows) { format!("{name}.bat") } else { name.to_owned() });
match command {
"flutter" => Some(script("flutter")),
"dart" => Some(
Some(bin.join("cache/dart-sdk/bin").join(exe("dart")))
.filter(|d| d.is_file())
.unwrap_or_else(|| script("dart")),
),
_ => None,
}
}
/// Points a run configuration launching a bare tool name at the executable from
/// [`tool_command`] (Godot apps live outside the search path).
/// [`tool_command`] (Godot apps live outside the search path; `flutter` / `dart` follow the
/// Flutter SDK setting).
pub fn resolve_run_command(config: &mut RunConfig, root: &Path, s: &Settings) {
if config.command == godot::COMMAND
if matches!(config.command.as_str(), godot::COMMAND | "flutter" | "dart")
&& let Some(path) = tool_command(root, s, &config.command)
{
config.command = path.to_string_lossy().into_owned();
@@ -2207,9 +2225,12 @@ pub fn without_derived_in(config: &RunConfig, root: &Path, fallback: Option<&Pat
&& let Some(name) = path.file_name().map(|n| n.to_string_lossy().into_owned())
{
// Generated configurations name the bare program (`java`), also on Windows where the
// derived path ends in `java.exe`.
let bare =
name.len().checked_sub(4).filter(|&at| name[at..].eq_ignore_ascii_case(".exe")).map(|at| &name[..at]);
// derived path ends in `java.exe` (`flutter.bat`).
let bare = name
.len()
.checked_sub(4)
.filter(|&at| name[at..].eq_ignore_ascii_case(".exe") || name[at..].eq_ignore_ascii_case(".bat"))
.map(|at| &name[..at]);
for candidate in bare.into_iter().chain([name.as_str()]) {
let mut probe = out.clone();
probe.command = candidate.to_owned();
+7 -1
View File
@@ -32,6 +32,7 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
SdkKind::Ruby => crate::ruby::detect(root),
SdkKind::Zig => zig(),
SdkKind::Dotnet => dotnet(),
SdkKind::Flutter => crate::flutter::detect(),
};
if let Some(root) = root {
pinned_first(&mut out, kind, root);
@@ -48,7 +49,12 @@ fn tool_of(kind: SdkKind) -> Option<Tool> {
SdkKind::Maven => Some(Tool::Maven),
SdkKind::Ruby => Some(Tool::Ruby),
SdkKind::Zig => Some(Tool::Zig),
SdkKind::Php | SdkKind::PackageManager | SdkKind::Rust | SdkKind::TypeScript | SdkKind::Dotnet => None,
SdkKind::Php
| SdkKind::PackageManager
| SdkKind::Rust
| SdkKind::TypeScript
| SdkKind::Dotnet
| SdkKind::Flutter => None,
}
}
+121
View File
@@ -0,0 +1,121 @@
//! Flutter SDKs: Settings › Languages & Frameworks › Flutter (the Flutter plugin's "Flutter SDK path").
use crate::exec::query_in;
use crate::{Sdk, home_dir};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
use std::time::Duration;
/// `flutter --version` may first unpack the Dart SDK or print the analytics notice.
const VERSION_TIMEOUT: Duration = Duration::from_secs(60);
/// What `flutter --version --machine` reports of an SDK.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct FlutterVersion {
/// SDK root (not part of Flutter's answer).
pub root: String,
pub framework_version: String,
pub channel: Option<String>,
pub dart_sdk_version: Option<String>,
}
pub(crate) fn flutter_script(sdk: &Path) -> PathBuf {
sdk.join("bin").join(if cfg!(windows) { "flutter.bat" } else { "flutter" })
}
/// The SDK root of a `flutter` executable; on the search path it is often a link into the SDK.
pub fn sdk_of(flutter: &Path) -> Option<PathBuf> {
let real = dunce::canonicalize(flutter).ok()?;
let root = real.parent()?.parent()?;
flutter_script(root).is_file().then(|| root.to_path_buf())
}
/// `flutter --version --machine` of the SDK at `sdk`. `None` when `sdk` holds no `bin/flutter`;
/// an empty `framework_version` when it did not answer.
pub fn version(sdk: &Path) -> Option<FlutterVersion> {
let flutter = flutter_script(sdk);
if !flutter.is_file() {
return None;
}
let out = query_in(&flutter, &["--version", "--machine"], Some(sdk), &[], VERSION_TIMEOUT).unwrap_or_default();
let mut version = parse_version(&out).unwrap_or_default();
version.root = sdk.to_string_lossy().into_owned();
Some(version)
}
/// The JSON object of `flutter --version --machine`, after anything it printed first.
fn parse_version(out: &str) -> Option<FlutterVersion> {
let json = &out[out.find('{')?..=out.rfind('}')?];
serde_json::from_str(json).ok()
}
/// The framework version an SDK records, without running it.
fn recorded_version(sdk: &Path) -> Option<String> {
let json = std::fs::read_to_string(sdk.join("bin/cache/flutter.version.json")).ok();
json.and_then(|j| parse_version(&j))
.map(|v| v.framework_version)
.or_else(|| std::fs::read_to_string(sdk.join("version")).ok().map(|v| v.trim().to_owned()))
.filter(|v| !v.is_empty())
}
/// Flutter SDKs: the one on the search path, fvm's and the usual install folders.
pub(crate) fn detect() -> Vec<Sdk> {
let mut roots: Vec<(PathBuf, &str)> = Vec::new();
if let Some(sdk) = crate::exec::which("flutter").and_then(|f| sdk_of(&f)) {
roots.push((sdk, "path"));
}
if let Some(home) = home_dir() {
for dir in ["flutter", "development/flutter", "sdk/flutter"] {
roots.push((home.join(dir), "system"));
}
if let Ok(versions) = std::fs::read_dir(home.join("fvm/versions")) {
roots.extend(versions.flatten().map(|e| (e.path(), "fvm")));
}
}
let mut seen = std::collections::HashSet::new();
roots
.into_iter()
.filter(|(sdk, _)| flutter_script(sdk).is_file())
.filter(|(sdk, _)| seen.insert(dunce::canonicalize(sdk).unwrap_or_else(|_| sdk.clone())))
.map(|(sdk, source)| {
let version = recorded_version(&sdk);
Sdk {
path: sdk.clone().into(),
name: format!("Flutter {}", version.as_deref().unwrap_or_default()).trim().to_owned(),
version,
source: source.to_owned(),
home: Some(sdk.into()),
extra: None,
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_the_version_after_what_flutter_printed_first() {
let out = "Downloading Dart SDK…\n{\n \"frameworkVersion\": \"3.38.1\",\n \"channel\": \"stable\",\n \"dartSdkVersion\": \"3.10.0\"\n}\n";
let v = parse_version(out).unwrap();
assert_eq!(
(v.framework_version.as_str(), v.channel.as_deref(), v.dart_sdk_version.as_deref()),
("3.38.1", Some("stable"), Some("3.10.0"))
);
assert_eq!(parse_version("flutter: command not found"), None);
}
#[test]
fn a_folder_without_bin_flutter_is_no_sdk() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(version(dir.path()), None);
std::fs::create_dir_all(dir.path().join("bin/cache")).unwrap();
std::fs::write(flutter_script(dir.path()), "").unwrap();
std::fs::write(dir.path().join("bin/cache/flutter.version.json"), r#"{"frameworkVersion":"3.35.0"}"#).unwrap();
assert_eq!(recorded_version(dir.path()).as_deref(), Some("3.35.0"));
assert_eq!(sdk_of(&flutter_script(dir.path())), Some(dunce::canonicalize(dir.path()).unwrap()));
}
}
+3
View File
@@ -12,6 +12,7 @@ mod astro;
pub mod container_python;
mod discover;
mod exec;
pub mod flutter;
pub mod go;
pub mod godot;
pub mod java;
@@ -57,6 +58,8 @@ pub enum SdkKind {
Zig,
/// .NET SDKs of the `dotnet` on the search path; `version` is what `global.json` pins.
Dotnet,
/// Flutter SDK roots.
Flutter,
}
/// One installed interpreter / toolchain.
+50 -1
View File
@@ -11,7 +11,7 @@ use ide_core::settings::Settings;
use ide_language::LanguageServerConfig;
use ide_run::RunConfig;
use std::collections::BTreeMap;
use std::path::Path;
use std::path::{Path, PathBuf};
use std::time::Duration;
fn fake_venv(root: &Path, name: &str) -> std::path::PathBuf {
@@ -2058,6 +2058,55 @@ fn the_godot_setting_applies_to_server_debugger_and_run_configurations() {
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "zls"), None);
}
#[test]
fn the_flutter_sdk_setting_picks_flutter_and_dart_for_server_and_run_configurations() {
let tmp = tempfile::tempdir().unwrap();
let sdk = tmp.path().join("flutter");
let run = |command: &str| RunConfig {
id: "dart:pub get".into(),
name: "pub get".into(),
kind: "dart-command".into(),
command: command.into(),
args: vec!["pub".into(), "get".into()],
cwd: None,
env: BTreeMap::new(),
detected: true,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
// No setting: the names stay for the search path.
let mut s = Settings::default();
let mut plain = run("flutter");
apply_to_run_configs(std::slice::from_mut(&mut plain), tmp.path(), &s);
assert_eq!(plain.command, "flutter");
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "dart"), None);
// A project-relative SDK: `bin/flutter`, and `bin/dart` until the Dart SDK is unpacked.
s.languages.flutter.sdk = "flutter".into();
let flutter = sdk.join("bin").join(if cfg!(windows) { "flutter.bat" } else { "flutter" });
let wrapper = sdk.join("bin").join(if cfg!(windows) { "dart.bat" } else { "dart" });
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "dart"), Some(wrapper));
let dart = sdk.join("bin/cache/dart-sdk/bin").join(exe("dart"));
std::fs::create_dir_all(dart.parent().unwrap()).unwrap();
std::fs::write(&dart, "").unwrap();
let mut cfg = server("dart");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(Path::new(&cfg.command), dart);
let mut configs = [run("flutter"), run("dart"), run("/usr/bin/flutter")];
apply_to_run_configs(&mut configs, tmp.path(), &s);
assert_eq!(Path::new(&configs[0].command), flutter);
assert_eq!(Path::new(&configs[1].command), dart);
assert_eq!(configs[2].command, "/usr/bin/flutter");
// Saved configurations keep the bare name.
assert_eq!(crate::apply::without_derived(&configs[0], tmp.path(), &s).command, "flutter");
// An explicit tool path still wins.
s.tools.insert("dart".into(), ide_core::settings::ToolSettings { path: "/opt/dart/bin/dart".into() });
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "dart"), Some(PathBuf::from("/opt/dart/bin/dart")));
}
#[test]
fn python_library_paths_are_parsed_and_deduplicated() {
let tmp = tempfile::tempdir().unwrap();
+15 -1
View File
@@ -46,7 +46,10 @@ fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)], out: &mut Vec<Line
utf16_len(&s.as_bytes()[..bounds.0])
};
(prev_start, prev_offset) = (bounds.0, text_offset);
let (m, used) = in_window(line_no, s, rest, bounds, text_offset);
// Only the ranges starting in the window: `in_window` reserves room for all it is given,
// and the rest of a long line can hold every match on it.
let starting = rest.partition_point(|&(a, _)| a <= bounds.1);
let (m, used) = in_window(line_no, s, &rest[..starting], bounds, text_offset);
out.push(m);
rest = &rest[used.max(1)..];
if rest.is_empty() {
@@ -265,6 +268,17 @@ mod tests {
assert!(started.elapsed() < std::time::Duration::from_secs(2), "{:?}", started.elapsed());
}
#[test]
fn each_window_holds_room_for_its_own_matches_only() {
// 7,000 windows of one match each on a 4 MB line.
let s = format!("{}function", "x".repeat(592)).repeat(7_000);
let ranges: Vec<_> = s.match_indices("function").map(|(a, m)| (a, a + m.len())).collect();
let mut out = Vec::new();
line_matches(0, s.as_bytes(), &ranges, &mut out);
let reserved: usize = out.iter().map(|m| m.ranges.capacity()).sum();
assert!(reserved <= 4 * out.len(), "{reserved} ranges reserved for {} windows", out.len());
}
/// `main`'s windowing, which counts each window's offset from the line start.
fn reference(line_no: u32, line: &[u8], ranges: &[(usize, usize)]) -> Vec<LineMatch> {
fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)], out: &mut Vec<LineMatch>) {
+24 -8
View File
@@ -1,7 +1,7 @@
//! App-wide SSH connections, one per SSH configuration, shared by every
//! feature that works on that host (deployment, run targets, data sources).
use crate::secrets::SecretFile;
use crate::secrets::{LegacyPasswordAction, SecretFile};
use crate::session::{ConnectError, Session, UnknownHostKey};
use crate::target::{SshFiles, SshTarget};
use ide_core::remote_settings::{SshAuth, SshConfiguration};
@@ -14,6 +14,7 @@ use std::sync::Arc;
pub struct SshManager {
files: SshFiles,
saved: SecretFile,
startup_migration: std::sync::Once,
/// Secrets entered this session (not saved, or not yet), by configuration id.
entered: Mutex<HashMap<String, String>>,
configs: RwLock<Vec<SshConfiguration>>,
@@ -34,7 +35,8 @@ impl SshManager {
pub fn with_files(secrets: PathBuf, files: SshFiles) -> Self {
Self {
files,
saved: SecretFile::new(secrets),
saved: SecretFile::ssh_passwords(secrets),
startup_migration: std::sync::Once::new(),
entered: Mutex::default(),
configs: RwLock::default(),
sessions: Mutex::default(),
@@ -47,6 +49,19 @@ impl SshManager {
&self.files
}
pub fn start_password_migration(&self) {
self.startup_migration.call_once(|| match self.saved.resolve_legacy(LegacyPasswordAction::Retry) {
Ok(None) => {}
Ok(Some(why)) => tracing::warn!("ssh-passwords.json still contains legacy plaintext credentials: {why}"),
Err(e) => tracing::warn!("could not check ssh-passwords.json: {}", e.message),
});
}
pub fn resolve_legacy_passwords(&self, action: LegacyPasswordAction) -> IdeResult<Option<String>> {
self.start_password_migration();
self.saved.resolve_legacy(action)
}
/// Replaces the configurations (Settings › SSH Configurations); sessions of
/// changed or removed ones are closed, secrets of removed ones forgotten.
pub fn set_configs(&self, configs: Vec<SshConfiguration>) {
@@ -86,7 +101,7 @@ impl SshManager {
/// Remembers the password / passphrase of configuration `id` for the session,
/// and in the saved passwords with `save` (`None` forgets it).
pub fn set_secret(&self, id: &str, secret: Option<String>, save: bool) {
pub fn set_secret(&self, id: &str, secret: Option<String>, save: bool) -> IdeResult<()> {
match &secret {
Some(s) => {
self.entered.lock().insert(id.to_owned(), s.clone());
@@ -96,12 +111,13 @@ impl SshManager {
}
}
match (secret, save) {
(Some(s), true) => {
if let Err(e) = self.saved.set(id, &s) {
tracing::warn!("could not save the SSH password: {}", e.message);
}
(Some(s), true) => self.saved.set(id, &s).map_err(|e| {
IdeError::unavailable(format!("The credential was kept for this session only. {}", e.message))
}),
_ => {
self.saved.delete(id);
Ok(())
}
_ => self.saved.delete(id),
}
}
+162 -15
View File
@@ -25,6 +25,14 @@ static LOCK: Mutex<()> = Mutex::new(());
/// Reads the secrets of an older version's file, by key (`None`: not that format).
pub type Legacy = fn(serde_json::Value) -> Option<BTreeMap<String, String>>;
#[derive(Clone, Copy, Deserialize, Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub enum LegacyPasswordAction {
Check,
Retry,
RemovePlaintext,
}
/// Where the secrets are kept: the default credential store, or a stand-in in tests.
pub trait Vault: Send + Sync {
fn available(&self) -> bool;
@@ -77,6 +85,7 @@ pub struct SecretFile {
path: PathBuf,
legacy: Legacy,
vault: Arc<dyn Vault>,
keep_legacy_until_moved: bool,
}
/// The file's contents. `id` keeps the credentials of different data directories
@@ -87,6 +96,11 @@ struct Index {
keys: BTreeSet<String>,
}
enum Stored {
Index(Index),
Legacy(BTreeMap<String, String>),
}
enum Contents {
Index(Index),
/// An older version's file that could not be moved, and why.
@@ -122,12 +136,17 @@ impl SecretFile {
Self::with_legacy(path, |v| serde_json::from_value(v).ok())
}
/// For the startup migration with a user-visible choice to retry or discard.
pub(crate) fn ssh_passwords(path: PathBuf) -> Self {
Self { keep_legacy_until_moved: true, ..Self::new(path) }
}
pub fn with_legacy(path: PathBuf, legacy: Legacy) -> Self {
Self::with_vault(path, legacy, Arc::new(DefaultStore))
}
pub fn with_vault(path: PathBuf, legacy: Legacy, vault: Arc<dyn Vault>) -> Self {
Self { path, legacy, vault }
Self { path, legacy, vault, keep_legacy_until_moved: false }
}
pub fn get(&self, key: &str) -> Option<String> {
@@ -222,23 +241,75 @@ impl SecretFile {
})
}
fn load(&self) -> Contents {
let value = match std::fs::read(&self.path) {
Err(_) => return Contents::Index(Index { id: new_id(), keys: BTreeSet::new() }),
Ok(bytes) => match serde_json::from_slice::<serde_json::Value>(&bytes) {
Ok(v) => v,
Err(e) => return self.set_aside(&e.to_string()),
},
fn read(&self) -> std::io::Result<Stored> {
use std::io::{Error, ErrorKind};
let bytes = match std::fs::read(&self.path) {
Err(e) if e.kind() == ErrorKind::NotFound => {
return Ok(Stored::Index(Index { id: new_id(), keys: BTreeSet::new() }));
}
other => other?,
};
let value = serde_json::from_slice::<serde_json::Value>(&bytes)
.map_err(|_| Error::new(ErrorKind::InvalidData, "invalid JSON"))?;
if let Ok(index) = serde_json::from_value::<Index>(value.clone()) {
return Contents::Index(index);
return Ok(Stored::Index(index));
}
match (self.legacy)(value) {
Some(old) => self.migrate(old),
None => self.set_aside("unknown format"),
(self.legacy)(value).map(Stored::Legacy).ok_or_else(|| Error::new(ErrorKind::InvalidData, "unknown format"))
}
fn load(&self) -> Contents {
match self.read() {
Ok(Stored::Index(index)) => Contents::Index(index),
Ok(Stored::Legacy(old)) => self.migrate(old),
Err(e) if e.kind() == std::io::ErrorKind::InvalidData => self.set_aside(&e.to_string()),
Err(e) => Contents::Plaintext(BTreeMap::new(), format!("{}: {e}", self.path.display())),
}
}
/// `Some` means plaintext remains. Never overwrite an index that another window
/// already migrated; an unreadable file is set aside, as on any other access.
pub(crate) fn resolve_legacy(&self, action: LegacyPasswordAction) -> IdeResult<Option<String>> {
off_runtime(|| {
let _g = LOCK.lock();
let old = match self.read() {
Ok(Stored::Legacy(old)) => old,
Ok(Stored::Index(_)) => return Ok(None),
Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
return match self.set_aside(&e.to_string()) {
Contents::Index(_) => Ok(None),
Contents::Plaintext(_, why) => Err(unavailable(&why)),
};
}
Err(e) => return Err(unavailable(&format!("{}: {e}", self.path.display()))),
};
if matches!(action, LegacyPasswordAction::Check) && !old.is_empty() {
return Ok(Some("Migration is incomplete.".into()));
}
if matches!(action, LegacyPasswordAction::RemovePlaintext) || old.is_empty() {
// A partial move may already have secured some keys. Preserve their
// namespace without needing the vault to be unlocked to remove plaintext.
let pending = self.pending_path();
let index = match std::fs::read_to_string(&pending) {
Ok(id) if !id.trim().is_empty() => Index { id: id.trim().into(), keys: old.into_keys().collect() },
Ok(_) => return Err(unavailable("empty migration id")),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Index { id: new_id(), keys: BTreeSet::new() },
Err(e) => return Err(unavailable(&format!("{}: {e}", pending.display()))),
};
self.write(&index)?;
if let Err(e) = std::fs::remove_file(&pending)
&& e.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!("saved passwords: could not remove {}: {e}", pending.display());
}
return Ok(None);
}
Ok(match self.migrate(old) {
Contents::Index(_) => None,
Contents::Plaintext(_, why) => Some(why),
})
})
}
/// An unreadable file is renamed rather than overwritten (it may index
/// credentials, or hold secrets); the store starts over.
fn set_aside(&self, why: &str) -> Contents {
@@ -262,8 +333,8 @@ impl SecretFile {
}
/// Moves an older version's secrets to the credential store, key by key; a secret
/// the store refuses for good (too long, say) is forgotten, and the user is asked
/// for it again. The old file is replaced only when everything else was moved.
/// the store refuses for good (too long, say) is forgotten unless the caller
/// offers explicit recovery. The old file is replaced only when everything else was moved.
/// Until then the id waits in `<file>.migrating`, so a retry after a failure or a
/// crash overwrites the same credentials instead of copying them again.
fn migrate(&self, old: BTreeMap<String, String>) -> Contents {
@@ -287,7 +358,7 @@ impl SecretFile {
Ok(()) => {
index.keys.insert(key.clone());
}
Err(e @ (StoreError::TooLong(..) | StoreError::Invalid(..))) => {
Err(e @ (StoreError::TooLong(..) | StoreError::Invalid(..))) if !self.keep_legacy_until_moved => {
tracing::warn!("saved passwords: {key} does not fit the credential store and is forgotten: {e}");
}
Err(e) => {
@@ -425,6 +496,82 @@ mod tests {
const OLD: &str = r#"{"https://a.example": "me\nold-a", "https://b.example": "me\nold-b"}"#;
#[test]
fn a_pending_plaintext_migration_can_be_retried_or_explicitly_discarded() {
use LegacyPasswordAction::{Check, RemovePlaintext, Retry};
for discard in [false, true] {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("ssh-passwords.json");
let vault = Arc::new(FakeVault::default());
let file = with_fake(&path, &vault);
assert!(file.resolve_legacy(Check).unwrap().is_none());
assert!(!path.exists());
std::fs::write(&path, OLD).unwrap();
vault.fail("https://b.example", platform);
assert!(file.resolve_legacy(Retry).unwrap().is_some());
assert!(file.resolve_legacy(Check).unwrap().is_some());
assert_eq!(std::fs::read_to_string(&path).unwrap(), OLD);
if discard {
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
}
vault.heal();
assert!(file.resolve_legacy(Retry).unwrap().is_none());
// A stale action from another window cannot erase a migrated index.
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
assert_eq!(files_containing(tmp.path(), "old-"), Vec::<PathBuf>::new());
assert_eq!(file.get("https://a.example").as_deref(), Some("me\nold-a"));
assert_eq!(file.get("https://b.example").as_deref(), (!discard).then_some("me\nold-b"));
}
}
#[test]
fn removing_plaintext_needs_no_vault_and_sets_an_unknown_format_aside() {
use LegacyPasswordAction::{RemovePlaintext, Retry};
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("ssh-passwords.json");
let vault = Arc::new(FakeVault { absent: true, ..Default::default() });
let file = with_fake(&path, &vault);
std::fs::write(&path, OLD).unwrap();
assert!(file.resolve_legacy(Retry).unwrap().is_some());
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
assert!(files_containing(tmp.path(), "old-").is_empty());
assert!(file.keys().is_empty());
std::fs::write(&path, "unknown-format").unwrap();
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
let aside = files_containing(tmp.path(), "unknown-format");
assert_eq!(aside.len(), 1);
assert_ne!(aside[0], path);
}
#[test]
fn ssh_keeps_the_only_copy_until_the_user_can_choose_what_to_do() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("ssh-passwords.json");
let vault = Arc::new(FakeVault::default());
let file = SecretFile { vault: vault.clone(), ..SecretFile::ssh_passwords(path.clone()) };
vault.fail("box", || StoreError::TooLong("password".into(), 2560));
std::fs::write(&path, r#"{"box":"legacy-value"}"#).unwrap();
assert!(file.resolve_legacy(LegacyPasswordAction::Retry).unwrap().is_some());
assert_eq!(file.get("box").as_deref(), Some("legacy-value"));
assert_eq!(files_containing(tmp.path(), "legacy-value"), std::slice::from_ref(&path));
}
#[test]
fn a_malformed_ssh_file_is_set_aside_instead_of_blocking_new_saves() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("ssh-passwords.json");
let vault = Arc::new(FakeVault::default());
let file = SecretFile { vault: vault.clone(), ..SecretFile::ssh_passwords(path.clone()) };
std::fs::write(&path, "{ malformed").unwrap();
assert!(file.resolve_legacy(LegacyPasswordAction::Check).unwrap().is_none());
let aside = files_containing(tmp.path(), "{ malformed");
assert_eq!(aside.len(), 1);
assert_ne!(aside[0], path);
file.set("box", "new-value").unwrap();
assert_eq!(file.get("box").as_deref(), Some("new-value"));
assert!(files_containing(tmp.path(), "new-value").is_empty());
}
#[test]
fn saved_secrets_never_reach_disk() {
use_memory_store();
+2 -1
View File
@@ -4,10 +4,11 @@
mod integration;
mod scrollback;
use ide_core::pty::native_pty_system;
use ide_core::utf8::Utf8Decoder;
use ide_core::{IdeError, IdeEvent, IdeResult, SharedSink, TerminalId};
use parking_lot::{Condvar, Mutex};
use portable_pty::{ChildKiller, CommandBuilder, MasterPty, PtySize, native_pty_system};
use portable_pty::{ChildKiller, CommandBuilder, MasterPty, PtySize};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::{BTreeMap, HashMap};
+3
View File
@@ -107,9 +107,12 @@ Double-click a table to edit its data, a data source to open its console, and a
| Duplicate (data source) | `⌘D` | `Ctrl+D` |
| Generate DDL to Clipboard | `⌘⌥⇧G` | `Ctrl+Alt+Shift+G` |
| Generate DDL to Query Console | `⌘⌥⇧B` | `Ctrl+Alt+Shift+B` |
| Diagrams › Show Diagram | `⌘⌥⇧U` | `Ctrl+Alt+Shift+U` |
These keys work while the Database tree has focus. The context menu also has **Truncate…**, **Run SQL Script…** (runs every statement of a `.sql` file), **Import Data from File…**, **Go to Referenced Table** (on foreign keys), SQL templates (select, insert, update, delete) and **Remove Data Source…**.
**Diagrams › Show Diagram** opens a read-only ER diagram of the selected tables, or of every table of a selected schema (up to 50), in an editor tab: columns with `PK` / `FK` markers and the foreign keys between the shown tables. Select several tables with `⌘`/`Ctrl`-click or `Shift`-click. Zoom with `⌘`/`Ctrl`+wheel; the diagram's buttons show it full screen or save it as an image.
**Modify Table…** and **New › Table** open a dialog to add, drop or change columns (name, data type, not null, primary key, default) with a live SQL preview. SQLite can only rename or drop existing columns. ClickHouse tables can't be modified this way.
## Query console
+1 -1
View File
@@ -164,7 +164,7 @@ Each form has **Host** and **Port** fields and shows the command to start the re
- **Java HotSwap**: **Run › Debugging Actions › Reload Changed Classes** compiles your changes and reloads the changed classes into the running Java debug session. Active frames keep running the old code until they return. When JDT LS finishes a build after a save, the IDE offers the reload.
- **JavaScript in the browser**: a **JavaScript Debug** configuration opens a URL in Chrome or Edge and debugs the page's scripts in their sources through source maps. See [JavaScript and TypeScript](/en/languages/javascript#debugging).
- **Maven and Gradle**: debugging a Maven or Gradle configuration starts the JVM with a JDWP agent and attaches java-debug to it.
- **Dart / Flutter**: **Hot Reload** and **Hot Restart** are available while a Dart session is running. In a Flutter project, the device selector next to the run configuration chooses where Run and Debug start the app; a run configuration's **Device** field pins it to one device. A Flutter configuration also sets the **Build mode** (Debug, Profile or Release; Profile and Release run without the debugger or hot reload), **Build flavor** and **Additional run args** (such as `--dart-define=KEY=value`); **Run › Flutter Attach** attaches the debugger to the app of the selected Flutter configuration that was started elsewhere (an add-to-app host), passing its **Additional attach args** to `flutter attach`. Saving a Dart file of a running Flutter debug session also hot reloads the app, unless the file has errors. Turn this off with **Hot reload on save** in **Settings › Build, Execution, Deployment › Debugger**.
- **Dart / Flutter**: **Settings › Languages & Frameworks › Flutter › Flutter SDK path** chooses the Flutter SDK whose `flutter` and Dart the language server, the debugger, run configurations, pub commands, the device list and **Build › Flutter** use; empty uses the ones on `PATH`. **Hot Reload** and **Hot Restart** are available while a Dart session is running. In a Flutter project, the device selector next to the run configuration chooses where Run and Debug start the app; a run configuration's **Device** field pins it to one device. A Flutter configuration also sets the **Build mode** (Debug, Profile or Release; Profile and Release run without the debugger or hot reload), **Build flavor** and **Additional run args** (such as `--dart-define=KEY=value`); **Run › Flutter Attach** attaches the debugger to the app of the selected Flutter configuration that was started elsewhere (an add-to-app host), passing its **Additional attach args** to `flutter attach`. Saving a Dart file of a running Flutter debug session also hot reloads the app, unless the file has errors. Turn this off with **Hot reload on save** in **Settings › Build, Execution, Deployment › Debugger**.
- **PHP**: if the PHP interpreter does not load Xdebug, breakpoints are skipped; the IDE warns about this when the session starts.
- **Python**: **Settings › Build, Execution, Deployment › Python Debugger** has **Attach to subprocess automatically while debugging** and **Gevent compatible**.
+5
View File
@@ -46,6 +46,11 @@ through the app-wide SSH configurations.
Saved passwords and passphrases go to the macOS Keychain, Windows Credential Manager or the Secret Service on Linux,
never to a settings file. The **+**, **−** and copy buttons above the list add, remove and duplicate configurations.
Older versions stored saved credentials in plaintext in `ssh-passwords.json`. On startup, OpenIDEA moves them into
the OS credential store. If the file still contains passwords, unlock the store and choose **Retry migration**, or
choose **Remove plaintext copy** and re-enter any credentials that were not migrated. New credentials that cannot
be saved are kept only for the session. Migration does not change old backups: rotate any exposed password.
### `~/.ssh/config` support
OpenIDEA has its own SSH client and reads `~/.ssh/config` itself. It understands `Host`, `Match`, `Include`,
+2 -1
View File
@@ -19,7 +19,7 @@ Showing an empty Terminal window opens a tab in the start directory (the project
- **+** (**New Tab**) opens a tab with the default shell.
- The **▾** button (**More Terminal Options**) has **New Terminal Tab**, **New Predefined Session** (one entry per installed shell, plus **SSH Session…**), **Split Right**, **Split Down** and **Settings**.
- Right-click a tab for **Rename Session…**, **Move to Editor**, **Close Tab**, **Close Other Tabs**, **Split Right**, **Split and Move Right**, **Split Down**, **Split and Move Down** and **Unsplit**. Double-clicking a tab also renames it.
- Drag tabs to reorder them, drop a tab on the edge of another group to split, or drag a tab into an editor group (or its edge) to keep the session running as an editor tab.
- Drag tabs to reorder them, drop a tab on the edge of another group to split, or drag a tab into an editor group (or its edge) to keep the session running as an editor tab. A terminal moved to the editor can return via **Move to Terminal** or by dragging its editor tab onto a Terminal tab strip, pane edge, or the **Terminal** stripe button.
A tab is named after your custom name, otherwise after the program running in it (when the shell reports it), otherwise `Local`, `Local (2)` and so on. A spinner shows while a command runs; **Exited** or **Failed** shows once the session ends.
@@ -56,6 +56,7 @@ The pane's context menu has **Copy**, **Paste**, **Select All**, **Clear Buffer*
- `http`, `https` and `file` URLs open in your browser. OSC 8 hyperlinks from programs work too.
- File locations such as `src/main.rs:42:7` or `Main.java(42,7)` open in the editor at that line. Paths resolve against the shell's current directory, then by file name across the project.
- Hold `⌘` (`Ctrl` on Windows/Linux) and hover over an existing file or folder name (`README.md`, `src/features`, `/tmp`) to turn it into a link: clicking opens files in an editor tab of the current window, opens project folders in the **Project** tool window, and reveals folders outside the project in Finder / Explorer / Files.
- Pasting copied files pastes their paths, quoted for the shell in use (bash/zsh/fish, PowerShell or cmd). Pasting an image from the clipboard saves it to a file and pastes that file's path.
- Dropping files from your file manager onto the terminal types their quoted paths at the prompt. They are not run.
+3
View File
@@ -107,9 +107,12 @@ description: "连接 SQL 数据库、浏览架构、在查询控制台中执行
| 复制(数据源) | `⌘D` | `Ctrl+D` |
| 生成 DDL 到剪贴板 | `⌘⌥⇧G` | `Ctrl+Alt+Shift+G` |
| 生成 DDL 到查询控制台 | `⌘⌥⇧B` | `Ctrl+Alt+Shift+B` |
| 图表 › 显示图表 | `⌘⌥⇧U` | `Ctrl+Alt+Shift+U` |
这些快捷键在数据库树获得焦点时生效。右键菜单中还有 **截断…**、**运行 SQL 脚本…**(执行某个 `.sql` 文件中的所有语句)、**从文件导入数据…**、**转到引用的表**(外键上)、SQL 模板(select、insert、update、delete)以及 **移除数据源…**。
**图表 › 显示图表** 会在编辑器标签页中打开所选表(或所选模式中的全部表,最多 50 个)的只读 ER 图:列带有 `PK` / `FK` 标记,并显示所示表之间的外键关系。用 `⌘`/`Ctrl` 单击或 `Shift` 单击可选择多个表。用 `⌘`/`Ctrl`+滚轮缩放;图上的按钮可全屏显示或保存为图片。
**修改表…** 和 **新建 › 表** 会打开一个对话框,可以添加、删除或修改列(名称、数据类型、非空、主键、默认值),并实时预览 SQL。SQLite 只能重命名或删除已有列。ClickHouse 表不能用这种方式修改。
## 查询控制台
Loaded 100 of 405 files, more files were not shown because too many files have changed in this diff. Show more