Compare commits

...
Author SHA1 Message Date
l0ng-ai 7cc52d7ed9 fix(flutter): compile the Flutter tests on Windows
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 test build failed under -D warnings.
2026-11-25 18:49:55 +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
l0ng-ai e5a4a6940a feat(agents): show images that Codex and ACP agents read, generate or receive (#5755)
Codex: an image the agent views or generates now carries its pixels into the
tool result, and images in a resumed thread's user messages (data URLs and
local files) show as images instead of a link or path.

ACP: tool results and replayed user messages show images given inline, by
data: or file:// URI, as a resource blob or as a resource_link to an image
file. A read tool that completes naming an image file but sends no image
(Cursor) shows that file.
2026-11-25 14:10:53 +08:00
l0ng-ai 196af0ac37 docs: record product and design-system context (#5726)
PRODUCT.md records the users, positioning, constraints and evidence the UI must respect.
DESIGN.md documents the visual system from src/styles/tokens.css and the src/ui primitives:
colour roles, the type scale, density and compact mode, tonal layering with shadows only on
floating surfaces, and component rules. .impeccable/ holds the design tool's config and the
machine-readable form of DESIGN.md.

The UI guidelines now say Islands Light is the default theme and list the built-in themes,
instead of describing the style as dark.
2026-11-25 14:10:49 +08:00
LU XIANGRUIandwildcatDownstairs 1e4388490c feat(flutter): start emulators and simulators from the device chooser (#5783)
The Flutter device chooser lists emulators that aren't running (Open iOS Simulator, Open Android Emulator: <name>), from the project's flutter daemon (emulator.getEmulators, asked on connect and whenever the chooser opens; one a device already runs on is left out). Choosing one shows Starting <name>… and selects its device once it connects; a failed launch shows what the tool printed. AVDs are started by ide-android in their own process group so they outlive the daemon and the IDE; the iOS Simulator goes through emulator.launch.

Part of #4096

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 14:09:37 +08:00
LU XIANGRUIandwildcatDownstairs ad8958901b feat(run): Flutter run configuration fields of the Flutter plugin (#5782)
The Flutter run configuration gets Dart entrypoint, Build mode (Debug / Profile / Release), Build flavor, Additional run args and Additional attach args next to the pinned Device. Mode and flavor become --profile / --release and --flavor=<name> on flutter run, are read back from existing command lines, and reach debug sessions too; hot reload stays debug-only. Run › Flutter Attach attaches with the selected configuration's entry point and attach args. The JetBrains importer keeps attachArgs as a form field instead of reporting it ignored.

Part of #4096

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 14:04:53 +08:00
LU XIANGRUIandwildcatDownstairs 25b49b1473 feat(flutter): Pub get / upgrade / outdated and Flutter doctor above pubspec.yaml (#5773)
pubspec.yaml gets a banner with Pub get, Pub upgrade, Pub outdated and, in Flutter packages, Flutter doctor; each runs flutter pub … (Flutter package) or dart pub … in the package folder, with output in the Run tool window. The banner warns when Pub get is due (no package config or lock, or pubspec.yaml / pubspec.lock newer than the package config); workspace members and untrusted projects get no prompt. Also in Find Action (category Flutter). Paths are matched with either separator.

Part of #4096

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 14:03:28 +08:00
Yann 1a689ff5da fix(agents): copy conversation images to the clipboard (#5785)
Conversation image thumbnails and the image preview get Copy Image (context menu, and a copy button with feedback in the preview); macOS Control-click opens the menu without opening the preview. Full-resolution PNG is copied: PNG bytes are kept, other formats are converted at their natural size. Desktop windows write the native image clipboard (Windows PNG + BITMAPV5, macOS NSPasteboard PNG, Linux GTK), so remote-project windows copy to the local machine; the browser build starts its ClipboardItem write before awaiting the conversion. Invalid or oversized images are rejected before the clipboard is touched.

Co-authored-by: YannABC <[email protected]>
2026-11-25 14:00:48 +08:00
LU XIANGRUIandwildcatDownstairs 2544db3025 feat(dart): show closing labels at the end of the line (#5766)
Dart files show closing labels after a widget's or call's closing bracket at the end of the line (`), // Column`), from the Dart server's dart/textDocument/publishClosingLabels, now requested at initialization. They are inlay hints of a new closingLabel kind, kept per document and server instance, dropped on the next edit until the server publishes again; several labels closing on one line share one hint. Editor › Inlay Hints › Closing labels (on by default) turns them off. Right-click Disable now writes the kind's own setting (it wrote inlay.type instead of inlay.types for type hints).

Part of #4096

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 13:59:24 +08:00
Mansur Akhmadiandmansur-akhmadi 6355534ed5 feat(debugger): Toggle Breakpoint Enabled action (#5764)
Enables or disables every breakpoint on the caret line, or on each line the selections and carets cover (line, method and field breakpoints), without removing them. In Find Action with no default shortcut; maps IDEA's ToggleBreakpointEnabled for imported keymaps and IdeaVim.

Closes #5763

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 13:54:06 +08:00
LU XIANGRUIandwildcatDownstairs 7bc26b9387 feat(vcs): add a Cherry-Pick button to the Git Log toolbar (#5762)
The Git Log toolbar gets a Cherry-Pick button next to Refresh that runs the existing vcs.log.cherryPick action. The context menu's can-apply rule (no merge commit, nothing from an external log) moves into canApplyCommits and backs both the action's enabled state and the menu. Hidden in external logs and File History.

Closes #5738

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 13:52:25 +08:00
l0ng-aiandDevin d7b9401a07 feat(agents): roll back files with the conversation to an earlier message (#5777)
* feat(agents): roll back files with the conversation to an earlier message

Each turn now keeps a record of the checkout as it started (HEAD, the
changed files' stamps, and copies shared between turns by path and
stamp). Rolling back to a message drops it and the later turns and puts
the files changed since back as they were before it was sent; the
message returns to the composer. Edit, Run Again From Here and
Regenerate Response put the files back the same way before running
again.

The plan is read and checked before anything changes, so a file that
can't be restored leaves the conversation and the files untouched. In
the project's own checkout only files a turn of the task changed are
restored. Tasks saved with only the last turn's record can roll back
files to their last or first message.

* fix(agents): harden turn rollback pre-checks, rename handling and confirmation

- Plan and validate all files before truncating the conversation even when rolling back to turn 0 without a turn record
- Record renamed_from paths in checkout snapshots and apply removals before writes so case-only renames restore cleanly on case-insensitive disks
- Guard rollback against concurrent operations, move file I/O and restamping out of the task lock, and emit Truncated/Task after files and turn records settle
- Scope local-mode turn rewind to the rolled-back turns' recorded changes so user edits to other turns' files stay untouched while committed files in rolled-back turns are reverted
- Use a stable blake3 hash for persisted turn copy names
- Confirm before Run Again From Here and Regenerate Response rewind files on later turns

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-25 13:51:39 +08:00
Mansur Akhmadiandmansur-akhmadi 465e4f80bc feat(vcs): Copy Commit Subject action for the Git Log (#5761)
Copies the subject lines of the selected Git Log commits, one per line, newest first. Reached from Find Action or a keymap shortcut (no menu entry, no default shortcut); maps IDEA's Vcs.CopyCommitSubjectAction.

Closes #5760

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 13:41:53 +08:00
l0ng-ai 1743aec533 test(settings): type the library roots layout probe (#5796)
The layout check from #5794 destructured a mapped array, which the e2e tsconfig types as possibly undefined, so pnpm typecheck failed on main. The rectangles are now read one by one.
2026-11-25 13:41:17 +08:00
l0ng-ai 52e2215dcf fix(database): read SQL Server catalogs under a case-sensitive collation (#5795)
A case-sensitive or binary collation resolves catalog names only in their declared case; the SQL Server introspection queries named INFORMATION_SCHEMA views and columns in lower case, so every database failed with "Invalid object name 'information_schema.schemata'". They are now upper case, and the system-schema filter matches 'INFORMATION_SCHEMA' as stored.

The foreign key queries read MySQL-only referenced_* columns that SQL Server lacks, so no foreign key ever showed; they now read sys.foreign_keys / sys.foreign_key_columns. A live test runs every query against a Latin1_General_CS_AS database.

Fixes #5772
2026-11-25 13:35:30 +08:00
l0ng-ai 57bccc916c fix(settings): keep the library roots panel at full width (#5794)
The library roots panel and its notes share a wrapping flex row; the panel grows from a zero basis, so short notes (Chinese, or a wide dialog) sat beside it and squeezed the roots tree to its toolbar's width. The notes now take a line of their own.

Fixes #5771
2026-11-25 13:31:37 +08:00
aconeshanaandaconeshana 46a712524d fix(run): leave UTF-16LE when the console output reads as UTF-8 again (#5791)
On Windows, a Run console stayed in UTF-16LE for the rest of the session once a program wrote a buffer whose tail was NUL bytes: the UTF-16 line it looked like never ended, so later UTF-8 output was decoded as UTF-16LE pairs. UTF-16LE text carries a NUL byte in every ASCII character and line end, so a read without NUL bytes that is valid UTF-8 (4 bytes or more) now ends UTF-16 even mid-line; a shorter read stays UTF-16 since one UTF-16 character can be valid UTF-8 on its own.

Closes #5768

Co-authored-by: aconeshana <[email protected]>
2026-11-25 13:17:23 +08:00
Mansur Akhmadiandmansur-akhmadi 0f5607d76c fix(editor): convert indents with the Code Style tab size and detect indents again afterwards (#5736)
With indent detection on, a detected space indent sets the editor's tab size to the indent width, so Convert Indents to Tabs in a 2-space file wrote a tab per 2 columns. The conversion now measures with the Code Style tab size (the editor's when unset), as IDEA's ConvertIndentsToTabs uses TAB_SIZE. Convert Indents also uses its own user event (input.indent.convert), after which the slot detects indents again like after Reformat Code, so the next Enter follows the converted style.

Closes #5735

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 13:15:23 +08:00
LU XIANGRUIandwildcatDownstairs 8c23c589ca feat(run): run JUnit 5 tests of Maven modules without Maven (#5571)
Gutter Run / Debug of JUnit 5 tests in Maven modules now starts OpenIDEA's own JUnit Platform runner (java/junit-runner, built from the in-tree source and embedded by ide-sdk) on the language server's test classpath instead of mvn test, as IDEA runs Maven tests unless build/run actions are delegated to Maven. The runner reports TeamCity service messages to the existing test tree; Debug and Rerun Failed Tests reuse it. The launcher jar of the engine's version comes from the classpath, else from the engine's Maven/Gradle repository folder, else is downloaded once from Maven Central.

The runner JVM gets the module's Surefire configuration like IDEA's MavenJUnitPatcher: argLine (with @{...} late replacement), systemPropertyVariables / systemProperties, environmentVariables, workingDirectory, additionalClasspathElements and classpathDependencyExcludes, read from the cached effective POM (else the module POM); the console lists what was applied.

Settings › Build Tools › Maven › Run tests using: OpenIDEA (default) or Maven (the previous mvn test -Dtest=... path). JUnit 4-only, TestNG and Gradle tests keep their current runners.

Closes #5553

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 13:15:08 +08:00
l0ng-ai ae7a8e74c8 fix(agents): quiet tool rows and use the IDE's controls and type scale (#5725)
The agents tool window looked like a separate chat app. A running tool call now shows one spinner (no entrance or pulse animation; shimmer only on summary text without a spinner); tool icons are muted, exit codes show only on failure, and terminal blocks lose their coloured edge. Home starts at the top with a 13px heading, the composer uses the text-field radius, conversation text uses line height 1.4 with tighter turn spacing, and message times are always shown. Badges, tags and the subagent chip are flat text; font sizes and heights use the shared tokens (so compact mode applies), list rows and chips use the tree and toolbar hover colours, Markdown headings stay on the UI type scale, and Compact session is a standard Button.
2026-11-25 11:26:49 +08:00
audichuang a7b67347c2 fix(vcs): let the Repository column of the Git Log be resized (#5718)
In a project with several Git roots the Git Log's Repository column was fixed at 100 px, so longer repository names were cut off. While Repository is shown, the first column's left divider (in the header and in the row strips) now resizes it through the same pair-resize path as the other columns; the width is stored in columnWidths.repository (default 100) and Reset Width is in the header's context menu. The column still keeps its place.

Closes #5291

Co-authored-by: audichuang <[email protected]>
2026-11-25 11:22:22 +08:00
Deng Liuanddengliu 707b6fe169 feat(terminal): drag terminal tabs into editor groups and splits (#5734)
Terminal tabs can be dragged from the Terminal tool window into any editor tab strip position, onto an editor pane or the empty editor area, or onto a pane edge to open a split, keeping the running session (PTY, processes, scrollback, focus). Splitting a terminal editor tab opens a fresh shell in the same working directory instead of showing one session in two panes (editor kinds can declare singleton + splitInput).

Co-authored-by: dengliu <[email protected]>
2026-11-25 11:01:14 +08:00
Mansur Akhmadiandmansur-akhmadi b9a0c66ca6 feat(workbench): Hide Side Tool Windows action (#5744)
Adds Window › Active Tool Window › Hide Side Tool Windows: hides every tool window on the active (else last active) window's side, un-maximizing that side and moving focus to the editor if it was in one of them. Available from Find Action and the native menu, with no default shortcut. IDEA keymap import and IdeaVim :action also map HideSideWindows and the existing Active Tool Window actions (HideActiveWindow, MaximizeToolWindow, JumpToLastWindow, ResizeToolWindow*).

Closes #5743

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 10:58:31 +08:00
LU XIANGRUIandwildcatDownstairs 26f83240a7 fix(debug): find Java sources when jdtls has not imported the project (#5741)
When jdtls has not imported a Maven project (e.g. a parent POM that does not resolve), Java debugging still stopped and stepped, but no frame had a file, so the editor never opened the stopped line. java-debug looks a frame's source up through jdtls and then in sourcePaths, which was never set; java-analyzer's debugger likewise falls back to sourcePaths for sibling modules. Java debug sessions (java-debug and java-analyzer, launch and attach) now pass the project's detected source and test roots as sourcePaths unless the configuration sets its own; jdtls still wins when it finds the source.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 10:57:14 +08:00
l0ng-ai c6bb0b84ce test(agents): give the hidden session tab tests room for their own waits (#5759)
hiddenWindow.test.tsx renders a long conversation twice per test and waits up to 10 s for it, but ran under the default 5 s test timeout, so on a loaded CI runner the test failed before its own wait gave up (Frontend failed on #5723 and #5736 this way). The suite now has a 30 s timeout.
2026-11-25 10:51:29 +08:00
l0ng-ai 09d1f4a673 fix(linux): follow the caret with Fcitx on GNOME Wayland (#5747)
With GTK_IM_MODULE=fcitx, Fcitx's GTK module only gets coordinates inside the window on Wayland, so with several monitors its candidate window opens on the wrong one. GNOME Wayland sessions now drop GTK_IM_MODULE when it names fcitx/fcitx5 and take input through the compositor (Mutter's text-input, served by Fcitx's IBus frontend), which places the candidates at the caret. KDE, other compositors, X11 sessions and an explicit GDK_BACKEND=x11 keep the module.

Fixes #5176
2026-11-25 10:36:38 +08:00
Mansur Akhmadiandmansur-akhmadi 3b875620d2 feat(editor): Move Caret to Page Top / Bottom actions (#5723)
Adds Move Caret to Page Top / Bottom and their With Selection variants: every caret moves to the first / last line fully shown in the editor, keeping its visual column (a line cut by the edge is used only when it is the only one there). Bound to Ctrl+PageUp / Ctrl+PageDown (+Shift) in the IntelliJ Windows keymap and Cmd+PageUp / Cmd+PageDown in the IntelliJ macOS keymap; unbound in the Eclipse and VS Code presets. IDEA keymap import and IdeaVim :action map EditorMoveToPageTop / Bottom (WithSelection).

Closes #5722

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 09:58:53 +08:00
Deng Liuanddengliu 843f2024c5 feat(plugins): expose the Git repository owning a project path (#5727)
Plugin API 1.16 adds vcs.roots and vcs.repository-at. roots lists the mapped Git worktree roots within or enclosing the project; repository-at returns the innermost mapped worktree for an existing project file or directory (a nested worktree directory names that worktree) with the repository-relative path, branch, commit, upstream, ahead count and credential-stripped remotes, or none outside Git. Both require vcs.read; repository-at also requires a trusted project. Existing project-root VCS calls are unchanged.

Co-authored-by: dengliu <[email protected]>
2026-11-25 09:36:31 +08:00
Mansur Akhmadiandmansur-akhmadi 4ed7bf14d6 feat(editor): Close Tabs to the Left / Right, Close Unmodified and Close All but Pinned as actions (#5720)
The tab menu's Close Unmodified Tabs, Close All but Pinned, Close Tabs to the Left / Right and Close All Read-Only Tabs become Window actions on the active tab of the active group, so Find Action lists them, they can take a shortcut, and IDEA keymaps / IdeaVim :action ids (CloseAllUnmodifiedEditors, CloseAllUnpinnedEditors, CloseAllToTheLeft, CloseAllToTheRight, CloseAllReadonly) map to them. Each is enabled exactly when the tab menu item would be. No default shortcuts.

Closes #5719

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 09:31:14 +08:00
l0ng-ai 4bc46baddb fix(vcs): only report state files from linked worktree gitdirs (#5730)
The project watcher reported every file below .git/worktrees/<id>/ except locks, so scratch files Git and the IDE write during read-only work (fsmonitor cookies, temporary indexes, reflogs, rebase state) each scheduled another VCS refresh. Linked worktree gitdirs now use the same allowlist as the main .git: HEAD, index, config.worktree, gitdir, commondir, locked, refs/** and the worktree entry itself.

The external metadata watcher only recognised our own status write-backs to .git/index, so a linked worktree's index refreshed VCS after every status run. The check now covers any index file.
2026-11-25 09:26:12 +08:00
598 changed files with 21549 additions and 3452 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
+15
View File
@@ -0,0 +1,15 @@
{
"detector": {
"ignoreRules": [],
"ignoreFiles": [],
"ignoreValues": [
{
"rule": "gradient-text",
"value": "*",
"files": ["src/features/agents/Session.module.css"],
"createdAt": "2026-11-24T14:58:12.514Z",
"reason": "agent: .shimmer is an animated in-progress sweep on running-step labels (commit 18b286e7e, comment documents intent), not decorative gradient text"
}
]
}
}
+557
View File
@@ -0,0 +1,557 @@
{
"schemaVersion": 2,
"generatedAt": "2026-11-24T15:06:05+00:00",
"title": "Design System: OpenIDEA",
"extensions": {
"colorMeta": {
"workbench-blue": {
"role": "primary",
"displayName": "Workbench Blue",
"canonical": "#3871e1",
"tonalRamp": [
"oklch(15% 0.073 262)",
"oklch(25% 0.121 262)",
"oklch(35% 0.17 262)",
"oklch(48% 0.17 262)",
"oklch(60% 0.17 262)",
"oklch(72% 0.136 262)",
"oklch(84% 0.078 262)",
"oklch(95% 0.024 262)"
]
},
"link-blue": {
"role": "primary",
"displayName": "Link Blue",
"canonical": "#2f5eb9",
"tonalRamp": [
"oklch(15% 0.064 262)",
"oklch(25% 0.107 262)",
"oklch(35% 0.15 262)",
"oklch(48% 0.15 262)",
"oklch(60% 0.15 262)",
"oklch(72% 0.12 262)",
"oklch(84% 0.069 262)",
"oklch(95% 0.021 262)"
]
},
"selection-wash": {
"role": "primary",
"displayName": "Selection Wash",
"canonical": "#d0dffe",
"tonalRamp": [
"oklch(15% 0.034 262)",
"oklch(25% 0.057 262)",
"oklch(35% 0.08 262)",
"oklch(48% 0.08 262)",
"oklch(60% 0.08 262)",
"oklch(72% 0.064 262)",
"oklch(84% 0.037 262)",
"oklch(95% 0.011 262)"
]
},
"tab-wash": {
"role": "primary",
"displayName": "Tab Wash",
"canonical": "#e3ebfe",
"tonalRamp": [
"oklch(15% 0.026 262)",
"oklch(25% 0.043 262)",
"oklch(35% 0.06 262)",
"oklch(48% 0.06 262)",
"oklch(60% 0.06 262)",
"oklch(72% 0.048 262)",
"oklch(84% 0.027 262)",
"oklch(95% 0.009 262)"
]
},
"danger": {
"role": "status",
"displayName": "Danger",
"canonical": "#c54e58",
"tonalRamp": [
"oklch(15% 0.064 18)",
"oklch(25% 0.107 18)",
"oklch(35% 0.15 18)",
"oklch(48% 0.15 18)",
"oklch(60% 0.15 18)",
"oklch(72% 0.12 18)",
"oklch(84% 0.069 18)",
"oklch(95% 0.021 18)"
]
},
"warning": {
"role": "status",
"displayName": "Warning",
"canonical": "#a56906",
"tonalRamp": [
"oklch(15% 0.056 70)",
"oklch(25% 0.093 70)",
"oklch(35% 0.13 70)",
"oklch(48% 0.13 70)",
"oklch(60% 0.13 70)",
"oklch(72% 0.104 70)",
"oklch(84% 0.059 70)",
"oklch(95% 0.019 70)"
]
},
"success": {
"role": "status",
"displayName": "Success",
"canonical": "#338555",
"tonalRamp": [
"oklch(15% 0.047 152)",
"oklch(25% 0.079 152)",
"oklch(35% 0.11 152)",
"oklch(48% 0.11 152)",
"oklch(60% 0.11 152)",
"oklch(72% 0.088 152)",
"oklch(84% 0.05 152)",
"oklch(95% 0.016 152)"
]
},
"frame-grey": {
"role": "neutral",
"displayName": "Frame Grey",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"island-white": {
"role": "neutral",
"displayName": "Island White",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"raised-paper": {
"role": "neutral",
"displayName": "Raised Paper",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink": {
"role": "neutral",
"displayName": "Ink",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-secondary": {
"role": "neutral",
"displayName": "Ink Secondary",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-muted": {
"role": "neutral",
"displayName": "Ink Muted",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-faint": {
"role": "neutral",
"displayName": "Ink Faint",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"hairline": {
"role": "neutral",
"displayName": "Hairline",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"control-edge": {
"role": "neutral",
"displayName": "Control Edge",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"frame-grey-dark": {
"role": "neutral",
"displayName": "Frame Grey (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"island-dark": {
"role": "neutral",
"displayName": "Island (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-dark": {
"role": "neutral",
"displayName": "Ink (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-strong-dark": {
"role": "neutral",
"displayName": "Ink Strong (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-muted-dark": {
"role": "neutral",
"displayName": "Ink Muted (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"control-edge-dark": {
"role": "neutral",
"displayName": "Control Edge (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"selection-wash-dark": {
"role": "primary",
"displayName": "Selection Wash (Dark)",
"canonical": "#2a4371",
"tonalRamp": [
"oklch(15% 0.034 262)",
"oklch(25% 0.057 262)",
"oklch(35% 0.08 262)",
"oklch(48% 0.08 262)",
"oklch(60% 0.08 262)",
"oklch(72% 0.064 262)",
"oklch(84% 0.037 262)",
"oklch(95% 0.011 262)"
]
}
},
"typographyMeta": {
"title": {
"displayName": "Title",
"purpose": "Tool window titles, section headers, dialog titles; weight 600 is the main emphasis."
},
"body": {
"displayName": "Body",
"purpose": "Default UI text, menus, rows, buttons."
},
"label": {
"displayName": "Label",
"purpose": "Secondary metadata, chips, status bar, table cells; the most-used size."
},
"label-tiny": {
"displayName": "Label Tiny",
"purpose": "Stripe labels, counters, badges."
},
"input-large": {
"displayName": "Input Large",
"purpose": "Search Everywhere and other large query fields."
},
"code": {
"displayName": "Code",
"purpose": "Editor, console, terminal and every monospace preview; size and weights are user settings."
}
},
"shadows": [
{
"name": "shadow-popup",
"value": "0 6px 20px rgba(0, 0, 0, 0.12)",
"purpose": "Popups, menus, completion, floating toolbar (Light; Dark uses 0.45 alpha)."
},
{
"name": "shadow-dialog",
"value": "0 0 0 0.5px rgba(0, 0, 0, 0.1), 0 10px 24px rgba(0, 0, 0, 0.1), 0 24px 72px rgba(0, 0, 0, 0.2)",
"purpose": "Window-style shadow for dialogs (Light)."
},
{
"name": "shadow-tooltip",
"value": "0 4px 12px rgba(0, 0, 0, 0.12)",
"purpose": "Hover tooltips (Light)."
},
{
"name": "shadow-balloon",
"value": "0 8px 24px rgba(0, 0, 0, 0.14)",
"purpose": "Notification balloons (Light)."
}
],
"motion": [
{
"name": "ease",
"value": "cubic-bezier(0.2, 0, 0, 1)",
"purpose": "Default easing for every state transition."
},
{
"name": "dur-fast",
"value": "80ms",
"purpose": "Hover, press and focus changes on controls."
},
{
"name": "dur",
"value": "140ms",
"purpose": "Standard transitions such as popup fades."
},
{
"name": "dur-slow",
"value": "220ms",
"purpose": "Upper bound for any state transition."
}
],
"density": [
{
"name": "default",
"value": "rows 24px, fields/buttons 28px, titlebar 40px, tab bar 38px, status bar 30px, island gap 6px, island radius 10px"
},
{
"name": "compact",
"value": "rows 22px, fields/buttons 24px, titlebar/headers 32px, tab bar 32px, status bar 24px, island gap 4px, island radius 8px, chrome text -1px"
}
]
},
"components": [
{
"name": "Primary Button",
"kind": "button",
"refersTo": "button-primary",
"description": "The one default action in a dialog or form.",
"html": "<button class=\"ds-btn ds-btn-primary\">OK</button>",
"css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-primary { background:var(--bg-button-primary,#3871e1); color:var(--fg-button-primary,#fff); } .ds-btn-primary:hover { background:var(--bg-button-primary-hover,#3366cc); }"
},
{
"name": "Secondary Button",
"kind": "button",
"refersTo": "button-secondary",
"description": "Every other dialog action: Cancel, Apply, Browse.",
"html": "<button class=\"ds-btn ds-btn-secondary\">Cancel</button>",
"css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-secondary { background:var(--bg-button,#fff); color:var(--fg-strong,#000); box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); } .ds-btn-secondary:hover { background:color-mix(in srgb, var(--bg-button,#fff) 94%, var(--fg-strong,#000)); }"
},
{
"name": "Ghost Button",
"kind": "button",
"refersTo": "button-ghost",
"description": "Low-emphasis text actions in headers and inline rows.",
"html": "<button class=\"ds-btn-ghost\">Show all</button>",
"css": ".ds-btn-ghost { display:inline-flex; align-items:center; height:var(--h-button,28px); padding:0 8px; border:0; background:transparent; border-radius:var(--radius-control,4px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-ui,13px); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-btn-ghost:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-btn-ghost:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-btn-ghost:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; }"
},
{
"name": "Toolbar Icon Button",
"kind": "button",
"refersTo": "icon-button",
"description": "Toolbar and tool window header actions; frameless at rest, toggles show Selection Wash.",
"html": "<div class=\"ds-iconbar\"><button class=\"ds-icon-btn\" aria-label=\"Refresh\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M13 8a5 5 0 1 1-1.46-3.54M13 3v2.5h-2.5\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg></button><button class=\"ds-icon-btn\" aria-label=\"Show options\" aria-pressed=\"true\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M2.5 4.5h11M2.5 8h11M2.5 11.5h11\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\"/></svg></button></div>",
"css": ".ds-iconbar { display:flex; gap:2px; } .ds-icon-btn { display:inline-flex; align-items:center; justify-content:center; width:24px; height:24px; padding:0; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-muted,#6c707e); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-icon-btn:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-icon-btn:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-icon-btn[aria-pressed=\"true\"] { background:var(--bg-toolbar-selected,#d0dffe); color:var(--fg-strong,#000); } .ds-icon-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
},
{
"name": "Text Field",
"kind": "input",
"refersTo": "input",
"description": "Framed text field; the frame doubles in Workbench Blue on focus.",
"html": "<input class=\"ds-input\" placeholder=\"Project name\" />",
"css": ".ds-input { height:var(--h-field,28px); padding:0 8px; border:0; appearance:none; border-radius:var(--radius-control,4px); background:var(--bg-field,#fff); color:var(--fg-strong,#000); font-family:var(--font-ui); font-size:var(--fs-ui,13px); outline:none; box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); transition:box-shadow var(--dur-fast,80ms) var(--ease); } .ds-input::placeholder { color:var(--fg-faint,#9fa2a8); } .ds-input:focus { box-shadow:inset 0 0 0 1px var(--focus-ring,#3871e1), 0 0 0 1px var(--focus-ring,#3871e1); }"
},
{
"name": "Chip",
"kind": "chip",
"refersTo": "chip",
"description": "Flat read-only fact or picker trigger, sized like the toolbar widgets.",
"html": "<button class=\"ds-chip\"><svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\"><circle cx=\"5\" cy=\"4\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"5\" cy=\"12\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"11\" cy=\"6\" r=\"1.5\" stroke=\"currentColor\"/><path d=\"M5 5.5v5M11 7.5c0 2-2 2.5-6 3\" stroke=\"currentColor\"/></svg><span>main</span></button>",
"css": ".ds-chip { display:inline-flex; align-items:center; gap:var(--space-1,4px); height:22px; padding:0 6px; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-small,12px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease); } .ds-chip svg { color:var(--fg-muted,#6c707e); } .ds-chip:hover { background:var(--bg-toolbar-hover,#00000012); } .ds-chip:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
},
{
"name": "Tree Rows",
"kind": "custom",
"refersTo": "list-row-selected",
"description": "24px rows with an inset rounded selection wash; unfocused selection turns neutral.",
"html": "<div class=\"ds-tree\" tabindex=\"0\"><div class=\"ds-row\">src</div><div class=\"ds-row ds-row-sel\">main.tsx</div><div class=\"ds-row\">workbench</div></div>",
"css": ".ds-tree { width:220px; padding:4px var(--tree-inset,6px); background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); color:var(--fg,#000); outline:none; } .ds-row { height:var(--h-row,24px); display:flex; align-items:center; padding:0 8px; border-radius:var(--radius-row,4px); } .ds-row:hover { background:var(--bg-tree-hover,#0000000a); } .ds-row-sel, .ds-row-sel:hover { background:var(--bg-tree-selected-inactive,#e9eaee); } .ds-tree:focus .ds-row-sel { background:var(--bg-tree-selected,#d0dffe); }"
},
{
"name": "Island on Frame",
"kind": "card",
"description": "The signature layout unit: rounded islands 6px apart on the grey frame, flat at rest.",
"html": "<div class=\"ds-frame\"><div class=\"ds-island ds-side\"><div class=\"ds-head\">Project</div></div><div class=\"ds-island ds-main\"><code>fn main() {}</code></div></div>",
"css": ".ds-frame { display:flex; gap:var(--island-gap,6px); padding:var(--island-gap,6px); background:var(--bg-frame,#e9eaee); height:160px; } .ds-island { background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); } .ds-side { width:140px; } .ds-main { flex:1; padding:12px; font-family:var(--font-mono); font-size:var(--fs-code,13px); color:var(--fg-editor,#080808); } .ds-head { height:40px; display:flex; align-items:center; padding:0 12px; font-family:var(--font-ui); font-size:var(--fs-ui,13px); font-weight:600; color:var(--fg-strong,#000); }"
},
{
"name": "Tooltip",
"kind": "custom",
"refersTo": "tooltip",
"description": "Floating hover help: one of the few surfaces allowed a shadow.",
"html": "<div class=\"ds-tooltip\">Run 'main' <span class=\"ds-kbd\">⌃R</span></div>",
"css": ".ds-tooltip { display:inline-flex; gap:8px; align-items:center; padding:6px 10px; border-radius:var(--radius-tooltip,6px); background:var(--bg-tooltip,#fff); color:var(--fg-tooltip,#000); border:1px solid var(--border-tooltip,#d1d3d9); box-shadow:var(--shadow-tooltip,0 4px 12px rgba(0,0,0,.12)); font-family:var(--font-ui); font-size:var(--fs-ui,13px); } .ds-kbd { font-family:var(--font-keys); color:var(--fg-muted,#6c707e); }"
}
],
"narrative": {
"northStar": "The Quiet Workbench",
"overview": "The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.\n\nThe visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.\n\nEvery panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.\n\nThe tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.\n\nExpression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.",
"keyCharacteristics": [
"JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.",
"Grey frame, rounded content islands, tonal layering only.",
"A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.",
"High density on a 4px grid. Compact mode is a first-class variant.",
"Controls are quiet at rest: toolbar buttons and chips have no frame until hover.",
"Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.",
"Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins."
],
"rules": [
{
"name": "The IDEA Reference Rule",
"body": "When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.",
"section": "overview"
},
{
"name": "The One Accent Rule",
"body": "Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.",
"section": "colors"
},
{
"name": "The Token Only Rule",
"body": "Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.",
"section": "colors"
},
{
"name": "The Flat Scale Rule",
"body": "The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.",
"section": "typography"
},
{
"name": "The User Owns Size Rule",
"body": "Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.",
"section": "typography"
},
{
"name": "The Flat at Rest Rule",
"body": "No docked panel, island, row or control gets a shadow. A shadow means \"this floats over the workbench and will go away\". Depth inside the layout is only ever a tonal step.",
"section": "elevation"
}
],
"dos": [
"**Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).",
"**Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.",
"**Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.",
"**Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.",
"**Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.",
"**Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.",
"**Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.",
"**Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`."
],
"donts": [
"**Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.",
"**Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.",
"**Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.",
"**Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.",
"**Don't** put shadows on docked panels, islands, rows or controls.",
"**Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.",
"**Don't** use hex, `rgb()` or named colours in component CSS or inline styles.",
"**Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature."
]
}
}
+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
+1
View File
@@ -4189,6 +4189,7 @@ dependencies = [
"ide-core",
"serde",
"specta",
"tempfile",
"which",
]
+323
View File
@@ -0,0 +1,323 @@
---
name: OpenIDEA
description: The IDE you know, rebuilt in Rust.
colors:
workbench-blue: "#3871e1"
link-blue: "#2f5eb9"
frame-grey: "#e9eaee"
island-white: "#ffffff"
raised-paper: "#f7f8f9"
ink: "#000000"
ink-secondary: "#5f6269"
ink-muted: "#6c707e"
ink-faint: "#9fa2a8"
hairline: "#e9eaee"
control-edge: "#d1d3d9"
selection-wash: "#d0dffe"
tab-wash: "#e3ebfe"
danger: "#c54e58"
warning: "#a56906"
success: "#338555"
frame-grey-dark: "#26282c"
island-dark: "#191a1c"
ink-dark: "#d1d3d9"
ink-strong-dark: "#dfe1e5"
ink-muted-dark: "#8c8f95"
control-edge-dark: "#40434a"
selection-wash-dark: "#2a4371"
typography:
title:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "13px"
fontWeight: 600
lineHeight: 1.4
body:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "13px"
fontWeight: 400
lineHeight: 1.4
label:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "12px"
fontWeight: 400
lineHeight: 1.4
label-tiny:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "11px"
fontWeight: 400
lineHeight: 1.4
input-large:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "15px"
fontWeight: 400
code:
fontFamily: "JetBrains Mono, JetBrains Mono Variable, ui-monospace, Menlo, monospace"
fontSize: "13px"
fontWeight: 400
lineHeight: "22px"
fontFeature: "\"liga\" 0"
rounded:
small: "4px"
control: "4px"
row: "4px"
selection: "5px"
tab: "6px"
toolbar-button: "6px"
tooltip: "6px"
popup: "8px"
island: "10px"
popup-large: "10px"
dialog: "10px"
spacing:
space-0-5: "2px"
space-1: "4px"
space-1-5: "6px"
space-2: "8px"
space-3: "12px"
space-4: "16px"
components:
button-primary:
backgroundColor: "{colors.workbench-blue}"
textColor: "{colors.island-white}"
typography: "{typography.body}"
rounded: "{rounded.control}"
padding: "0 16px"
height: "28px"
button-secondary:
backgroundColor: "{colors.island-white}"
textColor: "{colors.ink}"
typography: "{typography.body}"
rounded: "{rounded.control}"
padding: "0 16px"
height: "28px"
button-ghost:
textColor: "{colors.ink-secondary}"
typography: "{typography.body}"
rounded: "{rounded.control}"
padding: "0 8px"
height: "28px"
icon-button:
textColor: "{colors.ink-muted}"
rounded: "{rounded.toolbar-button}"
size: "24px"
icon-button-selected:
backgroundColor: "{colors.selection-wash}"
textColor: "{colors.ink}"
rounded: "{rounded.toolbar-button}"
size: "24px"
input:
backgroundColor: "{colors.island-white}"
textColor: "{colors.ink}"
typography: "{typography.body}"
rounded: "{rounded.control}"
padding: "0 8px"
height: "28px"
chip:
textColor: "{colors.ink-secondary}"
typography: "{typography.label}"
rounded: "{rounded.toolbar-button}"
padding: "0 6px"
height: "22px"
tooltip:
backgroundColor: "{colors.island-white}"
textColor: "{colors.ink}"
typography: "{typography.body}"
rounded: "{rounded.tooltip}"
padding: "6px 10px"
list-row-selected:
backgroundColor: "{colors.selection-wash}"
textColor: "{colors.ink}"
rounded: "{rounded.row}"
height: "24px"
---
# Design System: OpenIDEA
## Overview
**Creative North Star: "The Quiet Workbench"**
The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.
The visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.
Every panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.
The tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.
Expression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.
### Named Rules
**The IDEA Reference Rule.** When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.
**Key Characteristics:**
- JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.
- Grey frame, rounded content islands, tonal layering only.
- A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.
- High density on a 4px grid. Compact mode is a first-class variant.
- Controls are quiet at rest: toolbar buttons and chips have no frame until hover.
- Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.
- Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins.
## Colors
A near-neutral grey ramp with one cool blue accent. Status, VCS and syntax colours are functional vocabularies with fixed meanings. Values in the frontmatter are Islands Light (the default), and `-dark` keys are the Islands Dark counterparts. High Contrast, the Solarized themes, imported IntelliJ themes and plugin themes override the same tokens, so the names describe roles, not hexes.
### Project colour
- **Project wash** (`--project-color`): a radial tint of the project's colour (22% strength, 600 × 300px) that fades in from the frame's top-left corner, as the IDEA project gradient does. It identifies the project window. It is the one gradient in the chrome.
### Primary
- **Workbench Blue** (`--accent`): primary buttons, the focus ring, the selected-and-active stripe button, and search-match emphasis. The appearance setting can override it, so components reference `--accent`, never the hex.
- **Link Blue** (`--link`): inline links. In Dark it lightens to stay readable on the dark islands.
### Neutral
- **Frame Grey** (`--bg-frame`): the window frame behind the islands, and the stripes (the tool window button bars).
- **Island White** (`--bg-island`, `--bg-app`): editor and tool window surfaces. This is where the work lives.
- **Raised Paper** (`--bg-elev`, `--bg-dialog`): dialog bodies and inline popups, one tonal step off the island.
- **Ink** (`--fg`, `--fg-strong`): primary text. **Ink Secondary / Muted / Faint** (`--fg-secondary`, `--fg-muted`, `--fg-faint`): metadata, icons and placeholders, then disabled text.
- **Hairline** (`--border`): dividers between regions inside an island. **Control Edge** (`--border-button`, `--border-strong`): the 1px inset frame of fields and secondary buttons.
- **Selection Wash** (`--bg-tree-selected`, `--bg-selected`, `--bg-toolbar-selected`): the selected row in focused trees and lists, and pressed-on toolbar toggles. When the tree loses focus, the selection drops to the neutral `--bg-tree-selected-inactive`.
### Functional vocabularies
- **Status:** `--danger`, `--warning`, `--success` and `--info`, each with `--bg-feedback-*` and `--border-feedback-*` pairs for banners.
- **VCS and diff:** `--vcs-*` for file status in trees and tabs, `--gutter-*` for gutter marks, and `--diff-*` for diff fills and their error-stripe marks.
- **Syntax:** `--syn-*`, from the editor colour scheme. Users and plugins replace these per scheme.
### Named Rules
**The One Accent Rule.** Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.
**The Token Only Rule.** Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.
## Typography
**UI Font:** Inter Variable (with system-ui and -apple-system fallbacks)
**Code Font:** JetBrains Mono (with ui-monospace and Menlo fallbacks)
**Key Glyph Font:** the system UI font (`--font-keys`), so shortcut glyphs such as ⌘⇧⌥⌃↵ render as they do in native menus
**Character:** a neutral sans for chrome and a coding mono for content. Neither performs. Hierarchy comes from weight and colour, not size.
### Hierarchy
- **Title** (600, 13px, 1.4): tool window titles, section headers, dialog titles and emphasised names. Weight 600 is the system's main emphasis.
- **Body** (400, 13px, 1.4): default UI text, menus, tree and list rows, and buttons.
- **Label** (400, 12px): the most common size. It covers secondary metadata, chips, status bar items, table cells and hints.
- **Label Tiny** (400, 11px): stripe labels, counters and badges.
- **Input Large** (400, 15px): Search Everywhere and similar large query fields.
- **Code** (400, 13px, 22px line height): the editor, console, terminal and every monospace preview. Ligatures are off by default and follow the `editor.ligatures` setting. Users set the weights (`--fw-code`, `--fw-code-bold`) and the size.
### Named Rules
**The Flat Scale Rule.** The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.
**The User Owns Size Rule.** Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.
## Layout
The window is a grey frame holding docked islands: the editor in the centre, tool windows around it, stripes of tool window buttons on the edges (58px wide), a titlebar with the main toolbar (40px), and a status bar (30px). The status bar sits directly on the frame with no divider. Islands sit 6px apart and have 10px corners. Trees are inset 6px inside their island.
Spacing follows a 4px grid (`--space-0-5` to `--space-4`, 2–16px). It is used for gaps, with component heights doing most of the rhythm work: rows 24px, fields and buttons 28px, small controls 24px or 20px, tabs 28px in a 38px tab bar, and tool window headers 40px.
**Compact mode** (`data-compact`) is a full variant, not an afterthought. Rows drop to 22px, fields and buttons to 24px, the titlebar and headers to 32px, the status bar to 24px, the island gap to 4px and island corners to 8px, and chrome text gets 1px smaller. Every layout must hold in both modes.
The app is a desktop window. It is never a scrolling page: the document never scrolls, and every scroll region is its own scroller inside an island. Dialogs open about 10vh from the top and below the titlebar. Wide reading surfaces, such as an agent conversation, cap their width (900px) inside the island.
## Elevation & Depth
Static layout is flat and layered by tone. The grey frame sits under white islands (in Dark, a lighter frame under darker islands). Shadows exist only on surfaces that float above the layout: popups, menus, dialogs, tooltips, balloons, undocked tool windows and drag ghosts. Dialogs use a window-style shadow, because they are separate windows in spirit.
### Shadow Vocabulary
- **Popup** (`--shadow-popup`; Light `0 6px 20px rgba(0,0,0,0.12)`): popups, menus, completion and the floating editor toolbar.
- **Dialog** (`--shadow-dialog`): a hairline ring plus two soft drops, like a native window shadow.
- **Tooltip** (`--shadow-tooltip`) and **Balloon** (`--shadow-balloon`): small and medium drops for hover help and notifications.
### Named Rules
**The Flat at Rest Rule.** No docked panel, island, row or control gets a shadow. A shadow means "this floats over the workbench and will go away". Depth inside the layout is only ever a tonal step.
## Shapes
Corners scale with the size of the surface. Small controls get 4px (buttons, fields, combos, rows, small icon buttons). Toolbar buttons, chips, tabs and tooltips get 6px, and selection highlights get 5px. Popups get 8–10px, and islands and dialogs get 10px. Compact mode tightens island corners to 8px and combo corners to 2px. Frames are drawn as 1px inset box-shadows rather than borders, so they never shift layout and can double on focus. There are no pills, circles (apart from macOS window buttons and status dots), or rounding beyond 10px.
## Components
Quiet and dependable. Components don't call attention to themselves, they behave the same everywhere, and they come from `src/ui/` primitives before anything custom.
### Buttons
- **Shape:** gently rounded (4px). Minimum width 72px, 28px tall, 16px horizontal padding. The small variant is 24px tall with 10px padding.
- **Primary:** Workbench Blue fill with white text. Hover mixes it toward the strong ink colour (`--accent-hover`). Use it for one default action per dialog.
- **Secondary:** island-coloured with a 1px Control Edge inset frame. Hover darkens the fill by about 6%.
- **Ghost:** no fill or frame, secondary ink colour, 8px padding. Hover shows the toolbar hover wash and strong ink. Pressed is a stronger wash.
- **Focus:** a 2px Workbench Blue outline, 1px outside the button. **Disabled:** transparent fill, faint text and a hairline frame.
- **Motion:** background, colour and frame change over 80ms (`--dur-fast`) with `--ease`. There are no transitions under `prefers-reduced-motion`, and forced-colours mode gets a real border.
### Icon Buttons (toolbar actions)
- 20, 24 or 28px square, with 6px corners (4px at 20px). The icon is muted at rest.
- Hover shows the toolbar hover wash (`--bg-toolbar-hover`, a translucent ink) across the full hit target, and the icon turns strong ink. Pressed shows `--bg-toolbar-pressed`.
- A toggled-on button (`aria-pressed`) shows Selection Wash. The focus ring is drawn 2px inside the button.
- Tone variants (`danger`, `accent`) recolour only the icon.
### Chips
- **Style:** flat, like the main toolbar's project and branch widgets. They are 22px tall with 6px corners, have no fill or frame at rest, and use 12px secondary ink with a muted icon.
- **State:** a chip that opens a picker gets the toolbar hover wash. A read-only chip never changes on hover.
### Inputs / Fields
- **Style:** 28px tall with 8px horizontal padding and 4px corners. Island fill with a 1px Control Edge inset frame. Placeholders use the faint ink.
- **Focus:** the frame turns Workbench Blue and doubles with a 1px outer ring, drawn entirely with box-shadow.
- **Error:** the same doubled ring in `--danger`. **Disabled:** transparent fill, faint text and a hairline frame.
- Search fields have a muted leading icon. Monospace fields use the code font.
### Lists and Trees
- Rows are 24px (22px compact). The selection is a 4–5px rounded wash inset from the island edge, not a full-bleed bar.
- A focused selection uses Selection Wash, and an unfocused one drops to a neutral grey. Hover is a faint translucent wash. Search matches use `--bg-search-match`.
### Popups, Menus and Dialogs
- **Popups and menus:** `--bg-popup` with a 1px popup frame, 10px corners (`--radius-popup-large`) and the popup shadow.
- **Dialogs:** Raised Paper body with 10px corners and the dialog shadow. They behave like IDEA's dialogs, which are separate windows: the modal layer blocks the workbench but never dims it. The footer actions are right-aligned buttons. Focus returns to wherever it came from when the dialog closes.
### Tabs
- 28px tabs (24px compact) in a 38px bar, with 6px corners and 8px horizontal padding.
- As in IDEA, only the part holding focus accents its selected tab (`--bg-tab-selected` with `--border-tab-selected`). Elsewhere the selected tab drops to the neutral inactive pair.
- **Tooltips:** 6px corners with 6px × 10px padding, using `--bg-tooltip` (white in Light, dark grey in Dark) and the tooltip shadow.
### Tool Window Stripes (signature)
The edge bars of tool window buttons are 58px wide on Frame Grey, with icons over 11px labels. Hover and selected states are translucent ink washes. The selected button of the active tool window fills with Workbench Blue and white content. This is the one place the accent fills a large shape in the chrome, and it marks the active tool window.
## Do's and Don'ts
### Do:
- **Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).
- **Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.
- **Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.
- **Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.
- **Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.
- **Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.
- **Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.
- **Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`.
### Don't:
- **Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.
- **Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.
- **Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.
- **Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.
- **Don't** put shadows on docked panels, islands, rows or controls.
- **Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.
- **Don't** use hex, `rgb()` or named colours in component CSS or inline styles.
- **Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature.
+73
View File
@@ -0,0 +1,73 @@
# Product
<!-- impeccable:product-schema 1 -->
## Platform
web
The IDE is a Tauri desktop app for macOS, Windows and Linux. Its UI is a web frontend (React, CSS Modules) inside the system webview, with its own design language rather than each operating system's native one. Scope: this record covers the IDE application only. The openidea.sh docs site and home page (`docs/`) are out of scope.
## Users
- **Primary: JetBrains users who want something lighter.** They already know the IntelliJ IDEA keymap, tool windows and search-everything habits, and find IDEA heavy and slow. They do everyday multi-language development on the desktop: editing, navigating, refactoring, running and debugging, Git, terminal, database and HTTP clients.
- **Primary: developers working with AI coding agents.** They run CLI agents (Claude Code, Codex, Gemini CLI, Copilot, Cursor and others over ACP) inside the IDE as tasks, often several at once, each in its own Git worktree or in the checkout. They review the agents' diffs, answer their permission requests, and give agents the IDE's own tools through the built-in MCP server.
- **Secondary: people moving from VS Code or Eclipse.** Their keymaps are built in.
## Product Purpose
OpenIDEA brings the IntelliJ IDEA way of working to a native app with a Rust core: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages. Success means people who know the IDEA way of working can switch without relearning anything, and it opens, responds and quits much faster while using a fraction of the memory.
## Positioning
"The IDE you know, rebuilt in Rust." The habits are familiar (keymap, tool windows, Search Everywhere, Alt+Enter), the app is open source (Apache 2.0), and performance is measured: on the published benchmark, the window opens in 0.9 s against 3.1 s and the app uses 169 MB against 2011 MB. Coding agents are part of the IDE (tasks, worktrees, diffs and the IDE's tools over MCP) rather than a separate chat app.
## Operating Context
- Long sessions in one desktop window: the editor in the middle, tool windows docked around it, and keyboard-first navigation (Search Everywhere, Find Action, Go to Class/File/Symbol).
- Local projects, and remote development over SSH or in dev containers through the `openidea-server` backend.
- Agent tasks running alongside the developer's own work, with diff review and permission prompts.
- Built-in themes: Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark, with an option to follow the OS's light or dark mode. Users can import IntelliJ themes and `.icls` colour schemes, and plugins add more themes.
## Capabilities and Constraints
Hard constraints future work must preserve:
1. The default keymap and interaction habits stay the same as IDEA's.
2. All user-visible text is written in English and must also have a Chinese translation, through the text catalog (`T`, translated `aria-label`).
3. WebKit floor is Safari 15.4 (macOS 12). No regex lookbehind or `v` flag, no import attributes, and no newer runtime APIs in startup code. `scripts/check-webkit.ts` enforces this.
4. Design tokens in `src/styles/tokens.css` are the public theme API for plugins. Components use tokens only and never colour literals. A new token needs a value for every theme variant, and the docs must be regenerated with `pnpm gen:theme-docs`.
5. Every user operation is an action with a stable id, reachable from the keyboard and Find Action, not only by mouse.
6. No emoji as icons or decoration, in the UI or in user-visible text. Icons come from the `src/ui/icons.tsx` registry.
7. Performance (startup, memory, idle CPU) is the core selling point. UI work must not slow it down.
Other facts:
- Plugins are sandboxed WebAssembly components that add actions, completion, quick fixes, tool windows, custom editors, themes, file icons and languages. The plugin API is still a preview.
- UI is built from the primitives in `src/ui/` (Button, Dialog, Popup, Menu, List, Tree, Tabs and others). Workbench pieces come from contributions, not custom layout.
## Brand Commitments
- Name: OpenIDEA. Wordmarks are in `src-tauri/icons/source/` (`openidea-wordmark.svg` and `openidea-wordmark-dark.svg`).
- Not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o.
- Voice is plain, short and factual. It states measurements with their conditions rather than superlatives.
## Evidence on Hand
- Benchmark table and method: `README.md`, `perf/compare`. The conditions are stated with it: freqtrade, warm caches, median of 5 runs, Windows 11, 32-core AMD.
- Demo video linked from `README.md`.
- No testimonials, customer logos or user counts exist. Do not fabricate them.
## Product Principles
1. **Familiar first.** Existing IDEA habits must keep working. New behaviour must not break that muscle memory.
2. **Speed is a feature.** Every surface is judged by how much it costs in startup time, memory and responsiveness.
3. **Keyboard reachable.** If something can be done, it is an action that can be found and bound.
4. **Agents work inside the IDE.** Agent work is reviewed and controlled with the IDE's own tools: diffs, worktrees and permissions.
5. **Themeable by contract.** Visual decisions go through tokens that themes and plugins can rely on.
## Accessibility & Inclusion
- Use real `<button>` and `<input>` elements or the primitives that render them. Every icon-only button has a translated `aria-label`.
- Keep focus visible and predictable. Dialogs and popups return focus to where it came from.
- A dark high-contrast theme (`dark-hc`) ships and must be kept working.
+1 -1
View File
@@ -66,7 +66,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]
+143
View File
@@ -0,0 +1,143 @@
//! Images in agent content: ACP content blocks, `data:` URLs and image files on disk.
use crate::model::AgentImage;
use base64::Engine;
use serde_json::{Value, json};
use std::path::Path;
/// Image files larger than this are not inlined into the conversation.
const MAX_FILE_BYTES: u64 = 10 * 1024 * 1024;
/// The image an ACP content block shows: an `image` (inline or by URI), a `resource` with an
/// image blob, or a `resource_link` to an image file.
pub(crate) fn from_content(content: &Value) -> Option<AgentImage> {
match str_of(content, "type")? {
"image" => {
if let (Some(data), Some(mime)) = (str_of(content, "data"), str_of(content, "mimeType"))
&& mime.starts_with("image/")
{
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
}
from_uri(str_of(content, "uri")?)
}
"resource" => {
let resource = content.get("resource")?;
let (data, mime) = (str_of(resource, "blob")?, str_of(resource, "mimeType")?);
mime.starts_with("image/").then(|| AgentImage { mime_type: mime.into(), data: data.into(), name: None })
}
"resource_link" => {
let uri = str_of(content, "uri")?;
let declared = str_of(content, "mimeType").is_some_and(|m| m.starts_with("image/"));
if !declared && mime_of(Path::new(&uri_path(uri))).is_none() {
return None;
}
let mut image = from_uri(uri)?;
image.name = str_of(content, "name").map(str::to_owned);
Some(image)
}
_ => None,
}
}
fn str_of<'a>(v: &'a Value, key: &str) -> Option<&'a str> {
v.get(key).and_then(Value::as_str).filter(|s| !s.is_empty())
}
/// The image at a `data:` URL or a `file://` URI.
pub(crate) fn from_uri(uri: &str) -> Option<AgentImage> {
if let Some(rest) = uri.strip_prefix("data:") {
let (mime, data) = rest.split_once(";base64,")?;
return (mime.starts_with("image/") && !data.is_empty()).then(|| AgentImage {
mime_type: mime.into(),
data: data.into(),
name: None,
});
}
uri.starts_with("file://").then(|| from_file(Path::new(&uri_path(uri))))?
}
/// The image file at `path`, when it has an image extension and isn't too large.
pub(crate) fn from_file(path: &Path) -> Option<AgentImage> {
let mime = mime_of(path)?;
if std::fs::metadata(path).ok()?.len() > MAX_FILE_BYTES {
return None;
}
let bytes = std::fs::read(path).ok()?;
(!bytes.is_empty()).then(|| AgentImage {
mime_type: mime.into(),
data: base64::engine::general_purpose::STANDARD.encode(bytes),
name: path.file_name().and_then(|n| n.to_str()).map(str::to_owned),
})
}
/// `image` as an ACP image content block.
pub(crate) fn content(image: &AgentImage) -> Value {
json!({ "type": "image", "mimeType": image.media_type(), "data": image.data })
}
fn mime_of(path: &Path) -> Option<&'static str> {
let ext = path.extension()?.to_str()?.to_ascii_lowercase();
Some(match ext.as_str() {
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"webp" => "image/webp",
"bmp" => "image/bmp",
"svg" => "image/svg+xml",
_ => return None,
})
}
/// The path of a `file://` URI (percent-decoded); other URIs as they are.
pub(crate) fn uri_path(uri: &str) -> String {
let Some(rest) = uri.strip_prefix("file://") else { return uri.to_owned() };
let bytes = rest.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& let Some(b) = rest.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
{
out.push(b);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
let path = String::from_utf8_lossy(&out).into_owned();
// `file:///C:/x` on Windows.
match path.as_bytes() {
[b'/', drive, b':', ..] if drive.is_ascii_alphabetic() => path[1..].to_owned(),
_ => path,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn content_blocks_inline_data_urls_blobs_and_image_files() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("shot 1.png");
std::fs::write(&file, b"\x89PNG\r\n").unwrap();
std::fs::write(dir.path().join("notes.txt"), b"hi").unwrap();
let uri = crate::file_uri(&file);
let inline = json!({"type": "image", "mimeType": "image/png", "data": "aW1n"});
assert_eq!(from_content(&inline).unwrap().data, "aW1n");
let by_url = json!({"type": "image", "uri": "data:image/jpeg;base64,AAA"});
assert_eq!(from_content(&by_url).unwrap().mime_type, "image/jpeg");
let by_file = from_content(&json!({"type": "image", "uri": uri})).unwrap();
assert_eq!(by_file.data, base64::engine::general_purpose::STANDARD.encode(b"\x89PNG\r\n"));
let blob = json!({"type": "resource", "resource": {"uri": "x", "mimeType": "image/gif", "blob": "R0lG"}});
assert_eq!(from_content(&blob).unwrap().mime_type, "image/gif");
let link = from_content(&json!({"type": "resource_link", "uri": uri, "name": "shot"})).unwrap();
assert_eq!((link.mime_type.as_str(), link.name.as_deref()), ("image/png", Some("shot")));
let text = crate::file_uri(&dir.path().join("notes.txt"));
assert!(from_content(&json!({"type": "resource_link", "uri": text, "name": "notes"})).is_none());
assert!(from_content(&json!({"type": "resource", "resource": {"uri": "x", "text": "t"}})).is_none());
assert!(from_content(&json!({"type": "image", "uri": "https://example.com/a.png"})).is_none());
assert!(from_file(&dir.path().join("missing.png")).is_none());
}
}
+215 -48
View File
@@ -16,6 +16,7 @@ mod conversation;
mod elicitation;
mod external;
pub mod hermes;
mod images;
pub mod mcp;
mod model;
mod native;
@@ -330,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();
@@ -374,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);
}
@@ -419,9 +435,13 @@ struct TaskFile {
/// `None` for a worktree task, and a task saved before these were recorded.
#[serde(default, skip_serializing_if = "Option::is_none")]
touched: Option<BTreeSet<String>>,
/// The checkout as the last turn started, its copies in the store's `<id>.turn` folder.
#[serde(default, skip_serializing_if = "Option::is_none")]
/// The checkout as the last turn started, in task files saved before every turn's was kept.
#[serde(default, skip_serializing)]
turn: Option<worktree::TurnStart>,
/// The checkout as each turn of the conversation started (by turn, `None` where it wasn't
/// recorded), the copies in the store's `<id>.turn` folder.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
turns: Vec<Option<worktree::TurnStart>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
subagents: Vec<SavedSubagent>,
/// Turns to drop from the session once it is loaded (a fork of an earlier point).
@@ -455,6 +475,16 @@ impl PendingModel {
/// The changed files of a checkout, stamped.
type Snapshot = BTreeMap<String, worktree::Stamp>;
/// Holds `TaskState::busy` for the duration of an operation so concurrent prompts or rollbacks
/// wait until it finishes.
struct BusyGuard(Arc<Task>);
impl Drop for BusyGuard {
fn drop(&mut self) {
self.0.state.lock().busy = false;
}
}
struct TaskState {
task: AgentTask,
session_id: Option<String>,
@@ -467,8 +497,8 @@ struct TaskState {
saved: Option<String>,
/// See `TaskFile::touched`.
touched: Option<Arc<BTreeSet<String>>>,
/// See `TaskFile::turn`.
turn: Option<Arc<worktree::TurnStart>>,
/// See `TaskFile::turns`.
turns: Vec<Option<Arc<worktree::TurnStart>>>,
pending_rollback: u32,
/// The user named the task; see `TaskFile::title_renamed`.
title_renamed: bool,
@@ -721,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
})
@@ -989,6 +1019,7 @@ impl AgentManager {
saved: None,
touched: Some(BTreeSet::new()),
turn: None,
turns: Vec::new(),
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: true,
@@ -1043,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) {
@@ -1116,6 +1147,7 @@ impl AgentManager {
saved,
touched: (req.isolation == Isolation::Local).then(BTreeSet::new),
turn: None,
turns: Vec::new(),
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: false,
@@ -1478,8 +1510,9 @@ impl AgentManager {
before: (*s.before).clone(),
saved: s.saved.clone(),
touched: s.touched.as_deref().cloned(),
// The source's next turn replaces its copies: the fork's last turn is one of its own.
// The copies are the source's: the fork's turns are recorded as it runs them.
turn: None,
turns: Vec::new(),
subagents: s.conversation.saved_subagents(),
pending_rollback: total - keep,
title_renamed: s.title_renamed,
@@ -1496,21 +1529,31 @@ impl AgentManager {
}
/// Drops the task's turns after its first `turns`, in the agent's session and in the
/// conversation; returns the message that started the first dropped turn. Files the
/// agent changed stay as they are.
pub async fn rollback(&self, id: &str, turns: u32) -> IdeResult<Option<AgentPrompt>> {
/// conversation; returns the message that started the first dropped turn. With `files`,
/// the files the dropped turns changed go back as they were when the first of them
/// started; otherwise they stay as they are.
pub async fn rollback(&self, id: &str, turns: u32, files: bool) -> IdeResult<Option<AgentPrompt>> {
let task = self.task(id)?;
if task.state.lock().busy {
return Err(IdeError::invalid("wait until the agent is done"));
}
let starts = turn_starts(&task.state.lock().conversation.main.entries);
let Some(&cut) = starts.get(turns as usize) else { return Ok(None) };
let (starts, cut) = {
let mut s = task.state.lock();
if s.busy {
return Err(IdeError::invalid("wait until the agent is done"));
}
let starts = turn_starts(&s.conversation.main.entries);
let Some(&cut) = starts.get(turns as usize) else { return Ok(None) };
s.busy = true;
(starts, cut)
};
let guard = BusyGuard(task.clone());
// Read and checked before anything changes: a file that can't go back stops it all.
let planned = if files { self.plan_rewind(&task, turns as usize, starts.len()).await? } else { Vec::new() };
// Dropping every turn starts the conversation over, which needs no agent-side
// rewind — and some agents cannot rewind past their first turn (a resumed
// Claude Code session). A fresh session avoids both.
if turns == 0 {
task.kill();
let first = {
let restamped = self.write_rewind(&task, planned).await?;
let (first, dir, kept) = {
let mut s = task.state.lock();
let first = match s.conversation.main.entries.get(cut) {
Some(AgentEntry::User { text, .. }) => {
@@ -1527,25 +1570,29 @@ impl AgentManager {
s.task.usage = None;
s.pending_rollback = 0;
s.task.updated_ms = now_ms();
first
Self::finish_rewind(&mut s, 0, restamped);
(first, task.turn_dir(), s.turns.clone())
};
drop(guard);
task.streamed.lock().clear();
task.persist();
self.shared.emit(AgentEvent::Truncated { task: id.to_owned(), length: 0 });
task.emit_task();
self.prune_turn_copies(dir, kept).await;
return Ok(first);
}
let live = task.ensure_session().await.map_err(IdeError::internal)?;
if !live.capabilities.rollback {
return Err(IdeError::invalid("this agent can't undo turns"));
}
let drop = (starts.len() - turns as usize) as u32;
let drop_turns = (starts.len() - turns as usize) as u32;
let _: Value = live
.peer
.request("_openidea/rollback", json!({ "sessionId": live.session, "turns": drop }), None)
.request("_openidea/rollback", json!({ "sessionId": live.session, "turns": drop_turns }), None)
.await
.map_err(|e| IdeError::internal(task.describe(e)))?;
let first = {
let restamped = self.write_rewind(&task, planned).await?;
let (first, dir, kept) = {
let mut s = task.state.lock();
let first = match s.conversation.main.entries.get(cut) {
Some(AgentEntry::User { text, .. }) => Some(AgentPrompt { text: text.clone(), ..Default::default() }),
@@ -1553,12 +1600,15 @@ impl AgentManager {
};
s.conversation.truncate(cut);
s.task.updated_ms = now_ms();
first
Self::finish_rewind(&mut s, turns as usize, restamped);
(first, task.turn_dir(), s.turns.clone())
};
drop(guard);
task.streamed.lock().clear();
task.persist();
self.shared.emit(AgentEvent::Truncated { task: id.to_owned(), length: cut as u32 });
task.emit_task();
self.prune_turn_copies(dir, kept).await;
// Undoing may have started the agent: it stops again once idle.
task.release_when_idle();
Ok(first)
@@ -1916,6 +1966,98 @@ impl AgentManager {
.await
}
/// What rolling the task's files back to the start of its turn `turn` writes.
async fn plan_rewind(
&self,
task: &Arc<Task>,
turn: usize,
total_turns: usize,
) -> IdeResult<Vec<worktree::PutBack>> {
let (cwd, start, before, saved, touched, dropped_changed) = {
let s = task.state.lock();
let start = s.turns.get(turn).cloned().flatten();
let dropped = s.turns.get(turn..).unwrap_or(&[]);
let dropped_changed = (dropped.len() == total_turns - turn
&& dropped.iter().all(|t| t.as_ref().is_some_and(|t| t.changed.is_some())))
.then(|| {
dropped
.iter()
.flatten()
.filter_map(|t| t.changed.as_ref())
.flatten()
.cloned()
.collect::<BTreeSet<String>>()
});
(
s.task.cwd.0.clone(),
start,
s.before.clone(),
s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)),
s.touched.clone(),
dropped_changed,
)
};
let Some(start) = start else {
// The task's own start is the first turn's.
if turn == 0 {
let at = task.base();
return vcs(&self.shared, move || {
worktree::plan_restore(&at, &before, saved.as_deref(), touched.as_deref())
})
.await;
}
return Err(IdeError::invalid(
"the files weren't recorded as this message was sent: roll them back in the Changes view instead",
));
};
let dir = task.turn_dir();
vcs(&self.shared, move || {
let mut changed = worktree::changed_in_turn(&cwd, &start)?.1;
// In the project's own checkout, only files the rolled-back turns changed are put back.
if let Some(touched) = &touched {
let scope = dropped_changed.as_ref().unwrap_or(touched);
changed.retain(|rel| scope.contains(rel));
}
worktree::rewind(&cwd, &start, &dir, &changed)
})
.await
}
/// Writes what `plan_rewind` planned on the blocking VCS pool and computes any `before`
/// restamps off-lock.
async fn write_rewind(
&self,
task: &Arc<Task>,
planned: Vec<worktree::PutBack>,
) -> IdeResult<Vec<(String, worktree::Stamp)>> {
if planned.is_empty() {
return Ok(Vec::new());
}
let (before, saved) = {
let s = task.state.lock();
(s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)))
};
vcs(&self.shared, move || worktree::put_back(planned, &before, saved.as_deref())).await
}
/// Drops the records of the turns from `turn` on and applies any restamps to `before`.
fn finish_rewind(s: &mut TaskState, turn: usize, restamped: Vec<(String, worktree::Stamp)>) {
s.turns.truncate(turn);
if !restamped.is_empty() {
let mut before = (*s.before).clone();
before.extend(restamped);
s.before = Arc::new(before);
}
}
async fn prune_turn_copies(&self, dir: PathBuf, kept: Vec<Option<Arc<worktree::TurnStart>>>) {
let _ = vcs(&self.shared, move || {
worktree::prune_turn_copies(&dir, kept.iter().flatten().map(|t| &**t));
Ok(())
})
.await;
}
/// Rollback: puts the task's changed files among `rel_paths` (all with `None`) back as
/// `view` compares them: as they were when it started, as they are in `HEAD`, or as they
/// were when its last turn started.
@@ -1972,12 +2114,12 @@ impl AgentManager {
s.before = Arc::new(before);
}
// Rolled back further than the last turn: what it changed there is gone, not the turn's to list.
if let Some(turn) = &s.turn
if let Some(Some(turn)) = s.turns.last_mut()
&& let Some(changed) = &turn.changed
&& restored.iter().any(|rel| changed.contains(rel))
{
let changed = changed.iter().filter(|rel| !restored.contains(rel)).cloned().collect();
s.turn = Some(Arc::new(worktree::TurnStart { changed: Some(changed), ..(**turn).clone() }));
*turn = Arc::new(worktree::TurnStart { changed: Some(changed), ..(**turn).clone() });
}
}
task.persist();
@@ -2224,6 +2366,14 @@ impl Task {
config::add_client_options(&task.provider, &mut task.config);
let adopt = file.entries.is_empty() && file.session_id.is_some();
let conversation = Conversation::restore(file.entries, file.subagents);
let mut turns: Vec<_> = file.turns.into_iter().map(|t| t.map(Arc::new)).collect();
// Saved with the last turn's only: the turns before it have none.
if turns.is_empty()
&& let Some(last) = file.turn
{
turns.resize(turn_starts(&conversation.main.entries).len().saturating_sub(1), None);
turns.push(Some(Arc::new(last)));
}
let mut wanted = file.wanted;
let pending_model = file.pending_switch.or_else(|| {
let id = file.pending_model?;
@@ -2256,7 +2406,7 @@ impl Task {
before: Arc::new(file.before),
saved: file.saved,
touched: file.touched.map(Arc::new),
turn: file.turn.map(Arc::new),
turns,
pending_rollback: file.pending_rollback,
title_renamed: file.title_renamed,
busy: false,
@@ -2295,7 +2445,7 @@ impl Task {
(s.before.clone(), s.touched.clone())
}
/// Where the copies of the files already changed as the last turn started are kept.
/// Where the copies of the files already changed as the turns started are kept.
fn turn_dir(&self) -> PathBuf {
self.shared.paths.store_dir.join(format!("{}.turn", self.id))
}
@@ -2303,20 +2453,38 @@ impl Task {
/// The checkout as the last turn started, with the folder of its copies.
fn last_turn(&self) -> (PathBuf, Option<Arc<worktree::TurnStart>>, PathBuf) {
let s = self.state.lock();
(s.task.cwd.0.clone(), s.turn.clone(), self.turn_dir())
(s.task.cwd.0.clone(), s.turns.last().cloned().flatten(), self.turn_dir())
}
/// Records the checkout as a turn starts: what the turn's changes are compared with.
/// Records the checkout as a turn starts (its message shown): what the turn's changes are
/// compared with, and what rolling back to its message puts back.
async fn checkout_before_turn(self: &Arc<Self>) {
let (cwd, previous, dir) = self.last_turn();
let turn = match vcs(&self.shared, move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await {
let (cwd, dir, index, earlier) = {
let s = self.state.lock();
let index = turn_starts(&s.conversation.main.entries).len().saturating_sub(1);
let earlier: Vec<_> = s.turns.iter().take(index).cloned().collect();
(s.task.cwd.0.clone(), self.turn_dir(), index, earlier)
};
let kept = earlier.clone();
let turn = match vcs(&self.shared, move || {
let turn = worktree::start_turn(&cwd, &dir)?;
worktree::prune_turn_copies(&dir, kept.iter().flatten().map(|t| &**t).chain([&turn]));
Ok(turn)
})
.await
{
Ok(turn) => Some(Arc::new(turn)),
Err(e) => {
tracing::warn!("recording the checkout as a turn of agent task {} starts: {e}", self.id);
None
}
};
self.state.lock().turn = turn;
{
let mut s = self.state.lock();
s.turns = earlier;
s.turns.resize(index, None);
s.turns.push(turn);
}
self.persist_soon();
}
@@ -2338,7 +2506,9 @@ impl Task {
touched.extend(in_worktree);
s.touched = Some(Arc::new(touched));
}
s.turn = Some(Arc::new(worktree::TurnStart { changed: Some(all), ..(*turn).clone() }));
if let Some(last) = s.turns.last_mut() {
*last = Some(Arc::new(worktree::TurnStart { changed: Some(all), ..(*turn).clone() }));
}
}
self.persist_soon();
}
@@ -2509,7 +2679,8 @@ impl Task {
before: (*s.before).clone(),
saved: s.saved.clone(),
touched: s.touched.as_deref().cloned(),
turn: s.turn.as_deref().cloned(),
turn: None,
turns: s.turns.iter().map(|t| t.as_deref().cloned()).collect(),
subagents: s.conversation.saved_subagents(),
pending_rollback: s.pending_rollback,
title_renamed: s.title_renamed,
@@ -3666,12 +3837,8 @@ impl Task {
/// A user message of the adopted history: live turns show the user's own, so only a replay's count.
fn adopt_user_chunk(self: &Arc<Self>, update: &Value) {
let content = update.get("content");
let image = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image")).map(|c| AgentImage {
mime_type: c.get("mimeType").and_then(Value::as_str).unwrap_or_default().to_owned(),
data: c.get("data").and_then(Value::as_str).unwrap_or_default().to_owned(),
name: None,
});
let text = timeline::content_text(content).unwrap_or_default();
let image = content.and_then(images::from_content);
let text = if image.is_some() { String::new() } else { timeline::content_text(content).unwrap_or_default() };
if text.is_empty() && image.is_none() {
return;
}
@@ -473,6 +473,39 @@ fn history_replays_turns() {
assert_eq!(updates[4]["status"], "completed");
}
#[test]
fn viewed_generated_and_attached_images_carry_their_pixels() {
let dir = tempfile::tempdir().unwrap();
let png = dir.path().join("shot.png");
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
let png_path = png.to_str().unwrap();
let encoded = "iVBORw0K";
let view = json!({"id": "v", "type": "imageView", "path": png_path});
assert!(tool_call(&view, false, None, None).unwrap().get("content").is_none());
let image = &tool_call(&view, true, None, None).unwrap()["content"][0]["content"];
assert_eq!((image["type"].as_str(), image["data"].as_str()), (Some("image"), Some(encoded)));
let missing = json!({"id": "v", "type": "imageView", "path": dir.path().join("gone.png")});
assert!(tool_call(&missing, true, None, None).unwrap().get("content").is_none());
let inline = json!({"id": "g", "type": "imageGeneration", "status": "completed", "result": encoded});
let image = &tool_call(&inline, true, None, None).unwrap()["content"][0]["content"];
assert_eq!((image["mimeType"].as_str(), image["data"].as_str()), (Some("image/png"), Some(encoded)));
let saved =
json!({"id": "g", "type": "imageGeneration", "status": "completed", "fileId": "f", "savedPath": png_path});
assert_eq!(tool_call(&saved, true, None, None).unwrap()["content"][0]["content"]["data"], encoded);
let thread = json!({"turns": [{"items": [{"type": "userMessage", "id": "u", "content": [
{"type": "image", "url": "data:image/jpeg;base64,/9j/"},
{"type": "image", "url": "https://example.com/a.png"},
{"type": "localImage", "path": png_path},
{"type": "localImage", "path": "/gone.png"}
]}]}]});
let contents: Vec<Value> = history(&thread, None).into_iter().map(|u| u["content"].clone()).collect();
assert_eq!(contents[0], json!({"type": "image", "mimeType": "image/jpeg", "data": "/9j/"}));
assert_eq!(contents[1]["type"], "resource_link");
assert_eq!(contents[2], json!({"type": "image", "mimeType": "image/png", "data": encoded}));
assert_eq!(contents[3], json!({"type": "text", "text": "/gone.png"}));
}
#[test]
fn history_preserves_async_questions_with_stable_answer_ids() {
let updates = history(
+43 -26
View File
@@ -348,36 +348,18 @@ pub(super) fn user_input(prompt: &Value) -> Vec<Value> {
}
"resource" => {
let r = b.get("resource")?;
let path = uri_path(r.get("uri").and_then(Value::as_str).unwrap_or_default());
let path = crate::images::uri_path(r.get("uri").and_then(Value::as_str).unwrap_or_default());
let text = r.get("text").and_then(Value::as_str)?;
Some(json!({ "type": "text", "text": format!("<file path=\"{path}\">\n{text}\n</file>") }))
}
"resource_link" => Some(json!({ "type": "text", "text": uri_path(b.get("uri")?.as_str()?) })),
"resource_link" => {
Some(json!({ "type": "text", "text": crate::images::uri_path(b.get("uri")?.as_str()?) }))
}
_ => None,
})
.collect()
}
/// The path of a `file://` URI (percent-decoded); other URIs as they are.
fn uri_path(uri: &str) -> String {
let Some(rest) = uri.strip_prefix("file://") else { return uri.to_owned() };
let bytes = rest.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& let Some(b) = rest.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
{
out.push(b);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8_lossy(&out).into_owned()
}
/// A `session/update` notification's `update` for content.
pub(super) fn chunk(kind: &str, text: &str) -> Value {
json!({ "sessionUpdate": kind, "content": { "type": "text", "text": text } })
@@ -467,6 +449,9 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
"imageView" => {
let path = item.get("path").and_then(Value::as_str).unwrap_or_default();
call.insert("locations".into(), json!([{ "path": path }]));
if done && let Some(image) = crate::images::from_file(std::path::Path::new(path)) {
call.insert("content".into(), json!([image_content(&image)]));
}
(format!("View {}", display_path(path, cwd)), "read")
}
"collabAgentToolCall" => {
@@ -482,7 +467,12 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
}
"contextCompaction" => ("Compact the conversation".to_owned(), "other"),
"sleep" => ("Wait".to_owned(), "other"),
"imageGeneration" => ("Generate an image".to_owned(), "other"),
"imageGeneration" => {
if done && let Some(image) = generated_image(item) {
call.insert("content".into(), json!([image_content(&image)]));
}
("Generate an image".to_owned(), "other")
}
_ => return None,
};
call.insert("sessionUpdate".into(), json!(if done { "tool_call_update" } else { "tool_call" }));
@@ -493,6 +483,19 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
Some(Value::Object(call))
}
fn image_content(image: &crate::model::AgentImage) -> Value {
json!({ "type": "content", "content": crate::images::content(image) })
}
/// A generated image: inline (base64 PNG) or, when codex saved it, the file.
fn generated_image(item: &Value) -> Option<crate::model::AgentImage> {
if let Some(data) = item.get("result").and_then(Value::as_str).filter(|d| !d.is_empty()) {
let image = crate::model::AgentImage { mime_type: "image/png".into(), data: data.into(), name: None };
return Some(crate::model::AgentImage { mime_type: image.media_type().into(), ..image });
}
crate::images::from_file(std::path::Path::new(item.get("savedPath")?.as_str()?))
}
/// The output of a running command, as a `tool_call_update`.
pub(super) fn command_output(id: &str, output: &str) -> Value {
json!({ "sessionUpdate": "tool_call_update", "toolCallId": id, "content": [text_content(&tail(output))] })
@@ -856,9 +859,23 @@ pub(super) fn history(thread: &Value, cwd: Option<&str>) -> Vec<Value> {
"user_message_chunk",
c.get("text").and_then(Value::as_str).unwrap_or_default(),
)),
Some("image") => out.push(json!({ "sessionUpdate": "user_message_chunk",
"content": { "type": "resource_link", "uri": c.get("url"), "name": "image" } })),
Some("localImage" | "mention" | "skill") => {
Some("image") => {
let url = c.get("url").and_then(Value::as_str).unwrap_or_default();
let content = crate::images::from_uri(url).map_or_else(
|| json!({ "type": "resource_link", "uri": url, "name": "image" }),
|image| crate::images::content(&image),
);
out.push(json!({ "sessionUpdate": "user_message_chunk", "content": content }));
}
Some("localImage") => {
let path = c.get("path").and_then(Value::as_str).unwrap_or_default();
out.push(match crate::images::from_file(std::path::Path::new(path)) {
Some(image) => json!({ "sessionUpdate": "user_message_chunk",
"content": crate::images::content(&image) }),
None => chunk("user_message_chunk", path),
});
}
Some("mention" | "skill") => {
let path = c.get("path").and_then(Value::as_str).unwrap_or_default();
out.push(chunk("user_message_chunk", path));
}
+158 -11
View File
@@ -2688,7 +2688,7 @@ async fn forks_rollbacks_and_steering() {
}
// Undoing the last turn hands its message back.
let undone = mgr.rollback(&task.id, 1).await.unwrap().unwrap();
let undone = mgr.rollback(&task.id, 1, false).await.unwrap().unwrap();
assert_eq!(undone.text, "again");
assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 1);
assert!(agent.calls.lock().iter().any(|c| c == "_openidea/rollback 1"));
@@ -2715,7 +2715,7 @@ async fn forks_rollbacks_and_steering() {
}
handle.state.lock().conversation.main.entries.insert(0, AgentEntry::Agent { text: "Welcome".into() });
let rewinds = agent.calls.lock().iter().filter(|c| c.starts_with("_openidea/rollback")).count();
let first = mgr.rollback(&task.id, 0).await.unwrap().unwrap();
let first = mgr.rollback(&task.id, 0, false).await.unwrap().unwrap();
assert_eq!(first.text, "again");
assert!(mgr.entries(&task.id, None).unwrap().is_empty());
assert!(mgr.task(&task.id).unwrap().state.lock().session_id.is_none());
@@ -3654,7 +3654,7 @@ async fn idle_agents_stop_and_resume_their_session_on_the_next_message() {
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
tokio::time::sleep(Duration::from_millis(600)).await;
assert!(!live(&mgr, &task.id));
mgr.rollback(&task.id, 1).await.unwrap();
mgr.rollback(&task.id, 1, false).await.unwrap();
assert!(live(&mgr, &task.id));
tokio::time::sleep(Duration::from_millis(600)).await;
assert!(!live(&mgr, &task.id), "an agent started to undo turns stops too");
@@ -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")]
@@ -4665,6 +4661,157 @@ async fn the_last_turn_lists_and_rolls_back_only_its_own_changes() {
}
}
#[tokio::test(flavor = "multi_thread")]
async fn rolling_back_to_a_message_puts_back_the_files_as_it_was_sent() {
for isolation in [Isolation::Local, Isolation::Worktree] {
let repo = Checkout::new(Eol::Lf);
repo.write("a.txt", "base\n");
repo.write("gone.txt", "base\n");
repo.commit("init");
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("Hello"), provider: "claude".into(), isolation, ..Default::default() })
.await
.unwrap();
let cwd = task.cwd.0.clone();
let write = |rel: &str, text: &str| std::fs::write(cwd.join(rel), text).unwrap();
let read = |rel: &str| std::fs::read_to_string(cwd.join(rel)).ok();
let case = format!("{isolation:?}");
one_turn(&mgr, &task.id, None, || write("a.txt", "base\nturn 1\n")).await;
// The user's own work between the turns.
write("mine.txt", "mine\n");
one_turn(&mgr, &task.id, Some("more"), || {
write("a.txt", "base\nturn 1\nturn 2\n");
write("two.txt", "two\n");
})
.await;
one_turn(&mgr, &task.id, Some("last"), || {
write("a.txt", "base\nturn 1\nturn 2\nturn 3\n");
std::fs::remove_file(cwd.join("gone.txt")).unwrap();
})
.await;
// And after the last one.
write("later.txt", "later\n");
// After a restart: the turns' records are kept with the task.
mgr.shutdown();
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
let undone = mgr.rollback(&task.id, 1, true).await.unwrap().unwrap();
assert_eq!(undone.text, "more", "{case}");
assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 1, "{case}");
assert_eq!(read("a.txt").as_deref(), Some("base\nturn 1\n"), "{case}");
assert_eq!(read("gone.txt").as_deref(), Some("base\n"), "{case}");
assert_eq!(read("two.txt"), None, "{case}");
// There before the message was sent.
assert_eq!(read("mine.txt").as_deref(), Some("mine\n"), "{case}");
let later = match isolation {
// In the project's own checkout, a file no turn of the task changed is the user's.
Isolation::Local => Some("later\n"),
// In its own worktree, everything changed there since is the task's.
Isolation::Worktree => None,
};
assert_eq!(read("later.txt").as_deref(), later, "{case}");
assert_eq!(mgr.task(&task.id).unwrap().state.lock().turns.len(), 1, "{case}");
// Without `files` they stay; the first message takes the task back to its start.
one_turn(&mgr, &task.id, Some("retry"), || write("a.txt", "again\n")).await;
mgr.rollback(&task.id, 1, false).await.unwrap();
assert_eq!(read("a.txt").as_deref(), Some("again\n"), "{case}");
mgr.rollback(&task.id, 0, true).await.unwrap();
assert_eq!(read("a.txt").as_deref(), Some("base\n"), "{case}");
assert!(mgr.task(&task.id).unwrap().state.lock().turns.is_empty(), "{case}");
let left = std::fs::read_dir(repo.dir.join("store").join(format!("{}.turn", task.id)));
assert!(left.map_or(true, |mut d| d.next().is_none()), "{case}: no copies left");
mgr.delete(&task.id, true).await.unwrap();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_message_sent_before_turns_were_recorded_cannot_take_the_files_back() {
let repo = Checkout::new(Eol::Lf);
repo.write("a.txt", "base\n");
repo.commit("init");
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("Hello"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
one_turn(&mgr, &task.id, None, || repo.write("a.txt", "base\nturn 1\n")).await;
one_turn(&mgr, &task.id, Some("more"), || repo.write("a.txt", "base\nturn 1\nturn 2\n")).await;
one_turn(&mgr, &task.id, Some("last"), || repo.write("a.txt", "base\nturn 1\nturn 2\nturn 3\n")).await;
// As a task saved with its last turn's record only.
mgr.task(&task.id).unwrap().state.lock().turns[1] = None;
assert!(mgr.rollback(&task.id, 1, true).await.is_err());
assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 3, "nothing changed");
assert_eq!(repo.read("a.txt"), "base\nturn 1\nturn 2\nturn 3\n");
mgr.rollback(&task.id, 2, true).await.unwrap();
assert_eq!(repo.read("a.txt"), "base\nturn 1\nturn 2\n");
}
#[tokio::test(flavor = "multi_thread")]
async fn rolling_back_to_first_message_without_turn_record_checks_before_changing_anything() {
let repo = Checkout::new(Eol::Lf);
repo.write("a.txt", "base\n");
repo.write("b.txt", "base\n");
repo.commit("init");
repo.write("a.txt", "user edit\n");
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("Hello"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
one_turn(&mgr, &task.id, None, || {
repo.write("a.txt", "agent edit\n");
repo.write("b.txt", "agent edit\n");
})
.await;
{
let handle = mgr.task(&task.id).unwrap();
let mut s = handle.state.lock();
s.turns[0] = None;
s.saved = None;
}
assert!(mgr.rollback(&task.id, 0, true).await.is_err());
assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 1, "conversation stays intact");
assert!(mgr.task(&task.id).unwrap().state.lock().session_id.is_some(), "session stays intact");
assert_eq!(repo.read("a.txt"), "agent edit\n");
assert_eq!(repo.read("b.txt"), "agent edit\n");
}
#[tokio::test(flavor = "multi_thread")]
async fn local_turn_rollback_keeps_user_edits_to_other_turns_files_and_reverts_committed_files() {
let repo = Checkout::new(Eol::Lf);
repo.write("turn1.txt", "base\n");
repo.write("turn2.txt", "base\n");
repo.commit("init");
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
prompt: text("Hello"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
one_turn(&mgr, &task.id, None, || repo.write("turn1.txt", "turn 1\n")).await;
one_turn(&mgr, &task.id, Some("more"), || {
repo.write("turn2.txt", "turn 2\n");
repo.write("committed.txt", "from turn 2\n");
repo.git(&["add", "committed.txt"]);
repo.git(&["commit", "-q", "-m", "turn 2 commit"]);
})
.await;
// User edits a file from turn 1 after turn 2 finishes.
repo.write("turn1.txt", "turn 1 + user edit\n");
mgr.rollback(&task.id, 1, true).await.unwrap();
assert_eq!(repo.read("turn1.txt"), "turn 1 + user edit\n");
assert_eq!(repo.read("turn2.txt"), "base\n");
assert!(!repo.dir.join("committed.txt").exists());
}
#[tokio::test(flavor = "multi_thread")]
async fn rolling_back_the_whole_task_leaves_the_last_turn_nothing_to_list() {
let repo = Checkout::new(Eol::Lf);
+103 -44
View File
@@ -8,6 +8,9 @@ use std::collections::HashMap;
/// Tool output kept per call; longer output keeps its tail.
const MAX_OUTPUT: usize = 64 * 1024;
/// Image files a read tool names that are shown when it reports none itself.
const MAX_READ_IMAGES: usize = 4;
#[derive(Default)]
pub(crate) struct Timeline {
pub entries: Vec<AgentEntry>,
@@ -171,51 +174,17 @@ impl Timeline {
if update.get("locations").is_some_and(Value::is_array) {
*locs = locations(update.get("locations"));
}
let Some(content) = update.get("content").and_then(Value::as_array) else { return };
let mut text = String::new();
let mut new_diffs = Vec::new();
let mut new_images = Vec::new();
for item in content {
match item.get("type").and_then(Value::as_str) {
Some("content") => {
let content = item.get("content");
if let Some(image) = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image"))
&& let (Some(data), Some(mime)) =
(image.get("data").and_then(Value::as_str), image.get("mimeType").and_then(Value::as_str))
&& !data.is_empty()
&& mime.starts_with("image/")
{
new_images.push(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
}
if let Some(t) = content_text(content) {
if !text.is_empty() {
text.push('\n');
}
text.push_str(&t);
}
}
Some("diff") => {
let old = item.get("oldText").and_then(Value::as_str).unwrap_or_default();
let new = item.get("newText").and_then(Value::as_str).unwrap_or_default();
let (added, removed) = line_stats(old, new);
new_diffs.push(AgentToolDiff { path: IpcPath(str_field(item, "path").into()), added, removed });
}
_ => {}
}
if let Some(content) = update.get("content").and_then(Value::as_array) {
merge_content(content, output, images, diffs);
}
if !text.is_empty() {
// The command a call announced (`$ cmd`) stays above the result that replaces it.
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
text = format!("{command}\n{text}");
}
*output = Some(tail(text));
}
if !new_diffs.is_empty() {
*diffs = new_diffs;
}
if !new_images.is_empty() {
*images = new_images;
// Agents that only name the image a read tool opened (Cursor): show the file itself.
if *status == AgentToolStatus::Completed && kind == "read" && images.is_empty() {
images.extend(
locs.iter()
.filter(|p| p.0.is_absolute())
.take(MAX_READ_IMAGES)
.filter_map(|p| crate::images::from_file(&p.0)),
);
}
}
@@ -382,6 +351,54 @@ fn subagent_status(state: &Value) -> Option<(AgentSubagentStatus, Option<String>
})
}
/// Folds a tool update's content into its output, diffs and images.
fn merge_content(
content: &[Value],
output: &mut Option<String>,
images: &mut Vec<AgentImage>,
diffs: &mut Vec<AgentToolDiff>,
) {
let mut text = String::new();
let mut new_diffs = Vec::new();
let mut new_images = Vec::new();
for item in content {
match item.get("type").and_then(Value::as_str) {
Some("content") => {
let content = item.get("content");
if let Some(image) = content.and_then(crate::images::from_content) {
new_images.push(image);
} else if let Some(t) = content_text(content) {
if !text.is_empty() {
text.push('\n');
}
text.push_str(&t);
}
}
Some("diff") => {
let old = item.get("oldText").and_then(Value::as_str).unwrap_or_default();
let new = item.get("newText").and_then(Value::as_str).unwrap_or_default();
let (added, removed) = line_stats(old, new);
new_diffs.push(AgentToolDiff { path: IpcPath(str_field(item, "path").into()), added, removed });
}
_ => {}
}
}
if !text.is_empty() {
// The command a call announced (`$ cmd`) stays above the result that replaces it.
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
text = format!("{command}\n{text}");
}
*output = Some(tail(text));
}
if !new_diffs.is_empty() {
*diffs = new_diffs;
}
if !new_images.is_empty() {
*images = new_images;
}
}
/// The text of a list of content blocks, one per line.
pub(crate) fn blocks_text(content: Option<&Value>) -> String {
let blocks = content.and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
@@ -432,6 +449,7 @@ fn tail(mut text: String) -> String {
#[cfg(test)]
mod tests {
use super::*;
use crate::model::AgentImage;
use serde_json::json;
#[test]
@@ -478,6 +496,47 @@ mod tests {
assert_eq!(serde_json::from_str::<AgentEntry>(&saved).unwrap(), t.entries[0]);
}
#[test]
fn tool_images_come_from_linked_files_and_resource_blobs() {
let dir = tempfile::tempdir().unwrap();
let png = dir.path().join("out.png");
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
let mut t = Timeline::default();
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "r", "title": "Read", "kind": "read"}));
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "r", "content": [
{"type": "content", "content": {"type": "text", "text": "Read the image"}},
{"type": "content", "content": {"type": "resource_link", "uri": crate::file_uri(&png), "name": "out.png"}},
{"type": "content", "content": {"type": "resource", "resource": {"uri": "mem:1", "mimeType": "image/gif", "blob": "R0lG"}}}
]}));
let AgentEntry::Tool { images, output, .. } = &t.entries[0] else { panic!() };
let types: Vec<&str> = images.iter().map(|i| i.mime_type.as_str()).collect();
assert_eq!(types, ["image/png", "image/gif"]);
assert_eq!(output.as_deref(), Some("Read the image"));
}
#[test]
fn a_completed_read_shows_the_image_file_it_names() {
let dir = tempfile::tempdir().unwrap();
let png = dir.path().join("icon.png");
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
let text = dir.path().join("a.rs");
std::fs::write(&text, b"fn main() {}").unwrap();
let mut t = Timeline::default();
for (id, path) in [("img", &png), ("src", &text)] {
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": id, "title": "Read", "kind": "read",
"locations": [{"path": path}]}));
}
let images = |t: &Timeline, i: usize| match &t.entries[i] {
AgentEntry::Tool { images, .. } => images.len(),
_ => panic!(),
};
assert_eq!(images(&t, 0), 0, "not before the read completes");
for id in ["img", "src"] {
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": id, "status": "completed"}));
}
assert_eq!((images(&t, 0), images(&t, 1)), (1, 0));
}
#[test]
fn chunks_merge_into_one_message_until_another_entry_comes() {
let mut t = Timeline::default();
+240 -62
View File
@@ -697,12 +697,24 @@ pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, Stamp>> {
if let Some(rel) = nested_rel(&base, repo, &roots, &s.path) {
out.insert(rel, stamp(&s.path));
}
if let Some(old) = &s.renamed_from
&& let Some(rel) = nested_rel(&base, repo, &roots, &repo.root().join(old))
{
out.entry(rel).or_insert(None);
}
}
}
return Ok(out);
}
let Some(repo) = Repo::discover(cwd)? else { return Ok(BTreeMap::new()) };
Ok(repo.status()?.into_iter().map(|s| (s.rel_path, stamp(&s.path))).collect())
let mut out = BTreeMap::new();
for s in repo.status()? {
out.insert(s.rel_path, stamp(&s.path));
if let Some(old) = s.renamed_from {
out.entry(old).or_insert(None);
}
}
Ok(out)
}
/// The files whose state changed between two snapshots of a checkout: edited, new, deleted,
@@ -763,6 +775,36 @@ pub(crate) fn save_before(cwd: &Path, before: &BTreeMap<String, Stamp>, dir: &Pa
Ok(saved)
}
fn restore_content(
cwd: &Path,
rev: Option<&str>,
change: &AgentChange,
before: &BTreeMap<String, Stamp>,
saved: Option<&Path>,
) -> IdeResult<Option<Vec<u8>>> {
match before.get(&change.rel_path) {
Some(None) => Ok(None),
Some(Some(_)) => {
let copy =
saved.map(|d| d.join(saved_name(&change.rel_path))).filter(|p| p.is_file()).ok_or_else(|| {
IdeError::invalid(format!(
"{} had changes of yours when the task started that weren't saved; roll it back in Git instead",
change.rel_path
))
})?;
Ok(Some(std::fs::read(copy)?))
}
None => match rev {
Some(rev) => {
let at = change.repo.as_ref().map_or(cwd, |r| r.0.as_path());
let repo = Repo::discover(at)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
repo.file_bytes_at(&change.path.0, Some(rev))
}
None => Ok(None),
},
}
}
/// Rolls `change` back: to the copy saved when the task started when the file had changes
/// then (`before`, `saved` holding the copies), otherwise to `rev` (removed when `rev` lacks
/// it, or when there is no `rev`: the repository had no commits).
@@ -773,28 +815,35 @@ pub(crate) fn restore(
before: &BTreeMap<String, Stamp>,
saved: Option<&Path>,
) -> IdeResult<()> {
let content = match before.get(&change.rel_path) {
Some(None) => None,
Some(Some(_)) => {
let copy =
saved.map(|d| d.join(saved_name(&change.rel_path))).filter(|p| p.is_file()).ok_or_else(|| {
IdeError::invalid(format!(
"{} had changes of yours when the task started that weren't saved; roll it back in Git instead",
change.rel_path
))
})?;
Some(std::fs::read(copy)?)
}
None => match rev {
Some(rev) => {
let at = change.repo.as_ref().map_or(cwd, |r| r.0.as_path());
let repo = Repo::discover(at)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
repo.file_bytes_at(&change.path.0, Some(rev))?
}
None => None,
},
put(&change.path.0, restore_content(cwd, rev, change, before, saved)?)
}
/// The files the task changed since it started, with what to put back. Fails, changing
/// nothing, when one can't be put back.
pub(crate) fn plan_restore(
at: &TaskBase,
before: &BTreeMap<String, Stamp>,
saved: Option<&Path>,
touched: Option<&BTreeSet<String>>,
) -> IdeResult<Vec<PutBack>> {
let changes = made_by_task(at.changes(before, None)?, touched);
let rev = at.rev()?;
let sources = match rev.as_deref() {
Some(rev) => rename_sources(at.cwd(), rev)?,
None => Default::default(),
};
put(&change.path.0, content)
let mut seen = BTreeSet::new();
let mut out = Vec::new();
for change in &changes {
for change in std::iter::once(change).chain(sources.get(&change.rel_path)) {
if !seen.insert(change.rel_path.clone()) {
continue;
}
let content = restore_content(at.cwd(), rev.as_deref(), change, before, saved)?;
out.push(PutBack { rel: change.rel_path.clone(), path: change.path.0.clone(), content });
}
}
Ok(out)
}
/// Writes `content` to `path`, or removes the file when there is none.
@@ -819,7 +868,7 @@ pub(crate) fn saved_copy(dir: &Path, rel: &str) -> Option<Vec<u8>> {
std::fs::read(dir.join(saved_name(rel))).ok()
}
/// The checkout as the task's last turn started: what that turn's changes are compared with
/// The checkout as one of the task's turns started: what that turn's changes are compared with
/// and rolled back to. Recorded like the task's own start: `HEAD`, the files already changed,
/// and copies of those.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
@@ -840,13 +889,45 @@ pub(crate) struct TurnStart {
/// The files that changed while the turn ran, recorded as it ended (`None` while it runs).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub changed: Option<BTreeSet<String>>,
/// The copies are named by file and stamp, so the turns share them; the turn recorded
/// before that named them by file alone.
#[serde(default, skip_serializing_if = "is_false")]
pub stamped: bool,
}
fn is_false(b: &bool) -> bool {
!*b
}
/// The name of the copy of `rel` as stamped `stamp`: the same while the file is unchanged.
fn turn_copy_name(rel: &str, stamp: &Stamp) -> String {
let mut hasher = blake3::Hasher::new();
hasher.update(rel.as_bytes());
hasher.update(&[0]);
if let Some((len, modified)) = stamp {
hasher.update(&[1]);
hasher.update(&len.to_le_bytes());
hasher.update(&modified.to_le_bytes());
}
let hex = hasher.finalize().to_hex();
format!("t{}", &hex[..16])
}
impl TurnStart {
/// The name of the copy saved of `rel` as the turn began.
fn copy_name(&self, rel: &str) -> Option<String> {
if !self.stamped {
return Some(saved_name(rel));
}
Some(turn_copy_name(rel, self.before.get(rel)?))
}
}
/// Records the checkout at `cwd` as a turn starts, with copies of its changed files in `dir`.
/// The copies `previous` saved of files unchanged since are kept rather than made again, so
/// A copy an earlier turn saved of a file unchanged since is used rather than made again, so
/// starting a turn copies little more than what the turn before it changed.
pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -> IdeResult<TurnStart> {
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart::default()) };
pub(crate) fn start_turn(cwd: &Path, dir: &Path) -> IdeResult<TurnStart> {
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart { stamped: true, ..Default::default() }) };
let mut heads = BTreeMap::new();
let head = if at.nested {
for repo in &at.repos {
@@ -859,37 +940,95 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -
// As the turn's end is read, so the two compare.
let before = snapshot(cwd)?;
let mut saved = BTreeSet::new();
match previous {
Some(previous) => {
for rel in &previous.saved {
let unchanged =
before.get(rel).is_some_and(|now| now.is_some() && previous.before.get(rel) == Some(now));
if unchanged {
saved.insert(rel.clone());
} else {
let _ = std::fs::remove_file(dir.join(saved_name(rel)));
}
}
}
None => {
let _ = std::fs::remove_dir_all(dir);
}
}
for (rel, stamp) in &before {
let path = at.base.join(rel);
if stamp.is_none()
|| saved.contains(rel)
|| !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX)
{
if stamp.is_none() || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) {
continue;
}
let copy = dir.join(turn_copy_name(rel, stamp));
if copy.is_file() {
saved.insert(rel.clone());
continue;
}
std::fs::create_dir_all(dir)?;
// One that can't be copied is listed but can't be rolled back, as a large one.
if std::fs::copy(&path, dir.join(saved_name(rel))).is_ok() {
if std::fs::copy(&path, &copy).is_ok() {
saved.insert(rel.clone());
}
}
Ok(TurnStart { head, heads, before, saved, changed: None })
Ok(TurnStart { head, heads, before, saved, changed: None, stamped: true })
}
/// Removes the copies in `dir` that none of `turns` uses any more.
pub(crate) fn prune_turn_copies<'a>(dir: &Path, turns: impl IntoIterator<Item = &'a TurnStart>) {
let used: BTreeSet<String> =
turns.into_iter().flat_map(|t| t.saved.iter().filter_map(move |rel| t.copy_name(rel))).collect();
let Ok(read) = std::fs::read_dir(dir) else { return };
for entry in read.flatten() {
if !used.contains(&*entry.file_name().to_string_lossy()) {
let _ = std::fs::remove_file(entry.path());
}
}
}
/// A file to put back as it was.
pub(crate) struct PutBack {
/// Relative to the checkout, as the task names it.
pub rel: String,
pub path: PathBuf,
/// `None`: there was no file.
pub content: Option<Vec<u8>>,
}
/// The files among `rels` that differ from how they were as the turn `start` began, with what
/// to put back. Fails, changing nothing, when one can't be put back.
pub(crate) fn rewind(cwd: &Path, start: &TurnStart, dir: &Path, rels: &BTreeSet<String>) -> IdeResult<Vec<PutBack>> {
let Some(at) = TurnRepos::of(cwd)? else { return Ok(Vec::new()) };
let mut lower_counts: BTreeMap<String, usize> = BTreeMap::new();
for rel in rels {
*lower_counts.entry(rel.to_lowercase()).or_default() += 1;
}
let mut out = Vec::new();
for rel in rels {
let path = at.base.join(rel);
// A folder (a submodule, say) has nothing to put back.
if path.is_dir() {
continue;
}
let then = at_turn_start(&at, rel, start, dir)?;
// On a case-insensitive disk, `existing(&path)` can read a case-only rename's new name;
// keep the write so `put_back` deletes the new name and recreates the old one.
let case_collision = lower_counts.get(&rel.to_lowercase()).is_some_and(|&n| n > 1);
if !case_collision && existing(&path).is_some_and(|now| now == then) {
continue;
}
out.push(PutBack { rel: rel.clone(), path, content: then });
}
Ok(out)
}
/// Writes what `rewind` or `plan_restore` planned, returning the files back to their saved
/// pre-task copy so `before` can be restamped.
pub(crate) fn put_back(
mut planned: Vec<PutBack>,
before: &BTreeMap<String, Stamp>,
saved: Option<&Path>,
) -> IdeResult<Vec<(String, Stamp)>> {
// Removals first so a case-only rename on a case-insensitive disk ends at its old name.
planned.sort_by_key(|f| f.content.is_some());
let mut restamped = Vec::new();
for file in planned {
let should_restamp = matches!(before.get(&file.rel), Some(Some(_)))
&& file
.content
.as_deref()
.is_some_and(|bytes| saved.and_then(|d| saved_copy(d, &file.rel)).as_deref() == Some(bytes));
put(&file.path, file.content)?;
if should_restamp {
restamped.push((file.rel, stamp(&file.path)));
}
}
Ok(restamped)
}
/// The files that changed in `cwd` since the turn `start` began: in the working tree (as
@@ -919,7 +1058,12 @@ pub(crate) fn changed_in_turn(cwd: &Path, start: &TurnStart) -> IdeResult<(Vec<S
fn at_turn_start(at: &TurnRepos, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
match start.before.get(rel) {
Some(None) => Ok(None),
Some(Some(_)) => match start.saved.contains(rel).then(|| saved_copy(dir, rel)).flatten() {
Some(Some(_)) => match start
.saved
.contains(rel)
.then(|| start.copy_name(rel).and_then(|name| std::fs::read(dir.join(name)).ok()))
.flatten()
{
Some(bytes) => Ok(Some(bytes)),
None => Err(IdeError::invalid(format!(
"{rel} had changes when the turn started that weren't saved; roll it back in Git instead"
@@ -1312,30 +1456,64 @@ mod tests {
git(&repo, &["commit", "-q", "-m", "init"]);
let dir = tmp.path().join("turn");
let set = |names: &[&str]| names.iter().map(|n| (*n).to_owned()).collect::<BTreeSet<_>>();
let copy = |turn: &TurnStart, rel: &str| std::fs::read(dir.join(turn.copy_name(rel).unwrap())).ok();
let at = |turn: &TurnStart, rel: &str| {
at_turn_start(&TurnRepos::of(&repo).unwrap().unwrap(), rel, turn, &dir).unwrap()
};
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
std::fs::write(repo.join("b.txt"), "b\n").unwrap();
let first = start_turn(&repo, &dir, None).unwrap();
let first = start_turn(&repo, &dir).unwrap();
assert_eq!(first.saved, set(&["a.txt", "b.txt"]));
// A copy made again would replace this mark.
std::fs::write(dir.join(saved_name("b.txt")), "kept\n").unwrap();
std::fs::write(dir.join(first.copy_name("b.txt").unwrap()), "kept\n").unwrap();
std::thread::sleep(std::time::Duration::from_millis(10));
std::fs::write(repo.join("a.txt"), "turn two\n").unwrap();
let second = start_turn(&repo, &dir, Some(&first)).unwrap();
let second = start_turn(&repo, &dir).unwrap();
assert_eq!(second.saved, set(&["a.txt", "b.txt"]));
assert_eq!(saved_copy(&dir, "a.txt").as_deref(), Some(&b"turn two\n"[..]));
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"kept\n"[..]));
assert_eq!(copy(&second, "a.txt").as_deref(), Some(&b"turn two\n"[..]));
assert_eq!(copy(&second, "b.txt").as_deref(), Some(&b"kept\n"[..]));
// The first turn keeps its own copy of the file changed since.
assert_eq!(at(&first, "a.txt").as_deref(), Some(&b"turn 1\n"[..]));
// Back as committed: nothing to keep a copy of.
// Back as committed: nothing to keep a copy of, and the committed text is the start.
git(&repo, &["checkout", "--", "a.txt"]);
let third = start_turn(&repo, &dir, Some(&second)).unwrap();
let third = start_turn(&repo, &dir).unwrap();
assert_eq!(third.saved, set(&["b.txt"]));
assert_eq!(saved_copy(&dir, "a.txt"), None);
// Without a record of the last turn (a task from before), every copy is made afresh.
let fresh = start_turn(&repo, &dir, None).unwrap();
assert_eq!(fresh.saved, set(&["b.txt"]));
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"b\n"[..]));
assert_eq!(at(&third, "a.txt").as_deref(), Some(&b"base\n"[..]));
// Dropping the earlier turns drops the copies only they used.
prune_turn_copies(&dir, [&third]);
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
assert_eq!(copy(&third, "b.txt").as_deref(), Some(&b"kept\n"[..]));
}
#[test]
fn put_back_removes_new_name_before_writing_old_name_for_case_only_rename() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("A.txt"), "upper\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
let dir = tmp.path().join("turn");
let start = start_turn(&repo, &dir).unwrap();
git(&repo, &["mv", "A.txt", "a.txt"]);
let changed = changed_in_turn(&repo, &start).unwrap().1;
let planned = rewind(&repo, &start, &dir, &changed).unwrap();
put_back(planned, &BTreeMap::new(), None).unwrap();
assert_eq!(std::fs::read_to_string(repo.join("A.txt")).unwrap(), "upper\n");
let entries: Vec<String> = std::fs::read_dir(&repo)
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n != ".git")
.collect();
assert_eq!(entries, ["A.txt"]);
}
#[cfg(unix)]
@@ -1350,7 +1528,7 @@ mod tests {
git(&repo, &["commit", "-q", "-m", "init"]);
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
let dir = tmp.path().join("turn");
let start = start_turn(&repo, &dir, None).unwrap();
let start = start_turn(&repo, &dir).unwrap();
std::fs::write(repo.join("a.txt"), "turn 2\n").unwrap();
std::fs::write(repo.join("new.txt"), "new\n").unwrap();
let link = tmp.path().join("link");
+3
View File
@@ -10,3 +10,6 @@ ide-core.workspace = true
serde.workspace = true
specta.workspace = true
which = "8"
[dev-dependencies]
tempfile.workspace = true
+74 -2
View File
@@ -12,11 +12,12 @@ mod process;
pub use model::*;
use ide_core::process::{own_group, prepare};
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::process::{Command, Stdio};
use std::sync::OnceLock;
use std::time::Duration;
use std::time::{Duration, Instant};
/// `adb devices` is quick unless it starts the daemon, which can take a moment.
const DEVICES: Duration = Duration::from_secs(20);
@@ -28,6 +29,8 @@ const TAIL_LINES: u32 = 200;
/// while `IDLE` makes sure a quiet stream still shows its last line promptly.
const BATCH_IDLE: Duration = Duration::from_millis(60);
const BATCH_MAX: usize = 300;
/// How long a started emulator gets to fail: a locked or broken AVD exits within it.
const EMULATOR_STARTUP: Duration = Duration::from_secs(3);
fn exe(name: &str) -> String {
if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() }
@@ -91,6 +94,51 @@ fn executable() -> IdeResult<PathBuf> {
})
}
/// The SDK's `emulator` executable, which starts AVDs.
pub fn emulator_executable() -> Option<PathBuf> {
let name = exe("emulator");
sdk_roots().into_iter().map(|root| root.join("emulator").join(&name)).find(|p| p.is_file())
}
/// Starts AVD `avd` in its own process group, so it
/// outlives whoever asked: a restarted `flutter daemon`, a closed project, the IDE. Fails when
/// the emulator exits within its first seconds, with what it printed.
pub fn launch_emulator(avd: &str) -> IdeResult<()> {
let emulator = emulator_executable().ok_or_else(|| {
IdeError::unavailable(
"the Android emulator was not found: install it with the Android SDK Manager, or set ANDROID_HOME",
)
})?;
start_emulator(&emulator, avd)
}
fn start_emulator(emulator: &Path, avd: &str) -> IdeResult<()> {
let name: String = avd.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
let log_path = std::env::temp_dir().join(format!("openidea-emulator-{name}.log"));
let log = std::fs::File::create(&log_path)?;
let mut cmd = Command::new(emulator);
cmd.arg("-avd").arg(avd);
cmd.stdin(Stdio::null()).stdout(log.try_clone()?).stderr(log);
let mut child = prepare(own_group(&mut cmd)).spawn()?;
let deadline = Instant::now() + EMULATOR_STARTUP;
while Instant::now() < deadline {
if let Some(status) = child.try_wait()? {
let output = std::fs::read_to_string(&log_path).unwrap_or_default();
let tail: Vec<&str> = output.lines().filter(|l| !l.trim().is_empty()).collect();
let tail = tail[tail.len().saturating_sub(8)..].join("\n");
return Err(IdeError::unavailable(if tail.is_empty() {
format!("the emulator exited ({status})")
} else {
tail
}));
}
std::thread::sleep(Duration::from_millis(100));
}
// Reaps it whenever it ends.
std::thread::spawn(move || child.wait());
Ok(())
}
/// Connected devices, online ones first; starting the adb daemon when needed.
pub fn devices() -> IdeResult<Vec<AndroidDevice>> {
let adb = executable()?;
@@ -206,6 +254,30 @@ mod tests {
}
}
#[cfg(unix)]
#[test]
fn an_emulator_that_fails_at_once_says_why_and_one_that_runs_is_left_running() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let script = |name: &str, body: &str| {
let path = dir.path().join(name);
std::fs::write(&path, format!("#!/bin/sh\n{body}")).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
path
};
let broken = script("broken", "echo \"PANIC: Missing emulator engine for $2\" >&2\nexit 1\n");
let e = start_emulator(&broken, "Pixel_9").unwrap_err();
assert_eq!(e.message, "PANIC: Missing emulator engine for Pixel_9");
let args = dir.path().join("args");
let running =
script("running", &format!("echo $$ > '{0}.pid'\necho \"$@\" > '{0}'\nexec sleep 30\n", args.display()));
start_emulator(&running, "Pixel_9").unwrap();
assert_eq!(std::fs::read_to_string(&args).unwrap().trim(), "-avd Pixel_9");
let pid = std::fs::read_to_string(dir.path().join("args.pid")).unwrap();
assert!(Command::new("kill").arg(pid.trim()).status().unwrap().success(), "still running");
}
#[test]
fn executable_is_absolute_when_found() {
if let Some(adb) = adb_executable() {
+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| {
+1
View File
@@ -16,6 +16,7 @@ mod process;
#[cfg(test)]
mod process_numbers;
pub mod sbt;
pub mod surefire;
mod sync;
pub mod web;
mod xml;
+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();
+216
View File
@@ -0,0 +1,216 @@
//! A Maven module's Surefire configuration, for test runs OpenIDEA starts itself instead of
//! Surefire (IDEA's `MavenJUnitPatcher`): what the forked test JVM would get from the POM.
//!
//! Read from the effective POM the last sync cached (Maven merged parents, profiles and
//! `pluginManagement` there), else from the module's own `pom.xml` and its `<properties>`.
use crate::maven::{MavenModel, interpolate};
use crate::xml::{self, Element};
use std::collections::{BTreeMap, HashMap};
use std::path::Path;
const SUREFIRE: &str = "maven-surefire-plugin";
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SurefireConfig {
/// `<argLine>`, split into JVM options.
pub arg_line: Vec<String>,
/// `<systemPropertyVariables>` and the older `<systemProperties>`.
pub system_properties: BTreeMap<String, String>,
/// `<environmentVariables>`.
pub environment: BTreeMap<String, String>,
pub working_directory: Option<String>,
/// `<additionalClasspathElements>`.
pub additional_classpath: Vec<String>,
/// `<classpathDependencyExcludes>`: `groupId:artifactId`.
pub classpath_excludes: Vec<String>,
}
/// The Surefire configuration of the Maven module at `module` (absolute), if it is one.
pub fn surefire_config(root: &Path, cache_dir: &Path, model: &MavenModel, module: &Path) -> Option<SurefireConfig> {
let same = |a: &Path, b: &Path| dunce::canonicalize(a).ok() == dunce::canonicalize(b).ok();
let project = model.projects.iter().find(|p| same(&root.join(&p.dir), module))?;
let pom = root.join(&project.pom);
let modified = |p: &Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();
// A cache written before the POM last changed would apply an old configuration.
let effective = std::fs::read_dir(cache_dir).ok()?.flatten().map(|e| e.path()).find_map(|path| {
let name = path.file_name()?.to_str()?;
if !(name.starts_with("effective-pom-") && name.ends_with(".xml")) || modified(&path) < modified(&pom) {
return None;
}
let root = xml::parse(&xml::read_text(&path)?)?;
let projects: Vec<Element> = if root.name == "projects" {
root.children.into_iter().filter(|p| p.name == "project").collect()
} else {
vec![root]
};
projects.into_iter().find(|p| {
let group = p.text_of("groupId").or_else(|| p.at("parent/groupId").map(|g| g.text.trim().to_owned()));
group.as_deref() == Some(project.group_id.as_str())
&& p.text_of("artifactId").as_deref() == Some(&project.artifact_id)
})
});
let (element, own) = match effective {
Some(e) => (e, false),
// ponytail: without a sync, inherited configuration and parent properties are missing; Reload adds them.
None => (xml::parse(&xml::read_text(&pom)?)?, true),
};
let mut props: HashMap<String, String> = element
.child("properties")
.map(|p| p.children.iter().map(|c| (c.name.clone(), c.text.trim().to_owned())).collect())
.unwrap_or_default();
let dir = module.to_string_lossy().into_owned();
for (key, value) in [
("basedir", dir.clone()),
("project.basedir", dir.clone()),
("project.build.directory", format!("{dir}/target")),
("project.groupId", project.group_id.clone()),
("project.artifactId", project.artifact_id.clone()),
("project.version", project.version.clone()),
] {
props.entry(key.into()).or_insert(value);
}
Some(read(&element, &props, own))
}
/// `<build><plugins>` Surefire's configuration, then its `default-test` execution's.
fn read(project: &Element, props: &HashMap<String, String>, own: bool) -> SurefireConfig {
let is_surefire = |p: &&Element| p.text_of("artifactId").as_deref() == Some(SUREFIRE);
let mut plugins: Vec<&Element> = project.list("build/plugins", "plugin").into_iter().filter(is_surefire).collect();
if own && plugins.is_empty() {
plugins = project.list("build/pluginManagement/plugins", "plugin").into_iter().filter(is_surefire).collect();
}
let mut configurations: Vec<&Element> = Vec::new();
for plugin in plugins {
configurations.extend(plugin.child("configuration"));
let default_test = plugin
.list("executions", "execution")
.into_iter()
.find(|e| e.text_of("id").as_deref() == Some("default-test"));
configurations.extend(default_test.and_then(|e| e.child("configuration")));
}
let value = |text: &str| resolve(text.trim(), props);
let mut config = SurefireConfig::default();
for c in configurations {
if let Some(arg_line) = c.child("argLine") {
config.arg_line = split_arg_line(&value(&arg_line.text));
}
for p in c.child("systemPropertyVariables").map_or(&[][..], |p| &p.children) {
config.system_properties.insert(p.name.clone(), value(&p.text));
}
// `<systemProperties>`: `<property><name/><value/></property>` (deprecated, still honoured).
for p in c.list("systemProperties", "property") {
if let Some(name) = p.text_of("name") {
config.system_properties.insert(name, value(&p.text_of("value").unwrap_or_default()));
}
}
for e in c.child("environmentVariables").map_or(&[][..], |e| &e.children) {
config.environment.insert(e.name.clone(), value(&e.text));
}
if let Some(dir) = c.text_of("workingDirectory").map(|d| value(&d)).filter(|d| !d.is_empty()) {
config.working_directory = Some(dir);
}
let texts = |list: &str, item: &str| -> Vec<String> {
c.list(list, item).into_iter().map(|e| value(&e.text)).filter(|t| !t.is_empty()).collect()
};
config.additional_classpath.extend(texts("additionalClasspathElements", "additionalClasspathElement"));
config.classpath_excludes.extend(texts("classpathDependencyExcludes", "classpathDependencyExclude"));
}
config
}
/// `${…}` from the POM's properties, then Surefire's late replacement `@{…}` (a property a plugin
/// sets during the build, such as JaCoCo's `argLine`, is unknown here and left out, as in IDEA).
fn resolve(text: &str, props: &HashMap<String, String>) -> String {
let mut out = interpolate(text, props);
for open in ["@{", "${"] {
while let Some(start) = out.find(open) {
let Some(len) = out[start..].find('}') else { break };
let key = &out[start + 2..start + len];
let replacement = if open == "@{" { props.get(key).cloned().unwrap_or_default() } else { String::new() };
out.replace_range(start..=start + len, &replacement);
}
}
out.trim().to_owned()
}
/// Splits `argLine` as Surefire does (plexus `CommandLineUtils`): whitespace, `"…"` and `'…'`, no escapes.
fn split_arg_line(line: &str) -> Vec<String> {
let mut out = Vec::new();
let mut current: Option<String> = None;
let mut quote: Option<char> = None;
for c in line.chars() {
match quote {
Some(q) if c == q => quote = None,
Some(_) => current.get_or_insert_default().push(c),
None if c == '"' || c == '\'' => {
quote = Some(c);
current.get_or_insert_default();
}
None if c.is_whitespace() => out.extend(current.take()),
None => current.get_or_insert_default().push(c),
}
}
out.extend(current);
out
}
#[cfg(test)]
mod tests {
use super::*;
const POM: &str = r#"<project>
<groupId>com.example</groupId><artifactId>orders</artifactId><version>1</version>
<properties><openideaFail>true</openideaFail><mockito>/m2/mockito.jar</mockito></properties>
<build><plugins><plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>@{argLine} @{jacoco} -javaagent:${mockito} --add-opens "java.base/java.lang=ALL-UNNAMED" -Dx=${undefined}</argLine>
<systemPropertyVariables><openidea.fail>${openideaFail}</openidea.fail><dir>${project.build.directory}</dir></systemPropertyVariables>
<systemProperties><property><name>old</name><value>style</value></property></systemProperties>
<environmentVariables><TZ>UTC</TZ></environmentVariables>
<additionalClasspathElements><additionalClasspathElement>${basedir}/extra</additionalClasspathElement></additionalClasspathElements>
<classpathDependencyExcludes><classpathDependencyExclude>org.slf4j:slf4j-simple</classpathDependencyExclude></classpathDependencyExcludes>
</configuration>
<executions><execution><id>default-test</id><configuration><workingDirectory>${basedir}/work</workingDirectory></configuration></execution></executions>
</plugin></plugins></build>
</project>"#;
fn model(dir: &Path) -> MavenModel {
crate::maven::load(dir)
}
#[test]
fn reads_the_module_pom_and_the_effective_pom_the_sync_cached() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(root.join("pom.xml"), POM).unwrap();
let cache = root.join("cache");
std::fs::create_dir_all(&cache).unwrap();
let config = surefire_config(root, &cache, &model(root), root).unwrap();
let d = root.to_string_lossy();
assert_eq!(
config.arg_line,
["-javaagent:/m2/mockito.jar", "--add-opens", "java.base/java.lang=ALL-UNNAMED", "-Dx="]
);
assert_eq!(config.system_properties["openidea.fail"], "true");
assert_eq!(config.system_properties["dir"], format!("{d}/target"));
assert_eq!(config.system_properties["old"], "style");
assert_eq!(config.environment["TZ"], "UTC");
assert_eq!(config.working_directory, Some(format!("{d}/work")));
assert_eq!(config.additional_classpath, [format!("{d}/extra")]);
assert_eq!(config.classpath_excludes, ["org.slf4j:slf4j-simple"]);
// A sync's effective POM wins: it has what the module inherits.
let effective = POM.replace("<argLine>", "<argLine>-Xmx1g ").replace("<TZ>UTC</TZ>", "<TZ>Asia/Tokyo</TZ>");
std::fs::write(cache.join("effective-pom-0.xml"), format!("<projects>{effective}</projects>")).unwrap();
let config = surefire_config(root, &cache, &model(root), root).unwrap();
assert_eq!(config.arg_line[0], "-Xmx1g");
assert_eq!(config.environment["TZ"], "Asia/Tokyo");
}
#[test]
fn splits_arg_line_like_surefire() {
assert_eq!(split_arg_line(r#" -a "b c" 'd "e"' C:\x\y "" "#), ["-a", "b c", r#"d "e""#, r"C:\x\y", ""]);
}
}
+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,
+85
View File
@@ -0,0 +1,85 @@
use std::io::{Cursor, Error, ErrorKind, Result};
/// A top-down BITMAPV5HEADER and BGRA pixels. The alpha mask lets native paste targets
/// retain transparency; the PNG flavor is also written for browsers and image editors.
pub(crate) fn png_to_dib(png: &[u8]) -> Result<Vec<u8>> {
let invalid = |error| Error::new(ErrorKind::InvalidData, error);
let mut decoder = png::Decoder::new(Cursor::new(png));
decoder.set_transformations(png::Transformations::normalize_to_color8());
let mut reader = decoder.read_info().map_err(invalid)?;
let rgba_size = (reader.info().width as usize)
.checked_mul(reader.info().height as usize)
.and_then(|pixels| pixels.checked_mul(4))
.filter(|size| *size <= 64 * 1024 * 1024)
.ok_or_else(|| Error::new(ErrorKind::InvalidData, "Clipboard image is too large"))?;
let size = reader
.output_buffer_size()
.filter(|size| *size <= 64 * 1024 * 1024)
.ok_or_else(|| Error::new(ErrorKind::InvalidData, "Clipboard image is too large"))?;
let mut pixels = vec![0; size];
let info = reader.next_frame(&mut pixels).map_err(invalid)?;
let mut dib = vec![0; 124];
dib[0..4].copy_from_slice(&124u32.to_le_bytes());
dib[4..8].copy_from_slice(&info.width.to_le_bytes());
dib[8..12].copy_from_slice(&(-(info.height as i32)).to_le_bytes());
dib[12..14].copy_from_slice(&1u16.to_le_bytes());
dib[14..16].copy_from_slice(&32u16.to_le_bytes());
dib[16..20].copy_from_slice(&3u32.to_le_bytes()); // BI_BITFIELDS
dib[20..24].copy_from_slice(&(rgba_size as u32).to_le_bytes());
for (at, value) in [(40, 0x00ff0000u32), (44, 0x0000ff00), (48, 0x000000ff), (52, 0xff000000), (56, 0x73524742)] {
dib[at..at + 4].copy_from_slice(&value.to_le_bytes());
}
dib[108..112].copy_from_slice(&4u32.to_le_bytes()); // LCS_GM_IMAGES
for pixel in pixels[..info.buffer_size()].chunks_exact(info.color_type.samples()) {
let rgba = match info.color_type {
png::ColorType::Rgba => [pixel[0], pixel[1], pixel[2], pixel[3]],
png::ColorType::Rgb => [pixel[0], pixel[1], pixel[2], 255],
png::ColorType::Grayscale => [pixel[0], pixel[0], pixel[0], 255],
png::ColorType::GrayscaleAlpha => [pixel[0], pixel[0], pixel[0], pixel[1]],
png::ColorType::Indexed => unreachable!("palette expansion requested"),
};
dib.extend_from_slice(&[rgba[2], rgba[1], rgba[0], rgba[3]]);
}
Ok(dib)
}
#[cfg(test)]
mod tests {
use super::*;
fn encode(color: png::ColorType, pixels: &[u8]) -> Vec<u8> {
let mut png = Vec::new();
{
let mut encoder = png::Encoder::new(&mut png, 1, 2);
encoder.set_color(color);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header().unwrap().write_image_data(pixels).unwrap();
}
png
}
#[test]
fn keeps_rgba_colors_alpha_and_top_down_row_order() {
let png = encode(png::ColorType::Rgba, &[255, 0, 0, 128, 0, 255, 0, 255]);
let dib = png_to_dib(&png).unwrap();
assert_eq!(i32::from_le_bytes(dib[8..12].try_into().unwrap()), -2);
assert_eq!(&dib[124..], &[0, 0, 255, 128, 0, 255, 0, 255]);
let round_trip = crate::dib_to_png(&dib).unwrap();
let mut reader = png::Decoder::new(Cursor::new(round_trip)).read_info().unwrap();
let mut pixels = vec![0; reader.output_buffer_size().unwrap()];
reader.next_frame(&mut pixels).unwrap();
assert_eq!(pixels, [255, 0, 0, 128, 0, 255, 0, 255]);
}
#[test]
fn supports_rgb_and_grayscale_without_assuming_an_alpha_channel() {
for (color, pixels, expected) in [
(png::ColorType::Rgb, vec![255, 0, 0, 0, 255, 0], vec![0, 0, 255, 255, 0, 255, 0, 255]),
(png::ColorType::Grayscale, vec![20, 200], vec![20, 20, 20, 255, 200, 200, 200, 255]),
(png::ColorType::GrayscaleAlpha, vec![20, 10, 200, 250], vec![20, 20, 20, 10, 200, 200, 200, 250]),
] {
assert_eq!(&png_to_dib(&encode(color, &pixels)).unwrap()[124..], expected);
}
assert!(png_to_dib(b"not a PNG").is_err());
}
}
+108 -1
View File
@@ -25,6 +25,29 @@
use std::path::PathBuf;
#[cfg(any(windows, test))]
mod image;
/// Writes a PNG as a native image, independently of WebView clipboard permissions.
/// Call on the main thread on macOS and Linux; `owner` is a window handle on Windows.
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
if png.get(..8) != Some(b"\x89PNG\r\n\x1a\n") || png.get(12..16) != Some(b"IHDR") || png.len() < 24 {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid clipboard image"));
}
let width = u32::from_be_bytes(png[16..20].try_into().unwrap()) as usize;
let height = u32::from_be_bytes(png[20..24].try_into().unwrap()) as usize;
if width == 0
|| height == 0
|| !width
.checked_mul(height)
.and_then(|pixels| pixels.checked_mul(4))
.is_some_and(|size| size <= 64 * 1024 * 1024)
{
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Clipboard image is too large"));
}
imp::set_png(png, owner)
}
/// Replaces every clipboard flavor with plain text. `owner` is the calling window
/// handle on Windows, ignored elsewhere. Call on the main thread on macOS and Linux.
pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
@@ -240,6 +263,7 @@ mod imp {
/// `CF_DIB`: Windows synthesizes it from `CF_BITMAP` and `CF_DIBV5`, so every
/// bitmap on the clipboard reads as one.
const CF_DIB: u32 = 8;
const CF_DIBV5: u32 = 17;
/// The `PNG` format browsers and the Snipping Tool add beside the bitmap; it
/// keeps transparency, so it is read first.
@@ -422,6 +446,48 @@ mod imp {
}
}
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
let dib = super::image::png_to_dib(png)?;
let format = png_format();
if format == 0 {
return Err(std::io::Error::last_os_error());
}
let formats = [(format, png), (CF_DIBV5, dib.as_slice())];
// SAFETY: allocations remain ours until SetClipboardData accepts them. Prepare both
// before replacing the clipboard; free only allocations the OS did not take.
unsafe {
let mut blocks: Vec<_> = formats.iter().map(|(_, bytes)| global_bytes(bytes)).collect();
if blocks.iter().any(|memory| memory.is_null()) || !open_for(owner as Handle) {
let error = std::io::Error::last_os_error();
for memory in blocks {
if !memory.is_null() {
GlobalFree(memory);
}
}
return Err(error);
}
let mut result = Ok(());
if EmptyClipboard() == 0 {
result = Err(std::io::Error::last_os_error());
} else {
for ((format, _), memory) in formats.iter().zip(&mut blocks) {
if SetClipboardData(*format, *memory).is_null() {
result = Err(std::io::Error::last_os_error());
break;
}
*memory = ptr::null_mut();
}
}
CloseClipboard();
for memory in blocks {
if !memory.is_null() {
GlobalFree(memory);
}
}
result
}
}
pub fn set_files(paths: &[PathBuf]) -> bool {
let bytes = encode(paths);
if bytes.len() <= HEADER {
@@ -489,7 +555,7 @@ mod imp {
NSBitmapImageFileType, NSBitmapImageRep, NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypePNG,
NSPasteboardTypeString, NSPasteboardTypeTIFF, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting,
};
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL};
use objc2_foundation::{NSArray, NSData, NSDictionary, NSNumber, NSString, NSURL};
use std::path::PathBuf;
use super::names_text;
@@ -587,6 +653,23 @@ mod imp {
})
}
pub fn set_png(png: &[u8], _owner: usize) -> std::io::Result<()> {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
let data = NSData::with_bytes(png);
if NSBitmapImageRep::imageRepWithData(&data).is_none() {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid clipboard image"));
}
let board = NSPasteboard::generalPasteboard();
board.clearContents();
if board.setData_forType(Some(&data), unsafe { NSPasteboardTypePNG }) {
Ok(())
} else {
Err(std::io::Error::other("Cannot write clipboard image"))
}
})
}
pub fn set_files(paths: &[PathBuf]) -> bool {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
@@ -617,6 +700,21 @@ mod imp {
mod imp {
use std::path::PathBuf;
pub fn set_png(png: &[u8], _owner: usize) -> std::io::Result<()> {
#[cfg(target_os = "linux")]
{
let image = gtk::gdk_pixbuf::Pixbuf::from_read(std::io::Cursor::new(png.to_vec()))
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error.to_string()))?;
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).set_image(&image);
Ok(())
}
#[cfg(not(target_os = "linux"))]
{
let _ = png;
Err(std::io::Error::other("Clipboard images are unavailable on this platform"))
}
}
pub fn set_text(text: &str, _owner: usize) -> std::io::Result<()> {
#[cfg(target_os = "linux")]
{
@@ -658,6 +756,15 @@ mod imp {
mod tests {
use super::*;
#[test]
fn invalid_or_oversized_images_are_rejected_before_accessing_the_clipboard() {
assert!(set_png(b"not a PNG", 0).is_err());
let mut header = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
header.extend_from_slice(&100_000u32.to_be_bytes());
header.extend_from_slice(&100_000u32.to_be_bytes());
assert!(set_png(&header, 0).is_err());
}
fn paths(list: &[&str]) -> Vec<PathBuf> {
list.iter().map(PathBuf::from).collect()
}
+5
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,
}
}
}
@@ -362,6 +364,8 @@ pub struct InlayHintsSettings {
pub parameters: bool,
/// Hints of other kinds (chaining, closing labels…).
pub other: bool,
/// The Dart server's closing labels (`// Column` after a widget's closing bracket).
pub closing_labels: bool,
pub disabled_languages: Vec<String>,
/// Code vision as a whole (usages, author and language-server lenses); the switches below apply while it is on.
pub code_vision: bool,
@@ -394,6 +398,7 @@ impl Default for InlayHintsSettings {
types: true,
parameters: true,
other: true,
closing_labels: true,
disabled_languages: Vec::new(),
code_vision: true,
code_vision_usages: true,
+18
View File
@@ -264,6 +264,20 @@ pub struct FlutterDevice {
pub emulator: bool,
/// The adb state keeping it from being used (`unauthorized`, `offline`, …).
pub unavailable: Option<String>,
/// The [`FlutterEmulator`] it runs on: an AVD name, or `apple_ios_simulator`.
#[serde(default)]
#[specta(optional)]
pub emulator_id: Option<String>,
}
/// An Android emulator (AVD) or the iOS Simulator that `flutter emulators --launch` can start.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FlutterEmulator {
pub id: String,
pub name: String,
/// `android` or `ios`.
pub platform_type: Option<String>,
}
/// See [`FlutterDeviceList`].
@@ -289,6 +303,10 @@ pub enum FlutterDaemonStatus {
pub struct FlutterDeviceList {
pub status: FlutterDaemonStatus,
pub devices: Vec<FlutterDevice>,
/// The emulators that no listed device runs on.
#[serde(default)]
#[specta(optional)]
pub emulators: Vec<FlutterEmulator>,
}
/// See [`IdeEvent::Direnv`].
+29 -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 {
@@ -1657,6 +1668,20 @@ pub struct MavenSettings {
/// Always update snapshots (`-U`): Maven checks remote repositories for newer SNAPSHOT
/// dependencies on every sync, build and run, and jdtls on import (`java.maven.updateSnapshots`).
pub update_snapshots: bool,
/// Who runs the JUnit 5 tests of the gutter's Run / Debug.
pub run_tests_using: MavenRunTestsUsing,
}
/// Build Tools › Maven › Run tests using. IDEA runs a Maven project's tests itself unless its build
/// and run actions are delegated to Maven.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MavenRunTestsUsing {
/// OpenIDEA's JUnit Platform runner on the language server's test classpath (`java/junit-runner`).
#[default]
Ide,
/// Surefire (`mvn test -Dtest=…`).
Maven,
}
impl MavenSettings {
@@ -2099,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;
@@ -2318,6 +2345,7 @@ mod maven_linkage_tests {
let old: MavenSettings = serde_json::from_str(r#"{"home":"/opt/maven"}"#).unwrap();
assert!(old.runner_jre.is_empty());
assert!(!old.delegate_build);
assert_eq!(old.run_tests_using, MavenRunTestsUsing::Ide);
assert!(MavenSettings::default().runner_jre.is_empty());
let settings = MavenSettings { runner_jre: "/opt/jdk-21".into(), delegate_build: true, ..old };
let encoded = serde_json::to_string(&settings).unwrap();
+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 -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)]
+93 -40
View File
@@ -67,7 +67,7 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
AND has_schema_privilege(nspname, 'USAGE') ORDER BY 1"
}
DbDriver::Mysql if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
DbDriver::SqlServer if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
DbDriver::SqlServer if system => "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA ORDER BY 1",
DbDriver::Snowflake if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
DbDriver::Snowflake => {
"SELECT schema_name FROM information_schema.schemata WHERE schema_name <> 'INFORMATION_SCHEMA' ORDER BY 1"
@@ -89,8 +89,8 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
WHERE schema_name NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys') ORDER BY 1"
}
DbDriver::SqlServer => {
"SELECT schema_name FROM information_schema.schemata \
WHERE schema_name NOT IN ('sys', 'information_schema', 'guest') ORDER BY 1"
"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA \
WHERE SCHEMA_NAME NOT IN ('sys', 'INFORMATION_SCHEMA', 'guest') ORDER BY 1"
}
}
}
@@ -133,8 +133,8 @@ pub fn tables(driver: DbDriver, schema: &str) -> String {
quote_literal(driver, schema)
),
DbDriver::SqlServer => format!(
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
"SELECT TABLE_NAME, CASE WHEN TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = {} ORDER BY 1",
quote_literal(driver, schema)
),
}
@@ -177,14 +177,14 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
ORDER BY ordinal_position"
),
DbDriver::SqlServer => format!(
"SELECT column_name, data_type, is_nullable, column_default, \
CASE WHEN EXISTS (SELECT 1 FROM information_schema.table_constraints tc \
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = {s} \
AND tc.table_name = {t} AND k.column_name = c.column_name) THEN 1 ELSE 0 END \
FROM information_schema.columns c WHERE c.table_schema = {s} AND c.table_name = {t} \
ORDER BY c.ordinal_position"
"SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, \
CASE WHEN EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE k ON k.CONSTRAINT_NAME = tc.CONSTRAINT_NAME \
AND k.TABLE_SCHEMA = tc.TABLE_SCHEMA AND k.TABLE_NAME = tc.TABLE_NAME \
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_SCHEMA = {s} \
AND tc.TABLE_NAME = {t} AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END \
FROM INFORMATION_SCHEMA.COLUMNS c WHERE c.TABLE_SCHEMA = {s} AND c.TABLE_NAME = {t} \
ORDER BY c.ORDINAL_POSITION"
),
DbDriver::Snowflake => format!(
"SELECT column_name, {SNOWFLAKE_TYPE}, is_nullable, column_default, 0 \
@@ -300,18 +300,18 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
}
DbDriver::SqlServer => {
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
c.column_name, c.data_type, c.is_nullable, \
CASE WHEN EXISTS (SELECT 1 FROM information_schema.table_constraints tc \
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = c.table_schema \
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END, \
CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
FROM information_schema.columns c JOIN information_schema.tables t \
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
WHERE c.table_schema NOT IN ('sys', 'information_schema') \
ORDER BY c.table_schema, c.table_name, c.ordinal_position"
"SELECT c.TABLE_SCHEMA, c.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
c.COLUMN_NAME, c.DATA_TYPE, c.IS_NULLABLE, \
CASE WHEN EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE k ON k.CONSTRAINT_NAME = tc.CONSTRAINT_NAME \
AND k.TABLE_SCHEMA = tc.TABLE_SCHEMA AND k.TABLE_NAME = tc.TABLE_NAME \
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_SCHEMA = c.TABLE_SCHEMA \
AND tc.TABLE_NAME = c.TABLE_NAME AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END, \
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t \
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME \
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA') \
ORDER BY c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION"
}
DbDriver::Snowflake => {
"SELECT c.table_schema, c.table_name, CASE t.table_type WHEN 'VIEW' THEN 'view' \
@@ -372,11 +372,12 @@ pub fn foreign_keys(driver: DbDriver) -> &'static str {
ORDER BY table_schema, table_name, constraint_name, ordinal_position LIMIT 20000"
}
DbDriver::SqlServer => {
"SELECT table_schema, table_name, constraint_name, column_name, \
referenced_table_schema, referenced_table_name, referenced_column_name \
FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL \
AND table_schema NOT IN ('sys', 'information_schema') \
ORDER BY table_schema, table_name, constraint_name, ordinal_position"
"SELECT OBJECT_SCHEMA_NAME(fk.parent_object_id), OBJECT_NAME(fk.parent_object_id), fk.name, pc.name, \
OBJECT_SCHEMA_NAME(fk.referenced_object_id), OBJECT_NAME(fk.referenced_object_id), rc.name \
FROM sys.foreign_keys fk JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id \
JOIN sys.columns pc ON pc.object_id = fkc.parent_object_id AND pc.column_id = fkc.parent_column_id \
JOIN sys.columns rc ON rc.object_id = fkc.referenced_object_id AND rc.column_id = fkc.referenced_column_id \
WHERE fk.is_ms_shipped = 0 ORDER BY 1, 2, 3, fkc.constraint_column_id"
}
DbDriver::Oracle => {
"SELECT con.owner, con.table_name, con.constraint_name, col.column_name, \
@@ -410,7 +411,13 @@ pub fn table_foreign_keys(driver: DbDriver, schema: &str, table: &str) -> String
"SELECT table_schema, table_name, constraint_name, column_name, referenced_table_schema, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL AND table_schema = {s} AND table_name = {t} ORDER BY constraint_name, ordinal_position"
),
DbDriver::SqlServer => format!(
"SELECT table_schema, table_name, constraint_name, column_name, referenced_table_schema, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL AND table_schema = {s} AND table_name = {t} ORDER BY constraint_name, ordinal_position"
"SELECT OBJECT_SCHEMA_NAME(fk.parent_object_id), OBJECT_NAME(fk.parent_object_id), fk.name, pc.name, \
OBJECT_SCHEMA_NAME(fk.referenced_object_id), OBJECT_NAME(fk.referenced_object_id), rc.name \
FROM sys.foreign_keys fk JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id \
JOIN sys.columns pc ON pc.object_id = fkc.parent_object_id AND pc.column_id = fkc.parent_column_id \
JOIN sys.columns rc ON rc.object_id = fkc.referenced_object_id AND rc.column_id = fkc.referenced_column_id \
WHERE fk.parent_object_id = OBJECT_ID(N{}) ORDER BY 3, fkc.constraint_column_id",
quote_literal(driver, &qualified(driver, schema, table))
),
DbDriver::Oracle => format!(
"SELECT con.owner, con.table_name, con.constraint_name, col.column_name, rcon.owner, rcon.table_name, rcol.column_name FROM all_constraints con JOIN all_cons_columns col ON col.owner = con.owner AND col.table_name = con.table_name AND col.constraint_name = con.constraint_name JOIN all_constraints rcon ON rcon.owner = con.r_owner AND rcon.constraint_name = con.r_constraint_name JOIN all_cons_columns rcol ON rcol.owner = rcon.owner AND rcol.table_name = rcon.table_name AND rcol.constraint_name = rcon.constraint_name WHERE con.constraint_type = 'R' AND con.owner = {s} AND con.table_name = {t} ORDER BY con.constraint_name, col.position"
@@ -712,8 +719,8 @@ pub fn routines(driver: DbDriver, schema: &str) -> Option<String> {
FROM information_schema.routines r WHERE r.routine_schema = {s} ORDER BY 1"
)),
DbDriver::SqlServer => Some(format!(
"SELECT r.routine_name, lower(r.routine_type), '', r.data_type \
FROM information_schema.routines r WHERE r.routine_schema = {s} ORDER BY 1"
"SELECT r.ROUTINE_NAME, lower(r.ROUTINE_TYPE), '', r.DATA_TYPE \
FROM INFORMATION_SCHEMA.ROUTINES r WHERE r.ROUTINE_SCHEMA = {s} ORDER BY 1"
)),
DbDriver::Snowflake => Some(format!(
"SELECT function_name, 'function', argument_signature, data_type FROM information_schema.functions \
@@ -1019,19 +1026,65 @@ mod tests {
assert_eq!(crate::conn::begin_statement(DbDriver::SqlServer), "BEGIN TRAN");
assert_eq!(
schemas(DbDriver::SqlServer, true),
"SELECT schema_name FROM information_schema.schemata ORDER BY 1"
"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA ORDER BY 1"
);
assert!(schemas(DbDriver::SqlServer, false).contains("NOT IN ('sys', 'information_schema', 'guest')"));
assert!(schemas(DbDriver::SqlServer, false).contains("NOT IN ('sys', 'INFORMATION_SCHEMA', 'guest')"));
}
#[test]
fn sqlserver_introspection_queries() {
assert!(tables(DbDriver::SqlServer, "dbo").contains("information_schema.tables"));
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("information_schema.columns"));
assert!(tables(DbDriver::SqlServer, "dbo").contains("INFORMATION_SCHEMA.TABLES"));
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("INFORMATION_SCHEMA.COLUMNS"));
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
assert!(foreign_keys(DbDriver::SqlServer).contains("referenced_table_name IS NOT NULL"));
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("table_schema = 'dbo'"));
assert!(completion_columns(DbDriver::SqlServer).contains("information_schema.columns"));
assert!(foreign_keys(DbDriver::SqlServer).contains("sys.foreign_key_columns"));
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("OBJECT_ID(N'[dbo].[t]')"));
assert!(completion_columns(DbDriver::SqlServer).contains("INFORMATION_SCHEMA.COLUMNS"));
}
/// Under a case-sensitive or binary collation, catalog names only resolve as declared:
/// `INFORMATION_SCHEMA` views and their columns in upper case, `sys` views in lower case.
#[test]
fn sqlserver_catalog_names_keep_their_declared_case() {
let d = DbDriver::SqlServer;
let queries = [
schemas(d, true).to_owned(),
schemas(d, false).to_owned(),
tables(d, "dbo"),
columns(d, "dbo", "t"),
indexes(d, "dbo", "t"),
completion_columns(d).to_owned(),
foreign_keys(d).to_owned(),
table_foreign_keys(d, "dbo", "t"),
routines(d, "dbo").unwrap(),
];
const COLUMNS: [&str; 15] = [
"information_schema",
"schema_name",
"table_name",
"table_schema",
"table_type",
"column_name",
"data_type",
"is_nullable",
"column_default",
"constraint_name",
"constraint_type",
"ordinal_position",
"routine_name",
"routine_type",
"routine_schema",
];
for q in queries {
let words: Vec<&str> = q.split(|c: char| !c.is_alphanumeric() && c != '_').collect();
for (i, word) in words.iter().enumerate() {
let catalog = COLUMNS.contains(&word.to_lowercase().as_str())
|| i > 0 && words[i - 1] == "INFORMATION_SCHEMA" && !word.is_empty();
if catalog {
assert_eq!(*word, word.to_uppercase(), "{word} in {q}");
}
}
assert!(!q.contains("referenced_table_name"), "SQL Server has no referenced_* columns: {q}");
}
}
#[test]
+59
View File
@@ -136,3 +136,62 @@ async fn sqlserver_creates_from_a_held_model_and_force_drops_a_held_database() {
assert!(!db.databases("s").await.unwrap().names.contains(&name));
drop(held);
}
/// #5772: a case-sensitive collation resolves catalog names only in their declared case.
#[tokio::test]
async fn sqlserver_introspection_works_under_a_case_sensitive_collation() {
use ide_db::sql;
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
let parts = server.splitn(4, ':');
let source = |database: &str| DataSource {
driver: DbDriver::SqlServer,
host: parts.clone().next().unwrap().into(),
port: Some(parts.clone().nth(1).unwrap().parse().unwrap()),
user: parts.clone().nth(2).unwrap().into(),
database: database.into(),
ssl: DbSslMode::Disable,
..Default::default()
};
let password = parts.clone().nth(3);
let name = format!("oi_cs_catalog_{}", std::process::id());
let master = Pool::connect(&source("master"), password, None).await.unwrap();
master.rows(&format!("CREATE DATABASE {name} COLLATE Latin1_General_CS_AS"), 1).await.unwrap();
let pool = Pool::connect(&source(&name), password, None).await.unwrap();
pool.rows("CREATE TABLE dbo.Parent (Id int PRIMARY KEY)", 1).await.unwrap();
pool.rows("CREATE TABLE dbo.Child (Id int PRIMARY KEY, ParentId int CONSTRAINT FK_Child_Parent REFERENCES dbo.Parent (Id))", 1)
.await
.unwrap();
pool.rows("CREATE VIEW dbo.Kids AS SELECT Id FROM dbo.Child", 1).await.unwrap();
pool.rows("CREATE PROCEDURE dbo.Touch AS SELECT 1", 1).await.unwrap();
let d = DbDriver::SqlServer;
let cells = |rows: Vec<Vec<Option<String>>>| -> Vec<Vec<String>> {
rows.into_iter().map(|r| r.into_iter().map(Option::unwrap_or_default).collect()).collect()
};
let schemas = cells(pool.rows(sql::schemas(d, false), 100).await.unwrap());
assert!(schemas.contains(&vec!["dbo".to_owned()]));
assert!(!schemas.iter().any(|s| s[0] == "INFORMATION_SCHEMA" || s[0] == "sys"));
assert!(
cells(pool.rows(sql::schemas(d, true), 100).await.unwrap()).contains(&vec!["INFORMATION_SCHEMA".to_owned()])
);
assert_eq!(
cells(pool.rows(&sql::tables(d, "dbo"), 100).await.unwrap()),
[["Child", "table"], ["Kids", "view"], ["Parent", "table"]]
);
assert_eq!(
cells(pool.rows(&sql::columns(d, "dbo", "Child"), 100).await.unwrap())
.iter()
.map(|c| (c[0].as_str(), c[4].as_str()))
.collect::<Vec<_>>(),
[("Id", "1"), ("ParentId", "0")]
);
let fk = ["dbo", "Child", "FK_Child_Parent", "ParentId", "dbo", "Parent", "Id"];
assert_eq!(cells(pool.rows(&sql::table_foreign_keys(d, "dbo", "Child"), 100).await.unwrap()), [fk]);
assert_eq!(cells(pool.rows(sql::foreign_keys(d), 100).await.unwrap()), [fk]);
assert_eq!(cells(pool.rows(sql::completion_columns(d), 100).await.unwrap()).len(), 4);
assert_eq!(cells(pool.rows(&sql::routines(d, "dbo").unwrap(), 100).await.unwrap())[0][..2], ["Touch", "procedure"]);
drop(pool);
master
.rows(&format!("ALTER DATABASE {name} SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE {name}"), 1)
.await
.unwrap();
}
+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");
}
}
}
+201 -21
View File
@@ -3,31 +3,38 @@
//! The daemon speaks JSON-RPC over stdio, one bracketed message per line. After
//! `daemon.connected` it is asked for `device.enable`, which makes it report `device.added` /
//! `device.removed`, and once for `device.getDevices`, whose answer ends the "discovering" state.
//! `emulator.getEmulators` lists what can be started, then and whenever the chooser opens.
//!
//! The daemon keeps running after its stdin closes, so closing the pipe does not end it: on Unix
//! a watcher in its process group ends the group once the IDE is gone, even after a crash. A
//! 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};
use ide_core::event::{FlutterDaemonStatus, FlutterDevice, FlutterDeviceList, FlutterEmulator};
use ide_core::process::{kill_tree, own_group, prepare, terminate_tree};
use ide_core::tool_path::{find_command, search_path_in};
use ide_core::{IdeEvent, SharedSink};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::collections::{BTreeMap, VecDeque};
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::Arc;
use std::sync::mpsc;
use std::time::Duration;
const ENABLE: u64 = 1;
const GET_DEVICES: u64 = 2;
const GET_EMULATORS: u64 = 3;
/// `emulator.launch` waits for `xcrun simctl` or similar; past this the daemon is stuck.
const LAUNCH_TIMEOUT: Duration = Duration::from_secs(60);
/// How long the daemon gets to exit on `SIGTERM`.
const KILL_GRACE: Duration = Duration::from_millis(200);
/// Lines of unrecognised output kept to explain a failure.
@@ -39,6 +46,9 @@ enum Message {
Added(FlutterDevice),
Removed(String),
Devices(Vec<FlutterDevice>),
Emulators(Vec<FlutterEmulator>),
/// The answer to a request of ours other than the ones above.
Response(u64, Result<(), String>),
Other,
}
@@ -51,9 +61,15 @@ fn device(value: &Value) -> Option<FlutterDevice> {
category: text("category"),
emulator: value.get("emulator").and_then(Value::as_bool).unwrap_or(false),
unavailable: None,
emulator_id: text("emulatorId"),
})
}
fn emulator(value: &Value) -> Option<FlutterEmulator> {
let text = |key| value.get(key).and_then(Value::as_str).map(str::to_owned);
Some(FlutterEmulator { id: text("id")?, name: text("name")?, platform_type: text("platformType") })
}
/// The messages of one stdout line; `None` for anything outside the protocol (the tool's own
/// chatter, such as waiting for the startup lock).
fn parse_line(line: &str) -> Option<Vec<Message>> {
@@ -74,11 +90,23 @@ fn parse_message(message: &Value) -> Message {
params.get("id").and_then(Value::as_str).map_or(Message::Other, |id| Message::Removed(id.to_owned()))
}
Some(_) => Message::Other,
None if message.get("id").and_then(Value::as_u64) == Some(GET_DEVICES) => {
let result = message.get("result").and_then(Value::as_array);
Message::Devices(result.into_iter().flatten().filter_map(device).collect())
None => {
let result = message.get("result").and_then(Value::as_array).into_iter().flatten();
match message.get("id").and_then(Value::as_u64) {
Some(ENABLE) | None => Message::Other,
Some(GET_DEVICES) => Message::Devices(result.filter_map(device).collect()),
// A failure (no Android SDK, no Xcode) lists none.
Some(GET_EMULATORS) => Message::Emulators(result.filter_map(emulator).collect()),
Some(id) => Message::Response(
id,
match message.get("error") {
None | Some(Value::Null) => Ok(()),
Some(Value::String(error)) => Err(error.clone()),
Some(error) => Err(error.to_string()),
},
),
}
}
None => Message::Other,
}
}
@@ -86,6 +114,12 @@ fn request(id: u64, method: &str) -> String {
format!("{}\n", json!([{ "id": id, "method": method }]))
}
/// The emulators no device runs on.
fn idle_emulators(emulators: &[FlutterEmulator], devices: &BTreeMap<String, FlutterDevice>) -> Vec<FlutterEmulator> {
let running = |e: &FlutterEmulator| devices.values().any(|d| d.emulator_id.as_ref() == Some(&e.id));
emulators.iter().filter(|e| !running(e)).cloned().collect()
}
/// The daemon's devices, plus the Android devices adb sees that Flutter leaves out until they
/// are usable. A daemon Android device's id is its adb serial.
fn merged(daemon: &BTreeMap<String, FlutterDevice>, adb: &[AndroidDevice]) -> Vec<FlutterDevice> {
@@ -97,6 +131,7 @@ fn merged(daemon: &BTreeMap<String, FlutterDevice>, adb: &[AndroidDevice]) -> Ve
category: Some("mobile".into()),
emulator: d.serial.starts_with("emulator-"),
unavailable: Some(d.state.clone()),
emulator_id: None,
}));
let rank = |d: &FlutterDevice| match d.category.as_deref() {
Some("mobile") => 0,
@@ -121,15 +156,30 @@ struct State {
status: FlutterDaemonStatus,
devices: BTreeMap<String, FlutterDevice>,
adb: Vec<AndroidDevice>,
emulators: Vec<FlutterEmulator>,
/// Requests awaiting their answer; dropped with the daemon, which fails them.
pending: HashMap<u64, mpsc::Sender<Result<(), String>>>,
next_id: u64,
}
impl State {
fn list(&self) -> FlutterDeviceList {
FlutterDeviceList { status: self.status.clone(), devices: merged(&self.devices, &self.adb) }
FlutterDeviceList {
status: self.status.clone(),
devices: merged(&self.devices, &self.adb),
emulators: idle_emulators(&self.emulators, &self.devices),
}
}
/// Writes `requests` to the daemon; false without one.
fn send(&mut self, requests: &str) -> bool {
let Some(stdin) = self.running.as_mut().and_then(|r| r.stdin.as_mut()) else { return false };
stdin.write_all(requests.as_bytes()).and_then(|()| stdin.flush()).is_ok()
}
fn shut_down(&mut self) {
self.generation += 1;
self.pending.clear();
if let Some(Running { mut child, stdin }) = self.running.take() {
drop(stdin);
// Off the caller's thread: closing a window must not wait for the grace period.
@@ -141,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>,
}
@@ -152,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.
@@ -181,12 +235,57 @@ impl FlutterDaemon {
state.list()
}
/// Reads adb again: a device awaiting authorization changes no daemon event.
/// Reads adb again (a device awaiting authorization changes no daemon event) and asks the
/// daemon for its emulators again (one may have been created since).
pub fn refresh(&self) {
let generation = self.0.state.lock().generation;
let mut state = self.0.state.lock();
if state.status == FlutterDaemonStatus::Ready {
state.send(&request(GET_EMULATORS, "emulator.getEmulators"));
}
let generation = state.generation;
drop(state);
refresh_adb(&self.0, generation);
}
/// Starts an emulator the list offers; it shows up as a device once booted. Blocks until the
/// launch is under way. An AVD is started by `ide-android` rather than the daemon, which
/// would make it a child of its process group and end it with the daemon.
pub fn launch_emulator(&self, id: &str) -> Result<(), String> {
let mut state = self.0.state.lock();
let android = state.emulators.iter().any(|e| e.id == id && e.platform_type.as_deref() == Some("android"));
if android {
drop(state);
return ide_android::launch_emulator(id).map_err(|e| e.message);
}
state.next_id = state.next_id.max(GET_EMULATORS) + 1;
let request_id = state.next_id;
let (tx, rx) = mpsc::channel();
state.pending.insert(request_id, tx);
let params = json!({ "emulatorId": id });
let line = format!("{}\n", json!([{ "id": request_id, "method": "emulator.launch", "params": params }]));
if !state.send(&line) {
state.pending.remove(&request_id);
return Err("the Flutter daemon is not running".into());
}
drop(state);
let answer = rx.recv_timeout(LAUNCH_TIMEOUT);
self.0.state.lock().pending.remove(&request_id);
match answer {
Ok(result) => result,
Err(mpsc::RecvTimeoutError::Timeout) => Err("the Flutter daemon did not answer".into()),
Err(mpsc::RecvTimeoutError::Disconnected) => Err("the Flutter daemon exited".into()),
}
}
/// 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();
@@ -194,6 +293,7 @@ impl FlutterDaemon {
state.status = FlutterDaemonStatus::Stopped;
state.devices.clear();
state.adb.clear();
state.emulators.clear();
}
/// Ends the daemon before returning, for a process about to exit.
@@ -211,6 +311,7 @@ fn start(shared: &Arc<Shared>, state: &mut State) {
state.status = FlutterDaemonStatus::Starting;
state.devices.clear();
state.adb.clear();
state.emulators.clear();
let (shared, generation) = (shared.clone(), state.generation);
std::thread::spawn(move || run(&shared, generation));
}
@@ -265,6 +366,7 @@ fn finish(shared: &Shared, generation: u64, status: FlutterDaemonStatus) {
return;
}
let running = state.running.take();
state.pending.clear();
state.status = status;
let list = state.list();
drop(state);
@@ -298,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);
};
@@ -358,12 +464,25 @@ fn handle(shared: &Arc<Shared>, generation: u64, message: Message) -> bool {
match message {
Message::Other => return true,
Message::Connected => {
if let Some(stdin) = state.running.as_mut().and_then(|r| r.stdin.as_mut()) {
let requests = request(ENABLE, "device.enable") + &request(GET_DEVICES, "device.getDevices");
let _ = stdin.write_all(requests.as_bytes()).and_then(|()| stdin.flush());
state.send(
&(request(ENABLE, "device.enable")
+ &request(GET_DEVICES, "device.getDevices")
+ &request(GET_EMULATORS, "emulator.getEmulators")),
);
return true;
}
Message::Response(id, result) => {
if let Some(tx) = state.pending.remove(&id) {
let _ = tx.send(result);
}
return true;
}
Message::Emulators(emulators) => {
if state.emulators == emulators {
return true;
}
state.emulators = emulators;
}
Message::Added(device) => {
state.devices.insert(device.id.clone(), device);
}
@@ -395,6 +514,7 @@ mod tests {
category: Some(category.into()),
emulator,
unavailable: None,
emulator_id: None,
}
}
@@ -433,6 +553,33 @@ mod tests {
let Some([Message::Devices(devices)]) = answer.as_deref() else { panic!("{answer:?}") };
assert_eq!((devices[0].id.as_str(), devices[0].category.as_deref()), ("chrome", None));
assert_eq!(parse_line(r#"[{"id":1,"result":null}]"#), Some(vec![Message::Other]));
let emulators = parse_line(
r#"[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","category":"mobile","platformType":"ios"}]}]"#,
);
let Some([Message::Emulators(emulators)]) = emulators.as_deref() else { panic!("{emulators:?}") };
assert_eq!(
(emulators[0].id.as_str(), emulators[0].platform_type.as_deref()),
("apple_ios_simulator", Some("ios"))
);
assert_eq!(
parse_line(r#"[{"id":3,"error":"Unable to find Android SDK","trace":""}]"#),
Some(vec![Message::Emulators(vec![])])
);
assert_eq!(parse_line(r#"[{"id":7,"result":null}]"#), Some(vec![Message::Response(7, Ok(()))]));
assert_eq!(
parse_line(r#"[{"id":7,"error":"emulator 'x' not found","trace":"..."}]"#),
Some(vec![Message::Response(7, Err("emulator 'x' not found".into()))])
);
}
#[test]
fn offers_only_the_emulators_no_device_runs_on() {
let emulator = |id: &str| FlutterEmulator { id: id.into(), name: id.into(), platform_type: None };
let mut pixel = dev("emulator-5554", "Pixel", "mobile", true);
pixel.emulator_id = Some("Pixel_9".into());
let devices: BTreeMap<_, _> = [(pixel.id.clone(), pixel)].into_iter().collect();
let idle = idle_emulators(&[emulator("Pixel_9"), emulator("apple_ios_simulator")], &devices);
assert_eq!(idle, [emulator("apple_ios_simulator")]);
}
#[test]
@@ -498,8 +645,9 @@ mod tests {
echo $$ > pid
echo 'Waiting for another flutter command to release the startup lock...'
echo '[{"event":"daemon.connected","params":{"version":"0.6.1","pid":1}}]'
read enable; read get; echo "$enable$get" > requests
read enable; read get; read emulators; echo "$enable$get$emulators" > requests
echo '[{"id":1,"result":null}]'
echo '[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","category":"mobile","platformType":"ios"}]}]'
echo '[{"id":2,"result":[{"id":"macos","name":"macOS","category":"desktop","emulator":false}]}]'
echo '[{"event":"device.added","params":{"id":"chrome","name":"Chrome","category":"web","emulator":false}}]'
echo '[{"event":"device.removed","params":{"id":"macos","name":"macOS"}}]'
@@ -518,6 +666,8 @@ cat > /dev/null
});
let requests = std::fs::read_to_string(dir.path().join("requests")).unwrap();
assert!(requests.contains("device.enable") && requests.contains("device.getDevices"), "{requests}");
assert!(requests.contains("emulator.getEmulators"), "{requests}");
assert_eq!(daemon.devices().emulators[0].name, "iOS Simulator");
assert!(lists.0.lock().iter().any(|l| l.devices.iter().any(|d| d.id == "macos")));
let pid = std::fs::read_to_string(dir.path().join("pid")).unwrap();
@@ -529,6 +679,36 @@ cat > /dev/null
assert_eq!(daemon.0.state.lock().status, FlutterDaemonStatus::Stopped);
}
#[test]
fn launches_an_emulator_through_the_daemon_and_reports_its_error() {
let dir = tempfile::tempdir().unwrap();
let script = r#"
echo '[{"event":"daemon.connected","params":{"version":"0.6.1","pid":1}}]'
read enable; read get; read emulators
echo '[{"id":2,"result":[]}]'
echo '[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","platformType":"ios"}]}]'
read launch; echo "$launch" > launch
echo '[{"id":4,"result":null}]'
read launch
echo '[{"id":5,"error":"Unable to run Simulator: xcrun not found","trace":""}]'
cat > /dev/null
"#;
let (daemon, _lists) = daemon(dir.path(), script);
daemon.devices();
wait_for("the emulators", || !daemon.devices().emulators.is_empty());
assert_eq!(daemon.launch_emulator("apple_ios_simulator"), Ok(()));
let launch = std::fs::read_to_string(dir.path().join("launch")).unwrap();
let launch: Value = serde_json::from_str(&launch).unwrap();
assert_eq!(launch[0]["method"], "emulator.launch");
assert_eq!(launch[0]["params"], json!({ "emulatorId": "apple_ios_simulator" }));
assert_eq!(
daemon.launch_emulator("apple_ios_simulator"),
Err("Unable to run Simulator: xcrun not found".into())
);
daemon.stop();
assert_eq!(daemon.launch_emulator("apple_ios_simulator"), Err("the Flutter daemon is not running".into()));
}
#[test]
fn the_daemon_does_not_outlive_the_ide() {
let dir = tempfile::tempdir().unwrap();
+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");
}
}
+3
View File
@@ -399,6 +399,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 +529,7 @@ impl Host {
for project in self.projects() {
project.flutter.kill();
project.devtools.kill();
project.widget_preview.kill();
}
}
@@ -570,6 +572,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;
+9 -2
View File
@@ -360,10 +360,17 @@ pub async fn agent_fork(host: &Host, window: &str, task: String, turns: Option<u
}
/// Drops the task's turns after its first `turns`; returns the message of the first dropped one.
/// With `files`, the files those turns changed go back as they were before them.
#[command(trust = trusted)]
pub async fn agent_rollback(host: &Host, window: &str, task: String, turns: u32) -> IdeResult<Option<AgentPrompt>> {
pub async fn agent_rollback(
host: &Host,
window: &str,
task: String,
turns: u32,
files: bool,
) -> IdeResult<Option<AgentPrompt>> {
host.require_trust(window)?;
host.project(window)?.agents.rollback(&task, turns).await
host.project(window)?.agents.rollback(&task, turns, files).await
}
/// Checks the selected installation without modifying it.
+86 -2
View File
@@ -114,6 +114,12 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
extra["__adapterJavaHome"] = serde_json::json!(runtime.home);
config.extra_json = Some(extra.to_string());
}
if finds_java_sources(&config)
&& let Ok(project) = host.project(window)
{
let roots = host.blocking(move || Ok(java_source_roots(&project))).await?;
config = add_java_source_paths(config, &roots);
}
let root = config.cwd.clone().map(PathBuf::from).unwrap_or_default();
let mut ruby_tools = Vec::new();
if config.adapter == "rdbg" && config.request == "launch" {
@@ -308,6 +314,46 @@ fn start_java_attach_listener(mut config: LaunchConfig, windows: bool) -> Launch
config
}
/// The project's source and test roots, as the IDE detects them (no Maven / Gradle import needed).
fn java_source_roots(project: &crate::project::Project) -> Vec<PathBuf> {
use ide_workspace::roots::RootKind;
project
.roots()
.roots
.iter()
.filter(|r| matches!(r.kind, RootKind::Source | RootKind::Test))
.map(|r| project.root.join(&r.path))
.filter(|p| p.is_dir())
.collect()
}
/// Debuggers that look a frame's source up in `sourcePaths` when their own model has no file:
/// java-debug after jdtls (which has not imported a project whose Maven sync failed), and
/// java-analyzer after the module it debugs (whose sibling modules it does not load).
fn finds_java_sources(config: &LaunchConfig) -> bool {
matches!(config.adapter.as_str(), "java-debug" | ide_dap::adapter::JAVA_ANALYZER)
}
/// Without a file for the stopped frame the editor cannot follow the execution point, so Java
/// sessions get every source root of the project. The user's own list wins.
fn add_java_source_paths(mut config: LaunchConfig, roots: &[PathBuf]) -> LaunchConfig {
if !finds_java_sources(&config) || roots.is_empty() {
return config;
}
let mut extra = match config.extra_json.as_deref().map(serde_json::from_str) {
None => serde_json::Map::new(),
Some(Ok(serde_json::Value::Object(extra))) => extra,
Some(_) => return config,
};
if extra.get("sourcePaths").is_some_and(|v| !v.is_null()) {
return config;
}
let paths: Vec<String> = roots.iter().map(|r| r.to_string_lossy().into_owned()).collect();
extra.insert("sourcePaths".into(), paths.into());
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
config
}
/// A JVM launched by java-debug writes what java-debug decodes its output as
/// (see [`ide_core::output_encoding::java_debug_vm_args`]).
fn match_java_debug_encoding(mut config: LaunchConfig, windows: bool) -> LaunchConfig {
@@ -671,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.
@@ -737,6 +793,34 @@ mod tests {
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()["vmArgs"].clone()
}
#[test]
fn java_debug_sessions_look_up_sources_in_project_roots() {
let roots = [PathBuf::from("/p/src/main/java"), PathBuf::from("/p/src/test/java")];
let source_paths = |config: &LaunchConfig| {
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()["sourcePaths"]
.clone()
};
for adapter in ["java-debug", ide_dap::adapter::JAVA_ANALYZER] {
for request in ["launch", "attach"] {
let config = add_java_source_paths(launch(adapter, request, serde_json::json!({"port": 5005})), &roots);
assert_eq!(source_paths(&config), serde_json::json!(["/p/src/main/java", "/p/src/test/java"]));
}
}
let mut bare = launch("java-debug", "attach", serde_json::json!({}));
bare.extra_json = None;
assert_eq!(
source_paths(&add_java_source_paths(bare, &roots)),
serde_json::json!(["/p/src/main/java", "/p/src/test/java"])
);
let own = launch("java-debug", "launch", serde_json::json!({"sourcePaths": ["/elsewhere"]}));
assert_eq!(source_paths(&add_java_source_paths(own, &roots)), serde_json::json!(["/elsewhere"]));
let other = launch("debugpy", "launch", serde_json::json!({}));
assert_eq!(add_java_source_paths(other.clone(), &roots).extra_json, other.extra_json);
let none = launch("java-debug", "launch", serde_json::json!({}));
assert_eq!(add_java_source_paths(none.clone(), &[]).extra_json, none.extra_json);
}
#[test]
fn java_debug_launches_on_windows_write_utf8() {
let extra =
+32 -5
View File
@@ -25,15 +25,42 @@ pub fn flutter_daemon_restart(host: &Host, window: &str) -> IdeResult<FlutterDev
Ok(host.project(window)?.flutter.restart())
}
/// The address of the project's DevTools server, started on first use. A server that failed or
/// exited is only started again by the next request.
/// Starts an emulator from [`FlutterDeviceList::emulators`]. Returns once the launch is under way: the device follows as `IdeEvent::FlutterDevices`.
#[command(trust = trusted)]
pub async fn flutter_devtools_url(host: &Host, window: &str) -> IdeResult<String> {
pub async fn flutter_emulator_launch(host: &Host, window: &str, id: String) -> IdeResult<()> {
let project = host.project(window)?;
tokio::task::spawn_blocking(move || project.devtools.url())
tokio::task::spawn_blocking(move || project.flutter.launch_emulator(&id))
.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_devtools_url);
/// The address of the project's DevTools server, started on first use. A server that failed or
/// exited is only started again by the next request.
#[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(&[]))
.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_widget_preview_url);
+196 -9
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)
@@ -646,6 +681,129 @@ pub async fn java_build_workspace(
result
}
/// The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath:
/// the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the
/// classpath has one; from the engine's repository, else downloaded once from Maven Central), and,
/// for a Maven module, what its Surefire configuration gives the forked test JVM.
#[command(trust = trusted)]
pub async fn java_junit_runner(
host: &Host,
window: &str,
module: PathBuf,
class_paths: Vec<String>,
) -> IdeResult<JunitLaunch> {
host.require_trust(window)?;
let project = host.project(window)?;
let module = ide_core::project_roots::resolve(&project.root, &module);
let data_dir = host.local_data_dir.clone();
tokio::task::spawn_blocking(move || {
let scope = workspace::scope_for(&project, &module)?;
let model = load_launch_model(&scope);
let surefire = model
.maven
.as_ref()
.and_then(|maven| ide_build::surefire::surefire_config(&scope.root, &scope.cache, maven, &module))
.unwrap_or_default();
let runner = ide_sdk::java::junit_runner_jar(&data_dir)
.ok_or_else(|| IdeError::internal("Cannot install the JUnit runner"))?;
let launcher = match ide_sdk::java::junit_launcher(&class_paths) {
ide_sdk::java::JunitLauncher::OnClasspath => None,
ide_sdk::java::JunitLauncher::Found(path) => Some(path),
ide_sdk::java::JunitLauncher::Missing(version) => Some(download_junit_launcher(&data_dir, &version)?),
ide_sdk::java::JunitLauncher::NoPlatform => {
return Err(IdeError::unavailable(
"No JUnit Platform (junit-platform-engine) on the test classpath. To run these tests through \
Maven, set Settings › Build Tools › Maven › Run tests using to Maven.",
));
}
};
Ok(junit_launch(&module, class_paths, surefire, [Some(runner), launcher].into_iter().flatten()))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// The test JVM of OpenIDEA's JUnit runner.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct JunitLaunch {
pub class_paths: Vec<String>,
/// Surefire's `argLine`, then its system properties as `-Dkey=value`.
pub vm_args: Vec<String>,
pub env: std::collections::BTreeMap<String, String>,
pub working_directory: Option<String>,
/// The Surefire settings that were applied (`argLine`, `systemPropertyVariables`…), for the console.
pub surefire: Vec<String>,
}
fn junit_launch(
module: &Path,
class_paths: Vec<String>,
surefire: ide_build::surefire::SurefireConfig,
runner: impl Iterator<Item = PathBuf>,
) -> JunitLaunch {
let mut applied = Vec::new();
let mut note = |used: bool, name: &str| {
if used {
applied.push(name.to_owned());
}
};
note(!surefire.arg_line.is_empty(), "argLine");
note(!surefire.system_properties.is_empty(), "systemPropertyVariables");
note(!surefire.environment.is_empty(), "environmentVariables");
note(surefire.working_directory.is_some(), "workingDirectory");
note(!surefire.additional_classpath.is_empty(), "additionalClasspathElements");
note(!surefire.classpath_excludes.is_empty(), "classpathDependencyExcludes");
// `group:artifact` in a Maven repository (`g/r/p/artifact/…`) or the Gradle cache (`g.r.p/artifact/…`).
let excluded = |path: &str| {
let path = path.replace('\\', "/");
surefire.classpath_excludes.iter().any(|e| {
e.split_once(':').is_some_and(|(group, artifact)| {
path.contains(&format!("/{}/{artifact}/", group.replace('.', "/")))
|| path.contains(&format!("/{group}/{artifact}/"))
})
})
};
let mut class_paths: Vec<String> = class_paths.into_iter().filter(|p| !excluded(p)).collect();
class_paths.extend(surefire.additional_classpath);
class_paths.extend(runner.map(|p| p.to_string_lossy().into_owned()));
let mut vm_args = surefire.arg_line;
vm_args.extend(surefire.system_properties.into_iter().map(|(k, v)| format!("-D{k}={v}")));
JunitLaunch {
class_paths,
vm_args,
env: surefire.environment,
working_directory: surefire.working_directory.map(|d| module.join(d).to_string_lossy().into_owned()),
surefire: applied,
}
}
fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult<PathBuf> {
if version.is_empty() || !version.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c)) {
return Err(IdeError::invalid(format!("Unexpected JUnit Platform version '{version}'")));
}
let name = format!("junit-platform-launcher-{version}.jar");
let dest = data_dir.join("junit").join(&name);
if dest.is_file() {
return Ok(dest);
}
std::fs::create_dir_all(dest.parent().expect("has a parent"))?;
let url = format!("https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/{version}/{name}");
let partial = dest.with_extension("jar.part");
// ponytail: unverified like the Lombok download (Central publishes SHA-1 only); HTTPS from Central.
let fetched = ide_tools::Http::new(&ide_core::tool_path::search_path())
.map(ide_tools::Http::https_only)
.and_then(|http| http.download(&url, &partial, None, &CancellationToken::new(), &|_| {}))
.and_then(|()| Ok(std::fs::rename(&partial, &dest)?));
fetched.map(|()| dest).map_err(|e| {
IdeError::unavailable(format!(
"Cannot download {name} from Maven Central ({}). Add org.junit.platform:junit-platform-launcher to the \
test dependencies, or set Settings › Build Tools › Maven › Run tests using to Maven.",
e.message
))
})
}
/// An annotation processor's error for writing a file this build already wrote (JDT's
/// `IdeFilerImpl`: "Source file already created", javac's Filer: "Attempt to recreate a file").
fn processor_recreated_a_file(message: &str) -> bool {
@@ -663,6 +821,35 @@ fn drop_processor_recreate_errors(info: &mut JavaLaunchInfo) {
mod tests {
use super::*;
#[test]
fn junit_launch_applies_the_surefire_configuration() {
let surefire = ide_build::surefire::SurefireConfig {
arg_line: vec!["-Xmx1g".into()],
system_properties: [("openidea.fail".to_owned(), "true".to_owned())].into(),
environment: [("TZ".to_owned(), "UTC".to_owned())].into(),
working_directory: Some("work".into()),
additional_classpath: vec!["/extra".into()],
classpath_excludes: vec!["org.slf4j:slf4j-simple".into(), "com.acme:gone".into()],
};
let classpath = vec![
"/m/target/test-classes".into(),
"/m2/org/slf4j/slf4j-simple/2.0/slf4j-simple-2.0.jar".into(),
"/gradle/files-2.1/com.acme/gone/1/abc/gone-1.jar".into(),
"/m2/org/slf4j/slf4j-api/2.0/slf4j-api-2.0.jar".into(),
];
let launch = junit_launch(Path::new("/m"), classpath, surefire, [PathBuf::from("/runner.jar")].into_iter());
assert_eq!(
launch.class_paths,
["/m/target/test-classes", "/m2/org/slf4j/slf4j-api/2.0/slf4j-api-2.0.jar", "/extra", "/runner.jar"]
);
assert_eq!(launch.vm_args, ["-Xmx1g", "-Dopenidea.fail=true"]);
assert_eq!(launch.env["TZ"], "UTC");
assert_eq!(launch.working_directory.as_deref(), Path::new("/m").join("work").to_str());
assert_eq!(launch.surefire.len(), 6);
let plain = junit_launch(Path::new("/m"), vec![], Default::default(), std::iter::empty());
assert!(plain.surefire.is_empty() && plain.vm_args.is_empty() && plain.working_directory.is_none());
}
fn fake_jdk(dir: &Path, version: Option<&str>) -> PathBuf {
let bin = dir.join("bin");
std::fs::create_dir_all(&bin).unwrap();
@@ -946,4 +1133,4 @@ mod tests {
}
}
ide_command::domain!(java: java_build_workspace, java_debug_adapter, java_debug_server, java_resolve_launch);
ide_command::domain!(java: java_build_workspace, java_debug_adapter, java_debug_server, java_junit_runner, java_resolve_launch);
+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,
+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() {
+49 -2
View File
@@ -136,6 +136,10 @@ pub trait PluginWorkspace: Send + Sync {
fn apply_edits(&self, path: &Path, version: u64, edits: &[TextEdit], background: bool) -> Result<u64, HostError>;
/// Code from the project may run (git hooks and config on fetch).
fn trusted(&self, root: &Path) -> bool;
/// Git roots with the same directory mappings as the VCS tool window.
fn repositories(&self, _root: &Path) -> Result<ide_vcs::Repos, HostError> {
Err(HostError::NotFound("no open project repositories".into()))
}
/// The git executable of the project at `root` (see [`crate::Project::git_executable`]).
fn git_executable(&self, _root: &Path) -> Option<PathBuf> {
None
@@ -2394,8 +2398,40 @@ impl HostApi for PluginApi {
fn vcs_remotes(&self, root: &Path) -> Result<Vec<(String, String)>, HostError> {
let Some(repo) = ide_vcs::Repo::discover(root).map_err(failed)? else { return Ok(Vec::new()) };
let remotes = repo.remotes().map_err(failed)?;
Ok(remotes.into_iter().map(|r| (r.name, without_credentials(&r.url))).collect())
plugin_remotes(&repo)
}
fn vcs_roots(&self, root: &Path) -> Result<Vec<String>, HostError> {
let workspace = self.shared.workspace().ok_or(HostError::Cancelled)?;
Ok(workspace
.repositories(root)?
.roots()
.iter()
.filter(|r| r.starts_with(root) || root.starts_with(r))
.map(|r| to_ipc(r))
.collect())
}
fn vcs_repository_at(&self, root: &Path, path: &str) -> Result<Option<ide_plugin::RepositoryInfo>, HostError> {
let workspace = self.shared.workspace().ok_or(HostError::Cancelled)?;
if !workspace.trusted(root) {
return Err(HostError::Failed("the project is in Restricted Mode: git does not run there".into()));
}
let path = ide_plugin::resolve_in_root(root, path).map_err(HostError::Invalid)?;
let repos = workspace.repositories(root)?;
// A link to a nested worktree directory denotes that worktree, not its entry in the parent.
let Some(repo) = repos.at_root(&path).or_else(|| repos.for_path(&path)) else { return Ok(None) };
let relative = path.strip_prefix(repo.root()).map_err(failed)?;
let info = repo.branch_info().map_err(failed)?;
Ok(Some(ide_plugin::RepositoryInfo {
root: to_ipc(repo.root()),
relative_path: to_ipc(relative),
branch: info.head,
commit: info.head_commit,
upstream: info.upstream,
ahead: info.ahead,
remotes: plugin_remotes(repo)?,
}))
}
fn vcs_fetch(&self, root: &Path, cancel: &CancellationToken) -> Result<(), HostError> {
@@ -3730,6 +3766,13 @@ impl PluginWorkspace for HostWorkspace {
HostWorkspace::project_covering(self, root).is_some_and(|p| p.is_trusted())
}
fn repositories(&self, root: &Path) -> Result<ide_vcs::Repos, HostError> {
Ok(self
.project_covering(root)
.ok_or_else(|| HostError::NotFound("the project is no longer open".into()))?
.repos())
}
fn git_executable(&self, root: &Path) -> Option<PathBuf> {
HostWorkspace::project_covering(self, root)?.git_executable()
}
@@ -4694,6 +4737,10 @@ fn from_window<'a>(client: Option<&'a str>, what: &str) -> Result<&'a str, HostE
client.ok_or_else(|| HostError::Invalid(format!("can only {what} from a command the user invoked")))
}
fn plugin_remotes(repo: &ide_vcs::Repo) -> Result<Vec<(String, String)>, HostError> {
Ok(repo.remotes().map_err(failed)?.into_iter().map(|r| (r.name, without_credentials(&r.url))).collect())
}
/// `url` without the `user:password@` a remote may carry (`https://user:token@host/…`):
/// `vcs.read` must not hand out credentials. scp-style `git@host:path` has no password.
fn without_credentials(url: &str) -> String {
+67 -6
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(
@@ -2361,8 +2385,11 @@ fn git_metadata_watch(root: &Path, sink: &SharedSink) -> Option<Arc<ide_vcs::Met
.ok()
}
/// Whether a VCS metadata path changed for a reason other than our own status run
/// refreshing an index: the main repository's `.git/index` or a linked worktree's
/// `.git/worktrees/<id>/index`.
fn vcs_path_changed(path: &Path) -> bool {
!path.ends_with(".git/index") || !ide_vcs::is_own_index_write(path)
path.file_name().is_none_or(|n| n != "index") || !ide_vcs::is_own_index_write(path)
}
#[cfg(test)]
@@ -2446,6 +2473,40 @@ mod index_event_tests {
std::fs::remove_file(&index).unwrap();
assert!(vcs_path_changed(&index));
}
#[test]
fn status_write_in_a_linked_worktree_is_suppressed() {
let tmp = tempfile::tempdir().unwrap();
let main = tmp.path().join("main");
std::fs::create_dir(&main).unwrap();
let git = |dir: &std::path::Path, args: &[&str]| {
let output = std::process::Command::new("git")
.current_dir(dir)
.args(["-c", "user.name=t", "-c", "user.email=t@t"])
.args(args)
.output()
.unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
};
git(&main, &["init", "-q"]);
std::fs::write(main.join("file.txt"), "original\n").unwrap();
git(&main, &["add", "file.txt"]);
git(&main, &["commit", "-qm", "init"]);
let linked = tmp.path().join("linked");
git(&main, &["worktree", "add", "-q", linked.to_str().unwrap()]);
std::fs::File::options()
.write(true)
.open(linked.join("file.txt"))
.unwrap()
.set_modified(std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1))
.unwrap();
let index = main.join(".git/worktrees/linked/index");
let before = std::fs::read(&index).unwrap();
ide_vcs::Repo::discover(&linked).unwrap().unwrap().status().unwrap();
assert_ne!(before, std::fs::read(&index).unwrap(), "status must actually write the index");
assert!(!vcs_path_changed(&index));
assert!(vcs_path_changed(&main.join(".git/worktrees/linked/HEAD")));
}
}
#[cfg(all(test, unix))]
+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
+34
View File
@@ -81,6 +81,10 @@ impl TestWorkspace {
}
impl PluginWorkspace for TestWorkspace {
fn repositories(&self, root: &Path) -> Result<ide_vcs::Repos, HostError> {
ide_vcs::Repos::discover(root, &|_| false).map_err(|e| HostError::Failed(e.message))
}
fn run_configuration(&self, _client: &str, plugin: &str, id: &str) -> Result<ide_run::RunConfig, HostError> {
if !(plugin == "execution" && matches!(id, "detected" | "dynamic") || plugin == "api14" && id == "tests") {
return Err(HostError::NotFound(id.into()));
@@ -3609,6 +3613,36 @@ fn commands_see_the_paths_they_were_run_on() {
assert_eq!(f.run("jobs", "selection", None).unwrap().as_deref(), Some(""));
}
#[test]
fn plugin_reads_the_repository_owning_the_path() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
let lookup = |path: Option<&str>| f.run("jobs", "repository-at", path);
for name in ["alpha", "beta", "alpha/nested"] {
let dir = f.project.join(name);
std::fs::create_dir_all(&dir).unwrap();
git(&dir, &["init", "-b", "work"]);
git(&dir, &["remote", "add", "origin", &format!("https://user:[email protected]/{name}.git")]);
std::fs::write(dir.join("file.txt"), name).unwrap();
}
assert_eq!(lookup(None).unwrap().unwrap().lines().count(), 3);
for (path, repo, relative) in [
("alpha/file.txt", "alpha", "file.txt"),
("beta/file.txt", "beta", "file.txt"),
("alpha/nested/file.txt", "alpha/nested", "file.txt"),
("alpha/nested", "alpha/nested", ""),
] {
let root = to_ipc(&f.project.join(repo));
let expected = format!("{root}|{relative}|work|[(\"origin\", \"https://example.org/{repo}.git\")]");
assert_eq!(lookup(Some(path)).unwrap().as_deref(), Some(expected.as_str()));
}
assert_eq!(lookup(Some(".")).unwrap(), None);
assert!(lookup(Some("..")).unwrap_err().contains("outside"));
f.host.set_capability("jobs", "vcs.read", false).unwrap();
assert!(lookup(None).unwrap_err().contains("vcs.read"));
assert!(lookup(Some("alpha/file.txt")).unwrap_err().contains("vcs.read"));
}
#[test]
fn vcs_remotes_clipboard_and_open_url() {
let f = fixture(Limits::default());
+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!(
+105
View File
@@ -0,0 +1,105 @@
//! The Dart analysis server's closing labels (`dart/textDocument/publishClosingLabels`): the
//! widget or call a closing `)` / `]` ends, shown after it at the end of the line (`// Column`).
use crate::convert::Conv;
use crate::text::{DocText, Encoding, col_to_byte, units};
use crate::types::{InlayHint, InlayKind};
use ide_core::Pos;
use lsp_types as lsp;
use serde::Deserialize;
use std::collections::BTreeMap;
use std::path::Path;
#[cfg(test)]
use std::sync::Arc;
#[derive(Deserialize)]
pub(crate) struct Params {
pub uri: String,
pub labels: Vec<Label>,
}
#[derive(Clone, Deserialize)]
pub(crate) struct Label {
range: lsp::Range,
label: String,
}
/// One end-of-line hint per line, as the Flutter plugin shows them: `// Padding // Center` when
/// several constructs close on one line. A label whose range no longer ends in `)` or `]` (the
/// text changed since the analysis) is left out.
pub(crate) fn hints(conv: &Conv, path: &Path, text: &DocText, labels: Vec<Label>) -> Vec<InlayHint> {
let mut lines: BTreeMap<u32, Vec<String>> = BTreeMap::new();
for l in labels {
let end = conv.pos(path, l.range.end);
let line = text.line(end.line as usize);
let before = &line[..col_to_byte(line, end.col as usize, Encoding::Utf16)];
if before.ends_with([')', ']']) {
lines.entry(end.line).or_default().push(l.label);
}
}
lines
.into_iter()
.map(|(line, labels)| InlayHint {
position: Pos::new(line, units(text.line(line as usize), Encoding::Utf16) as u32),
label: format!("// {}", labels.join(" // ")),
kind: InlayKind::ClosingLabel,
padding_left: true,
padding_right: false,
tooltip: None,
parts: Vec::new(),
text_edits: Vec::new(),
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn labels(v: serde_json::Value) -> Vec<Label> {
serde_json::from_value(v).unwrap()
}
fn label(line: u32, from: u32, to: u32, label: &str) -> serde_json::Value {
json!({ "label": label, "range": { "start": { "line": line, "character": from }, "end": { "line": line, "character": to } } })
}
#[test]
fn labels_go_to_the_end_of_the_line_and_share_it() {
let text = DocText::new("return Center(\n child: Padding(\n child: Text('a'))), // x\n");
let conv = Conv::new(Encoding::Utf16, |_: &Path| None::<Arc<DocText>>);
let hints = hints(
&conv,
Path::new("/a.dart"),
&text,
labels(json!([label(2, 4, 21, "Padding"), label(2, 4, 22, "Center"), label(2, 11, 20, "Text")])),
);
assert_eq!(hints.len(), 1);
assert_eq!(hints[0].label, "// Padding // Center // Text");
assert_eq!(hints[0].position, Pos::new(2, 28));
assert_eq!(hints[0].kind, InlayKind::ClosingLabel);
}
#[test]
fn a_label_that_no_longer_ends_at_a_bracket_is_dropped() {
let text = DocText::new("Column(children: [])\nRow(\n");
let conv = Conv::new(Encoding::Utf16, |_: &Path| None::<Arc<DocText>>);
let hints = hints(
&conv,
Path::new("/a.dart"),
&text,
labels(json!([label(0, 0, 19, "<Widget>[]"), label(1, 0, 3, "Row")])),
);
assert_eq!(hints.iter().map(|h| h.label.as_str()).collect::<Vec<_>>(), ["// <Widget>[]"]);
}
#[test]
fn utf8_servers_and_wide_characters_give_utf16_columns() {
let text = Arc::new(DocText::new("Text('🙂')\n"));
let doc = text.clone();
let conv = Conv::new(Encoding::Utf8, move |_: &Path| Some(doc.clone()));
let hints = hints(&conv, Path::new("/a.dart"), &text, labels(json!([label(0, 0, 12, "Text")])));
assert_eq!(hints[0].position, Pos::new(0, 10));
}
}
+18
View File
@@ -414,6 +414,23 @@ impl ClientHandler {
}
}
fn publish_closing_labels(&self, mgr: &LspManager, params: Value) {
let params: crate::closing_labels::Params = match serde_json::from_value(params) {
Ok(p) => p,
Err(e) => {
tracing::debug!("{}: bad publishClosingLabels: {e}", self.server.name);
return;
}
};
let Some(path) = uri_to_path(&params.uri) else { return };
if !self.server.is_live(self.generation) {
return;
}
if mgr.set_closing_labels(&path, &self.server, self.generation, self.encoding(), params.labels) {
mgr.sink().emit(IdeEvent::LspRefresh { server: self.server.id, kind: LspRefreshKind::InlayHints });
}
}
/// Once per unresolved plugin, whether m2e marked a `pom.xml` or only logged it.
fn build_plan_failure(&self, mgr: &LspManager, (plugin, body): (String, String)) {
if mgr.first_message(&self.server.name, &format!("build plan: {plugin}")) {
@@ -622,6 +639,7 @@ impl Handler for ClientHandler {
}
"textDocument/publishDiagnostics" => self.publish_diagnostics(&mgr, params),
"dart/textDocument/publishFlutterOutline" => self.publish_flutter_outline(&mgr, params),
"dart/textDocument/publishClosingLabels" => self.publish_closing_labels(&mgr, params),
"window/showMessage" => self.show_message(&mgr, &params),
"window/logMessage" => {
let text = params.get("message").and_then(Value::as_str).unwrap_or_default();
+72
View File
@@ -10,6 +10,7 @@ mod angular;
mod arduino;
mod caps;
mod clang_tidy;
mod closing_labels;
mod compose;
mod convert;
mod external_project;
@@ -86,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);
@@ -150,6 +152,14 @@ struct DocState {
/// When the servers last got new text (open or change): diagnostics published before are stale.
changed: std::time::Instant,
flutter_outline: Option<FlutterOutline>,
/// The Dart server's closing labels for the current text; dropped on the next change.
closing_labels: Option<ClosingLabels>,
}
struct ClosingLabels {
server: ide_core::ServerId,
generation: u64,
hints: Vec<InlayHint>,
}
/// The widget tree last published for a document, valid while that server instance runs.
@@ -1303,6 +1313,7 @@ impl LspManager {
notebook: None,
changed: std::time::Instant::now(),
flutter_outline: None,
closing_labels: None,
};
let compose_added = {
let mut docs = self.docs.lock();
@@ -1351,6 +1362,7 @@ impl LspManager {
let Some(d) = docs.get_mut(&doc) else { return };
d.version = version as i32;
d.changed = std::time::Instant::now();
d.closing_labels = None;
// Servers that have this document open on their current instance.
let targets: Vec<(Arc<Server>, Running, SyncKind, Encoding)> = d
@@ -2437,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,
@@ -2453,6 +2493,37 @@ impl LspManager {
changed
}
/// Records published closing labels; whether what the open documents of `path` show changed.
fn set_closing_labels(
&self,
path: &Path,
server: &Server,
generation: u64,
enc: Encoding,
labels: Vec<closing_labels::Label>,
) -> bool {
let mut changed = false;
for d in self.docs.lock().values_mut().filter(|d| d.path == path && d.notebook.is_none()) {
// Not `self.conv`: it would lock `docs` again for a UTF-8 server's text.
let text = d.text.clone();
let conv = Conv::new(enc, move |_: &Path| Some(text.clone()));
let hints = closing_labels::hints(&conv, path, &d.text, labels.clone());
changed |= !hints.is_empty() || d.closing_labels.as_ref().is_some_and(|c| !c.hints.is_empty());
d.closing_labels = Some(ClosingLabels { server: server.id, generation, hints });
}
changed
}
fn closing_label_hints(&self, doc: DocId, range: Range) -> Vec<InlayHint> {
let docs = self.docs.lock();
let Some(d) = docs.get(&doc) else { return Vec::new() };
let Some(c) = d.closing_labels.as_ref() else { return Vec::new() };
if !d.servers.iter().any(|a| a.server.id == c.server && a.server.is_live(c.generation)) {
return Vec::new();
}
c.hints.iter().filter(|h| range.start <= h.position && h.position <= range.end).cloned().collect()
}
pub async fn workspace_symbols(&self, query: &str, cancel: CancellationToken) -> IdeResult<Vec<WorkspaceSymbol>> {
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
let targets = self.ready_targets(&servers, |c| c.has("workspaceSymbolProvider")).await;
@@ -3315,6 +3386,7 @@ impl LspManager {
}
}
let mut v = out.finish(Vec::new())?;
v.extend(self.closing_label_hints(doc, range));
v.sort_by_key(|h| h.position);
Ok(v)
}
+1
View File
@@ -237,6 +237,7 @@ impl LspManager {
notebook: Some(path.to_owned()),
changed: std::time::Instant::now(),
flutter_outline: None,
closing_labels: None,
},
);
state.cells.push((cell.id.clone(), doc));
+56
View File
@@ -247,6 +247,8 @@ pub enum InlayKind {
Type,
Parameter,
Other,
/// What a closing bracket ends, at the end of its line (the Dart server's closing labels).
ClosingLabel,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -652,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),
}
+113
View File
@@ -1549,6 +1549,119 @@ 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())]);
let (doc, path) = h.open("a.mk", "Center(\n child: Text('x'))\n");
h.wait_status("mock", ServerStatus::Ready).await;
let s = h.launcher.state("mock");
s.respond("textDocument/inlayHint", json!([]));
let refreshes = || {
h.events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::InlayHints, .. }))
.count()
};
let at = |l0: u32, c0: u32, c1: u32| json!({"start":{"line":l0,"character":c0},"end":{"line":1,"character":c1}});
let labels = json!({ "uri": uri_of(&path), "labels": [
{ "range": at(1, 9, 18), "label": "Text" },
{ "range": at(0, 0, 19), "label": "Center" },
]});
s.peer().notify("dart/textDocument/publishClosingLabels", labels).unwrap();
eventually(|| refreshes() == 1).await;
let whole = Range::new(Pos::new(0, 0), Pos::new(2, 0));
let hints = h.mgr.inlay_hints(doc, whole).await.unwrap();
assert_eq!(hints.len(), 1);
assert_eq!(hints[0].label, "// Text // Center");
assert_eq!(hints[0].position, Pos::new(1, 19));
assert_eq!(hints[0].kind, InlayKind::ClosingLabel);
assert!(h.mgr.inlay_hints(doc, Range::new(Pos::new(0, 0), Pos::new(0, 7))).await.unwrap().is_empty());
// Edited text: the labels wait for the next analysis.
h.mgr.did_change(doc, 2, &[change(rng(0, 0, 0, 0), " ")], &|| unreachable!());
assert!(h.mgr.inlay_hints(doc, whole).await.unwrap().is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn diagnostics_become_events_and_feed_code_actions() {
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;
+2
View File
@@ -317,6 +317,8 @@ pub trait HostApi: Send + Sync {
fn storage_keys(&self, prefix: &str) -> Result<Vec<String>, HostError>;
fn vcs_status(&self, root: &Path) -> Result<Option<RepositoryStatus>, HostError>;
fn vcs_remotes(&self, root: &Path) -> Result<Vec<(String, String)>, HostError>;
fn vcs_roots(&self, root: &Path) -> Result<Vec<String>, HostError>;
fn vcs_repository_at(&self, root: &Path, path: &str) -> Result<Option<crate::RepositoryInfo>, HostError>;
fn vcs_fetch(&self, root: &Path, cancel: &CancellationToken) -> Result<(), HostError>;
/// The commit being prepared in `client`'s window (`None`: no repository),
/// waiting for the window until `cancel` fires.
+12
View File
@@ -408,6 +408,18 @@ pub struct RepositoryStatus {
pub changed_files: u32,
}
/// Reference and remotes of a path's mapped worktree (WIT `vcs.repository-info`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RepositoryInfo {
pub root: String,
pub relative_path: String,
pub branch: Option<String>,
pub commit: Option<String>,
pub upstream: Option<String>,
pub ahead: u32,
pub remotes: Vec<(String, String)>,
}
/// A file a pending commit changes (WIT `commit.commit-change`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+28
View File
@@ -1446,6 +1446,34 @@ impl vcs::Host for StoreData {
let root = self.table.get(&project)?.root.clone();
Ok(self.host.vcs_remotes(&root).map_err(to_wit))
}
fn roots(&mut self, project: Resource<ProjectRes>) -> Fallible<Vec<String>> {
if let Err(e) = self.require(Capability::VcsRead) {
return Ok(Err(e));
}
Ok(self.host.vcs_roots(&self.table.get(&project)?.root).map_err(to_wit))
}
fn repository_at(&mut self, project: Resource<ProjectRes>, path: String) -> Fallible<Option<vcs::RepositoryInfo>> {
if let Err(e) = self.require(Capability::VcsRead) {
return Ok(Err(e));
}
Ok(self
.host
.vcs_repository_at(&self.table.get(&project)?.root, &path)
.map(|r| {
r.map(|r| vcs::RepositoryInfo {
root: r.root,
relative_path: r.relative_path,
branch: r.branch,
commit: r.commit,
upstream: r.upstream,
ahead: r.ahead,
remotes: r.remotes,
})
})
.map_err(to_wit))
}
}
impl build::Host for StoreData {
Binary file not shown.
@@ -1 +1 @@
1bd593215a298e86d1dcbccd5431d7efd3d0e0f0d83c0a05ecf95cd597cb89b1
68517d169bea40ca5a5426a3a05ace3389417073b9369e79157a2beb051dcfc0
Binary file not shown.
@@ -1 +1 @@
fce80835362944cf050a430a134a8c742e3365af32ad45ae2156918bd0c74575
6edda84fad0ee7cd56a3a28b55e6c559db7b7f6b9c8c0ca645be805b545c01e7
Binary file not shown.
@@ -1 +1 @@
e7d65dbf92a0edce8f1a6abf5a502dfc4fb4d818599ac1c54e8f82f60e62648a
ecc6b6c52753b11521ae033a5a66c2a289119e09e07d22742203d3a13122dd97
Binary file not shown.
@@ -1 +1 @@
c79c1613b8ce1dd69a2889b6a80a7608c6862b115d4283a8a9bae179e0fb57b9
4ec581c69a62bbf424983e241a79d0bfdb5d025a3e86d27eea745adcb1906253
Binary file not shown.
@@ -1 +1 @@
cc7ff6388700b72a9c8785f7935a79d018752e86ce32407ecd7a3b51f4093f09
5fb89ee3d07e4275433ad9ad930ad781ef4f227af11aa5eb9dfc9174c015b1b8
Binary file not shown.
@@ -1 +1 @@
fcf00edd43ed4fc26201ccdd4d1c102e51b9e0080603204d566e437bedc28fcf
236db5a85d3e7e9fee01c3ff0b9f5e66fad7e3d64fa618a0c1c980d9e5883839
Binary file not shown.
@@ -1 +1 @@
3f00290d04844109a9175f91dae042d3f377f0b2badf56955c589f1c1fbe71db
4f89bd09b571016cbb9feb0674e668aa66996997c6b53a91d1a4ffbf161083a3
Loaded 100 of 598 files, more files were not shown because too many files have changed in this diff. Show more