Compare commits

..
Author SHA1 Message Date
l0ng-ai d4ca3d7857 fix(plugins): keep the applied plugin theme over an older plugin list
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 One Dark Vivid Islands, 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:19 +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
469 changed files with 14110 additions and 2571 deletions

No files matched your search

+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",
]
+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() {
+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
);
}
+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;
+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", ""]);
}
}
+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`].
+18 -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,
@@ -1657,6 +1657,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 +2113,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 +2334,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,
+15 -8
View File
@@ -1977,20 +1977,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();
}
+174 -13
View File
@@ -3,6 +3,7 @@
//! 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
@@ -13,21 +14,25 @@ mod devtools;
pub use devtools::DevToolsServer;
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 +44,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 +59,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 +88,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 +112,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 +129,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 +154,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.
@@ -181,12 +229,48 @@ 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()),
}
}
/// Ends the daemon (project closed, or no longer trusted).
pub fn stop(&self) {
let mut state = self.0.state.lock();
@@ -194,6 +278,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 +296,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 +351,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);
@@ -358,12 +445,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 +495,7 @@ mod tests {
category: Some(category.into()),
emulator,
unavailable: None,
emulator_id: None,
}
}
@@ -433,6 +534,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 +626,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 +647,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 +660,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();
+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 =
+12 -1
View File
@@ -25,6 +25,16 @@ pub fn flutter_daemon_restart(host: &Host, window: &str) -> IdeResult<FlutterDev
Ok(host.project(window)?.flutter.restart())
}
/// 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_emulator_launch(host: &Host, window: &str, id: String) -> IdeResult<()> {
let project = host.project(window)?;
tokio::task::spawn_blocking(move || project.flutter.launch_emulator(&id))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
.map_err(IdeError::unavailable)
}
/// 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)]
@@ -36,4 +46,5 @@ pub async fn flutter_devtools_url(host: &Host, window: &str) -> IdeResult<String
.map_err(IdeError::unavailable)
}
ide_command::domain!(flutter: flutter_devices, flutter_devices_refresh, flutter_daemon_restart, flutter_devtools_url);
ide_command::domain!(flutter: flutter_devices, flutter_devices_refresh, flutter_daemon_restart, flutter_emulator_launch,
flutter_devtools_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(
+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 {
+38 -1
View File
@@ -2361,8 +2361,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 +2449,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))]
+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());
+20 -3
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));
+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 \"{}/threads-42-", dir.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();
+43
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;
@@ -150,6 +151,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 +1312,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 +1361,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
@@ -2453,6 +2464,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 +3357,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));
+2
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)]
+34
View File
@@ -1549,6 +1549,40 @@ 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 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())]);
+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
Binary file not shown.
@@ -1 +1 @@
b9812539466c03233fabd6a428a1598bed0e485841ec462f577889da2f8c1831
c5c3bac9e2b69e4957bd5049d4f560dd04faf4dfc2d7523bb7968aa29f3bdcfb
Binary file not shown.
@@ -1 +1 @@
4a9eaf0b5374baf7cca82553d8209b7750f34c9e6dfd923bb491b07294b564d2
a75758a44e255b7df3adf53e5f81b8f1283270d28f78ad0d8b358d9feea98a99
Binary file not shown.
@@ -1 +1 @@
4d9403692c7bb8698f06c6336c5d9db7934004d6dd09362f77aa361b215108ca
7e658a971fd58b84fcadc1f4939991d5f4506936989d4c8a7302ccebc0455e9c
Binary file not shown.
@@ -1 +1 @@
df21a4a36dbfeb99505d24da6f18011531f581327f2c5069479ad47ab03bb8b3
6b7c0d8971cfd3ba1d80c5fc6428e5890c820350972597a11be4ea6f0324973f
Binary file not shown.
@@ -1 +1 @@
545723b3a96ef095c60cc2e16743fcd23bb8568a023507e2f1c33cba27478717
20e43b6ac3aaa1527874f98f4b502ef88dd4676b6096b989c7bfba7a521e723d
Binary file not shown.
@@ -1 +1 @@
698653d9344a009b0682becb67708d8e4e49d6880bce448f865b985f2605a330
f879df5a331ec439c7e74af4d9c7d249477239e3a0a59d5e612548623cf5e9e2
Binary file not shown.
@@ -1 +1 @@
03da30c1e589f499ae0889af62d39cfdbdcdc9f1035f8ed1479058843ef39ebf
de1fc37d8fd5993164e0d903a0f1b4ba15005f2a90de325d7f4b4902a363fdf1
Binary file not shown.
@@ -1 +1 @@
f080d959792a14554e6978923d4c5461a1b3d31dead0b7ec69131acb98e47f27
367366c14b69d8f3837e731e061768ec5cb344d86fba89ced63fb196e5ca475e
Binary file not shown.
@@ -1 +1 @@
b48218bf3d0f76b519cce52856c5f5c577a2273eb7e0afd63c771c0222342450
b7bccc7f93b409263293d2dff8a31dbdcfcdfba133815f3ff60bc70a073257de
Binary file not shown.
@@ -1 +1 @@
e34aabcbc0fb1cb26d5c913a8ddece8eea205128b4985c24e89935a49c4e290d
f28d85f2004adcdf4e43faa57b7a5b52ab5d8233579979062461b0c5b4c63e10
Binary file not shown.
@@ -1 +1 @@
a6c412b5e9f0f5b677a0d6ec64f50e90a62a5559a25f70a2f40fa83defc35823
23c2c5e6e208104979e1f5b8620d2279547d372f0accf893c2d7797399fe39b0
Binary file not shown.
@@ -1 +1 @@
d364826baf1beeefbd582325a67c95d2d66a58ce2643100974a52e10c7cd7afe
57fc9ea26136a56fa2f502e4bb17531df3f5eed092fde1267199e2447c8fbc23
Binary file not shown.
@@ -1 +1 @@
f130b73f1a32c5a87d052dc3d8274ec92d21083d738775328cd6a587e92bd7b5
105017e20dd7a93cecb178576f2718ccf8433a6fac027b5708d6e2121f85e27a
Binary file not shown.
Loaded 100 of 469 files, more files were not shown because too many files have changed in this diff. Show more