Compare commits

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

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

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

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

Fixes #2692

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

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

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

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

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

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

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

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

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

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

Closes #5844

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

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

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

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

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

Related to #4096.

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

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

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

Part of #4096.

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

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

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

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

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

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

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

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

Part of #4096.

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

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

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

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

---------

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

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

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

Part of #4096

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

Closes #5825

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

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

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

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

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

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

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

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

Closes #5802

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Part of #5593.

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

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

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

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

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

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

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

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

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

Closes #5778

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

Part of #4096

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 14:13:23 +08:00
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
Deng Liuanddengliu 8e9a0e48cf fix(vfs): ignore fsmonitor traffic in linked worktrees (#5717)
With Git's built-in fsmonitor enabled, even read-only git status / git diff create cookie files under .git/worktrees/<id>/fsmonitor--daemon/. The watcher treated everything below .git/worktrees as VCS metadata, so each VCS or agent change-list refresh produced cookies that scheduled another refresh, keeping the CPU busy with no edits. The daemon directory and its IPC socket inside a linked worktree's gitdir are now neither watched nor reported; real worktree metadata (HEAD, index, refs) still refreshes VCS. The main gitdir's fsmonitor--daemon was already ignored.

Co-authored-by: dengliu <[email protected]>
2026-11-25 09:14:10 +08:00
Vladislav Kuzmin e3f8bd45cf feat(database): manage external TCP tunnels for PostgreSQL (#5670)
PostgreSQL data sources can choose External TCP tunnel in SSH/SSL when a local program provides access to the database. The IDE starts the foreground helper with the configured arguments ({localPort}, {host}, {port}), shares it across the source's connections and stops it on the last disconnect; Test Connection uses a temporary helper. The driver gets a loopback endpoint, so the route stays driver-independent like SSH forwarding.

The executable and arguments run only after a machine-local approval in the desktop dialog, bound to the reviewed settings, the destination and the executable's path and content; a project file alone never starts a program. The helper gets a cleared environment (plus PATH/HOME-style and credential-free proxy variables), its own session or job object, and each forwarded socket is checked for helper ownership. Verify Full is explained as unavailable on this route.

Fixes #5653

Co-authored-by: principalwater <[email protected]>
2026-11-25 08:55:09 +08:00
Fabio Nunes 4f01691ef3 fix(vfs): apply the configured encoding to ASCII files (#4829)
A plain-ASCII file reads the same in any ASCII-compatible encoding, so it was always labelled UTF-8 and the first non-ASCII character typed into it was saved as UTF-8 even when the project or global encoding said otherwise. The configured project/global encoding now labels ASCII files too (decoding is unchanged), through one rule (ide_vfs::Fallback / resolve) shared by the editor, closed-file reads, bounded snapshots, search and VCS revisions. The .properties encoding keeps only decoding non-UTF-8 bytes, so an ASCII .properties file stays UTF-8 by default. An .editorconfig charset now applies to existing ASCII files (judged by their bytes, never relabelling UTF-16) on open, external reload and resource reload as well as to empty files.

Refs #4557

Co-authored-by: LittleGuava <[email protected]>
2026-11-25 08:46:36 +08:00
Delaruno20andDelaruno20 7d4c58a0f1 feat(notebook): fold cells and outputs in the notebook editor (#5650)
A chevron in each cell toolbar folds the cell to one line (its first non-blank line, or a Markdown heading's text) with its output count; clicking the line unfolds it. Code cells with outputs get Hide Output / Show Output, which folds only the outputs, and the notebook toolbar gets Collapse All Cells / Expand All Cells. Fold state is view state on NotebookSession; the .ipynb file is not modified. The singular output counts use their own catalog keys so they don't collide with the run output pane's "{name} output".

Co-authored-by: Delaruno20 <[email protected]>
2026-11-25 08:46:07 +08:00
l0ng-ai f6e51d9214 feat(color-scheme): TypeScript interface, type alias and type parameter colours (#5716)
The JavaScript and TypeScript colour page gets Interface name, Type alias and Type parameter under Classes. tsserver's interface, type and typeParameter semantic tokens carry their own classes, which fall back to the class name colour until set. JS./TS.INTERFACE, TYPE.ALIAS and TYPE_PARAMETER in an imported .icls now land on these entries instead of Class name.

Refs #5619
2026-11-25 08:34:34 +08:00
Mansur Akhmadiandmansur-akhmadi 2f0b0b4ad5 feat(editor): Scroll Up / Scroll Down actions (#5714)
Scroll Up and Scroll Down move the editor by one line without moving the caret or touching the selection and history. Bound to Ctrl+Up / Ctrl+Down in the IntelliJ and VS Code Windows keymaps (unbound on macOS, where IDEA removes them) and mapped from IDEA's EditorScrollUp / EditorScrollDown ids.

Fixes #5713

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 08:28:01 +08:00
Mansur Akhmadiandmansur-akhmadi cf33432204 feat(editor): Find Word at Caret / Find Previous Word at Caret (#5712)
Find Word at Caret and Find Previous Word at Caret jump to the next or previous occurrence of the selection, or of the identifier around the caret, without opening the find bar: case-sensitive, not whole words, anywhere in the file, and the query becomes the last search so Find Next continues with it. Bound to Ctrl+F3 / Ctrl+Shift+F3 in the IntelliJ Windows keymap and mapped from IDEA's FindWordAtCaret / FindPrevWordAtCaret ids.

Fixes #5711

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 08:27:14 +08:00
Vladislav Kuzminandprincipalwater acad0645d4 fix(database): verify PostgreSQL read-only startup settings (#5693)
A PostgreSQL pooler can reject or silently drop the default_transaction_read_only startup option of a read-only source. The native driver now keeps the pooler's SQLSTATE and message with a hint on what to configure (PgBouncer's track_extra_parameters), checks after login that the default is really on before running the startup script, and after a startup script checks the default again and rejects an open writable transaction. Ordinary connections pay no extra round trips.

Fixes #5686

Co-authored-by: principalwater <+[email protected]>
2026-11-25 08:22:19 +08:00
l0ng-ai 55b710fe53 fix(project): show why a project can't be reopened instead of [object Object] (#5715)
The local trust check called its Tauri commands with the raw invoke, which rejects with the backend's error object, so reopening a recent project whose folder was deleted showed [object Object]. Both local trust commands now go through callDesktop, which raises an IpcError with the backend's message.
2026-11-25 08:20:32 +08:00
l0ng-ai dd4d3325d4 fix(tools): Install on a tool without an installer opens the settings page on that tool (#5710)
Install in the Language Servers popup or an install notification, for a server the IDE can't install itself, opened Settings › Language Servers on the first language, away from the manual install command. It now opens the page on that tool (languages.servers#<tool>).
2026-11-25 07:35:32 +08:00
audichuang 5f437929c0 perf(search): count a long line's window offsets from the previous window (#5698)
A very long line is cut into 500-unit windows around its matches, and each window's UTF-16 text offset was counted from the line start: quadratic in the line length (101 s for a 20 MB line with a frequent term). Each window's offset now adds the UTF-16 length since the previous window's start, falling back to the line start if a window starts earlier. Output is unchanged, checked against the previous windowing on 3,000 random lines; adds an observe-only search_long_line bench.

Co-authored-by: audichuang <[email protected]>
2026-11-25 07:32:14 +08:00
Vladislav Kuzmin f9ed5027c8 test(run): use native paths for the Tomcat deployment context (#5700)
The Tomcat multi-deployment test compared the generated docBase with a path built from mixed separators, so it failed on Windows. Build the expected directory one component at a time and match the full escaped docBase attribute; the file-content check uses the same directory.

Fixes #5699

Co-authored-by: principalwater <[email protected]>
2026-11-25 07:31:26 +08:00
l0ng-ai 9cd1f45b35 fix(editor): read XAML's alpha-first hex colors in the color preview (#5709)
XAML writes hex colors alpha first (#AARRGGBB, #ARGB); in .axaml files the color gutter read them as CSS's #RRGGBBAA and showed the wrong swatch. The swatch, the picker's starting value and the written-back color now use the alpha-first order in Avalonia XAML; other languages keep CSS's order.
2026-11-25 07:30:54 +08:00
l0ng-ai 26e7847457 feat(languages): Avalonia XAML (.axaml) as its own language with an Avalonia language server (#5708)
.axaml files opened as plain XML. They are now the Avalonia XAML language: XML grammar, highlighting, folding and outline as before, XAML's 4-space indent, Surround With tag, and the axsg-lsp language server (installed by hand as a prerelease dotnet tool; the Language Servers page shows the command and takes a custom path), with LemMinX as the XML fallback. .xaml stays XML.

Fixes #5664
2026-11-25 07:28:42 +08:00
audichuang 0a146e4ac9 perf(run): mark the console scenario's sequential awaits as intentional (#5707)
The consoleLongLines perf scenario and the sample console stream await one wheel step, scroll position or output batch per frame on purpose; mark those awaits so no-await-in-loop no longer fails lint on main.

Co-authored-by: audichuang <[email protected]>
2026-11-25 07:21:42 +08:00
l0ng-ai cd42a59c01 fix(run): run shell scripts in a terminal by default (#5706)
Shell scripts ran on pipes with no TTY, so `read` prompts, `[ -t 0 ]` checks and `tput` did not behave as in a shell, and remote SSH runs got no PTY or TERM at all. New Shell Script run configurations and shell scripts run from the editor (by extension or by their #! line) now run in a terminal. A run configuration template still decides the default for new configurations.

Fixes #5624
2026-11-25 07:20:10 +08:00
Mansur Akhmadiandmansur-akhmadi a37e837043 feat(editor): editor appearance switches as View toggle actions (#5704)
Show Line Numbers, Show Indent Guides, Show Sticky Lines and Show Whitespaces are now View toggle actions (editor.toggleLineNumbers / toggleIndentGuides / toggleStickyLines / toggleWhitespaces): runnable from Find Action with their ON/OFF state and bindable to a key, writing the same global settings as the gutter's Appearance menu and Settings. IDEA's EditorGutterToggleGlobalLineNumbers / IndentLines / StickyLines map to them. The gutter's Appearance menu gains Show Sticky Lines and builds its items from the same table.

Closes #5703

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 07:10:00 +08:00
Mansur Akhmadiandmansur-akhmadi 08444a4187 feat(editor): Convert Indents to Spaces / to Tabs actions (#5702)
Adds IDEA's Convert Indents to Spaces and Convert Indents to Tabs (code.convertIndentsToSpaces / code.convertIndentsToTabs, Edit category, no default shortcut). They rewrite only the leading whitespace of the selected lines, or of the whole file without a selection, measured in columns with the editor's tab size; To Tabs keeps the columns short of the next tab stop as spaces. ConvertIndentsToSpaces / ConvertIndentsToTabs from imported IDEA keymaps and IdeaVim :action now resolve.

Closes #5701

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 07:08:25 +08:00
audichuang 6cc0a877be fix(templates): count packages from Gradle-synced and Eclipse source roots (#5688)
New Java and Kotlin classes got the wrong package line (and New offered Directory instead of Package) in JVM source roots whose marker the build-file pattern didn't recognise: source sets a Gradle sync reports (marker Gradle, e.g. src/gen) and Eclipse .classpath source folders. The pattern in templates/files/create.ts and project-tree/packages.ts now accepts both markers.

Co-authored-by: audichuang <[email protected]>
2026-11-25 07:07:22 +08:00
audichuang ed66588b0d fix(i18n): show branch, repository and module names as written in pickers (#5690)
In the Chinese UI a branch, repository folder or module named dev or test showed as 开发 / 测试, because Select looks option labels up in the text catalog. The remaining pickers with detected names now mark their options verbatim: the Branches popup's multi-repository headers, the Rebase dialog's branches, Stashes and Apply Patch repositories, the new agent task's project and base branch, Find in Files modules, Execute Gradle/Maven Task projects, the Dependency Analyzer module, and run configuration selects that load their options.

Co-authored-by: audichuang <[email protected]>
2026-11-25 07:07:16 +08:00
audichuang e1d3eca189 perf(project-tree): find the top-level selected paths in linear time (#5695)
Copy, Cut, Delete, Move and drag and drop in the Project view went through topLevelPaths, which compared every selected path with every other one: with 10,000 selected files ⌘C and Delete blocked the UI for about 2-3 s. outermostPaths looks each path's parent folders up in a map of the selected paths instead, once per folder, and returns the same paths in the same order (checked against the pairwise filter on random path sets with mixed separators, drive letters and UNC roots). The Delete dialog's file and folder counts use a set. Adds a projectTreeSelection perf scenario.

Co-authored-by: audichuang <[email protected]>
2026-11-25 07:05:05 +08:00
faysouandfaysou 50e6f242ec feat(plugins): let interactive components choose a file on the project host (#5655)
API 1.16 adds ui.pick-file (host::pick_file in the SDK): during an interactive command or view event a component can choose an existing file or a save destination, with a title, a suggested name and extension filters. It returns an absolute path on the project host, or none when dismissed. It uses the same prompt routing and path validation as pick-directory: the native dialog locally and the project host's chooser in remote windows. Choosing a file grants no capability; the component uses the file through the grants it already has.

The suggested name is reduced to a file name, so the dialog never starts in a directory the plugin names, and filters are capped and clipped like other prompt text. Checked-in plugin components are rebuilt for the WIT change.

Co-authored-by: faysou <[email protected]>
2026-11-25 06:59:08 +08:00
Vadim LazukandInf1mum 5567aff80a feat(database): preview the console's execution range with a border (#5694)
A console now borders the SQL an Execute would submit: the caret's statement, or the selected statements, using the same db_statements split the run makes, so what is shown and what is submitted cannot differ. While a run is in progress its submitted range stays bordered as the caret moves. The selection is never changed.

The border is one box around each statement's text, drawn on an editor layer, in the accent colour with a soft fill (light and dark themes). Typing waits for a 150 ms pause before splitting again; caret moves update at once.

Closes #5524

Co-authored-by: Inf1mum <[email protected]>
2026-11-25 06:32:30 +08:00
Mansur Akhmadiandmansur-akhmadi fedd5ffd4f feat(editor): Fill Paragraph action (#5681)
Edit › Fill Paragraph (code.fillParagraph, IDEA's FillParagraph) re-wraps the comment or plain-text paragraph at the caret to the hard wrap column: a run of line comments with the same marker, the * lines of a block comment up to a blank line or @tag, or non-blank lines of a plain text file. Code, string literals and read-only editors are left alone. No default shortcut, as in IDEA.

Closes #5680

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 06:26:46 +08:00
audichuang f16cfb507b perf(run): detect console links in linear time (#5649)
The path and JVM-frame patterns in findOutputLinks were unanchored, so on a line without a match they rescanned to the end from every start position: quadratic in the line length. Streaming 1,000 lines of 10 KiB into the Run console took 37.6 s with frames up to 1 s; the Build and Debug consoles share the same detection.

Each matcher now anchors on a fixed delimiter or extension suffix and walks the path back from there, so detection is linear, and the overlap check becomes a cursor. The links found are unchanged (compared with the previous findOutputLinks on 400,000 generated lines). Adds a consoleLongLines perf scenario.

Co-authored-by: audichuang <[email protected]>
2026-11-25 06:24:45 +08:00
Mansur Akhmadiandmansur-akhmadi 80459bae37 fix(keymap): list the Remove All Breakpoints actions in the keymap presets (#5687)
debug.removeAllBreakpoints and debug.removeAllBreakpointsInFile (added in #5675) were missing from the keymap presets, so the vim :action ids test failed on main. Both have no default shortcut in IDEA; they are listed with [] in intellij-macos, intellij-windows and vscode-macos.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 06:22:10 +08:00
l0ng-ai 6cc82bd48e fix(java): tell the user when jdtls fails to sync a Gradle project (#5697)
When Buildship can't sync a Gradle build (a broken build script, a missing
toolchain, an init script error), jdtls only logs "Synchronize project X failed
due to an error connecting to the Gradle build." below error level. The import
failed silently: every Java file showed unresolved JDK types and nothing in the
UI said why.

That log now raises a "Gradle project sync failed" notification, once per
project and cause, with the deepest "Caused by" of the stack trace as the
reason. A sync that failed on an incompatible JDK is left to jdtls' following
"Can't use Java ... to import Gradle project ..." message, which already has its
own notification with Choose Gradle JVM / Download JDK, so the notification
waits briefly for it instead of showing both.

Refs #5669

Tested: ide-lsp unit tests for the log parsing (real Buildship logs) and a mock-server test for the once-only notification and the incompatible-JDK hand-off; ide-lsp clippy; locale catalog tests.
2026-11-25 06:21:07 +08:00
l0ng-ai e5c9e84c83 feat(editor): find a Vue component's usages from Code Vision and Find Usages on the file (#5696)
A .vue file now shows a "Show component usages" Code Vision entry at the top, and
Find Usages on a file in the project tree lists where it is used, not just
nothing.

The file's imports come from tsserver's fileReferences request (sent through
vtsls' typescript.tsserverRequest by the new lsp_file_references command). For a
.vue component, the default import binding at each import is then searched with
textDocument/references, so template tags like <Hello> and calls like
app.component('Hello', Hello) are listed too; the binding's own import line is
not repeated. Safe Delete on a file reuses the same search.

Vue files need vue-language-server installed for tsserver to resolve them.

Fixes #5603
2026-11-25 06:14:33 +08:00
l0ng-ai 5cae7ac316 feat(run): deploy several artifacts from one Tomcat run configuration (#5692)
The Deployment tab's "Deploy at the server startup" list now holds any
number of WAR artifacts, WAR files and exploded directories. + adds to
the list instead of replacing the deployment, − removes the selected
one, and the arrows reorder. Application context and context descriptor
edit the selected deployment, and a context path that two deployments
share is flagged.

The first deployment stays in the configuration's own fields, so
existing configurations work unchanged. The others are stored as a list
in `extraDeployments`. On launch, each deployment is exploded into its
own state directory (`deployments/<n>` below the runtime base) and gets
its own `conf/Catalina/localhost/<context>.xml`. A context used twice is
refused. Before launch builds every out-of-date WAR. Update actions
(resources, classes, redeploy) and the post-build class sync cover all
deployments.

Fixes #5607
2026-11-25 05:55:05 +08:00
l0ng-ai 5e3499026e feat(database): configurable keyword and identifier case for SQL Reformat Code (#5689)
Code Style › SQL gets a Case tab with Keywords and Identifiers, each To
upper / To lower / Do not change. Reformat Code applies them to every SQL
file and query console, bound to a data source or not. Keywords default to
upper case and identifiers stay as written.

Keywords are the dialect's reserved words, clause, join and predicate words
plus common DDL words, except where they are part of a qualified name
(`t.key`). Identifiers are unquoted names only. Quoted names, bind parameters
(`:name`, `@name`) and ClickHouse names, which are case-sensitive, keep
their case.

Fixes #5605
2026-11-25 05:44:48 +08:00
l0ng-ai 6cd463e9c1 feat(welcome): change any project's colour and icon from the project widget and Welcome screen (#5685)
Projects can show a custom icon instead of the coloured initials: an SVG or
PNG in `.openidea/icon.*` (or IntelliJ's `.idea/icon.*`, with `icon_dark.*`
used in dark themes). Change Project Icon… copies the chosen image there and
Reset Project Icon removes it.

The project context menu in the title bar project widget and on the Welcome
screen now offers Change Project Color…, Change Project Icon… and Reset
Project Icon for open projects as well as recent ones; the colour picker is
a workbench overlay so it opens from any of these places.

Fixes #5613
2026-11-25 05:36:17 +08:00
l0ng-ai 089b914c96 fix(agents): fit the session status strip to a narrow session (#5684)
In a narrow docked session the strip under the composer truncated nearly every item. It now gives way in steps: below 560px the provider shows its icon and the change/commit chips their count; below 420px a local task's branch and the task state (except a usage limit) are left out, keeping the changes and meters. Tooltips and accessible names keep the full text.

Fixes #5614
2026-11-25 05:22:07 +08:00
l0ng-ai 2523e17cbd feat(editor): colour JavaScript and TypeScript methods apart from functions (#5683)
tsserver's method/member tokens were mapped to the plain function class. Methods now also get an instance- or static-method class, with Identifiers › Instance method and Static method on the JavaScript and TypeScript colour scheme page; unset, they keep the function declaration/call styles so existing themes look the same. JetBrains scheme import maps INSTANCE_MEMBER_FUNCTION and STATIC_MEMBER_FUNCTION to them.

Fixes #5623
2026-11-25 05:13:27 +08:00
l0ng-ai 966e4cd03c feat(toolbar): add a Center group to Customize Main Toolbar (#5682)
Customize Main Toolbar now has Left, Center and Right groups (appearance.mainToolbar.center, empty by default). The Center group is centred on the whole title bar when the other groups leave room, otherwise pushed against the group it would overlap, as IDEA's main toolbar lays it out.

Fixes #5612
2026-11-25 05:06:00 +08:00
l0ng-ai 4fa84461ef feat(vcs): add a Git Branch status bar widget (#5679)
A Git Branch widget can now be switched on from the status bar's context menu (off by default). It shows the same branch label and incoming/outgoing markers as the toolbar widget, and a click opens Git Branches anchored above it. The popup state records which widget opened it, so each widget shows its own expanded state.

Fixes #5610
2026-11-25 04:57:31 +08:00
l0ng-ai d269570f72 feat(database): freeze the result grid's row numbers and add rows with ⌘/Ctrl-click (#5678)
The row-number column scrolled away with the data when a wide result was scrolled sideways. It is now sticky at the left edge (header included) and drawn above the cells passing under it.

Row numbers also select like a row header: ⌘/Ctrl-click adds or removes a row, Shift-click extends the lead range, dragging down the numbers selects whole rows. Copy, Copy Rows, the row context menu and the Aggregates panel use every selected row.

Fixes #5527
2026-11-25 04:51:37 +08:00
Vladislav Kuzmin 3927e70476 fix(run): scope JVM thread-dump test helpers to Unix (#5672)
The thread-dump tests' helpers in ide-jvm-attach and ide-host use Unix-only APIs, so the Windows test build failed to compile on main. Gate the helpers and the tests that use them to Unix.

Closes #5671

Co-authored-by: principalwater <[email protected]>
2026-11-25 04:43:07 +08:00
l0ng-ai af3e174702 fix(java): apply the Eclipse plugin to the project in the Gradle classpath init script (#5677)
Inside the Gradle classpath init script's closures a bare `apply plugin: 'eclipse'` resolves to the init script's own apply. On Gradle 7 the Eclipse plugin then can't get its project services (no IdeArtifactRegistry), applying java fails, and jdtls's Gradle import fails for every Gradle 7 project, leaving all Java files red. The script now calls project.apply; a test keeps bare apply calls out of it.

Fixes #5669
2026-11-25 04:37:46 +08:00
Mansur Akhmadiandmansur-akhmadi 7532ff30fd feat(debugger): Remove All Breakpoints In The Current File action (#5675)
Remove All Breakpoints In The Current File (Debugger.RemoveAllBreakpointsInFile) removes the line breakpoints of the file in the active editor, plus the method breakpoints and field watchpoints whose gutter icon is in that file; other files, name-only method breakpoints and exception breakpoints stay. It is in Find Action with no default shortcut. Imported IDEA keymaps and IdeaVim :action now map Debugger.RemoveAllBreakpoints and Debugger.RemoveAllBreakpointsInFile.

Closes #5674

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 04:03:10 +08:00
l0ng-ai 675e1ccd61 fix(editor): show hovers on the first lines while the caret is further down (#5676)
The sticky-scroll top scroll margin reserved the caret's enclosing header rows at all times. CodeMirror also treats that margin as covered when placing tooltips, so with the caret inside a method every hover on the first lines of a file (quick documentation, plugin decoration cards) was parked off screen though no sticky rows were showing. The caret's rows are now reserved only while the caret sits above where they would stick, which is when revealing it scrolls them in; otherwise the margin is the rows showing now.
2026-11-25 03:59:40 +08:00
Charlie.Weiandcharli117 00f482a7cc feat(plugins): Markdown hover cards for editor decorations (API 1.16) (#2622)
decorations.set-markdown (API 1.16) draws the same line-end labels as decorations.set and shows each item's markdown_hover as a hover card on the label or the decorated text. The card renders through the shared Markdown path (marked + DOMPurify, media and resource attributes stripped), uses the editor's hover styling, can be resized from its edges, and closes on Escape, an outside click, window blur or leaving the window. Set ids, the 10,000-item and 4 MiB limits and clear are shared with set. SDK: host::set_markdown_decorations and MarkdownDecoration, with a decorations fixture plugin.

Co-authored-by: charli117 <[email protected]>
2026-11-25 03:57:00 +08:00
Akbar Husain 6269c4e1e6 perf(run-db): resolve no-await-in-loop in run and database (#5673)
Enables oxlint's no-await-in-loop for src/features/run and src/features/database. Every await that stays sequential there carries the reason: launch tasks and derived tests run in order, debugger roots detach in order before the last one stops the shared process, retry loops classify each failure before the next attempt, credential and trust prompts must not stack, and schema introspection checks cancellation per schema. Tests that press keys and assert in sequence are annotated the same way. No behaviour changes.

Co-authored-by: akbar1214 <[email protected]>
2026-11-25 03:45:30 +08:00
faysouandfaysou 46b3a0bbc9 feat(plugins): support ranged reads in binary web editors (#4914)
A web custom editor declared with `binary = true` (API 1.16, web page with `layout = "tab"`) opens a file without creating a text document. Its page reads the file's size with `document.size()` and byte ranges of at most 1 MiB with `document.readRange(offset, length)`, so large binary formats such as Parquet can be read piece by piece. The path is always the editor's own file, never one the page supplies, and messages from the page to the plugin's code carry that file as the editor context.

The manifest field is rejected below API 1.16 and only allowed on tab-layout web editors; the docs and the API 1.16 notes list the new bridge methods.

Co-authored-by: faysou <[email protected]>
2026-11-25 03:40:24 +08:00
Akbar Husain f944a51e5a perf(editor): parallelize independent awaits and suppress intentional ones (#5652)
Independent awaits in the editor now run together, and the awaits that must stay sequential carry an explained no-await-in-loop suppression.

- Implementation and override gutter markers: base resolution, subclass outlines, super-method lookups and per-owner hierarchy walks run in parallel; results are merged in the original order, and outline/hierarchy requests stay deduplicated per pass.
- Inheritance graph and super-method walks resolve all bases of one level together; levels stay sequential.
- Introduce Variable verifies up to 30 occurrences in parallel; format requests for several ranges run together and edits are applied in range order.
- Python abstract members, Python hierarchy outlines, completion sources and embedded-document shutdown run in parallel, keeping declaration/source order.
- Budgeted walks, cancellation checks, ordered marker batches and Safe Delete's per-symbol search stay sequential.

Co-authored-by: akbar1214 <[email protected]>
2026-11-25 03:32:16 +08:00
Akbar Husain f943eee851 perf(vcs): resolve no-await-in-loop across VCS operations (#5657)
Clears the no-await-in-loop diagnostics under src/features/vcs. Pending-patch reads of the selected repositories now run in parallel (order kept); Git command sequences, confirmation and retry loops, cancellation checks and ordered UI or store updates stay sequential with narrow documented suppressions. The rule is enabled as an error for the VCS scope, next to evals, perf and smoke.

Co-authored-by: akbar1214 <[email protected]>
2026-11-25 03:27:12 +08:00
Akbar Husain 40379cdc91 perf(tooling): resolve no-await-in-loop in perf, evals and smoke (#5663)
Every no-await-in-loop diagnostic in evals/, perf/ and smoke/ is an intentionally sequential loop (measured inputs and frame pacing, shared editor and browser state, chained DAP requests, session and process lifecycle), so each gets a narrow documented suppression, and the rule is enabled as an error for those three directories so new ones are caught.

Co-authored-by: akbar1214 <[email protected]>
2026-11-25 02:53:34 +08:00
faysouandfaysou 1ad9189861 feat(editor): configure sticky lines by language (#5263)
Settings › Editor › General › Sticky Lines gains "Show sticky lines for:", a checkbox per language under the maximum line count. The editor stores the unchecked language ids with the line count; an editor of an unchecked language drops the sticky lines extension and its scroll margin, so Find and Go to Line use the full height. Applying the setting reconfigures open editors.

Co-authored-by: faysou <[email protected]>
2026-11-25 02:52:06 +08:00
Vadim LazukandInf1mum fba210e22d feat(php): devsense-php-ls as a selectable PHP language server (#5658)
DEVSENSE PHP Tools (devsense-php-ls) is one more selectable PHP language server in Settings › Languages & Frameworks › Language Servers, after Phoxite; Intelephense stays the default. Its engine is native (only the npm launcher needs Node), and while it serves it replaces laravel-lsp, as it answers the Laravel strings itself. Docs note which features need a DEVSENSE licence. A managed install can follow.

Fixes #5496

Co-authored-by: Inf1mum <[email protected]>
2026-11-25 02:37:03 +08:00
Vadim LazukandInf1mum 40c8e83084 feat(editor): cycle an identifier between snake, kebab, camel and Pascal case (#5666)
Code › Cycle Identifier Case (Shift+Alt+U in the IntelliJ keymaps; Find Action under camel, snake, kebab, Pascal) converts the identifier at each caret, which stays selected, or each selection to the next style: snake_case → SCREAMING_SNAKE_CASE → kebab-case → camelCase → PascalCase. The current style is read from the text; words split at separators, case changes and the end of an acronym; a single word goes name → Name → NAME, and a style that would write the text the same way is skipped.

Fixes #5615

Co-authored-by: Inf1mum <[email protected]>
2026-11-25 02:35:15 +08:00
Vadim LazukandInf1mum c6ea0ddab1 feat(welcome): Shift or Ctrl+click opens a recent project in a new window (#5667)
In the recent project lists (title bar project popup, Welcome screen, File › Open Recent), Shift+click or Ctrl+click (also ⌘+click on macOS) opens the project in a new window and Alt+click in this one, whatever "Open project in" says; Enter takes the same modifier keys. Local and SSH/WSL projects alike. A plain click or Enter is unchanged, and rows under Open Projects still switch to their window.

Fixes #5598

Co-authored-by: Inf1mum <[email protected]>
2026-11-25 02:31:53 +08:00
Mansur Akhmadiandmansur-akhmadi c3d1ba28fd feat(editor): Duplicate Entire Lines action (#5661)
Code › Duplicate Entire Lines (EditorDuplicateLines, no default shortcut, as in IDEA) copies every line a caret or selection touches below itself, even when only part of a line is selected, and moves the selection onto the copy. On a folded region's line it copies the folded block, as Duplicate Line or Selection does; that path now maps selections as well as carets onto the copy. Imported IDEA keymaps and IdeaVim :action map EditorDuplicateLines to it.

Fixes #5660

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-25 02:29:00 +08:00
l0ng-ai 75781a5731 fix(project): rename the type of a copied Java file to the copy's name (#5668)
Copying a .java file kept the type under its old name, so the copy failed to compile, and the default name "Foo copy.java" could never be a type name. A Java source now gets a default copy name its type can take (FooCopy.java, FooCopy2.java), and a copy under a new name renames the top-level type in it: its declaration, constructors and the copy's own references, not strings, comments or same-named members. Applies to Copy (F5) and to copy and paste in the Project view.

Fixes #5647
2026-11-25 02:25:17 +08:00
Vadim LazukandInf1mum 63f2f0280d fix(run): launch a Gradle-delegated run on the project's Java toolchain (#5656)
Build and run using Gradle started the main class on Gradle's own JVM: the openideaRun JavaExec task never set javaLauncher, and before Gradle 9 JavaExec does not default to the project's toolchain. With a toolchain newer than Gradle's JVM the class failed with UnsupportedClassVersionError. On Gradle 6.7+ the task now launches on the project's Java toolchain, as the application plugin's run does; a project without a toolchain still runs on Gradle's JVM.

Fixes #5594

Co-authored-by: Inf1mum <[email protected]>
2026-11-25 02:19:25 +08:00
faysouandfaysou cd3399df60 fix(vcs): keep selection history in the editor Git menu (#5654)
The shared Git submenu (#5611) dropped Show History for Selection from the editor's context menu. It is back for a right-click in the editor and stays out of the tab and Project view menus. The browser tests now use the shared menu's labels and groups, including keyboard navigation to Get from Version Control….

Co-authored-by: faysou <[email protected]>
2026-11-25 02:17:58 +08:00
faysouandfaysou fc4e4fa39a fix(markdown): keep large previews responsive when scrolling and switching tabs (#5249)
Fast scrolling could leave either pane of a Markdown split blank, and large previews were rebuilt on every tab switch.

- The source draws newly visible lines before painting a large scroll jump; the preview follows wrapped lines and table rows, handles trackpad gestures from their first wheel event, and updates its position while the scrollbar thumb is dragged (the Git log's scrollbar, resized as content grows).
- Recent Markdown tabs stay mounted while hidden (text editor wrappers can now opt into keepAlive); the hidden source view is detached as before and the preview is moved off screen on its own layer.
- Edits reuse unchanged equation and Mermaid SVGs, including diagrams with math labels; changing a TeX macro refreshes the equations that use it.
- Long embedded image payloads are folded in the source, and the Markdown parser skips the payload bytes of standalone images.

On a 5.85 MB document in WebKit, first open went from 22.9 s to 3.25 s and returning to the tab from 14.4 s to 0.24 s.

Co-authored-by: faysou <[email protected]>
2026-11-25 02:17:02 +08:00
faysouandfaysou 13e27f0133 fix(editor): calculate sticky scroll margins from the visible folded line (#5662)
The sticky-lines top margin used when scrolling the caret into view counted the headers enclosing the caret's source line, including headers a fold had hidden. Inside a folded block in a narrow split the extra rows made CodeMirror treat the visible fold placeholder as clipped and push the folded-code tooltip out of the viewport. The margin now starts from the caret's displayed line block, so outer scopes still count and unfolding restores the full margin.

Co-authored-by: faysou <[email protected]>
2026-11-25 02:09:48 +08:00
LU XIANGRUIandwildcatDownstairs f028109518 fix(java): colour unterminated string and char literals to the end of the line (#5566)
An unterminated Java string or char literal (`String s = "abc;`, `char c = 'a;`) is string-coloured up to the closing quote or the end of the line, as the IntelliJ lexer ends such a literal. @lezer/java has no token for it: error recovery leaves the quote as a one-character error node and parses the rest of the line as code. The new scan finds those error nodes, skips escaped quotes, and composes with the contextual-keyword and escape ranges in Java's syntaxRanges; nested spans inside the literal take the string colour. Unterminated text blocks already run to the end of the file and are unchanged.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 02:08:13 +08:00
ntbang0901 8492dc530a feat(run): Dump Threads for JVM run and debug sessions, with deadlocks (#5595)
Run › Dump Threads (Run tool window toolbar, for running Java applications, JAR applications, Gradle bootRun and Maven run goals) and Debug › Dump Threads (debugger toolbar menu) take a `Thread.print -l` of the JVM and open it in a thread viewer tab of the Run tool window: threads grouped by state with a filter and a toggle to hide JVM-internal threads, the selected thread's stack with navigable frames, deadlocks shown as a banner with the threads marked, and Refresh to take the next dump into the same tab.

- The run's JVM is the deepest HotSpot JVM of the run's process tree; Gradle runs, whose JVM forks under the daemon, are found by a stable -Dopenidea.run.token property instead, skipping Gradle's own JVMs.
- The attach listener is started only for a confirmed HotSpot JVM: the trigger file is private and created exclusively, a foreign socket is refused, and OpenJ9 is never sent SIGQUIT.
- A JVM a debugger holds suspended is dumped only when its listener is already open and the JDK is 17 or later; a debugged run's dump goes through its debug session, and Attach to Process links the session to the run.
- Remote runs, exited programs and JVMs with the attach mechanism disabled report why no dump was taken.
- The Run tool window comes forward when a dump opens, including one taken from the debugger.

Co-authored-by: ntbang0901 <[email protected]>
2026-11-25 02:01:59 +08:00
Floandflobo3 8bc7fd76be feat(i18n): add Russian (ru) UI language (#5626)
Russian joins the UI languages in Settings › Appearance & Behavior › System Settings › Language and Region and in the first-launch OS language detection, with the UI keys (Russian plural forms one / few / many / other) and the source-text catalog. Text not yet translated shows in English.

Co-authored-by: flobo3 <[email protected]>
2026-11-25 01:38:09 +08:00
l0ng-ai e8ac5d7bc2 test(i18n): allow the HotSwap section name to stay untranslated (#5665)
The Debugger settings page names its HotSwap section "HotSwap" in Chinese, as the existing HotSwap notification title is; the catalog test now lists it among the names kept in English, so it passes again on main.
2026-11-25 01:26:24 +08:00
l0ng-ai 12712253a8 fix(agents): let an open tool run grow instead of scrolling inside the chat (#5651)
Expanding a run such as "Ran 8 commands" showed its steps in a box capped at 16 rows with its own scrollbar. The run now lays out every step and scrolls with the conversation; a single tool call's output keeps its own 240px scroll area. The run's own follow-the-latest-call scrolling goes with its scroll area; the conversation's follow-to-end covers live runs.
2026-11-25 01:22:47 +08:00
RuyimgByCN b3e4bd63f1 feat(debug): reload classes after Recompile and builds, and sync exploded Tomcat deployments (#5601)
Settings › Build, Execution, Deployment › Debugger › HotSwap › Reload classes after compilation (Ask by default, Always, Never) decides what happens after a successful Build Project, Build Module or Recompile of a Java project while a debug session supports hot code replace: Ask offers "Reload '<file>.java' into the running debug session?", Always reloads at once, Never stays silent. The same setting applies to the language server's build-complete event, and overlapping prompts within two seconds are merged. After a single-file Recompile, classes that compiled cleanly are reloaded even if another file of the module still has errors.

Build completion is published as onBuildCompleted in contributions, and a running Tomcat with an exploded artifact deployment syncs its outputs after such a build (silently while it is debugged).

Co-authored-by: RuyimgByCN <[email protected]>
2026-11-25 01:20:59 +08:00
RuyimgByCN 748e5cee89 feat(build): add Build › Recompile for a single Java file (#5587)
Build › Recompile '<file>.java' (Shift+Cmd+F9 / Ctrl+Shift+F9, moved from Build Module, which keeps no default shortcut) compiles only the active Java file with javac and streams its output and diagnostics to the Build tool window. The menu, editor, tab and Project view entries name the file and are enabled only for local .java files.

- Maven modules resolve the classpath of the file's scope (compile for main sources, test for test sources) through dependency:build-classpath; the probe is now cancellable.
- Gradle projects get the source set's output, compile classpath, source folders and release from an init script.
- Projects without a build tool compile against their Project Structure roots, outputs and libraries.
- In a workspace the file's member project is used.
- javac gets -g, omits an empty -cp, and uses -source/-target on JDK 8; localized javac error and warning prefixes are parsed.

Co-authored-by: RuyimgByCN <[email protected]>
2026-11-25 00:59:59 +08:00
l0ng-ai d729ae8122 fix(search): keep multiline result names in one row (#5641)
Search Everywhere drew a result name containing line breaks over the rows below it, since names used white-space: pre in a fixed-height list. Names now stay on one line (line breaks collapse to spaces); code snippets keep white-space: pre for their indentation and tab stops.
2026-11-25 00:47:10 +08:00
l0ng-ai 503ed3b9bb fix(search): keep background scans off huge files and bound a search's line buffer (#5659)
The TODO index scans the whole project when it opens and rescans changed files, through the
Find in Files engine. That engine read a file line by line with no limit on a line's length, so a
database dump or bundle without line breaks was read whole into memory (a 2 GB single-line .sql
took the backend to 2.6 GB on every change) and searched in quadratic time, and every other large
file (logs, dumps) was read in full on each scan.

- Background scans (the TODO index, the files a usage search checks, the word candidates of a
  reference search) now leave out files over 2,500 KB, the code insight limit that IDEA's TODO and
  word indexes use (`idea.max.intellisense.filesize`).
- Every search caps its line buffer at 20 MB, IDEA's content-load limit: a longer line (or file,
  in a multi-line search) is not searched further instead of being read whole.

Fixes #5390
2026-11-25 00:45:06 +08:00
faysouandfaysou 1dd213964d test(boot): allow the workbench to mount within the startup deadline (#5636)
The slow-start boot test waited for the workbench's first render with Playwright's 10-second default, while OpenIDEA allows startup 60 seconds, so it failed on CI when Chromium was still loading the workbench. The test now runs with a 60-second timeout and uses it for that wait; it still advances the clock past the startup deadline and checks that the failure screen never appears.

Co-authored-by: faysou <[email protected]>
2026-11-25 00:12:31 +08:00
RuyimgByCN 5636fc0ecd fix(vcs): show declaration icons in the Commit changes tree (#5642)
The Commit tool window, the Commit dialog and the Local Changes tab resolved every file's icon from its name, so Java files showed the generic coffee cup instead of the class, interface, enum, test or Spring icons the Project tree and editor tabs show. Working-tree rows (and non-deleted amend preview rows) now take their icon from the shared file presentation cache; deleted files, added-then-deleted entries and ignored directories keep their file-type or folder icons.

Co-authored-by: RuyimgByCN <[email protected]>
2026-11-25 00:07:23 +08:00
Ilija Popivanov 5f64cce2a4 fix(editor): prevent paste when middle-click closes a tab (#5645)
On Linux, middle-clicking a tab could paste the primary selection into the editor that took focus: the shared tab strip closed the tab on mouse-down, so WebKitGTK delivered the release to the newly focused editor, which pasted. Tabs now close on the matching middle-button release, after cancelling its default action, and only when the button is released over the tab it was pressed on. This covers editor, tool window, database result and plugin tabs, which all use the shared strip.

Co-authored-by: ilijapopivanov <[email protected]>
2026-11-25 00:07:18 +08:00
Yann 4101e9d185 feat(deployment): upload files and folders directly into Remote Host (#5606)
Remote Host could only receive files through deployment mappings. Files and folders can now be dragged into it from the Project view or the desktop file manager, with the destination folder highlighted, and its context menu offers Upload Files… and Upload Folder…. Uploads go into the chosen folder without mappings or exclusion rules, keep each source's name, and ask before replacing files or merging folders.

Replacing a file uploads to a temporary name first and keeps the old file until the new one has its final name. Symbolic links and special files are skipped, transfers can be cancelled, and the affected listings are refreshed afterwards. Desktop drops are refused in Remote Development windows.

Co-authored-by: YannABC <[email protected]>
2026-11-24 23:59:44 +08:00
LU XIANGRUIandwildcatDownstairs a3ca576edd feat(editor): generate __init__ and properties in Python classes (#5354)
Generate (Cmd+N / Alt+Insert) in a Python class now also offers Constructor (__init__)… and Property…. The constructor takes the class fields chosen in a member chooser (fields with a value last, keeping it as the default) and is inserted before the first method; classes that get __init__ elsewhere (dataclasses, attrs, enums, named tuples, typed dicts, pydantic models) and classes that already define one get a hint instead. Property… offers class fields and attributes assigned on self, and writes a getter and setter over the private attribute, renaming a public class field to its private name so its value is kept.

Field values are read outside strings and comments, values spanning lines are skipped, and a one-line class body is split before inserting.

Closes #5329

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 23:51:43 +08:00
LU XIANGRUIandwildcatDownstairs 8b4e1e71fb feat(editor): Override Methods and Generate entries for Python classes (#5353)
Python classes had Implement Methods but no Override Methods or Generate. Override Methods (Ctrl+O) now opens a member chooser ("Select Methods to Override", grouped by declaring class) when the language server offers no code action, and Generate (Cmd+N / Alt+Insert) lists Override Methods and Implement Methods in Python editors.

The overridable methods follow the class's C3 linearization: for each name only the first definition in MRO order is offered, so the copied signature matches what super() calls; a @final, overload-only or name-mangled first definition hides the name. Class headers spanning several lines are read up to their closing colon, and inserting into a one-line class body (class C(Base): pass) splits it first. Overrides of one-line, static and non-ASCII methods are generated correctly, and missing imports for annotations are added.

Closes #5328

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 23:49:11 +08:00
LU XIANGRUIandwildcatDownstairs cdfc38231f feat(python): add the 'Method may be static' inspection (#5347)
PyCharm reports instance methods that never use self (PyMethodMayBeStatic); neither basedpyright nor Ruff's default rules do. The Python parser now reports a method's unused receiver (undecorated, not a dunder, a body that does more than pass, ..., a docstring or one raise, never naming the receiver, super or __class__), and a weak-warning inspection in the Python inheritance checks reports it, except for overrides, methods a subclass overrides, classes with an incompletely indexed hierarchy, and test code.

Alt+Enter offers Make method static. It searches the method's usages with the language server's references and applies only when every call goes through an instance (self.m(...), super().m(...)); otherwise it changes nothing, says how many usages may call it through a class and lists them in Find Usages. Suppressible with # noinspection PyMethodMayBeStatic.

Closes #5333

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 23:35:44 +08:00
Mr0Bread d18bd6144a refactor: one spawn_blocking helper instead of per-module copies (#5500)
ide-host carried eight private copies of the same blocking helper (spawn on the blocking pool, map a JoinError to IdeError::internal, flatten the closure's IdeResult), five private join_err mappers and about 50 inline spawn_blocking(..).await.map_err(join_err) sites. They now share ops::blocking and ops::blocking_value (for work that cannot fail) next to Host::blocking, which keeps spawning on the host's runtime. Error kind, message and runtime handle stay the same at every site; tests pin the value, error pass-through, panic mapping and runtime for each helper.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 23:29:14 +08:00
xiaohuiduanandxiaohuiduan 91cd0c058d feat(plugins): fetch plugin packages through the GitHub mirror prefix (#5492)
The Tools › Download sources GitHub mirror prefix carried language server, debugger and formatter archives but not plugin packages, which come from the same GitHub release host. Install, Update and Update All now try the mirror first and fall back to the official host; a mirror's failure, including bytes that fail the index digest or publisher signature, is that source's failure. The marketplace index itself is not mirrored, since it carries no signature of its own.

Packages are unpacked into a per-attempt staging folder and every exit except a verified one removes it, so nothing a mirror served stays where the install page reads. The app log records which source was tried, why a mirror failed and which one won. The failed-read test no longer depends on the OS's English wording.

Refs #3295

Co-authored-by: xiaohuiduan <[email protected]>
2026-11-24 23:23:07 +08:00
LU XIANGRUIandwildcatDownstairs 3ba9354159 feat(python): search PyPI package names in the Python Packages tool window (#5480)
The Python Packages tool window found a PyPI project only by its exact name, because PyPI has no search API. The first search now downloads PyPI's Simple index (PEP 691 JSON), keeps only the project names in the IDE cache directory, and refreshes them in the background once a day; a failed refresh keeps the old copy.

pypi_search matches names as PyPI normalises them: the exact name first, then names continuing with a separator, then other prefixes, then substrings. 50 results are listed with a note when there are more. The cache is written atomically, the scan honours cancellation, concurrent searches share one download, and an abandoned download stops after 10 seconds without a waiter. With another index configured, search results still wait for "Search PyPI for …".

Closes #5452

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 23:15:19 +08:00
Alexis 0eef66d793 feat(plugins): let web views embed declared and granted origins (#5618)
A plugin web view, custom editor or editor panel can list origins in a new frames field (API 1.16). Each origin must be https (or http to a loopback host), name one exact host with no path, and be covered by a net: capability of the manifest, so the install page shows it. Pages under that declaration's directory are served with a frame-src of the declared origins the user granted, and are revalidated instead of cached immutable, so declining or revoking a host takes effect on the next load. Without frames the CSP is unchanged, the plugin page cannot widen it, and the embedded page keeps the frame's sandbox without window.openidea.

Closes #5523

Co-authored-by: Rhombicdodecahedron <[email protected]>
2026-11-24 23:08:23 +08:00
Alexis ad81ff442e feat(plugins): let completion providers mark their list incomplete (#5643)
A plugin's completion was asked once when the popup opened; the editor then only filtered that list, so completions built from what is typed could not be offered. A new optional export, completion-list-provider, returns the items with an incomplete flag and is called instead of providers.completion for that plugin. While the user types on in the same word, only the plugins that marked their list incomplete are asked again; the language server's list and the other plugins' items from the first request are kept. A new word, a trigger character or an incomplete server list asks everyone, as before.

API 1.15 shipped with v0.1.51, so this starts API 1.16: wit/ and the SDK copy move to @1.16.0 with ENGINE_VERSION and API_VERSION, and the checked-in components are rebuilt.

Closes #4970

Co-authored-by: Rhombicdodecahedron <[email protected]>
2026-11-24 23:04:40 +08:00
LU XIANGRUIandwildcatDownstairs 01bd7fbe6e feat(editor): highlight FreeMarker templates (#5568)
FreeMarker templates (.ftl, .ftlh, .ftlx) opened as plain text. A stream mode, built like the ERB one, keeps HTML highlighting outside the template syntax and colours directives, user directives, comments and interpolations, with strings, numbers, operators, defaults and built-ins inside them. The square-bracket syntax is supported too, and the first directive picks the syntax as FreeMarker does. Toggle Block Comment uses <#-- -->, and the files get their own icon.

Closes #5558

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 22:51:01 +08:00
l0ng-ai 9e80289aa3 fix(remote): attach the latest of two connects to the same project (#5648)
Two connects to one remote location shared its progress key. When the backend superseded the older one, its cleanup cleared that key, so the newer connect, which the backend did publish, took itself for a cancelled one and never attached: the window showed nothing while the server stayed connected. Each connect now carries its own attempt number and only the latest one updates progress, attaches and cleans up.

Refs #5246
2026-11-24 22:41:12 +08:00
l0ng-ai fd959cc87d chore: remove agent skills and AGENTS.md from the repository 2026-11-24 22:36:56 +08:00
l0ng-ai 18eb515c83 fix(terminal): paste on plain Ctrl+V on Windows (#5646)
Plain Ctrl+V sent ^V to the shell on every platform, so Windows users had to use Ctrl+Shift+V or the context menu to paste. On Windows it now pastes in terminal tabs and in the embedded Run/Debug consoles, where xterm would otherwise turn the stroke into ^V itself. Linux and macOS keep ^V for the shell.

Fixes #5290
2026-11-24 22:32:54 +08:00
l0ng-ai 72b4d5c6de fix(agents): show an imported session's history in its task (#5644)
An imported Claude Code or Codex session starts as a task with the session id and no entries. Its first turn loaded the session, but every update replayed during session/load was dropped as history the task already had, and the timeline ignores user_message_chunk, so only messages sent after the import appeared. A task restored without entries now adopts the next load's replay as its history (user messages included), placed before any message that started the turn; later loads drop the replay as before. Importing also loads the session in the background, released when idle, so the history shows right away.
2026-11-24 22:23:45 +08:00
faysouandfaysou 6cca609d5c perf(terminal): reduce delays when opening and closing tabs (#5255)
Opening or closing a terminal tab stalled the workbench beside a large rendered document: xterm adds renderer styles per terminal, and mounting or removing them made WebKit restyle the whole document. Each session now renders into its own shadow root with its stylesheet; key routing reads the composed path so shortcuts still reach the terminal input. The first fit runs on the first available frame even when attach and resize notifications arrive together, and opening, splitting, restoring or closing a tab publishes the layout and session state in one change.

Co-authored-by: faysou <[email protected]>
2026-11-24 21:56:51 +08:00
faysouandfaysou fb56bd211b perf(ui): keep pane dividers responsive on large documents (#5506)
Grabbing a divider beside a large Markdown document changed the cursor on every element (an inherited cursor on the document, or the split group's own cursor rule), restyling the whole preview. A transparent fixed surface now holds the resize cursor during the drag, shared by split panes, docked tool windows and scrollbar drags. Visible and nearby Markdown blocks rewrap live; distant blocks keep their last width (clipped so the preview gains no horizontal overflow) until the drag ends, then reflow with the reading position preserved.

Co-authored-by: faysou <[email protected]>
2026-11-24 21:53:49 +08:00
audichuang ff1ef2b2f0 perf(vcs): virtualize the all-in-one diff's file blocks (#5336)
The all-in-one diff mounted an editor pair for every file, so large changes created hundreds of editors and long frames. Only blocks near the viewport are mounted now (overscan 4; the focused block and, with autosave off, blocks with unsaved staged edits stay mounted), each block keeps its last height, and a remounted block gets back its selections and expanded unchanged lines. Most of a block's mount cost was three themes created per editor (seamlessSelection, movedCodeHighlights, fontExtension), each adding rules and restyling the page; they are now created once per value. Also fixes a stale-response race in gitDiffEntries.

Co-authored-by: audichuang <[email protected]>
2026-11-24 21:50:20 +08:00
Mr0Bread 644a2d5784 perf(db): page results without re-reading the skipped rows and cap the size of a cell (#5260)
Every page re-ran the query and read and dropped all rows before it, and nothing capped a cell, so a page of wide values moved hundreds of MB to the UI. Paging forward now continues the statement's stream on its connection (SQLite, PostgreSQL, MySQL/MariaDB), bounded to one cursor per source and closed when its result tab closes, the source disconnects or a data-changing statement runs (also while a page is being read). Read-only queries cut cells to 8,192 UTF-16 units, marked truncated, and read the whole value when it is expanded, copied, edited or exported; a re-read is accepted only when the row count, uncut cells and each cut cell's length, prefix and hash still match.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 21:41:48 +08:00
Mr0Bread 40c616e46d perf(agents): send a running tool's output as the text it grew by (#5476)
A running tool's output was resent whole on every flush, so long outputs sent megabytes to the UI. The backend now sends a toolOutput event with only the appended text when the new output starts with everything already sent (checked by the sent length and a hash of the sent text); any replacement or other change goes out as a whole Entry. Agent and thought messages use the same check. PROTOCOL_VERSION is bumped to 4 so an older app refuses a newer server instead of showing stale output.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 21:30:53 +08:00
Mr0Bread c5f7b3ae98 perf(agents): save the task file off the state lock and coalesce saves (#5481)
Saving a task serialised the whole transcript while holding its state lock, so readers waited behind every save, and each turn rewrote the file for every status step. A save now copies the task under the lock and serialises and writes it outside it; high-frequency updates go through a coalesced save (one write of the latest state within 250 ms), while every stop the user or the next session depends on (including an answered permission request, before the agent is told) still writes before it returns.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 21:24:05 +08:00
l0ng-ai 5f628e8de3 fix(editor): keep the caret clear of sticky scroll headers when revealing it (#5639)
Moving the caret onto a line covered by the sticky header rows (vim N/n, search, go to line) scrolled it only to the viewport's top edge. The sticky scroll extension now contributes a top scroll margin equal to the header rows that would stick above the caret's line, capped by the sticky line limit.
2026-11-24 21:21:25 +08:00
l0ng-ai 82d13207a9 fix(editor): keep saving edits when touched ranges are out of date (#5638)
A range past the end of the document in ModifiedRanges made ChangeSet.mapPos throw inside onLocal, after the edit reached the backend but before the document was marked dirty, so autosave never wrote a reopened external file. Such ranges are now dropped with a warning. Fixes #5528.
2026-11-24 21:19:16 +08:00
l0ng-ai 74a009dcc3 fix(java): keep jdtls's temporary folder off paths with spaces (#5637)
jdtls ran with -Djava.io.tmpdir=<workspace>/.tmp under macOS's Application Support; Buildship writes its Gradle init script there and splits stored arguments at spaces, so every Gradle import failed. When the workspace path has whitespace, jdtls now gets its own folder in the system temporary folder (stable hash of the workspace), still emptied before each start. Fixes #5557.
2026-11-24 21:16:30 +08:00
faysouandfaysou 0c57c5bd0d fix(markdown): wrap source text to the split pane width (#5276)
In Markdown's Editor and Preview layout every wrapped source line reserved room for the inspection toolbar, leaving a wide blank column down the pane. Wrapped lines in the split source now reserve only the scrollbar lane (--cm-overview-width).

Co-authored-by: faysou <[email protected]>
2026-11-24 21:14:54 +08:00
faysouandfaysou b419c25912 fix(vcs): continue adding unversioned files across repositories (#5269)
Add to VCS staged every selected repository's files in one call, so a locked index in one repository left the others unstaged. It now stages each repository separately, names the repository in the notification when several are involved, and refreshes once at the end.

Co-authored-by: faysou <[email protected]>
2026-11-24 21:14:18 +08:00
LU XIANGRUIandwildcatDownstairs 798c88226c fix(java): say which build errors kept a module out of jdtls when Run or Debug starts (#5526)
When m2e or Buildship can't configure a module (e.g. a build plugin that doesn't resolve from the mirror), jdtls keeps it out of the Java model and puts the reason on the module's build file. Run and Debug waited 90 s and then said the module was not imported, or reported compile errors with none listed. The launch now reports the errors jdtls put on the build files of the module and its enclosing builds (pom.xml, build.gradle(.kts), settings.gradle(.kts)) without waiting, as ErrorData::JavaBuildProblems. Fixes #5525.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 21:14:11 +08:00
LU XIANGRUIandwildcatDownstairs bb850b25d6 fix(run): run selected Maven tests even when the build skips tests (#5521)
Running a JUnit test or class from the gutter only compiled when the build skipped tests through skipTests/maven.test.skip in POM properties or .mvn/maven.config: Maven printed 'Tests are skipped' and the Run window showed No tests. Every Maven test selection (gutter, JUnit configurations, package runs, Rerun Failed Tests) goes through withMavenTests, which now also passes -DskipTests=false -Dmaven.test.skip=false; when nothing ran, the console says why it may have been skipped. Fixes #5518.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 21:10:45 +08:00
LU XIANGRUIandwildcatDownstairs bee5e2ed1f fix(http-client): let the selected environment override file variables (#5532)
The ide-http resolver looked up @name file variables before the environment, so selecting an environment had no effect on a name the .http file also defines. As in the JetBrains HTTP Client (environment variables rank above in-place variables), the order with an environment selected is now private env, public env, $shared, then file variables; without one, file variables still come before $shared. Go to Declaration on {{name}} lists targets in the same order; the guide (en, zh) documents it. Fixes #5530.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 21:10:31 +08:00
l0ng-ai 4a14efc168 fix(diff): prevent layout jitter on load (#5600)
The side-by-side diff showed estimated gutter positions while CodeMirror measured the panes and the divider caught up. Collapsed unchanged rows get their final height immediately, and the panes and divider appear together after the first layout measurement.
2026-11-24 21:10:16 +08:00
Muuandmuutot 1a7bf6efdc feat(vcs): drag a whole changelist onto another to move its files (#5632)
Changelist header rows in the Commit tool window were drop targets but not drag sources. A changelist group row is now a drag source carrying all its files, so dropping one list on another moves every file, as in IntelliJ (the drag bean takes every change under the selected node). The drop path is unchanged.

Co-authored-by: muutot <[email protected]>
2026-11-24 21:07:25 +08:00
Mollo-i a68cae9311 fix(vcs): stop Git Log selection previewing in a tab when diffs open in a window (#5578)
With Open diff as editor tab off, selecting a file in a commit's changed files opened an editor preview tab and the following double-click opened a second diff window. The selection preview called openDiff() directly; it now follows the same setting as openVcsDiff().

Co-authored-by: Greenker <[email protected]>
2026-11-24 21:07:19 +08:00
jiejie1133 cf29d1342c fix(vcs): navigate across files in standalone diff windows (#5592)
The standalone diff window dropped the Commit panel's ordered file list, so Next/Previous Difference and Next/Previous File stopped at the first file. The window keeps the chain (2-way, 3-way and staged diffs), a reopen of an existing diff window applies the requested file, and a request arriving during a close prompt resumes if the close is cancelled. Fixes #5585.

Co-authored-by: jiejie1133 <[email protected]>
2026-11-24 21:07:11 +08:00
Muuandmuutot d1cc323c9e fix(vcs): build the Git submenu of every file menu from one shared generator (#5611)
The editor, editor tab and project view Git submenus were hand-written copies that had drifted: the tab menu's Commit File… opened an unscoped commit, lacked Add to .gitignore and the GitHub group, and used different wording. One gitMenuItems() generator in workbench/contributions now builds all three, with per-menu context flags; unregistered actions drop out at build time.

Co-authored-by: muutot <[email protected]>
2026-11-24 21:07:04 +08:00
faysouandfaysou 7164e17f1c test(editor): prepare the syntax tree before measuring line highlights (#5627)
On a busy runner CodeMirror could exhaust its foreground parse budget before reaching the test string, so the line-literal test failed before measuring. The test now prepares the tree through the target line first.

Co-authored-by: faysou <[email protected]>
2026-11-24 21:00:19 +08:00
faysouandfaysou de325c4d3c test(diff): wait for the follower pane to finish scrolling (#5622)
The split-diff navigation test read the other pane's scroll offset once, while a smooth scroll could still be moving it after the caret was centred. It now polls the offsets with the existing sub-2px tolerance.

Co-authored-by: faysou <[email protected]>
2026-11-24 21:00:12 +08:00
LU XIANGRUIandwildcatDownstairs af044d2435 fix(editor): highlight escape sequences in Java literals (#5552)
@lezer/java has no escape nodes and jdtls sends no string tokens, so escapes in Java strings, chars and text blocks were plain string colour. java/escapes.ts scans literals like IntelliJ's JavaStringLiteralLexer: valid escapes (including octal, multi-u unicode and the text-block line continuation) use Valid escape sequence, invalid ones the same colour with an error wave. Composed with the contextual keyword ranges in one syntaxRanges hook.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 20:57:09 +08:00
LU XIANGRUIandwildcatDownstairs 1d19a6dfec fix(java): underline reassigned local variables and parameters (#5556)
IntelliJ underlines reassigned locals and parameters; jdtls's token legend has no modifier for it. java/reassigned.ts finds them in the parse tree following ControlFlowUtil.isReassigned (parameters once assigned; locals assigned again, outside exclusive branches, in a loop they're declared outside of, or in switch case groups that fall through) and adds cm-sem-mutable to jdtls's variable/parameter tokens. SemanticToken gains from/doc/tree for hooks that look at the tree.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 20:56:17 +08:00
LU XIANGRUIandwildcatDownstairs c906064a16 fix(java): stop italicising static nested types (#5554)
jdtls marks nested classes, enums, records and interfaces static, and the generic mapping turned that into cm-sem-static for every token type, so their declarations and references were italic. IntelliJ italicises only static members; Java's tokenClasses now drops cm-sem-static for type tokens.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 20:55:31 +08:00
LU XIANGRUIandwildcatDownstairs 5beeacedf9 fix(editor): colour Java declarations before jdtls answers (#5551)
Until jdtls returned semantic tokens (startup, slow Maven/Gradle import, jdtls missing), Java field, enum constant and method/constructor declaration names were default text and changed colour later. java/declarations.ts colours them from the Lezer tree as fallbackRanges with the classes jdtls's tokens produce (static from modifiers; interface fields and enum constants static), so jdtls tokens replace them without a colour change. Composed with the contextual keyword syntax ranges from #5544.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 20:54:51 +08:00
LU XIANGRUIandwildcatDownstairs c8419934b2 fix(editor): colour Java contextual keywords as keywords (#5544)
record, sealed, permits, non-sealed, yield and when were plain text and var lost its keyword colour once jdtls answered: jdtls sends the first four as modifier tokens (dropped) and var as a type token. Java semantics now add syntax ranges for the contextual keywords from the Lezer tree (yield/when from the surrounding text) and map modifier/keyword tokens to the keyword class.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 20:53:53 +08:00
LU XIANGRUIandwildcatDownstairs 1f8eaec00a fix(editor): colour Java primitive types as keywords (#5543)
@lezer/java tags PrimitiveType as standard(typeName), so int/long/boolean/... used the built-in colour instead of the keyword colour IntelliJ uses (void already had it). JAVA_TAGS now tags PrimitiveType as keyword; this covers Java files, JSP scriptlets and java code blocks in Markdown.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 20:53:46 +08:00
Alexis 2f6bb7e995 fix(plugins): create missing output directories in keygen, pack and index (#5599)
openidea-plugin keygen, pack --out and index --out failed with 'No such file or directory' when the output file's folder didn't exist yet. They now create the parent directories first, like new and build already do, and the pack error names the path.

Co-authored-by: Rhombicdodecahedron <[email protected]>
2026-11-24 20:53:39 +08:00
Alexis f25df55a53 fix(theme): read .icls colours written with a leading # (#5625)
Both .icls readers (the theme converter and Settings > Color Scheme > Import) accepted only bare hex, so schemes like One Dark that write #rrggbb lost most colours. One iclsColor helper now follows IntelliJ's rules (bare, # or 0x prefixes); the settings import still leaves out RRGGBBAA values.

Co-authored-by: Rhombicdodecahedron <[email protected]>
2026-11-24 20:52:43 +08:00
Bin af60c1c5b9 fix(editor): parse JSX in JavaScript files (#5620)
JavaScript files were parsed without the JSX dialect, so JSX tags and attributes in .js/.mjs/.cjs files got parse errors and wrong colours. The JavaScript parser now enables JSX; TypeScript parsing is unchanged.

Co-authored-by: ffgenius <[email protected]>
2026-11-24 20:52:37 +08:00
faysouandfaysou 6fce934e95 fix(editor): refresh bracket matches after background parsing (#5630)
The bracket matcher only recomputed on document or selection changes, so a closing brace beyond the parsed prefix stayed marked unmatched after background parsing found its opening brace. A patch to @codemirror/language also refreshes the decorations when the syntax tree changes.

Co-authored-by: faysou <[email protected]>
2026-11-24 20:52:31 +08:00
l0ng-ai 24ef4143e6 fix(markdown): run a code block's current commands after it is edited (#5634)
Gutter markers compared only the entry name (block:<fence line>), so after editing a block CodeMirror kept the old run button and its click ran the old commands until the file was reopened. ScriptMarker.eq now compares the whole entry, covering the npm script and launch profile gutters that share it. Part of #5624.
2026-11-24 20:50:23 +08:00
l0ng-ai 30e72ffa57 chore: v0.1.51 2026-11-24 20:37:10 +08:00
Deng Liu dd164c0909 ci: route Linux CI and Language smoke jobs to self-hosted runners (#5539)
While SELFHOSTED_RUNNERS is true, trusted Linux jobs in ci.yml and language-smoke.yml run on the openidea-selfhosted runners and fall back to ubuntu-latest otherwise. The runner image moves to Ubuntu 24.04, E2E installs Chromium on the runner, and the smoke tests resolve fixtures from the runtime CARGO_MANIFEST_DIR.
2026-11-24 20:29:25 +08:00
Deng Liu 7419eb85c8 feat(services): show Docker volume disk usage across dashboards (#5545)
Add a docker_volume_sizes command (docker system df -v, Engine API fallback) and show each volume's disk usage in the Volume, Compose project and Container dashboards, refreshed every 30 seconds while the Services tool window is visible.
2026-11-24 19:58:10 +08:00
l0ng-ai 64a168a2d1 fix(agents): title a task from the prompt's text outside code fences (#5631)
A prompt that opened with a pasted fenced block was titled from the first line inside the block until the generated title arrived. A line outside the fences now wins; a prompt that is one fenced block is still titled from inside it.
2026-11-24 19:57:03 +08:00
l0ng-ai 77c531b9ca fix(python): keep inheritance inspections on classes an unsaved edit moved (#5629)
The inheritance inspections matched the open document's classes to the inheritance graph by exact position, and the graph is re-indexed only on save, so a line typed above a class hid the warnings of every class below until the file was saved. The document's classes now pair with the graph's in order while they read the same names, and by position otherwise; same-document methods and members come from the live document.
2026-11-24 19:55:22 +08:00
Deng Liu d411ace29b perf(vcs): cache unchanged ref queries (#5548)
Reuse the ref-decoration snapshot for log refs and cache branch lists, invalidated by ref storage, HEAD, repository config, shallow state and trust-mode changes.
2026-11-24 19:55:16 +08:00
l0ng-ai 4074d079b1 feat(agents): reorder the task menu and polish selection and images (#5621)
* feat(agents): reorder the task menu and polish selection and images

- Task menu: Pin, Rename, Mark as Unread/Read; Fork, Group; Archive (⇧⌘E
  in the task list), Archive All Below, Delete. Terminal and Open in New
  Window leave the menu. Hovering a task row shows Pin and Archive beside
  its age.
- Reply text: no stripe under the unselected start of a line when a
  selection runs on past it; inline code keeps its side insets inside the
  selection. A double or triple click no longer selects into the next
  message.
- Images: tool-read images show as same-height thumbnails; the remove
  button on attached images stays opaque on hover.

* fix(agents): keep Jump to Latest opaque on hover

* fix(agents): keep task row hover buttons from selecting or opening the task
2026-11-24 18:34:22 +08:00
l0ng-ai 2d0120f092 fix(editor): key navigation bar segments by position (#5616)
A path deeper than four folders collapses its middle into an ellipsis whose tooltip is the whole relative path, the same as the last folder's, so React warned about two children with the same key. Segments are now keyed by their position as well.
2026-11-24 17:53:35 +08:00
faysou df470f93c6 test(e2e): keep project focus checks from switching editor tabs (#5604)
With preview tabs enabled, selecting a file in the Project view also opens it, so the External Tools test disables preview tabs to keep the Project selection and the active editor on different files. The task-input shortcut test focuses a directory so the task editor stays visible.
2026-11-24 17:51:02 +08:00
faysou 764b6717e0 fix(python): skip Hatch discovery without a desktop bridge (#5608)
Opening Add Python Interpreter in a plain browser started a Hatch discovery request whose cancellation called the desktop command without a bridge, an unhandled rejection. Browser mode now returns an empty result with a no-op cancel.
2026-11-24 17:50:48 +08:00
l0ng-ai 7aa6adb0ef Revert "fix(agents): extend the chat scrollbar to the composer (#5583)"
This reverts commit c0f7ec93d3.
2026-11-24 17:22:50 +08:00
l0ng-ai 7ebdf04e2f ci: split E2E into four shards (#5591)
Two E2E shards of ~512 tests each hit the 30-minute job timeout; four shards keep each within it.
2026-11-24 16:13:51 +08:00
l0ng-ai c0f7ec93d3 fix(agents): extend the chat scrollbar to the composer (#5583) 2026-11-24 15:38:10 +08:00
l0ng-ai cc9089db11 test: make four tests pass on Windows (#5580)
Windows CI on main failed four tests the earlier clippy error had hidden:
- pipenv naming hashed a Unix path, which Windows joins with a backslash;
  the Windows expectation now uses a Windows path.
- the VIRTUAL_ENV assertion joined "member/.override" as one component.
- the diagnostics coalescing tests slept 30 ms for a 16 ms flush, too short
  for Windows timers; they wait for the flush with a deadline.
- the patch preview test read automatic mappings while new folders could
  still be re-indexing (automatic mappings pause then); it waits for indexing.
2026-11-24 15:36:45 +08:00
l0ng-ai 62095b904e fix(agents): keep selection highlights within reply text (#5574) 2026-11-24 15:36:40 +08:00
l0ng-ai 96c5e94975 fix(agents): open new tasks with less background work (#5573) 2026-11-24 15:36:35 +08:00
LU XIANGRUIandLU XIANGRUI 97e9657fd3 feat(editor): highlight JPQL, SQL and SpEL in Spring annotation strings (#5565)
- Java parses the string values of Spring Data JPA @Query (JPQL, or SQL with
  nativeQuery = true), @Value / @ConditionalOnExpression (SpEL #{...} and
  property placeholders ${...}), and the SpEL attributes of @PreAuthorize,
  @PostAuthorize, @PreFilter, @PostFilter, @Cacheable, @CachePut, @CacheEvict
- annotations are matched by their imported or qualified class, so other
  annotations named Query stay plain strings
- escape sequences stay outside the embedded text and keep the string colours

Co-authored-by: LU XIANGRUI <[email protected]>
2026-11-24 14:57:35 +08:00
LU XIANGRUIandLU XIANGRUI 1205ffecd2 fix(editor): leave Java statement labels uncoloured, as IntelliJ does (#5564)
Co-authored-by: LU XIANGRUI <[email protected]>
2026-11-24 14:54:09 +08:00
Deng Liu 51766249f9 fix(services): keep Docker Compose dashboard actions pinned on scroll (#5534) 2026-11-24 14:47:11 +08:00
l0ng-ai ff55bcdf9a fix(vcs): keep Git Log file selection in place (#5563) 2026-11-24 13:52:30 +08:00
l0ng-ai fd6d1d5d0e ci(smoke): build the smoke binaries once for every language (#5395)
Each language job compiled the language_smoke / project_smoke tests and
openidea-server itself, about 4-5 minutes of the same work nine times. A
build job now compiles them once and hands them on as an artifact; the
language jobs only install their tools and run the binaries.
2026-11-24 13:25:13 +08:00
l0ng-ai 9ad5bad82e fix(vcs): refresh status after git commands run outside the IDE in subfolder projects, worktrees and submodules (#5555)
The project file watcher only reports Git metadata in the .git folders it
sees: the project root's and nested repositories'. When the project is a
subfolder of its repository, a linked worktree, a mapped repository
elsewhere, or a submodule (.git/modules/<name>), a commit, checkout or
reset in a terminal wrote nothing the watcher reported, so file statuses
stayed stale until something else triggered a refresh.

Watch HEAD, index, packed-refs and refs/** of those git directories, follow
repository changes, and emit VcsChanged for them (ignoring the IDE's own
index writes).
2026-11-24 13:25:08 +08:00
l0ng-ai fec50f3925 fix(agents): show a sent message before recording the turn checkout (#5536)
The user's message was only added to the conversation after the pre-turn checkout was recorded, which can take seconds in a large repository, so pressing Enter appeared to do nothing and the view did not scroll to the new message.
2026-11-24 12:15:56 +08:00
l0ng-ai 8b3d9adcfe fix(agents): keep the new-task composer height when typing the first character (#5535)
The home composer's taller minimum height overrode the composer rule by selector, so stylesheet load order could reset it to the single-line height once CodeMirror re-rendered. The home view now sets a --composer-min-height variable that the composer rule reads.
2026-11-24 12:15:49 +08:00
l0ng-ai 457174a442 feat(workbench): keep rarely used tool windows off the stripe by default (#5531)
Bookmarks and TODO are listed under the stripe's "…" until first opened. The Database
window is on the stripe by default only while the project has data sources. Of the
Flutter DevTools windows only Flutter Inspector has a stripe button; Deep Links,
DevTools and DevTools Extensions wait under "…". A user's own stripe choice still wins.
2026-11-24 12:15:23 +08:00
Deng Liuanddengliu de868f1677 feat(remote): persist remote backend, terminals, runs, agents, and workbench state across window close (#4385)
Closing a remote window (SSH, WSL, Dev Containers) used to end openidea-server --stdio and tear down terminals, runs (running their stop commands), indexing and agent turns. openidea-server --attach now connects through a detached per-project daemon (private 0700 run dir, owner check, flock) that keeps them alive across disconnects; reopening reattaches terminals with bounded scrollback and OSC state, runs and agent turns, and restores remote editor tabs, tool windows and plugin views. The close dialog offers Keep Backend Running / Stop Backend; Stop Remote Backend shuts the daemon down on demand. A disconnected backend with no live work exits after an idle timeout (3 hours by default; presets, custom or Never in Settings › Tools › Remote Development, host override wins). The socket is keyed by project, so a new build replaces an idle backend of another build and reports a busy one; a window taken over by another shows that instead of a dropped connection. Clean documents are released on disconnect while dirty buffers keep the backend alive.

Also: a plugin-owned PTY keeps its exit hook across reattach (reattach only rebinds the forwarding sink), and a recent project clicked again while it is still opening joins that attempt instead of connecting twice (a double click made the second attach take over and fail the first).

Co-authored-by: dengliu <[email protected]>
2026-11-24 11:42:00 +08:00
l0ng-ai e27fc0d867 refactor(run): remove the npm tool window
Detected npm scripts are already in the run configuration list and runnable from the
package.json gutter. Remove the separate npm tool window, its package scan and e2e spec.
The editor context menu Run / Debug on a package.json script line stays.
2026-11-24 10:59:41 +08:00
l0ng-ai c50c2ea629 feat(editor): support Helm and Go templates (#5522)
Helm chart manifests and .tpl helpers keep YAML highlighting with Go template actions and are served by helm-ls (installable from Settings › Language Servers, pinned 0.5.4). Standalone .gotmpl / .tmpl / .go.tmpl files are a Go Template language: template actions highlighted, the Go icon, and gopls. Adds a small chart fixture.
2026-11-24 10:50:03 +08:00
l0ng-ai 3e9e86edf1 fix(services): keep a disconnected Docker connection disconnected across restarts (#5519)
Disconnecting a Docker connection in Services was remembered only in memory, so after a restart opening Services dialled every saved connection again (including SSH ones the user had disconnected). The Disconnect intent is now saved per connection; panel startup and the 10 s poll skip it until Connect clears the flag. Older settings keep connecting automatically.
2026-11-24 10:36:20 +08:00
l0ng-ai cb24be4c19 docs(readme): switch the WeChat group QR code to group 4 2026-11-24 10:32:53 +08:00
l0ng-ai 52e3276f93 test(ide-host): compile the code action stub only where its test runs (#5516)
The code action stub carries the cfg(unix) of its only test, fixing Windows clippy on main.
2026-11-24 10:24:30 +08:00
l0ng-ai fcf5406de0 fix(keymap): list Smart Type completion and Rearrange Code in every preset (#5515)
Smart Type completion is in the VS Code preset and Rearrange Code is listed (no default shortcut) in the IntelliJ and VS Code presets, fixing the keymap and Vim :action tests on main.
2026-11-24 10:22:47 +08:00
Deng Liuanddengliu aee72d994e chore(dev): replace dogfood:build/install with dogfood:local and dogfood:all (#5271)
dogfood:local builds and installs the local dogfood app (--build-only skips installation); dogfood:all <remote_name> runs it alongside dogfood:remote in parallel with [local]/[remote] prefixed output, validates the SSH configuration before the local build starts, stops the sibling process tree on failure, and runs the remote restart prompt once after both finish. AGENTS.md, mise tasks and the setup docs use the new names.

Co-authored-by: dengliu <[email protected]>
2026-11-24 08:57:51 +08:00
LU XIANGRUIandwildcatDownstairs 397522e099 feat(editor): show language server colors in the gutter (#5229)
Tailwind color classes (`bg-red-500`, `text-brand-700`, `@apply bg-brand-500` in CSS) and the colors a CSS server knows beyond the built-in literal detector (`hwb()`…) now show swatches in the editor gutter. This was the remaining acceptance criterion of #5154. The editor never asked language servers for `textDocument/documentColor`; it only drew swatches for literals it found itself and for colors that plugins reported.
- Backend (`ide-lsp`): the client advertises `colorProvider`. `document_colors` asks every server that has it and tags each color with its server, then drops the answer if the document version changed in the meantime. `color_presentations` asks that server for `textDocument/colorPresentation`. A presentation without its own `textEdit` replaces the color's range with its label. New commands `lsp_document_colors` / `lsp_color_presentations`; bindings regenerated.
- Frontend (`color-preview`): `lspColors.ts` sits next to the plugin source and shares its swatch and picker flow, now in `providerSwatch.ts`. A server color gets no swatch when the built-in detector already shows a literal at the same range, and two servers reporting the same range (CSS + Tailwind) get one swatch. The gutter follows Settings › Editor › General › Gutter Icons › Color preview, and while that is off the editor sends no requests. Picking a color applies the server's single presentation, or offers a menu when there are several.
- Tailwind only presents arbitrary values (`border-[#16a34a]` → `border-[#2563eb]` / `[rgb(…)]` / `[hsl(…)]`). For palette classes like `bg-red-500` it returns none, as in VS Code. In that case a hint says the color can't be changed with the picker (new string, en + zh).

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 08:45:02 +08:00
LU XIANGRUIandwildcatDownstairs f7e1dbe5eb feat(python): suppress the IDE's Python inspections with # noinspection comments (#5341)
The IDE's own Python inspections (Circular inheritance, Inconsistent '@override', Abstract method not implemented, Redundant override) could only be turned off for the whole profile. They now honour PyCharm's `# noinspection <Id>` comment (several ids comma-separated, or `ALL`): directly above a statement it covers that statement, above a `def` / `class` (or its decorators) the whole definition, and among the file's leading comments followed by a blank line the whole file. The parser reports these regions with the Python facts the inspections already read. Alt+Enter on such a problem offers Suppress for statement / function / class, which writes the comment at the definition's indentation or adds the id to a `# noinspection` comment already there.
While testing, the ⌥↵ options row for these problems read "Python builtin:python-abstract-method", and Disable inspection wrote an override for an id that doesn't exist: the checks publish under one producer with their inspection id as the code, and that id was not looked up. It now is.
Ruff and basedpyright problems need nothing new: both servers already offer their own suppress fixes (`# noqa: CODE`, `# pyright: ignore[rule]`), shown in the same menu.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 08:38:43 +08:00
LU XIANGRUIandwildcatDownstairs 52096fc904 feat(python): add Smart Type completion (#5351)
Ctrl+Shift+Space now runs **Smart Type** completion in Python files (Code › Code Completion › Smart Type, `code.smartTypeCompletion`): the lookup keeps the items whose type fits the caret's expected type, with that type in the right-hand column. basedpyright's completion items carry no type, so the candidates are resolved and their type is read from the documentation's code block.
The expected type comes from the active parameter's annotation (signature help), an annotated assignment `x: T = |`, or the enclosing function's `-> T` for `return |` (also in `async def`). A member access being typed (`x: T = task.|`, `return self.|`) is skipped over to find it. Keywords and comparisons are not taken for an assignment (`else: x = |`, `ok: bool = a <= |`).
An item fits when each member of its type's union fits the expected union:
- types are compared in a canonical form: module prefixes dropped, `typing` aliases lowered, `Optional` / `Union` and spacing read alike (`List[Optional[int]]` is `list[int | None]`);
- numbers are promoted as PEP 484 says: `float` accepts `int`, `complex` accepts both, and `bool` counts as an `int`;
- a class fits as any of its bases, from the project's classes (`Dog` for `Animal`);

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 08:38:28 +08:00
LU XIANGRUIandwildcatDownstairs 296c3d1477 feat(python): navigate between implementations and their .pyi stubs (#5339)
A Python module's type stub (`.pyi`) was invisible from the implementation, and jumping between a declaration and its stub meant finding the other file by hand. Functions, classes and methods that both files declare now get a gutter icon: in the `.py` it opens the stub declaration, in the `.pyi` the implementation. A new `nav_python_stubs` command finds the counterpart and matches declarations by qualified name on the tree-sitter outline of both texts, unsaved edits included. The counterpart is looked for:
- beside the file (`m.py` ↔ `m.pyi`);
- in a PEP 561 stub package beside the package (`pkg/m.py` ↔ `pkg-stubs/m.pyi`), or for a single module (`six.py` ↔ `six-stubs/__init__.pyi`);
- in the stub folder basedpyright reads (`stubPath` from `pyrightconfig.json` or `[tool.basedpyright]` / `[tool.pyright]` in `pyproject.toml`, else `typings/`), by module name. Modules are searched in the project's Python roots and its virtualenv's `site-packages`, so a `typings/requests/api.pyi` pairs with the installed `requests/api.py` both ways.
Navigate › **Stub / Implementation** (Find Action) does the same from the caret, and Related Symbol (⌃⌘↑) lists the counterpart. Markers refresh when a file where the counterpart may be changes, and a counterpart over the large-file limit still opens but gets no markers.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 08:32:17 +08:00
LU XIANGRUIandwildcatDownstairs c72a162b5c feat(python): create a function, class or method from an unresolved reference (#5355)
On an unresolved name in Python, Alt+Enter only offered basedpyright's "Add `# pyright: ignore[...]`" (and an import when one matches). It now also offers PyCharm's **Create function 'foo'** and **Create class 'Foo'** on an undefined name, and **Create method 'bar' in 'Greeter'** on a missing method called on `self`/`cls`. Parameters come from the call site: a keyword keeps its keyword, a plain-name argument keeps its name, others become `param1`, `param2`…, with `*args` / `**kwargs` for starred arguments; positional and starred names are renamed so they never repeat the receiver or a keyword. The function or class goes above the top-level statement that uses it; the method goes at the end of the enclosing class, a `@classmethod` when the calling method is one (none is offered from a `@staticmethod`). The caret lands on the `pass` body.
The server says what is unresolved (`reportUndefinedVariable` / `reportAttributeAccessIssue`, and the equivalent codes of Ruff, ty and pyrefly); the parse tree says where and how it is used. The fixes are local quick fixes, so they also show in the problem hover's quick-fix list.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 08:23:02 +08:00
LU XIANGRUIandwildcatDownstairs 3989b2715c feat(editor): write Python docstring stubs in the selected format (#5352)
Typing `"""` and Enter under a Python `def` always inserted reStructuredText `:param` / `:return:` fields: **Settings › Python › Docstrings** only changed highlighting. The stub now follows that setting (reStructuredText, Epytext, Google, NumPy, or Plain for a summary line only), lists the exceptions the function body raises (`raise X` / `raise X(...)`, nested functions skipped), and also closes a docstring under a `class`. The setting's hint and the Python docs page say so.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 08:20:48 +08:00
Akbar Husain aa1b6c1ce0 perf(lint): fix React performance lint violations (#5503)
Clears the React-specific violations reported by oxlint's `perf` category: 123 array-index keys, 28 constructed context values and 6 object/array default props. Keys now use a stable data id where one exists, and the index with a short documented suppression where position is the real identity (editable rows, streams, repeated data). Context values are memoized or hoisted, and default literals are module-level constants. Enabling the `perf` category itself is handled separately; this PR only fixes the violations.

Co-authored-by: akbar1214 <[email protected]>
2026-11-24 08:06:54 +08:00
Mr0Bread 2afd636314 perf(agents): drop a hidden session tab's painted history (#5494)
A kept-alive session tab (up to 5, `KEPT_TABS`) painted its whole conversation and never gave any of it back: `Stream` opens at the last `ENTRY_BATCH` (40) entries, then the "following the end" effect (`Stream.tsx`, the `useEffect` on `[start]`) keeps adding batches until the full history is DOM, hidden or not. Five long tabs therefore held every turn as DOM nodes (WebKit keeps layout/style/render-tree memory for all of it).
Now a tab that was left at the end of its conversation and stays hidden for 30 s drops back to its recent tail, and a hidden tab no longer paints more batches. When it is shown again it is at the end as before and re-paints the earlier entries in the background exactly as when it first opened.
Independent of #5462 (hidden tabs stop rendering), #5467 (per-chunk re-render) and the Rust PRs.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 08:06:38 +08:00
l0ng-ai de11bc02f1 fix(vcs): keep the log mounted while another Git tab is shown (#5454)
Switching between Console / Worktrees and Log in the Git tool window stuttered on every click of Log: the log view was unmounted whenever another tab was shown and rebuilt on return. The log now stays mounted (inert and unfocusable) while hidden; switching back takes ~33 ms instead of 70–100 ms.
2026-11-24 07:30:01 +08:00
faysouandfaysou 2f8d5f5118 fix(ui): keep the arrow cursor during scrollbar drags (#5504)
Dragging a scrollbar thumb across a split divider could show the resize cursor while the page was still scrolling. In a side-by-side Markdown editor, pressing the outside edge of the source thumb could start resizing the pane.
Keep the arrow until the scrollbar drag ends and keep the source thumb clear of the Markdown divider. A transparent surface catches the pointer during the drag, so grabbing the thumb does not change inherited styles across the document.

Co-authored-by: faysou <[email protected]>
2026-11-24 07:29:51 +08:00
Delaruno20andDelaruno20 4b4c25d7b1 fix(notebook): cell toolbar shows the file icon for Insert and Delete (#5505)
In the notebook editor, "Insert Code Cell Below" and "Delete Cell" (and the "Add Code Cell" /
"Add Markdown Cell" buttons) show the generic file icon instead of a plus and a trash can. They
ask for the icons `add` and `delete`, which are not in `src/ui/icons.tsx`; `IconButton` accepts
any string, so the unknown names fall back to `ICONS.file`. They now use `plus` and `trash`.

Co-authored-by: Delaruno20 <[email protected]>
2026-11-24 07:29:37 +08:00
Mr0Bread ca0f71bc39 refactor: share one CLI process runner between ide-docker, ide-github and ide-android (#5502)
`ide-docker`, `ide-github` and `ide-android` each carried a private copy of the same CLI runner (bounded `run`, cancellable line `stream`, SIGTERM-then-kill, output decoding): 570 lines, ~90% identical. The copies now live once in `ide_core::cli_process`; each crate keeps a ~35-line `process.rs` that binds its tool name and decoding and keeps its old call signatures, so no caller changes. `ide-core` already depended on by all three; no `Cargo.toml` / lockfile change. No behaviour change.
The three genuine differences are explicit parameters (3 knobs): `Decoding` (`ToolOutput` / `Utf8Lossy`), `Input` (`Inline` / `Threaded` stdin) and `CarriageReturn` (`EndsLine` / `Dropped`). The tool name only feeds the error texts. Android's batching loop stays in `ide-android`; it drives the shared `Lines` reader.
### Difference table (old code, before the change)
| Aspect | docker | github | android | Class | Now |
|---|---|---|---|---|---|
| spawn setup (`stdin` null, `stdout`/`stderr` piped, `own_group`, `ide_core::process::prepare`) | same | same | same | identical | shared `configure` |

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 07:02:30 +08:00
Mr0Bread b60b743843 refactor(ide-host): shared test HostConfig constructors replace ~100 copied literals (#5501)
`HostConfig` (9 fields) was written out as a full struct literal in about 100 tests of `ide-host`, almost all of them the same boilerplate, so a new field meant editing ~100 places. This adds one base constructor for tests and migrates every literal that is a plain variant of it. Tests that differ keep struct-update overrides (`HostConfig { sink_for: .., ..HostConfig::for_test(&base) }`). No builder.
- Unit tests (`src/`): `#[cfg(test)] pub(crate) fn HostConfig::for_test(base: &Path)` in `lib.rs`.
- Integration tests (`tests/`): `tests/common/mod.rs` with `host_config(base: &Path)`, pulled in with `mod common;`. It builds the same value as `for_test`.
Both build: `config`, `data`, and `data` again as the machine-local dir (the layout most tests used), `LanguageRegistry::load(None)`, empty syntax, a sink that drops events, identity owner, `Handle::current()`, `project_environment: false`.
Why not one constructor for both: integration tests compile against the crate without `cfg(test)`, so a shared one needs a new `testing` cargo feature plus a dev-dependency on the crate itself (nothing in `ide-host` does that today). Two small definitions need no feature, no `Cargo.toml` change and no public item.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 07:02:21 +08:00
Mr0Bread e6461f4935 refactor: one Utf8Decoder shared by ide-run and ide-terminal (#5499)
`Utf8Decoder` (incremental UTF-8 decoding for byte streams that split code points across reads) existed twice: in `ide-run` ("kept local so the crates stay independent") and in `ide-terminal`. The code was identical. It now lives once in `ide_core::utf8`; both crates already depended on `ide-core`, so there is no new dependency edge and no `Cargo.toml` change. `OutputDecoder`, `MixedDecoder` and `NativeDecoder` (encoding_rs based, ide-run only) stay in `ide-run` and import the shared type.
No behaviour change. The decoder was moved, not rewritten; ide-terminal's file was `git mv`'d to `ide-core/src/utf8.rs`.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 07:02:12 +08:00
Mr0Bread 0ef62c4999 refactor: use ide_core::jsonc in ide-agent instead of a private copy (#5498)
`ide-agent` carried a private JSONC stripper (`strip_jsonc` + `remove_trailing_commas` in `mcp.rs`) next to `ide_core::jsonc::strip`, which five other crates already use. Both callers in `ide-agent` (`parse_jsonc_value` in `mcp.rs`, the Copilot `config.json` read in `skills.rs`) now call `ide_core::jsonc::strip`, and the private copy is deleted (-94 lines).
To make the swap lossless I changed two small things in `ide_core::jsonc::strip` (these are the only behaviour changes, listed so they are not missed):
1. **Block comments keep their line breaks** (the private copy did; core dropped them). Without this, a JSON parse error in a pasted MCP config would report the wrong line after a multi-line `/* … */`, and `1/*\n*/2` was wrongly accepted as `12`. A comment is now whitespace, as in real JSONC.
2. **A trailing comma is dropped only when separated from `}`/`]` by ASCII whitespace** (core used Unicode `is_whitespace`). The private copy used ASCII whitespace. Inputs with e.g. NBSP before `]` were invalid either way; only the error text differed.
One more effect, only in `skills.rs`: core strips a leading UTF-8 BOM, the private copy did not. `~/.copilot/config.json` with a BOM previously failed to parse and its plugins were silently skipped; now it parses. (`mcp.rs` already stripped the BOM before calling.)

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 07:02:04 +08:00
Mr0Bread 7d39ab693c refactor: remove pass-through wrappers and redundant re-exports (#5497)
Several items only forwarded to another function or re-exported it, so each had an extra name to maintain and hid where the real code lives. This removes them and points every caller at the real definition. No behaviour change.
Removed (each was a pure forward, same arguments, no extra logic):
- `ide_run::which` (a bare `pub use ide_core::process::{executable_names, find_executable, find_executable_in}`): module deleted, 22 callers (ide-run, ide-profiler, ide-sdk, ide-run tests) now call `ide_core::process::…`.
- `ide_run::detect::package_manager(root, _pkg)` (the `_pkg` parameter was unused), `detect::subdirs` (→ `project_roots::children`) and `detect::build_dirs` (→ `project_roots::discover`).
- `ide_build::compile::package_manager` (→ `project_roots::package_manager`).
- `ide_lsp::is_virtual_uri` re-export (`uri.rs` and `lib.rs`). No caller used `ide_lsp::is_virtual_uri`; the one internal use now calls `ide_core::is_virtual_uri`, like every other crate.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 07:01:55 +08:00
Mr0Bread 71b4e1c367 refactor: keep test-only helpers out of production APIs (#5495)
Some `pub` items existed only to serve tests: they widened public APIs, and four were thin wrappers over the production entry point, so tests ran a different path than production. Each item below was re-checked on current `origin/main` with `lsp` references and `rg -w` across crates, `tests/`, benches, `src-tauri` and docs, then handled by the rule in the last column.
| Item | Users found | Decision |
|---|---|---|
| `LspManager::references` | only `ide-lsp/tests/{mock_server,real_servers}.rs` (38 calls); production uses `references_streaming` | wrapper deleted; tests call `references_streaming(.., true, cancel, None)` (the wrapper's exact body); doc merged |
| `McpServer::start` | in-crate test, `ide-mcp/tests/server.rs`, `ide-host/tests/mcp.rs`; production uses `start_with` | wrapper deleted; callers pass `ServerOptions::default()` (the wrapper's exact body) |
| `ide_mcp::endpoint_url` | in-crate test, `ide-mcp/tests/server.rs` | deleted; callers use `endpoint_url_at(Ipv4Addr::LOCALHOST.into(), ..)` |

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 07:01:46 +08:00
LU XIANGRUIandwildcatDownstairs 90bba44ba7 feat(python): add the Python Packages tool window (#5448)
Packages of the project's interpreter could only be managed in the Settings window, by typing an exact requirement. This adds a **Python Packages** tool window: the installed list with upgrade markers, a PyPI project looked up by its exact name, a version picker, and install / upgrade / uninstall through the same pip / uv path as Settings › Python › Dependencies.
The lookup is a new `pypi_package` command (`https://pypi.org/pypi/<name>/json`, HTTPS only, cancellable). The package list hook moved to `src/platform/pythonPackages.ts` so the settings page and the tool window share it.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 06:40:00 +08:00
LU XIANGRUIandwildcatDownstairs 68c4fe60ec feat(python): apply Code Style › Python to Ruff and Black (#5378)
Editor › Code Style › Python has indent, tab character and hard wrap, but Ruff and Black ignored them: without a configuration of their own they always formatted with 4 spaces at 88 columns, whatever the editor used. Now, when no Ruff configuration applies to the file (`ruff.toml`, `.ruff.toml` or `pyproject.toml` with `[tool.ruff]` in its folder or above, the user's Ruff configuration, or the configured Ruff configuration directory), Ruff gets the indentation and line length the editor uses, as `--config line-length / indent-width / format.indent-style`: the file's `.editorconfig` (`indent_size`, `indent_style`, `max_line_length`), then the values set on the page. Black, without `[tool.black]` in its project (found as Black finds it) and without a user configuration where Black would read one, gets the line length as `--line-length` (it has no indentation settings). Values set in neither place are not passed: the global hard wrap (120) is not Ruff's or Black's default (88), so existing projects keep formatting as before. The page says when these values apply.

Also adds Black as a selectable Python formatter (#5340's commits, which this branch was stacked on).

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 06:30:41 +08:00
wangfeiandhapput 558a98e74e fix(workbench): keep title bar and tabs visible while a project opens (#5484)
Opening a project as a new tab (or a new window) kept the full-screen boot
splash over the entire window until the project finished opening, so the title
bar and the window-group tab strip were hidden behind a bare logo + progress
screen. The splash was held for the whole `launch` promise, the opening view
rendered a `bare` title bar without tabs, and a loading tab fell back to the
window title ("OpenIDEA").

Co-authored-by: happut <[email protected]>
2026-11-24 06:06:31 +08:00
TWINKLE 8d701da584 feat(agents): copy an agent reference for files and selected code (#5469)
Co-authored-by: H-TWINKLE <[email protected]>
2026-11-24 06:01:19 +08:00
Muuandmuutot bd0f28cd3b feat(spelling): save typos to custom dictionaries with a default dictionary setting (#5466)
Co-authored-by: muutot <[email protected]>
2026-11-24 06:01:01 +08:00
LU XIANGRUIandwildcatDownstairs ea7ec41064 feat(python): optimize imports with Ruff's CLI without a Ruff configuration (#5373)
Optimize Imports in Python came only from the Ruff language server, which starts only below a Ruff configuration, so in other projects it said "Optimize imports is not available" and the Optimize imports options on save, before commit and in Code Cleanup did nothing. When no server offers `source.organizeImports` for a Python file, the IDE now runs `ruff check --extend-select I --fixable I,F401 --fix --exit-zero` on the unsaved text and offers the result as the organize-imports action, for the editor and for the MCP tools' organize-imports step alike. Imports are sorted; unused ones are removed where the project's Ruff rules check F401 (Ruff's defaults do; an `ignore` or `select` without it keeps them). It reads the project's Ruff settings or the configured Ruff configuration directory. Ruff comes from the file's project environment first (`.venv/bin/ruff`), as the Ruff language server does, then the IDE's copy and `PATH`. Without Ruff the action is disabled with "Install Ruff to optimize imports in Python files". Projects with a Ruff configuration keep using the Ruff server, which only sorts.
The first commit (Ruff from the project environment for Reformat Code too) answers a review comment on #5372, which was merged before it landed there.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 05:53:51 +08:00
LU XIANGRUIandwildcatDownstairs b1db1c6c3d feat(new-project): .NET solution name and SDK version (#5385)
The .NET entry of File › New Project had no way to create a solution or pick the SDK. It now has:
- **Create solution** (on by default) and **Solution name** (defaults to the project name). As in Visual Studio, the folder gets `<Solution>.sln`/`.slnx` at the top and the project in its own subfolder (`dotnet new sln`, then `dotnet sln add`). Unchecked, the layout is the same as before: the project at the top, no solution.
- **SDK version** lists the SDKs from `dotnet --list-sdks`, 8.0 and later, newest first. Older ones are left out because Blazor Web App and the templates' current options need SDK 8. The chosen one is pinned with `dotnet new globaljson --sdk-version … --roll-forward latestFeature`, which runs before `dotnet new <template>`. Without a roll-forward policy, `global.json` defaults to `latestPatch`: the project would then fail to build on a machine with only another feature band of the same .NET version, such as a teammate's or this one after an SDK update. `dotnet new` resolves the SDK through `global.json`, so the template also targets the pinned SDK's framework (10.0.401 gives `net10.0` on a machine whose default SDK is 11). **Automatic** writes no `global.json`.
How it is built: a new `dotnet` SDK kind in `ide-sdk` (detection runs in `sdk_detect`'s `spawn_blocking`), SDK field options that submit the version instead of the home (`version = true`) and leave out SDKs below a `min`, and `if-set` on generator steps (it already existed for arguments), so the pinning step runs only when a version is chosen. The New Project dialog now detects SDKs for any SDK field kind, not only `jdk`.
Edge cases: an empty or invalid solution name marks the field and disables Create. A solution name equal to the project name gives `App/App.slnx` + `App/App/App.csproj`. The generator now requires SDK 8.0 or later through `dotnet --version`, and a version command that exits with an error no longer counts as a version. So a missing `dotnet`, or a runtime-only install (no SDK), shows "dotnet is not installed" with the install hint and disables Create. An SDK 7 default shows that 8.0 or later is needed.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 05:30:14 +08:00
Mr0Bread 33ffa6cac1 refactor(plugin): make HostApi methods required, drop dead default bodies (#5489)
`HostApi` (`crates/ide-plugin/src/runtime.rs`) had 66 methods with default bodies (`Err(... unavailable on this host)`, `Ok(Vec::new())`, `let _ = (...)`). Its only implementor, `PluginApi`, overrides all of them, so those bodies could never run. They had to be kept in sync with real behaviour and let a forgotten override compile silently. They are now required methods (doc comments kept, signatures unchanged). No behaviour change.
`HostApi::project_of(&self, path)` is the one default that stays: `PluginApi` does not override it and it is live (`wit_host.rs` calls it, and the `project-of` guest fixtures exercise it). `PluginApi`'s own `project_of(window)` belongs to a different trait.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 05:29:51 +08:00
Mr0Bread a8aefa57c8 refactor(heap,index): compile test and bench support only for tests and benches (#5491)
`ide_heap::testing` (~430 lines of `.hprof` fixture builders) and `ide_index::bench_support` (`SyntheticIndex`) were `#[doc(hidden)] pub mod`s, so they were compiled into the desktop app and `openidea-server` and were part of the public API of both crates. Only tests and benches use them. They are now behind a `testing` feature (`ide-heap`) and a `bench-support` feature (`ide-index`), plus `cfg(test)` for in-crate tests. This follows what `ide-ssh` already does. `bench-support` is named for what it holds: a bench-only builder, not shared test fixtures.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 05:29:43 +08:00
Mr0Bread 1c24b77239 chore: remove unreferenced Rust items (#5493)
Removes ten `pub` Rust items that nothing references: not in production code, tests, benches, macros, strings, docs or `cfg`-gated code. They only widen public APIs and have to be kept up to date. No user-visible change.
Removed: `ExtensionRegistry::point_ids`, `Project::with_backend`, `diagnostics_store::RecordSinkFactory`, `ide_android::platform_tools_dir`, `ide_db::sql::ORACLE_SYSTEM_SCHEMAS`, `ide_run::go::package_sources`, `ide_build::maven::ALL_PHASES`, and `has_providers` / `has_views` / `has_hover_actions` on the plugin runtime. Two knock-on cleanups: the `PathBuf` import in `go.rs` became unused (removed), and the doc comment of `package_sources` (about Go's own build-file selection and `-find`) moved onto `package_info`, which it also describes.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 05:29:34 +08:00
Mr0Bread ae5c94e7d0 chore(deps): remove unused Rust dependencies (#5487)
Removes 25 Cargo dependency declarations that no code uses (found by `cargo shear`, each re-checked by hand): 11 unused internal crates in `src-tauri` (all still reach the app through `ide-host`), 12 unused deps in nine `crates/*` manifests, and the `anyhow` and `dashmap` entries in the root `[workspace.dependencies]` that no member uses. This shrinks the manifests and `Cargo.lock` edges. Only `Cargo.toml` files and `Cargo.lock` change; no Rust source is touched.
Removed:
- `ide-analysis`: `tracing`, `tree-sitter`
- `ide-android`: dev-dependency `tempfile` (the empty `[dev-dependencies]` header went with it)
- `ide-coverage`: `tracing`
- `ide-http`: `tracing`

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 05:29:23 +08:00
LU XIANGRUIandwildcatDownstairs fe9ee6a7a7 feat(python): create and detect Hatch environments (#5450)
"Add Python Interpreter" has a new **Hatch Environment** type. It lists the environments the project defines (`hatch env show --json`, without Hatch's internal `hatch-*` ones), runs `hatch env create <env>` with the chosen base interpreter as `HATCH_PYTHON`, and the result becomes the project interpreter. Hatch keeps an environment that already exists, whatever `HATCH_PYTHON` says. So if it was built on another Python version, nothing is changed and the dialog says so, rather than reporting it as created. The project's Hatch environments are also detected, with their own icon: `default` is listed as `Python 3.13 (Hatch: <project>)` and the others as `Python 3.13 (Hatch: <project>:<env>)`. The `default` one is the project interpreter when none is configured (after a `.venv` or pixi environment in the project, before the mise/asdf pin).
Until now Hatch was only a run wrapper (`hatch run`), and its data directory was not searched, so its environments never appeared. Detection does not start hatch:
- Hatch keeps environments at `<data>/env/virtual/<project name>/<project id>/<env>`, where the id is the first 8 characters of the URL-safe base64 SHA-256 of the project path.
- On Windows and macOS Hatch case-folds the path first (`ß` becomes `ss`); the IDE does the same for the letters a path is likely to hold.
- The project is the nearest folder, the opened one or above, with a `pyproject.toml` or `setup.py`, as for Hatch.
- The data directory is `HATCH_DATA_DIR` or the platform default.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 05:24:23 +08:00
LU XIANGRUIandwildcatDownstairs b5bff2fdfa feat(python): show the latest version of installed packages (#5433)
Settings › Python › Dependencies listed installed packages with their versions only, so finding out what can be upgraded meant running `pip list --outdated` in a terminal. The page now has a **Latest** column: once the installed list is shown, it asks the interpreter's package manager for newer releases in the background (`pip list --outdated --format json`, or `uv pip list --outdated` for uv environments) and marks the packages that can be upgraded.
Asking pip instead of the PyPI JSON API gives the newest release this interpreter can install, from the index pip is configured to use, in one command.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 05:08:30 +08:00
LU XIANGRUIandwildcatDownstairs e5f078913c feat(python): add Rearrange Code for Python classes (#5392)
There was no Rearrange Code for any language. **Rearrange Code** (Code menu, Find Action, IdeaVim's `RearrangeCode`) now orders the methods of every Python class in the file, nested ones included, as one undo step: `__new__` / `__init__` / `__post_init__`, other dunder methods, public, `_protected`, then `__private` methods, each group in its original order. The docstring and class attributes before the first method stay put; a method moves with its decorators and the comment lines directly above it; definitions sharing a name (a property and its setter, `@overload` stubs) move together in their order. Blank lines between methods stay where they were.
A class is left unchanged when moving could change it: other statements among its methods (`alias = method`, a nested class), standalone comments or `# region` / `# fmt: off` markers among them, or a decorator, default value or annotation that names another of its methods (`@_retry`, `@_visit.register`, `cb=_default`). Files with syntax errors are not rearranged.
The order is computed from one tree-sitter parse in `ide-language` (`Syntax::rearranged`); comments come from the syntax tree, so a `#` line inside a string is not taken for one. A language-neutral `doc_rearrange` command returns UTF-16 edits, so other languages can add an arrangement later. Backend errors are reported like formatting errors. There is no settings page yet.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 05:07:03 +08:00
Mr0Bread 5006e1934d fix(agents): confirm a Markdown code block copy with a check (#5488)
The Copy button in the top-right corner of a Markdown code block (agent replies) gave no sign that a click did anything: it copied silently and looked the same. After a successful copy it now shows a check in the success colour for two seconds and its label reads "Copied", then goes back to "Copy Code". Reply-level copy already behaves this way (`ReplyActions`).

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:41:31 +08:00
Mr0Bread 14d6d6892d fix(agents): skip code fences when titling a task from its prompt (#5486)
Starting an Agent Task with a pasted Markdown block named the tab "```text". The task title is the first non-empty line of the prompt (`title_of`), which for a pasted block is the opening code fence. The same title also names the worktree branch.
`title_of` now skips lines that open a code fence (``` or ~~~) and uses the first line after them.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:41:22 +08:00
Mr0Bread 080b7e80e7 perf(agents): stop re-rendering and rescanning the whole conversation for every streamed chunk (#5467)
While an agent streams, the visible session did work proportional to the whole conversation for every chunk: every earlier turn's reply and fold re-rendered, and the Composer re-read every tool output to rebuild the session assets. In a 170-turn conversation (2212 entries) that cost 12 ms per chunk in the stream and 7 ms in the composer; now it is 3 ms and 1 ms. Visible output, folding, turn numbers and reply actions are unchanged.
Root cause: the stream rebuilds its derived data for each chunk, and the props that carry it are new objects each time, so `memo` never held.
- `Entry:agent` (`session/messages.tsx`): `reply` (a fresh `ReplyTurn` from `replyTurns`) and `time` (a fresh `ReplyTimes` from `replyTimes`) for every earlier agent message.
- `TurnFold` (`session/ProcessRows.tsx`, rendered from `session/Stream.tsx`): a fresh `row`, the whole `entries` array, and fresh `children` elements. It was not memoized at all.
- `ProcessRun`: fresh `row` and `thinking` map each chunk.
- `extractSessionAssets` (`sessionAssetsModel.ts`, called from `SessionAssets.tsx`): re-parsed every tool entry's output each time `entries` changed.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:38:09 +08:00
Mr0Bread 92d94a7ac4 perf(ui): prefetch only the lazy views a window is likely to open (#5464)
After start-up, the workbench window loaded the code of every lazy view in the background, one chunk at a time, whether or not the user ever opened it: 122 extra chunks, +2.1 MB of JS and +3.0 MB of JS heap, plus ~300 ms of task time in the main window. `lazyComponent` / `lazyWhen` now take `{ prefetch: true }`, and `prefetchLazyComponents` loads only the components that set it. Everything else loads when it is first rendered, as it always could. Only the main workbench window prefetches (`mountWindowRoot(..., { prefetchLazy: true })`); auxiliary windows never did.
Opted in (what most sessions open early, where a blank first frame would show): Terminal tool window, Agents tool window + task and new-task editors, Commit and Git tool windows, the Settings dialog shell (not its pages), Search Everywhere / Find in Files / Recent files / File structure overlays, the markdown preview editor, the project switcher popup. Left on demand: all database, debugger, plugins, notebook, logcat, remote/deployment, github, python-console, web, build-tools, templates views, all settings pages (they already preload on page reveal via `preloadBuiltinPage`), edit-configurations, merge/compare/local-history editors, Run and Find tool windows (their stripes only appear on use, so the view mounts as it appears).

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:37:47 +08:00
Mr0Bread 518a62ea6c perf(agents): stop rendering and revealing a kept-alive session while its tab is hidden (#5462)
A kept-alive agent session tab (up to 5 per pane) that sits behind another tab kept rendering every streamed chunk like a visible one: the whole conversation re-rendered, the composer re-scanned all tool output (`extractSessionAssets`), and the reply's smooth-text reveal kept running its ~60 Hz `requestAnimationFrame` repaint. Up to 4 hidden tabs paid this on every chunk of a running task.
Now a hidden session stops reading conversation entries from the store (`useAgentsWhileShown` in `SessionEditor.tsx`) and the reveal is not live while hidden (`reveal.ts`). Shown again, it takes the latest entries in one render and paints unseen text whole instead of pacing it in. Visible tabs and docked sessions are unchanged.
```text
chunk -> store.entries
  visible tab:  TaskSession -> Stream, SessionComposer      (as before)
  hidden tab:   TaskSession keeps the entries it had, nothing re-renders

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:37:31 +08:00
Mr0Bread d16a87cf58 perf(vcs): stop polling for git process exit (#5459)
Every cancellable git read (`run_cancellable`, `run_bounded`, saved-credential transport, and GnuPG via `capture_command`) waited for the process to exit by calling `try_wait` and then sleeping a fixed 20 ms. A command that finishes in a few milliseconds therefore cost about 10 ms more on average than the same command through `wait_with_output`, and every git call made while opening or refreshing the Git tool window pays it. The wait now blocks on the output readers' completion (a channel that disconnects when both pipes reach EOF), so it wakes the moment the child closes its pipes, then polls `try_wait` with a 0.1 ms backoff capped at 20 ms for the reaping. Cancellation and output-limit checks still run at least every 20 ms, as before.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:37:12 +08:00
LU XIANGRUIandwildcatDownstairs f9fd1257c7 feat(python): show and edit an interpreter's sys.path (#5432)
Settings → Python → All Interpreters gets **Show Paths for Selected Interpreter** (toolbar and context menu). The dialog lists the interpreter's own `sys.path` (queried from the interpreter on a blocking thread, cancellable, with a reload button) and lets you add and remove folders outside the project. Until now there was no way to see `sys.path` or to put such a folder on the import path short of setting `PYTHONPATH` by hand in every run configuration.
Added folders are saved per interpreter in the global settings layer (`languages.python.interpreterPaths`, keyed by the interpreter's executable, like the interpreter list itself), so they apply to every project that uses the interpreter, as in PyCharm. They follow the interpreter that is actually used: basedpyright / Pyright get them as `extraPaths` for the interpreter that server analyses with, and run, debug, tests and the Python Console get them on `PYTHONPATH` for the interpreter the launch names (else the one of the project or workspace member it runs in), so Run and Debug of the same file agree. They are listed under External Libraries unless they are inside or around the project's own folders, which stay editable.
A folder that no longer exists is marked **Missing**, one `PYTHONPATH` cannot hold (not absolute, or with its separator in the name) is marked **Invalid**; neither is passed on. Duplicates and folders already on `sys.path` are not added. Removing an interpreter from the list drops its folders.
Not in this PR: removing the interpreter's own entries (PyCharm's excluded paths); ty, pyrefly, pylsp and notebook kernels don't get the folders. Docker / Compose run targets are not rows of this list, so they have no paths dialog.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 01:34:36 +08:00
LU XIANGRUIandwildcatDownstairs e57a709d19 feat(python): create and detect Pipenv environments (#5449)
"Add Python Interpreter" has a new **Pipenv Environment** type. It runs `pipenv --python <base>` in the project, which writes a `Pipfile` (importing `requirements.txt` if there is one) when the project has none. With **Install packages from Pipfile** checked, it then runs `pipenv install --dev`. The result becomes the project interpreter. If the project already has a Pipenv environment, it is reused and `--python` is not passed, because pipenv replaces an environment built on another Python without asking. When the versions differ, nothing is changed and the dialog says so. The project's Pipenv environment is also detected: it is listed as `Python 3.13 (Pipenv: <project>)` with the Pipfile icon, and it is the project interpreter when none is configured (after a `.venv` or pixi environment in the project, before the mise/asdf pin).
Until now Pipenv was only a run wrapper (`pipenv run`). Its environments were listed as plain virtualenvs named after their folder (`shop-Kpos5yRM`) and were never tied to their project. Detection does not start pipenv, which takes about a second. It looks for the `Pipfile` the way pipenv does, in the opened folder or one above it, and computes the folder name pipenv gives that project's environment: the folder name, `-`, and 8 characters of the URL-safe base64 SHA-256 of the `Pipfile` path. It looks for that name in `WORKON_HOME`, `~/.virtualenvs` and `$XDG_DATA_HOME/virtualenvs`, after the project's own `.venv`. An environment found elsewhere in the list is labelled as Pipenv's only if its `.project` names a folder with a `Pipfile` and its name matches. `ide-sdk` now depends on `sha2` and `base64`; both were already in `Cargo.lock`.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 01:28:27 +08:00
l0ng-ai abab90ca60 fix(maven): refresh stale SNAPSHOT sources on dependency reload (#5490)
After a SNAPSHOT dependency was republished and the project reloaded, navigating into it still showed the old sources: SNAPSHOT file names never change, the cached sources jar was reused as long as it existed, and open library editors kept their text. A sources jar older than its binary jar is now stale and replaced atomically; Maven reload waits for jdtls to finish importing, refreshes stale cached SNAPSHOT sources before reattaching archives, and refreshes open library editors. First-time source downloads still follow the Maven setting.
2026-11-24 01:09:14 +08:00
LU XIANGRUIandwildcatDownstairs 9d94b00911 feat(python): add type annotations from the inferred types (#5357)
basedpyright shows inferred types as inlay hints, and each hint carries the `textEdits` that insert it, including the import it needs (`from typing import Any`). The IDE dropped those edits, so an inferred type could not become an annotation. Inlay hints now keep `textEdits` over IPC, and Alt+Enter in Python offers PyCharm's:
- **Add type annotation ': int'** on an unannotated `name = value` assignment in a function or at module level (not in class bodies, where it would turn a dataclass/NamedTuple attribute into a field, nor for `global`/`nonlocal` names);
- **Add return type annotation '-> str'** on a function header;
- **Add type hints for function 'f'** on a function header: the return type plus the types of defaulted parameters (`limit: int = 10`), taken from hover and kept only when they name builtins, which need no import.
Annotations Python evaluates (signatures, module variables) use `X | Y` or `list[X]` only when `requires-python` allows them (3.10 / 3.9) or the file has `from __future__ import annotations`; a local variable's annotation is never evaluated. The intention asks the server for the hints itself, so it works with type hints turned off in Settings; a variable the server shows no hint for falls back to its hover type under the same builtin rule.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 00:40:35 +08:00
LU XIANGRUIandwildcatDownstairs cc1cc4cce5 feat(python): convert %-formatting and str.format() to f-strings (#5356)
Alt+Enter on a Python `%`-format expression said "No intentions available". It now offers PyCharm's **Convert to f-string literal** and **Replace with str.format() call**; on a `str.format()` call it offers **Convert to f-string literal**. Neither basedpyright nor Ruff offers these (Ruff's UP031/UP032 only report when a project enables pyupgrade rules, and the fix is not a quick fix).
`%` conversions `s r a d i u f e g x o` with flags, widths and precisions map to the equivalent format specs (`%5s` → `{x!s:>5}`, `%-8.3e` → `{x:<8.3e}`); `%d` keeps its truncation as `{int(x)}` unless the value is an int literal or `len()`/`int()`/`ord()` (`%05d` % `len(a)` → `{len(a):05d}`); `%(key)s` works with a dict literal; `%%` and literal braces are escaped, and `\N{NAME}` escapes are kept as they are. `.format()` fields support auto and manual numbering, keywords, `.attr` / `[0]` accessors, `!r` and specs. The conversion is not offered when it could change behaviour or produce invalid code: bytes, `*`/`**` arguments, `%c`, `*` widths, a precision on an integer conversion, nested format specs, a wrong argument count, an argument that would be dropped or evaluated twice, an argument containing the string's quote, a backslash or `#` (f-strings before Python 3.12), or, for `.format()`, a key that is a Python keyword. As in PyCharm, a single `%` operand that is not a tuple literal is taken as one value.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 00:30:27 +08:00
wangfeiandhapput 2478f67066 fix(workbench): keep project tab tint on hover (#5477)
Follow-up to #4481: hovering a coloured project tab made the custom colour disappear. The hover rule layered the opaque `--bg-hover` surface on top of the tint (`linear-gradient(var(--bg-hover), var(--bg-hover)), var(--tab-tint-mix)`), so while the pointer was over the tab only the plain grey hover surface remained.
The hover rule now mixes the project colour into the hover surface instead, mirroring how the selected rule mixes into `--bg-island`:
```css
.item[data-tinted]:hover {
  background: color-mix(in srgb, var(--project-color) 12%, var(--bg-hover));
}

Co-authored-by: happut <[email protected]>
2026-11-24 00:10:02 +08:00
zhzhsxandzhzhsx dc2924db17 fix(terminal): send the final size to a newly started PTY (#5473)
A new project's first terminal can end up with the wrong size. While the shell is starting, the terminal may resize, for example when the font finishes loading. That new size never reaches the shell. Full-screen programs such as vim then draw at the old width and the text looks broken. This fix sends the current size once the shell is ready.

Co-authored-by: zhzhsx <[email protected]>
2026-11-24 00:09:43 +08:00
l0ng-ai 348f4c2a2e fix(keymap): support mouse wheel shortcuts (#5483) 2026-11-23 23:58:16 +08:00
l0ng-ai 431b87c717 fix(remote): use the correct filesystem for file dialogs (#5479)
In an SSH or WSL window, Export Test Results passed a path picked in the desktop's Save dialog to the project host. Project-side pickers (Export Test Results, Save As, patch and Git dialogs, Maven/Gradle linking, scopes, coverage and Java sources, database source files, deployment destinations, tool and plugin paths) now browse the project host, with overwrite confirmation kept; flows whose files belong to the desktop (keymap and color scheme import/export, database and ACP imports, Clone) read and write through the desktop process. Follow-up to #5439.
2026-11-23 23:22:47 +08:00
l0ng-ai 3a53d13315 fix(editor): refresh Java inheritance markers after Maven import (#5478)
Interface methods could show no "is implemented" marker: the gutter cached the empty implementation results jdtls gave before the Maven import put the implementations on the classpath, and nothing invalidated them. When jdtls reports the project status after an import (generated sources attached first), the backend now emits an inheritance refresh next to the semantic-token refresh, and the gutter drops its cached markers and asks again. Covers implemented/overridden markers on interfaces, abstract classes and concrete overrides.
2026-11-23 23:20:57 +08:00
Mr0Bread 23f591289c perf(ipc): send binary command arguments as base64 instead of number arrays (#5436)
Pasting an image into a terminal or a Markdown file, or saving bytes from the UI, sent the data as a JSON array of numbers (3.6x the size), which Tauri and the remote server parse into a serde_json::Value first (~50x the bytes in memory: a 20 MB image took ~2.2 GB peak heap and 640 ms). Binary command arguments (fs_create_file_bytes, term_store_image) now travel as base64 text (IpcBytes): the same 20 MB takes ~112 MB and 32 ms. Native image drops reuse the base64 they already have.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 22:32:58 +08:00
l0ng-ai 8684e95778 fix(vcs): title git HTTPS credential prompts Username / Password instead of SSH (#5474) 2026-11-23 22:27:28 +08:00
Bert Verhelstandbertyhell 9d9e3f1c4f fix(java): don't reuse a launch snapshot copied while another build rewrote the outputs (#5420)
A Java launch that delegates to Maven could snapshot a dependency module's target/classes while an external mvn was rewriting it, then reuse that incomplete snapshot on every later launch (NoClassDefFoundError until the cache was cleared). A snapshot is now reused only while the live module outputs still match it (paths, sizes and modification times of the output tree, read from metadata only); output directories that appear after capture also invalidate it.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 22:24:59 +08:00
Bert Verhelstandbertyhell 5eff75cab5 fix(remote): keep scratches and generated requests on the host that writes them (#5439)
In a remote (SSH/WSL) window, Generate Request in HTTP Client failed with Permission denied: the scratches folder was resolved on the desktop and its path sent to the remote host. Scratches and generated HTTP requests now live in the data directory of the host that writes them (created on demand, rechecked on later calls), and remote IPC routing is installed before session listeners run.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 22:24:23 +08:00
l0ng-ai aec1382e79 fix(agents): keep the prompt box free of scrollbars until it reaches its height limit (#5472)
After one exchange, a new session's empty prompt box showed a horizontal scrollbar and a vertical thumb (visible with always-on scrollbars): the CodeMirror scroller kept a fixed height slightly taller than its content and allowed horizontal overflow. The scroller now sizes to its wrapped text, never scrolls horizontally, and scrolls vertically only past its 280 px limit.
2026-11-23 22:02:22 +08:00
l0ng-ai 999d84b189 fix(run): resolve Java launches in attached projects (#5471)
Running or debugging a Java main class of a project attached to the window failed to compile (its Maven dependencies were missing): launch preparation used the primary project's root, build model, settings and cache. Run/Debug/test launches now resolve the owning attached project (innermost root containing the module) and use its build model, Maven reactor, settings, classpath and launch-snapshot cache; older saved configurations resolve the same way.
2026-11-23 22:01:15 +08:00
jiejie1133 9fda9b92c2 fix(editor): edit a repeated template variable from one caret (#5443)
After expanding Java `fori`, the three occurrences of `i` were all editing selections, so arrow keys moved three carets. The shared snippet engine now selects only the first occurrence of each variable and mirrors edits to the others, for every live template and language and for LSP snippets with repeated placeholders; the Java-specific handling is gone.

Co-authored-by: jiejie1133 <[email protected]>
2026-11-23 21:41:18 +08:00
fun90andfun90 261eb03009 fix(markdown): open preview links to another file at the linked heading (#5422)
Clicking a link to a heading in another file (e.g. [§5.2](b.md#52-状态机)) in the Markdown preview opened the file at the top. The destination now opens at the heading, in Preview Only and split mode, also when the file wasn't open yet (the preview scrolls once it has rendered). Markdown file-type aliases are honoured and a later link click wins over a slower earlier one.

Co-authored-by: fun90 <[email protected]>
2026-11-23 21:21:17 +08:00
l0ng-ai db8b553364 fix(editor): merge inheritance gutter markers by line and kind (#5470)
Lombok-generated members (@SuperBuilder, @Data) put one override/implemented marker per generated method on the annotation line, filling the gutter. Markers of the same kind on a line now collapse into one icon with a combined tooltip; clicking it opens the target chooser (a single target still opens directly). Applies to all four inheritance marker kinds.
2026-11-23 21:19:14 +08:00
langxpandkradme 2494b2efdf fix(libraries): reveal classes from unlisted classifier jars (#5414)
Select Opened File could not reveal a class opened from a dependency JAR that used a Maven classifier and was absent from External Libraries. The document knew its exact archive, but the Project view only searches registered archive roots.
External Libraries now adds the exact archive referenced by the active library document, labels it with its Maven coordinate when available, and removes the temporary entry once the build model lists the same archive.

Co-authored-by: kradme <[email protected]>
2026-11-23 21:13:35 +08:00
Muuandmuutot d78ce7ec66 fix(editor): offer contributed Copy Path links in the tab and library menus (#5400)
Copy Path/Reference… built a different submenu per entry point: the project view and the editor caret chooser list the contributed copy items (features/vcs: Path From Repository Root, GitHub Link), while the editor tab menu and the External Libraries menu hand-wrote theirs and silently dropped every contribution. Both hand-written submenus now append the same `copyPath` menu group, so all four entry points agree — and future contributions appear everywhere at once.

Co-authored-by: muutot <[email protected]>
2026-11-23 21:10:34 +08:00
Bert Verhelstandbertyhell 9df9499bf5 fix(project-view): open files on single click when preview tabs are enabled (#5419)
With **Settings › Editor › General › Editor Tabs › Enable preview tab** on, a single click on a file in the Project view now opens it in the preview tab, and the next single click reuses that tab. Before, the click did nothing. The cause was two switches that weren't connected. The Project view checked its own "Enable Preview Tab" view option, which was off by default and only reachable from the view's ⋮ menu. The Settings checkbox was a separate setting, `editor.tabs.previewTab`, which was only read when a preview tab was created.
IntelliJ IDEA documents these as two ways into one setting, so this PR makes them one. The Project view reads `editor.tabs.previewTab` for single click and for Autoscroll to Source. Its ⋮ › Behavior › Enable Preview Tab item and the `project.option.previewTab` action (the id is unchanged) now write that setting. The old view option is removed from the saved Project view options when they load.
What existing users will see:
- Defaults (Settings on, view option off): single click now opens a preview tab. This is the fix. The editor setting already defaulted to on, so users who never changed anything get single-click preview after this change.
- Both on: no change.
- Both off: no change.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 21:10:08 +08:00
aconeshanaandaconeshana d4b5581441 fix(ui): paste into a tree's speed search, not the view's Paste (#5401)
In the Project view, copy a keyword, press ⌘F, then ⌘V: the app reported "No files on the clipboard" and the search box stayed empty, instead of pasting the keyword the user had copied to search with.
A tree's speed search is not a text field — its query is built from printable keydowns. So `⌘V` never reached the query: the keymap dispatcher ran `project.paste` on the selected folder, and the paste event that followed bubbled to the Project view's clipboard fallback, which runs the same action again.
The shared `Tree` now claims `⌘V` while a search is active (as it already claims `⌫` since #3226) and takes the clipboard text into its query: pasted text is flattened onto one line and the search jumps to the nearest match. With the search closed, or with a clipboard that holds no text, the view's Paste runs exactly as before.
Every tree with a speed search gets this — the Project view, the Database view, the Services tree and the GitHub changes tree all render `src/ui/Tree.tsx`.

Co-authored-by: aconeshana <[email protected]>
2026-11-23 21:00:08 +08:00
Bert Verhelstandbertyhell d96060f08b fix(ui): scroll text fields while drag-selecting past their edges (#5429)
Drag-selecting in a long Find in Files query (or any text field) and moving the pointer past the field's left or right edge didn't scroll the text, so you couldn't select past what's visible. IntelliJ IDEA does scroll. WebKitGTK extends the selection in this case but never scrolls the field to follow it. Arrow keys do scroll. Now, while a drag that started in the field is past one of its edges, the field moves the selection end and the scroll position itself, faster the further out the pointer is. Once the pointer is back inside, WebKit's own selection takes over again. Both `Input` and `SearchField` get this.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:59:53 +08:00
Bert Verhelstandbertyhell 507258daec fix(editor): stop clipping Code Vision hints that are taller than 16px (#5418)
The Code Vision row above a declaration (usage count, author) cut off the top or bottom of its text, most visibly for Chinese labels like "10 个用法" / "无用法". The row was a fixed `height: 16px` with `overflow: hidden`, while its text is the editor font size minus 1px. At larger editor fonts, or with CJK fallback fonts that ink below the Latin metrics (Microsoft YaHei, Noto Sans CJK), the glyphs didn't fit.
The row now has `min-height: 16px`, and its items use `line-height: normal`, so the row grows to the ascent and descent of the fonts actually used. At the default font a Latin-only row is still exactly 16px. The line-end hint (Code Vision kinds set to "right") has the same 1em box with `overflow: hidden`. It keeps its size and position but now clips only horizontally.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:59:37 +08:00
Mr0Bread dae402b966 perf(vcs): make a git history page cost independent of the commit count (#5446)
A Git Log page costs a fixed ~15 ms in a repository with 248 refs (the 100k-commit fixture), even for a one-row page. Every page listed and peeled all refs twice (once for the decorations, once more for the view cache key via `log_refs`), at ~25 µs per ref. The decorations are now cached until `HEAD`, `packed-refs` or a directory under `refs/` changes, and the cache key uses a change counter instead of the full ref map. A warm page no longer reads any ref.
The cost scales with the number of refs, not commits: the audit's 10k/100k fixtures have 50/248 refs, which is why it looked proportional to the commit count. A repository with thousands of remote branches pays correspondingly more.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 20:43:54 +08:00
Bert Verhelstandbertyhell 39e803b8f9 fix(vcs): keep a filtered log narrow while older matches are still unloaded (#5421)
With a User filter on a merge-heavy history, the first page of the Git Log fanned the top merge out into dozens of dashed lanes, and the graph column pushed the commit subjects to the right. It went back to one line only after every match was loaded. The cause: `pruneFilteredEdges` (the #2670 fix) only judges a filtered connection when its target is on the loaded page. With the first 300 rows of the issue's repository, the merge kept 43 connections, 42 of them to rows that weren't loaded yet.
Now, while another kept connection of the commit already leads below the page, a filtered connection to an unloaded target waits until that target loads, and is then judged exactly like before. If no kept connection leads below the page, one filtered connection stays, so a row never looks like the end of its history. This is a heuristic: a connection that turns out to be needed (two unrelated side branches, both below the page) appears once its target loads. The sibling-branch test pins that behaviour. An exact answer on the first page would need the backend projection (`Visibility::parents`) to drop ancestors that another projected parent already reaches. This PR doesn't touch Rust; that could be a follow-up.
Go to Parent now pages until every unpruned connection of the commit is loaded, as it did before, so a merge still offers all its parents.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:43:44 +08:00
TWINKLE d6b56856d2 Fix/terminal ime caret (#5458)
Closes #4112 (its remaining half: #4347 stopped the terminal sliding sideways while composing, the
candidate window still opened at the far right of pi's input box).
xterm anchors the IME candidate window on its hidden helper textarea, and keeps that textarea on the
terminal cursor — on every render, on `compositionstart` and again on each `compositionupdate`. A
program that paints its own caret leaves the terminal cursor elsewhere: pi asks for a column past the
right edge of its input box (`ESC[21;411H` in a 206-column terminal, which xterm clamps) while it

Co-authored-by: H-TWINKLE <[email protected]>
2026-11-23 20:40:44 +08:00
Yann 8a84e8f473 fix(agents): preserve and display tool result images (#5447)
Claude Code can return an image from a tool call without including a Markdown image in its final reply. OpenIDEA discarded that image while normalizing and saving the tool result, so the conversation showed no preview.
Preserve inline tool images separately from truncated text and show them below the folded work summary. The existing image viewer opens the full preview; expanding the work does not duplicate it, and old conversations without an image field still load.

Co-authored-by: YannABC <[email protected]>
2026-11-23 20:40:35 +08:00
Bert Verhelstandbertyhell f31aa29f3e fix(agents): update the context meter when Claude Code compacts the conversation (#5441)
After a compaction the context meter kept the pre-compaction usage until the next request. compact_boundary now sets the usage to post_tokens; without it the driver asks Claude Code (get_context_usage).

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:03:15 +08:00
faysouandfaysou 639e4b3df9 fix(editor): keep completion types and usage captions visible in narrow popups (#5387)
The completion popup can clip a return type after the editor font loads. Its return-type column now uses the row’s existing gap. In Show Usages, same-named files can be hard to distinguish because the filename and directory share too little space. The filename column now gets 38% of a narrow row, with the existing 176 px cap.
| Popup | Before | After |
| ----- | ------ | ----- |
| Completion | ![Return type ends in an ellipsis](https://raw.githubusercontent.com/faysou/openidea/691de74a16586ccc65eb229315507ba0f5938933/completion-before.png) | ![RegionalSettlementResult fits](https://raw.githubusercontent.com/faysou/openidea/691de74a16586ccc65eb229315507ba0f5938933/completion-after.png) |
| Show Usages | ![The checkout directory is truncated](https://raw.githubusercontent.com/faysou/openidea/691de74a16586ccc65eb229315507ba0f5938933/usages-before.png) | ![Both billing and checkout are visible](https://raw.githubusercontent.com/faysou/openidea/691de74a16586ccc65eb229315507ba0f5938933/usages-after.png) |

Co-authored-by: faysou <[email protected]>
2026-11-23 20:02:54 +08:00
Bert Verhelstandbertyhell 01b9908898 fix(search): offer every project file type in the file mask menu (#5416)
The **File mask** menu in Find in Files now lists every language file type present in the project, most common first, after the recently used masks. Before, `refreshProjectMasks` kept only the 5 most common types, so in a project with six (rs, md, json, toml, yml, properties) the least common one, `*.properties`, could not be picked. The menu already scrolls and stays inside the window, so a long list stays usable.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:02:43 +08:00
Bert Verhelstandbertyhell 7f201ed87d fix(editor): stop linked tag editing while a tag is being deleted (#5434)
Backspacing through a closing tag such as `</div>` also emptied the opening tag, leaving `<>`. The first Backspace removes `>`. The parser still reads `</div` as the element's close tag, so every later Backspace in the name counted as a rename and was mirrored. Linked tag editing now only pairs two tags that both still end in `>`. A tag missing its `>` is being deleted, so nothing is mirrored into it or out of it. The same applies to an opening tag deleted before its children, in all the HTML-based modes and in JSX/TSX. XML does not use linked tags (`LINKED_TAG_LANGUAGES` in `prefs.ts`).

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:02:33 +08:00
Shohruh Ismoilovandshohruh-genius 85344b86b5 fix(templates): offer Svelte components in the New menu (#5440)
The New menu had no built-in template for `.svelte` files. Add **Svelte Component** for Vite and Node.js projects, including SvelteKit workspace members. The template accepts SvelteKit filenames such as `+page.svelte`.

Co-authored-by: shohruh-genius <[email protected]>
2026-11-23 20:02:23 +08:00
faysouandfaysou 12e85a7c1b test(vcs): check Git Log graph options as separate equivalence cases (#5424)
The Git Log graph-equivalence test compares layouts for eight option combinations, each with five fragment configurations. Running all 40 comparisons in one Vitest case exceeded the five-second timeout on shared Linux runners. Give each option combination its own test for histories with and without refs. Each case still compares the complete layout with the dense reference implementation for all five fragment configurations and the same 2,400 commits.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:02:13 +08:00
faysouandfaysou 861acabf77 test(search): open the action search from the toolbar (#5386)
The action-search test could time out before reaching its first search assertion when the runner delayed the second Shift press. Open Search Everywhere through the title-bar button for this test, then enter a query and run the matching action. The adjacent shortcut test exercises double Shift directly.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:02:04 +08:00
faysouandfaysou 96395c979f test(project): control the clock during diagonal submenu navigation (#5384)
The Project tree test moves the pointer diagonally toward the New submenu in ten steps. On a busy runner, the time spent delivering input and checking assertions can exceed the menu’s hover delay and close it mid-gesture. Use Playwright’s browser clock to advance 75 ms at each step and check that the submenu stays open through the final 350 ms pause.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:01:55 +08:00
Mr0Bread e9f768d8b5 perf(events): serialise an event once for all windows (#5445)
With auxiliary windows open (comparison, diff, etc. that share the project's documents), every backend event was serialised once per window, because `emit_to` serialises its payload on each call. For a large diagnostics event that is 2.3 MB (10k items) or 11.6 MB (50k items) of JSON built again for each window, on the thread that emits the event. `TauriSink` now serialises the event once and sends the same JSON string to each window with `emit_str_to`. The payload is the same `serde_json::to_string(&event)` that `emit_to` produced, so the frontend (`getCurrentWebviewWindow().listen` in `src/platform/ipc.ts`) receives exactly what it did before. Which windows get which events is unchanged.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 20:01:45 +08:00
Mr0Bread d15abe54e2 perf(vcs): read the restricted-mode scoped status with a pathspec (#5451)
In Restricted Mode, the refresh after a watcher batch (`status_paths`) ignored its paths and answered with the full gitoxide status, which walks the whole tree to report one saved file. In a 100k-file repository that took about 87 ms against about 15 ms for a trusted project. It now runs `git status` with the pathspec, as a trusted project does.
The audit (row S4) blamed the extra `git config --null --list` process. That process is not the cause: the full `status()` never runs it (it runs `gitoxide`), and the old restricted `status_paths` did not run it either. The cause is the early return to the full status in `Repo::status_paths`, left from #3267, when the scoped read was in-process and `git` was not allowed. #3280 moved the scoped read to `git`, with the filter overrides the restricted fallback already used, but the restricted bypass stayed.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 20:01:29 +08:00
faysouandfaysou b501f51526 test(run): compile the output counting reader only on Unix (#5407)
The Windows Clippy job fails because the test reader `Counted` is compiled on Windows, where its only caller is excluded. The flooding-process test uses `awk` and already requires Unix. Apply the same condition to the reader and its `Read` implementation. The cross-platform queue shutdown test keeps its own reader.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:01:20 +08:00
faysouandfaysou 50cd478773 test(vfs): allow watch events for an excluded directory itself (#5382)
The per-directory watcher skips the contents of excluded directories. A watch on the parent can still report the directory itself, which macOS did for `node_modules`. The regression test now accepts that event while continuing to reject events for descendants.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:01:10 +08:00
faysouandfaysou 2c63f0eb22 chore(deps): update cookie to 0.18.3 for RUSTSEC-2026-0594 (#5431)
Update the transitive `cookie` dependency from 0.18.2 to 0.18.3. Cargo Deny reports the older release for possible nonce reuse when encrypting private cookies across a fork. The patched crate obtains those nonces from the operating system. [RustSec advisory](https://rustsec.org/advisories/RUSTSEC-2026-0594.html)

Co-authored-by: faysou <[email protected]>
2026-11-23 20:01:00 +08:00
faysouandfaysou ed1730f273 fix(vcs): preserve the index timestamp when preparing a commit selection (#5383)
A commit preview or a commit of selected changes can omit a same-size edit made on the same filesystem clock tick as the Git index. Git uses the index timestamp to decide when it must inspect the file contents. The temporary copy now preserves that timestamp so Git detects the edit.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:00:51 +08:00
akshathayadav378-boopandakshathayadav378-boop d6d0cc7926 fix(vcs): use the Project view selection for Git file actions while it is the context (#5428)
Show History (and Add to VCS / the ignore actions) took the editor's file when the shortcut ran right after clicking a Project view row: the row publishes its selection on mousedown, but tree focus is a separate DOM event, so projectViewFocus was still false. File actions now use the Project view selection while the tree owns the context (its lead is set and the editor has no focus), the same rule External Tools use (shared projectViewContextLead helper).

Co-authored-by: akshathayadav378-boop <[email protected]>
2026-11-23 20:00:11 +08:00
l0ng-ai a21de32077 fix(editor): give the top and bottom breadcrumbs distinct keys (#5463)
The top and bottom breadcrumb bars are keyed separately, so Markdown and HTML tabs no longer log React's duplicate key error.
2026-11-23 19:38:19 +08:00
Bert Verhelstandbertyhell 546ff9f314 fix(run): resolve External Tools file macros against the Project view selection (#5415)
External Tools expanded $FilePath$ and the other file macros from the editor's file even while the Project view was the user's context. They now take the Project view's selected file while it is the context (no editor focus, not a virtual document); caret macros apply only when the editor shows that same file.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 19:35:44 +08:00
l0ng-ai a144208170 fix(debugger): keep a rerun session's tab in place while its adapter starts (#5460)
Rerun keeps the finished tab in place and selected until the new session appears, which then takes its slot and the selection at once.
2026-11-23 19:33:10 +08:00
l0ng-ai fda2d2ff69 fix(run): scroll configuration choosers to their last item in short windows (#5457)
The configuration choosers' list fills the viewport left by a window-capped popup, so its last items scroll into view in short windows.
2026-11-23 19:28:33 +08:00
l0ng-ai 0fdf37f1bf fix(vcs): list every repository's branches and tags in Go to Hash/Branch/Tag (#5455)
Go to Hash/Branch/Tag reads refs from the repositories it searches (shown log tab, else the filtered ones, else every root) instead of an empty Repository filter, which offered only HEAD.
2026-11-23 19:24:50 +08:00
l0ng-ai 5c592bbc86 fix(editor): move a whole switch case in languages with flat case labels (#5453)
Move Statement on a case label in Go, JavaScript and Java moves the whole branch (stacked labels through its last line) past the neighbouring branch instead of only the label line.
2026-11-23 19:22:35 +08:00
l0ng-ai 819ccb8bb5 docs: refresh WeChat group QR code 2026-11-23 19:18:28 +08:00
l0ng-ai ae893f059f fix(agents): keep unrelated chat rows stable during text selection (#5438) 2026-11-23 18:56:34 +08:00
l0ng-ai fb2f567d5b fix(agents): hide Jump to Latest when the reply end is visible (#5442) 2026-11-23 18:51:44 +08:00
l0ng-ai 22af0931dd fix(vcs): name each repository of a shared branch in the Branches pane tooltip (#5413)
In the Git Log Branches pane with several repositories, a branch every
repository has is listed once with no repository name. Hovering it now
lists each repository with the branch it tracks there.
2026-11-23 17:21:59 +08:00
l0ng-ai 4af81625b1 fix(agents): scroll the container under the pointer and keep fold headers in place (#5411)
The wheel now scrolls only the innermost scrollable container under the
pointer: a run of tool calls from its headers, a tool output from its text,
the conversation elsewhere. A nested container at its edge no longer hands
the rest of the gesture to the conversation, and a gesture stays with the
container it started in.

Opening or closing a section keeps its header where it was. Closing one near
the end leaves temporary room below the conversation that scrolling up or new
content takes back.
2026-11-23 17:16:29 +08:00
l0ng-ai f3d18c0eb8 fix(agents): clarify settings names and align the import dialog (#5403)
* fix(agents): align and shorten the Import Sessions dialog

* fix(agents): clarify settings page names
2026-11-23 16:35:39 +08:00
l0ng-ai e662c915a2 fix(agents): show the changes scope as compact tool window tabs (#5393)
The Whole Task / Last Turn switch in the agent Changes pane was a full-width
segmented pill. It now uses the compact Tabs strip that tool window sub-views
use elsewhere.
2026-11-23 15:45:07 +08:00
l0ng-ai f57a17ec14 fix(vcs): group stashes by repository (#5380) 2026-11-23 15:45:02 +08:00
l0ng-ai 0b8d9135aa fix(github): keep the review composer readable (#5375) 2026-11-23 15:44:50 +08:00
l0ng-ai 290ef6956e fix(diff): align original and modified line numbers (#5370)
Unified Diff shows original line numbers in the first column and modified line numbers in the second. Matching rows show both. Removed and inserted rows show the number for their own revision.

Line numbers stay beside the start of their rows when code wraps, and follow scrolling inside a large removed block. Matching rows keep their original numbers when empty lines are ignored. The column order also applies when the editable side is the Git index.
2026-11-23 15:44:15 +08:00
l0ng-ai 8a4b8f45b4 fix(agents): shorten task context menu labels (#5394) 2026-11-23 15:35:46 +08:00
l0ng-ai 31b265cb41 fix(vcs): align the New Worktree dialog (#5367)
- Align the repository, checkout, branch, name, location and setup fields in one label-and-control grid. Use the standard dialog type size for labels and keep the worktree path preview beneath the Location field.
- Let the `.worktreeinclude` edit action wrap below its checkbox in narrow windows. With setup expanded, the standard dialog is about 118 logical pixels shorter, and the setup field fits without scrolling in a 440 × 520 window.
2026-11-23 15:17:34 +08:00
1817 changed files with 97732 additions and 12992 deletions

No files matched your search

-83
View File
@@ -1,83 +0,0 @@
---
name: eval
description: Run the code-intelligence evals (`pnpm eval`), pick the worst failing scenario, diagnose it from the attached timeline, fix it, prove the fix with before / after numbers measured on this machine without regressing other scenarios, and open one PR. Use for "跑 eval", "优化 Java 代码智能", "eval 失败了", an issue labelled `eval`, or any change to Java navigation / usages / gutter markers that needs numbers.
---
# Eval loop: measure → fix → prove
`pnpm eval` drives the production workbench in Chromium against a release `openidea-server`
with real language servers (Java / jdtls for now) and judges every scenario on what the user
sees: time to feedback, to the first result, to the final one, and the results themselves vs
`evals/<language>/golden/`. One machine, before and after: numbers from different machines or
from the nightly host don't judge a fix.
## 0. Preconditions
- `jdtls` on PATH and `JAVA_HOME` pointing at a JDK of the pinned `JAVA` version (projects
compile against it, and the JDK scenarios' results are in its sources; jdtls itself runs on
a newer installed JDK when it needs one). Pinned versions: `.github/tool-versions.env`. A
mismatch prints a warning and the report records both: say so in the PR when it applies.
- First run builds `cargo build --release -p ide-host --bin openidea-server` and the perf
bundle; later iterations of a frontend-only change can use `--no-build` after a
`pnpm exec vite build --mode perf --outDir target/eval/dist`, a backend-only one after the
cargo build alone.
- Run evals one at a time on this machine, with nothing heavy (builds, other evals) beside them.
## 1. Baseline on the base commit
```sh
git switch --detach origin/main # or the fix branch's merge base
pnpm eval --save-baseline # target/eval/baseline.json, this machine only
```
Read `target/eval/report.json`. Each verdict has `status`, `failures` (`kind`: `error`,
`timeout`, `degraded`, `correctness`, `budget`, `golden`), `regressions`, `repro` (the command
that reruns it) and, for failures, `diagnostics`: every command sent to the server in the
slowest run's window (`cmd`, `start`, `ms`, `ok`, `bytes`, `items`), background tasks, server
status changes and the server's log tail.
## 2. Pick one problem
Worst first: wrong or missing results and silent degradation, then timeouts, then the
feedback budget (100 ms), then the slowest `completeMs`. One problem per PR. Say which
scenario and metric, with its value vs budget.
## 3. Diagnose from the timeline
- Commands in the window ordered by `start`: what ran, what waited on what, what's serial
that could overlap, which request returned many `items`/`bytes`, which failed.
- `feedbackMs` far above 16 ms with a fast `firstResultMs`: the UI shows nothing while it
waits (a hint or popup that only appears after a delay).
- A task still running across the window: background work competing with the request.
- For the frontend side rerun with `--trace` and open `target/eval/traces/<id>@<cond>.json`
in Chrome's Performance panel.
- Name the cause at class level (as in `issue-fix`): it usually affects sibling scenarios.
## 4. Fix, then rerun that scenario until it passes
```sh
pnpm eval --only <scenario> --condition <warm|cold> # the verdict's `repro`
```
Correctness is enforced, so a faster answer that drops, truncates or serves stale results
fails. Don't trade a budget miss for a degraded answer.
## 5. Full suite, then PR
```sh
pnpm eval # vs the baseline from step 1: no new failures or regressions
```
PR per `issue-fix` §6, plus in **How it was verified** the before / after table from
`target/eval/report.md` (both on this machine, commits named) and the tool versions line.
## Guard rails
- Goldens (`evals/*/golden/`) and budgets (`evals/budgets.json`) are human-owned. Don't edit
them, and don't run `--update-golden`, to make a scenario pass. When a golden looks wrong
(a tool bump, a deliberate behaviour change), stop and say so: a PR that touches them gets
`needs-decision`.
- Don't weaken a scenario's checks or timeouts in `evals/<language>/scenarios.ts` to pass.
Adding a scenario (for a case the sweep or a user found) is fine; record its golden with
`--update-golden --only <id>` and ask a person to review the file.
- A flaky timing (passes on rerun) is not a regression: rerun once before acting on one.
-91
View File
@@ -1,91 +0,0 @@
---
name: issue-fix
description: Triage and fix a GitHub issue (or a user-reported bug) end to end — reproduce, find the root cause, generalise it to every sibling case, fix the class rather than the instance, verify, and open one PR. Use when given an issue URL/number or asked to fix a reported bug and open a PR ("看看这个 issue", "修一下这个 bug", "提 pr").
---
# Fix an issue: from one case to the whole class
The reported case is one sample of a defect class. A fix that only makes the
screenshot go away is not done: the next question is always "does this break for other
languages / platforms / entry points too?". Answer that before anyone asks.
## 1. Read and reproduce
- `gh issue view <n> --comments` (repo `l0ng-ai/openidea`). Read attached logs/screenshots
closely: OS, language, toolchain versions, exact error text.
- Locate the code path and confirm the claim in code, with `file:line` evidence.
Say plainly whether it is a real bug, a missing feature, or user environment.
- Reproduce locally when possible (`fixtures/` projects, `/verify` for runtime). If the
reporter's platform (often Windows/Linux) can't be reproduced here, say so up front.
- Do not ask for a generic environment/log checklist before trying the flow and inspecting the code.
Record the attempt and result; ask only for a fact that actually blocks the next diagnostic step.
Missing fields, limited time, or unavailable automation are not by themselves reasons to ask the reporter.
- Treat a maintainer-confirmed bug as an investigation task even if local reproduction fails. Distinguish
“not reproduced here” from “not a bug”, and do not require the reporter to prove its existence again.
## 2. Name the root cause as a class
Write one sentence of the form "<mechanism> is missing/wrong, so any <X> hits it",
not "<this button> is broken". Typical classes in this codebase:
- Per-language config handled for one language only (`languages/*.toml`, `ide-sdk`).
- Platform gaps: paths, executables, shells, `.cmd`/`.exe`, separators — macOS-only code.
- Toolchain/version discovery: one probe location, no version check, no rescan.
- Two features each implementing half a flow and never joined (feature isolation →
should go through an action/service).
- State not reset on project switch / window reuse; events not scoped per window.
- Failure surfaced as raw stderr/stack trace or retried until "crashed" instead of a
clear status with an action.
- UI: same primitive styled differently in N places.
## 3. Sweep for siblings
Search systematically, not by memory:
- Same pattern elsewhere: `git grep` the function, the config key, the error string,
the hard-coded path/flag. Check every `languages/*.toml` entry and every platform branch.
- Same flow for other languages/runtimes (Java ↔ Kotlin/Gradle, Python ↔ venv/uv,
Node ↔ Deno/Bun, Go, Rust …): would they fail the same way?
- Other callers/entry points of the same flow (menu, context menu, gutter, shortcut, CLI arg).
- Neighbouring failure modes of the same mechanism (not installed / wrong version /
installed but crashes / slow start / installed mid-session).
For broad sweeps spawn one Explore agent with the class description, not the instance.
## 4. Decide the fix at the right altitude
- Fix the mechanism once (shared helper, action, config hook) so siblings are fixed
by construction; don't patch each call site.
- Respect `AGENTS.md` rules (crate boundaries, no cross-feature imports, `IdeResult`,
UTF-16). If the right fix breaks a rule, pick the rule-respecting design and say why.
- Compare with how established IDEs solve it when relevant; prefer the established answer.
- Present: root cause, sibling table, proposed fix, what's deferred. When the user leaves
the choice to you, go ahead without asking again.
## 5. Implement and test the class
- Tests cover the class: table-driven over languages/platforms/states, not just the
reported input. Include the reporter's case verbatim.
- Run the scoped checks (`pnpm vitest run <path>`, `cargo nextest run -p <crate>`), then
`/verify` in the app for UI or runtime behaviour.
## 6. PR
- One branch `fix/<slug>`, one PR unless the user asks otherwise; `Fixes #<n>` in the body.
- Don't stage untracked IDE-state dirs (`.ideal/`, `.openidea/`) or screenshots.
- PR body follows `.github/pull_request_template.md`: `Closes #<n>`, then
**What and why** (user-visible change + root cause at class level, 2–4 sentences),
**How it was verified** (commands run and results, siblings fixed/deferred, what could break and how
it was checked, what was not verified, e.g. "Windows not tested"; for UI changes the before/after
screenshot paths from `/verify`), **Review focus** (optional). Short and plain.
## Report format
Reply in the user's language:
```
Root cause: <one sentence, class level>
Sibling sweep:
| Location / case | Affected? | Action |
Fixed / not covered (why) / not verified (platform)
PR: <url>
```
-57
View File
@@ -1,57 +0,0 @@
---
name: verify
description: Build, launch and drive the OpenIDEA desktop app through the Tauri MCP bridge to verify a change at runtime.
---
# Verify OpenIDEA in the running app
## Launch
- Run the app from the worktree that holds the change: `pnpm tauri dev` in the background, logging
into your task's scratch subdirectory. Use `pnpm dev:app` instead when your checks call
`window.__TAURI__` from `execute_js`. The wrapper gives each worktree its own app identity, data,
settings and Vite port, so other worktrees and the installed app don't interfere. If it reports a
session already running for this worktree, reuse that one.
- Once the app is up, `pnpm dev:status` lists this worktree's MCP bridges. Pass the reported
`appIdentifier` (the port) on every `mcp__tauri__*` call. The MCP server is shared between
sessions: never `driver_session stop` without an `appIdentifier`, and re-check `document.title` /
`location.href` before acting if anything looks off.
- Make sure the binary contains the change: a session already running for this worktree may be an
older build. Restart it after Rust changes; frontend changes reload through Vite.
- After the app restarts, `driver_session start` again for your port (a stale session says "Already connected").
- If the `pnpm tauri dev` process exits while the app window stays open, Vite is gone and any webview
reload shows an empty `#root`. Stop that app and start the session again.
- Stop everything you started when done and nothing else; never use process-name kills.
## Driving
- `manage_window focus` before screenshots / timing-sensitive steps: a background window throttles timers
(debounced LSP / VCS refreshes stall, `setTimeout` promises in `execute_js` time out) and native
screenshots come back black.
- Settings is a separate native window `settings-main`; pass `windowId`, focus it before screenshotting.
- CodeMirror / xterm ignore MCP `type`. Focus the element, then `document.execCommand('insertText', false, text)`.
For xterm Enter, dispatch a `keydown` (`key: 'Enter', keyCode: 13`) on `.xterm-helper-textarea`.
- MCP clicks arrive with `event.detail === 0`; CodeMirror treats them as line-select clicks. Set the caret
through the view instead: `document.querySelector('.cm-content').cmTile.view`.
- MCP `text` strategy can resolve to a hidden node; prefer coordinates (CSS px = image px × 0.9) or CSS selectors.
- CSS-module edits often trigger a full page reload in dev: dialogs close, Run sessions and terminal
scrollback reset, and each reload spawns a fresh shell. Re-open what you were testing.
## Evidence
- For UI or interaction changes, capture `before.png` (on `main` or with the fix reverted) and
`after.png` at the same state and window size, into your task's scratch subdirectory. Multi-step
flows: a numbered series (`after-1.png`, `after-2.png`, ...).
- Report the absolute paths; they go into the PR's **How it was verified** section and the triage
acceptance entry. Never commit screenshots to the feature branch.
## Fixture
`fixtures/` has sample projects (go-app, rust-app, ts-app, kotlin-gradle, polyglot). Copy one into
your scratch directory before editing it, and don't commit the IDE state it creates (`.openidea/`).
## Flows worth driving
⌘⇧O Goto File · ⌘⇧F Find in Files (preview scroll + highlight) · ⌘⇧A Find Action · editor edit/undo/autosave ·
Terminal (Unicode, venv) · Commit view at the default narrow width · Problems · Run → Stop · Project view
New / Delete (nested `a/b.txt` names) · ⌘, Settings search (+ Keymap filter) · Git Log on a repo without commits.
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/eval
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/issue-fix
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/verify
Binary file not shown.

Before

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 169 KiB

+70 -28
View File
@@ -28,7 +28,9 @@ jobs:
# shared runners to others. Pushes, the merge queue and manual runs always run everything.
changes:
name: Changes
runs-on: ubuntu-latest
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
timeout-minutes: 5
permissions:
pull-requests: read
@@ -108,10 +110,10 @@ jobs:
strategy:
fail-fast: false
matrix:
os: [macos-latest, ubuntu-22.04, windows-latest]
os: [macos-latest, ubuntu-latest, windows-latest]
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ matrix.os == 'ubuntu-22.04' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
@@ -144,8 +146,8 @@ jobs:
- name: Linux deps
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf)
dpkg -s "${pkgs[@]}" >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y "${pkgs[@]}"; }
# tauri-build checks that frontendDist exists.
- run: pnpm install --frozen-lockfile && mkdir -p dist
shell: bash
@@ -155,6 +157,13 @@ jobs:
# Test fixtures write LF files; keep Git from converting them on checkout.
- run: git config --global core.autocrlf false
- run: cargo nextest run --workspace --no-fail-fast
- name: Remote backend with Docker Compose
# Self-hosted runner containers do not mount /var/run/docker.sock (scripts/selfhost-runner/README.md).
if: runner.os == 'Linux' && runner.environment != 'self-hosted'
run: |
docker pull busybox:latest
cargo nextest run -p ide-host --test remote_daemon --run-ignored only \
-E 'test(=compose_service_survives_disconnect_and_is_removed_on_stop)'
# nextest skips doctests; ide-command's are its compile-fail tests.
- if: runner.os == 'Linux'
run: cargo test --doc -p ide-command
@@ -169,7 +178,7 @@ jobs:
name: Rust checks
needs: [changes, rust]
if: always()
runs-on: ubuntu-latest
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
timeout-minutes: 5
steps:
- env:
@@ -186,16 +195,27 @@ jobs:
needs: changes
if: needs.changes.outputs.server == 'true'
timeout-minutes: 40
runs-on: ubuntu-22.04
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
with: { targets: x86_64-unknown-linux-musl }
- uses: Swatinem/rust-cache@v2
if: runner.environment != 'self-hosted'
with: { key: server-musl }
- run: sudo apt-get update && sudo apt-get install -y musl-tools
- name: Persistent Cargo target dir
if: runner.environment == 'self-hosted'
shell: bash
run: |
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
if [ "${size:-0}" -gt 40000 ]; then
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
rm -rf "$CARGO_TARGET_DIR"
fi
- run: dpkg -s musl-tools >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y musl-tools; }
- run: cargo build --locked -p ide-host --bin openidea-server --target x86_64-unknown-linux-musl
- run: target/x86_64-unknown-linux-musl/debug/openidea-server --version
- run: '"${CARGO_TARGET_DIR:-target}/x86_64-unknown-linux-musl/debug/openidea-server" --version'
# The plugin SDK, the official plugins and the test fixtures build in their
# own workspaces (the root excludes them), so the jobs above don't see them.
@@ -204,18 +224,31 @@ jobs:
needs: changes
if: needs.changes.outputs.plugins == 'true'
timeout-minutes: 30
runs-on: ubuntu-22.04
env:
CARGO_TARGET_DIR: ${{ github.workspace }}/target-plugins
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
with: { targets: wasm32-wasip2, components: "clippy, rustfmt" }
- if: runner.environment != 'self-hosted'
shell: bash
run: echo "CARGO_TARGET_DIR=$GITHUB_WORKSPACE/target-plugins" >> "$GITHUB_ENV"
- uses: Swatinem/rust-cache@v2
if: runner.environment != 'self-hosted'
with:
key: plugins
cache-directories: target-plugins
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Persistent Cargo target dir
if: runner.environment == 'self-hosted'
shell: bash
run: |
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
if [ "${size:-0}" -gt 40000 ]; then
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
rm -rf "$CARGO_TARGET_DIR"
fi
echo "CARGO_TARGET_DIR=$CARGO_TARGET_DIR/plugins" >> "$GITHUB_ENV"
- name: Format, lint (host and wasm) and test each crate
shell: bash
run: |
@@ -232,7 +265,7 @@ jobs:
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with: { node-version: 22 }
with: { node-version: 22, package-manager-cache: false }
# Plugin web pages (`web-src/`, their own pnpm projects): typecheck and test.
- name: Web pages typecheck and test
shell: bash
@@ -256,7 +289,7 @@ jobs:
needs: changes
if: needs.changes.outputs.deny == 'true'
timeout-minutes: 15
runs-on: ubuntu-latest
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
@@ -268,13 +301,19 @@ jobs:
needs: changes
if: needs.changes.outputs.frontend == 'true'
timeout-minutes: 30
runs-on: ubuntu-22.04
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
# scripts/smoke-paths.test.ts runs `cargo metadata`, which is not preinstalled in the runner container.
- uses: dtolnay/rust-toolchain@stable
if: runner.environment == 'self-hosted'
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with: { node-version: 22, cache: pnpm }
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- run: pnpm install --frozen-lockfile
- run: pnpm typecheck
- run: pnpm lint
@@ -289,38 +328,41 @@ jobs:
needs: changes
if: needs.changes.outputs.catalog == 'true'
timeout-minutes: 15
runs-on: ubuntu-latest
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with: { node-version: 22, cache: pnpm }
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- run: pnpm install --frozen-lockfile
- run: pnpm vitest run src/platform/locales/textCatalog.test.ts
e2e:
name: E2E (${{ matrix.shard }}/2)
name: E2E (${{ matrix.shard }}/4)
needs: changes
if: needs.changes.outputs.e2e == 'true'
timeout-minutes: 30
runs-on: ubuntu-24.04
timeout-minutes: 45
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
strategy:
fail-fast: false
matrix:
shard: [1, 2]
# Browsers and their system libraries are preinstalled; keep the tag in step with @playwright/test.
container: mcr.microsoft.com/playwright:v1.64.1-noble
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with: { node-version: 22, cache: pnpm }
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- run: pnpm install --frozen-lockfile
- run: pnpm e2e --shard=${{ matrix.shard }}/2
env:
HOME: /root
- run: pnpm exec playwright install --with-deps chromium
- run: pnpm e2e --shard=${{ matrix.shard }}/4
- uses: actions/upload-artifact@v6
if: failure()
with:
+98 -24
View File
@@ -23,6 +23,7 @@ on:
- "Cargo.lock"
- "src/features/run/**"
- "src/features/debugger/**"
- "src/features/build/**"
- "src/features/build-tools/**"
- "src/platform/**"
- "src/workbench/**"
@@ -57,6 +58,9 @@ on:
paths: *paths
workflow_dispatch:
permissions:
contents: read
concurrency:
group: language-smoke-${{ github.ref }}
# A new push supersedes a PR's run; on main every merge runs to the end (and saves the cache).
@@ -72,7 +76,9 @@ jobs:
# run none; anything else runs them all. Pushes and manual runs always run them all.
changes:
name: Changes
runs-on: ubuntu-latest
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
timeout-minutes: 5
permissions:
pull-requests: read
@@ -100,7 +106,7 @@ jobs:
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
@@ -132,41 +138,105 @@ jobs:
done < files.txt
echo "languages=$(emit "$langs")" | tee -a "$GITHUB_OUTPUT"
smoke:
name: Language smoke (${{ matrix.language }})
# Builds the smoke test binaries and openidea-server once for every language below.
build:
name: Build
needs: changes
if: needs.changes.outputs.languages != '[]'
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
timeout-minutes: 30
env:
# Line tables keep test backtraces readable and the binaries handed on small without
# stripping local-variable debuginfo from fixtures debugged in the smoke job (CodeLLDB).
CARGO_PROFILE_DEV_DEBUG: line-tables-only
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
if: runner.environment != 'self-hosted'
with:
shared-key: language-smoke
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Persistent Cargo target dir
if: runner.environment == 'self-hosted'
shell: bash
run: |
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
if [ "${size:-0}" -gt 40000 ]; then
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
rm -rf "$CARGO_TARGET_DIR"
fi
- run: |
set -euo pipefail
mkdir -p smoke-bin
cargo test --locked -p ide-host --test language_smoke --test project_smoke --no-run --message-format=json \
| jq -r 'select(.reason == "compiler-artifact" and .executable != null and .target.kind == ["test"]) | "\(.target.name) \(.executable)"' \
| while read -r name exe; do cp "$exe" "smoke-bin/$name"; done
cargo build --locked -p ide-host --bin openidea-server
cp "${CARGO_TARGET_DIR:-target}/debug/openidea-server" smoke-bin/
ls -l smoke-bin
test -x smoke-bin/language_smoke && test -x smoke-bin/project_smoke
# A tar keeps the executable bits, which artifacts drop.
tar -cf smoke-bin.tar smoke-bin
- uses: actions/upload-artifact@v6
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
smoke:
name: Language smoke (${{ matrix.language }})
needs: [changes, build]
strategy:
fail-fast: false
matrix:
language: ${{ fromJSON(needs.changes.outputs.languages) }}
# C/C++ debug with GDB, whose DAP interpreter needs 14+: 22.04 ships 12.1, 24.04 ships 15.
runs-on: ${{ (matrix.language == 'c' || matrix.language == 'cpp') && 'ubuntu-24.04' || 'ubuntu-22.04' }}
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
timeout-minutes: 40
# Self-hosted runner slots have distinct checkout paths (/persist/slot-<N>/work/...); override
# the compiled-in CARGO_MANIFEST_DIR so binaries from the Build job find this slot's fixtures.
env:
CARGO_MANIFEST_DIR: ${{ github.workspace }}/crates/ide-host
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
# Tool versions, shared with the evals (pnpm eval).
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
- uses: dtolnay/rust-toolchain@stable
with: { components: "rust-analyzer, rustfmt" }
# One build cache for every language; main saves it.
- uses: Swatinem/rust-cache@v2
with:
shared-key: language-smoke
save-if: ${{ github.ref == 'refs/heads/main' && matrix.language == 'rust' }}
- uses: actions/download-artifact@v6
with: { name: smoke-bin }
- run: |
tar -xf smoke-bin.tar && rm smoke-bin.tar
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
- uses: pnpm/action-setup@v4
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v4
with: { node-version: 22, cache: pnpm }
- uses: actions/setup-node@v5
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- if: matrix.language == 'typescript'
run: npm install --global "@vtsls/language-server@$VTSLS" "typescript@$TYPESCRIPT"
# The smoke builds the c-app fixture and debugs it with GDB's own DAP interpreter.
# The smoke checks C/C++ with clangd and debugs c-app with GDB's own DAP interpreter (GDB 14+).
- if: matrix.language == 'c' || matrix.language == 'cpp'
shell: bash
run: |
sudo apt-get update
sudo apt-get install -y gdb
pkgs=()
command -v clangd >/dev/null || pkgs+=(clangd)
command -v gdb >/dev/null || pkgs+=(gdb)
if [ "${#pkgs[@]}" -gt 0 ]; then
sudo apt-get update
sudo apt-get install -y "${pkgs[@]}"
fi
major=$(gdb --version | head -n1 | grep -Eo '[0-9]+\.[0-9]+' | head -n1 | cut -d. -f1)
if [ "${major:-0}" -lt 14 ]; then
echo "::error::GDB 14+ is required for its DAP interpreter; recreate the runner from scripts/selfhost-runner (Ubuntu 24.04)."
exit 1
fi
- if: matrix.language == 'python'
uses: actions/setup-python@v5
@@ -185,6 +255,7 @@ jobs:
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
- if: matrix.language == 'java'
run: |
command -v mvn >/dev/null || { sudo apt-get update && sudo apt-get install -y maven; }
mkdir -p "$RUNNER_TEMP/jdtls"
curl -fsSL "https://download.eclipse.org/jdtls/milestones/${JDTLS%-*}/jdt-language-server-$JDTLS.tar.gz" \
| tar xz -C "$RUNNER_TEMP/jdtls"
@@ -209,17 +280,20 @@ jobs:
- if: matrix.language == 'php'
run: npm install --global "intelephense@$INTELEPHENSE"
- run: cargo test --locked -p ide-host --test language_smoke --no-run
- run: cargo test --locked -p ide-host --test language_smoke -- --ignored --exact ${{ matrix.language }}
# The binaries from the build job, run from the crate directory as `cargo test` does.
- working-directory: crates/ide-host
run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }}
- if: matrix.language == 'java'
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
working-directory: crates/ide-host
run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
- if: matrix.language == 'kotlin'
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact gradle_sync
working-directory: crates/ide-host
run: ../../smoke-bin/project_smoke --ignored --exact gradle_sync
- if: matrix.language == 'python'
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact python_venv
working-directory: crates/ide-host
run: ../../smoke-bin/project_smoke --ignored --exact python_venv
- run: pnpm install --frozen-lockfile
- run: cargo build --locked -p ide-host --bin openidea-server
- run: pnpm smoke smoke/run.test.ts -t "^${{ matrix.language }}$"
- run: pnpm smoke smoke/debug.test.ts -t "^${{ matrix.language }}$"
# The IDE installs the debugger from GitHub releases: authenticated, against rate limits.
+5 -7
View File
@@ -33,14 +33,12 @@ target/
test-results/
playwright-report/
# Local AI agent files. Shared skills live in .agents/skills; .claude/skills links to them.
# Local AI agent files
AGENTS.md
CLAUDE.md
CLAUDE.local.md
.claude/*
!.claude/skills/
.claude/skills/*
!.claude/skills/verify
!.claude/skills/issue-fix
!.claude/skills/eval
.agents/
.claude/
# Local reference screenshots
pycharm-screenshots/
+15
View File
@@ -0,0 +1,15 @@
{
"detector": {
"ignoreRules": [],
"ignoreFiles": [],
"ignoreValues": [
{
"rule": "gradient-text",
"value": "*",
"files": ["src/features/agents/Session.module.css"],
"createdAt": "2026-11-24T14:58:12.514Z",
"reason": "agent: .shimmer is an animated in-progress sweep on running-step labels (commit 18b286e7e, comment documents intent), not decorative gradient text"
}
]
}
}
+557
View File
@@ -0,0 +1,557 @@
{
"schemaVersion": 2,
"generatedAt": "2026-11-24T15:06:05+00:00",
"title": "Design System: OpenIDEA",
"extensions": {
"colorMeta": {
"workbench-blue": {
"role": "primary",
"displayName": "Workbench Blue",
"canonical": "#3871e1",
"tonalRamp": [
"oklch(15% 0.073 262)",
"oklch(25% 0.121 262)",
"oklch(35% 0.17 262)",
"oklch(48% 0.17 262)",
"oklch(60% 0.17 262)",
"oklch(72% 0.136 262)",
"oklch(84% 0.078 262)",
"oklch(95% 0.024 262)"
]
},
"link-blue": {
"role": "primary",
"displayName": "Link Blue",
"canonical": "#2f5eb9",
"tonalRamp": [
"oklch(15% 0.064 262)",
"oklch(25% 0.107 262)",
"oklch(35% 0.15 262)",
"oklch(48% 0.15 262)",
"oklch(60% 0.15 262)",
"oklch(72% 0.12 262)",
"oklch(84% 0.069 262)",
"oklch(95% 0.021 262)"
]
},
"selection-wash": {
"role": "primary",
"displayName": "Selection Wash",
"canonical": "#d0dffe",
"tonalRamp": [
"oklch(15% 0.034 262)",
"oklch(25% 0.057 262)",
"oklch(35% 0.08 262)",
"oklch(48% 0.08 262)",
"oklch(60% 0.08 262)",
"oklch(72% 0.064 262)",
"oklch(84% 0.037 262)",
"oklch(95% 0.011 262)"
]
},
"tab-wash": {
"role": "primary",
"displayName": "Tab Wash",
"canonical": "#e3ebfe",
"tonalRamp": [
"oklch(15% 0.026 262)",
"oklch(25% 0.043 262)",
"oklch(35% 0.06 262)",
"oklch(48% 0.06 262)",
"oklch(60% 0.06 262)",
"oklch(72% 0.048 262)",
"oklch(84% 0.027 262)",
"oklch(95% 0.009 262)"
]
},
"danger": {
"role": "status",
"displayName": "Danger",
"canonical": "#c54e58",
"tonalRamp": [
"oklch(15% 0.064 18)",
"oklch(25% 0.107 18)",
"oklch(35% 0.15 18)",
"oklch(48% 0.15 18)",
"oklch(60% 0.15 18)",
"oklch(72% 0.12 18)",
"oklch(84% 0.069 18)",
"oklch(95% 0.021 18)"
]
},
"warning": {
"role": "status",
"displayName": "Warning",
"canonical": "#a56906",
"tonalRamp": [
"oklch(15% 0.056 70)",
"oklch(25% 0.093 70)",
"oklch(35% 0.13 70)",
"oklch(48% 0.13 70)",
"oklch(60% 0.13 70)",
"oklch(72% 0.104 70)",
"oklch(84% 0.059 70)",
"oklch(95% 0.019 70)"
]
},
"success": {
"role": "status",
"displayName": "Success",
"canonical": "#338555",
"tonalRamp": [
"oklch(15% 0.047 152)",
"oklch(25% 0.079 152)",
"oklch(35% 0.11 152)",
"oklch(48% 0.11 152)",
"oklch(60% 0.11 152)",
"oklch(72% 0.088 152)",
"oklch(84% 0.05 152)",
"oklch(95% 0.016 152)"
]
},
"frame-grey": {
"role": "neutral",
"displayName": "Frame Grey",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"island-white": {
"role": "neutral",
"displayName": "Island White",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"raised-paper": {
"role": "neutral",
"displayName": "Raised Paper",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink": {
"role": "neutral",
"displayName": "Ink",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-secondary": {
"role": "neutral",
"displayName": "Ink Secondary",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-muted": {
"role": "neutral",
"displayName": "Ink Muted",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-faint": {
"role": "neutral",
"displayName": "Ink Faint",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"hairline": {
"role": "neutral",
"displayName": "Hairline",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"control-edge": {
"role": "neutral",
"displayName": "Control Edge",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"frame-grey-dark": {
"role": "neutral",
"displayName": "Frame Grey (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"island-dark": {
"role": "neutral",
"displayName": "Island (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-dark": {
"role": "neutral",
"displayName": "Ink (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-strong-dark": {
"role": "neutral",
"displayName": "Ink Strong (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"ink-muted-dark": {
"role": "neutral",
"displayName": "Ink Muted (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"control-edge-dark": {
"role": "neutral",
"displayName": "Control Edge (Dark)",
"tonalRamp": [
"oklch(15% 0.005 265)",
"oklch(25% 0.009 265)",
"oklch(35% 0.012 265)",
"oklch(48% 0.012 265)",
"oklch(60% 0.012 265)",
"oklch(72% 0.01 265)",
"oklch(84% 0.005 265)",
"oklch(95% 0.002 265)"
]
},
"selection-wash-dark": {
"role": "primary",
"displayName": "Selection Wash (Dark)",
"canonical": "#2a4371",
"tonalRamp": [
"oklch(15% 0.034 262)",
"oklch(25% 0.057 262)",
"oklch(35% 0.08 262)",
"oklch(48% 0.08 262)",
"oklch(60% 0.08 262)",
"oklch(72% 0.064 262)",
"oklch(84% 0.037 262)",
"oklch(95% 0.011 262)"
]
}
},
"typographyMeta": {
"title": {
"displayName": "Title",
"purpose": "Tool window titles, section headers, dialog titles; weight 600 is the main emphasis."
},
"body": {
"displayName": "Body",
"purpose": "Default UI text, menus, rows, buttons."
},
"label": {
"displayName": "Label",
"purpose": "Secondary metadata, chips, status bar, table cells; the most-used size."
},
"label-tiny": {
"displayName": "Label Tiny",
"purpose": "Stripe labels, counters, badges."
},
"input-large": {
"displayName": "Input Large",
"purpose": "Search Everywhere and other large query fields."
},
"code": {
"displayName": "Code",
"purpose": "Editor, console, terminal and every monospace preview; size and weights are user settings."
}
},
"shadows": [
{
"name": "shadow-popup",
"value": "0 6px 20px rgba(0, 0, 0, 0.12)",
"purpose": "Popups, menus, completion, floating toolbar (Light; Dark uses 0.45 alpha)."
},
{
"name": "shadow-dialog",
"value": "0 0 0 0.5px rgba(0, 0, 0, 0.1), 0 10px 24px rgba(0, 0, 0, 0.1), 0 24px 72px rgba(0, 0, 0, 0.2)",
"purpose": "Window-style shadow for dialogs (Light)."
},
{
"name": "shadow-tooltip",
"value": "0 4px 12px rgba(0, 0, 0, 0.12)",
"purpose": "Hover tooltips (Light)."
},
{
"name": "shadow-balloon",
"value": "0 8px 24px rgba(0, 0, 0, 0.14)",
"purpose": "Notification balloons (Light)."
}
],
"motion": [
{
"name": "ease",
"value": "cubic-bezier(0.2, 0, 0, 1)",
"purpose": "Default easing for every state transition."
},
{
"name": "dur-fast",
"value": "80ms",
"purpose": "Hover, press and focus changes on controls."
},
{
"name": "dur",
"value": "140ms",
"purpose": "Standard transitions such as popup fades."
},
{
"name": "dur-slow",
"value": "220ms",
"purpose": "Upper bound for any state transition."
}
],
"density": [
{
"name": "default",
"value": "rows 24px, fields/buttons 28px, titlebar 40px, tab bar 38px, status bar 30px, island gap 6px, island radius 10px"
},
{
"name": "compact",
"value": "rows 22px, fields/buttons 24px, titlebar/headers 32px, tab bar 32px, status bar 24px, island gap 4px, island radius 8px, chrome text -1px"
}
]
},
"components": [
{
"name": "Primary Button",
"kind": "button",
"refersTo": "button-primary",
"description": "The one default action in a dialog or form.",
"html": "<button class=\"ds-btn ds-btn-primary\">OK</button>",
"css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-primary { background:var(--bg-button-primary,#3871e1); color:var(--fg-button-primary,#fff); } .ds-btn-primary:hover { background:var(--bg-button-primary-hover,#3366cc); }"
},
{
"name": "Secondary Button",
"kind": "button",
"refersTo": "button-secondary",
"description": "Every other dialog action: Cancel, Apply, Browse.",
"html": "<button class=\"ds-btn ds-btn-secondary\">Cancel</button>",
"css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-secondary { background:var(--bg-button,#fff); color:var(--fg-strong,#000); box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); } .ds-btn-secondary:hover { background:color-mix(in srgb, var(--bg-button,#fff) 94%, var(--fg-strong,#000)); }"
},
{
"name": "Ghost Button",
"kind": "button",
"refersTo": "button-ghost",
"description": "Low-emphasis text actions in headers and inline rows.",
"html": "<button class=\"ds-btn-ghost\">Show all</button>",
"css": ".ds-btn-ghost { display:inline-flex; align-items:center; height:var(--h-button,28px); padding:0 8px; border:0; background:transparent; border-radius:var(--radius-control,4px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-ui,13px); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-btn-ghost:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-btn-ghost:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-btn-ghost:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; }"
},
{
"name": "Toolbar Icon Button",
"kind": "button",
"refersTo": "icon-button",
"description": "Toolbar and tool window header actions; frameless at rest, toggles show Selection Wash.",
"html": "<div class=\"ds-iconbar\"><button class=\"ds-icon-btn\" aria-label=\"Refresh\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M13 8a5 5 0 1 1-1.46-3.54M13 3v2.5h-2.5\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg></button><button class=\"ds-icon-btn\" aria-label=\"Show options\" aria-pressed=\"true\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M2.5 4.5h11M2.5 8h11M2.5 11.5h11\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\"/></svg></button></div>",
"css": ".ds-iconbar { display:flex; gap:2px; } .ds-icon-btn { display:inline-flex; align-items:center; justify-content:center; width:24px; height:24px; padding:0; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-muted,#6c707e); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-icon-btn:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-icon-btn:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-icon-btn[aria-pressed=\"true\"] { background:var(--bg-toolbar-selected,#d0dffe); color:var(--fg-strong,#000); } .ds-icon-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
},
{
"name": "Text Field",
"kind": "input",
"refersTo": "input",
"description": "Framed text field; the frame doubles in Workbench Blue on focus.",
"html": "<input class=\"ds-input\" placeholder=\"Project name\" />",
"css": ".ds-input { height:var(--h-field,28px); padding:0 8px; border:0; appearance:none; border-radius:var(--radius-control,4px); background:var(--bg-field,#fff); color:var(--fg-strong,#000); font-family:var(--font-ui); font-size:var(--fs-ui,13px); outline:none; box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); transition:box-shadow var(--dur-fast,80ms) var(--ease); } .ds-input::placeholder { color:var(--fg-faint,#9fa2a8); } .ds-input:focus { box-shadow:inset 0 0 0 1px var(--focus-ring,#3871e1), 0 0 0 1px var(--focus-ring,#3871e1); }"
},
{
"name": "Chip",
"kind": "chip",
"refersTo": "chip",
"description": "Flat read-only fact or picker trigger, sized like the toolbar widgets.",
"html": "<button class=\"ds-chip\"><svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\"><circle cx=\"5\" cy=\"4\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"5\" cy=\"12\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"11\" cy=\"6\" r=\"1.5\" stroke=\"currentColor\"/><path d=\"M5 5.5v5M11 7.5c0 2-2 2.5-6 3\" stroke=\"currentColor\"/></svg><span>main</span></button>",
"css": ".ds-chip { display:inline-flex; align-items:center; gap:var(--space-1,4px); height:22px; padding:0 6px; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-small,12px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease); } .ds-chip svg { color:var(--fg-muted,#6c707e); } .ds-chip:hover { background:var(--bg-toolbar-hover,#00000012); } .ds-chip:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
},
{
"name": "Tree Rows",
"kind": "custom",
"refersTo": "list-row-selected",
"description": "24px rows with an inset rounded selection wash; unfocused selection turns neutral.",
"html": "<div class=\"ds-tree\" tabindex=\"0\"><div class=\"ds-row\">src</div><div class=\"ds-row ds-row-sel\">main.tsx</div><div class=\"ds-row\">workbench</div></div>",
"css": ".ds-tree { width:220px; padding:4px var(--tree-inset,6px); background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); color:var(--fg,#000); outline:none; } .ds-row { height:var(--h-row,24px); display:flex; align-items:center; padding:0 8px; border-radius:var(--radius-row,4px); } .ds-row:hover { background:var(--bg-tree-hover,#0000000a); } .ds-row-sel, .ds-row-sel:hover { background:var(--bg-tree-selected-inactive,#e9eaee); } .ds-tree:focus .ds-row-sel { background:var(--bg-tree-selected,#d0dffe); }"
},
{
"name": "Island on Frame",
"kind": "card",
"description": "The signature layout unit: rounded islands 6px apart on the grey frame, flat at rest.",
"html": "<div class=\"ds-frame\"><div class=\"ds-island ds-side\"><div class=\"ds-head\">Project</div></div><div class=\"ds-island ds-main\"><code>fn main() {}</code></div></div>",
"css": ".ds-frame { display:flex; gap:var(--island-gap,6px); padding:var(--island-gap,6px); background:var(--bg-frame,#e9eaee); height:160px; } .ds-island { background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); } .ds-side { width:140px; } .ds-main { flex:1; padding:12px; font-family:var(--font-mono); font-size:var(--fs-code,13px); color:var(--fg-editor,#080808); } .ds-head { height:40px; display:flex; align-items:center; padding:0 12px; font-family:var(--font-ui); font-size:var(--fs-ui,13px); font-weight:600; color:var(--fg-strong,#000); }"
},
{
"name": "Tooltip",
"kind": "custom",
"refersTo": "tooltip",
"description": "Floating hover help: one of the few surfaces allowed a shadow.",
"html": "<div class=\"ds-tooltip\">Run 'main' <span class=\"ds-kbd\">⌃R</span></div>",
"css": ".ds-tooltip { display:inline-flex; gap:8px; align-items:center; padding:6px 10px; border-radius:var(--radius-tooltip,6px); background:var(--bg-tooltip,#fff); color:var(--fg-tooltip,#000); border:1px solid var(--border-tooltip,#d1d3d9); box-shadow:var(--shadow-tooltip,0 4px 12px rgba(0,0,0,.12)); font-family:var(--font-ui); font-size:var(--fs-ui,13px); } .ds-kbd { font-family:var(--font-keys); color:var(--fg-muted,#6c707e); }"
}
],
"narrative": {
"northStar": "The Quiet Workbench",
"overview": "The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.\n\nThe visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.\n\nEvery panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.\n\nThe tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.\n\nExpression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.",
"keyCharacteristics": [
"JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.",
"Grey frame, rounded content islands, tonal layering only.",
"A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.",
"High density on a 4px grid. Compact mode is a first-class variant.",
"Controls are quiet at rest: toolbar buttons and chips have no frame until hover.",
"Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.",
"Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins."
],
"rules": [
{
"name": "The IDEA Reference Rule",
"body": "When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.",
"section": "overview"
},
{
"name": "The One Accent Rule",
"body": "Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.",
"section": "colors"
},
{
"name": "The Token Only Rule",
"body": "Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.",
"section": "colors"
},
{
"name": "The Flat Scale Rule",
"body": "The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.",
"section": "typography"
},
{
"name": "The User Owns Size Rule",
"body": "Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.",
"section": "typography"
},
{
"name": "The Flat at Rest Rule",
"body": "No docked panel, island, row or control gets a shadow. A shadow means \"this floats over the workbench and will go away\". Depth inside the layout is only ever a tonal step.",
"section": "elevation"
}
],
"dos": [
"**Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).",
"**Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.",
"**Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.",
"**Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.",
"**Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.",
"**Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.",
"**Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.",
"**Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`."
],
"donts": [
"**Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.",
"**Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.",
"**Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.",
"**Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.",
"**Don't** put shadows on docked panels, islands, rows or controls.",
"**Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.",
"**Don't** use hex, `rgb()` or named colours in component CSS or inline styles.",
"**Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature."
]
}
}
+26
View File
@@ -147,6 +147,32 @@
"prefer-rest-params": "error",
"prefer-spread": "error"
}
},
{
"files": [
"evals/**/*.ts",
"perf/**/*.ts",
"smoke/**/*.ts",
"src/features/vcs/**/*.ts",
"src/features/vcs/**/*.tsx",
"src/features/run/**/*.ts",
"src/features/run/**/*.tsx",
"src/features/database/**/*.ts",
"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"
}
}
]
}
-151
View File
@@ -1,151 +0,0 @@
# OpenIDEA — contributor guide
Rust + Tauri 2 desktop IDE with full-featured, multi-language code intelligence.
Visual style: dark, low-contrast greys, one cool accent
(`src/styles/tokens.css` is the source of truth for colours and metrics).
## Layout
- `crates/ide-*` — backend crates; one domain each. Depend on `ide-core` for shared
types; never reach into another crate's internals.
- `src-tauri/` — glue only: `state.rs` (AppState / Project), `commands/<domain>.rs`
(desktop-only commands; the adapters of `ide-host` commands are derived), `events.rs`.
No domain logic here.
- `src/bindings.ts` — generated by tauri-specta (`pnpm gen:bindings`). Never edit.
- `src/platform/` — ipc (`call`, `onIdeEvent`, `nextRequestId`), actions registry,
keymap + dispatcher, context keys / `when` clauses, project store.
- `src/workbench/contributions.ts` — extension points (tool windows, status items,
overlays, editor kinds) and cross-feature services (editor, tool windows, notifications).
- `src/ui/` — design-system primitives. `src/features/<name>/` — one feature each,
exporting `activate()` registered in `src/features/index.ts`.
- `languages/<id>.toml` — language definitions (detection, comments, LSP, DAP).
- `crates/ide-host` — the `openidea-server` binary for remote development and the
`openidea-plugin` CLI (plugin starter templates live in its `templates.rs`).
- `wit/` — plugin interface definitions; `plugins/` — sample and bundled plugins.
Plugin docs: `plugins/README.md`, `plugins/themes.md`.
- `java/` — JDT LS extension bundles (`java-usages`, `kotlin-bridge`) and the patched
Lombok agent, embedded into the app by `ide-sdk` / `ide-tools`.
- `e2e/` — Playwright UI tests (`pnpm e2e`). `evals/` — code-intelligence evals (`pnpm eval`).
`fixtures/` — sample projects per language for manual and automated testing.
- `docs/` — the Mintlify documentation site (`docs.json` navigation, `en/` and `zh/` pages);
preview with `npx mint dev` in `docs/`.
## Rules
- IPC coordinates: 0-based lines, **UTF-16** columns/offsets everywhere (`ide-core::text`).
- Every command returns `IdeResult<T>`; convert internal errors at the crate edge.
- Declare a command once, on its implementation: `#[command(trust = …)]` in `ide-host::ops`
plus its module's `domain!` list (Tauri adapter, server handler and bindings are derived);
desktop-only commands use `#[desktop_command(trust = …)]` and `desktop_domain!`.
- Streaming → `tauri::ipc::Channel<T>`; cancellable → UI-allocated `RequestId` +
`cancel_request`. Backend → UI notifications → `IdeEvent` via `EventSink`.
- Long work never blocks the UI thread or a Tauri command thread: use
`spawn_blocking`/rayon, honour `CancellationToken`.
- Frontend features never import each other; communicate via actions, contributions
and services. All user-invocable behaviour is an action with a stable id; default
shortcuts live in `src/platform/keymaps/`.
- Styling: CSS Modules + tokens only (no hex literals in components). Inline SVG
icons from `src/ui/icons.tsx`, never emoji. Real `<button>`/`<input>`; `aria-label` on icon buttons.
`gap` uses the `--space-*` scale (`src/styles/tokens.css`, 4px grid) where a value is on it.
- User-visible text goes through the text catalog: add every new string to both
`src/platform/locales/text/en.json` and `zh.json` (`textCatalog.test.ts` enforces it).
Other locales may lack entries; their UI shows the English text until a translator adds it.
- Keep comments sparse and purposeful; match surrounding style.
- For GUI verification, prefer Tauri MCP; use Computer Use only when Tauri MCP is
unavailable or cannot cover the required checks.
## Issues & PRs
Follow `CONTRIBUTING.md` and `.github/pull_request_template.md`: one problem per PR
(`Closes #<n>` when it resolves an issue), reproduce first, keep the diff focused, short plain description, and a
**How it was verified** section with commands run, results and, when the change alters what users
see, before/after screenshots (not for UI removed along with a feature, copy-only or non-visual changes).
Unclear product decisions → `needs-decision` and stop.
## Skills
Do not use Impeccable or its related skills in this repository, including globally installed copies.
Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
`verify` drives the running app through Tauri MCP and captures screenshot evidence;
`issue-fix` takes an issue from reproduction to one PR;
`eval` takes a failing code-intelligence eval to a fix with before / after numbers.
## Commands
- Optional: `mise install` provisions the contributor toolchain; `mise tasks` lists the task aliases.
See [Development setup](docs/en/contribute/setup.mdx). The direct commands below still work without mise.
- `pnpm tauri dev` — run the app with worktree isolation. Use Node 22.22.2 or later on the 22.x line.
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
this worktree's running MCP bridges and actual ports.
- `pnpm build` — typecheck + bundle frontend.
- `pnpm dogfood:build` / `pnpm dogfood:install` (or `mise run dogfood:build` / `mise run dogfood:install`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
- `pnpm smoke smoke/run.test.ts -t <language>` — run and test that language's fixture through the
run store and a real `openidea-server` (build it first: `cargo build -p ide-host --bin openidea-server`).
- `pnpm smoke smoke/debug.test.ts -t <language>` — debug that fixture's entry point the same way, with
the debugger the IDE installs (on macOS, CodeLLDB and Delve may need Developer Mode:
`sudo DevToolsSecurity -enable`).
- `pnpm test`, `pnpm e2e`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm typecheck`,
`pnpm gen:bindings`.
- `pnpm perf` (UI interaction latency / frames / leaks), `pnpm perf:rust` (criterion
benches vs budgets). Budgets: `perf/budgets.json`.
- `pnpm eval [--only <id>] [--runs n] [--save-baseline]` — Java code intelligence (navigation,
usages, gutter markers) in the production workbench against a release `openidea-server` and
jdtls: time to feedback / first result / complete, results vs `evals/<language>/golden/`.
Report: `target/eval/report.json`. Goldens and `evals/budgets.json` are changed by people only.
Tool versions: `.github/tool-versions.env` (shared with Language smoke).
- `pnpm release:prepare <version>` — the release commit's changes: app version everywhere,
`Cargo.lock`, and the plugin API snapshot when `wit/` moved to a new version.
## Before opening a PR
Run what CI runs for the parts you touched:
- Rust: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,
`cargo nextest run --workspace`. After changing IPC types, run `pnpm gen:bindings` and
commit `src/bindings.ts`; CI fails if it differs.
- Frontend: `pnpm typecheck`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm test`,
`pnpm build`, and `pnpm e2e` for UI flows.
- UI or runtime behaviour: verify in the running app (`.agents/skills/verify`).
## Pitfalls
- Run a subset of frontend tests with `pnpm vitest run <path>`. `pnpm test -- <path>` ignores
the filter and runs the whole suite, which takes several minutes.
- Don't run clippy while iterating: `pnpm tauri dev` compiles anyway. Run
`cargo fmt --all` + `cargo clippy -p <crate> --all-targets -- -D warnings` once, right
before committing. A cold build cache can take around 5 minutes. Run long checks one at
a time, not chained in one shell call that may hit the 10-minute tool timeout.
- `pnpm tauri dev` does a full debug build. Clippy only checks the code, so a passing clippy
doesn't make the first launch fast.
## Parallel worktrees
Several worktrees can be developed and run side by side.
- Create one per task: `git worktree add ../<name> -b <branch> origin/main`, then
`pnpm install` in it.
- Launch with `pnpm tauri dev` / `pnpm dev:app`, not the raw `pnpm exec tauri dev` CLI. The
wrapper starts Vite on a worktree-derived port (advancing if occupied), passes its actual
URL to Tauri, and reports an existing launcher instead of starting another for the same
worktree. HMR uses the Vite port.
- Debug app identity, data, settings, logs and single-instance scope follow the canonical
worktree path captured at build time, independent of launch cwd. Launching the same debug
binary again focuses its existing instance and forwards its path argument. Different
worktrees and the installed release can coexist. `--release` uses normal release identity
and bypasses the development wrapper.
- MCP bridge ports are dynamic (9223–9322). Use `pnpm dev:status`, connect to the reported
port, verify identifier/cwd, and pass `appIdentifier: <port>` explicitly. Do not assume the
default MCP session belongs to this worktree.
- Keep each worktree's Cargo output directory separate; do not point `CARGO_TARGET_DIR` or
`target` symlinks at a shared directory.
- Each worktree's first build is cold (several minutes) and `cargo build` output takes
around 9 GB; tests, clippy and incremental builds add more. Avoid running several heavy builds on one machine at the same time.
- Stop only processes started for the current worktree/session. Never use broad
process-name kills such as `pkill openidea`.
- When done: stop that worktree's app and dev session, delete its build output, then
`git worktree remove ../<name>`.
-1
View File
@@ -1 +0,0 @@
AGENTS.md
-1
View File
@@ -1,7 +1,6 @@
# Contributing to OpenIDEA
These rules apply to everyone, and to any coding agent working on their behalf.
Project layout, coding rules, commands and checks are in [AGENTS.md](AGENTS.md).
## Issues
Generated
+62 -71
View File
@@ -1104,9 +1104,9 @@ checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
[[package]]
name = "cookie"
version = "0.18.2"
version = "0.18.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"
checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a"
dependencies = [
"time",
"version_check",
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4172,7 +4172,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4180,13 +4180,11 @@ dependencies = [
"rayon",
"serde",
"specta",
"tracing",
"tree-sitter",
]
[[package]]
name = "ide-android"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"serde",
@@ -4197,7 +4195,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"blake3",
"chardetng",
@@ -4215,7 +4213,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4229,7 +4227,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4240,7 +4238,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -4251,24 +4249,29 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
"dunce",
"encoding_rs",
"libc",
"portable-pty",
"serde",
"serde_json",
"sha2 0.10.9",
"specta",
"specta-typescript",
"tempfile",
"thiserror 2.0.21",
"tokio-util",
"tracing",
"windows-sys 0.61.2",
]
[[package]]
name = "ide-coverage"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-run",
@@ -4277,12 +4280,11 @@ dependencies = [
"serde_json",
"specta",
"tempfile",
"tracing",
]
[[package]]
name = "ide-dap"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4311,12 +4313,11 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"bb8",
"blake3",
"dirs 6.0.0",
"dunce",
"flate2",
"futures",
@@ -4324,6 +4325,7 @@ dependencies = [
"ide-http",
"ide-sdk",
"ide-ssh",
"libc",
"notify",
"open",
"oracledb",
@@ -4343,13 +4345,14 @@ dependencies = [
"toml_edit 0.25.17+spec-1.1.0",
"tracing",
"uuid",
"windows-sys 0.61.2",
"zeroize",
"zip",
]
[[package]]
name = "ide-docker"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"serde",
@@ -4362,7 +4365,7 @@ dependencies = [
[[package]]
name = "ide-drag-out"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4376,13 +4379,12 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"blake3",
"dunce",
"ed25519-dalek",
"ide-core",
"parking_lot",
"semver",
"serde",
@@ -4397,7 +4399,7 @@ dependencies = [
[[package]]
name = "ide-flutter"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-android",
"ide-core",
@@ -4408,7 +4410,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4420,7 +4422,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4433,10 +4435,11 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"criterion",
"ide-core",
"ide-heap",
"libc",
"memmap2",
"proptest",
@@ -4451,7 +4454,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4519,6 +4522,7 @@ dependencies = [
"toml 0.9.12+spec-1.1.0",
"tracing",
"tracing-subscriber",
"url",
"uuid",
"windows-sys 0.61.2",
"zip",
@@ -4526,7 +4530,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"hyper-util",
"ide-core",
@@ -4540,19 +4544,19 @@ dependencies = [
"specta",
"tempfile",
"tokio",
"tracing",
"uuid",
]
[[package]]
name = "ide-index"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"blake3",
"criterion",
"dunce",
"globset",
"ide-core",
"ide-index",
"ide-language",
"ignore",
"nucleo-matcher",
@@ -4568,7 +4572,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4580,10 +4584,9 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"encoding_rs",
"futures",
"ide-core",
"parking_lot",
"serde",
@@ -4597,7 +4600,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"libc",
"tempfile",
@@ -4606,7 +4609,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"futures",
"serde",
@@ -4617,7 +4620,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"blake3",
"criterion",
@@ -4676,7 +4679,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"criterion",
"dunce",
@@ -4705,7 +4708,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"bytes",
"dunce",
@@ -4724,9 +4727,8 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"futures",
"ide-core",
"ide-vfs",
"jupyter-protocol",
@@ -4739,7 +4741,6 @@ dependencies = [
"specta-typescript",
"tempfile",
"tokio",
"tracing",
"uuid",
"windows-sys 0.61.2",
"zeromq",
@@ -4747,7 +4748,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"blake3",
"dunce",
@@ -4759,7 +4760,6 @@ dependencies = [
"serde_json",
"specta",
"tempfile",
"thiserror 2.0.21",
"tokio",
"tracing",
"url",
@@ -4770,7 +4770,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4784,7 +4784,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"dunce",
"futures",
@@ -4804,7 +4804,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"dunce",
"encoding_rs",
@@ -4828,7 +4828,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-tools",
@@ -4844,8 +4844,9 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
"dunce",
"flate2",
@@ -4857,6 +4858,7 @@ dependencies = [
"quick-xml 0.42.0",
"serde",
"serde_json",
"sha2 0.10.9",
"specta",
"tar",
"tempfile",
@@ -4868,7 +4870,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"criterion",
"encoding_rs",
@@ -4889,7 +4891,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"parking_lot",
@@ -4902,7 +4904,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4927,7 +4929,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-language",
@@ -4940,7 +4942,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-language",
@@ -4955,7 +4957,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"ide-core",
"libc",
@@ -4969,7 +4971,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"criterion",
"ide-core",
@@ -4982,7 +4984,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"flate2",
"hex",
@@ -5003,7 +5005,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"blake3",
"dunce",
@@ -5025,7 +5027,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"chardetng",
"dunce",
@@ -5052,7 +5054,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5068,7 +5070,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"blake3",
"dunce",
@@ -6697,7 +6699,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.50"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -6706,14 +6708,11 @@ dependencies = [
"dunce",
"gtk",
"ide-agent",
"ide-analysis",
"ide-android",
"ide-build",
"ide-cli",
"ide-clipboard",
"ide-command",
"ide-core",
"ide-coverage",
"ide-dap",
"ide-db",
"ide-docker",
@@ -6723,24 +6722,16 @@ dependencies = [
"ide-github",
"ide-host",
"ide-http",
"ide-index",
"ide-jsonrpc",
"ide-language",
"ide-lsp",
"ide-mcp",
"ide-notebook",
"ide-plugin",
"ide-profiler",
"ide-remote",
"ide-run",
"ide-scaffold",
"ide-sdk",
"ide-search",
"ide-spell",
"ide-ssh",
"ide-syntax",
"ide-terminal",
"ide-text",
"ide-tools",
"ide-vcs",
"ide-vfs",
+1 -3
View File
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.50"
version = "0.1.51"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
@@ -69,13 +69,11 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time"
tokio-util = { version = "0.7", features = ["rt"] }
parking_lot = "0.12"
rayon = "1"
dashmap = "6"
futures = "0.3"
tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "__rustls-tls"] }
# errors & diagnostics
thiserror = "2"
anyhow = "1"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
+323
View File
@@ -0,0 +1,323 @@
---
name: OpenIDEA
description: The IDE you know, rebuilt in Rust.
colors:
workbench-blue: "#3871e1"
link-blue: "#2f5eb9"
frame-grey: "#e9eaee"
island-white: "#ffffff"
raised-paper: "#f7f8f9"
ink: "#000000"
ink-secondary: "#5f6269"
ink-muted: "#6c707e"
ink-faint: "#9fa2a8"
hairline: "#e9eaee"
control-edge: "#d1d3d9"
selection-wash: "#d0dffe"
tab-wash: "#e3ebfe"
danger: "#c54e58"
warning: "#a56906"
success: "#338555"
frame-grey-dark: "#26282c"
island-dark: "#191a1c"
ink-dark: "#d1d3d9"
ink-strong-dark: "#dfe1e5"
ink-muted-dark: "#8c8f95"
control-edge-dark: "#40434a"
selection-wash-dark: "#2a4371"
typography:
title:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "13px"
fontWeight: 600
lineHeight: 1.4
body:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "13px"
fontWeight: 400
lineHeight: 1.4
label:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "12px"
fontWeight: 400
lineHeight: 1.4
label-tiny:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "11px"
fontWeight: 400
lineHeight: 1.4
input-large:
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
fontSize: "15px"
fontWeight: 400
code:
fontFamily: "JetBrains Mono, JetBrains Mono Variable, ui-monospace, Menlo, monospace"
fontSize: "13px"
fontWeight: 400
lineHeight: "22px"
fontFeature: "\"liga\" 0"
rounded:
small: "4px"
control: "4px"
row: "4px"
selection: "5px"
tab: "6px"
toolbar-button: "6px"
tooltip: "6px"
popup: "8px"
island: "10px"
popup-large: "10px"
dialog: "10px"
spacing:
space-0-5: "2px"
space-1: "4px"
space-1-5: "6px"
space-2: "8px"
space-3: "12px"
space-4: "16px"
components:
button-primary:
backgroundColor: "{colors.workbench-blue}"
textColor: "{colors.island-white}"
typography: "{typography.body}"
rounded: "{rounded.control}"
padding: "0 16px"
height: "28px"
button-secondary:
backgroundColor: "{colors.island-white}"
textColor: "{colors.ink}"
typography: "{typography.body}"
rounded: "{rounded.control}"
padding: "0 16px"
height: "28px"
button-ghost:
textColor: "{colors.ink-secondary}"
typography: "{typography.body}"
rounded: "{rounded.control}"
padding: "0 8px"
height: "28px"
icon-button:
textColor: "{colors.ink-muted}"
rounded: "{rounded.toolbar-button}"
size: "24px"
icon-button-selected:
backgroundColor: "{colors.selection-wash}"
textColor: "{colors.ink}"
rounded: "{rounded.toolbar-button}"
size: "24px"
input:
backgroundColor: "{colors.island-white}"
textColor: "{colors.ink}"
typography: "{typography.body}"
rounded: "{rounded.control}"
padding: "0 8px"
height: "28px"
chip:
textColor: "{colors.ink-secondary}"
typography: "{typography.label}"
rounded: "{rounded.toolbar-button}"
padding: "0 6px"
height: "22px"
tooltip:
backgroundColor: "{colors.island-white}"
textColor: "{colors.ink}"
typography: "{typography.body}"
rounded: "{rounded.tooltip}"
padding: "6px 10px"
list-row-selected:
backgroundColor: "{colors.selection-wash}"
textColor: "{colors.ink}"
rounded: "{rounded.row}"
height: "24px"
---
# Design System: OpenIDEA
## Overview
**Creative North Star: "The Quiet Workbench"**
The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.
The visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.
Every panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.
The tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.
Expression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.
### Named Rules
**The IDEA Reference Rule.** When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.
**Key Characteristics:**
- JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.
- Grey frame, rounded content islands, tonal layering only.
- A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.
- High density on a 4px grid. Compact mode is a first-class variant.
- Controls are quiet at rest: toolbar buttons and chips have no frame until hover.
- Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.
- Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins.
## Colors
A near-neutral grey ramp with one cool blue accent. Status, VCS and syntax colours are functional vocabularies with fixed meanings. Values in the frontmatter are Islands Light (the default), and `-dark` keys are the Islands Dark counterparts. High Contrast, the Solarized themes, imported IntelliJ themes and plugin themes override the same tokens, so the names describe roles, not hexes.
### Project colour
- **Project wash** (`--project-color`): a radial tint of the project's colour (22% strength, 600 × 300px) that fades in from the frame's top-left corner, as the IDEA project gradient does. It identifies the project window. It is the one gradient in the chrome.
### Primary
- **Workbench Blue** (`--accent`): primary buttons, the focus ring, the selected-and-active stripe button, and search-match emphasis. The appearance setting can override it, so components reference `--accent`, never the hex.
- **Link Blue** (`--link`): inline links. In Dark it lightens to stay readable on the dark islands.
### Neutral
- **Frame Grey** (`--bg-frame`): the window frame behind the islands, and the stripes (the tool window button bars).
- **Island White** (`--bg-island`, `--bg-app`): editor and tool window surfaces. This is where the work lives.
- **Raised Paper** (`--bg-elev`, `--bg-dialog`): dialog bodies and inline popups, one tonal step off the island.
- **Ink** (`--fg`, `--fg-strong`): primary text. **Ink Secondary / Muted / Faint** (`--fg-secondary`, `--fg-muted`, `--fg-faint`): metadata, icons and placeholders, then disabled text.
- **Hairline** (`--border`): dividers between regions inside an island. **Control Edge** (`--border-button`, `--border-strong`): the 1px inset frame of fields and secondary buttons.
- **Selection Wash** (`--bg-tree-selected`, `--bg-selected`, `--bg-toolbar-selected`): the selected row in focused trees and lists, and pressed-on toolbar toggles. When the tree loses focus, the selection drops to the neutral `--bg-tree-selected-inactive`.
### Functional vocabularies
- **Status:** `--danger`, `--warning`, `--success` and `--info`, each with `--bg-feedback-*` and `--border-feedback-*` pairs for banners.
- **VCS and diff:** `--vcs-*` for file status in trees and tabs, `--gutter-*` for gutter marks, and `--diff-*` for diff fills and their error-stripe marks.
- **Syntax:** `--syn-*`, from the editor colour scheme. Users and plugins replace these per scheme.
### Named Rules
**The One Accent Rule.** Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.
**The Token Only Rule.** Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.
## Typography
**UI Font:** Inter Variable (with system-ui and -apple-system fallbacks)
**Code Font:** JetBrains Mono (with ui-monospace and Menlo fallbacks)
**Key Glyph Font:** the system UI font (`--font-keys`), so shortcut glyphs such as ⌘⇧⌥⌃↵ render as they do in native menus
**Character:** a neutral sans for chrome and a coding mono for content. Neither performs. Hierarchy comes from weight and colour, not size.
### Hierarchy
- **Title** (600, 13px, 1.4): tool window titles, section headers, dialog titles and emphasised names. Weight 600 is the system's main emphasis.
- **Body** (400, 13px, 1.4): default UI text, menus, tree and list rows, and buttons.
- **Label** (400, 12px): the most common size. It covers secondary metadata, chips, status bar items, table cells and hints.
- **Label Tiny** (400, 11px): stripe labels, counters and badges.
- **Input Large** (400, 15px): Search Everywhere and similar large query fields.
- **Code** (400, 13px, 22px line height): the editor, console, terminal and every monospace preview. Ligatures are off by default and follow the `editor.ligatures` setting. Users set the weights (`--fw-code`, `--fw-code-bold`) and the size.
### Named Rules
**The Flat Scale Rule.** The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.
**The User Owns Size Rule.** Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.
## Layout
The window is a grey frame holding docked islands: the editor in the centre, tool windows around it, stripes of tool window buttons on the edges (58px wide), a titlebar with the main toolbar (40px), and a status bar (30px). The status bar sits directly on the frame with no divider. Islands sit 6px apart and have 10px corners. Trees are inset 6px inside their island.
Spacing follows a 4px grid (`--space-0-5` to `--space-4`, 2–16px). It is used for gaps, with component heights doing most of the rhythm work: rows 24px, fields and buttons 28px, small controls 24px or 20px, tabs 28px in a 38px tab bar, and tool window headers 40px.
**Compact mode** (`data-compact`) is a full variant, not an afterthought. Rows drop to 22px, fields and buttons to 24px, the titlebar and headers to 32px, the status bar to 24px, the island gap to 4px and island corners to 8px, and chrome text gets 1px smaller. Every layout must hold in both modes.
The app is a desktop window. It is never a scrolling page: the document never scrolls, and every scroll region is its own scroller inside an island. Dialogs open about 10vh from the top and below the titlebar. Wide reading surfaces, such as an agent conversation, cap their width (900px) inside the island.
## Elevation & Depth
Static layout is flat and layered by tone. The grey frame sits under white islands (in Dark, a lighter frame under darker islands). Shadows exist only on surfaces that float above the layout: popups, menus, dialogs, tooltips, balloons, undocked tool windows and drag ghosts. Dialogs use a window-style shadow, because they are separate windows in spirit.
### Shadow Vocabulary
- **Popup** (`--shadow-popup`; Light `0 6px 20px rgba(0,0,0,0.12)`): popups, menus, completion and the floating editor toolbar.
- **Dialog** (`--shadow-dialog`): a hairline ring plus two soft drops, like a native window shadow.
- **Tooltip** (`--shadow-tooltip`) and **Balloon** (`--shadow-balloon`): small and medium drops for hover help and notifications.
### Named Rules
**The Flat at Rest Rule.** No docked panel, island, row or control gets a shadow. A shadow means "this floats over the workbench and will go away". Depth inside the layout is only ever a tonal step.
## Shapes
Corners scale with the size of the surface. Small controls get 4px (buttons, fields, combos, rows, small icon buttons). Toolbar buttons, chips, tabs and tooltips get 6px, and selection highlights get 5px. Popups get 8–10px, and islands and dialogs get 10px. Compact mode tightens island corners to 8px and combo corners to 2px. Frames are drawn as 1px inset box-shadows rather than borders, so they never shift layout and can double on focus. There are no pills, circles (apart from macOS window buttons and status dots), or rounding beyond 10px.
## Components
Quiet and dependable. Components don't call attention to themselves, they behave the same everywhere, and they come from `src/ui/` primitives before anything custom.
### Buttons
- **Shape:** gently rounded (4px). Minimum width 72px, 28px tall, 16px horizontal padding. The small variant is 24px tall with 10px padding.
- **Primary:** Workbench Blue fill with white text. Hover mixes it toward the strong ink colour (`--accent-hover`). Use it for one default action per dialog.
- **Secondary:** island-coloured with a 1px Control Edge inset frame. Hover darkens the fill by about 6%.
- **Ghost:** no fill or frame, secondary ink colour, 8px padding. Hover shows the toolbar hover wash and strong ink. Pressed is a stronger wash.
- **Focus:** a 2px Workbench Blue outline, 1px outside the button. **Disabled:** transparent fill, faint text and a hairline frame.
- **Motion:** background, colour and frame change over 80ms (`--dur-fast`) with `--ease`. There are no transitions under `prefers-reduced-motion`, and forced-colours mode gets a real border.
### Icon Buttons (toolbar actions)
- 20, 24 or 28px square, with 6px corners (4px at 20px). The icon is muted at rest.
- Hover shows the toolbar hover wash (`--bg-toolbar-hover`, a translucent ink) across the full hit target, and the icon turns strong ink. Pressed shows `--bg-toolbar-pressed`.
- A toggled-on button (`aria-pressed`) shows Selection Wash. The focus ring is drawn 2px inside the button.
- Tone variants (`danger`, `accent`) recolour only the icon.
### Chips
- **Style:** flat, like the main toolbar's project and branch widgets. They are 22px tall with 6px corners, have no fill or frame at rest, and use 12px secondary ink with a muted icon.
- **State:** a chip that opens a picker gets the toolbar hover wash. A read-only chip never changes on hover.
### Inputs / Fields
- **Style:** 28px tall with 8px horizontal padding and 4px corners. Island fill with a 1px Control Edge inset frame. Placeholders use the faint ink.
- **Focus:** the frame turns Workbench Blue and doubles with a 1px outer ring, drawn entirely with box-shadow.
- **Error:** the same doubled ring in `--danger`. **Disabled:** transparent fill, faint text and a hairline frame.
- Search fields have a muted leading icon. Monospace fields use the code font.
### Lists and Trees
- Rows are 24px (22px compact). The selection is a 4–5px rounded wash inset from the island edge, not a full-bleed bar.
- A focused selection uses Selection Wash, and an unfocused one drops to a neutral grey. Hover is a faint translucent wash. Search matches use `--bg-search-match`.
### Popups, Menus and Dialogs
- **Popups and menus:** `--bg-popup` with a 1px popup frame, 10px corners (`--radius-popup-large`) and the popup shadow.
- **Dialogs:** Raised Paper body with 10px corners and the dialog shadow. They behave like IDEA's dialogs, which are separate windows: the modal layer blocks the workbench but never dims it. The footer actions are right-aligned buttons. Focus returns to wherever it came from when the dialog closes.
### Tabs
- 28px tabs (24px compact) in a 38px bar, with 6px corners and 8px horizontal padding.
- As in IDEA, only the part holding focus accents its selected tab (`--bg-tab-selected` with `--border-tab-selected`). Elsewhere the selected tab drops to the neutral inactive pair.
- **Tooltips:** 6px corners with 6px × 10px padding, using `--bg-tooltip` (white in Light, dark grey in Dark) and the tooltip shadow.
### Tool Window Stripes (signature)
The edge bars of tool window buttons are 58px wide on Frame Grey, with icons over 11px labels. Hover and selected states are translucent ink washes. The selected button of the active tool window fills with Workbench Blue and white content. This is the one place the accent fills a large shape in the chrome, and it marks the active tool window.
## Do's and Don'ts
### Do:
- **Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).
- **Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.
- **Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.
- **Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.
- **Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.
- **Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.
- **Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.
- **Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`.
### Don't:
- **Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.
- **Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.
- **Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.
- **Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.
- **Don't** put shadows on docked panels, islands, rows or controls.
- **Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.
- **Don't** use hex, `rgb()` or named colours in component CSS or inline styles.
- **Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature.
+73
View File
@@ -0,0 +1,73 @@
# Product
<!-- impeccable:product-schema 1 -->
## Platform
web
The IDE is a Tauri desktop app for macOS, Windows and Linux. Its UI is a web frontend (React, CSS Modules) inside the system webview, with its own design language rather than each operating system's native one. Scope: this record covers the IDE application only. The openidea.sh docs site and home page (`docs/`) are out of scope.
## Users
- **Primary: JetBrains users who want something lighter.** They already know the IntelliJ IDEA keymap, tool windows and search-everything habits, and find IDEA heavy and slow. They do everyday multi-language development on the desktop: editing, navigating, refactoring, running and debugging, Git, terminal, database and HTTP clients.
- **Primary: developers working with AI coding agents.** They run CLI agents (Claude Code, Codex, Gemini CLI, Copilot, Cursor and others over ACP) inside the IDE as tasks, often several at once, each in its own Git worktree or in the checkout. They review the agents' diffs, answer their permission requests, and give agents the IDE's own tools through the built-in MCP server.
- **Secondary: people moving from VS Code or Eclipse.** Their keymaps are built in.
## Product Purpose
OpenIDEA brings the IntelliJ IDEA way of working to a native app with a Rust core: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages. Success means people who know the IDEA way of working can switch without relearning anything, and it opens, responds and quits much faster while using a fraction of the memory.
## Positioning
"The IDE you know, rebuilt in Rust." The habits are familiar (keymap, tool windows, Search Everywhere, Alt+Enter), the app is open source (Apache 2.0), and performance is measured: on the published benchmark, the window opens in 0.9 s against 3.1 s and the app uses 169 MB against 2011 MB. Coding agents are part of the IDE (tasks, worktrees, diffs and the IDE's tools over MCP) rather than a separate chat app.
## Operating Context
- Long sessions in one desktop window: the editor in the middle, tool windows docked around it, and keyboard-first navigation (Search Everywhere, Find Action, Go to Class/File/Symbol).
- Local projects, and remote development over SSH or in dev containers through the `openidea-server` backend.
- Agent tasks running alongside the developer's own work, with diff review and permission prompts.
- Built-in themes: Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark, with an option to follow the OS's light or dark mode. Users can import IntelliJ themes and `.icls` colour schemes, and plugins add more themes.
## Capabilities and Constraints
Hard constraints future work must preserve:
1. The default keymap and interaction habits stay the same as IDEA's.
2. All user-visible text is written in English and must also have a Chinese translation, through the text catalog (`T`, translated `aria-label`).
3. WebKit floor is Safari 15.4 (macOS 12). No regex lookbehind or `v` flag, no import attributes, and no newer runtime APIs in startup code. `scripts/check-webkit.ts` enforces this.
4. Design tokens in `src/styles/tokens.css` are the public theme API for plugins. Components use tokens only and never colour literals. A new token needs a value for every theme variant, and the docs must be regenerated with `pnpm gen:theme-docs`.
5. Every user operation is an action with a stable id, reachable from the keyboard and Find Action, not only by mouse.
6. No emoji as icons or decoration, in the UI or in user-visible text. Icons come from the `src/ui/icons.tsx` registry.
7. Performance (startup, memory, idle CPU) is the core selling point. UI work must not slow it down.
Other facts:
- Plugins are sandboxed WebAssembly components that add actions, completion, quick fixes, tool windows, custom editors, themes, file icons and languages. The plugin API is still a preview.
- UI is built from the primitives in `src/ui/` (Button, Dialog, Popup, Menu, List, Tree, Tabs and others). Workbench pieces come from contributions, not custom layout.
## Brand Commitments
- Name: OpenIDEA. Wordmarks are in `src-tauri/icons/source/` (`openidea-wordmark.svg` and `openidea-wordmark-dark.svg`).
- Not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o.
- Voice is plain, short and factual. It states measurements with their conditions rather than superlatives.
## Evidence on Hand
- Benchmark table and method: `README.md`, `perf/compare`. The conditions are stated with it: freqtrade, warm caches, median of 5 runs, Windows 11, 32-core AMD.
- Demo video linked from `README.md`.
- No testimonials, customer logos or user counts exist. Do not fabricate them.
## Product Principles
1. **Familiar first.** Existing IDEA habits must keep working. New behaviour must not break that muscle memory.
2. **Speed is a feature.** Every surface is judged by how much it costs in startup time, memory and responsiveness.
3. **Keyboard reachable.** If something can be done, it is an action that can be found and bound.
4. **Agents work inside the IDE.** Agent work is reviewed and controlled with the IDE's own tools: diffs, worktrees and permissions.
5. **Themeable by contract.** Visual decisions go through tokens that themes and plugins can rely on.
## Accessibility & Inclusion
- Use real `<button>` and `<input>` elements or the primitives that render them. Every icon-only button has a translated `aria-label`.
- Keep focus visible and predictable. Dialogs and popups return focus to where it came from.
- A dark high-contrast theme (`dark-hc`) ships and must be kept working.
+1 -1
View File
@@ -68,7 +68,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
- WeChat group — scan to join:
<img src=".github/assets/wechat-group-3.png" alt="WeChat group QR code" width="200">
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
- Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup).
+1 -1
View File
@@ -68,7 +68,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
- WeChat grubu, katılmak için kodu okut:
<img src=".github/assets/wechat-group-3.png" alt="WeChat grubu QR kodu" width="200">
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
+1 -1
View File
@@ -66,7 +66,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
- 微信群,扫码加入:
<img src=".github/assets/wechat-group-3.png" alt="微信群二维码" width="200">
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
- 参与贡献:参见 [CONTRIBUTING.md](CONTRIBUTING.md) 和[贡献者文档](https://openidea.sh/zh/contribute/setup)。
+8 -1
View File
@@ -6,6 +6,13 @@
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
## Microsoft ConPTY
`crates/ide-core/resources/conpty/` contains the unmodified Microsoft Windows Console
ConPTY runtime 1.25.260930003, embedded in Windows builds. Copyright (c) Microsoft
Corporation. Licensed under MIT; see its [license](crates/ide-core/resources/conpty/LICENSE)
and [package provenance](crates/ide-core/resources/conpty/README.md).
## Project Lombok
`java/lombok/lombok-1.18.48-openidea.3.jar` contains Project Lombok v1.18.48 with the Equinox
@@ -66,7 +73,7 @@ At render time `src/ui/icons.tsx` may recolour monochrome icons to `currentColor
These icons of [flutter-intellij](https://github.com/flutter/flutter-intellij) (commit `d02813ad5890`) are used
under the BSD 3-Clause License:
- `src/ui/expui/flutter/*.svg`: the DevTools tool window icons, copied unmodified from
- `src/ui/expui/flutter/*.svg`: the Flutter tool window icons, copied unmodified from
`resources/icons/expui/`.
- `src/ui/expui/flutter/[email protected]` and `[email protected]`: the Flutter outline's widget
icons, `resources/icons/custom/[email protected]` and `[email protected]`, renamed, content unmodified.
+2 -2
View File
@@ -196,11 +196,11 @@ fn levels_for_model_from_slice(options: &[AgentConfigOption]) -> Vec<AgentConfig
.filter(|o| config::is_per_model_option(o))
.cloned()
.map(|mut o| {
if config::is_context_option(&o.id) {
if config::is_context_option(&o.id) || config::is_fast_option(&o.id) {
if o.category.is_none() {
o.category = Some("model_config".into());
}
} else if o.category.as_deref() != Some("thought_level") {
} else if o.category.is_none() {
o.category = Some("thought_level".into());
}
o
+4 -3
View File
@@ -168,11 +168,12 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
assert_eq!(calls.iter().map(|(m, _)| m.as_str()).collect::<Vec<_>>(), ["initialize", "session/new"]);
assert_eq!(calls[1].1["mcpServers"], json!([]));
let cursor = mgr.providers().into_iter().find(|p| p.id == "cursor").unwrap();
let fast = cursor.config.iter().find(|o| o.id == "fast").expect("fast option");
// Per-model options (`effort`, `fast`, `context`) belong to the session's model, not provider-wide config.
assert!(!cursor.config.iter().any(|o| o.id == "fast"));
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
let fast = cursor.thought_levels["m1"].iter().find(|o| o.id == "fast").expect("fast option");
assert_eq!(fast.category.as_deref(), Some("model_config"));
assert_eq!(fast.current.as_deref(), Some("false"));
// The effort option belongs to the session's model; m2 may offer other levels.
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
assert!(cursor.thought_levels["m1"].iter().any(|o| o.category.as_deref() == Some("thought_level")));
}
+24 -6
View File
@@ -15,6 +15,8 @@ use tokio::time::Instant;
const FRESH_FOR: Duration = Duration::from_secs(15 * 60);
const COOLDOWN: Duration = Duration::from_secs(30);
/// Persisted catalog layout version; bump when option classification changes so stale per-model entries re-discover.
const CATALOG_SCHEMA: u8 = 2;
type Store = Arc<Mutex<HashMap<String, Known>>>;
type Key = (PathBuf, PathBuf, String);
@@ -80,6 +82,8 @@ impl CatalogData {
pub(crate) struct SavedCatalog {
/// An opaque cryptographic digest, never raw launch arguments or credentials.
fingerprint: String,
#[serde(default)]
schema: u8,
#[serde(flatten)]
catalog: CatalogData,
}
@@ -111,7 +115,7 @@ impl LaunchContext {
hash.update(&(value.len() as u64).to_le_bytes());
hash.update(value);
}
field(&mut hash, b"openidea-model-catalog-v1");
field(&mut hash, b"openidea-model-catalog-v2");
field(
&mut hash,
match self.spec.driver {
@@ -200,7 +204,14 @@ impl AgentCatalogs {
cache
.get(provider)
.and_then(|known| known.catalogs.get(&shared.root_key()))
.map(|saved| saved.catalog.clone())
.map(|saved| {
let mut catalog = saved.catalog.clone();
if saved.schema < CATALOG_SCHEMA {
catalog.refreshed_at_ms = None;
catalog.thought_levels.clear();
}
catalog
})
.unwrap_or_default()
}
@@ -228,7 +239,8 @@ impl AgentCatalogs {
}
drop(state);
let cache = shared.known.lock();
cache.get(provider)?.catalogs.get(&shared.root_key())?.catalog.thought_levels.get(model).cloned()
let saved = cache.get(provider)?.catalogs.get(&shared.root_key())?;
(saved.schema >= CATALOG_SCHEMA).then(|| saved.catalog.thought_levels.get(model).cloned()).flatten()
}
pub(super) async fn load_levels(
@@ -281,7 +293,7 @@ impl AgentCatalogs {
AgentModelCatalog {
provider: provider.to_owned(),
config: shared.config_for_new_task(catalog.config, provider),
thought_levels: catalog.thought_levels,
thought_levels: shared.thought_levels_for_new_task(catalog.thought_levels, provider),
refreshing: entry.flight.is_some(),
refreshed_at_ms: catalog.refreshed_at_ms,
retry_at_ms: model_failure
@@ -318,7 +330,9 @@ impl AgentCatalogs {
let generation = state.generation;
let saved =
shared.known.lock().get(&spec.id).and_then(|known| known.catalogs.get(&shared.root_key())).cloned();
let matching = saved.as_ref().is_some_and(|saved| saved.fingerprint == context.fingerprint());
let matching = saved
.as_ref()
.is_some_and(|saved| saved.schema >= CATALOG_SCHEMA && saved.fingerprint == context.fingerprint());
let age = saved
.as_ref()
.filter(|_| matching)
@@ -489,7 +503,11 @@ impl AgentCatalogs {
}
known.catalogs.insert(
shared.root_key(),
SavedCatalog { fingerprint: entry.context.fingerprint(), catalog: catalog.clone() },
SavedCatalog {
fingerprint: entry.context.fingerprint(),
schema: CATALOG_SCHEMA,
catalog: catalog.clone(),
},
);
entry.catalog = Some(catalog);
shared.persist_known(&cache);
+9 -6
View File
@@ -169,9 +169,12 @@ fn make_manager_at(root: &Path, models_file: &Path, catalogs: Arc<AgentCatalogs>
fn events(manager: &AgentManager) -> mpsc::UnboundedReceiver<AgentEvent> {
let (tx, rx) = mpsc::unbounded_channel();
manager.subscribe(Arc::new(move |event| {
let _ = tx.send(event);
}));
manager.subscribe_as(
"",
Arc::new(move |event| {
let _ = tx.send(event);
}),
);
rx
}
@@ -489,7 +492,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
set.reply.send(Err("Sign in required".into())).unwrap();
let error = switching.await.unwrap_err().to_string();
assert!(error.contains("Sign in required"), "{error}");
assert_eq!(manager.subscribe(Arc::new(|_| {})).remove(0).config, before_config);
assert_eq!(manager.subscribe_as("", Arc::new(|_| {})).remove(0).config, before_config);
assert!(harness.pending.try_recv().is_err());
manager.shutdown();
return;
@@ -498,7 +501,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
manager.set_config(&task.id, "model", "old".into()).await.unwrap();
set.reply.send(Ok(response(&["new", "old"], &["quick", "thorough"]))).unwrap();
switching.await.unwrap();
let task = manager.subscribe(Arc::new(|_| {})).remove(0);
let task = manager.subscribe_as("", Arc::new(|_| {})).remove(0);
assert_eq!(task.config.iter().find(|o| o.id == "model").unwrap().current.as_deref(), Some("old"));
assert_eq!(task.config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("low"));
assert!(harness.pending.try_recv().is_err());
@@ -529,7 +532,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
let effort = update.config.iter().find(|o| o.id == "effort").unwrap();
assert_eq!(effort.values.iter().map(|v| v.value.as_str()).collect::<Vec<_>>(), ["quick", "thorough"]);
}
let snapshot = |manager: &AgentManager| manager.subscribe(Arc::new(|_| {})).remove(0);
let snapshot = |manager: &AgentManager| manager.subscribe_as("", Arc::new(|_| {})).remove(0);
let current = snapshot(&manager);
assert_eq!(current.config.iter().find(|o| o.id == "model").unwrap().current.as_deref(), Some("new"));
assert_eq!(current.model.as_deref(), Some(if live { "new" } else { "old" }));
+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());
}
}
File diff suppressed because it is too large. Load diff
+1 -98
View File
@@ -941,107 +941,10 @@ fn normalize_agents_list(agents: Vec<String>) -> Vec<String> {
out
}
/// Strips `//` line comments, `/* ... */` block comments, and trailing commas before `}` or `]`
/// outside JSON string literals so JSONC config files parse cleanly with `serde_json`.
pub(crate) fn strip_jsonc(input: &str) -> String {
let bytes = input.as_bytes();
let mut out = String::with_capacity(input.len());
let mut i = 0;
let mut in_str = false;
while i < bytes.len() {
if in_str {
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
if ch == '\\' && i < bytes.len() {
let next = input[i..].chars().next().unwrap();
out.push(next);
i += next.len_utf8();
} else if ch == '"' {
in_str = false;
}
continue;
}
if bytes[i] == b'"' {
in_str = true;
out.push('"');
i += 1;
continue;
}
if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'/' {
i += 2;
while i < bytes.len() && bytes[i] != b'\n' {
i += 1;
}
continue;
}
if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'*' {
i += 2;
while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
if bytes[i] == b'\n' {
out.push('\n');
i += 1;
} else {
let ch = input[i..].chars().next().unwrap();
i += ch.len_utf8();
}
}
i = (i + 2).min(bytes.len());
continue;
}
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
}
remove_trailing_commas(&out)
}
fn remove_trailing_commas(input: &str) -> String {
let bytes = input.as_bytes();
let mut out = String::with_capacity(input.len());
let mut i = 0;
let mut in_str = false;
while i < bytes.len() {
if in_str {
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
if ch == '\\' && i < bytes.len() {
let next = input[i..].chars().next().unwrap();
out.push(next);
i += next.len_utf8();
} else if ch == '"' {
in_str = false;
}
continue;
}
if bytes[i] == b'"' {
in_str = true;
out.push('"');
i += 1;
continue;
}
if bytes[i] == b',' {
let mut j = i + 1;
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
j += 1;
}
if j < bytes.len() && (bytes[j] == b'}' || bytes[j] == b']') {
i += 1;
continue;
}
}
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
}
out
}
fn parse_jsonc_value(raw: &str) -> Result<Value, String> {
let trimmed = raw.trim().trim_start_matches('\u{feff}');
serde_json::from_str::<Value>(trimmed)
.or_else(|_| serde_json::from_str::<Value>(&strip_jsonc(trimmed)))
.or_else(|_| serde_json::from_str::<Value>(&ide_core::jsonc::strip(trimmed)))
.map_err(|e| format!("Invalid JSON: {e}"))
}
+14 -1
View File
@@ -536,6 +536,9 @@ pub enum AgentEntry {
kind: String,
status: AgentToolStatus,
locations: Vec<IpcPath>,
/// Images returned by the tool, kept separately from its truncated text.
#[serde(default)]
images: Vec<AgentImage>,
/// Text the tool reported (command output…), truncated.
output: Option<String>,
diffs: Vec<AgentToolDiff>,
@@ -766,7 +769,7 @@ pub struct AgentModelCatalog {
pub error: Option<String>,
}
/// Streamed to the window that subscribed (`AgentManager::subscribe`).
/// Streamed to the window that subscribed (`AgentManager::subscribe_as`).
#[derive(Clone, Debug, Serialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum AgentEvent {
@@ -798,6 +801,16 @@ pub enum AgentEvent {
from: u32,
text: String,
},
/// Text was appended to the output of tool entry `index`: it read the first `from` UTF-16
/// units of its output when the previous event for it was sent. Any other change of the
/// tool (status, title, diffs…) arrives as an `Entry`.
ToolOutput {
task: String,
subagent: Option<String>,
index: u32,
from: u32,
text: String,
},
/// An agent reported the usage limits of its account (shared by every task of `provider`).
Limits {
provider: String,
+30
View File
@@ -1007,11 +1007,16 @@ impl Session {
let mut updates = Vec::new();
let mut finished = None;
let mut read_title = false;
let mut refresh_usage = false;
{
let mut st = self.st.lock();
let st = &mut *st;
match kind {
"system" => match msg.get("subtype").and_then(Value::as_str) {
Some("compact_boundary") => {
refresh_usage = msg.pointer("/compact_metadata/post_tokens").is_none_or(Value::is_null);
updates.extend(st.tr.on_message(&msg));
}
Some("init") => {
st.terminal_only = strings(msg.get("terminal_slash_commands"));
}
@@ -1115,6 +1120,31 @@ impl Session {
if read_title {
self.read_title();
}
if refresh_usage {
self.refresh_usage();
}
}
/// Sends what the context holds after a compaction that didn't report it, as Claude Code
/// counts it (`get_context_usage`); until then the meter would show the count from before.
fn refresh_usage(self: &Arc<Self>) {
let me = self.clone();
tokio::spawn(async move {
let Some(proc) = me.st.lock().proc.clone() else { return };
let usage = match proc.control(json!({ "subtype": "get_context_usage" })).await {
Ok(usage) => usage,
Err(e) => {
tracing::debug!("reading claude context usage after compaction: {e}");
return;
}
};
let n = |k: &str| usage.get(k).and_then(Value::as_u64);
let (Some(used), Some(size)) = (n("totalTokens"), n("maxTokens").filter(|m| *m > 0)) else { return };
let update = me.st.lock().tr.on_context_usage(used, size);
if let Some(shim) = me.shim() {
shim.notify(vec![update]);
}
});
}
/// Sends the session's title once it has one: the one in its transcript, or else one
@@ -531,6 +531,38 @@ async fn sessions_without_a_title_get_one_generated() {
assert_eq!(request["request"]["persist"], true);
}
/// A compaction that doesn't report what the context holds now (no `post_tokens`): the
/// driver asks Claude Code, and the meter shows that instead of the count from before.
#[tokio::test(flavor = "multi_thread")]
async fn a_compaction_without_its_token_count_reads_the_context_usage() {
let mut processes = load_fixture("simple");
processes[0].extend([
Frame::Cli(json!({"type": "system", "subtype": "compact_boundary",
"compact_metadata": {"trigger": "manual", "pre_tokens": 120000}})),
Frame::Shim(json!({"type": "control_request", "request_id": "req_3",
"request": {"subtype": "get_context_usage"}})),
Frame::Cli(json!({"type": "control_response", "response": {"subtype": "success", "request_id": "req_3",
"response": {"categories": [], "totalTokens": 4200, "maxTokens": 200000, "model": "claude"}}})),
]);
let cli = replay_cli(processes);
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
let h =
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
let session = h.new_session().await;
h.prompt(&session, "Reply with exactly: hello there").await.unwrap();
let mut usage = Vec::new();
for _ in 0..100 {
usage = h.updates(&session, "usage_update");
if usage.last().is_some_and(|u| u["used"] == 4200) {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert!(cli.errors.lock().is_empty(), "{:?}", cli.errors.lock());
assert_eq!(usage.last().map(|u| (u["used"].clone(), u["size"].clone())), Some((json!(4200), json!(200000))));
}
#[tokio::test(flavor = "multi_thread")]
async fn replay_multi_turn() {
let r = replay("multi_turn").await;
@@ -1098,6 +1130,24 @@ fn streamed_text_is_not_sent_twice() {
assert_eq!(usage[0].update, json!({"sessionUpdate": "usage_update", "used": 15, "size": 1000}));
}
#[test]
fn a_compaction_replaces_the_context_usage() {
let mut t = Translator::new("s", PathBuf::from("/w"), true);
let assistant = json!({"type": "assistant", "parent_tool_use_id": null,
"message": {"id": "m1", "model": "x", "content": [], "usage": {"input_tokens": 900, "output_tokens": 50}}});
t.on_message(&assistant);
let result = json!({"modelUsage": {"x": {"contextWindow": 1000}}});
assert_eq!(t.on_result(&result)[0].update["used"], 950);
let boundary = |meta: Value| json!({"type": "system", "subtype": "compact_boundary", "compact_metadata": meta});
let out = t.on_message(&boundary(json!({"trigger": "manual", "pre_tokens": 950, "post_tokens": 120})));
assert_eq!(out[0].update, json!({"sessionUpdate": "usage_update", "used": 120, "size": 1000}));
// The `/compact` turn's result reports what compaction left, not the count from before.
assert_eq!(t.on_result(&result)[0].update["used"], 120);
// Without `post_tokens` nothing is known yet (the driver asks): the stale count stays out.
assert!(t.on_message(&boundary(json!({"trigger": "auto", "pre_tokens": 950}))).is_empty());
assert!(t.on_result(&result).is_empty());
}
#[test]
fn rate_limits_and_cost() {
let mut t = Translator::new("s", PathBuf::from("/w"), false);
@@ -144,6 +144,22 @@ pub(super) fn result_fields(name: &str, input: &Value, block: &Value, structured
content.push(text(&t));
}
}
if let Some(blocks) = block.get("content").and_then(Value::as_array) {
for block in blocks {
if block.get("type").and_then(Value::as_str) != Some("image") {
continue;
}
let Some(source) = block.get("source") else { continue };
if source.get("type").and_then(Value::as_str) != Some("base64") {
continue;
}
let data = source.get("data").and_then(Value::as_str).unwrap_or_default();
let mime = source.get("media_type").and_then(Value::as_str).unwrap_or_default();
if !data.is_empty() && mime.starts_with("image/") {
content.push(json!({"type": "content", "content": {"type": "image", "mimeType": mime, "data": data}}));
}
}
}
let mut out = json!({ "status": if failed { "failed" } else { "completed" } });
if !content.is_empty() {
out["content"] = Value::Array(content);
@@ -230,6 +246,43 @@ mod tests {
assert_eq!(call_fields("WebSearch", &json!({"query": "q"}), cwd)["kind"], "fetch");
}
#[test]
fn image_tool_results_keep_text_and_inline_images() {
let result = result_fields(
"Read",
&json!({"file_path": "/w/preview.png"}),
&json!({"content": [
{"type": "text", "text": "Preview ready"},
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
]}),
None,
);
assert_eq!(result["status"], "completed");
assert_eq!(
result["content"],
json!([
text("Preview ready"),
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": "aW1hZ2U="}}
])
);
}
#[test]
fn failed_shell_tool_images_keep_fallback_error_text() {
let result = result_fields(
"Bash",
&json!({}),
&json!({"is_error": true, "content": [
{"type": "text", "text": "Preview command failed"},
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
]}),
Some(&json!({"stdout": "", "stderr": ""})),
);
assert_eq!(result["status"], "failed");
assert_eq!(result["content"][0], text("Preview command failed"));
assert_eq!(result["content"][1]["content"]["type"], "image");
}
#[test]
fn results() {
let input = json!({"file_path": "/w/n.txt", "content": "two"});
@@ -458,6 +458,13 @@ impl Translator {
let last = self.children.get(&tool_use).map(|c| c.last_text.clone()).filter(|t| !t.is_empty());
self.finish_child(&tool_use, stop, last.or(summary))
}
// Compaction replaced the conversation with its summary: the context now holds
// `post_tokens`. Without it the stale count must not come back with the result;
// the driver asks Claude Code instead (`Session::refresh_usage`).
Some("compact_boundary") => {
self.used = msg.pointer("/compact_metadata/post_tokens").and_then(Value::as_u64);
self.usage_update().into_iter().collect()
}
// A turn's background tasks (`run_in_background`) outlive it: the task keeps
// the list and stays up while it isn't empty (see `Task::release_when_idle`).
Some("background_tasks_changed") => {
@@ -561,6 +568,16 @@ impl Translator {
self.usage_update().into_iter().collect()
}
/// The context usage Claude Code reports (`get_context_usage`), as a usage update.
pub fn on_context_usage(&mut self, used: u64, size: u64) -> Update {
self.used = Some(used);
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
if let Some(amount) = self.cost_usd {
update["cost"] = json!({ "amount": amount, "currency": "USD" });
}
Update { session: self.root.clone(), update }
}
fn usage_update(&self) -> Option<Update> {
let used = self.used?;
let size = self
@@ -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));
}
+1 -1
View File
@@ -406,7 +406,7 @@ fn copilot_installed_plugin_roots(copilot_dir: &Path) -> Vec<(PathBuf, AgentSkil
};
if let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json"))
&& let Ok(root) = serde_json::from_str::<serde_json::Value>(&crate::mcp::strip_jsonc(&text))
&& let Ok(root) = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text))
&& let Some(installed) = root.get("installedPlugins").and_then(serde_json::Value::as_array)
{
for entry in installed {
File diff suppressed because it is too large. Load diff
+131 -33
View File
@@ -1,6 +1,6 @@
//! Folds ACP `session/update` notifications into a task's entries.
use crate::model::{AgentEntry, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
use crate::model::{AgentEntry, AgentImage, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
use ide_core::IpcPath;
use serde_json::Value;
use std::collections::HashMap;
@@ -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>,
@@ -84,6 +87,7 @@ impl Timeline {
status: tool_status(update.get("status")).unwrap_or(AgentToolStatus::Pending),
locations: locations(update.get("locations")),
output: None,
images: Vec::new(),
diffs: Vec::new(),
started_ms: Some(crate::now_ms()),
ended_ms: None,
@@ -150,7 +154,7 @@ impl Timeline {
}
fn merge_tool(&mut self, index: usize, update: &Value) {
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, ended_ms, .. } =
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
&mut self.entries[index]
else {
return;
@@ -170,38 +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();
for item in content {
match item.get("type").and_then(Value::as_str) {
Some("content") => {
if let Some(t) = content_text(item.get("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;
// 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)),
);
}
}
@@ -368,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();
@@ -418,6 +449,7 @@ fn tail(mut text: String) -> String {
#[cfg(test)]
mod tests {
use super::*;
use crate::model::AgentImage;
use serde_json::json;
#[test]
@@ -439,6 +471,72 @@ mod tests {
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
}
#[test]
fn tool_images_survive_updates_text_truncation_and_serialization() {
use base64::Engine;
let mut t = Timeline::default();
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "preview", "title": "Render", "kind": "execute"}));
let mut old = serde_json::to_value(&t.entries[0]).unwrap();
old.as_object_mut().unwrap().remove("images");
let legacy: AgentEntry = serde_json::from_value(old).unwrap();
assert!(matches!(legacy, AgentEntry::Tool { images, .. } if images.is_empty()));
let data = base64::engine::general_purpose::STANDARD.encode(vec![0; MAX_OUTPUT]);
let update = json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "content": [
{"type": "content", "content": {"type": "text", "text": "x".repeat(MAX_OUTPUT + 100)}},
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": data}}
]});
t.apply(&update);
t.apply(&update);
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "status": "completed"}));
let AgentEntry::Tool { images, output, status, .. } = &t.entries[0] else { panic!() };
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None }]);
assert!(output.as_ref().unwrap().len() < MAX_OUTPUT + 100);
assert_eq!(*status, AgentToolStatus::Completed);
let saved = serde_json::to_string(&t.entries[0]).unwrap();
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");
-2
View File
@@ -10,8 +10,6 @@ ide-core.workspace = true
ide-language.workspace = true
serde.workspace = true
specta.workspace = true
tree-sitter.workspace = true
rayon.workspace = true
tracing.workspace = true
# Pinned: 0.40.2+ moves to tree-sitter 0.26, the workspace is on 0.25.
ast-grep-core = "=0.40.1"
+72 -6
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,10 +94,49 @@ fn executable() -> IdeResult<PathBuf> {
})
}
/// The directory holding adb, for command lines that expect `adb` on `PATH`.
pub fn platform_tools_dir() -> Option<&'static Path> {
static DIR: OnceLock<Option<PathBuf>> = OnceLock::new();
DIR.get_or_init(|| adb_executable().as_deref().and_then(Path::parent).map(Path::to_path_buf)).as_deref()
/// 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.
@@ -212,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() {
+216 -134
View File
@@ -1,101 +1,18 @@
//! Child processes of the `adb` CLI: bounded runs, and cancellable line streams
//! The `adb` CLI as a child process: bounded runs, and cancellable line streams
//! that are handed over in batches (logcat is far too chatty for one message a line).
use ide_core::process::terminate_tree;
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::io::Read;
use std::process::{Child, Command, Stdio};
use std::sync::mpsc;
pub(crate) use ide_core::cli_process::Output;
use ide_core::cli_process::{CarriageReturn, CliTool, Decoding, Poll, Stream, keep_stderr_line};
use ide_core::{CancellationToken, IdeResult};
use std::process::Command;
use std::time::{Duration, Instant};
/// How long a cancelled child gets to exit on `SIGTERM` (and flush) before `SIGKILL`.
const KILL_GRACE: Duration = Duration::from_millis(20);
pub(crate) struct Output {
pub stdout: String,
pub stderr: String,
pub success: bool,
}
fn prepare(cmd: &mut Command) {
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
ide_core::process::prepare(ide_core::process::own_group(cmd));
}
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run adb: {e}")))
}
fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<String> {
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = pipe.read_to_end(&mut buf);
ide_core::output_encoding::decode_tool_output(&buf)
})
}
const ADB: CliTool = CliTool::new("adb", Decoding::ToolOutput);
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
/// a non-zero exit is reported in [`Output::success`], not as an error.
pub(crate) fn run(mut cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
prepare(&mut cmd);
let mut child = spawn(&mut cmd)?;
let out = child.stdout.take().map(read_all);
let err = child.stderr.take().map(read_all);
let deadline = Instant::now() + timeout;
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_some_and(CancellationToken::is_cancelled) {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
if Instant::now() >= deadline {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::unavailable("adb did not respond in time"));
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(Output {
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
success: status.success(),
})
}
enum Event {
Line(bool, String),
Closed,
}
fn spawn_reader(mut pipe: impl Read + Send + 'static, tx: mpsc::Sender<Event>, stdout: bool) {
std::thread::spawn(move || {
let mut buf = [0u8; 8192];
let mut pending: Vec<u8> = Vec::new();
let flush = |pending: &mut Vec<u8>| {
if !pending.is_empty() {
let line = ide_core::output_encoding::decode_tool_output(pending);
pending.clear();
let _ = tx.send(Event::Line(stdout, line.trim_end().to_string()));
}
};
loop {
match pipe.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
for &b in &buf[..n] {
if b == b'\n' {
flush(&mut pending);
} else if b != b'\r' {
pending.push(b);
}
}
}
}
}
flush(&mut pending);
let _ = tx.send(Event::Closed);
});
pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
ADB.run(cmd, timeout, cancel)
}
fn flush<T>(batch: &mut Vec<T>, on_batch: &mut dyn FnMut(Vec<T>)) {
@@ -109,41 +26,22 @@ fn flush<T>(batch: &mut Vec<T>, on_batch: &mut dyn FnMut(Vec<T>)) {
/// old, so neither a quiet nor a steady stream holds lines back. Stderr is kept as a
/// tail for the error message. Returns whether the child exited successfully.
pub(crate) fn stream_batched<T>(
mut cmd: Command,
cmd: Command,
cancel: &CancellationToken,
idle: Duration,
max: usize,
mut parse: impl FnMut(&str) -> Option<T>,
on_batch: &mut dyn FnMut(Vec<T>),
) -> IdeResult<(bool, Vec<String>)> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
prepare(&mut cmd);
let mut child = spawn(&mut cmd)?;
let (tx, rx) = mpsc::channel::<Event>();
let mut open = 0;
if let Some(out) = child.stdout.take() {
spawn_reader(out, tx.clone(), true);
open += 1;
}
if let Some(err) = child.stderr.take() {
spawn_reader(err, tx.clone(), false);
open += 1;
}
drop(tx);
let mut lines = ADB.lines(cmd, cancel, CarriageReturn::Dropped)?;
let mut stderr_tail: Vec<String> = Vec::new();
let mut batch: Vec<T> = Vec::with_capacity(max);
// When the first line of the waiting batch arrived.
let mut since = Instant::now();
while open > 0 {
if cancel.is_cancelled() {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
loop {
let wait = if batch.is_empty() { idle } else { idle.saturating_sub(since.elapsed()) };
match rx.recv_timeout(wait) {
Ok(Event::Line(true, line)) => {
match lines.poll(cancel, wait)? {
Poll::Line(Stream::Stdout, line) => {
if let Some(item) = parse(&line) {
if batch.is_empty() {
since = Instant::now();
@@ -154,36 +52,25 @@ pub(crate) fn stream_batched<T>(
}
}
}
Ok(Event::Line(false, line)) => {
Poll::Line(Stream::Stderr, line) => {
if !line.trim().is_empty() {
stderr_tail.push(line);
if stderr_tail.len() > 20 {
stderr_tail.remove(0);
}
keep_stderr_line(&mut stderr_tail, line);
}
}
Ok(Event::Closed) => open -= 1,
Err(mpsc::RecvTimeoutError::Timeout) => flush(&mut batch, on_batch),
Err(mpsc::RecvTimeoutError::Disconnected) => break,
Poll::Closed => {}
Poll::Timeout => flush(&mut batch, on_batch),
Poll::Finished => break,
}
}
flush(&mut batch, on_batch);
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_cancelled() {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
std::thread::sleep(Duration::from_millis(10));
};
Ok((status.success(), stderr_tail))
Ok((lines.finish(cancel)?, stderr_tail))
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use ide_core::error::ErrorKind;
use ide_core::process::process_alive;
#[test]
fn a_steady_stream_is_handed_over_while_it_runs() {
@@ -203,4 +90,199 @@ mod tests {
assert_eq!(sizes.iter().sum::<usize>(), 20);
assert!(sizes.len() >= 3, "lines arriving every 20 ms waited for the end: {sizes:?}");
}
const LONG: Duration = Duration::from_secs(30);
fn sh(script: &str) -> Command {
let mut cmd = Command::new("sh");
cmd.args(["-c", script]);
cmd
}
/// A script that records its pid in `name`'s file, then runs `rest`.
fn recording_pid(name: &str, rest: &str) -> (Command, std::path::PathBuf) {
let file = std::env::temp_dir().join(format!("openidea-process-{}-{name}", std::process::id()));
let _ = std::fs::remove_file(&file);
(sh(&format!("echo $$ > '{0}.tmp' && mv '{0}.tmp' '{0}'; {rest}", file.display())), file)
}
fn recorded_pid(file: &std::path::Path) -> u32 {
let pid = std::fs::read_to_string(file).unwrap().trim().parse().unwrap();
let _ = std::fs::remove_file(file);
pid
}
/// Cancels `cancel` once the script has recorded its pid.
fn cancel_when_recorded(file: &std::path::Path, cancel: &CancellationToken) {
let (file, cancel) = (file.to_owned(), cancel.clone());
std::thread::spawn(move || {
while !file.exists() {
std::thread::sleep(Duration::from_millis(5));
}
cancel.cancel();
});
}
fn assert_gone(pid: u32) {
let deadline = Instant::now() + Duration::from_secs(5);
while process_alive(pid) {
assert!(Instant::now() < deadline, "process {pid} survived");
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn the_exit_status_is_reported_not_raised() {
assert!(run(sh("exit 0"), LONG, None).unwrap().success);
assert!(!run(sh("exit 3"), LONG, None).unwrap().success);
}
#[test]
fn both_streams_are_captured_separately_and_in_order() {
let out = run(sh("printf 'a\\nb\\nc\\n'; printf 'x\\ny\\n' >&2"), LONG, None).unwrap();
assert_eq!(out.stdout, "a\nb\nc\n");
assert_eq!(out.stderr, "x\ny\n");
assert!(out.success);
}
#[test]
fn invalid_utf8_is_replaced_in_collected_output() {
let out = run(sh("printf 'ok\\n\\377\\n'; printf 'a\\377b' >&2"), LONG, None).unwrap();
assert_eq!(out.stdout, "ok\n\u{FFFD}\n");
assert_eq!(out.stderr, "a\u{FFFD}b");
}
#[test]
fn stdin_is_closed() {
assert_eq!(run(sh("cat; echo done"), LONG, None).unwrap().stdout, "done\n");
}
#[test]
fn a_missing_program_is_unavailable() {
let err = run(Command::new("/nonexistent/openidea-adb"), LONG, None).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "could not run adb: No such file or directory (os error 2)");
}
#[test]
fn a_run_past_its_timeout_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("adb-timeout", "exec sleep 30");
let err = run(cmd, Duration::from_secs(1), None).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "adb did not respond in time");
assert_gone(recorded_pid(&file));
}
#[test]
fn a_cancelled_run_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("adb-cancel", "exec sleep 30");
let cancel = CancellationToken::new();
cancel_when_recorded(&file, &cancel);
let err = run(cmd, LONG, Some(&cancel)).err().unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
assert_gone(recorded_pid(&file));
}
/// Runs `script` batched by `max` lines (a long `idle`, so only `max` and the end flush),
/// parsing stdout lines unless they are `skip`.
fn batches(script: &str, max: usize) -> (bool, Vec<Vec<String>>, Vec<String>) {
let mut batches = Vec::new();
let (ok, tail) = stream_batched(
sh(script),
&CancellationToken::new(),
LONG,
max,
|line| (line != "skip").then(|| line.to_owned()),
&mut |batch| batches.push(batch),
)
.unwrap();
(ok, batches, tail)
}
#[test]
fn a_batch_is_handed_over_as_soon_as_max_lines_are_ready() {
let (ok, batches, _) = batches("printf '1\\n2\\n3\\n4\\n5\\n'", 2);
assert!(ok);
assert_eq!(batches, [vec!["1", "2"], vec!["3", "4"], vec!["5"]]);
}
#[test]
fn lines_the_parser_rejects_are_dropped() {
let (_, batches, _) = batches("printf '1\\nskip\\n2\\n'", 10);
assert_eq!(batches, [vec!["1", "2"]]);
}
#[test]
fn carriage_returns_are_dropped_not_split_on_and_line_ends_are_trimmed() {
let (_, batches, _) = batches("printf 'a\\r\\nb\\rc \\n\\n\\nd'", 10);
assert_eq!(batches, [vec!["a", "bc", "d"]]);
}
#[test]
fn a_stream_replaces_invalid_utf8() {
let (_, batches, _) = batches("printf 'a\\377b\\n'", 10);
assert_eq!(batches, [vec!["a\u{FFFD}b"]]);
}
#[test]
fn a_stream_reports_the_exit_status() {
assert!(batches("exit 0", 10).0);
assert!(!batches("exit 2", 10).0);
}
#[test]
fn stderr_is_not_parsed_and_its_last_twenty_non_blank_lines_are_kept() {
let (_, batches, tail) =
batches("echo ' ' >&2; i=1; while [ $i -le 25 ]; do echo e$i >&2; i=$((i+1)); done; echo out", 10);
assert_eq!(batches, [vec!["out"]]);
let expected: Vec<String> = (6..=25).map(|i| format!("e{i}")).collect();
assert_eq!(tail, expected);
}
#[test]
fn a_stream_cancelled_before_it_starts_does_not_spawn() {
let cancel = CancellationToken::new();
cancel.cancel();
let err = stream_batched(
Command::new("/nonexistent/openidea-adb"),
&cancel,
LONG,
10,
|line| Some(line.to_owned()),
&mut |_| {},
)
.err()
.unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
}
#[test]
fn a_stream_cancelled_while_running_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("adb-stream-cancel", "echo started; exec sleep 30");
let cancel = CancellationToken::new();
let err = stream_batched(cmd, &cancel, LONG, 1, |line| Some(line.to_owned()), &mut |_| cancel.cancel())
.err()
.unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
assert_gone(recorded_pid(&file));
}
#[test]
fn a_missing_program_cannot_be_streamed() {
let err = stream_batched(
Command::new("/nonexistent/openidea-adb"),
&CancellationToken::new(),
LONG,
10,
|line| Some(line.to_owned()),
&mut |_| {},
)
.err()
.unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "could not run adb: No such file or directory (os error 2)");
}
}
-2
View File
@@ -17,6 +17,4 @@ serde_json.workspace = true
specta.workspace = true
tracing.workspace = true
dirs.workspace = true
[dev-dependencies]
tempfile.workspace = true
+2 -1
View File
@@ -26,9 +26,10 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
let module = dunce::canonicalize(root.join(module))?;
if let Some(p) = model.maven.as_ref().and_then(|m| m.projects.iter().find(|p| root.join(&p.dir) == module)) {
let mut args = p.options.clone();
let repo = crate::maven::local_repository_for(&p.options);
args.extend([
"process-resources".into(),
"help:evaluate".into(),
crate::maven::plugin_goal("help:evaluate", repo.as_deref()),
"-Dexpression=project.build.outputDirectory".into(),
format!("-Doutput={}", manifest.display()),
]);
+96 -28
View File
@@ -15,12 +15,12 @@ pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
pub use launch_resources::process_launch_resources;
pub use modules::record_module_build;
pub use single::{
SingleFileTarget, compile_file_plan, find_javac, javac_step, module_classpath, module_classpaths,
single_file_classpath, single_file_target,
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
has_gradle_file_target, javac_step, module_classpath, module_classpaths, single_file_classpath, single_file_target,
};
pub use structure::{
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_outputs, structure_plan,
structure_war_plan, structure_web_artifacts,
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
};
pub use up_to_date::{menu_up_to_date, record_menu_build};
@@ -483,11 +483,6 @@ fn go_module_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
vec![s]
}
/// `pnpm` / `yarn` / `bun` / `npm`, from the lock file next to `package.json` or above it.
fn package_manager(dir: &Path) -> &'static str {
ide_core::project_roots::package_manager(dir)
}
fn has_build_script(dir: &Path) -> bool {
std::fs::read(dir.join("package.json"))
.ok()
@@ -525,7 +520,12 @@ fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
fn ts_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
let script = has_build_script(dir);
if script && (kind == BuildKind::Artifacts || !dir.join("tsconfig.json").is_file()) {
return vec![BuildStep::new(package_manager(dir), &["run", "build"], dir, Format::Tsc)];
return vec![BuildStep::new(
ide_core::project_roots::package_manager(dir),
&["run", "build"],
dir,
Format::Tsc,
)];
}
let local = dir.ancestors().map(|d| d.join("node_modules/.bin/tsc")).find(|p| p.is_file());
let program = local.map_or_else(|| "tsc".to_owned(), |p| p.to_string_lossy().into_owned());
@@ -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
@@ -1008,12 +1011,7 @@ pub fn build_for_launches(
if plan.system == BuildSystem::Maven
&& let Some(m) = &model.maven
{
maven_launch_projects(root, m, module, test)
.iter()
.flat_map(|p| {
launch_class_dirs(plan.system, &subdir(root, &p.dir), test && subdir(root, &p.dir) == module)
})
.collect()
maven_launch_output_dirs(root, m, module, test).into_iter().filter(|dir| dir.is_dir()).collect()
} else {
launch_class_dirs(plan.system, module, test)
}
@@ -1021,6 +1019,60 @@ pub fn build_for_launches(
Ok(modules.iter().map(|m| LaunchBuild { class_dirs: class_dirs(m), failure: failure.clone() }).collect())
}
/// Maven output directories for a launch, including directories that have yet to be created.
pub fn maven_launch_output_dirs(root: &Path, model: &maven::MavenModel, module: &Path, test: bool) -> Vec<PathBuf> {
maven_launch_projects(root, model, module, test)
.into_iter()
.flat_map(|p| {
let dir = subdir(root, &p.dir);
maven_output_dirs(&dir, test && dir == module)
})
.collect()
}
/// The class directories of a Maven launch that must hold classes after its build: those of
/// the launch projects with sources in a conventional JVM source root. One that is missing
/// or holds no class was caught mid-rewrite, e.g. cleaned by a concurrent `mvn` (#5404).
pub fn launch_required_class_dirs(root: &Path, model: &BuildModel, module: &Path, test: bool) -> Vec<PathBuf> {
fn has_sources(dir: &Path, depth: u32) -> bool {
let Ok(entries) = std::fs::read_dir(dir) else { return false };
entries.flatten().any(|e| {
let p = e.path();
if p.is_dir() {
depth > 0 && has_sources(&p, depth - 1)
} else {
// A package-info.java without annotations compiles to nothing.
p.file_name() != Some("package-info.java".as_ref())
&& p.extension().is_some_and(|x| x == "java" || x == "kt" || x == "groovy" || x == "scala")
}
})
}
let compiles = |dir: &Path, set: &str| {
["java", "kotlin", "groovy", "scala"].iter().any(|lang| has_sources(&dir.join("src").join(set).join(lang), 32))
};
let Some(m) = &model.maven else { return Vec::new() };
let mut dirs = Vec::new();
for p in maven_launch_projects(root, m, module, test) {
let dir = subdir(root, &p.dir);
if test && dir == module && compiles(&dir, "test") {
dirs.push(subdir(&dir, "target/test-classes"));
}
if compiles(&dir, "main") {
dirs.push(subdir(&dir, "target/classes"));
}
}
dirs
}
fn maven_output_dirs(module: &Path, test: bool) -> Vec<PathBuf> {
let mut dirs = Vec::new();
if test {
dirs.push(subdir(module, "target/test-classes"));
}
dirs.push(subdir(module, "target/classes"));
dirs
}
fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<PathBuf> {
let sets: &[&str] = if test { &["test", "main"] } else { &["main"] };
let dirs: Vec<PathBuf> = match system {
@@ -1031,8 +1083,7 @@ fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<Path
.map(|d| subdir(module, &format!("build/{d}/{s}")))
})
.collect(),
BuildSystem::Maven if test => vec![subdir(module, "target/test-classes"), subdir(module, "target/classes")],
BuildSystem::Maven => vec![subdir(module, "target/classes")],
BuildSystem::Maven => maven_output_dirs(module, test),
_ => Vec::new(),
};
dirs.into_iter().filter(|d| d.is_dir()).collect()
@@ -1774,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"]
@@ -1786,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
);
}
+35 -7
View File
@@ -200,19 +200,22 @@ fn kotlin_line(line: &str) -> Option<RawMessage> {
kotlin_location(rest, severity)
}
/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg`.
/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg`
/// (and localized javac prefixes such as Chinese/Japanese `错误:` / `錯誤:` / `エラー:` / `警告:`).
fn javac_header(line: &str) -> Option<RawMessage> {
let (path, ln, col, rest) = path_line_col(line)?;
if !looks_like_source_path(path) {
return None;
}
let rest = rest.trim_start_matches(':').trim_start();
let (severity, msg) = if let Some(m) = rest.strip_prefix("error:") {
(Severity::Error, m)
} else {
let m = rest.strip_prefix("warning:")?;
(Severity::Warning, m)
};
let (severity, msg) = ["error:", "错误:", "錯誤:", "エラー:"]
.into_iter()
.find_map(|prefix| rest.strip_prefix(prefix).map(|m| (Severity::Error, m)))
.or_else(|| {
["warning:", "警告:"]
.into_iter()
.find_map(|prefix| rest.strip_prefix(prefix).map(|m| (Severity::Warning, m)))
})?;
Some(RawMessage::new(severity, msg.trim(), ColUnit::Char).at(path, ln, col))
}
@@ -555,6 +558,31 @@ mod tests {
assert_eq!(out[1].text, "[removal] finalize() has been deprecated");
}
#[test]
fn localized_javac_errors_and_warnings() {
let out = parse(
Format::Gradle,
"/p/src/A.java:12: 错误: 找不到符号\n\
\x20 Foo foo = new Foo();\n\
\x20 ^\n\
\x20 符号: 类 Foo\n\
\x20 位置: 类 A\n\
/p/src/B.java:5: 錯誤: 需要 ';'\n\
\x20 int x = 1\n\
\x20 ^\n\
/p/src/C.java:8: 警告: [deprecation] old() 已过时\n\
\x20 old();\n\
\x20 ^\n",
);
assert_eq!(out.len(), 3, "{out:?}");
assert_eq!(pos(&out[0]), (Severity::Error, "/p/src/A.java", 12, Some(9)));
assert_eq!(out[0].text, "找不到符号\n符号: 类 Foo\n位置: 类 A");
assert_eq!(pos(&out[1]), (Severity::Error, "/p/src/B.java", 5, Some(14)));
assert_eq!(out[1].text, "需要 ';'");
assert_eq!(pos(&out[2]), (Severity::Warning, "/p/src/C.java", 8, Some(5)));
assert_eq!(out[2].text, "[deprecation] old() 已过时");
}
#[test]
fn gradle_kotlin() {
let out = parse(
+356 -60
View File
@@ -1,4 +1,4 @@
//! Single-file Java compilation with `javac` for the Compile File action (#2476).
//! Single-file Java compilation with `javac` for the Recompile action (#2476).
//!
//! A module build (`-pl … -am`) still walks every upstream module, and packaging
//! walks the whole reactor; compiling one file only needs that file's module
@@ -6,12 +6,93 @@
use super::*;
use serde::{Deserialize, Serialize};
use std::fs;
use std::process::Command as ProcCommand;
/// Output file of the `dependency:build-classpath` probe, relative to each module.
const CP_FILE: &str = "target/ide-compile-cp.txt";
// Older records include undeclared reactor test outputs even in runtime classpaths.
const CLASSPATH_CACHE_VERSION: u32 = 1;
const GRADLE_COMPILE_CP_INIT_SCRIPT: &str = include_str!("../gradle-compile-cp.init.gradle");
pub(super) fn is_java_file(file: &Path) -> IdeResult<String> {
if file.extension().is_none_or(|ext| !ext.eq_ignore_ascii_case("java")) {
return Err(IdeError::invalid("only Java sources can be compiled as a single file"));
}
if !file.is_file() {
return Err(IdeError::not_found("no Java source found for single-file compilation"));
}
Ok(file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default())
}
pub(super) fn is_test_source(rel: &str) -> bool {
let parts: Vec<&str> = rel.split(['/', '\\']).collect();
parts.windows(2).any(|w| w == ["src", "test"])
}
pub(super) fn java_home_major(env: &BTreeMap<String, String>) -> Option<u32> {
let home = env.get("JAVA_HOME").filter(|h| !h.trim().is_empty())?;
let release = fs::read_to_string(Path::new(home).join("release")).ok()?;
let value = release.lines().find_map(|l| l.trim().strip_prefix("JAVA_VERSION="))?;
let value = value.trim().trim_matches(['"', '\'']);
language_release(value)
}
/// `--release N` from JDK 9 on; older compilers only know `-source` / `-target`.
pub(super) fn release_args(level: Option<u32>, jdk_major: Option<u32>) -> Vec<String> {
let Some(level) = level else { return Vec::new() };
if jdk_major.is_none_or(|m| m >= 9) {
vec!["--release".into(), level.to_string()]
} else {
vec!["-source".into(), format!("1.{level}"), "-target".into(), format!("1.{level}")]
}
}
pub(super) fn join_classpath(entries: impl IntoIterator<Item = String>) -> String {
let separator = if cfg!(windows) { ";" } else { ":" };
let mut seen = HashSet::new();
let mut out = Vec::new();
for entry in entries {
if !entry.is_empty() && seen.insert(entry.clone()) {
out.push(entry);
}
}
out.join(separator)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn build_javac_step(
javac: &str,
cwd: &Path,
out_dir: &Path,
classpath: &str,
sources: &[PathBuf],
release: Vec<String>,
file: &Path,
env: BTreeMap<String, String>,
) -> IdeResult<BuildStep> {
fs::create_dir_all(out_dir)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", out_dir.display())))?;
// Raw `javac` prints `path:line: error: …`, the same form Gradle forwards.
let mut step = BuildStep::new(javac, &[], cwd, Format::Gradle);
step.args.extend(["-encoding".into(), "UTF-8".into(), "-g".into()]);
step.args.extend(["-d".into(), out_dir.to_string_lossy().into_owned()]);
if !classpath.is_empty() {
step.args.extend(["-cp".into(), classpath.to_owned()]);
}
// Classes of the module that were never built (or are older than their source) are read
// from its sources; only `file` is written, so a test compile never puts main classes
// into test-classes.
if !sources.is_empty() {
let separator = if cfg!(windows) { ";" } else { ":" };
step.args.push("-sourcepath".into());
step.args.push(sources.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>().join(separator));
step.args.push("-implicit:none".into());
}
step.args.extend(release);
step.args.push(file.to_string_lossy().into_owned());
step.env = env;
step.mkdirs = vec![out_dir.to_path_buf()];
Ok(step)
}
/// The resolved dependency classpath for one module and scope, tied to the same
/// inputs as its launch build so POM, JDK, settings and profile changes invalidate it.
@@ -41,12 +122,7 @@ pub struct SingleFileTarget {
/// Locates the linked Maven module owning a `.java` source file.
pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeResult<SingleFileTarget> {
if file.extension().is_none_or(|ext| ext != "java") {
return Err(IdeError::invalid("only Java sources can be compiled as a single file"));
}
if !file.is_file() {
return Err(IdeError::not_found("no Java source found for single-file compilation"));
}
is_java_file(file)?;
let Some(m) = &model.maven else {
return Err(IdeError::not_found("no linked Maven project found for module"));
};
@@ -70,8 +146,7 @@ pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeRe
let top_dir = subdir(root, &top.dir);
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
// Test sources see the test classpath and compile into test classes.
let parts: Vec<&str> = rel.split('/').collect();
let test = parts.windows(2).any(|w| w == ["src", "test"]);
let test = is_test_source(&rel);
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
}
@@ -112,7 +187,17 @@ pub fn find_javac(env: &BTreeMap<String, String>) -> String {
/// `mvn dependency:build-classpath` (which resolves without compiling anything,
/// so `-am` stays cheap). Entries are platform-separated (`;` on Windows).
pub fn single_file_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget) -> IdeResult<String> {
classpath(root, model, target, "test", false)
single_file_classpath_cancellable(root, model, target, &CancellationToken::new())
}
fn single_file_classpath_cancellable(
root: &Path,
model: &BuildModel,
target: &SingleFileTarget,
cancel: &CancellationToken,
) -> IdeResult<String> {
let scope = if target.test { "test" } else { "compile" };
classpath(root, model, target, scope, false, cancel)
}
/// Runtime (or test) dependency classpath for a launch module.
@@ -172,10 +257,12 @@ pub fn module_classpaths(
}
let scope = if test { "test" } else { "runtime" };
let targets: Vec<&SingleFileTarget> = probes.iter().map(|p| &p.0).collect();
let classpaths = match classpaths(root, model, &targets, scope, true) {
let classpaths = match classpaths(root, model, &targets, scope, true, cancel) {
Ok(classpaths) => classpaths,
// Another module's failure must not cost this launch its own probe.
Err(_) if targets.len() > 1 && !cancel.is_cancelled() => classpaths(root, model, &targets[..1], scope, true)?,
Err(_) if targets.len() > 1 && !cancel.is_cancelled() => {
classpaths(root, model, &targets[..1], scope, true, cancel)?
}
Err(e) => return Err(e),
};
if cancel.is_cancelled() {
@@ -236,8 +323,9 @@ fn classpath(
target: &SingleFileTarget,
scope: &str,
compile_first: bool,
cancel: &CancellationToken,
) -> IdeResult<String> {
Ok(classpaths(root, model, &[target], scope, compile_first)?.pop().unwrap())
Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
}
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
@@ -247,6 +335,7 @@ fn classpaths(
targets: &[&SingleFileTarget],
scope: &str,
compile_first: bool,
cancel: &CancellationToken,
) -> IdeResult<Vec<String>> {
let top = &targets[0].top;
let probe = CP_FILE;
@@ -272,18 +361,21 @@ fn classpaths(
if compile_first {
args.push("compile");
}
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
let build_classpath =
maven::plugin_goal("dependency:build-classpath", maven::local_repository_for(&top.options).as_deref());
args.extend([build_classpath.as_str(), output_arg.as_str(), scope_arg.as_str(), "-q"]);
let top_dir = subdir(root, &top.dir);
let mut command = ProcCommand::new(&top.command);
command.args(&args).envs(&top.env).current_dir(&top_dir);
let status = ide_core::process::prepare(&mut command)
.output()
.map_err(|e| IdeError::internal(format!("cannot resolve the compile classpath: {e}")))?;
if !status.status.success() {
let stdout = String::from_utf8_lossy(&status.stdout);
let stderr = String::from_utf8_lossy(&status.stderr);
let owned_args: Vec<String> = args.into_iter().map(str::to_owned).collect();
let out = process::run_bounded(&top.command, &owned_args, &top_dir, &top.env, cancel, |_, _| {}).map_err(|e| {
if e.kind == ide_core::error::ErrorKind::Cancelled {
e
} else {
IdeError::internal(format!("cannot resolve the compile classpath: {}", e.message))
}
})?;
if !out.success {
// Maven reports reactor/dependency failures on stdout, not only stderr.
let tail: Vec<&str> = stdout.lines().chain(stderr.lines()).filter(|l| !l.trim().is_empty()).collect();
let tail: Vec<&str> = out.text.lines().filter(|l| !l.trim().is_empty()).collect();
let tail = tail.iter().rev().take(5).rev().cloned().collect::<Vec<_>>().join("\n");
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
}
@@ -325,39 +417,14 @@ fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget)
})?;
let separator = if cfg!(windows) { ';' } else { ':' };
entries.extend(content.split([separator, '\n', '\r']).map(str::trim).filter(|e| !e.is_empty()).map(str::to_owned));
entries.dedup();
Ok(entries.join(&separator.to_string()))
Ok(join_classpath(entries))
}
/// The `javac` step compiling `file` into `target`'s output directory.
pub fn javac_step(target: &SingleFileTarget, file: &Path, classpath: &str, javac: &str) -> IdeResult<BuildStep> {
fs::create_dir_all(&target.out_dir)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", target.out_dir.display())))?;
let mut step = BuildStep::new(javac, &[], &target.module, Format::Gradle);
// Raw `javac` prints `path:line: error: …`, the same form Gradle forwards.
step.args.push("-encoding".into());
step.args.push("UTF-8".into());
step.args.push("-d".into());
step.args.push(target.out_dir.to_string_lossy().into_owned());
step.args.push("-cp".into());
step.args.push(classpath.to_owned());
// Classes of the module that were never built (or are older than their source) are read
// from its sources; only `file` is written, so a test compile never puts main classes
// into test-classes.
let sources = source_roots(target);
if !sources.is_empty() {
let separator = if cfg!(windows) { ";" } else { ":" };
step.args.push("-sourcepath".into());
step.args.push(sources.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>().join(separator));
step.args.push("-implicit:none".into());
}
if let Some(version) = target.java_version {
step.args.push("--release".into());
step.args.push(version.to_string());
}
step.args.push(file.to_string_lossy().into_owned());
step.env = target.top.env.clone();
Ok(step)
let release = release_args(target.java_version, java_home_major(&target.top.env));
build_javac_step(javac, &target.module, &target.out_dir, classpath, &sources, release, file, target.top.env.clone())
}
/// The module's Java source folders that exist, generated ones included; test sources see
@@ -383,8 +450,18 @@ fn source_roots(target: &SingleFileTarget) -> Vec<PathBuf> {
/// Resolves the classpath and plans the `javac` invocation for one Java source.
pub fn compile_file_plan(root: &Path, model: &BuildModel, file: &Path) -> IdeResult<BuildPlan> {
compile_file_plan_cancellable(root, model, file, &CancellationToken::new())
}
/// Cancellable [`compile_file_plan`].
pub fn compile_file_plan_cancellable(
root: &Path,
model: &BuildModel,
file: &Path,
cancel: &CancellationToken,
) -> IdeResult<BuildPlan> {
let target = single_file_target(root, model, file)?;
let classpath = single_file_classpath(root, model, &target)?;
let classpath = single_file_classpath_cancellable(root, model, &target, cancel)?;
let javac = find_javac(&target.top.env);
let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
Ok(BuildPlan {
@@ -394,6 +471,140 @@ pub fn compile_file_plan(root: &Path, model: &BuildModel, file: &Path) -> IdeRes
})
}
fn gradle_for_file<'a>(
root: &Path,
model: &'a BuildModel,
file: &Path,
) -> Option<(&'a crate::GradleModel, &'a crate::GradleProject, PathBuf)> {
let file = normalize(file);
let file_ref = &file;
model
.gradle
.iter()
.flat_map(|g| {
let g_dir = normalize(&subdir(root, &g.dir));
let g_depth = g_dir.components().count();
g.projects.iter().filter_map(move |p| {
let p_dir = normalize(&subdir(root, &p.dir));
file_ref.starts_with(&p_dir).then_some((g, p, p_dir, g_depth))
})
})
.max_by_key(|(_, _, p_dir, g_depth)| (p_dir.components().count(), *g_depth))
.map(|(g, p, p_dir, _)| (g, p, p_dir))
}
/// Whether `file` lies inside a linked Gradle project of `model`.
pub fn has_gradle_file_target(root: &Path, model: &BuildModel, file: &Path) -> bool {
gradle_for_file(root, model, file).is_some()
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GradleCompileCp {
out_dir: Option<String>,
#[serde(default)]
classpath: Vec<String>,
#[serde(default)]
src_dirs: Vec<String>,
release: Option<u32>,
}
/// Resolves the compile classpath from Gradle and plans a single-file `javac` step.
pub fn gradle_compile_file_plan(
root: &Path,
model: &BuildModel,
file: &Path,
cache: &Path,
cancel: &CancellationToken,
) -> IdeResult<BuildPlan> {
let name = is_java_file(file)?;
let (gradle, project, module_dir) = gradle_for_file(root, model, file)
.ok_or_else(|| IdeError::not_found("no linked Gradle project found for file"))?;
let rel = rel_str(&module_dir, file);
let test = is_test_source(&rel);
let scope = if test { "test" } else { "main" };
fs::create_dir_all(cache)?;
let init_script = cache.join("gradle-compile-cp.init.gradle");
fs::write(&init_script, GRADLE_COMPILE_CP_INIT_SCRIPT)?;
let args = vec![
"--console=plain".into(),
"-q".into(),
"-Dorg.gradle.configuration-cache=false".into(),
"--init-script".into(),
init_script.to_string_lossy().into_owned(),
format!("-Popenidea.target={}", project.path),
format!("-Popenidea.scope={scope}"),
"help".into(),
];
let gradle_dir = subdir(root, &gradle.dir);
let mut reported: Option<String> = None;
let out = process::run_bounded(&gradle.command, &args, &gradle_dir, &gradle.env, cancel, |_, line| {
if let Some(json) = line.strip_prefix("@openidea-compile-cp\t") {
reported = Some(json.to_owned());
}
})
.map_err(|e| {
if e.kind == ide_core::error::ErrorKind::Cancelled {
e
} else {
IdeError::internal(format!("cannot resolve the compile classpath: {}", e.message))
}
})?;
if !out.success {
let tail: Vec<&str> = out.text.lines().filter(|l| !l.trim().is_empty()).collect();
let tail = tail.iter().rev().take(5).rev().cloned().collect::<Vec<_>>().join("\n");
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
}
let json = reported.ok_or_else(|| {
IdeError::internal(format!(
"cannot resolve the compile classpath: Gradle did not report source set '{scope}' for {}",
project.path
))
})?;
let cp: GradleCompileCp = serde_json::from_str(&json)
.map_err(|e| IdeError::internal(format!("cannot parse Gradle compile classpath: {e}")))?;
let out_dir = cp
.out_dir
.filter(|d| !d.trim().is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| module_dir.join("build/classes/java").join(scope));
let mut cp_entries: Vec<String> = Vec::new();
if out_dir.is_dir() {
cp_entries.push(out_dir.to_string_lossy().into_owned());
}
if test {
let main_out = module_dir.join("build/classes/java/main");
if main_out.is_dir() {
cp_entries.push(main_out.to_string_lossy().into_owned());
}
}
for sibling in &gradle.projects {
let sibling_dir = subdir(root, &sibling.dir);
if sibling_dir == module_dir {
continue;
}
let classes = sibling_dir.join("build/classes/java/main");
if classes.is_dir() {
cp_entries.push(classes.to_string_lossy().into_owned());
}
}
cp_entries.extend(cp.classpath);
let classpath = join_classpath(cp_entries);
let mut sources: Vec<PathBuf> = cp.src_dirs.into_iter().map(PathBuf::from).filter(|p| p.is_dir()).collect();
if sources.is_empty() {
let fallback: &[&str] = if test { &["src/test/java", "src/main/java"] } else { &["src/main/java"] };
sources.extend(fallback.iter().map(|s| module_dir.join(s)).filter(|p| p.is_dir()));
}
let javac = find_javac(&gradle.env);
let release = release_args(cp.release.or(gradle.java_version), java_home_major(&gradle.env));
let step =
build_javac_step(&javac, &module_dir, &out_dir, &classpath, &sources, release, file, gradle.env.clone())?;
Ok(BuildPlan { system: BuildSystem::Gradle, title: format!("Compile {name}"), steps: vec![step] })
}
#[cfg(test)]
mod tests {
use super::*;
@@ -439,7 +650,8 @@ mod tests {
#[test]
fn target_finds_the_owning_module_and_the_test_scope() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let model = fixture(root);
let main = single_file_target(root, &model, &root.join("app/src/main/java/demo/Main.java")).unwrap();
assert_eq!(main.module, root.join("app"));
@@ -453,7 +665,8 @@ mod tests {
#[test]
fn target_rejects_non_java_missing_and_unlinked_files() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let model = fixture(root);
write(root, "app/pom.xml", "<project/>");
assert!(single_file_target(root, &model, &root.join("app/pom.xml")).is_err());
@@ -465,7 +678,8 @@ mod tests {
#[test]
fn javac_prefers_the_module_jdk_and_scopes_test_sources() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let model = fixture(root);
let file = root.join("app/src/test/java/demo/MainTest.java");
let target = single_file_target(root, &model, &file).unwrap();
@@ -501,7 +715,8 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
fixture(root);
let script = root.join("mvnw");
fs::write(
@@ -532,6 +747,7 @@ mod tests {
assert!(cp.split(separator).count() >= 3, "{cp}");
let args = fs::read_to_string(root.join("args.txt")).unwrap();
assert!(!args.lines().any(|a| a == "compile" || a == "package"), "{args}");
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=compile"), "{args}");
fs::create_dir_all(root.join("app/target/test-classes")).unwrap();
let target = single_file_target(root, &model, &root.join("app/src/test/java/demo/MainTest.java")).unwrap();
let cp = single_file_classpath(root, &model, &target).unwrap();
@@ -539,6 +755,8 @@ mod tests {
assert_eq!(paths[0], root.join("app/target/test-classes"));
assert!(paths.contains(&root.join("app/target/classes")), "{cp}");
assert!(!paths.contains(&root.join("lib/target/test-classes")), "{cp}");
let args = fs::read_to_string(root.join("args.txt")).unwrap();
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
}
/// Launches request Maven's matching scope without adding reactor test outputs.
@@ -548,7 +766,8 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
fixture(root);
let script = root.join("mvnw");
fs::write(
@@ -605,7 +824,8 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
fixture(root);
write(root, "lib/src/main/java/demo/Lib.java", "class Lib {}");
let script = root.join("mvnw");
@@ -646,7 +866,8 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
fixture(root);
let script = root.join("mvnw");
// `dependency:build-classpath` reports reactor outputs as absolute paths. Keep
@@ -712,4 +933,79 @@ mod tests {
calls.push('x');
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), calls);
}
#[test]
fn javac_step_omits_empty_classpath_and_uses_source_target_on_jdk_8() {
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let mut model = fixture(root);
let file = root.join("app/src/main/java/demo/Main.java");
let jdk8 = root.join("jdk8");
fs::create_dir_all(jdk8.join("bin")).unwrap();
fs::write(jdk8.join("release"), "JAVA_VERSION=\"1.8.0_372\"\n").unwrap();
let project = model.maven.as_mut().unwrap().projects.iter_mut().find(|p| p.dir == "app").unwrap();
project.java_version = Some(8);
let mut target = single_file_target(root, &model, &file).unwrap();
target.top.env.insert("JAVA_HOME".into(), jdk8.to_string_lossy().into_owned());
let step = javac_step(&target, &file, "", "javac").unwrap();
assert!(!step.args.iter().any(|a| a == "-cp"), "{:?}", step.args);
assert!(step.args.iter().any(|a| a == "-g"), "{:?}", step.args);
assert!(step.args.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"]), "{:?}", step.args);
assert!(!step.args.iter().any(|a| a == "--release"), "{:?}", step.args);
}
#[cfg(unix)]
#[test]
fn gradle_single_file_compiles_with_source_set_classpath_and_siblings() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
write(root, "settings.gradle", "include ':lib', ':app'");
write(root, "lib/build.gradle", "plugins { id 'java' }");
write(root, "app/build.gradle", "plugins { id 'java' }");
write(root, "app/src/main/java/demo/App.java", "package demo; class App {}");
write(root, "app/src/test/java/demo/AppTest.java", "package demo; class AppTest {}");
fs::create_dir_all(root.join("lib/build/classes/java/main")).unwrap();
fs::create_dir_all(root.join("app/build/classes/java/main")).unwrap();
let wrapper = root.join("gradlew");
fs::write(
&wrapper,
"#!/bin/sh\nprintf '%s\\n' \"$@\" > gradle_args.txt\nscope='main'\nfor a in \"$@\"; do\ncase \"$a\" in -Popenidea.scope=*) scope=\"${a#-Popenidea.scope=}\" ;; esac\ndone\nprintf '@openidea-compile-cp\\t{\"outDir\":\"%s/app/build/classes/java/%s\",\"classpath\":[\"%s/deps/guava.jar\"],\"srcDirs\":[\"%s/app/src/%s/java\"],\"release\":17}\\n' \"$PWD\" \"$scope\" \"$PWD\" \"$PWD\" \"$scope\"\n",
)
.unwrap();
fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755)).unwrap();
let model = crate::load(root, &root.join("cache"), None);
let cache = root.join("cache");
let cancel = CancellationToken::new();
let main_file = root.join("app/src/main/java/demo/App.java");
let main_plan = gradle_compile_file_plan(root, &model, &main_file, &cache, &cancel).unwrap();
assert_eq!(main_plan.system, BuildSystem::Gradle);
assert_eq!(main_plan.title, "Compile App.java");
let step = &main_plan.steps[0];
let args = fs::read_to_string(root.join("gradle_args.txt")).unwrap();
assert!(args.lines().any(|a| a == "-Popenidea.target=:app"), "{args}");
assert!(args.lines().any(|a| a == "-Popenidea.scope=main"), "{args}");
let cp = &step.args[step.args.iter().position(|a| a == "-cp").unwrap() + 1];
let paths: Vec<_> = std::env::split_paths(cp).collect();
assert!(paths.contains(&root.join("app/build/classes/java/main")), "{cp}");
assert!(paths.contains(&root.join("lib/build/classes/java/main")), "{cp}");
assert!(paths.contains(&root.join("deps/guava.jar")), "{cp}");
assert!(step.args.windows(2).any(|w| w == ["--release", "17"]), "{:?}", step.args);
assert!(step.args.iter().any(|a| a == "-implicit:none"), "{:?}", step.args);
let test_file = root.join("app/src/test/java/demo/AppTest.java");
let test_plan = gradle_compile_file_plan(root, &model, &test_file, &cache, &cancel).unwrap();
assert_eq!(test_plan.title, "Compile AppTest.java");
let test_step = &test_plan.steps[0];
let args = fs::read_to_string(root.join("gradle_args.txt")).unwrap();
assert!(args.lines().any(|a| a == "-Popenidea.scope=test"), "{args}");
assert!(
test_step.args.windows(2).any(|w| w == ["-d", &root.join("app/build/classes/java/test").to_string_lossy()])
);
}
}
+157 -21
View File
@@ -162,16 +162,6 @@ fn classpath(entries: &[String]) -> String {
entries.join(if cfg!(windows) { ";" } else { ":" })
}
/// `--release N` from JDK 9 on; older compilers only know `-source` / `-target`.
fn release_args(level: Option<u32>, jdk: Option<&StructureJdk>) -> Vec<String> {
let Some(level) = level else { return Vec::new() };
if jdk.is_none_or(|j| j.major >= 9) {
vec!["--release".into(), level.to_string()]
} else {
vec!["-source".into(), format!("1.{level}"), "-target".into(), format!("1.{level}")]
}
}
/// `"17"`, `"1.8"`, `"JDK_17"` → the release number.
pub fn language_release(level: &str) -> Option<u32> {
let digits = level.trim().trim_start_matches("JDK_").trim_start_matches("jdk").replace('_', ".");
@@ -179,6 +169,25 @@ pub fn language_release(level: &str) -> Option<u32> {
digits.split(['.', ' ']).next()?.parse().ok().filter(|n| *n > 0)
}
fn structure_compiler(
root: &Path,
ps: &ProjectStructureSettings,
jdk: Option<&StructureJdk>,
language_level: &str,
) -> (Option<u32>, BTreeMap<String, String>, String) {
let module = root_module(root, ps);
let level = module
.map(|m| m.language_level.as_str())
.filter(|l| !l.trim().is_empty())
.or(Some(language_level))
.and_then(language_release);
let env: BTreeMap<String, String> = jdk
.map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())]))
.unwrap_or_default();
let javac = find_javac(&env);
(level, env, javac)
}
/// The Build / Rebuild plan of a project without a build tool, or `None` when it has no
/// Java sources under its source roots. `language_level`: the project's, unless the module
/// overrides it. Writes the javac argument files below `cache`.
@@ -203,16 +212,7 @@ pub fn structure_plan(
return Ok(None);
}
let (main_out, test_out) = structure_outputs(root, ps);
let module = root_module(root, ps);
let level = module
.map(|m| m.language_level.as_str())
.filter(|l| !l.trim().is_empty())
.or(Some(language_level))
.and_then(language_release);
let env: BTreeMap<String, String> = jdk
.map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())]))
.unwrap_or_default();
let javac = find_javac(&env);
let (level, env, javac) = structure_compiler(root, ps, jdk, language_level);
let args_dir = cache.join("javac");
fs::create_dir_all(&args_dir)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", args_dir.display())))?;
@@ -241,7 +241,7 @@ pub fn structure_plan(
if !cp.is_empty() {
step.args.extend(["-cp".into(), classpath(cp)]);
}
step.args.extend(release_args(level, jdk));
step.args.extend(single::release_args(level, jdk.map(|j| j.major)));
step.args.push(format!("@{}", args_file.to_string_lossy()));
step.env = env.clone();
step.mkdirs = vec![out.to_path_buf()];
@@ -281,6 +281,47 @@ pub fn structure_plan(
Ok(Some(BuildPlan { system: BuildSystem::Javac, title: module_name(root), steps }))
}
/// Single-file `javac` plan for a Java project without a build tool (Project Structure).
pub fn structure_compile_file_plan(
root: &Path,
ps: &ProjectStructureSettings,
roots: &StructureRoots,
jdk: Option<&StructureJdk>,
language_level: &str,
file: &Path,
) -> IdeResult<BuildPlan> {
let name = single::is_java_file(file)?;
let rel = rel_str(root, file);
let test = if roots.tests.is_empty() {
single::is_test_source(&rel)
} else {
let file_norm = normalize(file);
roots.tests.iter().any(|t| file_norm.starts_with(normalize(t)))
};
let (main_out, test_out) = structure_outputs(root, ps);
let out_dir = if test { &test_out } else { &main_out };
let mut cp: Vec<String> = Vec::new();
if test && test_out.is_dir() {
cp.push(test_out.to_string_lossy().into_owned());
}
if main_out.is_dir() {
cp.push(main_out.to_string_lossy().into_owned());
}
cp.extend(library_entries(root, ps, test));
let cp = single::join_classpath(cp);
let mut src_roots: Vec<PathBuf> = Vec::new();
if test {
src_roots.extend(roots.tests.iter().filter(|p| p.is_dir()).cloned());
}
src_roots.extend(roots.sources.iter().filter(|p| p.is_dir()).cloned());
let (level, env, javac) = structure_compiler(root, ps, jdk, language_level);
let release = single::release_args(level, jdk.map(|j| j.major));
let step = single::build_javac_step(&javac, root, out_dir, &cp, &src_roots, release, file, env)?;
Ok(BuildPlan { system: BuildSystem::Javac, title: format!("Compile {name}"), steps: vec![step] })
}
/// Where an artifact goes: its output folder, else `out/artifacts/<name>`.
pub fn artifact_output(root: &Path, artifact: &ArtifactConfig) -> PathBuf {
resolve_dir(root, &artifact.output_directory)
@@ -1008,4 +1049,99 @@ mod tests {
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
assert!(project.join("c.jar").is_file());
}
#[test]
fn plans_single_file_javac_for_main_test_and_jdk8() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("shop");
write(&root.join("src/com/a/Main.java"), "package com.a; class Main {}");
write(&root.join("test/com/a/MainTest.java"), "package com.a; class MainTest {}");
write(&root.join("out/production/shop/com/a/Helper.class"), "");
let ps = ProjectStructureSettings {
libraries: vec![
ProjectLibrary { name: "core".into(), classes: vec!["lib/core.jar".into()], ..Default::default() },
ProjectLibrary {
name: "junit".into(),
classes: vec!["lib/junit.jar".into()],
scope: DependencyScope::Test,
..Default::default()
},
],
..Default::default()
};
let roots =
StructureRoots { sources: vec![root.join("src")], tests: vec![root.join("test")], ..Default::default() };
let jdk21 = StructureJdk { home: PathBuf::from("/jdk21"), major: 21 };
let main_plan =
structure_compile_file_plan(&root, &ps, &roots, Some(&jdk21), "17", &root.join("src/com/a/Main.java"))
.unwrap();
assert_eq!(main_plan.system, BuildSystem::Javac);
assert_eq!(main_plan.title, "Compile Main.java");
let main_step = &main_plan.steps[0];
let cp = &main_step.args[main_step.args.iter().position(|a| a == "-cp").unwrap() + 1];
assert!(cp.contains("core.jar") && !cp.contains("junit.jar"), "{cp}");
assert!(main_step.args.windows(2).any(|w| w == ["--release", "17"]));
assert!(main_step.args.iter().any(|a| a == "-implicit:none"));
let jdk8 = StructureJdk { home: PathBuf::from("/jdk8"), major: 8 };
let test_plan =
structure_compile_file_plan(&root, &ps, &roots, Some(&jdk8), "8", &root.join("test/com/a/MainTest.java"))
.unwrap();
let test_step = &test_plan.steps[0];
let test_cp = &test_step.args[test_step.args.iter().position(|a| a == "-cp").unwrap() + 1];
assert!(test_cp.contains("out/production/shop") || test_cp.contains("out\\production\\shop"), "{test_cp}");
assert!(test_cp.contains("junit.jar"), "{test_cp}");
assert!(test_step.args.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"]));
assert!(test_step.args.windows(2).any(|w| w[0] == "-d" && Path::new(&w[1]).ends_with("out/test/shop")));
}
#[test]
fn compiles_only_the_target_java_file_and_reports_errors() {
let exe = if cfg!(windows) { "javac.exe" } else { "javac" };
if !std::process::Command::new(exe).arg("-version").output().is_ok_and(|o| o.status.success()) {
return;
}
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("demo");
let good = root.join("src/p/Good.java");
let broken_sibling = root.join("src/p/BrokenSibling.java");
let bad_target = root.join("src/p/BadTarget.java");
write(&good, "package p;\npublic class Good { public static int ok() { return 1; } }\n");
write(&broken_sibling, "package p;\npublic class BrokenSibling { MissingType field; }\n");
write(&bad_target, "package p;\npublic class BadTarget {\n UnknownSymbol field;\n}\n");
let ps = ProjectStructureSettings::default();
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
let cancel = CancellationToken::new();
// 1. Valid file compiles cleanly without touching or failing on BrokenSibling.java.
let plan = structure_compile_file_plan(&root, &ps, &roots, None, "", &good).unwrap();
let events = std::sync::Mutex::new(Vec::new());
let result = run(&root, &plan, &cancel, &|e| events.lock().unwrap().push(e)).unwrap();
assert!(result.success, "expected single-file compile to succeed: {:?}", result.messages);
assert_eq!(result.errors, 0);
assert!(root.join("out/production/demo/p/Good.class").is_file());
assert!(!root.join("out/production/demo/p/BrokenSibling.class").exists());
// 2. Broken target fails, streams raw compiler output, and produces structured diagnostics.
let plan = structure_compile_file_plan(&root, &ps, &roots, None, "", &bad_target).unwrap();
let bad_events = std::sync::Mutex::new(Vec::new());
let bad_result = run(&root, &plan, &cancel, &|e| bad_events.lock().unwrap().push(e)).unwrap();
assert!(!bad_result.success);
assert!(bad_result.errors >= 1, "{bad_result:?}");
assert!(
bad_events.lock().unwrap().iter().any(|e| matches!(e, BuildEvent::Output { .. })),
"expected streamed output"
);
assert!(
bad_result.messages.iter().any(|m| {
m.severity == Severity::Error
&& m.path.as_ref().is_some_and(|p| <ide_core::IpcPath as AsRef<Path>>::as_ref(p) == bad_target)
&& m.range.is_some_and(|r| r.start.line == 2)
}),
"messages={:?}",
bad_result.messages
);
}
}
@@ -0,0 +1,58 @@
// OpenIDEA single-file javac classpath probe for Gradle projects.
// Prints the target source set's output directory, compile classpath, source dirs and release version.
import groovy.json.JsonOutput
def identity = { Project p -> try { p.identityPath.toString() } catch (ignored) { p.path } }
gradle.projectsEvaluated { g ->
def wantedTarget = g.rootProject.findProperty('openidea.target')?.toString() ?: ':'
def scope = g.rootProject.findProperty('openidea.scope')?.toString() ?: 'main'
def project = g.rootProject.allprojects.find { identity(it) == wantedTarget }
if (project == null && g.parent == null) {
project = g.rootProject.allprojects.find { it.path == wantedTarget }
}
if (project == null) return
def sets = project.extensions.findByName('sourceSets') ?: project.findProperty('sourceSets')
def ss = sets?.findByName(scope)
if (ss == null) return
def outDir = null
try { outDir = ss.java.destinationDirectory.get().asFile.canonicalPath } catch (ignored) {}
if (outDir == null) {
try { outDir = ss.output.classesDirs.files.iterator().next().canonicalPath } catch (ignored) {}
}
def cp = []
if (scope == 'test') {
def mainSet = sets.findByName('main')
try { mainSet?.output?.classesDirs?.files?.each { cp << it.canonicalPath } } catch (ignored) {}
}
try { ss.compileClasspath.files.each { cp << it.canonicalPath } } catch (ignored) {}
cp = cp.unique()
def srcDirs = []
try { ss.java.srcDirs.each { srcDirs << it.canonicalPath } } catch (ignored) {}
if (scope == 'test') {
def mainSet = sets.findByName('main')
try { mainSet?.java?.srcDirs?.each { srcDirs << it.canonicalPath } } catch (ignored) {}
}
srcDirs = srcDirs.unique()
def release = null
try {
def compileTask = project.tasks.findByName(ss.compileJavaTaskName)
release = compileTask?.options?.release?.getOrNull()
} catch (ignored) {}
if (release == null) {
try {
def java = project.extensions.findByName('java')
def lv = null
try { lv = java?.toolchain?.languageVersion?.getOrNull() } catch (ignored) {}
def target = java != null ? java.targetCompatibility : project.findProperty('targetCompatibility')
release = lv != null ? lv.asInt() : (target?.majorVersion as Integer)
} catch (ignored) {}
}
println '@openidea-compile-cp\t' + JsonOutput.toJson([outDir: outDir, classpath: cp, srcDirs: srcDirs, release: release])
}
+1
View File
@@ -16,6 +16,7 @@ mod process;
#[cfg(test)]
mod process_numbers;
pub mod sbt;
pub mod surefire;
mod sync;
pub mod web;
mod xml;
+71 -34
View File
@@ -31,40 +31,6 @@ pub const LOCAL_REPO_TRACKING_ARG: &str = "-Daether.enhancedLocalRepository.trac
pub const LIFECYCLE: &[&str] =
&["clean", "validate", "compile", "test", "package", "verify", "install", "site", "deploy"];
/// Every phase of the clean, default and site lifecycles (Execute Maven Goal completion).
pub const ALL_PHASES: &[&str] = &[
"pre-clean",
"clean",
"post-clean",
"validate",
"initialize",
"generate-sources",
"process-sources",
"generate-resources",
"process-resources",
"compile",
"process-classes",
"generate-test-sources",
"process-test-sources",
"generate-test-resources",
"process-test-resources",
"test-compile",
"process-test-classes",
"test",
"prepare-package",
"package",
"pre-integration-test",
"integration-test",
"post-integration-test",
"verify",
"install",
"deploy",
"pre-site",
"site",
"post-site",
"site-deploy",
];
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MavenModel {
@@ -551,6 +517,59 @@ pub fn local_repository_of(settings: &Path) -> Option<PathBuf> {
Some(PathBuf::from(repo.replace("${user.home}", &home)))
}
/// The local repository a Maven run with these options resolves into: `-Dmaven.repo.local=`
/// first, then `<localRepository>` of the `-s` settings, then the user's default.
pub fn local_repository_for(options: &[String]) -> Option<PathBuf> {
if let Some(repo) = options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")) {
return Some(PathBuf::from(repo));
}
let mut args = options.iter();
while let Some(arg) = args.next() {
let path = match arg.as_str() {
"-s" | "--settings" => args.next().map(String::as_str),
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
};
if let Some(path) = path {
return local_repository_of(Path::new(path)).or_else(default_local_repo);
}
}
default_local_repo()
}
/// A goal of the IDE's own (`help:evaluate`, `dependency:build-classpath`, …) by its plugin's
/// coordinates rather than its prefix: offline, Maven resolves a prefix only from group metadata
/// in the local repository, which a repository filled from a private mirror often lacks even when
/// the plugin itself is there. Uses the newest 3.x version already in `repo`, so nothing is
/// downloaded, else a pinned one.
pub fn plugin_goal(goal: &str, repo: Option<&Path>) -> String {
let (prefix, goal) = goal.split_once(':').expect("prefix:goal");
let (artifact, pinned) = match prefix {
"help" => ("maven-help-plugin", "3.5.1"),
"dependency" => ("maven-dependency-plugin", "3.8.1"),
_ => unreachable!("not a goal of the IDE's own: {prefix}"),
};
let version = repo.and_then(|repo| newest_local_plugin(repo, artifact, 3)).unwrap_or_else(|| pinned.to_owned());
format!("org.apache.maven.plugins:{artifact}:{version}:{goal}")
}
/// The newest release of `org.apache.maven.plugins:<artifact>` whose jar is in `repo`,
/// from major version `min_major` up.
pub(crate) fn newest_local_plugin(repo: &Path, artifact: &str, min_major: u64) -> Option<String> {
let dir = repo.join("org/apache/maven/plugins").join(artifact);
let parse = |v: &str| v.split('.').map(|n| n.parse::<u64>().ok()).collect::<Option<Vec<u64>>>();
std::fs::read_dir(&dir)
.ok()?
.flatten()
.filter_map(|e| e.file_name().into_string().ok())
.filter_map(|v| parse(&v).map(|n| (n, v)))
.filter(|(n, v)| {
n.first().is_some_and(|&major| major >= min_major)
&& dir.join(v).join(format!("{artifact}-{v}.jar")).is_file()
})
.max()
.map(|(_, v)| v)
}
impl Resolver {
fn new(local_repo: Option<PathBuf>, profiles: &[String]) -> Self {
Self::new_with_jdk(local_repo, profiles, None)
@@ -2591,6 +2610,24 @@ mod tests {
assert!(local_repository_of(&tmp.path().join("missing.xml")).is_none());
}
#[test]
fn ide_goals_resolve_from_the_repository_the_run_uses() {
let tmp = tempfile::tempdir().unwrap();
let settings = tmp.path().join("settings.xml");
std::fs::write(&settings, "<settings><localRepository>/srv/m2</localRepository></settings>").unwrap();
let s = settings.to_string_lossy().into_owned();
let opts = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(local_repository_for(&opts(&["-s", &s])), Some(PathBuf::from("/srv/m2")));
assert_eq!(local_repository_for(&opts(&[&format!("--settings={s}")])), Some(PathBuf::from("/srv/m2")));
let explicit = opts(&["-s", &s, "-Dmaven.repo.local=/tmp/r"]);
assert_eq!(local_repository_for(&explicit), Some(PathBuf::from("/tmp/r")));
// No repository known: a pinned version, still by coordinates.
assert_eq!(
plugin_goal("dependency:build-classpath", None),
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:build-classpath"
);
}
#[test]
fn effective_pom_goals_come_from_the_local_repository_it_is_given() {
let tmp = tempfile::tempdir().unwrap();
+263 -13
View File
@@ -3,7 +3,13 @@
use super::MavenProject;
use crate::process;
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::collections::HashSet;
use std::fs::{self, File};
use std::path::{Component, Path, PathBuf};
use std::time::SystemTime;
const DEPENDENCY_PLUGIN: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1";
const SOURCE_REFRESH_WORKERS: usize = 4;
#[derive(Debug, PartialEq, Eq)]
pub struct Artifact {
@@ -11,6 +17,29 @@ pub struct Artifact {
pub name: String,
pub version: String,
pub sources: PathBuf,
binary: PathBuf,
}
fn valid_part(part: &str) -> bool {
!part.is_empty()
&& part != "."
&& part != ".."
&& part.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
}
fn modified_file(path: &Path) -> Option<SystemTime> {
let metadata = fs::metadata(path).ok()?;
if metadata.is_file() { metadata.modified().ok() } else { None }
}
impl Artifact {
fn stale_binary(&self) -> Option<SystemTime> {
if !self.version.ends_with("-SNAPSHOT") {
return None;
}
let binary = modified_file(&self.binary)?;
(modified_file(&self.sources)? < binary).then_some(binary)
}
}
/// Resolve only jars inside the selected local repository, including custom repositories.
@@ -28,16 +57,14 @@ pub fn artifact(jar: &Path, repository: &Path) -> Option<Artifact> {
}
let n = parts.len();
let (name, version, file) = (parts[n - 3], parts[n - 2], parts[n - 1]);
let valid = |s: &str| {
!s.is_empty() && s != "." && s != ".." && s.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
};
if !parts[..n - 1].iter().all(|s| valid(s)) || file != format!("{name}-{version}.jar") {
if !parts[..n - 1].iter().all(|s| valid_part(s)) || file != format!("{name}-{version}.jar") {
return None;
}
Some(Artifact {
group: parts[..n - 3].join("."),
name: name.into(),
version: version.into(),
binary: jar.to_owned(),
sources: jar.with_file_name(format!("{name}-{version}-sources.jar")),
})
}
@@ -48,26 +75,58 @@ pub fn download(
artifact: &Artifact,
repository: &Path,
cancel: &CancellationToken,
) -> IdeResult<Option<PathBuf>> {
resolve(root, project, artifact, repository, &[], artifact.stale_binary(), cancel)
}
fn resolve(
root: &Path,
project: &MavenProject,
artifact: &Artifact,
repository: &Path,
profile_args: &[String],
stale: Option<SystemTime>,
cancel: &CancellationToken,
) -> IdeResult<Option<PathBuf>> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if artifact.sources.is_file() {
if stale.is_none() && artifact.sources.is_file() {
return Ok(Some(artifact.sources.clone()));
}
let mut args = vec!["-B".into(), "-N".into(), "-Dstyle.color=never".into()];
args.extend(project.options.clone());
args.extend([
format!("-Dmaven.repo.local={}", repository.display()),
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:get".into(),
format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version),
"-Dtransitive=false".into(),
]);
args.extend(project.options.iter().cloned());
args.extend(profile_args.iter().cloned());
args.push(format!("-Dmaven.repo.local={}", repository.display()));
let coordinate = format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version);
let stage = if let Some(binary) = stale {
// Keep the existing attachment readable while Maven resolves the timestamped snapshot.
// Disable Resolver's in-place copy to the base -SNAPSHOT filename.
let stage =
tempfile::Builder::new().prefix(".openidea-sources-").tempdir_in(artifact.sources.parent().unwrap())?;
args.extend([
"-U".into(),
"-Daether.artifactResolver.snapshotNormalization=false".into(),
format!("{DEPENDENCY_PLUGIN}:copy"),
coordinate,
"-Dmdep.useBaseVersion=true".into(),
format!("-DoutputDirectory={}", stage.path().display()),
]);
Some((stage, binary))
} else {
args.extend([format!("{DEPENDENCY_PLUGIN}:get"), coordinate, "-Dtransitive=false".into()]);
None
};
let output = process::run(&project.command, &args, &root.join(&project.dir), &project.env, cancel, |_, _| {})?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if artifact.sources.is_file() {
if let Some((stage, binary)) = stage {
let resolved = stage.path().join(artifact.sources.file_name().unwrap());
if output.success && resolved.is_file() {
return replace_stale_sources(artifact, &resolved, binary, cancel);
}
} else if artifact.sources.is_file() {
return Ok(Some(artifact.sources.clone()));
}
let coordinate = format!("{}:{}:jar:sources:{}", artifact.group, artifact.name, artifact.version);
@@ -83,6 +142,115 @@ pub fn download(
))
}
fn replace_stale_sources(
artifact: &Artifact,
resolved: &Path,
binary: SystemTime,
cancel: &CancellationToken,
) -> IdeResult<Option<PathBuf>> {
// Maven can fall back to a locally installed snapshot. Keep its timestamp if it returned
// the same bytes so a later reload can retry when newer sources are available.
let hash = |path| -> std::io::Result<_> { Ok(blake3::Hasher::new().update_reader(File::open(path)?)?.finalize()) };
if hash(resolved)? == hash(&artifact.sources)? {
return Ok(None);
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
match artifact.stale_binary() {
Some(current) if current == binary => {
File::options().write(true).open(resolved)?.set_modified(SystemTime::now().max(binary))?;
fs::rename(resolved, &artifact.sources)?;
Ok(Some(artifact.sources.clone()))
}
None if artifact.sources.is_file() => Ok(Some(artifact.sources.clone())),
_ => Ok(None),
}
}
/// Resolved Maven dependencies with an existing attachment. Binaries may still be
/// updating during import, so freshness is checked when the refresh runs.
pub fn cached_snapshots<'a>(
repository: &Path,
projects: impl Iterator<Item = (usize, &'a MavenProject)>,
) -> Vec<(usize, Artifact)> {
let mut seen = HashSet::new();
let mut candidates = Vec::new();
for (owner, project) in projects {
let mut dependencies: Vec<_> = project.dependencies.iter().collect();
while let Some(dep) = dependencies.pop() {
if !dep.resolved() {
continue;
}
dependencies.extend(&dep.children);
let Some(version) = dep.version.as_deref().filter(|v| v.ends_with("-SNAPSHOT") && valid_part(v)) else {
continue;
};
if dep.scope == "system"
|| dep.classifier.is_some()
|| !matches!(dep.kind.as_str(), "jar" | "bundle" | "maven-plugin" | "ejb")
|| !valid_part(&dep.artifact_id)
|| !dep.group_id.split('.').all(valid_part)
{
continue;
}
let name = &dep.artifact_id;
let jar = repository
.join(dep.group_id.replace('.', "/"))
.join(name)
.join(version)
.join(format!("{name}-{version}.jar"));
if let Some(artifact) = artifact(&jar, repository)
&& artifact.sources.is_file()
&& seen.insert(jar)
{
candidates.push((owner, artifact));
}
}
}
candidates
}
/// Refresh only previously attached snapshots. Maven subprocesses are bounded
/// and share the build reload's cancellation token.
pub fn refresh_snapshots(
root: &Path,
projects: &[MavenProject],
repository: &Path,
candidates: &[(usize, Artifact)],
profiles: &[String],
cancel: &CancellationToken,
) -> Vec<PathBuf> {
let profile_args = if profiles.is_empty() { vec![] } else { vec![format!("-P{}", profiles.join(","))] };
let profile_args = &profile_args;
let stale: Vec<_> = candidates.iter().filter(|(_, artifact)| artifact.stale_binary().is_some()).collect();
let batch_size = stale.len().div_ceil(SOURCE_REFRESH_WORKERS).max(1);
std::thread::scope(|scope| {
let workers: Vec<_> = stale
.chunks(batch_size)
.map(|batch| {
scope.spawn(move || {
let mut refreshed = Vec::new();
for (owner, artifact) in batch.iter().copied() {
if cancel.is_cancelled() {
break;
}
let Some(binary) = artifact.stale_binary() else { continue };
match resolve(root, &projects[*owner], artifact, repository, profile_args, Some(binary), cancel)
{
Ok(Some(_)) => refreshed.push(artifact.binary.clone()),
Ok(None) => {}
Err(e) => tracing::debug!(path = %artifact.sources.display(), "Maven sources refresh: {e}"),
}
}
refreshed
})
})
.collect();
workers.into_iter().flat_map(|worker| worker.join().expect("Maven sources worker")).collect()
})
}
#[cfg(test)]
mod tests {
use super::*;
@@ -121,4 +289,86 @@ mod tests {
assert_eq!(artifact(Path::new(path), repository), None, "{path}");
}
}
#[test]
fn selects_existing_snapshot_attachments_from_the_resolved_tree() {
use crate::maven::{MavenDependency, Omission};
let repo = tempfile::tempdir().unwrap();
let dependency = |name: &str, version: &str, cached: bool| {
if cached {
let dir = repo.path().join("example").join(name).join(version);
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join(format!("{name}-{version}-sources.jar")), b"cached").unwrap();
}
MavenDependency {
group_id: "example".into(),
artifact_id: name.into(),
version: Some(version.into()),
kind: "jar".into(),
..Default::default()
}
};
let transitive = dependency("transitive", "1-SNAPSHOT", true);
let direct = MavenDependency { children: vec![transitive.clone()], ..dependency("direct", "1-SNAPSHOT", true) };
let omitted =
MavenDependency { omitted: Some(Omission::Conflict), ..dependency("omitted", "1-SNAPSHOT", true) };
let projects = [
MavenProject {
dependencies: vec![
direct,
omitted,
dependency("missing", "1-SNAPSHOT", false),
dependency("release", "1", true),
],
..Default::default()
},
MavenProject { dependencies: vec![transitive], ..Default::default() },
];
let mut found: Vec<_> = cached_snapshots(repo.path(), projects.iter().enumerate())
.into_iter()
.map(|(owner, artifact)| (owner, artifact.name))
.collect();
found.sort();
assert_eq!(found, [(0, "direct".into()), (0, "transitive".into())]);
}
#[cfg(unix)]
#[test]
fn downloads_sources_again_when_the_snapshot_binary_is_newer() {
use std::fs::FileTimes;
use std::os::unix::fs::PermissionsExt;
use std::time::Duration;
let dir = tempfile::tempdir().unwrap();
let repository = dir.path().join("repository");
let jar = repository.join("example/lib/1-SNAPSHOT/lib-1-SNAPSHOT.jar");
fs::create_dir_all(jar.parent().unwrap()).unwrap();
fs::write(&jar, b"new binary").unwrap();
let artifact = artifact(&jar, &repository).unwrap();
fs::write(&artifact.sources, b"old sources").unwrap();
File::open(&artifact.sources)
.unwrap()
.set_times(FileTimes::new().set_modified(SystemTime::now() - Duration::from_secs(60)))
.unwrap();
let launcher = dir.path().join("mvn");
fs::write(
&launcher,
"#!/bin/sh\nfor arg do\n case \"$arg\" in\n -DoutputDirectory=*) out=\"${arg#*=}\" ;;\n esac\ndone\nprintf 'new sources' > \"$out/lib-1-SNAPSHOT-sources.jar\"\n",
)
.unwrap();
fs::set_permissions(&launcher, fs::Permissions::from_mode(0o755)).unwrap();
let cancel = CancellationToken::new();
cancel.cancel();
assert!(download(dir.path(), &MavenProject::default(), &artifact, &repository, &cancel).is_err());
assert_eq!(fs::read(&artifact.sources).unwrap(), b"old sources");
let project = MavenProject { command: launcher.to_string_lossy().into_owned(), ..Default::default() };
let cancel = CancellationToken::new();
let path = download(dir.path(), &project, &artifact, &repository, &cancel).unwrap().unwrap();
assert_eq!(fs::read(&path).unwrap(), b"new sources");
assert_eq!(
download(dir.path(), &MavenProject::default(), &artifact, &repository, &CancellationToken::new()).unwrap(),
Some(path)
);
}
}
+216
View File
@@ -0,0 +1,216 @@
//! A Maven module's Surefire configuration, for test runs OpenIDEA starts itself instead of
//! Surefire (IDEA's `MavenJUnitPatcher`): what the forked test JVM would get from the POM.
//!
//! Read from the effective POM the last sync cached (Maven merged parents, profiles and
//! `pluginManagement` there), else from the module's own `pom.xml` and its `<properties>`.
use crate::maven::{MavenModel, interpolate};
use crate::xml::{self, Element};
use std::collections::{BTreeMap, HashMap};
use std::path::Path;
const SUREFIRE: &str = "maven-surefire-plugin";
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SurefireConfig {
/// `<argLine>`, split into JVM options.
pub arg_line: Vec<String>,
/// `<systemPropertyVariables>` and the older `<systemProperties>`.
pub system_properties: BTreeMap<String, String>,
/// `<environmentVariables>`.
pub environment: BTreeMap<String, String>,
pub working_directory: Option<String>,
/// `<additionalClasspathElements>`.
pub additional_classpath: Vec<String>,
/// `<classpathDependencyExcludes>`: `groupId:artifactId`.
pub classpath_excludes: Vec<String>,
}
/// The Surefire configuration of the Maven module at `module` (absolute), if it is one.
pub fn surefire_config(root: &Path, cache_dir: &Path, model: &MavenModel, module: &Path) -> Option<SurefireConfig> {
let same = |a: &Path, b: &Path| dunce::canonicalize(a).ok() == dunce::canonicalize(b).ok();
let project = model.projects.iter().find(|p| same(&root.join(&p.dir), module))?;
let pom = root.join(&project.pom);
let modified = |p: &Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();
// A cache written before the POM last changed would apply an old configuration.
let effective = std::fs::read_dir(cache_dir).ok()?.flatten().map(|e| e.path()).find_map(|path| {
let name = path.file_name()?.to_str()?;
if !(name.starts_with("effective-pom-") && name.ends_with(".xml")) || modified(&path) < modified(&pom) {
return None;
}
let root = xml::parse(&xml::read_text(&path)?)?;
let projects: Vec<Element> = if root.name == "projects" {
root.children.into_iter().filter(|p| p.name == "project").collect()
} else {
vec![root]
};
projects.into_iter().find(|p| {
let group = p.text_of("groupId").or_else(|| p.at("parent/groupId").map(|g| g.text.trim().to_owned()));
group.as_deref() == Some(project.group_id.as_str())
&& p.text_of("artifactId").as_deref() == Some(&project.artifact_id)
})
});
let (element, own) = match effective {
Some(e) => (e, false),
// ponytail: without a sync, inherited configuration and parent properties are missing; Reload adds them.
None => (xml::parse(&xml::read_text(&pom)?)?, true),
};
let mut props: HashMap<String, String> = element
.child("properties")
.map(|p| p.children.iter().map(|c| (c.name.clone(), c.text.trim().to_owned())).collect())
.unwrap_or_default();
let dir = module.to_string_lossy().into_owned();
for (key, value) in [
("basedir", dir.clone()),
("project.basedir", dir.clone()),
("project.build.directory", format!("{dir}/target")),
("project.groupId", project.group_id.clone()),
("project.artifactId", project.artifact_id.clone()),
("project.version", project.version.clone()),
] {
props.entry(key.into()).or_insert(value);
}
Some(read(&element, &props, own))
}
/// `<build><plugins>` Surefire's configuration, then its `default-test` execution's.
fn read(project: &Element, props: &HashMap<String, String>, own: bool) -> SurefireConfig {
let is_surefire = |p: &&Element| p.text_of("artifactId").as_deref() == Some(SUREFIRE);
let mut plugins: Vec<&Element> = project.list("build/plugins", "plugin").into_iter().filter(is_surefire).collect();
if own && plugins.is_empty() {
plugins = project.list("build/pluginManagement/plugins", "plugin").into_iter().filter(is_surefire).collect();
}
let mut configurations: Vec<&Element> = Vec::new();
for plugin in plugins {
configurations.extend(plugin.child("configuration"));
let default_test = plugin
.list("executions", "execution")
.into_iter()
.find(|e| e.text_of("id").as_deref() == Some("default-test"));
configurations.extend(default_test.and_then(|e| e.child("configuration")));
}
let value = |text: &str| resolve(text.trim(), props);
let mut config = SurefireConfig::default();
for c in configurations {
if let Some(arg_line) = c.child("argLine") {
config.arg_line = split_arg_line(&value(&arg_line.text));
}
for p in c.child("systemPropertyVariables").map_or(&[][..], |p| &p.children) {
config.system_properties.insert(p.name.clone(), value(&p.text));
}
// `<systemProperties>`: `<property><name/><value/></property>` (deprecated, still honoured).
for p in c.list("systemProperties", "property") {
if let Some(name) = p.text_of("name") {
config.system_properties.insert(name, value(&p.text_of("value").unwrap_or_default()));
}
}
for e in c.child("environmentVariables").map_or(&[][..], |e| &e.children) {
config.environment.insert(e.name.clone(), value(&e.text));
}
if let Some(dir) = c.text_of("workingDirectory").map(|d| value(&d)).filter(|d| !d.is_empty()) {
config.working_directory = Some(dir);
}
let texts = |list: &str, item: &str| -> Vec<String> {
c.list(list, item).into_iter().map(|e| value(&e.text)).filter(|t| !t.is_empty()).collect()
};
config.additional_classpath.extend(texts("additionalClasspathElements", "additionalClasspathElement"));
config.classpath_excludes.extend(texts("classpathDependencyExcludes", "classpathDependencyExclude"));
}
config
}
/// `${…}` from the POM's properties, then Surefire's late replacement `@{…}` (a property a plugin
/// sets during the build, such as JaCoCo's `argLine`, is unknown here and left out, as in IDEA).
fn resolve(text: &str, props: &HashMap<String, String>) -> String {
let mut out = interpolate(text, props);
for open in ["@{", "${"] {
while let Some(start) = out.find(open) {
let Some(len) = out[start..].find('}') else { break };
let key = &out[start + 2..start + len];
let replacement = if open == "@{" { props.get(key).cloned().unwrap_or_default() } else { String::new() };
out.replace_range(start..=start + len, &replacement);
}
}
out.trim().to_owned()
}
/// Splits `argLine` as Surefire does (plexus `CommandLineUtils`): whitespace, `"…"` and `'…'`, no escapes.
fn split_arg_line(line: &str) -> Vec<String> {
let mut out = Vec::new();
let mut current: Option<String> = None;
let mut quote: Option<char> = None;
for c in line.chars() {
match quote {
Some(q) if c == q => quote = None,
Some(_) => current.get_or_insert_default().push(c),
None if c == '"' || c == '\'' => {
quote = Some(c);
current.get_or_insert_default();
}
None if c.is_whitespace() => out.extend(current.take()),
None => current.get_or_insert_default().push(c),
}
}
out.extend(current);
out
}
#[cfg(test)]
mod tests {
use super::*;
const POM: &str = r#"<project>
<groupId>com.example</groupId><artifactId>orders</artifactId><version>1</version>
<properties><openideaFail>true</openideaFail><mockito>/m2/mockito.jar</mockito></properties>
<build><plugins><plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>@{argLine} @{jacoco} -javaagent:${mockito} --add-opens "java.base/java.lang=ALL-UNNAMED" -Dx=${undefined}</argLine>
<systemPropertyVariables><openidea.fail>${openideaFail}</openidea.fail><dir>${project.build.directory}</dir></systemPropertyVariables>
<systemProperties><property><name>old</name><value>style</value></property></systemProperties>
<environmentVariables><TZ>UTC</TZ></environmentVariables>
<additionalClasspathElements><additionalClasspathElement>${basedir}/extra</additionalClasspathElement></additionalClasspathElements>
<classpathDependencyExcludes><classpathDependencyExclude>org.slf4j:slf4j-simple</classpathDependencyExclude></classpathDependencyExcludes>
</configuration>
<executions><execution><id>default-test</id><configuration><workingDirectory>${basedir}/work</workingDirectory></configuration></execution></executions>
</plugin></plugins></build>
</project>"#;
fn model(dir: &Path) -> MavenModel {
crate::maven::load(dir)
}
#[test]
fn reads_the_module_pom_and_the_effective_pom_the_sync_cached() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(root.join("pom.xml"), POM).unwrap();
let cache = root.join("cache");
std::fs::create_dir_all(&cache).unwrap();
let config = surefire_config(root, &cache, &model(root), root).unwrap();
let d = root.to_string_lossy();
assert_eq!(
config.arg_line,
["-javaagent:/m2/mockito.jar", "--add-opens", "java.base/java.lang=ALL-UNNAMED", "-Dx="]
);
assert_eq!(config.system_properties["openidea.fail"], "true");
assert_eq!(config.system_properties["dir"], format!("{d}/target"));
assert_eq!(config.system_properties["old"], "style");
assert_eq!(config.environment["TZ"], "UTC");
assert_eq!(config.working_directory, Some(format!("{d}/work")));
assert_eq!(config.additional_classpath, [format!("{d}/extra")]);
assert_eq!(config.classpath_excludes, ["org.slf4j:slf4j-simple"]);
// A sync's effective POM wins: it has what the module inherits.
let effective = POM.replace("<argLine>", "<argLine>-Xmx1g ").replace("<TZ>UTC</TZ>", "<TZ>Asia/Tokyo</TZ>");
std::fs::write(cache.join("effective-pom-0.xml"), format!("<projects>{effective}</projects>")).unwrap();
let config = surefire_config(root, &cache, &model(root), root).unwrap();
assert_eq!(config.arg_line[0], "-Xmx1g");
assert_eq!(config.environment["TZ"], "Asia/Tokyo");
}
#[test]
fn splits_arg_line_like_surefire() {
assert_eq!(split_arg_line(r#" -a "b c" 'd "e"' C:\x\y "" "#), ["-a", "b c", r#"d "e""#, r"C:\x\y", ""]);
}
}
+54 -36
View File
@@ -86,22 +86,37 @@ const MAVEN_CACHE_VERSION: u32 = 1;
/// `dependency:tree` of a plugin version whose `-Dverbose` lists the occurrences Maven
/// omitted (conflicts, duplicates): verbose output was dropped in 3.0 and is back since 3.2.
/// Offline, it is used only when an earlier sync downloaded it; otherwise the project's own
/// plugin version is, which may be cached instead.
/// Offline, it is used only when an earlier sync downloaded it; otherwise the newest version
/// in the local repository is.
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
const DEPENDENCY_TREE_JAR: &str =
"org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar";
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
/// `repo` is the local repository the build resolves from.
/// `repo` is the local repository the build resolves from. Both goals name their plugin by
/// coordinates: offline, a prefix resolves only from group metadata the repository may lack.
/// Offline without a cached 3.x `maven-help-plugin`, `effective-pom` is skipped so `mvn -o`
/// still resolves the dependency tree instead of failing to download the help plugin.
fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec<String> {
let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file());
vec![
"help:effective-pom".into(),
format!("-Doutput={}", effective.to_string_lossy()),
if pinned { DEPENDENCY_TREE.into() } else { "dependency:tree".into() },
"-Dverbose".into(),
]
let tree = if pinned {
DEPENDENCY_TREE.to_owned()
} else {
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2)).map_or_else(
|| "dependency:tree".to_owned(),
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
)
};
let has_help =
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3).is_some());
let mut goals = Vec::with_capacity(4);
if has_help {
goals.push(maven::plugin_goal("help:effective-pom", repo));
goals.push(format!("-Doutput={}", effective.to_string_lossy()));
}
goals.push(tree);
goals.push("-Dverbose".into());
goals
}
/// The settings' Maven options for the sync runs: the thread count (`-T`, also
@@ -367,25 +382,8 @@ pub fn sync_maven(
verbose: true,
..MavenCache::default()
};
// Where the build resolves its jars, and therefore where the plugin goals are read
// from: `-Dmaven.repo.local=` first, then `<localRepository>` of the `-s` settings,
// then the user's default repository (which `plugin()` resolves itself).
let local_repo: Option<PathBuf> =
options.maven_options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")).map(PathBuf::from).or_else(
|| {
let mut args = options.maven_options.iter();
while let Some(arg) = args.next() {
let path = match arg.as_str() {
"-s" | "--settings" => args.next().map(String::as_str),
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
};
if let Some(path) = path {
return maven::local_repository_of(Path::new(path));
}
}
None
},
);
// Where the build resolves its jars, and therefore where the plugin goals are read from.
let repo = maven::local_repository_for(&options.maven_options);
let mut errors: Vec<String> = Vec::new();
for (n, top) in model.projects.iter().filter(|p| !p.aggregated).enumerate() {
let effective = cache_dir.join(format!("effective-pom-{n}.xml"));
@@ -407,7 +405,6 @@ pub fn sync_maven(
if !options.profiles.is_empty() {
args.push(format!("-P{}", options.profiles.join(",")));
}
let repo = local_repo.clone().or_else(maven::default_local_repo);
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref()));
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
let command = options.maven_command.as_deref().unwrap_or(&top.command);
@@ -425,7 +422,7 @@ pub fn sync_maven(
}
})?;
let effective_projects = std::fs::read_to_string(&effective)
.map(|t| maven::parse_effective_pom_in(&t, local_repo.as_deref()))
.map(|t| maven::parse_effective_pom_in(&t, repo.as_deref()))
.unwrap_or_default();
let trees = maven::parse_dependency_tree(&out.text);
for (key, plugins, deps) in effective_projects {
@@ -953,11 +950,32 @@ mod tests {
#[test]
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline_without_it() {
let tmp = tempfile::tempdir().unwrap();
let online = maven_sync_goals(Path::new("e.xml"), false, None);
assert_eq!(online, ["help:effective-pom", "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom";
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()));
assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
// Offline with neither plugin cached: `effective-pom` is skipped so `mvn -o` does not fail
// on an uncached `maven-help-plugin`, and the tree falls back to the project's own version.
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline[2], "dependency:tree");
assert!(offline.contains(&"-Dverbose".to_owned()));
assert_eq!(offline, ["dependency:tree", "-Dverbose"]);
// #5757 / #5844: offline, plugins in the local repository are named by their coordinates,
// since the prefix needs group metadata a repository filled from a private mirror may lack;
// a repository with `maven-dependency-plugin` but no 3.x `maven-help-plugin` runs only the tree.
for (artifact, version) in [("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")] {
let jar =
tmp.path().join(format!("org/apache/maven/plugins/{artifact}/{version}/{artifact}-{version}.jar"));
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
std::fs::write(&jar, "").unwrap();
}
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline, ["org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree", "-Dverbose"]);
let help_jar = tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.4.0/maven-help-plugin-3.4.0.jar");
std::fs::create_dir_all(help_jar.parent().unwrap()).unwrap();
std::fs::write(&help_jar, "").unwrap();
// A version folder without its jar (only the POM was fetched) doesn't count.
std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap();
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline[0], "org.apache.maven.plugins:maven-help-plugin:3.4.0:effective-pom");
assert_eq!(offline[2], "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree");
// Downloaded by an online sync: offline keeps using it, the project's version may be missing.
let jar = tmp.path().join(DEPENDENCY_TREE_JAR);
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
@@ -1029,7 +1047,7 @@ mod tests {
let cache = tmp.path().join("cache");
sync_maven(&root, &cache, &SyncOptions::default(), &CancellationToken::new(), &|_| {}).unwrap();
let args = std::fs::read_to_string(root.join("mvnw-args")).unwrap();
assert!(args.contains("help:effective-pom"), "args: {args}");
assert!(args.contains("maven-help-plugin:"), "args: {args}");
let loaded = crate::load_linked(&root, &cache, None, &Default::default(), &Default::default());
let maven = loaded.maven.unwrap();
assert!(maven.synced_at.is_some() && maven.sync_error.is_none(), "{:?}", maven.sync_error);
@@ -1054,6 +1072,6 @@ mod tests {
let args = std::fs::read_to_string(root.join("mvnd-args")).unwrap();
// `-T1` pins the daemon serial so the dependency trees stay parseable.
assert!(args.contains("-T1"), "args: {args}");
assert!(args.contains("help:effective-pom"), "args: {args}");
assert!(args.contains("maven-help-plugin:"), "args: {args}");
}
}
+4 -7
View File
@@ -137,19 +137,16 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
// POM's effective identity first; profiles and -D options can change its GAV.
let output = cache.join("artifact-project.txt");
let mut probe = top.options.clone();
let evaluate =
crate::maven::plugin_goal("help:evaluate", crate::maven::local_repository_for(&top.options).as_deref());
probe.extend([
"-f".into(),
root.join(&p.pom).to_string_lossy().into_owned(),
"help:evaluate".into(),
evaluate.clone(),
"-Dexpression=project.id".into(),
format!("-Doutput={}", output.display()),
]);
args.extend([
"-DskipTests".into(),
"package".into(),
"help:evaluate".into(),
format!("-Doutput={}", manifest.display()),
]);
args.extend(["-DskipTests".into(), "package".into(), evaluate, format!("-Doutput={}", manifest.display())]);
return Ok(WebBuild {
command: top.command.clone(),
args,
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "ide-clipboard"
description = "The OS clipboard's file list (Explorer <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB or macOS NSPasteboard, no window or message loop"
description = "The OS clipboard's file list (file manager <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB, macOS NSPasteboard, Linux text/uri-list via GTK"
version.workspace = true
edition.workspace = true
license.workspace = true
+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());
}
}
+259 -5
View File
@@ -16,8 +16,12 @@
//! thread: AppKit and WebKit also access the general pasteboard there, and its
//! mutable type cache cannot be protected by a mutex in this crate.
//!
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
//! empty and [`set_files`] fails there.
//! Linux keeps it as `text/uri-list` (Dolphin, Nautilus and most file
//! managers) or GNOME's `x-special/gnome-copied-files` (`copy` or `cut`, then
//! one URI per line), read and written through the GTK clipboard on X11 and
//! Wayland alike; [`request_files`] reads it without blocking the main loop.
//! Other platforms are not wired up: [`files`] is empty and [`set_files`]
//! fails there.
//!
//! [`png`] reads an image (a screenshot) for the project view's Paste, which
//! saves it as a file: `public.png` or `public.tiff` on macOS, the registered
@@ -25,6 +29,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<()> {
@@ -56,6 +83,7 @@ const HEADER: usize = 20;
/// The absolute paths on the clipboard, empty when it holds no file list.
/// Read failures remain errors so callers can retain an internal copy.
/// Empty on Linux, where [`request_files`] reads it.
pub fn files() -> std::io::Result<Vec<PathBuf>> {
imp::files()
}
@@ -78,7 +106,7 @@ pub fn set_files(paths: &[PathBuf]) -> bool {
/// line. An editor paste inserts names, not the absolute paths the file list
/// keeps for Explorer (#1878; IDEA's text flavor is names too). A path with no
/// file name (a root like `C:\`) keeps its whole path.
#[cfg(any(windows, target_os = "macos", test))]
#[cfg(any(windows, target_os = "macos", target_os = "linux", test))]
fn names_text(paths: &[PathBuf], separator: &str) -> String {
paths
.iter()
@@ -89,6 +117,82 @@ fn names_text(paths: &[PathBuf], separator: &str) -> String {
.join(separator)
}
/// The `file://` URIs in a `text/uri-list` or `x-special/gnome-copied-files`
/// payload as local paths: comments, the `copy`/`cut` line and URIs for other
/// hosts or schemes are skipped.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn uri_list_paths(text: &str) -> Vec<PathBuf> {
text.lines().map(str::trim).filter(|line| !line.starts_with('#')).filter_map(uri_to_path).collect()
}
/// A local `file://` URI (`file:///a%20b` or `file://localhost/a%20b`) as a
/// path; its percent-escapes are raw bytes, as GLib writes them.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn uri_to_path(uri: &str) -> Option<PathBuf> {
use std::os::unix::ffi::OsStringExt;
let rest = uri.strip_prefix("file://")?;
let path = if rest.starts_with('/') { rest } else { rest.strip_prefix("localhost")? };
let path = path.split(['?', '#']).next()?;
if !path.starts_with('/') {
return None;
}
let hex = |b: u8| (b as char).to_digit(16).map(|d| d as u8);
let bytes = path.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
let escaped =
(bytes[i] == b'%').then(|| Some((hex(*bytes.get(i + 1)?)? << 4) | hex(*bytes.get(i + 2)?)?)).flatten();
match escaped {
Some(b) => {
out.push(b);
i += 3;
}
None => {
out.push(bytes[i]);
i += 1;
}
}
}
Some(PathBuf::from(std::ffi::OsString::from_vec(out)))
}
/// `path` as a `file://` URI, every byte outside the unreserved set and `/`
/// percent-escaped.
#[cfg(any(target_os = "linux", all(test, unix)))]
fn file_uri(path: &std::path::Path) -> String {
use std::fmt::Write;
use std::os::unix::ffi::OsStrExt;
let mut uri = String::from("file://");
for &b in path.as_os_str().as_bytes() {
if b.is_ascii_alphanumeric() || b"/-._~".contains(&b) {
uri.push(b as char);
} else {
let _ = write!(uri, "%{b:02X}");
}
}
uri
}
/// Reads the clipboard's file list without blocking: `text/uri-list` first,
/// then GNOME's list, and calls `done` with the paths (empty without a list).
/// Call on the main thread; `done` runs there later.
#[cfg(target_os = "linux")]
pub fn request_files(done: impl FnOnce(Vec<PathBuf>) + 'static) {
use gtk::gdk::{Atom, SELECTION_CLIPBOARD};
fn paths_in(data: &gtk::SelectionData) -> Vec<PathBuf> {
// A failed request has a negative length and no data.
if data.length() <= 0 { Vec::new() } else { uri_list_paths(&String::from_utf8_lossy(&data.data())) }
}
gtk::Clipboard::get(&SELECTION_CLIPBOARD).request_contents(&Atom::intern(imp::URI_LIST), move |board, data| {
let paths = paths_in(data);
if !paths.is_empty() {
return done(paths);
}
board.request_contents(&Atom::intern(imp::GNOME_COPIED), move |_, data| done(paths_in(data)));
});
}
/// `DROPFILES` for `paths`, in the wide form so names outside the ANSI code
/// page survive. Empty paths are skipped.
pub fn encode(paths: &[PathBuf]) -> Vec<u8> {
@@ -240,6 +344,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 +527,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 +636,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 +734,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 +781,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")]
{
@@ -630,8 +809,25 @@ mod imp {
}
}
#[cfg(target_os = "linux")]
pub const URI_LIST: &str = "text/uri-list";
#[cfg(target_os = "linux")]
pub const GNOME_COPIED: &str = "x-special/gnome-copied-files";
pub fn has_files() -> bool {
false
#[cfg(target_os = "linux")]
{
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).wait_for_targets().is_some_and(|targets| {
targets.into_iter().any(|target| {
let name = target.name();
name == URI_LIST || name == GNOME_COPIED
})
})
}
#[cfg(not(target_os = "linux"))]
{
false
}
}
pub fn has_image() -> bool {
@@ -649,6 +845,33 @@ mod imp {
Ok(Vec::new())
}
/// Offers `paths` as `text/uri-list` (KDE and most file managers), GNOME's
/// list (Nautilus, Thunar) and their names as text, rendered on request.
#[cfg(target_os = "linux")]
pub fn set_files(paths: &[PathBuf]) -> bool {
use gtk::{TargetEntry, TargetFlags};
let uris: Vec<String> = paths.iter().map(|p| super::file_uri(p)).collect();
let uri_list: String = uris.iter().map(|uri| format!("{uri}\r\n")).collect();
let gnome = format!("copy\n{}", uris.join("\n"));
let names = super::names_text(paths, "\n");
let entry = |name: &str, info: u32| TargetEntry::new(name, TargetFlags::empty(), info);
let targets = [
entry(URI_LIST, 0),
entry(GNOME_COPIED, 1),
entry("UTF8_STRING", 2),
entry("text/plain;charset=utf-8", 2),
entry("text/plain", 2),
];
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).set_with_data(&targets, move |_, data, info| match info {
0 => data.set(&data.target(), 8, uri_list.as_bytes()),
1 => data.set(&data.target(), 8, gnome.as_bytes()),
_ => {
let _ = data.set_text(&names);
}
})
}
#[cfg(not(target_os = "linux"))]
pub fn set_files(_paths: &[PathBuf]) -> bool {
false
}
@@ -658,10 +881,41 @@ 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()
}
#[cfg(unix)]
#[test]
fn file_manager_uri_lists_become_paths() {
// Dolphin: CRLF-separated `text/uri-list`, with a comment line.
let kde = "# copied\r\nfile:///home/u/a%20b.txt\r\nfile://localhost/home/u/%E6%A1%8C%E9%9D%A2\r\n";
assert_eq!(uri_list_paths(kde), paths(&["/home/u/a b.txt", "/home/u/桌面"]));
// Nautilus/Thunar: `copy` or `cut`, then one URI per line.
assert_eq!(uri_list_paths("cut\nfile:///tmp/x\nfile:///tmp/y"), paths(&["/tmp/x", "/tmp/y"]));
// Other hosts and schemes are not local files.
assert!(uri_list_paths("file://server/share/x\nhttps://example.com/x\nsmb:///x").is_empty());
}
#[cfg(unix)]
#[test]
fn written_uris_read_back_as_the_same_paths() {
let list = paths(&["/home/u/a b#1%.txt", "/home/u/桌面/项目", "/tmp/plain-name_1.~"]);
let uris: Vec<String> = list.iter().map(|p| file_uri(p)).collect();
assert_eq!(uris[0], "file:///home/u/a%20b%231%25.txt");
assert_eq!(uris[2], "file:///tmp/plain-name_1.~");
assert_eq!(uri_list_paths(&uris.join("\r\n")), list);
}
#[test]
fn a_written_list_reads_back_unchanged() {
let list = paths(&["C:/work/project/a.txt", "C:/work/project/sub"]);
+6 -1
View File
@@ -6,6 +6,7 @@ edition.workspace = true
license.workspace = true
[dependencies]
base64.workspace = true
dunce.workspace = true
encoding_rs.workspace = true
serde.workspace = true
@@ -14,12 +15,16 @@ specta.workspace = true
specta-typescript.workspace = true
thiserror.workspace = true
tokio-util.workspace = true
portable-pty.workspace = true
[dev-dependencies]
sha2 = "0.10"
tempfile.workspace = true
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
dirs.workspace = true
tracing.workspace = true
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
+21
View File
@@ -0,0 +1,21 @@
Copyright (c) Microsoft Corporation. All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,39 @@
# Bundled Windows console host
Unmodified files from Microsoft's MIT-licensed
[Microsoft.Windows.Console.ConPTY 1.25.260930003](https://www.nuget.org/packages/Microsoft.Windows.Console.ConPTY/1.25.260930003).
The system ConPTY on Windows 10 build 19045 consumes alternate-screen transitions; xterm then
puts full-screen applications' redraws in normal scrollback. A current console host
preserves those transitions, including while resizing and updating a running TUI.
The package is pinned, checked in and embedded by `ide-core`, so desktop, server,
Run and debugger builds work offline and do not depend on another installed IDE.
Only the target architecture is embedded, along with its MIT license. `src/pty.rs`
extracts them atomically to a versioned user cache and preloads the DLL's absolute
path before portable-pty initializes.
Windows reuses that module when portable-pty loads `conpty.dll` by name. Loading
failure is logged and falls back to the system backend. Windows builds before
19041 also retain the system backend.
Source archive:
`https://api.nuget.org/v3-flatcontainer/microsoft.windows.console.conpty/1.25.260930003/microsoft.windows.console.conpty.1.25.260930003.nupkg`
Archive SHA-256: `02b07b349af66d801159bdf9e440d4a1ce78bb951f37fc8609731665afdae7ee`
For each architecture, `conpty.dll` comes from
`runtimes/win-<arch>/native/conpty.dll`, and `OpenConsole.exe` from
`build/native/runtimes/<arch>/OpenConsole.exe` in that archive. Preserve the pair and
the license when updating; update `VERSION` in `src/pty.rs` and these checksums too.
| File | SHA-256 |
| --------------------- | ------------------------------------------------------------------ |
| arm64/conpty.dll | `151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf` |
| arm64/OpenConsole.exe | `4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f` |
| x64/conpty.dll | `feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a` |
| x64/OpenConsole.exe | `3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586` |
| x86/conpty.dll | `d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93` |
| x86/OpenConsole.exe | `e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3` |
Verification: `cargo test -p ide-core pty::`. `pty::checksums` checks the embedded files against the table above on every platform. The native PTY test launches a child
console application and requires alternate-screen entry and exit to reach the
reader; a system ConPTY that consumes them fails this check.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+319
View File
@@ -0,0 +1,319 @@
//! Runs a tool's CLI (`docker`, `gh`, `adb`) as a child process: bounded runs that collect
//! its output, and cancellable streams that hand over its output line by line.
//!
//! Every child leads its own process group ([`own_group`]), so cancelling or timing out
//! reaches what it started in turn (`gh` → `git`, `docker` → CLI plugins such as compose).
//! They get [`KILL_GRACE`] to exit on `SIGTERM` and clean up (git removes its lock files)
//! before `SIGKILL`.
use crate::process::{own_group, prepare, terminate_tree};
use crate::{CancellationToken, IdeError, IdeResult};
use std::borrow::Cow;
use std::io::{Read, Write};
use std::process::{Child, Command, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};
/// How long a cancelled or timed-out child's process group gets to exit on `SIGTERM`
/// before `SIGKILL`.
const KILL_GRACE: Duration = Duration::from_millis(20);
/// How many of a streamed child's last non-blank stderr lines are kept for its error message.
const STDERR_TAIL: usize = 20;
/// How a tool's output bytes become text.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Decoding {
/// [`decode_tool_output`](crate::output_encoding::decode_tool_output): UTF-8, and on
/// Windows the system code page for what is not.
ToolOutput,
/// UTF-8, invalid bytes replaced by U+FFFD.
Utf8Lossy,
}
impl Decoding {
fn decode(self, bytes: &[u8]) -> Cow<'_, str> {
match self {
Decoding::ToolOutput => Cow::Owned(crate::output_encoding::decode_tool_output(bytes)),
Decoding::Utf8Lossy => String::from_utf8_lossy(bytes),
}
}
}
/// What a child's stdin is fed with, and how.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Input<'a> {
/// Written before the output is read, then closed: only for input small enough
/// (a password) to fit the pipe, as a full pipe blocks the caller.
Inline(&'a str),
/// Written by a thread of its own, then closed: a large body must not block on a full
/// pipe while the child is not reading yet.
Threaded(&'a str),
}
/// How a streamed child's `\r` is read.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CarriageReturn {
/// Ends a line like `\n`: progress output rewrites its line in place.
EndsLine,
/// Is dropped; only `\n` ends a line.
Dropped,
}
/// What a bounded run collected.
pub struct Output {
pub stdout: String,
pub stderr: String,
pub success: bool,
}
/// Which pipe a streamed line came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Stream {
Stdout,
Stderr,
}
/// One tool's CLI: its name for error messages and how its output is decoded.
#[derive(Clone, Copy, Debug)]
pub struct CliTool {
name: &'static str,
decoding: Decoding,
}
impl CliTool {
pub const fn new(name: &'static str, decoding: Decoding) -> Self {
Self { name, decoding }
}
fn spawn(self, cmd: &mut Command) -> IdeResult<Child> {
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run {}: {e}", self.name)))
}
/// Pipes stdout and stderr, closes stdin and starts the child in its own process group.
fn configure(cmd: &mut Command) {
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
prepare(own_group(cmd));
}
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
/// a non-zero exit is reported in [`Output::success`], not as an error.
pub fn run(self, cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
self.run_with_input(cmd, None, timeout, cancel)
}
/// [`run`](Self::run) with `input` written to the child's stdin and then closed.
pub fn run_with_input(
self,
mut cmd: Command,
input: Option<Input>,
timeout: Duration,
cancel: Option<&CancellationToken>,
) -> IdeResult<Output> {
Self::configure(&mut cmd);
if input.is_some() {
cmd.stdin(Stdio::piped());
}
let mut child = self.spawn(&mut cmd)?;
match (input, child.stdin.take()) {
(Some(Input::Inline(text)), Some(mut stdin)) => {
// Dropping `stdin` afterwards closes it, so the CLI sees EOF.
let _ = stdin.write_all(text.as_bytes());
}
(Some(Input::Threaded(text)), Some(mut stdin)) => {
let text = text.to_owned();
std::thread::spawn(move || {
let _ = stdin.write_all(text.as_bytes());
});
}
_ => {}
}
let decoding = self.decoding;
let out = child.stdout.take().map(|pipe| read_all(pipe, decoding));
let err = child.stderr.take().map(|pipe| read_all(pipe, decoding));
let deadline = Instant::now() + timeout;
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_some_and(CancellationToken::is_cancelled) {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
if Instant::now() >= deadline {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::unavailable(format!("{} did not respond in time", self.name)));
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(Output {
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
success: status.success(),
})
}
/// Runs `cmd`, handing every output line to `on_line` until it exits or `cancel`
/// fires. Returns whether it exited successfully plus the last stderr lines.
pub fn stream(
self,
cmd: Command,
cancel: &CancellationToken,
on_line: &mut dyn FnMut(Stream, String),
) -> IdeResult<(bool, Vec<String>)> {
let mut lines = self.lines(cmd, cancel, CarriageReturn::EndsLine)?;
let mut stderr_tail: Vec<String> = Vec::new();
loop {
match lines.poll(cancel, Duration::from_millis(50))? {
Poll::Line(stream, line) => {
if stream == Stream::Stderr && !line.trim().is_empty() {
keep_stderr_line(&mut stderr_tail, line.clone());
}
on_line(stream, line);
}
Poll::Closed | Poll::Timeout => {}
Poll::Finished => break,
}
}
Ok((lines.finish(cancel)?, stderr_tail))
}
/// Starts `cmd` with a reader thread per pipe, for a caller that drives the loop itself
/// (see [`Lines::poll`]). Fails when `cancel` has already fired, without starting it.
pub fn lines(self, mut cmd: Command, cancel: &CancellationToken, cr: CarriageReturn) -> IdeResult<Lines> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
Self::configure(&mut cmd);
let mut child = self.spawn(&mut cmd)?;
let (tx, rx) = mpsc::channel::<Event>();
let mut open = 0;
if let Some(out) = child.stdout.take() {
spawn_reader(out, tx.clone(), Stream::Stdout, self.decoding, cr);
open += 1;
}
if let Some(err) = child.stderr.take() {
spawn_reader(err, tx.clone(), Stream::Stderr, self.decoding, cr);
open += 1;
}
drop(tx);
Ok(Lines { child, rx, open })
}
}
/// Appends a stderr line to `tail`, which keeps only the last [`STDERR_TAIL`].
pub fn keep_stderr_line(tail: &mut Vec<String>, line: String) {
tail.push(line);
if tail.len() > STDERR_TAIL {
tail.remove(0);
}
}
fn read_all(mut pipe: impl Read + Send + 'static, decoding: Decoding) -> std::thread::JoinHandle<String> {
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = pipe.read_to_end(&mut buf);
decoding.decode(&buf).into_owned()
})
}
enum Event {
Line(Stream, String),
Closed,
}
fn spawn_reader(
mut pipe: impl Read + Send + 'static,
tx: mpsc::Sender<Event>,
stream: Stream,
decoding: Decoding,
cr: CarriageReturn,
) {
std::thread::spawn(move || {
let mut buf = [0u8; 8192];
let mut pending: Vec<u8> = Vec::new();
let flush = |pending: &mut Vec<u8>| {
if !pending.is_empty() {
let line = decoding.decode(pending).trim_end().to_string();
pending.clear();
let _ = tx.send(Event::Line(stream, line));
}
};
loop {
match pipe.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
for &b in &buf[..n] {
if b == b'\n' || (b == b'\r' && cr == CarriageReturn::EndsLine) {
flush(&mut pending);
} else if b != b'\r' {
pending.push(b);
}
}
}
}
}
flush(&mut pending);
let _ = tx.send(Event::Closed);
});
}
/// A running child whose output lines are read by threads: see [`CliTool::lines`].
pub struct Lines {
child: Child,
rx: mpsc::Receiver<Event>,
/// Pipes whose reader has not reported its end yet.
open: usize,
}
/// What [`Lines::poll`] saw.
pub enum Poll {
Line(Stream, String),
/// A pipe reached its end.
Closed,
/// Nothing arrived within the wait.
Timeout,
/// Every pipe is at its end.
Finished,
}
impl Lines {
/// Waits up to `wait` for the next line. Fails, after killing the child, when `cancel` has fired.
pub fn poll(&mut self, cancel: &CancellationToken, wait: Duration) -> IdeResult<Poll> {
if self.open == 0 {
return Ok(Poll::Finished);
}
if cancel.is_cancelled() {
terminate_tree(&mut self.child, KILL_GRACE);
return Err(IdeError::cancelled());
}
match self.rx.recv_timeout(wait) {
Ok(Event::Line(stream, line)) => Ok(Poll::Line(stream, line)),
Ok(Event::Closed) => {
self.open -= 1;
Ok(Poll::Closed)
}
Err(mpsc::RecvTimeoutError::Timeout) => Ok(Poll::Timeout),
Err(mpsc::RecvTimeoutError::Disconnected) => {
self.open = 0;
Ok(Poll::Finished)
}
}
}
/// Waits for the child to exit and returns whether it did so successfully. Fails, after
/// killing it, when `cancel` fires first.
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<bool> {
let status = loop {
if let Some(status) = self.child.try_wait()? {
break status;
}
if cancel.is_cancelled() {
terminate_tree(&mut self.child, KILL_GRACE);
return Err(IdeError::cancelled());
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(status.success())
}
}
+30
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,
}
}
}
@@ -336,6 +338,7 @@ pub struct CodeEditingSettings {
/// Next / previous error goes to errors only (skips warnings).
pub next_error_errors_only: bool,
pub sticky_lines_max: u32,
pub sticky_lines_disabled_languages: Vec<String>,
}
impl Default for CodeEditingSettings {
@@ -348,6 +351,7 @@ impl Default for CodeEditingSettings {
quick_doc_delay: 500,
next_error_errors_only: true,
sticky_lines_max: 5,
sticky_lines_disabled_languages: Vec::new(),
}
}
}
@@ -360,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,
@@ -392,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,
@@ -473,6 +480,12 @@ pub struct LanguageCodeStyle {
/// PHP: align `=` of consecutive assignment statements after formatting.
#[serde(skip_serializing_if = "Option::is_none")]
pub align_consecutive_assignments: Option<bool>,
/// SQL › Case › Keywords: `upper` | `lower` | `keep` (other languages ignore it).
#[serde(skip_serializing_if = "Option::is_none")]
pub keyword_case: Option<String>,
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
#[serde(skip_serializing_if = "Option::is_none")]
pub identifier_case: Option<String>,
}
/// Editor › Code Style (General tab + per-language overrides).
@@ -585,3 +598,20 @@ mod folding_tests {
}
}
}
#[cfg(test)]
mod sticky_lines_tests {
use super::CodeEditingSettings;
#[test]
fn sticky_lines_language_exclusions_round_trip_and_default_to_empty() {
let old: CodeEditingSettings = serde_json::from_value(serde_json::json!({"stickyLinesMax": 3})).unwrap();
assert_eq!(old.sticky_lines_max, 3);
assert!(old.sticky_lines_disabled_languages.is_empty());
let json = serde_json::json!(["markdown", "rust"]);
let saved: CodeEditingSettings =
serde_json::from_value(serde_json::json!({"stickyLinesDisabledLanguages": json})).unwrap();
assert_eq!(saved.sticky_lines_disabled_languages, ["markdown", "rust"]);
assert_eq!(serde_json::to_value(saved).unwrap()["stickyLinesDisabledLanguages"], json);
}
}
+5
View File
@@ -41,6 +41,11 @@ pub enum ErrorData {
AmendConflict {
commit: String,
},
/// jdtls could not set a module up as a Java project: the errors on its build files and
/// the builds enclosing it (`path: message`, the path relative to the project), nearest first.
JavaBuildProblems {
problems: Vec<String>,
},
}
/// Git's reported result for each destination ref. A remote with several push URLs can
+23 -2
View File
@@ -40,10 +40,11 @@ pub enum IdeEvent {
McpBackgroundProjectsChanged,
/// A window entered or left full screen, itself or as a member of a full-screen window group.
WindowFullscreenChanged,
/// This remote window's connection to its host ended on its own (network loss, the host or
/// its server went away); the window's project is unreachable until it reconnects.
/// This remote window's connection ended or another window took over the session.
RemoteConnectionLost {
host: String,
#[serde(default)]
taken_over: bool,
},
ProjectTrustChanged {
root: crate::IpcPath,
@@ -263,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`].
@@ -288,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`].
@@ -324,6 +343,8 @@ pub enum LspRefreshKind {
InlayHints,
SemanticTokens,
CodeLens,
/// An import or classpath update may have changed inheritance search results.
Inheritance,
/// The Dart server published a document's Flutter outline.
FlutterOutline,
}
@@ -71,6 +71,11 @@ pub struct SpellingSettings {
pub project_words: Vec<String>,
/// Custom dictionaries: plain word lists or Hunspell `.dic` files.
pub custom_dictionaries: Vec<String>,
/// Where "Save '…' to dictionary" writes: `project`, `application`, or a
/// `spelling.customDictionaries` entry verbatim; empty (the default) is
/// project when one is open, application otherwise.
#[specta(optional)]
pub default_dictionary: Option<String>,
}
/// Changes to one inspection; absent fields keep the inspection's defaults.
+122
View File
@@ -0,0 +1,122 @@
//! Binary arguments of IPC commands travel as base64 text: [`IpcBytes`] is a `Vec<u8>` that
//! serializes as a standard padded base64 string and is a plain `string` in the generated
//! bindings.
//!
//! A plain `Vec<u8>` is a JSON array of numbers, 3.6 times the size of the bytes, and parsing it
//! into a `serde_json::Value` (the remote protocol and Tauri both do) takes about 50 times the
//! bytes in memory: 20 MB become about 1 GB. Base64 is 1.33 times the size and one string.
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::ops::Deref;
/// A binary argument or result of an IPC command.
#[derive(Clone, Default, PartialEq, Eq, specta::Type)]
#[specta(transparent)]
pub struct IpcBytes(#[specta(type = String)] pub Vec<u8>);
impl IpcBytes {
pub fn into_vec(self) -> Vec<u8> {
self.0
}
}
impl fmt::Debug for IpcBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "IpcBytes({} bytes)", self.0.len())
}
}
impl Serialize for IpcBytes {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&STANDARD.encode(&self.0))
}
}
impl<'de> Deserialize<'de> for IpcBytes {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct Base64;
impl Visitor<'_> for Base64 {
type Value = IpcBytes;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a base64 string")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<IpcBytes, E> {
STANDARD.decode(v).map(IpcBytes).map_err(|e| E::custom(format!("invalid base64: {e}")))
}
}
d.deserialize_str(Base64)
}
}
impl Deref for IpcBytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.0
}
}
impl From<Vec<u8>> for IpcBytes {
fn from(bytes: Vec<u8>) -> Self {
Self(bytes)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{Value, json};
fn round_trip(bytes: Vec<u8>) {
let value = serde_json::to_value(IpcBytes(bytes.clone())).unwrap();
let text = value.as_str().expect("serializes as a string");
assert_eq!(text.len(), bytes.len().div_ceil(3) * 4);
assert_eq!(serde_json::from_value::<IpcBytes>(value).unwrap().into_vec(), bytes);
}
#[test]
fn round_trips_empty_every_byte_and_large_input() {
round_trip(Vec::new());
round_trip((0..=255).collect());
round_trip((0..=255).rev().cycle().take(5 * 1024 * 1024 + 1).collect());
}
#[test]
fn round_trips_through_a_json_document() {
let bytes: Vec<u8> = (0..=255).collect();
let text = serde_json::to_string(&json!({ "data": IpcBytes(bytes.clone()) })).unwrap();
#[derive(Deserialize)]
struct Args {
data: IpcBytes,
}
assert_eq!(serde_json::from_str::<Args>(&text).unwrap().data.into_vec(), bytes);
}
/// The old wire form of a `Vec<u8>`: 3.6 times the bytes. The string must stay near 4/3.
#[test]
fn serialized_form_is_a_string_about_a_third_larger_than_the_bytes() {
let bytes: Vec<u8> = (0..=255).cycle().take(1_000_000).collect();
let json = serde_json::to_string(&IpcBytes(bytes.clone())).unwrap();
assert!(json.starts_with('"') && json.ends_with('"'));
assert!(json.len() <= bytes.len().div_ceil(3) * 4 + 2, "{} bytes for {}", json.len(), bytes.len());
let as_array = serde_json::to_string(&bytes).unwrap();
assert!(json.len() * 2 < as_array.len(), "{} vs {}", json.len(), as_array.len());
}
#[test]
fn rejects_what_is_not_base64() {
for bad in [json!([1, 2, 3]), json!(7), Value::Null, json!("not base64!"), json!("QQ"), json!("QQ=a")] {
assert!(serde_json::from_value::<IpcBytes>(bad.clone()).is_err(), "{bad}");
}
}
#[test]
fn debug_does_not_print_the_bytes() {
assert_eq!(format!("{:?}", IpcBytes(vec![0; 3])), "IpcBytes(3 bytes)");
}
}
+54 -1
View File
@@ -40,6 +40,10 @@ pub fn strip(src: &str) -> String {
if prev == '*' && n == '/' {
break;
}
// Keep the comment's line breaks so parse errors report the original line.
if n == '\n' {
out.push('\n');
}
prev = n;
}
}
@@ -65,7 +69,7 @@ pub fn strip(src: &str) -> String {
in_str = true;
cleaned.push(c);
} else if c == ',' {
let next = bytes[i + 1..].iter().find(|ch| !ch.is_whitespace());
let next = bytes[i + 1..].iter().find(|ch| !ch.is_ascii_whitespace());
if !matches!(next, Some('}') | Some(']')) {
cleaned.push(c);
}
@@ -95,4 +99,53 @@ mod tests {
let v: serde_json::Value = serde_json::from_str(&strip("\u{feff}{ \"a\": 1 }")).unwrap();
assert_eq!(v["a"], 1);
}
#[test]
fn keeps_line_breaks_of_block_comments_so_errors_report_the_original_line() {
assert_eq!(strip("{\"a\"/*\n\n*/:x}"), "{\"a\"\n\n:x}");
let err = serde_json::from_str::<serde_json::Value>(&strip("{\"a\"/*\n\n*/:x}")).unwrap_err();
assert_eq!(err.line(), 3);
// A comment is whitespace, not a join: `1 2` stays invalid.
assert!(serde_json::from_str::<serde_json::Value>(&strip("1/*\n*/2")).is_err());
}
#[test]
fn line_comments_keep_their_line_break_and_may_end_the_input() {
assert_eq!(strip("{\"a\":1} // tail"), "{\"a\":1} ");
assert_eq!(strip("// a\r\n{\"a\":1}"), "\n{\"a\":1}");
assert_eq!(strip("[1, // c\n2]"), "[1, \n2]");
}
#[test]
fn unterminated_block_comment_drops_the_rest() {
assert_eq!(strip("{\"a\":1}/* open"), "{\"a\":1}");
assert_eq!(strip("/*"), "");
assert_eq!(strip("/*/ x"), "");
assert_eq!(strip("/**/{}"), "{}");
assert_eq!(strip("/***/{}"), "{}");
}
#[test]
fn comment_markers_inside_strings_survive_including_after_escapes() {
let src = "{\"a\":\"\\\\\",\"b\":\"//x\",\"c\":\"/*y*/\",\"d\":\"é,\u{1F600}\"} // é";
let v: serde_json::Value = serde_json::from_str(&strip(src)).unwrap();
assert_eq!(v, serde_json::json!({"a": "\\", "b": "//x", "c": "/*y*/", "d": "é,\u{1F600}"}));
}
#[test]
fn trailing_commas_are_dropped_across_whitespace_and_comments_only_before_a_closer() {
assert_eq!(strip("[1,2, ]"), "[1,2 ]");
assert_eq!(strip("[1,\r\n]"), "[1\r\n]");
assert_eq!(strip("[1,/*c*/]"), "[1]");
assert_eq!(strip("[1,//c\n]"), "[1\n]");
assert_eq!(strip("[1,/*c*/ ,]"), "[1, ]");
assert_eq!(strip("{\"a\":\"x,}\"}"), "{\"a\":\"x,}\"}");
assert_eq!(strip("[1,2]"), "[1,2]");
}
#[test]
fn only_json_whitespace_may_separate_a_trailing_comma_from_its_closer() {
// U+00A0 is not JSON whitespace: the comma stays and serde_json reports it.
assert_eq!(strip("[1,\u{a0}]"), "[1,\u{a0}]");
}
}
+5
View File
@@ -4,6 +4,7 @@
//! feature crates depend on `ide-core` and never on each other's internals.
//! All IPC-facing types derive `specta::Type`, which generates `src/bindings.ts`.
pub mod cli_process;
pub mod editor_settings;
pub mod error;
pub mod event;
@@ -12,6 +13,7 @@ pub mod ids;
pub mod ignored;
pub mod input;
pub mod inspection_settings;
pub mod ipc_bytes;
pub mod ipc_path;
pub mod java_runtime;
pub mod jsonc;
@@ -23,6 +25,7 @@ pub mod project_dir;
pub mod project_env;
pub mod project_roots;
pub mod proxy_settings;
pub mod pty;
pub mod real_path;
pub mod remote_settings;
pub mod settings;
@@ -30,6 +33,7 @@ pub mod task;
pub mod text;
pub mod tool_path;
pub mod updates;
pub mod utf8;
pub mod version_managers;
pub mod workflow_settings;
pub mod wsl;
@@ -37,6 +41,7 @@ pub mod wsl;
pub use error::{IdeError, IdeResult};
pub use event::{EventSink, IdeEvent, NullSink, SharedSink};
pub use ids::*;
pub use ipc_bytes::IpcBytes;
pub use ipc_path::IpcPath;
pub use text::*;
pub use tokio_util::sync::CancellationToken;
+58 -2
View File
@@ -402,12 +402,14 @@ mod windows_job {
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle};
use windows_sys::Win32::Foundation::{ERROR_MORE_DATA, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
AssignProcessToJobObject, CreateJobObjectW, IsProcessInJob, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
JOBOBJECT_BASIC_LIMIT_INFORMATION, JOBOBJECT_BASIC_PROCESS_ID_LIST, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
JobObjectBasicProcessIdList, JobObjectExtendedLimitInformation, QueryInformationJobObject,
SetInformationJobObject, TerminateJobObject,
};
use windows_sys::Win32::System::Threading::{IO_COUNTERS, OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE};
use windows_sys::Win32::System::Threading::{
IO_COUNTERS, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SET_QUOTA, PROCESS_TERMINATE,
};
/// A job object holding one launch's processes. The handle is kept open for the
/// launch's lifetime: `KILL_ON_JOB_CLOSE` ends anything still in the job when the
@@ -510,6 +512,21 @@ mod windows_job {
ok != 0
}
/// Whether the running process belongs to this specific launch's job.
pub fn contains_pid(&self, pid: u32) -> bool {
// SAFETY: a non-null result is a process handle owned by this call.
let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
if handle.is_null() {
return false;
}
// SAFETY: the process handle was just opened above and the job handle is owned here.
let handle = unsafe { OwnedHandle::from_raw_handle(handle) };
let mut contained = 0;
// SAFETY: both handles remain valid and `contained` is a writable BOOL.
(unsafe { IsProcessInJob(handle.as_raw_handle(), self.0.as_raw_handle(), &mut contained) }) != 0
&& contained != 0
}
/// Terminates every process in the job. `false` when the call failed (the job
/// handle is invalid): callers then fall back to `taskkill /T /F`. Termination is
/// asynchronous; poll [`Job::is_running`] (bounded by [`TREE_EXIT_WAIT`]) until
@@ -1334,6 +1351,45 @@ mod tests {
assert_eq!(cmd.get_envs().find(|(k, _)| *k == "PATH").and_then(|(_, v)| v), Some(OsStr::new("/custom")));
}
#[test]
fn unix_uses_the_name_as_is() {
assert_eq!(executable_names("kotlinc", false, Some(".BAT")), ["kotlinc"]);
}
#[test]
fn windows_appends_pathext_extensions() {
assert_eq!(
executable_names("kotlinc", true, None),
["kotlinc.com", "kotlinc.exe", "kotlinc.bat", "kotlinc.cmd"]
);
assert_eq!(executable_names("npx", true, Some(".EXE;.CMD;;")), ["npx.exe", "npx.cmd"]);
assert_eq!(executable_names("npx", true, Some(" ")), executable_names("npx", true, None));
// Already has an executable extension (any case): only that file.
assert_eq!(executable_names("rustc.EXE", true, None), ["rustc.EXE"]);
assert_eq!(executable_names("gradlew.bat", true, None), ["gradlew.bat"]);
// A dot that is not an executable extension (`clang++`, `python3.12`).
assert_eq!(executable_names("python3.12", true, Some(".EXE")), ["python3.12.exe"]);
}
#[test]
fn finds_batch_files_and_skips_extensionless_scripts_on_windows() {
let dir = tempfile::tempdir().unwrap();
let a = dir.path().join("a");
let b = dir.path().join("b");
std::fs::create_dir_all(&a).unwrap();
std::fs::create_dir_all(&b).unwrap();
// `node_modules/.bin` style: a POSIX script next to its `.cmd` shim.
std::fs::write(a.join("tsx"), "#!/bin/sh\n").unwrap();
std::fs::write(b.join("tsx.cmd"), "@echo off\n").unwrap();
std::fs::write(b.join("kotlinc.bat"), "@echo off\n").unwrap();
let search = std::env::join_paths([&a, &b]).unwrap();
assert_eq!(find_executable_in("tsx", &search, true, None), Some(b.join("tsx.cmd")));
assert_eq!(find_executable_in("kotlinc", &search, true, None), Some(b.join("kotlinc.bat")));
assert_eq!(find_executable_in("tsx", &search, false, None), Some(a.join("tsx")));
assert_eq!(find_executable_in("kotlinc", &search, false, None), None);
assert_eq!(find_executable_in("nope", &search, true, None), None);
}
#[test]
fn find_executable_finds_bare_names_on_the_given_path() {
let dir = tempfile::tempdir().unwrap();
+254
View File
@@ -0,0 +1,254 @@
//! The PTY backend shared by terminals, Run consoles and debugger launchers.
pub fn native_pty_system() -> Box<dyn portable_pty::PtySystem + Send> {
#[cfg(windows)]
windows::initialize();
portable_pty::native_pty_system()
}
#[cfg(windows)]
mod windows {
use std::fs;
use std::io::{self, Write};
use std::os::windows::ffi::OsStrExt;
use std::path::Path;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU64, Ordering};
use windows_sys::Win32::Foundation::FreeLibrary;
use windows_sys::Win32::System::LibraryLoader::{
GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
};
const VERSION: &str = "1.25.260930003";
#[cfg(target_arch = "x86_64")]
const RUNTIME: (&str, &[u8], &[u8]) = (
"x64",
include_bytes!("../resources/conpty/x64/conpty.dll"),
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
);
#[cfg(target_arch = "aarch64")]
const RUNTIME: (&str, &[u8], &[u8]) = (
"arm64",
include_bytes!("../resources/conpty/arm64/conpty.dll"),
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
);
#[cfg(target_arch = "x86")]
const RUNTIME: (&str, &[u8], &[u8]) = (
"x86",
include_bytes!("../resources/conpty/x86/conpty.dll"),
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
);
pub(super) fn initialize() -> bool {
static BUNDLED: OnceLock<bool> = OnceLock::new();
*BUNDLED.get_or_init(|| {
if !crate::platform::windows_build_number().is_some_and(|build| build >= 19041) {
return false;
}
match load() {
Ok(()) => true,
Err(error) => {
tracing::warn!(%error, "bundled ConPTY unavailable; using the system terminal backend");
false
}
}
})
}
fn load() -> io::Result<()> {
let cache = dirs::cache_dir().ok_or_else(|| io::Error::other("no user cache directory"))?;
let directory = cache.join("OpenIDEA").join("conpty").join(VERSION).join(RUNTIME.0);
fs::create_dir_all(&directory)?;
install(&directory.join("LICENSE.txt"), include_bytes!("../resources/conpty/LICENSE"))?;
install(&directory.join("OpenConsole.exe"), RUNTIME.2)?;
let library = directory.join("conpty.dll");
install(&library, RUNTIME.1)?;
let wide: Vec<u16> = library.as_os_str().encode_wide().chain(Some(0)).collect();
// portable-pty 0.9 opens conpty.dll by name. Preload our verified absolute path:
// Windows reuses this module, without adding the project directory to DLL search.
// SAFETY: the path is terminated and the module is retained for the process lifetime.
let module = unsafe {
LoadLibraryExW(
wide.as_ptr(),
std::ptr::null_mut(),
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32,
)
};
if module.is_null() {
return Err(io::Error::last_os_error());
}
for name in [c"CreatePseudoConsole", c"ResizePseudoConsole", c"ClosePseudoConsole"] {
// SAFETY: `module` is loaded and each name is a terminated export name.
if unsafe { GetProcAddress(module, name.as_ptr().cast()) }.is_none() {
// SAFETY: no PTY uses this rejected module yet; release our load reference.
unsafe { FreeLibrary(module) };
return Err(io::Error::other("bundled ConPTY lacks the portable-pty exports"));
}
}
// Keep this reference for the process lifetime, including between PTY sessions.
tracing::info!(path = %library.display(), version = VERSION, "loaded bundled ConPTY");
Ok(())
}
fn install(path: &Path, data: &[u8]) -> io::Result<()> {
if fs::read(path).is_ok_and(|existing| existing == data) {
return Ok(());
}
static NEXT: AtomicU64 = AtomicU64::new(0);
let pending =
path.with_extension(format!("{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let result = (|| {
let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&pending)?;
file.write_all(data)?;
file.sync_all()?;
drop(file);
match fs::rename(&pending, path) {
Ok(()) => Ok(()),
Err(_) if fs::read(path).is_ok_and(|existing| existing == data) => Ok(()),
Err(error) => Err(error),
}
})();
let _ = fs::remove_file(pending);
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn installs_atomically_and_repairs_incomplete_files() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("conpty.dll");
fs::write(&path, b"partial").unwrap();
std::thread::scope(|scope| {
for _ in 0..8 {
let path = &path;
scope.spawn(move || install(path, b"complete runtime").unwrap());
}
});
assert_eq!(fs::read(&path).unwrap(), b"complete runtime");
assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
}
#[test]
fn loads_the_bundled_backend() {
assert!(initialize());
}
#[test]
fn conpty_output_child() {
if std::env::var_os("OPENIDEA_CONPTY_TEST_CHILD").is_none() {
return;
}
use windows_sys::Win32::System::Console::{
ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleMode, GetStdHandle, STD_OUTPUT_HANDLE, SetConsoleMode,
};
// SAFETY: the inherited console output handle and a local writable mode word.
unsafe {
let output = GetStdHandle(STD_OUTPUT_HANDLE);
let mut mode = 0;
assert_ne!(GetConsoleMode(output, &mut mode), 0);
assert_ne!(SetConsoleMode(output, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING), 0);
}
std::io::stdout()
.write_all(b"\x1b[?1049h\x1b[2J\x1b[HWorking (3m 19s)\x1b[1;1H\x1b[2KWorking (2m 59s)\x1b[?1049l\r\nVT_DONE\r\n")
.unwrap();
std::io::stdout().flush().unwrap();
}
#[test]
fn conpty_preserves_alternate_screen_transitions() {
use std::io::Read;
use std::sync::mpsc;
use std::time::{Duration, Instant};
let pair = super::super::native_pty_system().openpty(portable_pty::PtySize::default()).unwrap();
let mut reader = pair.master.try_clone_reader().unwrap();
let mut writer = pair.master.take_writer().unwrap();
let mut command = portable_pty::CommandBuilder::new(std::env::current_exe().unwrap());
command.args(["--exact", "pty::windows::tests::conpty_output_child", "--nocapture"]);
command.env("OPENIDEA_CONPTY_TEST_CHILD", "1");
let mut child = pair.slave.spawn_command(command).unwrap();
drop(pair.slave);
let (tx, rx) = mpsc::channel();
let reading = std::thread::spawn(move || {
let mut bytes = [0; 4096];
while let Ok(count) = reader.read(&mut bytes) {
if count == 0 || tx.send(bytes[..count].to_vec()).is_err() {
break;
}
}
});
let deadline = Instant::now() + Duration::from_secs(10);
let mut output = Vec::new();
let mut cursor_replied = false;
while Instant::now() < deadline {
if let Ok(bytes) = rx.recv_timeout(Duration::from_millis(50)) {
output.extend_from_slice(&bytes);
if !cursor_replied && output.windows(4).any(|s| s == b"\x1b[6n") {
writer.write_all(b"\x1b[1;1R").unwrap();
cursor_replied = true;
}
if output.windows(7).any(|s| s == b"VT_DONE") {
break;
}
}
}
let _ = child.kill();
let _ = child.wait();
drop(writer);
drop(pair.master);
reading.join().unwrap();
let output = String::from_utf8_lossy(&output);
assert!(output.contains("\x1b[?1049h"), "alternate screen entry missing: {output:?}");
assert!(output.contains("\x1b[?1049l"), "alternate screen exit missing: {output:?}");
}
}
}
/// The embedded runtime is the pinned NuGet package's files (`resources/conpty/README.md`).
#[cfg(test)]
mod checksums {
use sha2::{Digest, Sha256};
const FILES: [(&str, &[u8], &str); 6] = [
(
"arm64/conpty.dll",
include_bytes!("../resources/conpty/arm64/conpty.dll"),
"151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf",
),
(
"arm64/OpenConsole.exe",
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
"4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f",
),
(
"x64/conpty.dll",
include_bytes!("../resources/conpty/x64/conpty.dll"),
"feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a",
),
(
"x64/OpenConsole.exe",
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
"3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586",
),
(
"x86/conpty.dll",
include_bytes!("../resources/conpty/x86/conpty.dll"),
"d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93",
),
(
"x86/OpenConsole.exe",
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
"e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3",
),
];
#[test]
fn embedded_runtime_matches_the_pinned_package() {
for (name, bytes, expected) in FILES {
let actual: String = Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(actual, expected, "{name}");
}
}
}
+14
View File
@@ -4,6 +4,20 @@
use serde::{Deserialize, Serialize};
use specta::Type;
/// Tools › Remote Development. This is a user setting on the remote host.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct RemoteDevelopmentSettings {
/// Zero disables idle shutdown. Positive values from older configurations keep their meaning.
pub idle_timeout_minutes: u16,
}
impl Default for RemoteDevelopmentSettings {
fn default() -> Self {
Self { idle_timeout_minutes: 180 }
}
}
/// How an SSH connection authenticates.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+46 -2
View File
@@ -60,6 +60,7 @@ pub struct Settings {
pub spelling: SpellingSettings,
/// Tools › SSH Configurations.
pub ssh: SshSettings,
pub remote_development: RemoteDevelopmentSettings,
/// Build, Execution, Deployment › Deployment.
pub deployment: DeploymentSettings,
/// Build, Execution, Deployment › Run Targets.
@@ -144,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,
@@ -578,6 +579,7 @@ impl Default for Settings {
inspections: InspectionSettings::default(),
spelling: SpellingSettings::default(),
ssh: SshSettings::default(),
remote_development: RemoteDevelopmentSettings::default(),
deployment: DeploymentSettings::default(),
run_targets: Vec::new(),
cmake: CMakeSettings::default(),
@@ -939,6 +941,8 @@ pub struct FileIconThemeOptions {
#[serde(default, rename_all = "camelCase")]
pub struct MainToolbarSettings {
pub left: Vec<String>,
/// Centred in the toolbar (between the other two groups when they leave too little room).
pub center: Vec<String>,
pub right: Vec<String>,
/// Widgets the user removed.
pub hidden: Vec<String>,
@@ -1208,11 +1212,13 @@ pub struct LanguagesSettings {
pub oxfmt: ExternalFormatterSettings,
pub biome: ExternalFormatterSettings,
pub ruff: ExternalFormatterSettings,
pub black: ExternalFormatterSettings,
pub java: JavaSettings,
pub ruby: RubySettings,
pub markdown: MarkdownSettings,
pub arduino: ArduinoSettings,
pub zig: ZigSettings,
pub flutter: FlutterSettings,
}
impl Default for LanguagesSettings {
@@ -1235,11 +1241,16 @@ impl Default for LanguagesSettings {
languages: vec!["python".into()],
..ExternalFormatterSettings::default()
},
black: ExternalFormatterSettings {
languages: vec!["python".into()],
..ExternalFormatterSettings::default()
},
java: JavaSettings::default(),
ruby: RubySettings::default(),
markdown: MarkdownSettings::default(),
arduino: ArduinoSettings::default(),
zig: ZigSettings::default(),
flutter: FlutterSettings::default(),
}
}
}
@@ -1304,6 +1315,7 @@ impl LanguagesSettings {
ExternalFormatter::Oxfmt => &self.oxfmt,
ExternalFormatter::Biome => &self.biome,
ExternalFormatter::Ruff => &self.ruff,
ExternalFormatter::Black => &self.black,
}
}
}
@@ -1316,6 +1328,7 @@ pub enum ExternalFormatter {
Oxfmt,
Biome,
Ruff,
Black,
}
impl ExternalFormatter {
@@ -1326,6 +1339,7 @@ impl ExternalFormatter {
Self::Oxfmt => "oxfmt",
Self::Biome => "biome",
Self::Ruff => "ruff",
Self::Black => "black",
}
}
}
@@ -1334,7 +1348,7 @@ impl ExternalFormatter {
pub const BIOME_LANGUAGES: [&str; 8] =
["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"];
/// An external formatter (Prettier, oxfmt, Biome, Ruff) and the languages it formats.
/// An external formatter (Prettier, oxfmt, Biome, Ruff, Black) and the languages it formats.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ExternalFormatterSettings {
@@ -1396,6 +1410,9 @@ pub struct PythonSettings {
pub hide_other_project_interpreters: bool,
/// Show each interpreter's path under its name on the interpreters page.
pub show_interpreter_paths: bool,
/// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
/// by interpreter executable; absolute or `~/`.
pub interpreter_paths: BTreeMap<String, Vec<String>>,
}
impl Default for PythonSettings {
@@ -1407,6 +1424,7 @@ impl Default for PythonSettings {
hidden_interpreters: Vec::new(),
hide_other_project_interpreters: false,
show_interpreter_paths: true,
interpreter_paths: BTreeMap::new(),
}
}
}
@@ -1499,6 +1517,15 @@ pub struct ZigSettings {
pub zig: String,
}
/// The Flutter plugin's "Flutter SDK path".
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct FlutterSettings {
/// Flutter SDK root (holding `bin/flutter`); its `flutter` and Dart replace the ones on
/// `PATH`. Empty = `PATH`.
pub sdk: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GoSettings {
@@ -1641,6 +1668,20 @@ pub struct MavenSettings {
/// Always update snapshots (`-U`): Maven checks remote repositories for newer SNAPSHOT
/// dependencies on every sync, build and run, and jdtls on import (`java.maven.updateSnapshots`).
pub update_snapshots: bool,
/// Who runs the JUnit 5 tests of the gutter's Run / Debug.
pub run_tests_using: MavenRunTestsUsing,
}
/// Build Tools › Maven › Run tests using. IDEA runs a Maven project's tests itself unless its build
/// and run actions are delegated to Maven.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MavenRunTestsUsing {
/// OpenIDEA's JUnit Platform runner on the language server's test classpath (`java/junit-runner`).
#[default]
Ide,
/// Surefire (`mvn test -Dtest=…`).
Maven,
}
impl MavenSettings {
@@ -2083,8 +2124,10 @@ mod tests {
assert!(old.agents.show_cost);
assert!(old.agents.show_context_usage && old.agents.show_work_time && old.agents.show_usage_limits);
assert!(!old.agents.fit_window_width);
assert!(!old.agents.fold_turns);
assert!(!Settings::default().agents.show_cost);
assert!(!Settings::default().agents.fit_window_width);
assert!(!Settings::default().agents.fold_turns);
let mut settings = Settings::default();
settings.agents.show_usage_limits = false;
settings.agents.fit_window_width = true;
@@ -2302,6 +2345,7 @@ mod maven_linkage_tests {
let old: MavenSettings = serde_json::from_str(r#"{"home":"/opt/maven"}"#).unwrap();
assert!(old.runner_jre.is_empty());
assert!(!old.delegate_build);
assert_eq!(old.run_tests_using, MavenRunTestsUsing::Ide);
assert!(MavenSettings::default().runner_jre.is_empty());
let settings = MavenSettings { runner_jre: "/opt/jdk-21".into(), delegate_build: true, ..old };
let encoded = serde_json::to_string(&settings).unwrap();
@@ -48,6 +48,7 @@ impl Utf8Decoder {
}
}
#[cfg(test)]
/// Convenience wrapper around [`Self::decode_into`].
pub fn decode(&mut self, bytes: &[u8]) -> String {
let mut out = String::new();
@@ -65,6 +66,7 @@ impl Utf8Decoder {
}
}
#[cfg(test)]
pub fn has_pending(&self) -> bool {
!self.pending.is_empty()
}
+28
View File
@@ -460,6 +460,16 @@ impl Default for ConsoleSettings {
}
}
/// Whether compiled classes are reloaded into running Java debug sessions after compilation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum HotSwapPolicy {
#[default]
Ask,
Always,
Never,
}
/// Build, Execution, Deployment › Debugger (+ Data Views, Stepping, Python Debugger).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -487,6 +497,8 @@ pub struct DebuggerSettings {
pub debug_server_page: bool,
/// Flutter: saving a Dart file of a running debug session hot reloads the app.
pub flutter_hot_reload_on_save: bool,
/// Java: whether to reload changed classes into running debug sessions after compilation.
pub hot_swap_after_compile: HotSwapPolicy,
pub python: PythonDebuggerSettings,
}
@@ -508,6 +520,7 @@ impl Default for DebuggerSettings {
skip_library_code: true,
debug_server_page: false,
flutter_hot_reload_on_save: true,
hot_swap_after_compile: HotSwapPolicy::Ask,
python: PythonDebuggerSettings::default(),
}
}
@@ -718,4 +731,19 @@ mod tests {
let off: GitSettings = serde_json::from_str(r#"{"syncBranchOperations":false}"#).unwrap();
assert!(!off.sync_branch_operations);
}
#[test]
fn debugger_hotswap_after_compile_defaults_to_ask_and_roundtrips() {
let missing: DebuggerSettings = serde_json::from_str("{}").unwrap();
assert_eq!(missing.hot_swap_after_compile, HotSwapPolicy::Ask);
for (raw, expected) in
[("ask", HotSwapPolicy::Ask), ("always", HotSwapPolicy::Always), ("never", HotSwapPolicy::Never)]
{
let parsed: DebuggerSettings =
serde_json::from_str(&format!(r#"{{"hotSwapAfterCompile":"{raw}"}}"#)).unwrap();
assert_eq!(parsed.hot_swap_after_compile, expected);
let serialized = serde_json::to_value(&parsed).unwrap();
assert_eq!(serialized["hotSwapAfterCompile"], raw);
}
}
}
-1
View File
@@ -12,7 +12,6 @@ quick-xml = "0.42"
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
tracing.workspace = true
[dev-dependencies]
tempfile.workspace = true
+27 -1
View File
@@ -1,5 +1,6 @@
//! Class-table snapshots of a debugged JVM, read over the HotSpot attach listener or, where
//! that is unavailable, counted by the debugger; and the JVM's objects through the debugger.
//! that is unavailable, counted by the debugger; the JVM's objects through the debugger; and
//! its thread dumps.
mod fallback;
mod heap;
@@ -10,6 +11,7 @@ mod snapshot;
pub(crate) mod test_support;
#[cfg(test)]
mod tests;
mod threads;
use crate::session::Session;
use crate::session::Suspension;
@@ -28,6 +30,8 @@ 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, 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];
pub const HISTOGRAM_TIMEOUT: Duration = Duration::from_secs(10);
@@ -190,6 +194,25 @@ fn histogram_pid(session: &Session) -> Result<Option<i32>, JvmMemoryUnavailable>
Ok(None)
}
/// Whether `session` is a JVM session attached to `run` that may hold `pid`: its JVM is `pid` or
/// not located yet.
pub(crate) fn attached_to_run(session: &Session, run: ide_core::RunId, pid: u32) -> bool {
let located = session.jvm_pid.load(Ordering::Acquire);
session.run == Some(run)
&& JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str())
&& !session.terminated.load(Ordering::Acquire)
&& (located <= 0 || located == i64::from(pid))
}
/// Whether `session` debugs the JVM `pid`: the program it launched or the JVM its attach found.
pub(crate) fn debugs_jvm(session: &Session, pid: u32) -> bool {
let jvm = if session.request == "launch" { launch_pid(session) } else { session.jvm_pid.load(Ordering::Acquire) };
JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str())
&& !session.terminated.load(Ordering::Acquire)
&& jvm > 0
&& jvm == i64::from(pid)
}
/// The JVM a launch session started: the one the IDE started for an app-launched (Kotlin)
/// session, else the program the adapter reported; 0 when neither is known.
pub(crate) fn launch_pid(session: &Session) -> i64 {
@@ -206,6 +229,8 @@ pub(crate) enum JvmTarget<'a> {
/// The JVM of an attach session. While `pid` is 0 it is looked up by `jdwp_port`, which is
/// `None` for a remote JVM.
Attached { pid: &'a AtomicI64, jdwp_port: Option<u16> },
/// A JVM the session debugs, found from outside it (in a run's process tree).
Known(i32),
/// Known without asking any JVM: no histogram can be taken, for this reason.
Unavailable(JvmMemoryUnavailable),
}
@@ -261,6 +286,7 @@ async fn histogram(
fn lookup(target: JvmTarget<'_>) -> Result<Lookup, JvmMemoryUnavailable> {
match target {
JvmTarget::Launched(pid) => Ok(Lookup::Tree(pid)),
JvmTarget::Known(pid) => Ok(Lookup::Known(pid)),
JvmTarget::Attached { pid, jdwp_port } => match i32::try_from(pid.load(Ordering::Acquire)) {
Ok(p) if p > 0 => Ok(Lookup::Known(p)),
_ => jdwp_port.map(Lookup::Scan).ok_or(JvmMemoryUnavailable::AttachedJvmNotFound),
+24 -1
View File
@@ -15,7 +15,8 @@ use std::time::Duration;
const VERSION_TIMEOUT: Duration = Duration::from_secs(2);
const FLAGS_TIMEOUT: Duration = Duration::from_secs(2);
/// The attach calls a snapshot or a heap dump makes, so tests can stand in for a JVM.
/// The attach calls a snapshot, a heap dump or a thread dump makes, so tests can stand in for a
/// JVM.
pub(crate) trait AttachProbe: Send + Sync {
fn has_listener(&self, pid: u32) -> bool;
/// Asks only the JVMs whose pid `may_query` accepts.
@@ -27,6 +28,12 @@ pub(crate) trait AttachProbe: Send + Sync {
fn heap_dump(&self, pid: u32, path: &Path, timeout: Duration) -> Result<HeapDumpReply, AttachError>;
/// `None` where the free space is not known.
fn free_bytes(&self, dir: &Path) -> Option<u64>;
fn thread_print(&self, pid: u32) -> Result<String, AttachError>;
/// Opens `pid`'s attach listener unless it runs; refuses a process not confirmed HotSpot.
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 {
@@ -73,6 +80,22 @@ impl AttachProbe for JdkProbe {
fn free_bytes(&self, dir: &Path) -> Option<u64> {
ide_heap::free_bytes(dir)
}
fn thread_print(&self, pid: u32) -> Result<String, AttachError> {
ide_jvm_attach::thread_print(pid, ide_jvm_attach::THREAD_DUMP_TIMEOUT)
}
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError> {
ide_jvm_attach::ensure_listener(pid, ide_jvm_attach::LISTENER_START_TIMEOUT)
}
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 {
+521
View File
@@ -3,6 +3,7 @@ use super::heap::*;
use super::scan::*;
use super::snapshot::*;
use super::test_support::{BareSession, FakeInspector, bare_session, bare_session_of};
use super::threads::*;
use super::*;
use ide_core::CancellationToken;
use ide_jvm_attach::{AttachError, HeapDumpReply, HistogramRow, JavaVersion};
@@ -39,6 +40,15 @@ struct FakeProbe {
free: Option<u64>,
/// Answering this command stops the program: runs the hook.
stops_on: Option<(&'static str, StopHook)>,
thread_dumps: parking_lot::Mutex<VecDeque<Result<String, AttachError>>>,
/// Replies to `ensure_listener`, in order; `Ok` once empty.
listener_starts: parking_lot::Mutex<VecDeque<Result<(), AttachError>>>,
/// Pids `is_application_jvm` confirms.
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>;
@@ -97,6 +107,12 @@ impl FakeProbe {
dump_bytes: 64,
free: None,
stops_on: None,
thread_dumps: parking_lot::Mutex::new(VecDeque::new()),
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()),
}
}
@@ -167,6 +183,26 @@ impl AttachProbe for FakeProbe {
fn free_bytes(&self, _dir: &Path) -> Option<u64> {
self.free
}
fn thread_print(&self, _pid: u32) -> Result<String, AttachError> {
self.enter("thread_print");
std::thread::sleep(self.delay);
self.leave();
self.thread_dumps.lock().pop_front().expect("unexpected thread dump request")
}
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError> {
self.record("ensure_listener");
self.ensured.lock().push(pid);
self.listener_starts.lock().pop_front().unwrap_or(Ok(()))
}
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";
@@ -1160,6 +1196,491 @@ async fn jdk11_is_refused_while_the_link_is_suspended_before_dap_stops() {
assert!(!dir.exists());
}
const THREADS: &str = "Full thread dump OpenJDK 64-Bit Server VM (21.0.5+11-LTS mixed mode, sharing):\n\n\"main\" #1 [259] prio=5 os_prio=31 cpu=31.20ms elapsed=1.70s tid=0x1 nid=259 runnable [0x2]\n java.lang.Thread.State: RUNNABLE\n";
fn dumping_threads(listener: u32, dumps: Vec<Result<String, AttachError>>) -> FakeProbe {
let fake = FakeProbe::new(listener, Vec::new());
*fake.thread_dumps.lock() = dumps.into();
fake
}
fn threads_unavailable(r: JvmThreadsResult) -> JvmThreadsUnavailable {
match r {
JvmThreadsResult::Unavailable { reason } => reason,
other => panic!("{other:?}"),
}
}
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_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);
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn threads_while_suspended_without_listener_do_not_attach() {
let fake = dumping_threads(99, Vec::new());
assert_eq!(threads_unavailable(dump_text(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
}
#[test]
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_text(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 })
);
fake.version = None;
assert_eq!(
threads_unavailable(dump_text(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 0 })
);
assert!(fake.commands.lock().is_empty());
}
#[test]
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_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");
assert_eq!(*fake.commands.lock(), ["thread_print"]);
}
#[test]
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, None, &|| false);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, 12);
assert_eq!(*fake.ensured.lock(), [12]);
// No JVM at all: the reported pid is asked, which tells an exited program from a non-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, None, &|| false)),
threads_jvm(JvmMemoryUnavailable::NoJvmProcess)
);
assert_eq!(*fake.ensured.lock(), [10]);
}
#[cfg(unix)]
#[tokio::test]
async fn launched_thread_dump_without_a_listener_finds_the_jvm_below_the_reported_pid() {
struct Child(std::process::Child);
impl Drop for Child {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
let child = Child(std::process::Command::new("sleep").arg("30").spawn().unwrap());
let jvm = child.0.id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let mut fake = dumping_threads(0, vec![Ok(THREADS.into())]);
fake.application_jvms = vec![jvm];
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, None).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, jvm);
assert_eq!(*fake.ensured.lock(), [jvm]);
}
#[tokio::test]
async fn a_session_debugs_the_jvm_it_launched_or_found() {
let attach = bare_session("attach");
attach.session.jvm_pid.store(4242, Ordering::Release);
assert!(debugs_jvm(&attach.session, 4242));
assert!(!debugs_jvm(&attach.session, 4243));
let launch = bare_session("launch");
launch.session.debuggee_pid.store(77, Ordering::Release);
assert!(debugs_jvm(&launch.session, 77));
let python = bare_session_of("debugpy", "attach");
python.session.jvm_pid.store(4242, Ordering::Release);
assert!(!debugs_jvm(&python.session, 4242));
attach.session.terminated.store(true, Ordering::Release);
assert!(!debugs_jvm(&attach.session, 4242));
// An attach whose JVM is not found yet debugs no pid.
assert!(!debugs_jvm(&bare_session("attach").session, 0));
}
#[tokio::test]
async fn a_session_attached_to_a_run_may_hold_its_jvm_before_it_is_located() {
let run = ide_core::RunId(7);
let mut bare = bare_session("attach");
Arc::get_mut(&mut bare.session).unwrap().run = Some(run);
// Gradle bootRun Debug opens no attach listener, so the attach-time scan finds no pid.
assert!(attached_to_run(&bare.session, run, 555));
assert!(!attached_to_run(&bare.session, ide_core::RunId(8), 555));
bare.session.jvm_pid.store(4242, Ordering::Release);
assert!(attached_to_run(&bare.session, run, 4242));
assert!(!attached_to_run(&bare.session, run, 555), "another JVM of the same run");
bare.session.terminated.store(true, Ordering::Release);
assert!(!attached_to_run(&bare.session, run, 4242));
let mut python = bare_session_of("debugpy", "attach");
Arc::get_mut(&mut python.session).unwrap().run = Some(run);
assert!(!attached_to_run(&python.session, run, 555));
assert!(!attached_to_run(&bare_session("attach").session, run, 555), "not linked to a run");
}
#[tokio::test]
async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
// Stopped at a breakpoint, no listener: refused with the resume reason, no listener start.
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, None).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
// Running: the run's JVM is dumped under the session's turn.
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, 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]);
}
/// A run's JVM held at a breakpoint by a debugger attached to it (Debug of `spring-boot:run`).
fn stopped_attach(pid: u32) -> BareSession {
let bare = bare_session("attach");
bare.session.jvm_pid.store(i64::from(pid), Ordering::Release);
bare.session.suspended.stopped(None, true);
bare
}
#[tokio::test]
async fn run_dump_of_a_suspended_debugged_jvm_takes_the_suspended_path() {
let bare = stopped_attach(4242);
let mut fake = dumping_threads(4242, Vec::new());
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, 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, 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, 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");
bare.session.jvm_pid.store(4242, Ordering::Release);
let fake = Arc::new(dumping_threads(99, Vec::new()));
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, 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);
drop(histogram);
assert_eq!(threads_unavailable(queued.await.unwrap()), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
}
#[test]
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_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_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_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_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess));
fake.alive = false;
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_text(&fake, 12, false)) else {
panic!("not a failure")
};
assert!(message.contains("no"), "{message}");
}
#[test]
fn thread_results_serialize_with_camel_case_tags() {
let r = JvmThreadsResult::Unavailable { reason: threads_jvm(JvmMemoryUnavailable::ListenerNotRunning) };
assert_eq!(
serde_json::to_value(r).unwrap(),
serde_json::json!({"status": "unavailable", "reason": {"kind": "jvm", "reason": {"kind": "listenerNotRunning"}}})
);
let r = JvmThreadsResult::Unavailable { reason: JvmThreadsUnavailable::ListenerDidNotStart };
assert_eq!(
serde_json::to_value(r).unwrap(),
serde_json::json!({"status": "unavailable", "reason": {"kind": "listenerDidNotStart"}})
);
let dump = JvmThreadDump {
text: "t".into(),
pid: 7,
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,
"virtualJson": null, "virtualNote": "whileSuspended"
}
})
);
assert_eq!(serde_json::to_value(VirtualThreadsNote::TooLarge).unwrap(), serde_json::json!("tooLarge"));
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn threads_take_the_memory_lock() {
let pid = std::process::id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let mut fake = dumping_threads(pid, vec![Ok(THREADS.into())]);
*fake.histograms.lock() = vec![Ok(HISTOGRAM.into())].into();
fake.delay = Duration::from_millis(100);
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
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), None)
);
assert!(matches!(classes.unwrap(), JvmMemoryResult::Ready { .. }));
let threads = threads.unwrap();
assert!(matches!(threads, JvmThreadsResult::Ready { .. }), "{threads:?}");
assert_eq!(fake.max_in_flight.load(Ordering::SeqCst), 1);
assert_eq!(*fake.commands.lock(), ["histogram", "ensure_listener", "thread_print"]);
}
#[cfg(unix)]
#[tokio::test]
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 = 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 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);
drop(running);
assert_eq!(threads_unavailable(queued.await.unwrap()), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
}
#[tokio::test]
async fn attached_thread_dump_keeps_the_scanned_jvm() {
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let jvm_pid = AtomicI64::new(0);
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
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, 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"]) {
+260
View File
@@ -0,0 +1,260 @@
//! A thread dump (`Thread.print -l`) of a debugged or running JVM.
use super::heap::capture_suspended;
use super::snapshot::{AttachProbe, JdkProbe, attach_failure, gone, pick_jvm_pid};
use super::{
JvmMemoryState, JvmMemoryUnavailable, JvmTarget, histogram_pid, keep_found, lookup, resolve_jvm,
safe_while_suspended, session_target, until_located,
};
use crate::session::Session;
use ide_core::{IdeError, IdeResult};
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 {
pub text: String,
pub pid: u32,
/// Empty when unknown.
pub java_version: String,
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)]
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum JvmThreadsUnavailable {
/// The reason a class table could not be read applies to the dump too.
Jvm {
reason: JvmMemoryUnavailable,
},
/// The JVM ignored the request to open its attach listener (`-XX:+DisableAttachMechanism`).
ListenerDidNotStart,
/// A run on a remote host, whose JVM this machine cannot attach to.
RemoteRun,
Failed {
message: String,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(tag = "status", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum JvmThreadsResult {
Ready { dump: JvmThreadDump },
Unavailable { reason: JvmThreadsUnavailable },
}
/// 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, 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>,
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
// answering and let a class-table request run next to it.
tokio::spawn(async move {
let target = session_target(&session, launched);
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
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}")))?
}
/// 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,
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, 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: &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);
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_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_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_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, json_dir.as_deref(), &suspended_now)),
Err(reason) => (None, jvm(reason)),
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?;
keep_found(target, found);
Ok(outcome)
}
/// `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,
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, 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.
/// 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));
}
} else if let Err(e) = probe.ensure_listener(pid) {
return failure(probe, pid, e);
}
let version = probe.version(pid);
if suspended && !safe_while_suspended(version.as_ref()) {
return jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: version.map_or(0, |v| v.major) });
}
let started = std::time::Instant::now();
let text = match probe.thread_print(pid) {
Ok(text) => text,
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,
pid,
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,
// A program that exited leaves no perf-data file, so it fails the HotSpot check too.
AttachError::NotAJvm if probe.alive(pid) => {
JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::NoJvmProcess }
}
AttachError::NotAJvm => JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::ProgramExited },
e => match attach_failure(probe, pid, e, "thread dump") {
Ok(reason) => JvmThreadsUnavailable::Jvm { reason },
Err(e) => JvmThreadsUnavailable::Failed { message: e.message },
},
};
JvmThreadsResult::Unavailable { reason }
}
fn jvm(reason: JvmMemoryUnavailable) -> JvmThreadsResult {
JvmThreadsResult::Unavailable { reason: JvmThreadsUnavailable::Jvm { reason } }
}
+62 -16
View File
@@ -27,7 +27,7 @@ use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
use connection::{Connection, DapError};
pub use exception_classes::{ExceptionClassBreakpoint, ExceptionClassSupport};
use futures::future::join_all;
use ide_core::{DebugSessionId, IdeError, IdeResult, SharedSink};
use ide_core::{DebugSessionId, IdeError, IdeResult, RunId, SharedSink};
use ide_language::LanguageRegistry;
pub use js_cdp::JsResponseRule;
pub use js_debug::JsResponseBody;
@@ -460,6 +460,15 @@ fn child_name(configuration: &Value, parent: &str) -> String {
}
}
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
/// adapter.
pub const RUN_LINK: &str = "__openideaRun";
fn take_run_link(arguments: &mut Value) -> Option<RunId> {
let run = arguments.as_object_mut()?.remove(RUN_LINK)?;
serde_json::from_value(run).ok()
}
/// Builds the `launch`/`attach` arguments: our fields first, then `extra_json` merged on top.
pub fn launch_arguments(config: &LaunchConfig) -> IdeResult<Value> {
// VS Code puts `type`, `request` and `name` in the arguments; js-debug picks launch
@@ -888,6 +897,21 @@ impl DebugManager {
if config.adapter == "rdbg" {
rdbg_command_line(&mut spec, &config, &cwd)?;
}
// Flutter: a project depending on the Flutter SDK needs `flutter debug_adapter`
// (the Dart adapter cannot start a program importing `dart:ui`, and hot reload
// is Flutter-only). Plain Dart projects keep the configured `dart`. Before
// `custom_command`, which picks the Flutter SDK setting's `flutter`.
if config.adapter == "dart" {
let program = arguments.get("program").and_then(Value::as_str).map(Path::new);
if force_flutter || is_flutter_project(&cwd, program) {
if spec.command == "dart" {
spec.command = "flutter".into();
}
if let Some(device) = flutter_device {
add_flutter_device(&mut arguments, device);
}
}
}
if let Some(command) = custom_command(&spec.command) {
spec.command = command;
}
@@ -903,20 +927,6 @@ impl DebugManager {
spec.command = python;
}
}
// Flutter: a project depending on the Flutter SDK needs `flutter debug_adapter`
// (the Dart adapter cannot start a program importing `dart:ui`, and hot reload
// is Flutter-only). Plain Dart projects keep the configured `dart`.
if config.adapter == "dart" {
let program = arguments.get("program").and_then(Value::as_str).map(Path::new);
if force_flutter || is_flutter_project(&cwd, program) {
if spec.command == "dart" {
spec.command = "flutter".into();
}
if let Some(device) = flutter_device {
add_flutter_device(&mut arguments, device);
}
}
}
let id = DebugSessionId::next();
let debug_server = take_debug_server(&mut arguments)?;
if let Some(server) = &debug_server {
@@ -1047,7 +1057,7 @@ impl DebugManager {
adapter_name: String,
parent: Option<DebugSessionId>,
request: String,
arguments: Value,
mut arguments: Value,
spec: AdapterSpec,
reuse_port: Option<u16>,
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
@@ -1067,6 +1077,7 @@ impl DebugManager {
.flatten();
let mut session = Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child);
session.exception_classes = exception_classes;
session.run = take_run_link(&mut arguments);
let session = Arc::new(session);
if let Some(launch_type) = arguments.get("type").and_then(Value::as_str) {
let _ = session.launch_type.set(launch_type.to_owned());
@@ -1967,6 +1978,41 @@ 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, 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, 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, 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, json_dir).await)
}
/// A session attached to `run` first: one whose JVM is not located yet (its attach-time scan
/// found no listener) still holds `pid`.
fn jvm_session_of(&self, run: RunId, pid: u32) -> Option<Arc<Session>> {
let sessions = self.live_sessions();
let linked = || sessions.iter().filter(|s| jvm_memory::attached_to_run(s, run, pid));
linked()
.find(|s| jvm_memory::debugs_jvm(s, pid))
.or_else(|| linked().next())
.or_else(|| sessions.iter().find(|s| jvm_memory::debugs_jvm(s, pid)))
.cloned()
}
/// Gives the session the backend for [`Self::jvm_memory_instances`] and the debugger's class
/// counts; the UI is told to reload the session's capabilities.
pub fn set_jvm_inspector(
+7 -2
View File
@@ -8,7 +8,7 @@ use crate::{Breakpoint, BreakpointState, DataBreakpoint, DebugManager, FunctionB
use ide_core::event::DebugEvent;
#[cfg(unix)]
use ide_core::process::process_tree;
use ide_core::{DebugSessionId, IdeEvent, TaskId};
use ide_core::{DebugSessionId, IdeEvent, RunId, TaskId};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::collections::{BTreeSet, HashMap};
@@ -117,6 +117,9 @@ pub(crate) struct Session {
pub jvm_located: watch::Sender<bool>,
pub kotlin_mirror: Mutex<Option<crate::kotlin::SourceMirror>>,
pub jvm_memory: tokio::sync::Mutex<crate::JvmMemoryState>,
/// The run whose JVM this session attached to (Debug of a build tool's run, Attach to
/// Process on a run): that run's thread dumps go through this session.
pub run: Option<RunId>,
pub stream_tracer: parking_lot::Mutex<Option<Arc<dyn ide_jvm_inspect::StreamTracer>>>,
/// Given at start: the class breakpoints must be armed before `configurationDone`.
pub(crate) exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
@@ -333,6 +336,7 @@ impl Session {
jvm_located: watch::channel(false).0,
kotlin_mirror: Mutex::new(None),
jvm_memory: tokio::sync::Mutex::default(),
run: None,
stream_tracer: parking_lot::Mutex::new(None),
exception_classes: None,
exception_turn: tokio::sync::Mutex::default(),
@@ -1057,7 +1061,8 @@ fn reap_on_exit(mut child: Box<dyn portable_pty::Child + Send + Sync>, exited: A
/// starts a launcher that gives the program its terminal, and the program reads input only from
/// a terminal), forwards its output to the console, and keeps the terminal for typed input.
pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, String> {
use portable_pty::{CommandBuilder, PtySize, native_pty_system};
use ide_core::pty::native_pty_system;
use portable_pty::{CommandBuilder, PtySize};
let argv: Vec<String> = args
.get("args")
.and_then(Value::as_array)
+49
View File
@@ -3074,6 +3074,55 @@ async fn local_attach_finds_its_jvm_before_the_debugger_connects() {
assert_eq!(session.jvm_pid.load(Ordering::Acquire), 4242);
}
/// Gradle bootRun Debug: the JVM has no attach listener, so the session never learns its pid. The
/// run's dump still goes through the session and, the program being stopped, signals nothing.
#[cfg(unix)]
#[tokio::test]
async fn a_run_dump_goes_through_the_session_attached_to_the_run() {
let h = harness(Script::default());
let project = tempfile::tempdir().unwrap();
let mut cfg = remote_attach("java-debug", project.path());
let mut extra: Value = serde_json::from_str(cfg.extra_json.as_deref().unwrap()).unwrap();
extra[RUN_LINK] = json!(7);
cfg.extra_json = Some(extra.to_string());
let id = h.start(cfg).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
assert!(h.request("attach")["arguments"].get(RUN_LINK).is_none(), "IDE-side only");
let session = h.manager.session(id).unwrap();
assert_eq!((session.run, session.jvm_pid.load(Ordering::Acquire)), (Some(RunId(7)), 0));
// `sleep` stands in for the JVM: a SIGQUIT would end it.
let mut jvm = std::process::Command::new("sleep").arg("30").spawn().unwrap();
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, None).await.unwrap().unwrap();
let alive = jvm.try_wait().unwrap().is_none();
let _ = jvm.kill();
let _ = jvm.wait();
assert_eq!(
dump,
JvmThreadsResult::Unavailable {
reason: JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::ListenerNotRunning }
}
);
assert!(alive, "the stopped JVM was signalled");
}
/// A run's Dump Threads reaches the session attached to the run's JVM, not the plain run path.
#[cfg(unix)]
#[tokio::test]
async fn a_run_jvm_is_found_by_the_session_attached_to_it() {
let h = harness(Script::default());
h.manager.set_jvm_finder(Arc::new(|port, _| (port == 5005).then_some(4242)));
let mut cfg = java_config("attach");
cfg.extra_json = Some(json!({"hostName": "127.0.0.1", "port": 5005}).to_string());
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, None).await.is_none());
}
#[cfg(unix)]
#[tokio::test]
async fn local_attach_remembers_its_jdwp_port() {
+14 -2
View File
@@ -17,7 +17,7 @@ specta.workspace = true
toml.workspace = true
toml_edit.workspace = true
blake3.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["net"] }
tracing.workspace = true
parking_lot.workspace = true
notify.workspace = true
@@ -27,7 +27,6 @@ tiberius.workspace = true
oracledb.workspace = true
bb8.workspace = true
tokio-util = { workspace = true, features = ["compat"] }
dirs.workspace = true
ide-ssh.workspace = true
ide-http.workspace = true
reqwest = { workspace = true, features = ["query"] }
@@ -39,6 +38,19 @@ rsa = { version = "0.10.0-rc.18", features = ["sha2", "pkcs5"] }
zeroize = "1"
open = "5"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_NetworkManagement_IpHelper",
"Win32_Networking_WinSock",
"Win32_System_Diagnostics_ToolHelp",
"Win32_System_Threading",
"Win32_System_JobObjects",
] }
[dev-dependencies]
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "net"] }
ide-ssh = { workspace = true, features = ["testing"] }
+1
View File
@@ -316,6 +316,7 @@ impl ClickhousePool {
has_more,
elapsed_ms: started.elapsed().as_secs_f64() * 1000.0,
execution_ms,
truncated: Vec::new(),
})
};
let result = tokio::select! {
+349 -55
View File
@@ -12,7 +12,7 @@ use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use serde::{Deserialize, Serialize};
use specta::Type;
use sqlx::{
Column, ColumnIndex, Connection, Decode, Executor, Row, SqlSafeStr, Sqlite, TypeInfo, ValueRef,
Column, ColumnIndex, ConnectOptions, Connection, Decode, Executor, Row, SqlSafeStr, Sqlite, TypeInfo, ValueRef,
mysql::{MySqlConnectOptions, MySqlConnection, MySqlSslMode},
pool::PoolConnection,
postgres::{PgConnectOptions, PgConnection, PgSslMode},
@@ -48,6 +48,65 @@ pub struct QueryResult {
pub elapsed_ms: f64,
/// Until the server's first answer; the rest of `elapsed_ms` is fetching.
pub execution_ms: f64,
/// Cells of `rows` cut short by [`QueryResult::cap_cells`], in row order.
pub truncated: Vec<TruncatedCell>,
}
/// A cell of a [`QueryResult`] whose text was cut to a prefix.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbTruncatedCell")]
pub struct TruncatedCell {
pub row: u32,
pub column: u32,
/// Length of the whole value in UTF-16 code units (what a JavaScript string counts).
pub length: u32,
/// FNV-1a (32 bits) of the whole value's UTF-16 code units, each taken as one 16-bit step,
/// so a client that reads the value again can tell whether it is the one that was cut.
pub hash: u32,
}
/// FNV-1a over UTF-16 code units, one step per unit (the same on the client: see `cutCells.ts`).
fn fnv1a_utf16(text: &str) -> u32 {
let mut hash: u32 = 0x811c_9dc5;
let mut pair = [0u16; 2];
for ch in text.chars() {
for unit in ch.encode_utf16(&mut pair) {
hash = (hash ^ u32::from(*unit)).wrapping_mul(0x0100_0193);
}
}
hash
}
impl QueryResult {
/// Cuts every cell longer than `limit` UTF-16 code units to its first `limit` (never inside a
/// surrogate pair) and lists it in `truncated`, so a page's size no longer depends on how
/// wide its values are. The full value is read again, one row at a time, when it is needed.
pub fn cap_cells(&mut self, limit: usize) {
for (r, row) in self.rows.iter_mut().enumerate() {
for (c, cell) in row.iter_mut().enumerate() {
let Some(text) = cell else { continue };
// A UTF-16 length never exceeds the UTF-8 one.
if text.len() <= limit {
continue;
}
let mut units = 0;
let mut cut = text.len();
for (at, ch) in text.char_indices() {
if units + ch.len_utf16() > limit && cut == text.len() {
cut = at;
}
units += ch.len_utf16();
}
if units <= limit {
continue;
}
let hash = fnv1a_utf16(text);
text.truncate(cut);
self.truncated.push(TruncatedCell { row: r as u32, column: c as u32, length: units as u32, hash });
}
}
}
}
/// Session context belongs to the physical connection, including across pool checkouts.
@@ -76,7 +135,7 @@ impl Context {
}
macro_rules! sqlx_pool {
($manager:ident, $handle:ident, $options:ty, $connection:ty, $driver:expr, $query:expr) => {
($manager:ident, $handle:ident, $options:ty, $connection:ty, $driver:expr, $query:expr $(, $after_init:ident)?) => {
pub struct $manager {
options: $options,
init: Arc<Vec<String>>,
@@ -111,7 +170,7 @@ macro_rules! sqlx_pool {
async fn connect(&self) -> Result<Self::Connection, Self::Error> {
tokio::time::timeout(self.timeout, async {
let mut conn = <$connection>::connect_with(&self.options).await?;
let mut conn = self.options.connect().await?;
let context_sql = |value: Option<String>| {
value.map(|v| {
if $driver == DbDriver::Postgres {
@@ -124,6 +183,9 @@ macro_rules! sqlx_pool {
for sql in self.init.iter() {
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut conn).await?;
}
$(if !self.init.is_empty() {
self.options.$after_init(&mut conn).await?;
})?
let row = sqlx::raw_sql(sqlx::AssertSqlSafe($query.to_owned())).fetch_one(&mut conn).await?;
let context = Context::new(context_sql(row.try_get(0)?));
Ok($handle {
@@ -150,7 +212,88 @@ macro_rules! sqlx_pool {
};
}
sqlx_pool!(PgManager, PgHandle, PgConnectOptions, PgConnection, DbDriver::Postgres, "SHOW search_path");
#[derive(Clone)]
struct PostgresOptions {
connection: PgConnectOptions,
read_only: bool,
}
const PG_READ_ONLY_HINT: &str = "Read-only requires the pooler to track default_transaction_read_only for each client. \
For PgBouncer, check track_extra_parameters.";
impl PostgresOptions {
async fn connect(&self) -> Result<PgConnection, sqlx::Error> {
let mut conn = self.connection.connect().await?;
// A pooler can silently discard startup options. Check before giving the startup script a connection.
self.verify_read_only(&mut conn).await?;
Ok(conn)
}
async fn verify_read_only(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
if self.read_only && !pg_setting_on(conn, "SHOW default_transaction_read_only").await? {
return Err(sqlx::Error::Configuration(
format!(
"PostgreSQL did not enable the requested default_transaction_read_only setting. \
Check the Advanced properties and startup script. {PG_READ_ONLY_HINT}"
)
.into(),
));
}
Ok(())
}
async fn verify_startup_script(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
self.verify_read_only(conn).await?;
if self.read_only && !pg_setting_on(conn, "SHOW transaction_read_only").await? {
return Err(sqlx::Error::Configuration(
"The startup script left a writable transaction open on a read-only PostgreSQL source.".into(),
));
}
Ok(())
}
}
async fn pg_setting_on(conn: &mut PgConnection, show: &'static str) -> Result<bool, sqlx::Error> {
let row = sqlx::raw_sql(show).fetch_one(conn).await?;
Ok(row.try_get::<&str, _>(0)? == "on")
}
fn postgres_read_only_hint(read_only: bool, code: Option<&str>, message: &str) -> Option<&'static str> {
match (read_only, code, message) {
(
true,
Some("08P01"),
"unsupported startup parameter in options: default_transaction_read_only"
| "unsupported startup parameter: default_transaction_read_only",
) => Some(PG_READ_ONLY_HINT),
(true, Some("08P01"), "unsupported startup parameter: options") => Some(
"This endpoint rejects PostgreSQL startup options. Use an endpoint that supports and tracks \
default_transaction_read_only for each client.",
),
_ => None,
}
}
fn postgres_connect_error(error: sqlx::Error, read_only: bool) -> IdeError {
let hint =
error.as_database_error().and_then(|db| postgres_read_only_hint(read_only, db.code().as_deref(), db.message()));
let mut error = db_err(error);
if let Some(hint) = hint {
error.message.push_str(". ");
error.message.push_str(hint);
}
error
}
sqlx_pool!(
PgManager,
PgHandle,
PostgresOptions,
PgConnection,
DbDriver::Postgres,
"SHOW search_path",
verify_startup_script
);
sqlx_pool!(MysqlManager, MysqlHandle, MySqlConnectOptions, MySqlConnection, DbDriver::Mysql, "SELECT DATABASE()");
pub struct ServerPool<M: ManageConnection> {
@@ -486,6 +629,86 @@ fn result_columns<R: Row>(row: &R) -> Vec<ResultColumn> {
.collect()
}
/// How far a statement's stream has been read: the columns seen so far, and the row that
/// showed more were coming, which the next read starts with.
pub(crate) struct Reader<R> {
columns: Vec<ResultColumn>,
carry: Option<R>,
}
impl<R> Default for Reader<R> {
fn default() -> Self {
Self { columns: Vec::new(), carry: None }
}
}
#[cfg(test)]
thread_local! {
/// Rows pulled from statement streams on this thread (tests count what paging reads).
pub(crate) static ROWS_PULLED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// Reads on from `stream`: past the next `skip` rows without decoding them, then keeping at
/// most `max` rows with their cells read as `mode`. `rows_affected` reads a command's count.
async fn drain<S, D, R>(
stream: &mut S,
reader: &mut Reader<R>,
skip: usize,
max: usize,
mode: Cells,
rows_affected: impl Fn(&D) -> u64,
) -> IdeResult<Fetched>
where
S: futures::Stream<Item = Result<sqlx::Either<D, R>, sqlx::Error>> + Unpin,
R: Row,
usize: ColumnIndex<R>,
String: sqlx::Type<R::Database>,
for<'r> String: Decode<'r, R::Database>,
for<'r> Vec<u8>: Decode<'r, R::Database>,
{
let mut rows: Vec<Vec<Option<String>>> = Vec::new();
let mut affected: Option<u64> = None;
let mut has_more = false;
let mut first: Option<Instant> = None;
let mut to_skip = skip;
loop {
let item = match reader.carry.take() {
Some(row) => Ok(sqlx::Either::Right(row)),
None => match stream.next().await {
Some(item) => {
#[cfg(test)]
if matches!(item, Ok(sqlx::Either::Right(_))) {
ROWS_PULLED.with(|n| n.set(n.get() + 1));
}
item
}
None => break,
},
};
first.get_or_insert_with(Instant::now);
match item {
Ok(sqlx::Either::Left(done)) => affected = Some(affected.unwrap_or(0) + rows_affected(&done)),
Ok(sqlx::Either::Right(row)) => {
if reader.columns.is_empty() {
reader.columns = result_columns(&row);
}
if to_skip > 0 {
to_skip -= 1;
continue;
}
if rows.len() >= max {
reader.carry = Some(row);
has_more = true;
break;
}
rows.push((0..row.len()).map(|i| cell(&row, i, mode)).collect());
}
Err(e) => return Err(db_err(e)),
}
}
Ok((reader.columns.clone(), rows, affected, has_more, first))
}
/// Streams the results of `$sql` on executor `$exec`, reading past the first `$skip`
/// rows without decoding them, then keeping at most `$max` rows with their cells read as `$mode`.
macro_rules! fetch {
@@ -493,44 +716,8 @@ macro_rules! fetch {
fetch!($exec, $sql, 0usize, $max, $mode)
};
($exec:expr, $sql:expr, $skip:expr, $max:expr, $mode:expr) => {{
use futures::StreamExt;
let mut stream = sqlx::raw_sql(sqlx::AssertSqlSafe($sql.to_owned())).fetch_many($exec);
let mut columns: Vec<ResultColumn> = Vec::new();
let mut rows: Vec<Vec<Option<String>>> = Vec::new();
let mut affected: Option<u64> = None;
let mut has_more = false;
let mut failure = None;
let mut first: Option<Instant> = None;
let mut to_skip: usize = $skip;
while let Some(item) = stream.next().await {
first.get_or_insert_with(Instant::now);
match item {
Ok(sqlx::Either::Left(done)) => affected = Some(affected.unwrap_or(0) + done.rows_affected()),
Ok(sqlx::Either::Right(row)) => {
if columns.is_empty() {
columns = result_columns(&row);
}
if to_skip > 0 {
to_skip -= 1;
continue;
}
if rows.len() >= $max {
has_more = true;
break;
}
rows.push((0..row.len()).map(|i| cell(&row, i, $mode)).collect());
}
Err(e) => {
failure = Some(db_err(e));
break;
}
}
}
drop(stream);
match failure {
Some(e) => Err(e),
None => Ok((columns, rows, affected, has_more, first)),
}
drain(&mut stream, &mut Reader::default(), $skip, $max, $mode, |done| done.rows_affected()).await
}};
}
@@ -586,6 +773,31 @@ macro_rules! backend_id {
}};
}
mod cursor;
pub(crate) use cursor::{Cursors, Key as CursorKey};
/// Whether the pages of `sql`'s result can be read by a cursor (see [`cursor`]): a query that
/// leaves the session as it was.
pub(crate) fn cursor_statement(sql: &str) -> bool {
looks_like_query(sql) && !context_may_change(sql)
}
/// A [`QueryResult`] of what `fetched` read of `sql`, run since `started`.
pub(crate) fn query_result(sql: &str, fetched: Fetched, started: Instant) -> QueryResult {
let (columns, rows, affected, has_more, first) = fetched;
let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
QueryResult {
statement: sql.to_owned(),
affected: if columns.is_empty() { Some(affected.unwrap_or(0) as f64) } else { None },
columns,
rows,
has_more,
elapsed_ms,
execution_ms: first.map_or(elapsed_ms, |t| t.duration_since(started).as_secs_f64() * 1000.0),
truncated: Vec::new(),
}
}
// Session control, scripts and PostgreSQL set_config can invalidate the tracked context.
fn context_may_change(sql: &str) -> bool {
let text = sql.trim().trim_end_matches(';');
@@ -852,17 +1064,18 @@ impl Pool {
if let Some(n) = setup.statement_cache {
opts = opts.statement_cache_capacity(n);
}
let mut manager = PgManager { options: opts, init: init.clone(), timeout };
let options = PostgresOptions { connection: opts, read_only: source.read_only };
let mut manager = PgManager { options, init: init.clone(), timeout };
// Open once directly so authentication failures retain their database error.
let first = match manager.connect().await {
Err(e) if source.ssl == DbSslMode::Prefer && tls_failed(&e) => {
tracing::info!("TLS handshake failed, connecting without TLS (SSL mode Prefer): {e}");
manager.options = manager.options.clone().ssl_mode(PgSslMode::Disable);
manager.options.connection = manager.options.connection.clone().ssl_mode(PgSslMode::Disable);
manager.connect().await
}
first => first,
}
.map_err(db_err)?;
.map_err(|e| postgres_connect_error(e, source.read_only))?;
let pool = Bb8Pool::builder().max_size(MAX).connection_timeout(timeout).build_unchecked(manager);
let _ = pool.add(first);
Ok(Pool::Postgres(ServerPool { inner: pool, closed: AtomicBool::new(false) }))
@@ -985,6 +1198,12 @@ impl Pool {
}
}
/// Whether a later page of a result can be read from a cursor instead of by running the statement
/// again: the drivers whose rows stream from one connection that can wait for the next page.
pub(crate) fn keeps_cursors(&self) -> bool {
matches!(self, Pool::Sqlite(_) | Pool::Postgres(_) | Pool::Mysql(_))
}
/// Runs `sql` (no row limit beyond `max`), for introspection: cells are text (see [`Cells::Text`]).
pub async fn rows(&self, sql: &str, max: usize) -> IdeResult<Vec<Vec<Option<String>>>> {
if let Pool::Jdbc(p) = self {
@@ -1403,17 +1622,7 @@ impl Held {
Held::Clickhouse(_) | Held::Snowflake(..) => unreachable!(),
};
self.after_statement(sql);
let (columns, rows, affected, has_more, first) = fetched;
let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
Ok(QueryResult {
statement: sql.to_owned(),
affected: if columns.is_empty() { Some(affected.unwrap_or(0) as f64) } else { None },
columns,
rows,
has_more,
elapsed_ms,
execution_ms: first.map_or(elapsed_ms, |t| t.duration_since(started).as_secs_f64() * 1000.0),
})
Ok(query_result(sql, fetched, started))
}
}
@@ -1439,6 +1648,91 @@ mod tests {
use super::*;
use crate::source::{DbOptions, DbProperty};
fn rows(cells: Vec<Vec<Option<String>>>) -> QueryResult {
query_result("select", (Vec::new(), cells, None, false, None), Instant::now())
}
#[test]
fn capping_cells_bounds_a_page_and_reports_the_whole_length() {
let wide = "x".repeat(1_000_000);
let mut r = rows(vec![vec![Some("short".into()), Some(wide.clone()), None], vec![Some(wide), None, None]]);
r.cap_cells(100);
let size: usize = r.rows.iter().flatten().flatten().map(String::len).sum();
assert_eq!(size, 5 + 100 + 100);
assert_eq!(
r.truncated,
[
TruncatedCell { row: 0, column: 1, length: 1_000_000, hash: fnv1a_utf16(&"x".repeat(1_000_000)) },
TruncatedCell { row: 1, column: 0, length: 1_000_000, hash: fnv1a_utf16(&"x".repeat(1_000_000)) }
]
);
assert_eq!(r.rows[0][0].as_deref(), Some("short"));
assert_eq!(r.rows[0][2], None);
}
#[test]
fn a_cut_cell_is_hashed_by_its_utf16_units() {
// Fixed values: the client (`cutCells.ts`) computes the same hash to recognise a value it reads again.
assert_eq!(fnv1a_utf16(""), 2_166_136_261);
assert_eq!(fnv1a_utf16("a"), 3_826_002_220);
assert_eq!(fnv1a_utf16("a😀b"), 2_412_414_209);
assert_eq!(fnv1a_utf16("日本語日本語"), 2_778_669_755);
assert_ne!(fnv1a_utf16(&"x".repeat(100)), fnv1a_utf16(&format!("{}y", "x".repeat(99))));
let mut r = rows(vec![vec![Some("a😀b".into())]]);
r.cap_cells(2);
assert_eq!(r.truncated[0].hash, 2_412_414_209);
}
#[test]
fn capping_cells_keeps_values_at_or_under_the_limit_whole() {
let mut r = rows(vec![vec![Some("abcd".into()), Some("😀😀".into()), Some("ééé".into())]]);
// 4 units, 4 units (two pairs), 3 units in 6 bytes.
r.cap_cells(4);
assert!(r.truncated.is_empty());
assert_eq!(r.rows[0][1].as_deref(), Some("😀😀"));
r.cap_cells(3);
assert_eq!(
r.truncated,
[
TruncatedCell { row: 0, column: 0, length: 4, hash: fnv1a_utf16("abcd") },
TruncatedCell { row: 0, column: 1, length: 4, hash: fnv1a_utf16("😀😀") }
]
);
assert_eq!(r.rows[0][2].as_deref(), Some("ééé"));
}
#[test]
fn capping_cells_never_splits_a_character_or_a_surrogate_pair() {
// "a😀b": units a=1, 😀=2, b=1. A cut inside the pair falls back to before it.
let mut r = rows(vec![vec![Some("a😀b".into()), Some("日本語日本語".into())]]);
r.cap_cells(2);
assert_eq!(r.rows[0][0].as_deref(), Some("a"));
assert_eq!(r.rows[0][1].as_deref(), Some("日本"));
assert_eq!(r.truncated[0].length, 4);
assert_eq!(r.truncated[1].length, 6);
// What is kept is a prefix of the whole value, measured in UTF-16 units.
for (cut, whole) in [(&r.rows[0][0], "a😀b"), (&r.rows[0][1], "日本語日本語")] {
assert!(whole.starts_with(cut.as_deref().unwrap()));
assert!(cut.as_deref().unwrap().encode_utf16().count() <= 2);
}
}
#[test]
fn postgres_read_only_guidance_identifies_what_the_pooler_rejected() {
let rejected = "unsupported startup parameter in options: default_transaction_read_only";
assert_eq!(postgres_read_only_hint(true, Some("08P01"), rejected), Some(PG_READ_ONLY_HINT));
let direct = "unsupported startup parameter: default_transaction_read_only";
assert_eq!(postgres_read_only_hint(true, Some("08P01"), direct), Some(PG_READ_ONLY_HINT));
let options = postgres_read_only_hint(true, Some("08P01"), "unsupported startup parameter: options").unwrap();
assert!(options.contains("rejects PostgreSQL startup options"));
assert_eq!(postgres_read_only_hint(false, Some("08P01"), rejected), None);
assert_eq!(postgres_read_only_hint(true, Some("28P01"), rejected), None);
assert_eq!(
postgres_read_only_hint(true, Some("08P01"), "unsupported startup parameter: extra_float_digits"),
None
);
}
#[test]
fn prefer_retries_without_tls_only_after_a_failed_handshake() {
use std::io;
+474
View File
@@ -0,0 +1,474 @@
//! Result paging that reads on from where the previous page stopped.
//!
//! A statement has no way to start at row N: its server sends the rows before it, and a
//! page that re-runs the query reads and drops all of them. The page after another one
//! continues the same stream instead, so paging forward costs one page per click.
//!
//! A cursor keeps its statement's stream, and so its connection, open, which holds
//! server resources (locks, a snapshot) for as long as it lives. That is bounded:
//! one cursor per target, a few overall, each closed after [`IDLE`] without a page, when
//! its tab is closed or its target disconnects, and before a statement that is not a
//! query runs on its target. A page that finds no cursor at its position (jumping
//! to another page, going back, a closed cursor) starts a new one.
use super::{Cells, Fetched, Held, Pool, Reader, drain, looks_like_query, statement_columns};
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use parking_lot::Mutex;
use sqlx::{Executor, SqlSafeStr};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};
/// How long a cursor waits for its next page.
const IDLE: Duration = Duration::from_secs(30);
/// Cursors kept at once, over all targets (each holds a connection).
const MAX_CURSORS: usize = 4;
/// What a cursor reads the pages of: one statement of one target, in a schema context.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Key {
target: String,
statement: String,
schema: Option<String>,
}
impl Key {
pub(crate) fn new(target: &str, statement: &str, schema: Option<&str>) -> Self {
Self {
target: target.to_owned(),
statement: statement.to_owned(),
schema: schema.filter(|s| !s.is_empty()).map(str::to_owned),
}
}
}
/// A request for the next rows of a cursor's statement.
struct Read {
skip: usize,
max: usize,
cancel: CancellationToken,
reply: oneshot::Sender<IdeResult<Fetched>>,
}
/// A live cursor: where its stream stands, and the channel to the task that owns it.
struct Slot {
id: u64,
key: Key,
/// The number of rows read from the start of the statement (skipped or returned).
next: usize,
/// A page is being read from it: it stays registered meanwhile, so a release finds it.
busy: bool,
reads: mpsc::Sender<Read>,
}
/// Reads `max` rows after the first `skip` of a cursor's stream through `reads`; `None` when the cursor is gone.
async fn read(
reads: &mpsc::Sender<Read>,
skip: usize,
max: usize,
cancel: &CancellationToken,
) -> Option<IdeResult<Fetched>> {
let (reply, answer) = oneshot::channel();
reads.send(Read { skip, max, cancel: cancel.clone(), reply }).await.ok()?;
answer.await.ok()
}
#[derive(Default)]
struct Registry {
/// Oldest first.
slots: Vec<Slot>,
issued: u64,
}
#[derive(Default)]
pub(crate) struct Cursors {
registry: Mutex<Registry>,
}
impl Cursors {
/// The page at `skip` read from the cursor of `key` that stands there; `None` when
/// there is none (the caller starts one) or it failed (a lost connection: the caller
/// runs the statement again and reports whatever that returns).
pub(crate) async fn resume(
&self,
key: &Key,
skip: usize,
max: usize,
cancel: &CancellationToken,
) -> Option<IdeResult<Fetched>> {
let (id, reads) = {
let mut registry = self.registry.lock();
let slot = registry
.slots
.iter_mut()
.find(|s| s.key == *key && s.next == skip && !s.busy && !s.reads.is_closed())?;
slot.busy = true;
(slot.id, slot.reads.clone())
};
match read(&reads, 0, max, cancel).await {
Some(Ok(fetched)) => {
self.finish(id, &fetched);
Some(Ok(fetched))
}
Some(Err(e)) if e.kind == ErrorKind::Cancelled => {
self.close(id);
Some(Err(e))
}
_ => {
self.close(id);
None
}
}
}
/// Runs the statement of `key` on `held`, returns the page at `skip` and keeps the
/// statement's stream for the page after it. `held` is taken out of `pool` (its
/// context applied); `pool` stops the statement on the server when `cancel` fires.
pub(crate) async fn start(
&self,
held: Held,
pool: Arc<Pool>,
key: Key,
skip: usize,
max: usize,
cancel: &CancellationToken,
) -> IdeResult<Fetched> {
let (reads, requests) = mpsc::channel(1);
tokio::spawn(serve(held, pool, key.statement.clone(), requests));
let id = self.register(key, skip, reads.clone());
let fetched = match read(&reads, skip, max, cancel).await {
Some(Ok(fetched)) => fetched,
other => {
self.close(id);
return other.unwrap_or_else(|| Err(IdeError::internal("the statement stopped before it answered")));
}
};
self.finish(id, &fetched);
Ok(fetched)
}
/// Registers a cursor that is reading its first page. A target keeps one cursor (its
/// connection pool is small), and all together are bounded.
fn register(&self, key: Key, next: usize, reads: mpsc::Sender<Read>) -> u64 {
let mut registry = self.registry.lock();
registry.issued += 1;
let id = registry.issued;
registry.slots.retain(|s| s.key.target != key.target && !s.reads.is_closed());
registry.slots.push(Slot { id, key, next, busy: true, reads });
if registry.slots.len() > MAX_CURSORS {
registry.slots.remove(0);
}
id
}
/// Ready for the page after `fetched`, which cursor `id` just read, when more rows are waiting in its
/// stream; closed otherwise. A cursor released meanwhile is gone from the registry: the caller's
/// handle on its channel is the last, so the statement stops.
fn finish(&self, id: u64, fetched: &Fetched) {
let mut registry = self.registry.lock();
let Some(at) = registry.slots.iter().position(|s| s.id == id) else { return };
if fetched.3 {
let slot = &mut registry.slots[at];
slot.next += fetched.1.len();
slot.busy = false;
} else {
registry.slots.remove(at);
}
}
fn close(&self, id: u64) {
self.registry.lock().slots.retain(|s| s.id != id);
}
/// Closes the cursor of one statement of `target` (its result tab was closed), also when it is reading a page.
pub(crate) fn release(&self, key: &Key) {
self.registry.lock().slots.retain(|s| s.key != *key);
}
/// Closes the cursors of `target`: it disconnects, or a statement that changes
/// data or schema is about to run there.
pub(crate) fn release_target(&self, target: &str) {
self.registry.lock().slots.retain(|s| s.key.target != target);
}
}
/// Owns `held` and the stream of `sql` on it, answering reads until the stream ends,
/// nobody asks for [`IDLE`], or it is released (its channel closes).
async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Receiver<Read>) {
let Some(first) = reads.recv().await else { return held.discard().await };
// `$id`: the query naming the server process, `$kill`: how another connection stops it.
// Evaluates to whether the connection can go back to its pool (the stream was read to
// its end); otherwise it is closed rather than left to be drained.
macro_rules! serve {
($conn:expr, $id:expr, $kill:expr) => {{
let backend = match $id {
Some(q) => backend_id!(&mut **$conn, q),
None => None,
};
let mut stream = sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).fetch_many(&mut **$conn);
let mut reader = Reader::default();
let mut request = Some(first);
let mut last = None;
let mut reusable = false;
while let Some(Read { skip, max, cancel, reply }) = request.take() {
let read = tokio::select! {
r = drain(&mut stream, &mut reader, skip, max, Cells::Display, |done| done.rows_affected()) => r,
() = cancel.cancelled() => Err(IdeError::cancelled()),
};
if cancel.is_cancelled() {
if let Some(b) = backend {
let _ = pool.rows(&$kill(b), 1).await;
}
let _ = reply.send(Err(IdeError::cancelled()));
break;
}
match read {
Ok(fetched) if fetched.3 => {
if reply.send(Ok(fetched)).is_err() {
break;
}
request = tokio::time::timeout(IDLE, reads.recv()).await.unwrap_or(None);
}
Ok(fetched) => {
last = Some((reply, fetched));
reusable = true;
break;
}
Err(e) => {
let _ = reply.send(Err(e));
reusable = true;
break;
}
}
}
drop(stream);
if let Some((reply, mut fetched)) = last {
if fetched.0.is_empty() && looks_like_query(&sql) {
fetched.0 = (&mut **$conn)
.prepare(sqlx::AssertSqlSafe(sql.clone()).into_sql_str())
.await
.map(|s| statement_columns(&s))
.unwrap_or_default();
}
let _ = reply.send(Ok(fetched));
}
reusable
}};
}
let reusable = match &mut held {
Held::Sqlite(c) => serve!(c, None::<&str>, |_: String| String::new()),
Held::Postgres(c) => {
serve!(&mut ***c, Some("SELECT pg_backend_pid()"), |b: String| format!("SELECT pg_cancel_backend({b})"))
}
Held::Mysql(c) => serve!(&mut ***c, Some("SELECT CONNECTION_ID()"), |b: String| format!("KILL QUERY {b}")),
_ => unreachable!("only the sqlx drivers keep cursors"),
};
if !reusable {
held.discard().await;
}
}
#[cfg(test)]
mod tests {
use super::super::ROWS_PULLED;
use crate::{DataSource, DbDriver, DbManager};
use ide_core::{CancellationToken, error::ErrorKind};
const PAGE: usize = 100;
const ROWS: usize = 1000;
/// A SQLite data source `s1` with a table `t` of `ROWS` rows (`id` 1..=ROWS).
async fn manager() -> (tempfile::TempDir, DbManager) {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().to_path_buf();
std::fs::File::create(root.join("app.db")).unwrap();
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
let db = DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
db.save_sources(vec![DataSource {
id: "s1".into(),
name: "app".into(),
driver: DbDriver::Sqlite,
file: Some("app.db".into()),
..Default::default()
}])
.await
.unwrap();
let cancel = CancellationToken::new();
db.execute("s1", "CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)", 0, &cancel).await.unwrap();
db.execute(
"s1",
&format!(
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < {ROWS}) \
INSERT INTO t SELECT i, 'row ' || i FROM n"
),
0,
&cancel,
)
.await
.unwrap();
(tmp, db)
}
const QUERY: &str = "SELECT id, name FROM t ORDER BY id";
/// The ids of page `page` of `QUERY`, and whether more rows follow.
async fn page(db: &DbManager, statement: &str, page: usize) -> (Vec<i64>, bool) {
let r = db.execute_from("s1", statement, page * PAGE, PAGE, &CancellationToken::new(), None).await.unwrap();
(r.rows.iter().map(|row| row[0].as_deref().unwrap().parse().unwrap()).collect(), r.has_more)
}
fn ids(page: usize) -> Vec<i64> {
((page * PAGE + 1) as i64..=((page + 1) * PAGE) as i64).collect()
}
fn pulled() -> u64 {
ROWS_PULLED.with(std::cell::Cell::get)
}
#[tokio::test]
async fn paging_forward_reads_each_row_once() {
let (_tmp, db) = manager().await;
let before = pulled();
for p in 0..ROWS / PAGE {
let (rows, has_more) = page(&db, QUERY, p).await;
assert_eq!(rows, ids(p), "page {p}");
assert_eq!(has_more, p + 1 < ROWS / PAGE, "page {p} has_more");
}
// Running the query again for every page reads 1+2+…+10 pages (5500 rows); one pass reads ~1000.
assert!(pulled() - before < 2 * ROWS as u64, "read {} rows", pulled() - before);
}
#[tokio::test]
async fn jumping_and_going_back_return_the_right_pages() {
let (_tmp, db) = manager().await;
for p in [5, 6, 2, 3, 9, 0, 1, 7, 7, 8] {
assert_eq!(page(&db, QUERY, p).await.0, ids(p), "page {p}");
}
}
#[tokio::test]
async fn reading_a_row_leaves_the_cursor_of_the_pages_alone() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 1).await;
let row = db.read_row("s1", QUERY, 350, &CancellationToken::new(), None).await.unwrap();
assert_eq!(row.rows, [[Some("351".to_owned()), Some("row 351".to_owned())]]);
assert_eq!(db.cursors.registry.lock().slots.len(), 1);
// The next page still continues the cursor: it reads one page, not 200 rows again.
let before = pulled();
assert_eq!(page(&db, QUERY, 2).await.0, ids(2));
assert!(pulled() - before <= PAGE as u64 + 1, "read {} rows", pulled() - before);
}
#[tokio::test]
async fn pages_past_the_end_are_empty() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 8).await;
let r = db.execute_from("s1", QUERY, 2 * ROWS, PAGE, &CancellationToken::new(), None).await.unwrap();
assert!(r.rows.is_empty() && !r.has_more);
// The columns of an empty page still come from the statement.
assert_eq!(r.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "name"]);
}
#[tokio::test]
async fn another_statement_does_not_continue_a_cursor() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 1).await;
let other = "SELECT id, name FROM t ORDER BY id DESC";
let r = db.execute_from("s1", other, 2 * PAGE, PAGE, &CancellationToken::new(), None).await.unwrap();
let first: i64 = r.rows[0][0].as_deref().unwrap().parse().unwrap();
assert_eq!(first, (ROWS - 2 * PAGE) as i64);
}
#[tokio::test]
async fn a_statement_that_changes_data_closes_the_cursor() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 1).await;
assert_eq!(db.cursors.registry.lock().slots.len(), 1);
db.execute("s1", "DELETE FROM t WHERE id = 150", 0, &CancellationToken::new()).await.unwrap();
assert_eq!(db.cursors.registry.lock().slots.len(), 0);
// The next page shows the change: row 150 is gone, so page 2 starts at 202.
assert_eq!(page(&db, QUERY, 2).await.0[0], 202);
}
#[tokio::test]
async fn releasing_and_abandoning_cursors_gives_their_connections_back() {
let (_tmp, db) = manager().await;
// The pool has 4 connections: a leak would starve `execute` after a few rounds.
for _ in 0..8 {
page(&db, QUERY, 1).await;
db.release_result("s1", QUERY, None);
assert_eq!(db.cursors.registry.lock().slots.len(), 0);
assert_eq!(page(&db, "SELECT count(*) FROM t", 0).await.0, [ROWS as i64]);
}
// Finishing a result also frees its connection.
for _ in 0..8 {
for p in 1..ROWS / PAGE {
page(&db, QUERY, p).await;
}
}
assert_eq!(db.cursors.registry.lock().slots.len(), 0);
}
#[tokio::test]
async fn a_cancelled_page_closes_its_cursor() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 1).await;
let cancel = CancellationToken::new();
cancel.cancel();
let e = db.execute_from("s1", QUERY, 2 * PAGE, PAGE, &cancel, None).await.unwrap_err();
assert_eq!(e.kind, ErrorKind::Cancelled);
assert_eq!(db.cursors.registry.lock().slots.len(), 0);
assert_eq!(page(&db, QUERY, 2).await.0, ids(2));
}
/// A closed result tab releases its cursor even when a page is being read from it: the
/// cursor is not put back afterwards and its statement stops.
#[tokio::test]
async fn releasing_a_cursor_in_the_middle_of_a_page_read_closes_it() {
use super::{Cursors, Key, Read};
use std::sync::Arc;
use tokio::sync::{Notify, mpsc};
let cursors = Arc::new(Cursors::default());
let key = Key::new("s1", QUERY, None);
let (reads, mut requests) = mpsc::channel::<Read>(1);
cursors.register(key.clone(), 0, reads.clone());
let page = || (Vec::new(), vec![vec![Some("1".to_owned())]], None, true, None);
cursors.finish(1, &page());
drop(reads);
let in_read = Arc::new(Notify::new());
let (release, announced) = (Arc::new(Notify::new()), in_read.clone());
let server = tokio::spawn({
let release = release.clone();
async move {
let read = requests.recv().await.unwrap();
announced.notify_one();
release.notified().await;
let _ = read.reply.send(Ok(page()));
// The channel closes once nobody holds a handle on it.
requests.recv().await.is_none()
}
});
let resumed = tokio::spawn({
let (cursors, key) = (cursors.clone(), key.clone());
async move { cursors.resume(&key, 1, 1, &CancellationToken::new()).await.is_some() }
});
in_read.notified().await;
cursors.release(&key);
release.notify_one();
assert!(resumed.await.unwrap(), "the page that was being read is still returned");
assert!(cursors.registry.lock().slots.is_empty(), "the released cursor is not put back");
assert!(server.await.unwrap(), "the statement's task sees its channel close");
}
#[tokio::test]
async fn a_target_keeps_one_cursor_and_all_are_bounded() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 1).await;
page(&db, "SELECT id, name FROM t WHERE id > 0 ORDER BY id", 1).await;
assert_eq!(db.cursors.registry.lock().slots.len(), 1);
// The first statement's cursor is gone: its next page is read again, and still right.
assert_eq!(page(&db, QUERY, 2).await.0, ids(2));
}
}
+436
View File
@@ -0,0 +1,436 @@
//! An approved foreground helper behind a loopback relay owned by the IDE.
use crate::DbExternalTunnel;
use ide_core::{IdeError, IdeResult, error::ErrorKind, process};
use parking_lot::Mutex;
use std::io;
use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, Weak};
use std::time::Duration;
use tokio::net::{TcpListener, TcpSocket, TcpStream};
use tokio::sync::Semaphore;
use tokio::task::{JoinHandle, JoinSet};
#[cfg(target_os = "linux")]
#[path = "external_tunnel/linux.rs"]
mod platform;
#[cfg(target_os = "macos")]
#[path = "external_tunnel/macos.rs"]
mod platform;
#[cfg(windows)]
#[path = "external_tunnel/windows.rs"]
mod platform;
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
mod platform {
use super::*;
pub(super) async fn owns_socket(_: &Arc<Helper>, _: SocketAddr, _: Option<SocketAddr>) -> io::Result<bool> {
Err(io::Error::new(io::ErrorKind::Unsupported, "socket ownership cannot be verified on this OS"))
}
}
const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
const CONNECTION_TIMEOUT: Duration = Duration::from_secs(3);
const POLL_INTERVAL: Duration = Duration::from_millis(100);
const MAX_CONNECTIONS: usize = 128;
static VERIFICATION_SLOTS: Semaphore = Semaphore::const_new(8);
static HELPERS: Mutex<ActiveHelpers> = Mutex::new(ActiveHelpers { stopping: false, children: Vec::new() });
struct ActiveHelpers {
stopping: bool,
children: Vec<Weak<Helper>>,
}
/// Stop the IDE's external TCP tunnel processes before desktop exit or restart.
pub fn stop_external_tunnels_on_exit() {
let children = {
let mut active = HELPERS.lock();
active.stopping = true;
std::mem::take(&mut active.children)
};
for helper in children.into_iter().filter_map(|child| child.upgrade()) {
helper.stop();
}
}
pub(super) struct ExternalTunnel {
port: u16,
// Keep the address reserved even after the helper exits, until the last route reference drops.
_listener: Arc<TcpListener>,
helper: Weak<Helper>,
task: JoinHandle<()>,
}
impl ExternalTunnel {
pub(super) fn validate(config: &DbExternalTunnel, target: (&str, u16)) -> IdeResult<()> {
helper_target(config, target).map(|_| ())
}
pub(super) async fn open(config: &DbExternalTunnel, target: (&str, u16)) -> IdeResult<Self> {
if !cfg!(any(target_os = "linux", target_os = "macos", windows)) {
return Err(IdeError::unavailable("External TCP tunnel socket ownership cannot be verified on this OS"));
}
let listener = Arc::new(loopback_socket()?.listen(128)?);
let port = listener.local_addr()?.port();
let reservation = loopback_socket()?;
let endpoint = reservation.local_addr()?;
let arguments = helper_arguments(config, target, endpoint.port())?;
drop(reservation);
let helper = launch_helper(Path::new(&config.executable), &arguments)?;
let ready = tokio::time::timeout(STARTUP_TIMEOUT, async {
loop {
if !helper.is_alive() {
return Err(IdeError::new(
ErrorKind::Io,
"The external TCP tunnel helper exited before opening its loopback listener. \
Check the helper command in a terminal.",
));
}
if verify_socket(&helper, endpoint, None).await.map_err(|error| {
IdeError::new(ErrorKind::Io, format!("Could not verify the external TCP tunnel listener: {error}"))
})? {
return Ok(());
}
tokio::time::sleep(POLL_INTERVAL).await;
}
})
.await;
ready.map_err(|_| {
IdeError::new(
ErrorKind::Io,
format!(
"The external TCP tunnel helper did not open an owned listener at {endpoint} before the startup timeout. \
Check that the command binds to 127.0.0.1 and uses {{localPort}}."
),
)
})??;
let watched_helper = Arc::downgrade(&helper);
let task = tokio::spawn(relay(Arc::clone(&listener), endpoint, helper));
Ok(Self { port, _listener: listener, helper: watched_helper, task })
}
pub(super) fn port(&self) -> u16 {
self.port
}
pub(super) fn is_closed(&self) -> bool {
self.task.is_finished() || self.helper.upgrade().is_none_or(|helper| !helper.is_alive())
}
}
impl Drop for ExternalTunnel {
fn drop(&mut self) {
self.task.abort();
}
}
fn loopback_socket() -> io::Result<TcpSocket> {
let socket = TcpSocket::new_v4()?;
#[cfg(windows)]
platform::make_exclusive(&socket)?;
socket.bind(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0).into())?;
Ok(socket)
}
fn helper_target<'a>(config: &DbExternalTunnel, (host, port): (&'a str, u16)) -> IdeResult<(&'a str, u16)> {
let executable = Path::new(&config.executable);
if !executable.is_absolute() || executable.file_name().is_none() || config.executable.contains('\0') {
return Err(IdeError::invalid("Choose an absolute path to the external TCP tunnel executable"));
}
#[cfg(windows)]
if !executable.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("exe")) {
return Err(IdeError::invalid("Choose an .exe file for the external TCP tunnel"));
}
let host = host.trim();
let host = host
.strip_prefix('[')
.and_then(|host| host.strip_suffix(']'))
.filter(|host| host.parse::<std::net::Ipv6Addr>().is_ok())
.unwrap_or(host);
let dns = host.strip_suffix('.').unwrap_or(host);
if host.parse::<IpAddr>().is_err()
&& (dns.len() > 253
|| !dns.split('.').all(|label| {
let bytes = label.as_bytes();
bytes.len() <= 63
&& bytes.first().is_some_and(u8::is_ascii_alphanumeric)
&& bytes.last().is_some_and(u8::is_ascii_alphanumeric)
&& bytes.iter().all(|byte| byte.is_ascii_alphanumeric() || *byte == b'-')
}))
{
return Err(IdeError::invalid("Enter a DNS name or IP address for the external TCP tunnel"));
}
if port == 0 {
return Err(IdeError::invalid("Enter a valid destination port for the external TCP tunnel"));
}
if !config.arguments.iter().any(|arg| arg.contains("{localPort}")) {
return Err(IdeError::invalid("Include {localPort} in the external TCP tunnel arguments"));
}
if config.arguments.iter().any(|arg| arg.contains('\0')) {
return Err(IdeError::invalid("External TCP tunnel arguments cannot contain NUL characters"));
}
Ok((host, port))
}
fn helper_arguments(config: &DbExternalTunnel, target: (&str, u16), local_port: u16) -> IdeResult<Vec<String>> {
let (host, port) = helper_target(config, target)?;
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
let (local_port, port) = (local_port.to_string(), port.to_string());
let placeholders =
[("{host}:{port}", target.as_str()), ("{localPort}", &local_port), ("{host}", host), ("{port}", &port)];
Ok(config
.arguments
.iter()
.map(|arg| {
let mut remaining = arg.as_str();
let mut expanded = String::with_capacity(arg.len());
while let Some(start) = remaining.find('{') {
expanded.push_str(&remaining[..start]);
remaining = &remaining[start..];
if let Some((value, tail)) = placeholders
.into_iter()
.find_map(|(key, value)| remaining.strip_prefix(key).map(|tail| (value, tail)))
{
expanded.push_str(value);
remaining = tail;
} else {
expanded.push('{');
remaining = &remaining[1..];
}
}
expanded.push_str(remaining);
expanded
})
.collect())
}
fn launch_helper(executable: &Path, arguments: &[String]) -> IdeResult<Arc<Helper>> {
let mut active = HELPERS.lock();
if active.stopping {
return Err(IdeError::cancelled());
}
let helper = Arc::new(Helper::spawn(executable, arguments).map_err(|error| {
IdeError::new(ErrorKind::Io, format!("Could not start the external TCP tunnel helper: {error}"))
})?);
active.children.retain(|child| child.strong_count() > 0);
active.children.push(Arc::downgrade(&helper));
Ok(helper)
}
struct Helper {
child: Option<Child>,
#[cfg(windows)]
job: process::Job,
}
impl Helper {
fn spawn(executable: &Path, arguments: &[String]) -> io::Result<Self> {
let mut command = Command::new(executable);
command
.args(arguments)
.current_dir(executable.parent().expect("validated absolute executable path"))
.env_clear()
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
// Keep user config discovery available without inheriting database or project variables.
for key in [
"PATH",
"HOME",
"XDG_CONFIG_HOME",
"XDG_CACHE_HOME",
"XDG_DATA_HOME",
"XDG_RUNTIME_DIR",
"USERPROFILE",
"APPDATA",
"LOCALAPPDATA",
"SYSTEMROOT",
"WINDIR",
"TMPDIR",
"TEMP",
"TMP",
"SSH_AUTH_SOCK",
"NO_PROXY",
"no_proxy",
] {
if let Some(value) = process::host_var_os(key) {
command.env(key, value);
}
}
for key in ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"] {
if let Some(value) = process::host_var_os(key)
&& value.to_str().is_some_and(credential_free_proxy)
{
command.env(key, value);
}
}
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// Membership of this group is an authorization check. A separate session limits
// membership to this child and its descendants; the leader also owns the group.
// SAFETY: setsid is async-signal-safe and does not access Rust state after fork.
unsafe {
command.pre_exec(|| if libc::setsid() == -1 { Err(io::Error::last_os_error()) } else { Ok(()) });
}
}
#[cfg(windows)]
{
platform::spawn_suspended(command)
}
#[cfg(not(windows))]
{
Ok(Self { child: Some(command.spawn()?) })
}
}
fn child(&self) -> &Child {
self.child.as_ref().expect("the live helper owns its child handle")
}
#[cfg(unix)]
fn pid(&self) -> u32 {
self.child().id()
}
fn is_alive(&self) -> bool {
#[cfg(unix)]
{
loop {
let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
// Keep the group leader unreaped so its id cannot be reused before group cleanup.
// SAFETY: valid output buffer and the id of the child owned by `self`.
let result = unsafe {
libc::waitid(
libc::P_PID,
self.pid(),
info.as_mut_ptr(),
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
if result == 0 {
// SAFETY: the buffer was zeroed and waitid returned successfully.
return unsafe { info.assume_init().si_pid() == 0 };
}
if io::Error::last_os_error().kind() != io::ErrorKind::Interrupted {
return false;
}
}
}
#[cfg(windows)]
{
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Foundation::WAIT_TIMEOUT;
use windows_sys::Win32::System::Threading::WaitForSingleObject;
// SAFETY: the owned child handle stays open through this non-blocking check.
unsafe { WaitForSingleObject(self.child().as_raw_handle(), 0) == WAIT_TIMEOUT }
}
#[cfg(not(any(unix, windows)))]
{
false
}
}
fn stop(&self) {
#[cfg(windows)]
let _ = self.job.terminate();
#[cfg(unix)]
process::kill_tree_of(self.pid());
}
}
fn credential_free_proxy(value: &str) -> bool {
let url = if value.contains("://") {
reqwest::Url::parse(value)
} else {
reqwest::Url::parse(&format!("http://{value}"))
};
url.is_ok_and(|url| {
matches!(url.scheme(), "http" | "https" | "socks4" | "socks4a" | "socks5" | "socks5h")
&& url.host().is_some()
&& url.username().is_empty()
&& url.password().is_none()
&& matches!(url.path(), "" | "/")
&& url.query().is_none()
&& url.fragment().is_none()
})
}
impl Drop for Helper {
fn drop(&mut self) {
self.stop();
#[cfg(unix)]
if let Some(mut child) = self.child.take() {
// A helper blocked in the kernel must not hold up the async caller during cleanup.
if !matches!(child.try_wait(), Ok(Some(_))) {
let _ = std::thread::Builder::new().spawn(move || child.wait());
}
}
}
}
async fn relay(listener: Arc<TcpListener>, endpoint: SocketAddr, helper: Arc<Helper>) {
let mut connections = JoinSet::new();
let mut liveness = tokio::time::interval(Duration::from_secs(1));
liveness.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
_ = liveness.tick() => {
if !helper.is_alive() { break; }
}
accepted = listener.accept(), if connections.len() < MAX_CONNECTIONS => {
let Ok((mut client, _)) = accepted else {
// Transient errors such as descriptor exhaustion affect new sockets only.
tokio::time::sleep(POLL_INTERVAL).await;
continue;
};
let helper = Arc::clone(&helper);
connections.spawn(async move {
if let Ok(Ok(mut upstream)) = tokio::time::timeout(CONNECTION_TIMEOUT, connect_verified(&helper, endpoint)).await {
let _ = tokio::io::copy_bidirectional(&mut client, &mut upstream).await;
true
} else {
false
}
});
}
finished = connections.join_next(), if !connections.is_empty() => {
if matches!(finished, Some(Ok(false)))
// A slow ownership probe must not interrupt already verified connections.
&& matches!(tokio::time::timeout(CONNECTION_TIMEOUT, verify_socket(&helper, endpoint, None)).await, Ok(Ok(false)))
{
break;
}
}
}
}
}
async fn connect_verified(helper: &Arc<Helper>, endpoint: SocketAddr) -> io::Result<TcpStream> {
let upstream = TcpStream::connect(endpoint).await?;
let peer = upstream.local_addr()?;
// TCP connect can complete before the helper accepts. Check the server's half of this
// exact connection, keeping all client bytes in the IDE until that socket has an owner.
loop {
if !helper.is_alive() {
return Err(io::Error::new(io::ErrorKind::BrokenPipe, "external TCP tunnel helper exited"));
}
if verify_socket(helper, endpoint, Some(peer)).await? && helper.is_alive() {
return Ok(upstream);
}
tokio::time::sleep(POLL_INTERVAL).await;
}
}
async fn verify_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let _slot = VERIFICATION_SLOTS.acquire().await.map_err(io::Error::other)?;
platform::owns_socket(helper, local, peer).await
}
#[cfg(all(test, any(target_os = "linux", target_os = "macos", windows)))]
mod tests;
@@ -0,0 +1,92 @@
use super::{Helper, io};
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Read};
use std::net::{SocketAddr, SocketAddrV4};
use std::sync::Arc;
pub(super) async fn owns_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let helper = Arc::clone(helper);
tokio::task::spawn_blocking(move || {
let (SocketAddr::V4(local), peer) = (local, peer) else { return Ok(false) };
let peer = match peer {
Some(SocketAddr::V4(peer)) => Some(peer),
None => None,
_ => return Ok(false),
};
let state = if peer.is_some() { "01" } else { "0A" };
for (table, ipv6) in [("/proc/net/tcp", false), ("/proc/net/tcp6", true)] {
let file = match File::open(table) {
Ok(file) => file,
Err(error) if ipv6 && error.kind() == io::ErrorKind::NotFound => continue,
Err(error) => return Err(error),
};
let local = address(local, ipv6);
let peer = peer.map(|peer| address(peer, ipv6));
// Kernel rows are small, but bound the time spent scanning a busy host's table.
for line in BufReader::new(file.take(8 * 1024 * 1024)).lines().skip(1) {
let line = line?;
let mut fields = line.split_ascii_whitespace().skip(1);
let (Some(left), Some(right), Some(current_state)) = (fields.next(), fields.next(), fields.next())
else {
continue;
};
if left != local || current_state != state || peer.as_deref().is_some_and(|peer| peer != right) {
continue;
}
let Some(inode) = fields.nth(5).and_then(|inode| inode.parse::<u64>().ok()).filter(|inode| *inode != 0)
else {
continue;
};
if group_holds_socket(helper.pid(), inode)? {
return Ok(true);
}
}
}
Ok(false)
})
.await
.map_err(io::Error::other)?
}
fn address(address: SocketAddrV4, ipv6: bool) -> String {
let ip = address.ip();
let port = address.port();
if !ipv6 {
return format!("{:08X}:{port:04X}", u32::from_ne_bytes(ip.octets()));
}
let octets = ip.to_ipv6_mapped().octets();
let [a, b, c, d] = octets.as_chunks::<4>().0 else { unreachable!() };
format!(
"{:08X}{:08X}{:08X}{:08X}:{port:04X}",
u32::from_ne_bytes(*a),
u32::from_ne_bytes(*b),
u32::from_ne_bytes(*c),
u32::from_ne_bytes(*d)
)
}
fn group_holds_socket(group: u32, inode: u64) -> io::Result<bool> {
let group = i32::try_from(group).map_err(io::Error::other)?;
let target = format!("socket:[{inode}]");
for process in fs::read_dir("/proc")? {
let Ok(process) = process else { continue };
let name = process.file_name();
let Some(pid) = name.to_str().and_then(|name| name.parse::<libc::pid_t>().ok()).filter(|pid| *pid > 0) else {
continue;
};
// SAFETY: this only queries the process group of the enumerated pid.
if unsafe { libc::getpgid(pid) } != group {
continue;
}
let Ok(descriptors) = fs::read_dir(process.path().join("fd")) else { continue };
for descriptor in descriptors.flatten() {
if fs::read_link(descriptor.path()).is_ok_and(|link| link.as_os_str() == target.as_str()) {
// SAFETY: check membership again after examining the fd directory.
if unsafe { libc::getpgid(pid) } == group {
return Ok(true);
}
}
}
}
Ok(false)
}
Loaded 100 of 1817 files, more files were not shown because too many files have changed in this diff. Show more