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
l0ng-ai a6a05caa2e fix(editor): keep multiline find and replace compact (#5362)
Limit the inline Find and Replace fields to three visible lines each. Longer text scrolls inside the fields, leaving more of the matched code on screen.
2026-11-23 14:56:44 +08:00
Deng Liuanddengliu 4690463c53 feat(services): show Compose service resource usage and named volumes (#5330)
The Compose project dashboard listed only container chips, so resource usage meant opening each container, and the project's named volumes were only findable in the global Volumes group among anonymous hashes. It now shows a per-service table (status, CPU, memory, network and block I/O, PIDs) sampled with bounded concurrency and refreshed every 3 s without overlapping requests while the dashboard is visible (paused when the tool window or app is hidden; the container dashboard's stats use the same live sampling instead of a manual Refresh), plus a Volumes section with the project's named volumes that links to each Volume Overview and back.

Co-authored-by: dengliu <[email protected]>
2026-11-23 14:49:42 +08:00
Deng Liuanddengliu 8200ce8b5e feat(services): jump from Compose containers to their Compose file (#5348)
Docker Compose containers carry their Compose files and service name but had no way back to the source. Jump to Source (F4 / Cmd+Down, context menu, docker.jumpToSource) on a Compose container opens the Compose file at its service declaration and on a Compose project at the services section; the container dashboard's Command row has a button that lands on the service's command value (else entrypoint, across inline values, block scalars and sequences, later override files taking precedence), and the Compose project dashboard lists its Compose files as links. Missing or unreadable files show a notification.

Co-authored-by: dengliu <[email protected]>
2026-11-23 14:47:10 +08:00
Deng Liuanddengliu b524f738e5 fix(services): keep long Docker commands bounded and collapsible in dashboards (#5337)
Property rows in the Docker dashboards aligned items on their baseline; an inline-block value's baseline is its last line, so a wrapped multi-line command painted its earlier lines upward over the rows above it. Rows now align at start with a minmax(0, 1fr) value column, and container/image commands render as a single-line preview (newline markers, copy button, no auto-ellipsis tooltip via data-no-tooltip) that expands into a bounded scrollable block with Entrypoint and Command arguments shown separately.

Co-authored-by: dengliu <[email protected]>
2026-11-23 14:43:37 +08:00
l0ng-ai 1f871dc1c2 fix(search): keep multiline file search fields compact (#5358)
Find in Files and Replace in Files show up to three lines in each query field. Longer text scrolls within its field. Closer spacing between the search and replacement fields gives matches and the source preview more room in short windows.
2026-11-23 14:39:03 +08:00
langxpandkradme ceb3cef1af feat(vcs): scope Commit… to the selected project directory (#5304)
Git > Commit… from the Project view ignored the selection. It now passes the selected paths, and the commit interface (modal or not) opens with only the changes at or below them checked: tracked and unversioned files included, conflicts left out, the rest of the working tree still listed.

Co-authored-by: kradme <[email protected]>
2026-11-23 14:27:36 +08:00
Deng Liuanddengliu 735a0157c1 fix(editor): cap inline highlight backgrounds and frames at line height (#5285)
When the editor font's glyph box is taller than the line height (e.g. 18px font at 18px line height), Find matches, occurrence highlights, in-place rename spans, matched brackets, search results and plugin range marks painted the full inline box into the rows above and below. They now share a 1lh-capped background (and a 1px-framed variant), as selection marks already were, keeping background-color / outline fallbacks for Safari before 16.4.

Co-authored-by: dengliu <[email protected]>
2026-11-23 14:25:39 +08:00
Mr0Bread 82f26202ed perf(search): keep Find in Files cost linear while results stream in (#5239)
Every streamed file triggered a Find tool window update that rebuilt the whole result tree and its lookup tables, so a search matching thousands of files grew quadratically and froze the IDE. The session now publishes streamed results at most every 50 ms (the first file still at once), and the tool window builds its tree incrementally: only new files get nodes, merged into the sorted result; a list that is not an extension of the previous one is rebuilt.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 14:18:35 +08:00
l0ng-ai a90a9b20e3 fix(debugger): keep Memory instance fields readable (#5342)
The Memory Instances tree gives field values room beside long names. The panel title uses the workbench font. Field names and value previews that run out of space use ellipses and show the full text on hover, and the row's Show Referrers button stays in reach.
2026-11-23 14:17:51 +08:00
Deng Liuanddengliu aad701ba16 fix(editor): clear selection highlights when hiding kept-alive tabs (#5273)
WebKit skips clearing the selection highlight inside a subtree whose rendering is skipped, so a kept-alive tab (an Agent conversation) hidden with content-visibility kept a stale highlight after switching back. Hiding a kept tab now clears a selection inside it while keeping it rendered (invisibly) for one frame via a shared useSelectionVisibility hook, and the agent stream keeps data-selection independent of visibility so off-screen rows clear too.

Co-authored-by: dengliu <[email protected]>
2026-11-23 14:16:18 +08:00
Mr0Bread 46d4036038 perf(editor): keep typing and Enter fast in large TypeScript files (#5251)
Typing and Enter in a large TypeScript file got slower with its size. @lezer/common 1.5.6 gives each repeat group the look-ahead in effect where it ends, so groups above an edit stay reusable and an edit no longer re-parses the file up to the caret; decoratorRanges scans only subtrees not already known to hold no decorator; and Enter's one-line string check parses and highlights only the caret's line instead of the whole document.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 14:16:13 +08:00
LU XIANGRUIandwildcatDownstairs 19859b4ae2 fix(java): refresh semantic highlighting after a project import (#5319)
jdtls returns no semantic tokens for files outside any Java project (a failed Maven import) and sends no workspace/semanticTokens/refresh once a later import takes them in, so open editors stayed uncoloured until edited or reopened. On ProjectStatus the IDE now asks open editors to fetch semantic tokens again, after generated Maven sources are attached. Refs #5301.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-23 14:13:06 +08:00
Qingandqtvbwfn f3f05f8b15 fix(vue): keep the vtsls route on TypeScript 7 for Vue projects (#5368)
With a TypeScript 7 workspace the native server replaced vtsls before the Vue branch could inject @vue/typescript-plugin, so .vue files lost TypeScript support (Go to Declaration on the 'vue' import failed). The native swap now skips vtsls in a Vue project whose Vue language server is installed; typescript-language-server still takes the native route. Closes #4876.

Co-authored-by: qtvbwfn <[email protected]>
2026-11-23 14:13:02 +08:00
LU XIANGRUIandwildcatDownstairs b0417c83f4 fix(tools): find the Ruff the IDE installed when formatting (#5372)
The formatter lookup checked the project's node_modules and PATH but never a tool's managed virtualenv, so a Ruff installed from the tools list was reported as not installed by Reformat with Ruff. It now looks there before PATH, which also covers Black and Ruff-based Optimize Imports. Closes #5371.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-23 14:12:58 +08:00
l0ng-ai 4a5d90a91e fix(coverage): make report columns adjustable (#5331)
Make the Coverage table's Line and Branch columns adjustable. The divider next to Element gives space to the file tree, and the divider between the metrics redistributes space between them. Each column shows the full covered/total count when it has room. Compact columns keep the percentage visible and show the full count on hover.

Drag a divider or focus it and use the arrow keys. Double-click a divider to restore the default widths. The table remembers widths across reloads and fits them to smaller docks.
2026-11-23 13:52:09 +08:00
Mr0Bread 1e61b3b270 perf(search): search large files in context mode and non-UTF-8 encodings without reading them whole (#5254)
Project search read a non-UTF-8 file whole and decoded it as one String, and in the comments/strings modes read every file whole to find its comments, even ones far above what the parser takes. Non-UTF-8 files now stream through an incremental decoder (ide_vfs::decode_stream: a detection pass with the same result as decode_text, then 64 KiB chunks), and files too large for the parser are not read for comments at all. Results, binary detection, the match limit and cancellation are unchanged.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:47:56 +08:00
Mr0Bread 0809eb417c perf(vcs): keep Git Log graph layout cost per page linear in the loaded commits (#5243)
computeGraph kept its lanes in a dense array indexed by layout number, which grows with the log, and scanned every slot for each row, making each further page of Git Log quadratic in the loaded commits. Lanes are now kept sparsely so a row costs its live lanes, with identical output (checked against a reference implementation), and the graph is laid out again only when an option that shapes it changes.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:45:28 +08:00
Mr0Bread 86531ee1ba perf(run): bound the output queue of run and build processes (#5256)
The run and build runners passed every pipe chunk or line to their consumer through an unbounded channel, so a process printing faster than the console drained piled its whole output up in memory (hundreds of MB for a few million lines). Both queues are now bounded (128 x 16 KiB chunks for runs, 64 lines for builds): the reader waits, the pipe fills and the child blocks on its write, as on a terminal. Nothing is dropped, and a reader blocked on a full queue ends once the consumer is gone.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:45:25 +08:00
Mr0Bread 54f0373acf fix(project-tree): find removed directories without checking every loaded dir (#5235)
planRefresh and dropListings compared every loaded folder with every removed path or ignore-rule root. They now look up each folder and its ancestors in a set (insideAnyOf), with the same semantics as isSameOrInside.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:43:24 +08:00
Mr0Bread 137b1cc384 perf(code-insight): apply diagnostics events to the problems store without copying every file's map (#5234)
Each diagnostics event copied the whole problems map, so a storm of per-file events cost files^2 copies. The store now updates its data in place and publishes a new facade per change, so subscribers still see a new identity exactly when the content changed; the MCP problems report keeps its own copy to diff against, and profiledProblems builds its map without per-file copies.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:43:19 +08:00
Mr0Bread 6c9d432504 perf(host): run route scan, agent reads and plugin keychain calls off the main thread (#5233)
spring_route_sources (walks the project tree), agent_providers (reads the registry and custom agent files), agent_entries (serialises the whole conversation), plugin_secrets and plugin_set_secret (OS keychain) were sync commands that Tauri runs on the main thread. They are now async, all but agent_entries on the blocking pool, and blocking_commands.rs keeps them there.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:43:16 +08:00
Mr0Bread 2395c9544b fix(project-tree): apply one fs change with a single model build (#5241)
Each folder reloaded for an fs event copied the listings map and notified the store, so the mounted view rebuilt the whole tree model once per folder, and the reads were unbounded. One event now reads its folders at most eight at a time and applies all listings in one store update; a folder dropped while the batch was reading stays dropped.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:36:18 +08:00
Mr0Bread 4b55039e6e fix(editor): refresh usage counts only when a source file changed (#5242)
The usages code lens re-asked the language server for every visible declaration on every fsChanged event, even ones carrying only images or logs. It now recounts only when a changed path can be a file a language server analyses (by the language registry and Settings > File Types), and still recounts when in doubt: unloaded languages or paths without an extension.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:36:12 +08:00
Mr0Bread 7264194b0f fix(history): find removed files' snapshots without scanning every removed path (#5238)
LocalHistory::note_removed compared every snapshot entry with every removed path, stalling the watcher thread (and saves waiting on the history lock) for seconds on large deletions. Entries are now matched by looking up their path and its ancestors in a set of the removed paths.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:36:06 +08:00
Mr0Bread 9ebdf0d68f fix(index): remove a deleted subtree in one pass (#5232)
A removed folder arrives with every path below it in one watcher batch; each child that was already gone was looked up as a folder and triggered another full scan of the indexed paths under the write lock, so the cost was removed paths x indexed files. Removed paths that are not indexed files are now collected and everything below them is removed in a single scan.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:36:02 +08:00
LU XIANGRUIandwildcatDownstairs 0843dd8363 fix(agents): don't reference the same file twice with Send to Agent (#5349)
Send to Agent appended an @ mention for every target even when the message already held the same file and lines, leaving duplicate chips and file entries. Mentions already in the message are skipped (a different line range is still its own reference), the draft keeps one file entry per path, and the composer is still shown when nothing new was added. Part of #5296.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-23 13:34:40 +08:00
Deng Liuanddengliu 9935bfb7c6 fix(agents): coalesce change reads per task (#5346)
The 500 ms notification timer did not cover a change-list read already running, so slow reads overlapped and an older snapshot could land last. Refreshes for one task now share one active read and one trailing read; results from an old project, a removed task or an evicted cache are dropped, and other tasks refresh independently. Refs #5335.

Co-authored-by: dengliu <[email protected]>
2026-11-23 13:34:26 +08:00
Deng Liuanddengliu db08dbc4f5 fix(agents): refresh stale queue rows without error toasts (#5334)
A turn could take the next queued message before its row disappeared, so Send now / Edit / Remove on it failed with "already sent" once per click. The dequeue is now published as soon as the turn takes the message; a stale queue action returns OutOfSync after re-publishing the current queue, which the row ignores, and only the pending row is disabled. A missing task or other failure still shows an error.

Co-authored-by: dengliu <[email protected]>
2026-11-23 13:34:22 +08:00
Deng Liuanddengliu cfab86588b perf(agents): skip change diffs for unattributed sibling checkouts (#5344)
A flat change-list request with known attribution now diffs only the nested checkouts that own the task's paths (deleted files included), resolves the nested layout once, keeps the final attribution filter, and falls back to the full scan when attribution is unknown. A task with no touched paths reads nothing. Refs #5335.

Co-authored-by: dengliu <[email protected]>
2026-11-23 13:34:18 +08:00
Deng Liuanddengliu ba300ecbf9 fix(agents): bound concurrent change-list reads across tasks (#5343)
Flat, grouped and last-turn change-list reads now share four slots per agent manager, acquired before taking a blocking worker and held until the Git work ends even if the caller goes away. Mutations and other VCS work are not limited. Refs #5335.

Co-authored-by: dengliu <[email protected]>
2026-11-23 13:32:49 +08:00
Muuandmuutot 1e79ccaf41 fix(project): run workspace-member settings work off the IPC thread (#5360)
project_workspace_members and project_workspace_member_set ran synchronously on the main thread; each attached root's for_project() re-parses both settings layers and validates the merge against Settings, which overflowed the main thread's stack from a WebView2 callback in a debug build on Windows (STATUS_STACK_OVERFLOW on project open). Both now use desktop_body = spawn with thin desktop bodies, and blocking_commands.rs keeps them off the main thread.

Co-authored-by: muutot <[email protected]>
2026-11-23 13:31:23 +08:00
LU XIANGRUIandwildcatDownstairs 6815cb5f89 fix(debugger): suppress synthetic continued events superseded by a newer stop (#5226)
resume, step and step_in_target emitted a synthetic Continued after the DAP reply even when the adapter's next stopped event had already landed (php-debug/Xdebug on fast steps), leaving the Debug window showing running while paused. The reply now ends prior stops and emits Continued under the suspension lock only when a prior stop was ended and no newer stop superseded it; stopped and continued adapter events emit under the same lock so a synthetic Continued can never follow a newer Stopped.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-23 13:28:19 +08:00
l0ng-ai a79d551bd3 fix(vcs): anchor the Git Log path editor (#5317)
- Open the resizable text editor from its Git Log filter. It follows the visible Paths or More Filters control as the window narrows.
- Give paths a code-font editing area with soft wrapping. Keep the one-path-per-line hint and apply controls beneath it.
- Enter inserts a newline. The platform's primary modifier with Enter applies the filter, and Escape or clicking outside discards the draft.
2026-11-23 13:27:58 +08:00
langxpandkradme 0284b7091b fix(debugger): keep session tab order when restarting (#5318)
Debug tabs were ordered by the backend's increasing session id, so Rerun or a replaced finished tab jumped to the end. Each tab now has a stable local slot that a rerun, a prepared start, a pinned tab's rerun and a browser page inherit; a new session reuses a stopped tab by configuration id, then name, then the selected one. Child sessions are ordered by their root's slot so they stay next to their parent.

Co-authored-by: kradme <[email protected]>
2026-11-23 13:27:13 +08:00
Charlie.Weiandcharli117 93143ce872 test(ide-host): give the Maven import-roots poll a longer deadline (#5366)
The import_roots helper in maven_external polled the background jdtls Maven re-import for 5s, which a loaded CI runner can exceed. Raise the deadline to 15s.

Co-authored-by: charli117 <[email protected]>
2026-11-23 13:25:05 +08:00
Charlie.Weiandcharli117 6cbb27ed82 test(ide-lsp): wait for the retiring transport to close before asserting (#5365)
java_sharing_cancels_a_retiring_initialize_before_starting_its_replacement checked old.is_closed() once right after reconfigure() returned, racing the asynchronous close on a loaded runner. Wait for the close before releasing the initialize response; the ordering guarantee still holds because the gate stays shut until then.

Co-authored-by: charli117 <[email protected]>
2026-11-23 13:25:01 +08:00
Charlie.Weiandcharli117 74cf06505f test(ide-docker): wait for the log flush instead of a fixed sleep (#5363)
log_lines_arrive_in_order_as_few_batches slept 80ms and assumed the 30ms flusher had emitted the 1000-line burst by then; on a loaded runner the flusher is starved and the trailing line folds into the burst. Wait until every line of the burst has been flushed before sending the trailing one.

Co-authored-by: charli117 <[email protected]>
2026-11-23 13:22:45 +08:00
l0ng-ai d6d73e1072 test(search): measure the scope pattern field after the dialog settles (#5364)
The Scopes dialog relays out over a few frames after the viewport shrinks; wait until the pattern field's position is stable before measuring it.
2026-11-23 13:09:37 +08:00
l0ng-ai bbea793adf fix(debugger): align the Python table viewer (#5309)
- Keep the shape and paging controls above the table and put the full-width slice expression below it, above Close. The grid scrolls between the controls.
- Open at 700 × 500 when there is room. Give short tables the available width, use workbench typography and center the row and column headers.
- Update the title when a slice is submitted and show expression errors below the field.
2026-11-23 13:01:59 +08:00
l0ng-ai f1c556e2ec fix(editor): align the Find Usages source preview (#5305)
- Start with equal space for the results tree and source preview. Each orientation restores its saved split and starts at 50/50 when it has no saved split.
- Follow the editor's line height and size the preview gutter for the document's longest line number. Keep the selected line visible when the panel height or line metrics change.
2026-11-23 12:42:18 +08:00
l0ng-ai 2d99a79e69 fix(settings): align the Editor Tabs form (#5300)
- Align the tab placement and close button selectors in the Appearance form.
- Put the row and overflow choices on separate lines with the overflow options nested under the single-row choice. The two groups retain their own selections and support independent arrow-key navigation.
- Stack each set of closing policy choices below its heading, so the order stays consistent as the window narrows.
2026-11-23 12:24:08 +08:00
l0ng-ai ca778e2382 fix(search): improve structural template layout (#5298)
- Put the language picker in the Search template header and keep each label next to its template.
- Give both templates 150 px of editing space in a standard window. Tighten the editors on shorter screens and keep the dialog footer accessible.
- Use the configured editor font, size, and line height in both templates.
2026-11-23 12:08:57 +08:00
Deng Liuandl0ng-ai 414353a5bd ci: add Docker Compose setup for persistent self-hosted Actions runners (#5307)
* ci: add Docker Compose setup for persistent self-hosted Actions runners

* ci: wire Linux Rust CI to hardened self-hosted runners under scripts/

* ci: gate self-hosted runners behind a variable and use the jammy image

- Pin the Ubuntu 22.04 runner image; the untagged-distro image is 20.04 and
  cannot install libwebkit2gtk-4.1-dev.
- Route the Linux Rust job to self-hosted runners only while the
  SELFHOSTED_RUNNERS repository variable is 'true', so CI keeps working when
  no runner is online.
- On self-hosted runners, enable incremental compilation and clear the
  persistent target dir once it exceeds 40 GB.
- README: document the variable, passwordless sudo inside the container and
  the target dir shared between main and same-repo branches.

---------

Co-authored-by: l0ng-ai <[email protected]>
2026-11-23 11:54:56 +08:00
l0ng-ai 3080dc6100 fix(editor): balance the Edit Macros panes (#5293)
Edit Macros starts with equal widths for the macro list and recorded steps. The keyboard-resizable divider remembers its position. Rename and Delete sit in the toolbar above the macro list, and the dialog opens with focus on the list. Recorded steps use the UI font and wrap within their pane.
2026-11-23 11:45:46 +08:00
l0ng-ai 1bb9f8d07c fix(analysis): align controls with scope choices (#5292)
The shared analysis scope picker aligns directory and custom scope controls with their radio choices. At narrow widths each control sits directly below its choice. Controls stay visible when inactive, and switching the radio selection keeps both values.
2026-11-23 11:24:06 +08:00
l0ng-ai a539baec37 test(settings): measure Git Log checkboxes after the dialog settles (#5311)
The Git Log settings layout test read two checkbox positions one after the other while the Settings dialog was still opening, so it failed depending on timing. It now polls both positions together until they match.
2026-11-23 11:16:43 +08:00
l0ng-ai 7dff6e1852 fix(debugger): give Memory class filtering room (#5289)
The Debug Memory toolbar uses the available space for class search and places the Changed only filter in View Options at the right edge. The button shows when the filter is active. The search field shows a clear button when a query is present.
2026-11-23 11:07:14 +08:00
l0ng-ai fc7fa85850 fix(maven): give plugin names priority in the tree (#5288)
Maven plugin rows use the plugin prefix as the primary label and show the coordinates in muted text. The coordinates truncate independently in narrow docks and can be read in full from their tooltip.
2026-11-23 10:49:33 +08:00
l0ng-ai 7e5a2cf051 fix(vcs): group Git Log display settings (#5287)
Settings → Version Control → Log now groups the display and column checkboxes under titled separators. Both groups use the same checkbox alignment, row spacing, and UI font size, so the controls are easier to scan at narrow window widths.
2026-11-23 10:32:53 +08:00
l0ng-ai c4e08a9676 fix(gradle): keep task descriptions in row tooltips (#5286)
Gradle task rows give the available space beside the icon to the task name. The full description appears in the row tooltip, where assistive technology can also read it.
2026-11-23 10:06:57 +08:00
l0ng-ai 2c0b76c9e6 fix(editor): align the line separator menu (#5284)
- Give the line separator picker a standard menu heading. List Windows, Unix and macOS, and classic Mac OS from top to bottom.
- Use the localized platform names and escaped newline sequences in the menu. The status bar still shows the abbreviation and the menu checks the current format.
2026-11-23 09:48:46 +08:00
l0ng-ai 4d1f51c607 fix(editor): integrate usage access filters into the toolbars (#5283)
- Put read and write filters alongside the other actions in Show Usages and in the Find Usages tool window. Both results areas use the space previously occupied by a separate filter row.
- Keep the two buttons together as the popup narrows. The side toolbar can scroll when the tool window is short.
2026-11-23 09:26:05 +08:00
l0ng-ai 2215239ecb fix(editor): put the pin in the editor tab action slot (#5282)
- Put the pin in a pinned editor tab's action slot so the filename has more room. The pin follows the left or right placement and can unpin the tab directly.
- Use the same Unpin action in Hidden Editor Tabs. A modified pinned tab shows its unsaved marker beside the pin.
2026-11-23 09:23:25 +08:00
l0ng-ai 43eeb080be fix(run): expand multiline configuration fields in place (#5267)
Multiline run configuration fields now keep the Expand button inside the field. The larger editor opens next to the field so the configuration stays in view. It can be resized, scrolls long arguments horizontally, and applies edits through OK or Ctrl/⌘+Enter.
2026-11-23 09:16:39 +08:00
l0ng-ai 03a19d4284 fix(search): keep line numbers visible in text results (#5281)
- Give Search Everywhere's Text results a separate column for the line number. Long filenames truncate within the existing metadata width, leaving the same amount of space for the highlighted code snippet.
- Use tabular digits at the trailing edge and show the full relative path on hover.
2026-11-23 09:16:00 +08:00
l0ng-ai 3aeee3fcfc fix(settings): align the navigation tree spacing (#5280)
- Move the top-level disclosure arrows away from the sidebar edge and reduce each nested level from 20 px to 16 px.
- Keep leaf and expandable labels aligned at the same depth. The third-level result has 4 px more room in the 160 px sidebar shown below.
2026-11-23 09:15:52 +08:00
l0ng-ai 471003a8c5 fix(vcs): size annotation details to their content (#5279)
Git annotation details size themselves to the commit text, so short messages cover less of the editor. Long author details and messages wrap within the available width. The revision and its metadata share the tooltip's UI font, and the full revision remains clickable.
2026-11-23 09:15:44 +08:00
l0ng-ai c109773d2a fix(editor): keep completion controls on one row (#5278)
The completion footer keeps its shortcut hint and sorting control on one line. In narrow editor splits the hint shortens first, and hovering reveals its full text. The compact footer takes up less vertical space in the editor.
2026-11-23 09:15:36 +08:00
l0ng-ai ed6b67faed fix(run): keep configuration types reachable in short windows (#5277)
Add New Configuration keeps the title and search field above a scrollable list. The picker keeps its width while filtering with the standard 16 px icons and shows more types when the window has room. After filtering, Enter opens the configuration type highlighted in the list, including types under a group heading.
2026-11-23 09:15:28 +08:00
l0ng-ai ff7bfcaf1d fix(search): keep file context visible in Find previews (#5275)
The source preview in Find in Files and Replace in Files keeps the filename prominent and leaves the end of its containing path visible. The middle of a long directory shortens to fit, and hovering over the caption reveals the full project-relative path.
2026-11-23 09:15:20 +08:00
l0ng-ai 91330a82d0 fix(build): keep diagnostic names and elapsed time readable (#5274)
The Build tree shortens long directory hints first so there is room for the filename and diagnostic counts. The build duration uses smaller, tabular text at the trailing edge. Hovering over a file row reveals its full path.
2026-11-23 09:15:11 +08:00
l0ng-ai ce75c58a34 fix(workbench): give notification balloons room for their content (#5270)
Notification balloons reserve space for Dismiss in the title row. The body and action rows extend underneath it, giving paths and action labels more room to wrap in narrow windows. The cards use the standard UI text size and spacing.
2026-11-23 09:15:01 +08:00
l0ng-ai 03b9070b9b fix(vcs): show file names in staging diff headings (#5268)
The three-way staging diff displays the filename in the index heading. When a version has a different path, its heading shows that filename too. The headings use the standard workbench text size, and hovering over a filename heading reveals its full path.
2026-11-23 09:14:53 +08:00
l0ng-ai f6f610516c fix(vcs): clarify staging groups and row actions (#5266)
The Commit staging tree gives group headings more weight so the staged, unstaged, and unversioned sections are easy to scan. The inline Stage or Unstage action appears on the current selected row and on hover, so a multi-selection shows which row the inline action applies to.
2026-11-23 09:14:44 +08:00
l0ng-ai cf49a91b66 fix(vcs): group branches and tags in commit details (#5265)
Git Log commit details now show branches and tags in separate groups. Reference names use the same size as the surrounding metadata, and each group wraps within the details pane.
2026-11-23 09:14:35 +08:00
l0ng-ai e0a97e32f7 fix(terminal): give scrollback search a compact layout (#5264)
Size the floating terminal find bar to its controls. Keep the match count beside the previous and next buttons, and move the controls below the query in narrow docks so the full first row is available for typing.
2026-11-23 09:14:26 +08:00
l0ng-ai dd0eeeae29 fix(debugger): align compact editor value hints (#5262)
Use the standard bold UI font for compact debugger value hints. Put the variable icon and expand control beside the summary so wrapped values align with their first line. Size the hint to the available editor width, including when a dock reduces the space or the window is resized.
2026-11-23 09:14:18 +08:00
l0ng-ai 4bb22df1fb fix(run): show before-launch tasks as ordered tags (#5261)
Show before-launch tasks as compact tags numbered in execution order. Tags wrap within the configuration form, and each task has a remove button and a menu for moving it up or down. Shell commands stay editable in place.
2026-11-23 09:14:10 +08:00
l0ng-ai aee087597a fix(vcs): show readable commit message history previews (#5258)
Place commit message history just above the editor and use the same font settings as the draft. Show the beginning of the body in each row so messages with the same subject are distinguishable. Keep seven rows visible when space allows and scroll through the rest.
2026-11-23 09:14:02 +08:00
l0ng-ai 993a321dd0 fix(vcs): keep commit check actions visible while reading results (#5257)
Give commit check results their own scroll area. The status icon and retry action stay in place, and the results fit the space above the commit buttons. Use the standard 13 px UI type and a 4 px gap between results.
2026-11-23 09:13:53 +08:00
l0ng-ai 381e66aca5 fix(vcs): keep commit subjects readable in the Amend chooser (#5253)
The Amend chooser sizes to its contents within the window, up to about 520 px. Long subjects get more room and the full text on hover. The latest commit row gives its action label more weight and leaves the subject in secondary text. The list still shows five rows before scrolling.
2026-11-23 09:13:45 +08:00
l0ng-ai d7a05eea21 fix(vcs): align commit author and date fields (#5252)
Commit Options gives the author and date fields a shared label column when there is room. A narrow options pane puts the labels above the controls and moves the clear button below the date when needed. In the 650 px desktop window, the author input grew from 104 px to 157 px, and the date input grew from 133 px to 157 px. The native date control can still clip part of the time display at that width.
2026-11-23 09:13:37 +08:00
l0ng-ai c61ddbff3d fix(vcs): make Git Log commit choices easier to scan (#5250)
The Git Log commit chooser now gives its results the full dialog width and sizes the list to the number of candidates. Previously the list could be clipped inside a fixed-height area. Each row separates the subject from the hash, author and timestamp. The search field keeps keyboard focus while the arrow keys move the selection.
2026-11-23 09:13:30 +08:00
l0ng-ai 0c20d72cbf fix(project): group file rename options below the name field (#5247)
Project tree Rename places the name prompt directly above the input and keeps the two search options together below it. The options share one row when they fit and wrap at the dialog width. This gives the name and any validation message a clear place in the form.
2026-11-23 09:13:22 +08:00
l0ng-ai 021f334c0c fix(run): keep configuration names distinct in gutter menus (#5245)
Run and Debug menus keep the end of a long configuration name visible beside the shortcut. When the label runs out of room, the menu truncates the middle so names with the same prefix remain distinguishable. Hovering still shows the full name.
2026-11-23 09:13:13 +08:00
l0ng-ai c61264cdf9 fix(search): keep recent find and replace values readable (#5244)
The editor Find bar and the Find and Replace in Files dialog now share one history menu. The menu can grow up to 200 px wider than its field, within the window, and the text uses the space previously reserved for icons. The heading stays visible as the list scrolls. Multi-line entries show a line-break marker and restore the original text when selected.
2026-11-23 09:13:05 +08:00
l0ng-ai e4d6f50a0b fix(search): make Replace All details easier to review (#5236)
Replace All puts the affected count above separate, scrollable values for the search text and replacement. Both values stay available in full, and an empty replacement is labeled explicitly. The Replace in Files popup and the Find tool window use the same confirmation.
2026-11-23 09:12:56 +08:00
l0ng-ai 0435e0330e fix(search): keep scope names and patterns readable in the editor dialog (#5231)
The Scopes dialog in Find in Files keeps its list scrollable beside the Name and Pattern fields. At narrow widths the editor moves below the list, giving the pattern more room. Long names show an ellipsis and a tooltip, and the selected scope stays visible when a row is added.
2026-11-23 09:12:48 +08:00
l0ng-ai 13b5f9e575 fix(editor): keep image viewer controls and details readable (#5230)
The image viewer groups the image and zoom controls at the start of a compact toolbar. Its dimensions, file size, and zoom appear at the other end in the standard UI text size. In narrow splits the details wrap onto another row, leaving the SVG Open as Text action readable on one line.
2026-11-23 09:12:39 +08:00
l0ng-ai dde4b28abd fix(editor): keep color picker controls in view (#5228)
The editor color picker uses a shorter color field and a tighter control row. Numeric inputs use the UI text size, recent colors wrap with consistent spacing, and the action buttons stay visible when the popup has to scroll.
2026-11-23 09:12:30 +08:00
l0ng-ai 3817724637 fix(vcs): make files and actions easier to scan in local changes review (#5227)
The local changes review shows the filename first and uses smaller, muted text for its parent folder. This keeps filenames visible when directories are long. The warning and change preservation hint sit together above the file list. Force Checkout sits on the left, with Smart Checkout and cancellation on the right.
2026-11-23 09:12:22 +08:00
l0ng-ai 26b5856ce0 feat(workbench): let users move the More Tool Windows button (#5224)
Right-click **More Tool Windows** (`…`) and choose **Move to Right** or **Move to Left**. The workbench previously placed this button on the left unconditionally. It now starts on the left, remembers your choice across restarts, and opens the list toward the editor from either edge.
2026-11-23 09:12:13 +08:00
l0ng-ai 6aeb733f20 fix(run): make test report export paths easier to edit (#5223)
The test results export dialog puts HTML and XML on separate rows and gives the file name and folder separate fields. The file name is selected on open, so it can be replaced without retyping the directory. Pasting a full path and choosing a destination with Browse still work.
2026-11-23 09:12:05 +08:00
l0ng-ai 29fcec6ab8 fix(debugger): keep gutter breakpoint controls in view (#5221)
The gutter breakpoint popup puts the file and line in a fixed header and keeps the action buttons visible while the fields scroll. The popup gives the condition and hit-count fields more room. Long filenames shorten in the header while the line number stays visible. The same popup layout covers method breakpoints and field watchpoints.
2026-11-23 09:11:56 +08:00
l0ng-ai 5d6c76cdda fix(keymap): make shortcut recording and conflicts easier to read (#5220)
The shortcut recorder puts the action name and its category in the dialog body and uses a full-width first field. The optional second stroke stays beside its checkbox. Conflicting actions use two-line rows that keep the action name, category and binding readable in a narrow window.
2026-11-23 09:11:47 +08:00
l0ng-ai 844c2f3145 test(maven): wait for the background refresh of jdtls import roots (#5272)
external_maven_link_persists_reloads_and_unlink_keeps_files failed on the macOS runner: setting languages.java.maven.linkedProjects refreshes the language server's import roots on a blocking task, and the test read them right after build_model returned. It now waits up to 5 s for them to change.
2026-11-23 05:18:24 +08:00
Charlie.Weiandcharli117 76d67145f5 test(smoke): give the language-smoke closure tests a 20s timeout (#5240)
The two Language smoke workflow tests compute the repo-wide import closure and crate tree. On a CI runner running the whole suite they took longer than vitest's default 5 s and failed the Frontend job on main.

Co-authored-by: charli117 <[email protected]>
2026-11-23 01:13:43 +08:00
Charlie.Weiandcharli117 cf4273eeea chore(deps): bump url to 2.5.9 for RUSTSEC-2026-0592 (#5237)
url 2.5.8 overflows the stack in Url::origin() on nested blob: URLs (RUSTSEC-2026-0592), which failed Cargo deny on main. 2.5.9 fixes it; form_urlencoded moves to 1.2.3 with it. The rest of the lockfile stays as on main.

Co-authored-by: charli117 <[email protected]>
2026-11-23 01:13:33 +08:00
l0ng-ai 81dd5f0dd2 fix(vcs): keep Git Log path selection in a resizable tree (#5218)
The Git Log path chooser now uses a compact, resizable dialog with a framed file tree. Files and folders have icons and use the standard workbench text size. Long names shorten inside their rows and show the full name on hover. The tree and the checked paths list scroll independently, keeping both reachable in a short window.
2026-11-22 22:57:50 +08:00
l0ng-ai 36061abc91 fix(debugger): lay out inline evaluation and history together (#5216)
The Variables pane now keeps Add to Watches and the history arrow at the trailing edge of the evaluation field. The field uses the configured editor font family at up to the workbench text size, and its short placeholder fits narrow docks. The history menu matches the field width and uses the existing Evaluate history for single-line expressions.
2026-11-22 22:24:43 +08:00
l0ng-ai b8a11df800 fix(editor): keep tab title disambiguation out of the editor API (#5222)
src/editor/api.ts re-exported disambiguateTitles, which brought src/editor/core/model/tabTitles.ts into what the frontend language smoke loads without it being in that workflow's paths, so scripts/smoke-paths.test.ts failed on main. The Show Usages popup now imports it from its module, as EditorArea does.
2026-11-22 22:04:12 +08:00
l0ng-ai 401c542647 feat(vcs): improve Git workflows (#5174)
Improve OpenIDEA's Git workflows across commit and staging, branch and remote operations, merge and rebase, Git Log and signing, worktrees, stash and shelf, patch application, and clone settings. Adds a one-click stash for tracked changes across Git roots and lets users open a worktree branch's associated GitHub review from its context menu. Cloning now includes submodules by default (Settings › Version Control › Git, can be turned off).

Repository entry points added here run in each repository's execution scope, so they use the project's own git executable.
2026-11-22 21:57:30 +08:00
l0ng-ai a435be54e0 fix(editor): compact the line-number gutter (#5212)
Editor line numbers use a font 1 px smaller than the code and a more compact column. The gutter grows with the editor font and with longer line numbers. Sticky Lines uses the same number metrics, and a breakpoint sits at the trailing edge of the number column at the full editor font size.
2026-11-22 21:56:37 +08:00
l0ng-ai 4b58b2a5a5 fix(agents): clear the selection highlight on off-screen conversation rows (#5209)
Selecting new text in an agent conversation left the previous selection highlighted on messages that had been scrolled out of view, so it looked like several selections at once while copying only the new one. Rows that were laid out once skip rendering off screen (`content-visibility: auto`), and WebKit doesn't clear the selection highlight of skipped rows. While the conversation holds a selection, every row now renders (`data-selection` on the stream), until the frame after the selection is cleared, when WebKit applies the change; then off-screen rows skip rendering again.
2026-11-22 21:40:40 +08:00
l0ng-ai 39068cffb3 fix(editor): make Find Usages result rows easier to scan (#5207)
Find Usages now uses the result tree's font for both line numbers and snippets. Line numbers start at the same indent and take only the width of their digits, with a 4 px gap before the snippet. This brings short line numbers closer to their code and gives the snippet more room on narrow panes.
2026-11-22 21:31:46 +08:00
l0ng-ai bef9223913 fix(database): rename databases and schemas from the tree (#5219)
Rename… (db.rename, Shift+F6) did nothing on a database or schema node: canRename accepted only tables, columns, views and PostgreSQL indexes, and database nodes map to no schema object.

Databases of a server that creates them (PostgreSQL, SQL Server) now rename with ALTER DATABASE after the IDE closes its sessions on them; the connected database and read-only sources keep Rename disabled, as Drop does. Schemas rename with ALTER SCHEMA on PostgreSQL and Snowflake. Both use the rename dialog with its SQL preview and refresh the tree.

Fixes #5205
2026-11-22 21:25:44 +08:00
lifeir f2b06bc376 feat(run): npm tool window with the project's package.json scripts (#5217)
A new npm tool window on the right lists the scripts of every package.json in the project (root, workspace members, detected module roots and any other package.json the index knows outside node_modules), grouped by package. Double-click runs a script; the context menu offers Run / Debug through the same path as the package.json gutter, reusing a matching run configuration or creating a temporary one. The window appears only while the project has scripts and refreshes when a package.json changes or indexing finishes. The editor context menu on a package.json script line also offers Run / Debug for that script.

Co-authored-by: lifeir <[email protected]>
2026-11-22 21:10:59 +08:00
l0ng-ai 08d719e03d fix(search): keep action names and shortcuts readable (#5203)
Search Everywhere reserves room for action names alongside shortcuts and categories. Shortcut text is smaller and semibold. Very long key sequences and categories can shorten with an ellipsis, and hovering shows their full text.
2026-11-22 21:07:00 +08:00
ntbang0901 aa849b9cf4 fix(vcs): keep each project's git executable with its repositories (#5214)
Settings › Version Control › Git › Path to Git executable can be set per project, but the value lived in one process-wide variable that each trusted window overwrote before running git. Two windows running git at once could start a command of one project with the other's executable, and a relative value then resolved inside the wrong repository.

Each project's repositories now carry its executable on the same per-thread scope that already carries their trust. Work that opens repositories of its own (agent worktrees and snapshots, gh pull requests, plugin repository access, Create Git Repository…) runs with the project's value. The process-wide value is only the global settings' one, used for git without a project (clone, init without a project).

Co-authored-by: ntbang0901 <[email protected]>
2026-11-22 20:56:38 +08:00
l0ng-ai 0cc8f90708 fix(vcs): keep long Git Log filters compact (#5201)
Long Git Log filter values now end in an ellipsis, with the full value available on hover. A tighter width in compact commit panes keeps the active filter and its clear button visible at more window sizes.
2026-11-22 20:47:43 +08:00
LU XIANGRUIandwildcatDownstairs bc307fdea3 feat(lsp): lint CSS, SCSS and Less with Stylelint (#5208)
CSS, SCSS and Less files get Stylelint diagnostics from the Stylelint language server, installed on demand like the other tools. A project's Stylelint config is picked up as is, a Fix Stylelint Problems action applies the server's fixes, and the built-in CSS diagnostics step aside for rules Stylelint covers.

Closes #5156

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 20:44:18 +08:00
ntbang0901 407f1c5235 feat(debugger): toggle an exception breakpoint from a throw or catch (#5206)
Alt+Enter on a throw statement or a catch parameter offers to create, enable or disable a Java exception breakpoint for that exception type. The type is resolved by the new openidea.java.exceptionType command in the java-usages bundle (1.17.0), and intention providers can now be asynchronous.

Co-authored-by: ntbang0901 <[email protected]>
2026-11-22 20:43:54 +08:00
l0ng-ai ddf9cc3d70 fix(debugger): stabilize the inline variable editor (#5195)
Keep a debugger variable's icon, name and equals sign anchored when Set Value opens. The input fits the tree row, and an error uses a limited share of the value area so the field remains usable in a narrow pane.
2026-11-22 20:43:05 +08:00
l0ng-ai 6e4f536722 fix(search): keep Find in Files footer actions together (#5192)
Keep the shortcut hint beside Open in Find Window and keep Replace All beside the current selection action when the popup wraps. A separator and a smaller keyboard hint give the footer its own visual hierarchy. The popup handles its advertised shortcut when either search field has focus.
2026-11-22 20:42:54 +08:00
l0ng-ai d3be99543d fix(run): anchor console fold controls in the gutter (#5198)
Expanded output has a collapse control beside its row in the Run console gutter. It stays at the left edge while long output scrolls horizontally. A fold at the start of the buffer keeps its control after expansion, and activating a focused fold control leaves process input alone.
2026-11-22 20:34:31 +08:00
l0ng-ai f0cc99a4c7 fix(vcs): give commit subjects room beside compact refs (#5191)
Give Git Log commit subjects room beside long reference labels. Compact References View keeps labels within about a third of the available text column, with the full reference on hover. References in the log use the small UI font and the layout works on either side of the subject.
2026-11-22 20:34:26 +08:00
l0ng-ai 8db16dea32 fix(editor): keep same-name tabs distinguishable (#5187)
Same-name editor tabs show the distinguishing directory before the filename. In a narrow split, the directory gives up space first and the filename stays intact when it fits. The Hidden Tabs picker uses the same path label.
2026-11-22 20:34:21 +08:00
l0ng-ai 6a7297519c fix(settings): keep the current page visible in breadcrumbs (#5196)
Keep the current page name visible as the Settings pane narrows. Parent labels shorten first, and the breadcrumb tooltip shows the full path.
2026-11-22 20:33:01 +08:00
l0ng-ai 08362db3ca fix(run): keep the test summary together and clarify its status (#5186)
Keep elapsed time beside the test counts in the Run window at the same text size. The summary keeps its Running label when the first test has started and no results have arrived yet. A thin line below the summary shows the current state alongside the icon and counts.
2026-11-22 20:32:57 +08:00
l0ng-ai b7f3df0472 fix(debugger): keep values readable beside long type labels (#5185)
Keep debugger values readable beside long runtime types. The row reserves space for a value preview based on its length, so short values leave more room for names. A truncated type can still be read on hover, and the full type appears when the pane has room.
2026-11-22 20:32:52 +08:00
l0ng-ai c5824771c1 fix(editor): make workspace refactoring previews easier to scan (#5183)
Separate the filename from its directory in workspace refactoring previews. This gives same-named files distinct locations and frees space for rename targets and occurrence counts. Hovering a file or a rename target shows its full path.
2026-11-22 20:32:47 +08:00
l0ng-ai 40e5f9b7b3 fix(usages): distinguish files with the same name in the popup (#5181)
Add a muted directory caption beside each filename that appears in more than one file in Show Usages. Identical filenames, line numbers and snippets can otherwise make two results indistinguishable until selected. The popup uses the same directory labels as editor tabs, including a longer suffix when directory names repeat at different depths.
2026-11-22 20:32:41 +08:00
l0ng-ai 8bc82d08c6 fix(vcs): give outgoing commit messages a clear subject (#5180)
Give the selected commit's subject a stronger weight and separate it from the body in the Push dialog. The preview uses the editor's font settings for the message and compact text for the revision, author and date, matching the message hierarchy in Git Log.
2026-11-22 20:32:23 +08:00
l0ng-ai b0473f17b5 fix(run): keep the configuration header visible while scrolling (#5175)
Keep the configuration name and project-file checkbox visible above the scrolling options in Run/Debug Configurations. Long forms previously scrolled these controls out of view, so editing the name or changing where a configuration is saved meant returning to the top.
2026-11-22 20:31:59 +08:00
l0ng-ai 21264641ba fix(search): clarify Recent Locations file captions (#5170)
Recent Locations now shows the filename once, with a symbol breadcrumb or its parent directory beside it. Directory captions distinguish entries with the same filename, and hovering over a caption reveals the full project-relative path.
2026-11-22 20:31:00 +08:00
l0ng-ai 3ce4578600 fix(editor): separate quick fixes in the intentions popup (#5167)
Separate quick fixes from other actions in the Intentions popup with a divider. The divider is skipped during keyboard navigation and disappears when filtering leaves a single group. The popup keeps the chosen action selected when more results arrive from the language server.
2026-11-22 20:30:36 +08:00
l0ng-ai e89b565a78 fix(diff): keep revision filenames readable in narrow panes (#5163)
Keep filenames visible in side-by-side revision headings. Long directories elide before the filename, and the title tooltip shows the complete path and revision. Revision paths use the standard 13 px UI text size.
2026-11-22 20:28:36 +08:00
l0ng-ai b2a1ee2204 fix(run): keep primary actions in view in side docks (#5159)
Keep Rerun and Stop together and give narrow Run docks more room for output. When the toolbar gets narrow, Scroll to End and Soft-Wrap move into More Actions and keep their checked states. The same menu opens the current run configuration, and a wider panel shows the console toggles on the toolbar.
2026-11-22 20:28:31 +08:00
l0ng-ai 828cb271d9 fix(search): keep file locations readable in Find in Files (#5145)
Give line numbers their own space at the right edge of Find in Files and Replace in Files results. Long file labels can still fit with an ellipsis, and hovering reveals the full relative path. Consecutive hits in the same file use quieter filename text so the line numbers are easier to scan.
2026-11-22 20:28:26 +08:00
l0ng-ai ed369c2a6d fix(debugger): group line breakpoint actions (#5141)
Group a line breakpoint's logging controls under Actions in the Breakpoints dialog and gutter popup. The dialog includes Remove once hit in the same group. The gutter popup uses the standard 13 px text size for the condition and hit count labels.
2026-11-22 20:28:20 +08:00
l0ng-ai 3103ec19f9 fix(vcs): Add to .gitignore and Show History act on the focused Project view (#5215)
Add to .gitignore, Add to .git/info/exclude and Show History for File took the active editor's file even when the shortcut was pressed in the Project view. Like Add to VCS they now take the Project view's selection while it has focus and the open file otherwise.
2026-11-22 20:07:24 +08:00
Aevion 026ef8794f fix(vcs): Add to VCS stages the Project view's selection (#5210)
Pressing Add to VCS (Option+Cmd+A) with a folder selected in the Project view reported "Nothing to add" instead of staging the unversioned files in it: the action resolved its targets from the active editor's file only. While the Project view has focus it now takes the Project view's selection; from the editor it still adds the open file.

Co-authored-by: aevioni <[email protected]>
2026-11-22 20:03:40 +08:00
l0ng-ai 7e77c270b7 fix(java): resolve compileOnly project dependencies in Gradle builds (#5213)
Gradle's Eclipse model, which jdtls imports a Gradle build through, leaves out project dependencies a source set only compiles against (compileOnly / testCompileOnly(project(":a"))), so their classes showed as unresolved although Gradle compiled them. jdtls's Gradle import now runs an init script that adds every project on the main and test compile classpaths, keeping test-only ones marked as test code.

On macOS, Buildship stores a build's arguments joined by spaces and splits them again, and jdtls passes its own init scripts from its configuration area under Application Support, so every import that set a Gradle JDK, user home or argument failed ("The specified initialization script '.../Application' does not exist"). A jdtls install under a path with spaces now gets a configuration area in the user's cache directory, and our init script goes to the first directory without spaces.

Fixes #5090
2026-11-22 19:56:38 +08:00
Emir 9abca932d1 feat(settings): pick a custom accent colour with the colour picker (#5204)
The custom swatch of Settings > Appearance > Accent color now opens the editor's colour picker (opaque: RGB and HEX fields, recent colours, eyedropper where available) instead of a native colour input and hex field. The new value is staged and saved with Settings Apply.

The picker moves from the color-preview feature to src/ui so both features use the same component.

Co-authored-by: laot7490 <[email protected]>
2026-11-22 19:33:55 +08:00
Muuandmuutot ce6c61aa5e feat(settings): preview Diff & Merge colours in a real merge view (#5098)
Settings > Editor > Color Scheme > Diff & Merge now previews the colours in a three-pane merge view (left / result / right) painted with the same CodeMirror diff decorations as a real merge, including a folded unchanged fragment with the wave separator. Clicking a coloured line selects its attribute.

The preview is a mergeSchemePreview editor kind registered from the VCS settings pages, so it also works in the standalone Settings window, which never activates the workbench diff viewer, and the settings feature does not import the VCS feature.

Co-authored-by: muutot <[email protected]>
2026-11-22 19:27:01 +08:00
LU XIANGRUIandwildcatDownstairs 9e8722feb6 feat(lsp): lint and format with Biome (#5200)
Adds Biome as a language server (lint diagnostics and code actions) and as a formatter for CSS, GraphQL, JavaScript, TypeScript (and JSX), JSON and JSONC, with a Languages & Frameworks > Biome settings page (path, provider, run on save, enabled languages).

Biome formats instead of Prettier and oxfmt below a biome.json / biome.jsonc or a Biome installation, unless the nearest configuration sets formatter.enabled to false, in which case Prettier keeps formatting. Resolved conflicts with the Tailwind CSS language server: both servers are listed in the language definitions, registry tests and docs.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 19:18:37 +08:00
faysou f2950defcf perf(markdown): render preview math as SVG (#5048)
Typeset equations with MathJax before painting the Markdown preview.
Load MathJax on demand, preserve accessible MathML, and fall back
to KaTeX for unsupported equations.
2026-11-22 19:06:38 +08:00
LU XIANGRUIandwildcatDownstairs 0130847bc0 feat(languages): start the Tailwind CSS language server in Tailwind projects (#5199)
Runs @tailwindcss/language-server next to the language's own servers for HTML, CSS, JS/JSX, TS/TSX, Vue, Svelte and Astro, only below a tailwind.config.* (v3) or a package.json listing tailwindcss in dependencies or devDependencies (v4), with one-click install like the ESLint and Angular servers. JSON root markers (package.json#…) now match a key with any non-null value, not only objects. Adds fixtures/tailwind-app and an ignored real-server test.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 18:55:05 +08:00
LU XIANGRUIandwildcatDownstairs b9f9e2668a fix(debugger): adopt child sessions whose ids an earlier backend used (#5197)
A window whose project moves to another backend process (a remote reconnect, or a new openidea-server in the smoke tests) sees session ids numbered from 1 again. ownSession checked the ids of forgotten sessions before looking for a known parent, so a new child's started event reusing such an id was dropped, along with every later event of that child: the Debug tool window never showed the pause. started is a session's first event and can't be a late event of a forgotten session, so it no longer stops there; a child is still adopted only under a session of this window, and other late events of forgotten ids stay ignored.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 18:51:58 +08:00
LU XIANGRUIandwildcatDownstairs 1f39eb8e63 fix(run): keep Jest and Vitest gutter runs as they were (#5194)
#5173 gave every JS file in test/ gutter targets and #5169 made all kind-node test configurations bases for gutter runs, so Jest/Vitest projects gained run icons in test/ helpers and imported npx jest configurations started running gutter targets. test/ now counts only in projects with a Mocha or node --test configuration, and only Playwright's node configurations are gutter bases.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 18:50:42 +08:00
l0ng-ai a4db4a9e3f fix(vcs): commit a new file's edits made after Add to Git (#5202)
Add to Git stages a new file as it was created, usually empty; edits afterwards leave it partially staged, and Commit included partially staged files with only their staged part, so the first commit held the empty file and the content needed a second commit. A partially staged file whose staged side is an addition is now included whole by default (also when committing selected files) and loses the partial badge; other partially staged files keep committing their staged part.

Fixes #5189
2026-11-22 18:48:23 +08:00
l0ng-ai c209e189e0 docs(plugins): format the run-targets process tables (#5193)
Re-aligns the Running programs tables in docs/{en,zh}/plugins/guides/run-targets.mdx so pnpm format:check passes on main again. Whitespace only.
2026-11-22 17:44:20 +08:00
Muuandmuutot 0b83b3ffbc style(ui): compact metrics for combo boxes and editor tabs (#5188)
Compact mode now also steps the combo box label padding (9/6 → 6/6, ComboBox.padding.compact) and radius (4px → 2px, ComboBox.arc.compact), and the editor tab pill's inline padding (8px → 6px, EditorTabs.tabInsets.compact), through new --combo-pad-start/end, --radius-combo and --tab-pad-x tokens. Toolbar and tool window stripe button radii stay at 6px → 4px (MainToolbar.Button.arc and Button.ToolWindow.arc 12 → 8).

Co-authored-by: muutot <[email protected]>
2026-11-22 16:55:22 +08:00
l0ng-ai 7caec95fee fix(java): stop reusing launch snapshots after Build › Rebuild (#5190)
Launch snapshots are reused while a module's sources keep their fingerprint. Build › Rebuild Project cleaned and recompiled target/classes but left the launch records untouched, so the next run kept loading a snapshot that could hold classes the clean removed (a class compiled under its old package), and Spring found two beans with the same name.

A Rebuild now clears the fingerprint of every launch record in the project, so the next launch copies the rebuilt outputs; the records stay, so those modules keep delegating to Maven.

Fixes #5179
2026-11-22 16:46:53 +08:00
Deng Liuanddengliu 3d56af936d feat(dev): add dogfood:remote task to build and stage openidea-server (#5139)
Adds `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean] [--install-rust]` (also `mise run dogfood:remote`) for dogfooding backend changes in Remote Development without cross-compiling locally. It reads the host from Settings › Tools › SSH Configurations, checks SSH reachability and the minimum Rust version, syncs the backend workspace to `~/.cache/openidea-dogfood/workspace`, builds `openidea-server` there, installs it at the `~/.openidea/server/<version>/<build_id>` path `ensure_server` expects (so connecting doesn't upload another binary), stages the matching binary locally (`--clean` restores the release one), and asks before restarting a running server. The `build_id` hash uses `blake3` from the new `@noble/hashes` devDependency. Rust is installed on the host only with `--install-rust`.

Closes #5135

Co-authored-by: dengliu <[email protected]>
2026-11-22 15:35:33 +08:00
Deng Liuanddengliu 0a3eac8652 feat(agents): parse context:fork and paths/globs skill metadata and show badges (#5162)
Skills now parse `context: fork` and `paths` / `globs` frontmatter (inline, bracketed or YAML list). Settings › Agents › Skills shows `context: fork` and `paths (n)` badges, with the patterns in the inspector, and the session Skills picker shows fork / paths pills. `SKILL.md` is still staged untouched, so CLIs that support these fields natively apply them. Frontmatter key lookup is case-insensitive.

Part of #5113

Co-authored-by: dengliu <[email protected]>
2026-11-22 15:33:47 +08:00
LU XIANGRUIandwildcatDownstairs 70702934d1 feat(run): run Mocha tests with a test tree and Rerun Failed Tests (#5173)
Mocha runs showed no test tree, and single tests ran with Jest's `-t`. A `package.json` script that runs `mocha` is now a test configuration with `testRunner: "mocha"`. Test runs import the IDE's hook (`mochaHook.js`, a `data:` URL in `NODE_OPTIONS`), which prints a record per finished test (file, suite chain, status, duration, declaration line, error) next to the run's own reporter; the records become the tree and are hidden from the console. Gutter icons, Rerun Failed Tests and running selected tests use Mocha's own `--grep`. New fixture `fixtures/mocha-app`, run by `smoke/run.test.ts` in the TypeScript job.

Closes #5153

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 15:24:38 +08:00
LU XIANGRUIandwildcatDownstairs 8e541d5b45 feat(run): run node:test tests with a test tree and Rerun Failed Tests (#5172)
`node --test` runs showed no test tree, and single tests ran with Jest's `-t`.

- Detection: a `package.json` script whose Node options include `--test` (also `tsx --test`) is a test configuration with `testRunner: "node-test"`; a script that picks its own `--test-reporter` runs as written.
- Test tree: test runs add the IDE's reporter (`nodeTestReporter.js`, passed as a `data:` URL) next to `spec` through `NODE_OPTIONS`, which works through `npm run`, Node's per-file child processes and remote run targets. It prints a record per test (file, describe chain, status, duration, declaration line, error); the records become the tree and are hidden from the console, which keeps `spec`'s output.
- Gutter, Rerun Failed Tests, run selected tests: select by full name with `--test-name-pattern` in `NODE_OPTIONS`, plus the files.

New fixture `fixtures/node-test-app`, run by `smoke/run.test.ts` in the TypeScript job.

Closes #5152

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 15:19:57 +08:00
LU XIANGRUIandwildcatDownstairs 87c4659547 fix(i18n): insert tx template values as written (#5177)
In the Chinese UI, Rename on a folder named `tasks` read 将目录“任务”及其用法重命名为:. The `tx` template tag translated every interpolated string that had a catalog entry of its own, so a file, branch, script or container name that matched a UI word (`tasks`, `Retry`) was shown translated. Values are now inserted as written. Call sites that interpolate the app's own UI words (kind labels, option titles, "Source"/"Target") mark them with the new `txPart(...)`, which is also translated again after a language change; the text catalog guard checks `txPart` literals too. `txTemplate` still translates captured parts.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 15:14:54 +08:00
l0ng-ai 3475dbd688 fix: restore frontend tests after the skill installer and Python Console (#5182)
Three frontend tests failed on main after #5157 and #5164: SkillsPage.module.css read an undeclared --r-sm (now --radius-small); the SKILL.md catalog entry is a file name kept as written in Chinese, so it joins the same-as-English list; and the VS Code presets lacked python.console.executeSelection, which stays unbound there because Shift+Enter would shadow typing in Python files.
2026-11-22 15:14:02 +08:00
Deng Liuanddengliu 0800e8445f feat(agents): native GitHub skill browser, preview, static scan, and installer (#5157)
Settings › Agents › Skills gets Install Skill…: enter a GitHub source in the forms `npx skills add` accepts (`owner/repo`, `owner/repo@skill`, `owner/repo#ref`, `owner/repo/path[@ref]`, GitHub tree URLs, pasted skills.sh links), pick one of the skills found, preview its `SKILL.md` and file list, and install it into `~/.agents/skills` (default) or the workspace `.agents/skills` (trusted projects only). Sources resolve through GitHub's Git Trees and Blobs APIs over the existing `ide-tools` HTTP client, with no curated repository list and no Node or git dependency, retrying unauthenticated when an ambient GitHub token gets HTTP 401 on a public repository. Only the selected skill's subtree is downloaded (capped at 2 MiB / 256 files) and installed atomically through a staging folder. A static scan flags hidden or bidirectional Unicode, out-of-root symlinks (omitted on disk), executable scripts and `allowed-tools` shell grants; the user must confirm the warnings, and the backend checks that confirmation again before writing.

Part of #5115

Co-authored-by: dengliu <[email protected]>
2026-11-22 15:09:01 +08:00
Deng Liuanddengliu b7ac5f1bbb feat(plugins): declarative [[contributes.skills]] in plugin.toml (API 1.15) (#5144)
Plugins can now bundle `SKILL.md` folders with a manifest-only `[[contributes.skills]]` extension point (API 1.15, no WIT change). They appear under Plugins in Settings › Agents › Skills and the Composer Skills picker while the plugin is enabled, and are staged into each CLI's per-session skill folder from the plugin's package directory; disabling or uninstalling the plugin removes them right away. Load-time validation keeps `path` inside the package (no `..` or escaping symlinks), requires `<dir>/SKILL.md` with the usual folder-name and frontmatter rules, and caps a skill folder at 2 MiB / 256 files; an invalid entry becomes a plugin load warning without failing the rest of the plugin. Every file of a valid skill folder is part of the package files, so versioned installs and remote sync copy supporting scripts and references. Workspace and user skills win on a name clash. Includes a declarative fixture plugin and docs.

Closes #5114

Co-authored-by: dengliu <[email protected]>
2026-11-22 15:02:11 +08:00
l0ng-ai f473cd9927 fix(agents): give Codex skill paths one separator on Windows (#5158)
Skill roots are joined as `.agents/skills`, so a SKILL.md path that could not be canonicalized kept a forward slash on Windows and failed hub_staging_hands_each_cli_its_own_tree. Rebuild the path from its components before handing it to Codex.
2026-11-22 14:44:44 +08:00
LU XIANGRUIandwildcatDownstairs 9a3b97a5fa feat(python): flag requirements the interpreter does not satisfy and offer to install them (#5168)
`requirements*.txt` and `pyproject.toml` (`[project]` dependencies, optional dependencies, `[dependency-groups]`) now mark each requirement the project's interpreter doesn't have installed, or whose installed version misses the specifier. A banner offers Install requirements, and the quick fixes are Install requirement and Install all missing requirements; installs use the same pip/uv path as the interpreter settings page, run as a background task, report failures in one notification and re-check the file. The interpreter judges the requirements itself (with `packaging` or pip's vendored copy), so PEP 440 specifiers, PEP 503 names and markers behave as pip does; Rust only parses the files for spans, skipping `-r`, `-e`, options, URLs and paths. Nothing is checked without a local interpreter, for a container interpreter, or in Restricted Mode. It is a new inspection, "Unsatisfied package requirements", and the Cargo version check now shares the same editor plugin (`manifestCheck.ts`).

Closes #5147

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 14:43:09 +08:00
LU XIANGRUIandwildcatDownstairs c632dfa01c feat(python): add a Python Console tool window (#5164)
Adds a Python Console tool window: an interactive interpreter of the project's Python (the one Settings and the status bar show; in a workspace, the member the active file is in), started in the project root with the source roots on `PYTHONPATH`. It uses IPython when the interpreter has it and plain Python otherwise, in its own `__main__`. Enter runs the input, Shift+Enter adds a line, Up/Down recall earlier inputs, and while code runs a typed line answers its `input()`. A Variables pane lists the console's globals after each run. Execute Selection in Python Console (`python.console.executeSelection`, Alt+Shift+E, also in the editor context menu of Python files) sends the selection or the current line, starting the console if needed; a selection inside an indented block is dedented. The console is a small driver script run on the existing Run process host, so there are no backend changes.

Closes #5148

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 14:34:50 +08:00
LU XIANGRUIandwildcatDownstairs 88f494ca50 feat(debugger): view pandas and numpy values as a table (#5166)
In a Python debug session, a DataFrame, Series or ndarray variable or watch only showed a one-line repr. It now has View as Table in its context menu: a resizable window with column headers (with dtypes for a DataFrame), the index, the shape, and pagers for rows (100 per page) and columns (30 per page). Each page is one `evaluate` in the paused frame: a small helper slices the object in the debuggee and returns only that page as JSON, so the whole object never goes over DAP. The expression can be edited (e.g. `a[0]` for a 3-D array), and the window stays open across steps, refreshing after each step or frame change.

Closes #5165

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 14:31:17 +08:00
LU XIANGRUIandwildcatDownstairs 9b4ee2a6ff feat(run): run Playwright tests with a test tree and Rerun Failed Tests (#5169)
A Playwright project had no test tree and no Rerun Failed Tests: its output went through the Jest / Vitest parser, single tests ran with Jest's `-t`, and projects without a `test` script weren't detected at all.

- Detection: a `package.json` script that runs `playwright test` is a test configuration and records `testRunner: "playwright"` (new optional `RunExtras.test_runner`, `test-runner` in `run.toml`); a package with a `playwright.config.*` that no script runs gets `npx playwright test`.
- Test tree: test runs add `--reporter=list` unless a reporter is named, parsed into file › [project] › describe chain › test with status, duration, location and failure details.
- Gutter: `test.describe` blocks and `fixme` / `fail` / `serial` tests get run / debug icons and run by declaration line (`file:line`); in a project with Playwright and another runner, specs run on Playwright's configuration and other tests on the other runner's.
- Rerun Failed Tests / run selected tests: the files plus `--grep` on the describe chain and title, with `--project` when the run named projects.

New fixture `fixtures/playwright-app`; `smoke/run.test.ts` runs it after `ts-app`.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 14:30:06 +08:00
LU XIANGRUIandwildcatDownstairs e75d438f70 feat(python): update imports when a module or package is renamed or moved (#5171)
Renaming or moving a Python module or package left every import of it broken: basedpyright has no `workspace/willRenameFiles`, so no reference updates reached the move preview. `refactor_file_move_edits` now maps the moved paths to dotted module names from the project's Python roots (`src/` layout or the project root, `tests/`), and `Syntax::python_import_edits` rewrites the import statements of each project `.py`/`.pyi` file from its tree-sitter tree. It covers `import a.b` (with qualified uses `a.b.X`), `import a.b as c`, `from a.b import X`, `from a import b`, relative imports (kept relative, also in the moved files themselves) and package moves; when a rename changes the name an import binds, the import keeps it with an alias. The edits join the existing move preview and undo. A Python server that answers `willRenameFiles` still wins. The Python language smoke now checks file moves.

Closes #5146

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 14:26:50 +08:00
LU XIANGRUIandwildcatDownstairs a67b27c33a feat(editor): highlight CSS, GraphQL, SQL and HTML in template literals (#5160)
In JavaScript and TypeScript files, embedded code in template literals showed as one string. The body of a tagged template literal is now parsed in the language its tag names: CSS for styled-components / emotion / Lit (`styled.div`, `styled(Comp)`, `.attrs(…)`, `css`, `createGlobalStyle`, `keyframes`, `injectGlobal`, parsed as declarations plus nested rules), GraphQL for `gql` / `graphql` (also the `graphql(`…`)` call form), SQL for `sql` and HTML for `html`; a `/* GraphQL */`-style comment before a plain literal works too. Substitutions stay JavaScript. CSS, SQL and HTML use the same modes as files in those languages; GraphQL gets a small stream mode used only inside literals (`.graphql` files keep tree-sitter highlighting). The embedded mode loads lazily, comment toggling and bracket matching follow it, and Angular TypeScript files and Markdown `ts` fences get the same injection.

Closes #5150

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 14:24:24 +08:00
Akbar Husain 62028362d6 feat(remote): forward ports of a WSL project (#5140)
The Ports tool window existed only for SSH hosts and dev containers; a WSL project refused to forward. A WSL distribution shares this machine's loopback (as `forward_web_url` already assumes), so a port it listens on is reachable here on the same port without a tunnel. The route decision is now a pure `forward_route(target, host)` (SSH channel tunnel, container exec tunnel, or WSL's shared loopback; another host stays reachable from a dev container only), and `Forward::Wsl` reports the port unchanged and owns no resource. The Ports tool window registers for WSL sessions, remembered ports are scoped per distribution and folder (`wsl:<distro>:<root>`), the refusal and its string are gone, and the remote docs describe it.

Co-authored-by: akbar1214 <[email protected]>
2026-11-22 14:23:05 +08:00
LU XIANGRUIandwildcatDownstairs c57af26f9d feat(python): offer to install pylsp-rope when a refactoring needs it (#5161)
On Python files, Extract Method, Inline, Introduce Parameter and module-level Introduce Constant come from pylsp-rope, a companion server the missing-server prompt skipped, so without it these refactorings only said "Cannot perform refactoring". Now, when one of them finds nothing and pylsp-rope isn't installed, the usual missing-tool notification offers to install it (Install restarts the server, so the refactoring works right away). `promptInstall` takes a purpose (code insight, formatter or a refactoring) instead of a formatter flag; a refactoring purpose lets a companion server through, even when another server already serves the files. Opening a project stays quiet.

Closes #5149

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 14:21:33 +08:00
Ainul YaqinandAkin01 ed6f264875 fix(plugins): provide lossless bounded streaming and configurable capture for processes (#4812)
Plugins running compilers, linters or large diffs lost output: `start` kept only a 1 MiB tail and `run`/`run-command` truncated stderr. API 1.15 adds `process-options` (`max-output-bytes` up to 128 MiB, `buffer-bytes` up to 4 MiB), `run-captured`, which fails explicitly when either stream overflows, and `start-stream`, which streams losslessly with pipe backpressure: readers pause at the buffer limit, resume as `poll`/`chunk` consume, and `wait` drains up to the total limit so fast producers don't deadlock. Overflow stops the process tree and records its exit status before reaping it. `run`, `run-command` and `start` behave as before, and 1.14 components still load.

Closes #4763

Co-authored-by: Akin01 <[email protected]>
2026-11-22 14:11:13 +08:00
HEOJUNFO 369f52d39e fix(http-client): use http when server.ssl.enabled is false (#5143)
A request generated from a Spring mapping got an `https://` host when `server.ssl.enabled=false` and a key store was also configured (typically a base file with the key store and a profile that turns TLS off for local runs). `hostFromConfig` picked https when TLS was enabled or a key store was set, so the key store won over an explicit `false`. In Spring Boot the property defaults to true and SSL is configured only when it is, so an explicit `false` now wins; the other cases are unchanged.

Co-authored-by: HEOJUNFO <[email protected]>
2026-11-22 14:06:03 +08:00
HEOJUNFO 305ff382e7 fix(run): carry a duration's rounded seconds into its minutes (#5142)
A run or test lasting between 1 m 59.5 s and 2 m showed as `1 m 60 s` (and likewise at every minute) in the test tree, the exported test report and the run tab's "Finished in …" tooltip. `formatDuration` split off whole minutes first and rounded the remainder afterwards; it now rounds to whole seconds first and splits after.

Co-authored-by: HEOJUNFO <[email protected]>
2026-11-22 14:04:54 +08:00
l0ng-ai 92dbf0baa5 fix(terminal): separate session choices from window actions (#5138)
Open the predefined session chooser directly on the installed shells and SSH. The plus button opens the default shell. Split commands live in the terminal tool window's Options menu, with Settings at the bottom of the session chooser. On the Windows fixture the chooser went from nine actions to six and from 267 px to 153 px in height.
2026-11-22 14:03:13 +08:00
l0ng-ai b02f212d3e fix(completion): keep suggestion names readable in narrow lookups (#5133)
Keep suggestion names readable when long signatures compete for space. The name keeps its natural width when it fits, the return type gets space next, and parameters use the rest. Exceptionally long names can still truncate within the editor.
2026-11-22 13:36:07 +08:00
l0ng-ai ca7f26f484 fix(editor): give a completed foreach its body (#5123)
⌘⇧↵ after `foreach ($xs as $x)` in PHP produced `foreach ($xs as $x);` with the caret on the next line: a semicolon that terminates an empty loop. `foreach` was missing from the block-head keywords, so the line was treated as a plain statement.

`foreach` (PHP, C#) and PHP's `elseif` are now block heads: the line gets `{` / caret / `}`, and a bare `foreach` gets `(|)` like `for`.
2026-11-22 13:21:34 +08:00
l0ng-ai bf4fff8fcf fix(editor): end completed C and C++ type definitions with }; (#5122)
⌘⇧↵ after `struct S` (C) or `class A` (C++) produced `struct S {` / `|` / `}`: a type definition without its terminating `;`, which does not compile.

`completeStatementSpec` now closes the body with `};` in C, C++, Objective-C and Objective-C++ when the header is a type definition: `struct` / `class` / `union` / `enum` / `enum class`, optionally with `typedef`, `template <…>`, `final` and base classes. `typedef struct Node`, `union U` and `template <typename T> class Box` are now recognised as block heads too. Namespaces and control flow keep a plain `}`.
2026-11-22 13:20:15 +08:00
l0ng-ai 3cbe327a6a fix(editor): line up C++ access specifiers with their class (#5128)
Typing `public:` on a member line of a C++ class left it at member indentation (`    public:`) instead of lining it up with the class, as CLion's default code style does. The Lezer C++ indentation has no rule for access specifiers, and its `indentOnInput` only reindents `case`, `default:` and braces.

For C++ (`EXTRA_SUPPORT` in `languages.ts`), an indent service puts a `public:` / `protected:` / `private:` line at the indentation of the line opening its class body (`FieldDeclarationList`), and an `indentOnInput` pattern reindents the line when the colon is typed. Members after it keep the member indentation; `std::` is unaffected.
2026-11-22 13:18:09 +08:00
l0ng-ai 0311297886 fix(editor): indent the body after a case label in C, C++ and PHP (#5124)
Enter after an 8-space `case 1:` (or `default:`) in C, C++ or PHP put the caret at 8 spaces, aligned with the label, instead of 12 for the branch body: the Lezer C++ and PHP grammars indent a `case` body from the switch body, not from the label.

`caseBodyIndent`, an indent service added for C, C++ and PHP in `EXTRA_SUPPORT`, puts the new line one level deeper than a `case …:` / `default:` line when nothing follows the caret. Other lines, including a C++ `std::`, are unchanged.
2026-11-22 13:16:56 +08:00
l0ng-ai a711c991b6 fix(navigation): compact navigation bar child lists (#5132)
Use compact rows and content-based widths in navigation bar child lists. The default row height is 18 px and the text stays at 13 px. The wide desktop fixture shows 20 complete rows, up from 14. The two-folder list in the narrow fixture uses 95 px of width, down from 199 px.
2026-11-22 13:15:32 +08:00
Gabriel Gondim 698cad2b3f fix(ci): run language smoke when editor navigation providers change (#5101)
src/editor/api.ts re-exports navigationProviders and relatedProviders, which the frontend smoke loads. Add both files to the Language smoke workflow paths and to the Changes step's smoke pattern, so scripts/smoke-paths.test.ts passes again and a change to either file runs every language.

Closes #5073
2026-11-22 12:57:44 +08:00
l0ng-ai 581c64f544 fix(vcs): surface the Git Log affected changes filter (#5130)
Show the affected-changes toggle on the changed-files toolbar when Git Log has a path filter. This makes it possible to narrow the selected commit's file list in one click. Group the Diff preview toggle and its location under Layout in View Options. Let the toolbar wrap when the pane is narrow.
2026-11-22 12:52:57 +08:00
l0ng-ai 77d6d81f8a fix(editor): complete /** doc stubs in PHP files and list C/C++ tags (#5127)
Two problems with the `/**` + Enter stub:

- **PHP**: `/**` + Enter right after `<?php` gave `/**` / caret, with no `*/`, so the function below ended up inside an open comment. With an unclosed `/**` directly after `<?php`, Lezer PHP parses the text as the surrounding HTML: `languageDataAt("commentTokens")` there returns only `<!-- -->` (checked with the real PHP language), and `enterInDocComment` stood back. In PHP documents it no longer requires `/* */` tokens at the caret, so the stub is closed and lists `@param` / `@return` as elsewhere in PHP.
- **C / C++**: the stub had no tags. New `cDocTags` lists `@param` per named parameter (defaults and array suffixes dropped, `void` / `...` skipped) and `@return` unless the function returns `void` or is a constructor or destructor. It handles specifiers, pointers and references, `template <…>`, qualified names (`Box<T>::take`), trailing `const` / `noexcept` / `override` and initializer lists; types, calls and statements get no tags.
2026-11-22 12:45:26 +08:00
l0ng-ai ea62941bc6 fix(editor): pair include and template angle brackets in C and C++ (#5126)
With bracket pairing on, `<` after `#include ` (C, C++) and after `std::vector` (C++) stayed single: `smartAngleBrackets` had no rule for C or C++.

- C and Objective-C: `#include <` (and `#include_next`, `#import`) pairs.
- C++ and Objective-C++: the same, plus `template <`, a standard template or cast written against its `<` (`std::vector<`, `std::make_unique<`, `static_cast<`…) and a capitalized name (`Box<`).
- Lowercase values (`a <`, `i<`), `std::cout <`, all-caps macros (`MAX<`) and `operator<` stay single.

`inLiteral` treated any node whose name contains "template" as a template literal, which made Lezer C++'s `TemplateFunction` (`std::make_unique`) look like a string; C++ template nodes are now excluded.
2026-11-22 12:42:18 +08:00
l0ng-ai 00e044b66b fix(project): group tool window options in submenus (#5118)
Project's Options menu groups its settings under Behavior, Appearance, and Sort By. Sort By includes the folder ordering toggle alongside the sort choices. The first level now has seven items, so the window controls stay visible in a short window.
2026-11-22 12:39:34 +08:00
l0ng-ai 1db368d2b4 fix(refactor): find clangd's extractions from the refactoring shortcuts (#5121)
⌥⌘V on `value * value` in C or C++ said "Selected block should represent an expression", while ⌥↵ on the same selection offered **Extract subexpression to variable** and it worked. clangd gives every tweak the kind `refactor`, and `refactor` is not contained in `refactor.extract`, so the shortcut's request returned nothing. Checked with a small LSP script against the installed clangd: `only: ["refactor"]` → `Extract subexpression to variable` (`refactor`); `only: ["refactor.extract"]` → none.

`requestKind` now asks for `refactor` in C, C++, Objective-C and Objective-C++ too (as it already does for typescript-language-server); `classifyAction` already maps a generic `refactor` action by its title.
2026-11-22 12:36:03 +08:00
l0ng-ai db50b5df5b fix(editor): keep inline find controls together (#5120)
Keep the Close button next to More in the editor's Find and Replace toolbar. The two fields share a column that scales with the editor pane. In narrow panes, the controls wrap below the query and the fields use the space freed by moving Close.
2026-11-22 12:32:52 +08:00
Deng Liu 17fe162f6c chore(dev): add dogfood build and install tasks (#5125)
Add `pnpm dogfood:build` / `pnpm dogfood:install` (and matching mise tasks) to build a fast local release app named openidea_dogfood with a grey icon. It keeps the release identifier, so it shares settings and data with the installed app.

The dogfood config clears the updater endpoints so a release never replaces the dogfood bundle, the bundle is read from Cargo's target directory, and the install output and setup docs note that the two apps share one instance and settings and that the dogfood app never updates itself.
2026-11-22 12:26:36 +08:00
Dan Zhengandclevertension 0fc462350b feat(editor): copy absolute path with line number (#5136)
Copy Path/Reference… gets "Absolute Path with line number" right below "Absolute Path": the absolute file path with the caret line, or the selected line range (`/abs/path/File.java:12`, `/abs/path/File.java:12-18`), like the existing relative "Path with line number". It is also an action (`editor.copyAbsolutePathWithLineNumber`) reachable from Find Action. Like the relative variant, the chooser copies the value it previewed, even if the caret moved after it opened.

Co-authored-by: clevertension <[email protected]>
2026-11-22 12:07:33 +08:00
l0ng-ai ff80b4351a fix(editor): pair Kotlin template braces and generic factory calls (#5108)
Two pairing gaps in Kotlin:

- **`"${`** stayed `"${|"`: `closeBrackets()` pairs `{` only before whitespace or a closer, and here the auto-inserted closing quote follows. `templateBrace` pairs a `{` typed right after `$` inside an open string into `${|}`, in Kotlin, Groovy, Dart, Scala, JavaScript and TypeScript (template literals). Outside a string nothing changes.
- **`mutableListOf<`** got no `>`: the Kotlin rule only treats capitalized names as types. A generic factory call written directly against its `<` — `…Of` (`listOf`, `mutableMapOf`, `setOf`…), `empty…`, `arrayOfNulls`, `enumValues`, `enumValueOf`, `typeOf` — now pairs. Other lowercase names, and any name followed by a space, stay comparisons.
2026-11-22 11:55:51 +08:00
l0ng-ai af2be518ec fix(editor): move selected text by dragging it (#5137)
The desktop window keeps native drag and drop on for files dropped onto it, so HTML5 drop events never reach the page and CodeMirror's built-in text drag never landed: dragged text stayed where it was.

Text drag now runs on mouse events. Dragging the selection shows a drop caret, scrolls the editor near its edges, and drops the text at the caret on release, into the same or another editor. Option (macOS) or Ctrl held at release copies instead of moving; Escape cancels; a click on the selection without dragging places the caret. "Enable drag-and-drop functionality in editor" still turns it off.

Closes #5117
2026-11-22 11:53:25 +08:00
l0ng-ai 9f60e9b209 fix(search): integrate the Search Everywhere query field (#5116)
The Search Everywhere query field now sits directly on the popup surface. A single inset divider shows focus for the query and its history button. The shorter query row gives results more room in short windows.
2026-11-22 11:45:46 +08:00
Deng Liuanddengliu 1838919f47 fix(agents): close Phase 1 skills hub discovery, staging, and override gaps (#5129)
Fixes the remaining Phase 1 gaps of the Agent Skills hub:

- `/` completion drops skills that are off or `user-invocable: false`, de-duplicates Codex's prefixed names, keeps `argument-hint`, defaults `disable-model-invocation: true` skills to slash-only, and refreshes when session or draft overrides change.
- Discovery scans workspace member folders, monorepo packages up to two levels down, `<category>/<skill>/SKILL.md` folders and Copilot CLI's two-level `installed-plugins` layout (skipping disabled plugins). Codex disable rules point at `<skill>/SKILL.md`, and roots each CLI already scans are treated as native so skills aren't staged twice.
- A skill that is off globally or for the workspace can be turned on for one session; untrusted workspace skills stay locked. Settings › Agents › Skills shows the other folders a symlinked skill is linked from.

Closes #3897

Co-authored-by: dengliu <[email protected]>
2026-11-22 11:45:20 +08:00
l0ng-ai 256d77c3f6 fix(editor): move Go switch cases and Kotlin when branches as a whole (#5112)
Move Statement (⌘⇧↓/↑) on a branch header:

- **Go** `case 1:`: `structural_ranges` climbed past the branch to the whole `switch` (a `case` keyword's ancestors are not direct children of a block until the switch). With no sibling, the line-based fallback ran and moved `println("one")` above every label, breaking the switch.
- **Kotlin** `1 -> …` in a `when`: the statement was the whole `when`, so nothing moved.

`LangKinds` gains `clauses` (Go `expression_case`, `default_case`, `type_case`, `communication_case`; Kotlin `when_entry`). In `structural_ranges`, a branch reached from its header is the statement, and its neighbours are only other branches (never the switch subject `x`). Statements inside a branch are unchanged. On the frontend, `planMoveStatement` trims the line breaks a node may end with: Go branch ranges run to the next line's start, which made `ownsLines` reject them and fall back again.
2026-11-22 11:31:54 +08:00
Ernstjan FreriksandEjaYF 7ec2b18b63 fix(tools): name the .NET SDK a dotnet tool needs instead of dotnet's generic error (#5076)
Installing a .NET tool (csharp-ls, FsAutoComplete) on a machine whose newest SDK is older than the one the tool targets failed with dotnet's generic "NuGet feed cannot be accessed" hint.

Before installing, the IDE reads the newest SDK from `dotnet --list-sdks` and the target framework of the package's releases from the nuget.org catalog. If the latest release needs a newer SDK, it installs the newest stable release that runs on the installed one and logs why; if none of the 20 newest does, it fails naming the SDK version required. When nuget.org can't be reached it installs as before, and a failed install now quotes dotnet's `error NUxxxx` lines.

Co-authored-by: EjaYF <[email protected]>
2026-11-22 11:30:34 +08:00
l0ng-ai f8ec222a0d fix(run): integrate the Run Anything command field into the popup (#5111)
The Run Anything command field now sits directly on the popup surface. A single inset divider shows keyboard focus. The command row is 14 px shorter, giving the scrollable results the extra space in short windows.
2026-11-22 11:29:49 +08:00
l0ng-ai aad0573fb9 fix(refactor): introduce a Go variable where gopls offers only a constant (#5110)
⌥⌘V on `1 + 2` in `println(1 + 2)` (Go) answered "Selected block should represent an expression". gopls 0.24 offers only **Extract constant** (`refactor.extract.constant`) for a constant expression — checked with a small LSP script against the installed gopls: both `only: ["refactor"]` and `["refactor.extract"]` return just that action. No action mapped to Introduce Variable, and the syntax-based fallback deliberately stands back when a running server answers nothing (`reason: "empty"`).

When the server's answer contains another introduce-kind extraction for the selection, the server evidently takes it for an expression, so `runRefactoring` now calls the fallback with a new reason `otherKind`, which builds the variable from the syntax tree (`value := 1 + 2`, as GoLand does). An empty answer otherwise still means no fallback.
2026-11-22 11:28:17 +08:00
l0ng-ai 8ea0052a7f fix(editor): continuation indent after a Kotlin when arrow or assignment (#5109)
In Kotlin, Enter after `1 ->` in a `when` (with the body still to come) or after `val answer =` kept the line's indentation (8 and 4 spaces) instead of continuing one level deeper (12 and 8), as IDEA does. Kotlin uses CodeMirror's legacy C-like mode, whose indentation does not know either construct.

An indent service for the Kotlin mode (`EXTRA_SUPPORT` in `languages.ts`) adds one level after a line ending in `->` or in an assignment `=` (not `==`, `!=`, `<=`, `>=`), with nothing after the caret and no bracket left open.
2026-11-22 11:25:27 +08:00
l0ng-ai b20e0b0902 fix(editor): continue Rust /// documentation comments on Enter (#5107)
Enter after `/// Summary` above a Rust function gave a blank line: `enterInLineComment` only splits a comment when text follows the caret, so at the end of the line nothing continued the documentation. RustRover (and Rider for C#) continue documentation line comments.

`enterAfterDocLineComment` handles Enter at the end of a `///` line (Rust, C#, Dart, Swift, F#) or a Rust `//!` line: the next line gets the same indentation and prefix, caret after `/// `. Plain `//` comments and `////` banners are unchanged, as is Enter in the middle of a comment (still split by `enterInLineComment`).
2026-11-22 11:21:28 +08:00
l0ng-ai e3fca1bb6f fix(editor): keep the caret where the comment commands put it (#5106)
Two caret problems with the comment commands, seen in Go, Rust and Kotlin:

- **⌘/, Undo, Redo**: the comment came back but the caret went to the line above (L2 instead of L3). As with Delete Line and Move Statement, CodeMirror's history maps the pre-command caret through the change on Redo unless a selection was recorded after it; `commentLine` now records its resulting caret (and keeps its repeated-⌘/ detection on the state after that).
- **⌥⌘/ on a blank line without a selection** inserted `/*  */` with the caret before it. It now inserts the language's empty block comment with the caret between the delimiters (`/* | */`); lines with code keep the existing behaviour.
2026-11-22 11:18:58 +08:00
l0ng-ai bfea07a30e fix(editor): keep a Rust lifetime's apostrophe single (#5105)
With quote pairing on, typing `'a` between `<>` in `fn borrow<>() {}` gave `fn borrow<'a'>() {}`, and `&'a` got a stray quote too: `closeBrackets()` pairs `'` wherever no word character precedes it, and Rust's apostrophe also starts lifetimes.

`rustLifetimeQuote` (an input handler for Rust, under the Insert pair quote option) inserts a single `'` where a lifetime goes: after `<`, `&` or `+`, and after `,` or `:` inside angle brackets (`<'a, 'b>`, `<T: 'static>`). Lifetimes earlier on the line are ignored when counting brackets. A char literal (`let c = '`, `f('a', '`) still pairs.
2026-11-22 11:17:13 +08:00
l0ng-ai 4d5648c38d fix(editor): add the parameter list when completing a bare function header (#5104)
Complete Current Statement (⌘⇧↵) after `func f` (Go), `fn f` (Rust) or `fun f` (Kotlin) produced `func f {` / `|` / `}`: a body without a parameter list, which does not compile. A header that names a function (after any modifiers such as `pub async`, `private suspend`, and optional type parameters) but has no `(` yet now gets `()` before the body; the caret goes into the body as before. `pub async fn …` is now recognised as a block head too.
2026-11-22 11:15:17 +08:00
l0ng-ai fbcbfb648c fix(vcs): align Git Log commit message typography (#5103)
Git Log now uses the editor's configured font, size, and weights for commit subjects and descriptions. Authors, dates, branches, and signatures use smaller UI text and tighter spacing. Long metadata can wrap inside the details pane.
2026-11-22 11:14:45 +08:00
Charlie.Weiandcharli117 bf2478934e feat(plugins): deliver caret-moved events (API 1.15) (#5119)
Plugin API 1.15 adds a caret-moved event through the existing events.other channel (no WIT interface or signature change): {path, line, col, settled} with 0-based UTF-16 positions for the focused editor. The frontend batches caret moves after 120 ms (only the latest position per file) and sends one settled event 600 ms after the caret rests; queued and delayed events are dropped when the editor, document, path or project changes. editor-focused now carries the focused editor (path, language, selections) through an optional argument on plugin_set_active_file, which the remote adapter forwards. Requires the events capability; components and fixtures are rebuilt for 1.15.

Co-authored-by: charli117 <[email protected]>
2026-11-22 10:43:27 +08:00
l0ng-ai 8f252398fe fix(debugger): adapt frames and variables to side docks (#5102)
The Debug tool window puts the call stack above Variables when docked on either side, giving both panes the full dock width; in the bottom dock the panes sit side by side. Each orientation remembers its divider position.
2026-11-22 10:35:18 +08:00
l0ng-ai 54c7cbc3b0 fix(problems): adapt the preview to the dock position (#5099)
In a side dock, Problems puts the severity and navigation toolbar above the list and the source preview below it, both at the full dock width; in the bottom dock the list and preview sit side by side. Each orientation remembers its divider position.
2026-11-22 10:08:12 +08:00
l0ng-ai 1fd9246ccc fix(structure): put tree controls in the tool window header (#5097)
The docked Structure tree starts directly below the tool window header, gaining 32 px of vertical space. The header's View Options menu groups sorting and member filters, and the existing Options menu holds Expand All, Collapse All and the two source-following commands.
2026-11-22 09:45:38 +08:00
l0ng-ai 7b6ac0d5a8 fix(run): keep session tab controls visible in narrow panels (#5096)
Run session tabs fit the available space in the tool window header. Long names shorten to keep the close or pin button visible, and hovering shows the full name and, for completed runs, the duration and exit code.
2026-11-22 09:24:47 +08:00
l0ng-ai d764f9cae1 fix(search): keep distinguishing folders visible in search results (#5095)
Search Everywhere shortens long directory paths before the last folder in Files and Classes, so same-named results stay distinguishable; hovering shows the full directory. File names keep their extensions visible when the name fits on the row.
2026-11-22 08:59:37 +08:00
Muuandmuutot 3908b70b61 fix(ui): match JetBrains compact Tree.border insets (#5100)
Compact Mode reduced tree row height and the island gap, but the tree's horizontal inset stayed at 6px, leaving compact trees 2px wider on each side than JetBrains' compact Tree.border (2,8,2,8). The --tree-inset token now steps 6px → 4px in Compact Mode, so island gap plus inset is 12px normally and 8px compact.

Co-authored-by: muutot <[email protected]>
2026-11-22 08:50:19 +08:00
l0ng-ai c1f0a85718 fix(diff): keep status and viewer tools together (#5094)
The single-file diff toolbar keeps the comparison status beside Settings and the other viewer tools, in a group that can wrap to a second row so longer comparison messages stay readable. At toolbar widths of 520 px and below, the viewer layout, collapse and synchronized scrolling commands are available from Settings.
2026-11-22 08:37:37 +08:00
l0ng-ai acdd88f0f7 fix(debugger): group variable and watch context menu actions (#5093)
The debugger variable menu groups Set Value with Copy Value and Copy Name, and watch creation and field watchpoints get their own group when available. The watch menu puts Remove Watch and Remove All Watches first, above value and source commands.
2026-11-22 08:15:54 +08:00
l0ng-ai 1f8c869293 fix(vcs): group Commit changes menu actions by workflow (#5092)
The Commit changes menu leads with Commit, Rollback and Move to Another Changelist in the change-list workflow, and with Stage and Unstage in staging mode. Diff, source and path-copy commands are grouped together, and the two patch commands sit next to each other.
2026-11-22 07:53:31 +08:00
l0ng-ai f3928b3553 fix(terminal): organize the output context menu (#5091)
The terminal output menu puts Find and session commands first, then groups Copy, Paste and Select All above Clear Buffer and the split commands. Find opens the search bar with the selected text as the query.
2026-11-22 07:31:15 +08:00
l0ng-ai 5161d266ab fix(console): give the search field more room in narrow panes (#5088)
The console search field no longer shares a row with its matching options in a narrow dock: below 224 px the clear and matching controls move below the query. The match count uses the small UI font with tabular digits and sits beside the previous and next buttons.
2026-11-22 07:11:38 +08:00
l0ng-ai b30b30311f fix(workbench): keep toolbar controls readable in narrow windows (#5087)
The main toolbar shares the available text width between labels, so long project and run configuration names give up space before short branch names. At the minimum window width, dropdowns with leading icons show just those icons with their tooltips, while Run, Debug and the window buttons keep their hit targets.
2026-11-22 06:47:40 +08:00
l0ng-ai c9c6d87a14 fix(vcs): group Git Log commit context menu actions (#5086)
The Git Log commit menu puts revision copying and patch creation at the top, then separates comparison from operations that change the repository. Cherry-pick sits with the other commit operations, parent and child navigation sit together, and both bookmark actions share a group.
2026-11-22 06:17:56 +08:00
l0ng-ai 97ffd9aae9 fix(project): group Project view context menu actions (#5084)
The Project view puts Rename beside Refactor and Delete, with a separate group for Reformat Code and Optimize Imports. Jump to Source follows the clipboard actions; Local History, Git and Reload from Disk share a group, and comparison is separated from directory roles and file colors.
2026-11-22 05:58:37 +08:00
l0ng-ai 5e39650886 fix(editor): organize the editor tab context menu (#5081)
The editor tab context menu puts Close All Tabs beside Close Other Tabs, followed by the more specific close commands. Copy Path/Reference gets its own group above the splits, each split sits beside its split-and-move action, and pinning, opening a new window and configuring tabs share a group.
2026-11-22 05:42:00 +08:00
l0ng-ai 444c315d57 fix(platform): paste the primary selection only over editable content on Linux (#5089)
WebKitGTK pastes the primary selection on a middle-button release into the focused editable, wherever the release lands, so closing a tab with a middle click pasted into the active editor (and a middle click on a tree, tool window or the terminal did the same). Middle-button releases outside editable content now cancel that paste; a middle click in the editor or a text field still pastes.

Fixes #5079
2026-11-22 05:23:22 +08:00
l0ng-ai a4bea25ae3 fix(editor): group clipboard, search and open actions in the context menu (#5080)
The editor context menu keeps Cut, Copy, Paste and Copy / Paste Special together, with clipboard shortcut labels that follow the host platform. With a selection, Find in Files sits with the other search and navigation actions, and Split Right sits next to Open In, above Local History and Git.
2026-11-22 05:23:10 +08:00
Emir 84b1770da4 feat(i18n): detect the system language on first launch (#5082)
When the global settings.toml is missing, OpenIDEA now saves the OS's preferred UI language (NSLocale on macOS, GetUserPreferredUILanguages on Windows, LC_ALL/LC_MESSAGES/LANG elsewhere) as appearance.locale, mapped to one of the shipped UI languages with English as the fallback, and loads that catalog before the workbench renders. An existing settings file keeps its saved language. The mapping lives in ide-workspace next to the settings store, and a test keeps its locale list in step with the frontend's.

Co-authored-by: laot7490 <[email protected]>
2026-11-22 05:23:06 +08:00
arookieofc-ai 88295ecca8 fix(e2e): track tightened status bar height in compactMode sizes (#5083)
#5037 tightened the standard status bar to 30 px; the Compact Mode e2e still expected 34 px for the normal density.
2026-11-22 05:17:47 +08:00
l0ng-ai e87aee5969 fix(editor): make the Expressions chooser compact and readable (#5077)
The Expressions chooser uses one compact column for both the refactoring action and the syntax fallback. Multiline candidates show their first source line followed by an ellipsis, while selecting a row still highlights and uses the full expression; the highlight clears when filtering leaves no active row.
2026-11-22 05:02:33 +08:00
l0ng-ai 84d8be1181 fix(window): show minimize and maximize on Linux without a desktop session (#5085)
With no desktop session (WSLg, a bare compositor) GTK reports its built-in decoration layout, close only, so the frameless title bar had no way to minimize or maximize the window. The desktop's gtk-decoration-layout is now used only when a desktop session is running (XDG_CURRENT_DESKTOP, XDG_SESSION_DESKTOP or DESKTOP_SESSION); otherwise the title bar shows minimize, maximize and close.

Fixes #4421
2026-11-22 04:42:35 +08:00
l0ng-ai 27cbdb1ba6 fix(editor): preview changes in the Unwrap or Remove chooser (#5075)
The Unwrap/Remove chooser uses a compact list of action names. The selected action previews the kept and removed code in the editor; switching rows leaves the caret and scroll position in place, and Escape dismisses the chooser and clears the preview.
2026-11-22 04:42:22 +08:00
l0ng-ai 1005dc1363 fix(editor): lay out inline refactoring names as a lookup list (#5072)
Inline refactoring name suggestions align with the identifier being edited. Rows follow the editor font and zoom, with a separate footer for the shortcut; the list fits inside the editor and scrolls to keep the active suggestion visible.
2026-11-22 04:25:59 +08:00
l0ng-ai 3f3cdeba0d fix(editor): make the Generate chooser compact and scannable (#5069)
Generate now uses the compact, caret-anchored action chooser. Constructors, accessors, overrides and tests get distinct icons at the standard action-list size, and the chooser keeps its width while typing to filter.
2026-11-22 04:03:48 +08:00
l0ng-ai 9b8c88e1ee fix(editor): show the opening line of offscreen scopes (#5068)
When the caret reaches a closing delimiter whose opener is above the viewport, the opening line of that scope (with the declaration above a brace on its own line) is shown at the top of the editor after a short pause, in the editor's font, line numbers and colours. Caret and scroll stay put; it follows the brace highlighting setting, closes on Escape, and stays hidden when Sticky Lines already shows the opener.
2026-11-22 03:42:22 +08:00
l0ng-ai 392574fe2a fix(ui): don't show a scrollbar over content that fits after a resize (#5016)
A scroll range of one pixel or less is WebKit rounding after a resize (a splitter drag leaves scrollHeight 319 over clientHeight 318), not content: the overlay scrollbar and the editor scrollbar thumb no longer show for it.
2026-11-22 03:40:25 +08:00
l0ng-ai 41829e74db fix(editor): keep inline hints aligned with source text (#5066)
Inline hints use a size one pixel under the editor font, sit on the text baseline with even padding, and stay a single label when lines wrap, so they no longer shift or split around the source text.
2026-11-22 03:16:31 +08:00
l0ng-ai aee21233fb test(lsp): pass a lazy action's resolve data as a string (#5078)
CodeAction.data is serialized JSON on the IPC boundary; the test added in #5074 gave it an object, which pnpm typecheck rejects.
2026-11-22 03:04:29 +08:00
l0ng-ai 17f5889037 fix(diff): make collapsed unchanged lines easier to find and expand (#5065)
Collapsed unchanged lines in the diff viewer are now a full-width button: a chevron, the line count in UI type and a hatched rule in the separator colour, with hover and focus states. Clicking it or pressing Enter expands the range in both panes and returns focus to the editor.
2026-11-22 02:57:36 +08:00
l0ng-ai ff6c6eb13f fix(editor): restore the caret of Move Statement on Redo (#5063)
Redo of Move Statement Up / Down left the caret where the move started: CodeMirror's history maps the selection from before the edit through it unless the command records the selection after. Both the structural and the line-based move now record the caret they set, so Undo / Redo put it back.
2026-11-22 02:50:09 +08:00
l0ng-ai ac015847a3 fix(editor): remove unused imports in Optimize Imports for TypeScript (#5062)
Optimize Imports in JavaScript / TypeScript now removes unused imports first: typescript-language-server's organize imports only sorts and merges them, and removing the unused ones is its own source.removeUnusedImports action. Optimize-imports-on-save does the same.
2026-11-22 02:46:43 +08:00
l0ng-ai 4c774d2e8e fix(refactor): find TypeScript extractions for Introduce Variable and Extract Method (#5061)
typescript-language-server answers code actions with refactorings only when `only` contains a kind that contains `refactor`; asked for `refactor.extract` it returned nothing, so Introduce Variable and Extract Method refused the selection. JavaScript / TypeScript now ask for `refactor`; the actions are still mapped by their own kind, and other servers keep the narrow kind.
2026-11-22 02:43:04 +08:00
l0ng-ai 8adbbd1b05 fix(lsp): apply refactorings that resolve their edit lazily (#5074)
TypeScript Introduce Variable, Extract Constant and Extract Method did nothing with vtsls: its refactoring actions carry resolve data and a follow-up command but no edit, and an action was only resolved when it had no command either. The resolved edit then failed on a create of the edited file marked ignoreIfExists, which the conversion dropped.

- Resolve an action without an edit whenever it carries resolve data (interactive path and lsp_apply_code_action).
- Leave out create / rename operations their ignoreIfExists makes no-ops, and deletes their ignoreIfNotExists does.
2026-11-22 02:41:50 +08:00
l0ng-ai c207e57686 fix(editor): preview folded code on hover (#5060)
Hovering a folded region's placeholder shows the folded lines in a tooltip: highlighted as in the editor, with line numbers when the gutter shows them, up to 80 lines, aligned to the pane edge. It closes on Escape, scroll or a fold change. The sticky-lines renderer shares the line rendering.
2026-11-22 02:36:02 +08:00
l0ng-ai ac0a56d1ec fix(editor): show font size feedback when zooming (#5059)
Wheel or keyboard zoom now shows the current font size at the bottom of the editor pane that changed, with Reset Font Size and a link to Editor > General. It stays while hovered or focused and dismisses after five seconds; LightEdit gets the same reset.
2026-11-22 02:32:38 +08:00
l0ng-ai 07cbb560df fix(agents): give agents every root of a multi-project workspace (#5071)
A task's agent only learned its own directory, so in a workspace with attached projects it missed the other projects and left their part of a change undone.

- Sessions pass the workspace's other roots (the project and the trusted attached projects, minus the task's own directory and project) as ACP additionalDirectories to agents that advertise the capability.
- The Codex shim turns them into runtimeWorkspaceRoots on thread start, resume and fork, so workspace-write covers them and the model is told about them; the Claude Code shim passes each as --add-dir.
- New read-only MCP tool get_workspace_roots lists the roots, and the server instructions point to it for workspace questions and changes that span projects.

Fixes #5058
2026-11-22 02:17:09 +08:00
l0ng-ai 88936106ab feat(editor): documentation stub tags for TypeScript and Python docstrings (#5057)
Insert documentation comment stub filled tags in for PHP only.

- **JavaScript / TypeScript**: `/**` + Enter above a function declaration, method, constructor or arrow function assigned to a `const` now lists `@param name` for each parameter (parameter properties, rest and defaulted parameters included) and `@returns` when a non-void result type is declared. Calls and statements get no tags.
- **Python**: Enter between the quotes of a `"""` (or `'''`) opened on the first line under a `def` expands it into a docstring, as PyCharm does with its default reStructuredText format: the summary line, `:param name:` per parameter (`self` / `cls` skipped, `*args` / `**kw` by name) and `:return:` (not for `__init__` or `-> None`), then the closing quotes.

Both follow the existing Smart Keys › Insert documentation comment stub option.
2026-11-22 01:56:46 +08:00
l0ng-ai 78041f3745 fix(editor): complete arrow functions, open brackets and Python headers (#5056)
Complete Current Statement (⌘⇧↵) in TypeScript and Python (both use the text rules in `completeStatementSpec`):

- `const f = (x: number) =>` became `=>;`. An arrow function now gets a block body, followed by the brackets still open and a `;` where the statement needs one: `=> {` / `|` / `};`, `items.map((x) => {` / `|` / `});`.
- `const obj = { name: "Ada"` became `{ name: "Ada";`. Brackets the line opened and left open are now closed before the `;` (`{ name: "Ada" };`, `foo(a, bar(2));`); a line ending in `,` or `{` is left to continue.
- Python `async def …`, `with …`, `except …`, `case …`, `match …`, `async for …` got no `:`. Every compound statement header now gets one; `match = 5` and `case.x` stay statements.
2026-11-22 01:56:40 +08:00
l0ng-ai d0eeb5e8c3 fix(editor): type over a closing bracket that already closes a pair (#5054)
`closeBrackets()` steps over a closer only when it inserted that closer itself during the session. So with `value = (1 + 2|)` in a reopened file (or code pasted / written earlier), typing `)` gave `(1 + 2)|)`; same for `]` and `}`. IDEA types over a closing bracket that already closes a pair.

`skipClosingBracket` (an input handler next to `skipClosingQuote`, under the Insert pair bracket option) steps over the bracket at the caret when the syntax tree matches it to an opener and the line has no more openers than closers of that kind outside strings; otherwise the bracket is inserted (`f(g(x|)` still gets its missing `)`). Multi-line pairs (`foo(` … `)` on a later line) are stepped over too.
2026-11-22 01:52:21 +08:00
l0ng-ai 5a9783dbf0 fix(workbench): keep tool window header actions in view (#5053)
Tool window titles and tabs give up width before the header actions, so Options and Hide stay at the right edge of a narrow pane. A shortened title keeps its full text on hover. When the contributed controls need more room, their strip scrolls independently while Options and Hide stay in place.
2026-11-22 01:51:01 +08:00
l0ng-ai 74c2757a7a fix(editor): dedent after return and realign bare except: in Python (#5052)
Two Python indentation gaps against PyCharm:

- Enter after `return 1`, `pass`, `raise …`, `break` or `continue` kept the block's indentation. The dedent rule existed only in `fallbackIndent`, which steps aside when a language mode is loaded (Python has `@codemirror/lang-python`). An indent service for Python now applies it: one level out, unless a bracket is still open (`return foo(`) or text follows the caret.
- Typing a bare `except:` inside a `try` body left it indented: the stock `indentOnInput` pattern and `Body` rule only know `except ` with a space. `except:` now triggers reindentation and aligns with its `try:` (or a previous `except`).

Both are added through `EXTRA_SUPPORT` for the Python mode (`src/editor/core/cm/languages.ts`).
2026-11-22 01:50:44 +08:00
l0ng-ai ff6187ebf9 fix(editor): pair backticks, Python prefixed strings and triple quotes (#5051)
`prefsExtension` gives `closeBrackets()` its own pairing list (to honour the Insert pair bracket / quote options), and that list replaced the language's: only `( [ { ' "`. So:

- TypeScript / JavaScript: typing `\`` left the template literal open;
- Python: `f"`, `r'`, `b"`… left the string open (the language's `stringPrefixes` were dropped), and `"""` did not close.

The list now adds the backtick for JavaScript, TypeScript, Vue, Svelte, Astro and Go, and Python's `'''` / `"""` with its string prefixes; the two options still switch brackets and quotes off.
2026-11-22 01:48:28 +08:00
l0ng-ai 708ceac09a fix(editor): keep editor banner messages and actions readable (#5050)
Editor notification bars group their action links and let the message wrap at the width of the editor pane. Links stay on the same row when there is room and wrap below the message in narrower splits. The banner uses the UI text size and has smaller vertical insets in Compact Mode.
2026-11-22 01:47:53 +08:00
l0ng-ai 5ba43e93e5 fix(services): load container logs in batches and keep their colours (#5067)
Docker logs reached the webview one IPC message per line; WebView2 delivers each message on its own, so a 1000-line tail took 10-40 s on Windows. ide_docker::logs now collects lines for 30 ms and sends them together from a second thread, so a quiet log still flushes, and docker_logs streams Vec<DockerLogLine>. The log pane (container and plugin service logs) renders ANSI colours instead of stripping them, takes the Console log level colours like the Run console, and has Scroll to End.

Fixes #5049
2026-11-22 01:36:39 +08:00
l0ng-ai c552183924 fix(editor): restore the caret of Delete Line on Redo (#5047)
Delete Line (⌘⌫), Undo, Redo: the line was deleted again, but the caret ended at the end of the line above instead of where the deletion had put it (the next line, same column). CodeMirror's history restores, on Redo, the first selection recorded after the change, and otherwise maps the pre-change caret through it; Delete Line set its caret in the same transaction, so nothing was recorded and the old caret (inside the deleted line) mapped to the previous line end. `deleteLine` now dispatches its resulting selection once more, which the history records as the selection after the edit.
2026-11-22 01:16:55 +08:00
l0ng-ai f2adcccf2a feat(editor): fill the Java documentation stub with its tags (#5045) 2026-11-22 01:16:49 +08:00
l0ng-ai 158d11bd7f (#5044)
Copy Path/Reference opens at 500 px when space permits. Each row places the action and shortcut before the right-aligned path preview. Long paths keep the filename in view, and dragging the popup edge gives them more room.
2026-11-22 01:16:32 +08:00
l0ng-ai c6de070cba fix(editor): split a string literal on Enter instead of breaking it (#5043)
Enter inside a Java string (`String t = "hello|world";`) inserted a raw line break into the literal, leaving code that does not compile. A new Enter handler (`enterInStringLiteral`) splits a one-line string literal into two joined with `+`, the second on a continuation-indented line with the caret after its opening quote:

```java
String t = "hello" +
        "|world";
```

It applies in Java, C#, Kotlin, Groovy, JavaScript and TypeScript (the literal's own quote in JS/TS), with IDEA's default continuation indent (two levels for the JVM languages and C#, one for JS/TS). Text blocks, template literals, a caret inside an escape (`\\|n`), char literals, multi-line literals and other languages keep the plain newline.
2026-11-22 01:16:04 +08:00
l0ng-ai 42b9106ade fix(editor): undo Introduce Variable in one step (#5040)
After Introduce Variable (⌥⌘V) and Enter on a suggested name, one Undo only put the server's placeholder name back (`value` → `extracted`); the reformatting and the extraction each needed another Undo. The refactoring is made of several transactions (the server's workspace edit, `reformatGenerated`, the in-place rename) and each was its own history event.

A small history group (`src/editor/lsp/historyGroup.ts`) keeps the transactions in between out of the undo history and, when it closes, records the net change once. `applyIntroduceAction` opens it before applying the server action and closes it when the in-place rename ends (new `onEnd` on the session), or right away if no rename starts. One Undo now restores the original expression, and Redo brings the whole refactoring back.

Escape during the rename keeps the introduced variable with its current name, as the hint says and as IDEA does; that part of the report is not changed.
2026-11-22 01:04:48 +08:00
l0ng-ai 92a49f19af fix(editor): keep the keyboard in the editor after closing the focused tab (#5039)
Closing the focused editor tab with ⌘W (or its close button) showed the next tab, but `document.activeElement` became `<body>`: arrow keys and typing did nothing until the editor was clicked. `closeTab` removed the tab without giving the focus to the editor that took its place. It now does so when the closed editor had the focus (a tab closed while focus is elsewhere leaves focus alone).
2026-11-22 01:04:18 +08:00
l0ng-ai f58e6d1259 fix(editor): complete Java block heads and open strings with Complete Current Statement (#5038)
Complete Current Statement (⌘⇧↵) in Java added a `;` where a block was meant, because tree-sitter's error recovery reports a missing `;` after an unfinished head and the structural pass inserted it:

- `if (true)` → `if (true);` (the next statement then runs unconditionally)
- `public class App` / `public void run()` → `…;`
- `String m = "hello` → `"hello;` (the `;` inside the open string)
- `for` → `for { }` (the text rules only knew keyword-led heads)

Now a finished block head (balanced brackets, not followed by an Allman `{` line) and an open string skip the parser's `;` and go to the text rules, which:

- recognise type declarations behind modifiers/annotations and Java / C# method and constructor headers (`abstract` / `native` methods keep the `;`; `return` / `throw` / `new` lines and plain calls are statements);
- give a bare `if` / `for` / `while` / `switch` / `catch` its parentheses with the caret inside (`for (|) {` / `}`) in languages with parenthesised conditions;
- close an open string or char literal before the `;` (Rust's `'a` is a lifetime, not a quote).
2026-11-22 01:04:12 +08:00
l0ng-ai 13a2356fa1 fix(workbench): tighten status bar height and widget spacing (#5037)
The status bar uses one 30 px row in the standard density and a 24 px row in Compact Mode. Adjacent widgets use their existing insets for spacing, which gives the editor and its status controls a little more room.
2026-11-22 00:58:32 +08:00
Mr0Bread 002751e524 refactor(agents): remove CSS rules nothing reads (#5055)
Three CSS rules in the agents feature can never apply, so they only add to the files:

- `ReferenceChip.module.css` `.selected`: no `styles.selected` (or `chipStyles.selected`) anywhere in `src/`.
- `SkillsPage.module.css` `.link` and `.link:hover`: `SkillsPage.tsx` never reads `styles.link`.
- `Session.module.css`: the first `.questionChoices` block (`display`, `flex-direction`, `gap`) is overridden property-for-property by the second `.questionChoices` block later in the file (same selector, same specificity, no media query), so the computed style is unchanged.

22 lines removed, no behaviour change.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-22 00:52:31 +08:00
l0ng-ai ac87278ddd fix(welcome): separate project names, locations and branches in the switcher (#5035)
Project names now have a line of their own in the title bar project switcher, so a long Git branch can no longer crowd out the name. The path and branch use the smaller metadata type size. Remote projects show their host and folder on separate lines, with keyboard search highlighting each match in its corresponding line.
2026-11-22 00:52:24 +08:00
l0ng-ai a62d4d11c3 fix(editor): indent the line after Complete Current Statement like the statement (#5028)
Complete Current Statement (⌘⇧↵) on `String a = "123"` added the `;` but put the caret on a new line one continuation indent deeper (12 spaces instead of 8). `completeStatementSpec` asked for the new line's indentation before inserting the `;`, when the parser still saw an unfinished statement. The indentation is now computed on the line with the `;` in place.
2026-11-22 00:52:18 +08:00
l0ng-ai 0164e82e32 fix(run): group test navigation and display options (#5027)
The test results toolbar groups its filters together and moves Previous and Next Failed Test into More Actions, where the shortcuts are shown next to their labels. Test Runner Options can hide row durations to give long test names more room. The choice is remembered across sessions and the test summary and selected output remain visible.
2026-11-22 00:52:11 +08:00
l0ng-ai edb8f69024 fix(editor): finish Introduce Variable on a double-clicked name suggestion (#5026)
During Introduce Variable, the name suggestions listed under the new variable reacted only to a single press: a double click put the name in but left the refactoring open, so it looked like double click did nothing. A double click now puts the name in and finishes, as Enter does (a single click still only puts it in). The list and its hint used the hand cursor; they now show the arrow, as other editor popups do.
2026-11-22 00:52:05 +08:00
l0ng-ai ccfa4a1f22 fix(run): show why Profile or Run with Coverage did not start (#5025)
With the Run notification group set to not show balloons (Settings › Notifications, or Don't Show Again on a Run notification), clicking Profile '…' / Allocations / Live Objects or Run with Coverage looked like it did nothing: the reason the run could not start (async-profiler or the coverage tool is not installed, the configuration is not supported, preparing it failed) went only to the Notifications list. These notifications answer a command the user just ran, so they are now `userInitiated` and always show as a balloon, like a manual update check.
2026-11-22 00:51:58 +08:00
l0ng-ai 8eb332aba7 fix(new-project): flag a taken folder and remember the location (#5024)
New Project accepted the name of a folder that already exists and has files, and only reported "already exists and is not empty" in the progress view after Create. It now checks as the name or location changes: the name field and its hint turn red and Create is disabled. Until the user types a name, it follows the first free `untitled`, `untitled1`, … in the location.

The location always started at the home folder (unless Default Project Directory was set). It now starts where the last project was created; the Default Project Directory setting still comes first.

The check is the one `scaffold_create` already did, moved into `ide_scaffold::target_taken` and exposed with `free_name` as `scaffold_target_taken` / `scaffold_free_name`.
2026-11-22 00:51:52 +08:00
l0ng-ai 0798582173 feat(markdown): add a stacked editor and preview layout (#5023)
Markdown can display the editor above its live preview so both use the full width of a narrow editor group. Choose Side by side or Stacked under Preview layout in Markdown settings. Each layout remembers its own divider position, and existing side-by-side sizes are restored when switching back.
2026-11-22 00:51:45 +08:00
l0ng-ai 46883c413c feat(welcome): show Remote Development as a header button (#5021)
Remote Development was hidden in the welcome page's More Actions menu, with the same folder icon as Open; New File used the same plus as New Project. Remote Development is now a header button next to Clone Repository with a new server icon, and New File has a new page-with-plus icon (both icons apply wherever these actions appear). Header buttons no longer cap their width, which cut "Remote Development" to "Remote Develo…"; they collapse to icons below 740px.

The Remote Development dialog's rows ended at different edges because Configure… is wider than Browse. The form is now a two-column grid: fields share the first column and side buttons the second, and its horizontal padding matches the dialog footer, so fields, side buttons and Cancel / Open line up.
2026-11-22 00:51:38 +08:00
l0ng-ai 840dddb897 fix(editor): fit long single-row tabs inside narrow splits (#5020)
A long file name in a single-row editor split could push the selected tab's close button outside the visible strip. Single-row tabs now constrain the label to the available width and keep the close button beside the shortened name. The hidden tabs picker still opens tabs outside the visible strip.
2026-11-22 00:51:33 +08:00
l0ng-ai ae51e195a5 fix(vcs): reorder the annotation gutter context menu (#5019)
Right-clicking the annotation gutter showed Show Commit in Git Log first and Close Annotations last, below Options. The menu now starts with Close Annotations, then Show Diff and Copy Revision Number; after a separator come the revision actions (Annotate at Revision…, Annotate Previous Revision, Show Commit in Git Log, Ignore This Commit), and Options is last. On an uncommitted line the menu is Close Annotations, Options.
2026-11-22 00:51:26 +08:00
l0ng-ai 205be89d4e fix(terminal): keep the selected session tab visible in narrow panes (#5017)
A long terminal session name could take more space than its tab strip and push the close button out of view. Each tab now fits the available width, with an ellipsis for long labels and the full name on hover. New Tab and the terminal options sit next to the strip, and the tab picker handles sessions that overflow.
2026-11-22 00:51:20 +08:00
l0ng-ai ece9c7ef73 fix(project): keep file refactoring changes visible in the preview (#5013)
File refactoring previews give each file a distinct header with its directory and occurrence count. Each code excerpt starts near the changed text and can wrap in a narrow window. The reference count and confirmation buttons stay visible as the list scrolls, and excluded files have a struck-through file name.
2026-11-22 00:51:13 +08:00
Emir fe55a73e97 style(app): redesign welcome and plugins page (#4999)
The plugin details page groups version, downloads, author, categories and the ID / homepage / mail / signer fields so they are easier to scan, with translated labels. The Welcome sidebar uses a larger logo and full-width navigation rows; danger menu items tint their icons.

Co-authored-by: laot7490 <[email protected]>
2026-11-22 00:39:07 +08:00
Vladislav Kuzmin 65b0cc45f0 feat(database): choose tree visibility from row counts (#4824)
The count on a Database tree row opens a searchable chooser for what that row shows, without opening Data Source Properties: PostgreSQL source rows choose databases and database rows choose schemas (each database inherits the source rules until overridden, stored as schemasByDatabase); ClickHouse keeps a flat database list. A visibility-only save updates the rules against the latest saved file and keeps the connection and loaded metadata, while wildcard rules and names the server did not return are preserved.

Closes #4781

Co-authored-by: principalwater <[email protected]>
2026-11-22 00:38:27 +08:00
Vladislav Kuzmin aaab9a5dc6 feat(database): select a JDBC driver from a database preset (#4607)
The General tab of a named database preset lists its built-in driver and the local JDBC profiles associated with that preset, so a local driver no longer requires switching the type to Custom JDBC; the type and tree icon stay. Manage Drivers and Go to Driver open the profile manager scoped to that type. A connection refuses a profile associated with another preset, and a JDBC password is kept apart from a Snowflake key-pair passphrase when switching transports.

Closes #4564

Co-authored-by: principalwater <[email protected]>
2026-11-22 00:37:23 +08:00
Muuandmuutot 4bc68d27cc feat(settings): Color Scheme › Diff & Merge support (#4994)
Adds a Diff & Merge page to Color Scheme with the four change types (Changed, Conflict, Deleted, Inserted: line background and error stripe mark) and the folded unchanged fragments wave. Each attribute edits the --diff-* tokens the diff viewer paints, with a live preview, and IntelliJ scheme import maps DIFF_* keys and DIFF_SEPARATOR_WAVE onto them. The theme template and token reference list the new wave token.

Co-authored-by: muutot <[email protected]>
2026-11-22 00:37:11 +08:00
Mr0Bread 50f0363669 refactor(agents): share the session MCP and skills picker chrome (#5029)
The MCP and Skills pickers in the composer share one SessionPicker for the trigger, popup header, filter, footer and row parts, and one CSS module; each picker supplies only its data and labels. The trigger's product name is passed as `brand` and shown as written, as before.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-22 00:37:06 +08:00
Mr0Bread 0ff51fdae4 refactor(agents): share the settings-page CSS between MCP servers and skills (#5030)
The rules the MCP Servers and Skills settings pages had in common move into SettingsPage.module.css; each page keeps only its own rules. No visual change.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-22 00:36:54 +08:00
Mr0Bread 7df0880dcc refactor(agents): table-drive classifyUrl and share tool-output ingestion (#5031)
GitHub and GitLab item URLs are matched through one route table, and tool output (JSON metadata and links) is ingested by one helper for both the gh-create and plain tool paths. Classification results are unchanged.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-22 00:36:50 +08:00
Mr0Bread 312559e121 refactor(editor): expose navigation providers, related providers and position helpers through editor/api (#4989)
Features import navigation/related provider registration and the offset/position helpers from `@/editor/api` instead of reaching into editor internals. No behaviour change.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-22 00:36:46 +08:00
LU XIANGRUIandwildcatDownstairs db8f9a72b0 feat(vcs): edit the compared folders in Compare Directories (#4975)
The left and right paths of Compare Directories are editable fields with a folder chooser beside each, as in IDEA. Enter, leaving the field or picking a folder compares the new pair, opened as its own tab in place of the current one; a path that isn't a folder, or the same folder on both sides, is refused with a message. The layout e2e test follows the editable fields and per-row synchronisation.

Closes #3925

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 00:17:22 +08:00
LU XIANGRUIandwildcatDownstairs 0a7a292d82 feat(vcs): synchronize compared directories with per-row operations (#4974)
Each Compare Directories row carries IDEA's synchronisation operation in the marker column: copy to the right, copy to the left, delete (one-sided entries) or do nothing; Space or a click cycles it. Synchronize Selected and Synchronize All run the operations as one batch after a single confirmation counting deletions and overwrites. The new fs_synchronize_directories command validates every path, runs the operations on the blocking pool through the existing copy/merge and delete paths (Local History, VCS delete hooks), continues past failures and returns them; cancelling stops before the next entry. The per-row operations replace the single-entry Copy to Left / Copy to Right / Delete buttons.

Refs #3925

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 00:16:19 +08:00
LU XIANGRUIandwildcatDownstairs a78d1fdc27 feat(project-view): mark folders of attached projects as excluded (#4962)
A folder inside an attached project now has Mark Directory as › Excluded (and Cancel Exclusion), written to that project's own .openidea settings so it also applies when the project is opened alone. New commands project_workspace_members and project_workspace_member_set (projectStructure.* keys of attached projects only); the existing markFolder logic computes the change. Other roles stay out of the menu for attached projects until their source and test roots are applied.

Closes #4712

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 00:13:04 +08:00
LU XIANGRUIandwildcatDownstairs 8681bfab0d feat(vcs): compare directories by content, text, size or timestamp (#4973)
Compare Directories gets IDEA's Compare by selector: Binary content (default), Text, Size, and Size and timestamp. Text decodes both files with the editor's encoding detection and ignores line separators (files over 5 MiB or binary ones fall back to bytes); Size and timestamp allows 2 s of skew. The choice is remembered.

Refs #3925

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 00:09:12 +08:00
LU XIANGRUIandwildcatDownstairs 2e7aab9ec6 feat(run): build configurations started together in one Maven run (#4963)
With Delegate IDE build/run actions to Maven, starting several Java configurations together (a Compound, or several Services rows) ran one mvn -pl <module> -am compile plus one classpath probe per configuration, one after another, rebuilding shared upstream modules each time. A launch's Maven run now also builds the modules of the launches still waiting for theirs (same reactor, scope, incremental policy and delegation) as one -pl a,b,c -am run with one classpath probe; the waiting launches reuse the recorded snapshots and classpaths. A member with JDT errors makes it a clean compile; if the shared build fails, none start and each console shows the failure. A lone launch builds as before.

Refs #3971

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 00:09:07 +08:00
LU XIANGRUIandwildcatDownstairs c08b9b8d4d feat(project): give attached projects their own excluded folders (#4960)
In a workspace with attached projects, the primary project's excluded folders were applied relative to every root (excluding gen in the primary also hid gen in each attached project), while an attached project's own exclusions were ignored. Each workspace project now keeps its own excluded folders, read from its Project Structure settings and build files, and one per-root lookup (exclude_globs_in / search_excludes_in / root_of) gives the index, file watchers, Find in Files, the Project view, the Cucumber/Spring scans and the MCP file tools that root's set. A workspace folder (container) still applies its excluded folders in every member.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 00:09:02 +08:00
LU XIANGRUIandwildcatDownstairs 81b357cdce feat(color-scheme): add Kotlin extension call, package-level call and enum entry entries (#4979)
The Kotlin page gets Identifiers › Extension function call, Package-level function call and Classes › Enum entry, as IntelliJ's Kotlin page has. Calls on an explicit receiver to top-level functions are extension calls, without one package-level calls; enum entries no longer take Constant. Each falls back to its parent until set; .icls KOTLIN_* keys fill them.

Closes #4059

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 00:08:46 +08:00
LU XIANGRUIandwildcatDownstairs 9eaa44e004 feat(color-scheme): split predefined types and functions and separate literal keywords (#4978)
Language Defaults and each language page get Identifiers › Predefined type and Predefined function next to Predefined symbol, and Literal keyword next to Keyword. The new entries show their parent until set, so existing overrides keep applying. true / false / null in the clike modes (Kotlin, Scala, Dart, Groovy, C#) are bool / null tokens taking Literal keyword instead of Constant.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 00:07:39 +08:00
LU XIANGRUIandwildcatDownstairs a3dc3c99a6 feat(color-scheme): add a JavaScript and TypeScript page with decorator and global entries (#4977)
Settings › Editor › Color Scheme gets a JavaScript and TypeScript page as in WebStorm, with Decorator and Identifiers › Global variable / Global function. A decorator's whole name takes the Decorator colour (tsserver reports it as a class), from the syntax tree before the server answers; non-local variables and functions take the global entries, library symbols stay Predefined symbol. .icls TS.* / JS.* keys land on the new page.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-22 00:06:29 +08:00
SunZhiQiang 4c19b7d5b0 fix(agents): answer AskUserQuestion in the conversation (#5034)
The open AskUserQuestion card was pinned above the composer: with several options it covered the conversation (max 50vh, its own scroll), and in a short conversation it floated away from its messages. The card now renders in the conversation at the asking entry and scrolls with it; picking an option on a single-select question moves on to the next one. Permission forms and questions that outlive their turn still wait above the composer at the composer's width.

Closes #5033

Co-authored-by: panda-student <[email protected]>
2026-11-22 00:06:25 +08:00
faysouandfaysou 85edcf0660 fix(markdown): hide code breadcrumbs in Preview Only (#5032)
Markdown Preview Only still showed the code breadcrumbs (the heading at the caret) under the rendered preview. A text editor wrapper can now report that it hides the source editor (useSourceHidden); the editor pane then drops that tab's code breadcrumbs. Markdown does so in Preview Only and keeps its heading breadcrumbs while the source is shown.

Co-authored-by: faysou <[email protected]>
2026-11-21 23:51:24 +08:00
faysouandfaysou 49dd1bbef3 perf(markdown): cut layout reads while scrolling previews (#5036)
Each preview scroll frame read offsetTop of every block to find the line at the top. The preview now indexes its blocks when the HTML changes and binary-searches them, reading offsets lazily from the live layout so reflows (zoom, images, diagrams) still count.

Co-authored-by: faysou <[email protected]>
2026-11-21 23:51:17 +08:00
faysouandfaysou aa73f4c2b9 feat(markdown): render linked footnotes in the preview (#4996)
The Markdown preview showed footnote references as raw text. A marked extension renders references as bracketed superscript links and collects (multi-line) definitions after the document body in citation order, each with return links to its citations; unresolved references and code spans stay literal.

Co-authored-by: faysou <[email protected]>
2026-11-21 23:51:12 +08:00
LU XIANGRUIandwildcatDownstairs 5375099042 feat(editor): move a ; typed before ) to the end of the statement (#4943)
Typing ; while only closing parentheses follow the caret puts it after the last ), as IntelliJ IDEA's editor.move.semicolon.after.paren does (on by default). It applies in languages that end statements with ;, and not in strings, comments, control statement heads (for, if, try-with-resources, …), declarations, annotations, or when the statement continues on the next line. Settings › Editor › General › Smart Keys has an option to turn it off.

Closes #4936

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-21 23:51:07 +08:00
faysouandfaysou 2c47bd58bb fix(vcs): group branches across linked worktrees (#5018)
Linked worktrees share one repository's branches, but the branch popup and the Git Log Branches pane listed each checkout as its own repository. vcs_roots now reports each root's branch_root (the main worktree of its common Git directory), and both views group checkouts by it while the Paths filter still scopes the log to the selected checkout. The branch menus also offer New Worktree from '<branch>'…, which preselects the branch, requires a new branch when it is already checked out, and opens the worktree in a new window.

Co-authored-by: faysou <[email protected]>
2026-11-21 23:51:03 +08:00
l0ng-ai d80aeb6e9e docs: describe ESLint, browser debugging, Bun debugging and Open In › GitHub (#5046)
The JavaScript page still said there was no ESLint integration, no browser debugging and no Bun debugging, and the GitHub page said files couldn't be opened on GitHub or linked. Document the ESLint server, the JavaScript Debug configuration, bun-dap, Open In / Copy Path/Reference… for GitHub, GitLab and Bitbucket remotes, and the TypeScript inlay hints, in English and Chinese.
2026-11-21 23:13:08 +08:00
l0ng-ai 55a5e79c9f fix(json): validate JSON files and map SchemaStore schemas for common config files (#5042)
vscode-json-language-server validates nothing unless json.validate.enable is set, so even a file's own $schema was ignored. JSON and JSONC now enable validation and map package.json, tsconfig/jsconfig, ESLint, Prettier, Babel, Lerna, Turborepo, SWC and Composer configs to their published schemas.
2026-11-21 23:09:01 +08:00
l0ng-ai df4210f529 fix(typescript): show inlay hints from vtsls and typescript-language-server (#5041)
Both servers produce no inlay hints unless their inlayHints settings ask for them, and no language config set any. TS, TSX, JS, JSX and Vue's vtsls now enable parameter names at literal arguments, inferred variable types and enum member values; Editor › Inlay Hints still decides which kinds are shown.
2026-11-21 23:08:56 +08:00
Deng Liuanddengliu 09d8e92e2c chore(dev): add an optional mise contributor toolchain (#4948)
Add mise.toml pinning Rust (with rustfmt and clippy), Node.js and pnpm, plus six tasks (setup, dev, dev:app, build, test, check) that call the existing pnpm scripts and Cargo commands, so the worktree-aware launcher is unchanged and contributors can still work without mise. Document the optional workflow in both setup guides and AGENTS.md, and raise the documented Node minimum to 22.22.2, which the locked jsdom requires on the 22.x line.

Closes #4941

Co-authored-by: dengliu <[email protected]>
2026-11-21 22:22:19 +08:00
Mr0Bread 221b6c3098 fix(ci): validate language smoke dependency triggers (#4847)
Language smoke's path filters missed inputs the smoke actually loads (src/workbench, src/ui, src/bindings.ts, editor LSP modules, vite/tsconfig, pnpm-workspace, patches, build-tools) and the crates ide-host pulls in directly (ide-search, ide-streams), so changes there skipped the smoke. Add them to the workflow paths and the Changes step patterns, and add scripts/smoke-paths.ts with a test that derives the smoke's inputs from the frontend import closure and cargo metadata and fails when the workflow misses one. CI's frontend filter now also runs on crate manifest changes, which the test reads.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-21 22:21:17 +08:00
ntbang0901 d154dce4f7 fix(app): restrict base and form targets in the workbench CSP (#4874)
The workbench CSP had no base-uri or form-action, so injected markup could add a <base> element to retarget relative URLs or post a form to any origin. Add base-uri 'self' and form-action 'none'; the workbench never uses <base> and every form handles submit in script. The plugin view CSP already sets form-action 'none'.

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 22:19:42 +08:00
l0ng-ai 83364c5423 chore: v0.1.50 2026-11-21 21:03:57 +08:00
l0ng-ai fa33819afb fix(agents): keep the model name readable in a narrow chat composer (#5015)
In a narrow composer the toolbar's first item was capped at 110px, meant for the New Task agent picker. A chat's composer has no agent picker, so the cap fell on the model control and squeezed the model name to "G…" next to its settings chip while the row had room to spare. The agent picker already shows only its icon and doesn't grow, so the cap is removed.
2026-11-21 20:59:22 +08:00
l0ng-ai 5e6a59eae8 fix(agents): pick the model from the list and set its options from one chip (#5012)
The composer's model controls had three ways into the same settings: a "High" detail next to the model chip with a half divider and no chevron, a "Low ›" entry on model list rows leading to a settings page with a back arrow, and inside it a dropdown for Codex's six effort levels — two steps to change effort. While a model's settings loaded, a "Loading model settings…" text broke the row's alignment.

Now the model chip only picks (and pins) models, and the chip next to it opens every option of the current model — effort, context size, fast mode — in one popup, each a click away: on/off as a switch, up to five values as a segmented control, more listed. A model with a single option closes the popup on a choice. The chip has a chevron like the other composer chips, and a spinner takes its place while settings load. Configuring a model other than the current one from its list row is gone.
2026-11-21 20:46:14 +08:00
l0ng-ai a9971905dc fix(navigation): prioritize existing tests in the test chooser (#5011)
The Test and Test Subject choosers give file names their own space and align directories to the right, keeping the end of long directories visible. When there are several tests, the first match is selected and Create New Test appears below the results, with a divider before it.
2026-11-21 20:38:21 +08:00
l0ng-ai 7e6296f0c6 fix(navigation): separate target names from file locations (#5010)
Navigation target rows show the container next to the symbol at the same text size. File locations align to the right and keep the file name and line visible when a long path has to be shortened. The list scrolls inside the popup when space is limited.
2026-11-21 20:18:55 +08:00
l0ng-ai 31c169c889 fix(editor): give the indentation chooser a code style heading (#5008)
The indentation popup uses a Code Style heading for the active file's language. The current indentation stays checked even when the file uses a custom number of spaces. The heading and choices use the standard menu text size.
2026-11-21 20:05:32 +08:00
l0ng-ai 13103fd5af fix(plugins): update wasmtime to 49.0.7 for the WASI sandbox advisory (#5009)
RUSTSEC-2026-0587: on Windows a drive-prefixed path component let a WASI guest escape its preopened directory. 49.0.7 carries the fix; the rest of the wasmtime crates move with it. Lockfile-only.
2026-11-21 20:03:31 +08:00
l0ng-ai 50340219ac fix(editor): show usages on a declaration a server finds no definition for
Go to Declaration on a declaration's own name shows its usages only when the language server answers the declaration itself. kotlin-language-server answers nothing there, so ⌘B / ⌘-click on `fun lend` reported "Cannot find declaration to go to" while Find Usages listed four. When the server has no definition and the syntax tree puts the caret on a declaration's name, the usages show now, for every language.
2026-11-21 19:58:02 +08:00
l0ng-ai 71000e15f2 fix(editor): open library sources reached by navigation read-only
Go to Declaration into a library could open its source editable: only files under the External Libraries roots were read-only, and many language servers answer with sources they keep elsewhere (java-analyzer's source cache, the TypeScript lib files of the server's own typescript, Intelephense's stubs, the temporary copies kotlin-language-server writes). A file outside the project that code navigation opens (declarations, implementations, usages, hierarchy, documentation and inlay links) now opens read-only with the Library source notice. Files opened outside the project in other ways stay editable.
2026-11-21 19:58:02 +08:00
l0ng-ai 042008f681 fix(run): don't launch Java with a server JDK older than the module's release
Without jdtls, a Java run or debug used the JDK the Java language server reports (java-analyzer's own runtime) before matching the module's Java version, so a module compiled for release 21 started on JDK 17 and failed with UnsupportedClassVersionError. The server's JDK is now used only when it can run the module's release; otherwise the installed JDK matching it is picked.
2026-11-21 19:58:02 +08:00
l0ng-ai 942e6cb237 fix(windows): stop WebView2 browser shortcuts from taking unhandled IDE keys (#5007)
A key the keymap leaves alone reached WebView2's browser accelerators: Ctrl+F in a view without its own find opened the page's Find bar over the whole window, and F3, F12 or Alt+Left ran browser features. Turn the accelerators off for every webview; the page still gets every key.
2026-11-21 19:57:55 +08:00
l0ng-ai 674cdd3925 fix(diff): align headers in the combined changes view (#5006)
The combined changes view gives each file its own inset section, with a bold file name and a muted path. File actions sit before the name so they stay visible when a narrow editor pane truncates the text. Compact Mode reduces the space around file sections and headers.
2026-11-21 19:44:35 +08:00
l0ng-ai 04666f5980 fix(app): open middle-clicked links in the browser (#5005)
A middle click on a link (an agent reply, any rendered content) navigated the IDE window to it: link handlers listen to click, and the middle button fires auxclick, whose default action the webview carried out. A window-wide auxclick handler now cancels it for every link and opens a web link in the default browser, as a left click does; a link into the app itself does nothing.

Fixes #4992
2026-11-21 19:33:15 +08:00
l0ng-ai d335ba5fdd fix(project): align the New file type picker (#5004)
The keyboard New popup aligns the search icon and text with the options below it. The search divider has side margins, and the search field keeps its height in short windows while the list scrolls. The wider list and smaller shortcut text let the full Scratch File label fit alongside its Windows shortcut.
2026-11-21 19:23:09 +08:00
l0ng-ai 33d2f34e58 fix(vcs): list a nested repository's files once (#5003)
A folder the enclosing repository still tracks can become a repository of its own; both then reported its files, so the same path appeared twice in the Commit tool window's change tree and its rows went stale when a repository group was collapsed. Each file now belongs to its innermost repository: the enclosing repository's entries inside a nested one are dropped, in the full status and the scoped refresh.

Fixes #4990
2026-11-21 19:07:29 +08:00
l0ng-ai 7646bc4746 fix(workbench): align the empty editor shortcuts (#5001)
The empty editor presents its actions and shortcuts in a left-aligned block centered across the editor. The text uses a 16 px default size with more space between rows, and shortcuts use the foreground color. The Project action appears when the Project tool window is hidden. LightEdit uses the same layout for its file actions.
2026-11-21 19:04:42 +08:00
Emir 2c161812a0 fix(plugins): refresh marketplace after uninstall (#5000)
After uninstalling a plugin, the marketplace kept showing it as installed until it was refreshed, so it couldn't be installed again right away. Uninstall now refreshes the marketplace (from its cached index), as install already does.

Co-authored-by: laot7490 <[email protected]>
2026-11-21 18:51:06 +08:00
l0ng-ai 1778bf1ef3 fix(editor): keep inspection counts readable in split panes (#4998)
The editor inspection widget uses smaller tabular counts and groups the two diagnostic navigation buttons. A narrow pane shows the total beside the Problems icon, leaving more of the code visible. The summary tooltip and accessible label provide the count for each severity.
2026-11-21 18:39:36 +08:00
l0ng-ai 1e7fe7605b fix(editor): align Sticky Lines with the editor viewport (#4997)
Sticky Lines now shares the editor's typography, tab width, and line-number mode. Pinned text and line numbers align with their columns in the document. The panel follows the editor viewport and paints behind the overview lane, with header text clipped at the lane's edge.
2026-11-21 18:19:08 +08:00
l0ng-ai 67dcf5c978 fix(workbench): make background task details easier to read (#4995)
The Background Tasks popup has a fixed title bar and a scrollable task list. Long titles and progress details wrap, and the progress bars, percentages, and cancel buttons line up across rows. The popup remembers its size after it is resized.
2026-11-21 18:00:33 +08:00
l0ng-ai 20404d2f44 fix(workbench): give Notifications a readable timeline (#4993)
Notifications now has a Timeline heading and a Clear All button that stays visible while the history scrolls. Entries use the workbench UI text size and align their titles, timestamps, and actions. In a narrow pane the timestamp and dismiss button move below the title so longer titles can wrap at normal word boundaries. Multiline messages scroll with the history.
2026-11-21 17:38:38 +08:00
l0ng-ai b44e552628 fix(navigation): make the Bookmarks popup resizable (#4991)
The Bookmarks popup opens in the center and remembers its window size and the split between the bookmark list and source preview. The panes sit side by side in a wide window and stack in a narrow one so the preview has room for source lines. Bookmark rows use the workbench list density and align their line numbers on the right.
2026-11-21 17:18:32 +08:00
l0ng-ai bc4e8e9655 fix(editor): align Parameter Info typography and overload rows (#4988)
Parameter Info uses the workbench font and UI size for its signatures. A single signature emphasizes the current argument in bold. Overload lists use inset separators and a rounded highlight for the active signature, while keeping the current argument visible as the list wraps.
2026-11-21 16:55:56 +08:00
faysouandfaysou c12799c973 test(debugger): select stack threads by their labels (#4987)
The narrow debug dock test timed out after the thread selector started including each thread's state in its option name (Order worker Running). It now finds the option by its visible thread label within the Thread listbox.

Co-authored-by: faysou <[email protected]>
2026-11-21 16:43:04 +08:00
l0ng-ai 0d4bd4a69a fix(editor): group Quick Documentation popup actions (#4986)
Quick Documentation now keeps Edit Source and More Actions in its lower-right corner. More Actions groups the commands for opening the Documentation tool window and moving back or forward through the current document history. The corner stays visible while the documentation scrolls.
2026-11-21 16:42:03 +08:00
l0ng-ai bf2f44d523 fix(debugger): align evaluation history with the expression editor (#4985)
Evaluate uses the configured editor font, size and line height for the expression field. Its history dropdown lines up with the full field and uses the same code typography. The Result label also names the results area for assistive technology.
2026-11-21 16:23:40 +08:00
LU XIANGRUIandwildcatDownstairs 2b6fab3c1c fix(semantic): colour typescript-language-server's member tokens as methods (#4984)
typescript-language-server passes tsserver's own token type for methods, member (vtsls renames it method). The semantic token mapping only knew method and dropped member tokens, so with typescript-language-server method declarations took the field colour and calls none. member now maps like method.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-21 16:20:04 +08:00
LU XIANGRUIandwildcatDownstairs 37df909358 fix(color-scheme): let derived tokens follow a scheme's overrides (#4983)
Under an imported or explicitly chosen non-default scheme, tokens that tokens.css derives with var() kept the parent scheme's colour: resolvedSchemeTokens resolved the parent's var() chains to hex first and applied the overrides afterwards. Overrides now take part in resolving, so a derived token follows its source unless it is overridden itself, in the editor stylesheet, the Settings preview and resolvedAttribute. The theme's own scheme is unchanged.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-21 16:15:03 +08:00
l0ng-ai b51054daca fix(navigation): group File Structure filters above the tree (#4980)
File Structure puts the member filters in a compact toolbar above the search field and symbol tree. The toolbar wraps complete labels on narrow windows, while the tree scrolls independently. Sorting and narrowing on typing are available from the View Options menu on the right.
2026-11-21 16:05:46 +08:00
l0ng-ai 57856f2d54 fix(search): keep filter controls visible while scrolling (#4976)
Search Everywhere now aligns the checkbox, type icon and label in each filter row. All, None and Invert sit below the scrolling list so they stay visible when the list is long or the window is short.
2026-11-21 15:50:40 +08:00
LU XIANGRUIandwildcatDownstairs e06c16f547 fix(color-scheme): let Python method calls follow a Python function call colour (#4971)
A Python override of Function call coloured plain calls but not method calls: tokens.css declares --syn-python-method-call: var(--syn-function-call) on :root, so the fallback was resolved there and never saw the Python block's override. The Python block now re-declares the Python tokens whose default is a var() of a token it overrides (unless they have their own override), so Method call follows Function call and Nested function definition follows Function definition, as in PyCharm. The Settings page shows the same inherited colour.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-21 15:49:34 +08:00
Vladislav Kuzmin 7b893d2982 fix(database): show SQL batch progress as statements finish (#4799)
The SQL console got one response at the end of a batch, so progress, timings and results only appeared once every statement had finished. A new db_execute_stream command reports each statement's start and completion over a channel; the console shows the spinner and timer on the running statement and publishes each result grid as it completes. The batch still runs once, stops at the first error or on cancel, and an older remote server falls back to db_execute after rejecting the new command before execution.

Closes #4782

Co-authored-by: principalwater <[email protected]>
2026-11-21 15:45:35 +08:00
l0ng-ai 1cc8a361b8 fix(project-view): move speed search above the file rows (#4969)
- Place the Project tree's speed search above the file rows so the first item stays readable while typing.
- Use the standard field height, a 16 px search icon, and a visible caret. Long queries truncate within the sidebar. Keyboard focus stays in the tree.
2026-11-21 15:26:36 +08:00
l0ng-ai a28f6ce331 fix(editor): preview regex replacements at the match (#4967)
- Show the expanded replacement beneath the current match in file-level regex Replace when the result differs from the template. The preview uses the same replacement calculation as Replace Next.
- Use a compact monospace balloon that preserves line breaks and stays within the editor width. It follows the selected match and leaves focus in the toolbar.
2026-11-21 15:18:13 +08:00
l0ng-ai 5d27b4254b fix(editor): align the hidden tabs popup (#4966)
- List only the editor tabs clipped by the strip. A separator marks the split between tabs clipped before and after the visible stretch.
- Use compact rows with file icons, the tab label, and its close control. Keep the popup open while closing hidden tabs and bring the chosen tab into view when it is opened.
2026-11-21 14:52:59 +08:00
LU XIANGRUIandwildcatDownstairs 45d85f5721 fix(plugins): keep web view panels transparent under a dark theme on Windows (#4964)
WebView2 paints an opaque backdrop behind an iframe whose color-scheme differs from the embedding page's. Plugin web view pages (web = "...") got data-theme from the frame bridge but no color-scheme (only html views get BASE_STYLE), so under a dark theme they turned white on Windows. The bridge now sets the frame root's color-scheme along with data-theme, as html views already have.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-21 14:48:21 +08:00
LU XIANGRUIandwildcatDownstairs fa7fcd0d90 fix(color-scheme): import PyCharm's function call, class and f-string colours (#4965)
Importing a PyCharm color scheme skipped eight PyCharm Python keys (PY.FUNCTION_CALL, PY.CLASS_DEFINITION, PY.PARAMETER, PY.LOCAL_VARIABLE, PY.TYPE_PARAMETER, PY.INVALID_STRING_ESCAPE, PY.FSTRING_FRAGMENT_BRACES, PY.FSTRING_FORMAT_SPEC_NUMBER), so Python calls took the shared call colour. They now map to the existing Python attributes and export under PyCharm's keys; files exported earlier under OPENIDEA_ names still import.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-21 14:48:07 +08:00
l0ng-ai 6b2b4a96e7 fix(debugger): align the thread selector with the frames pane (#4961)
- Give the thread selector the width of the call stack header, with the standard workbench font and a fixed chevron at the trailing edge.
- Show a leading icon for running, suspended, and breakpoint threads in both the header and the menu. Keep the status text in the menu and make the selected thread's full name and status available in the header tooltip and accessible description.
2026-11-21 14:33:37 +08:00
l0ng-ai d507e67123 fix(debugger): anchor Smart Step Into to the paused line (#4959)
- Open the Smart Step Into target list by the paused source line. Center it when the paused source is outside the visible editor.
- Keep the list compact for short target lists. Scroll longer lists and show clipped method names in a tooltip.
2026-11-21 14:13:46 +08:00
l0ng-ai 5563345a8f fix(debugger): fit the full value viewer to its popup (#4958)
Size the debugger's full-value popup to the workbench and let the text fill the available space as the popup grows. Render the value with the configured editor font, line height and tab width. Keep the resized popup visible if the workbench shrinks.
2026-11-21 13:52:34 +08:00
Mollo-i bff0761c48 fix(vcs): honour the diff window setting in Show Diff (#4957)
Show Diff called openDiff directly and always opened an editor tab, ignoring Settings > Version Control > Confirmation > Open diff as editor tab. It now goes through openVcsDiff like the other change entry points, so with the option off the diff opens in the separate Diff window.

Co-authored-by: Greenker <[email protected]>
2026-11-21 13:42:14 +08:00
l0ng-ai 2811a438a0 fix(editor): skip project-wide background requests in library sources (#4933)
Go to Declaration in a library file could wait 10-20 s behind usage lenses, server code lenses and inheritor markers, which asked references / implementation for every visible library declaration and made the server analyse the whole project.

Usage lenses and server code lenses now skip library sources (library roots, node_modules, excluded folders, virtual documents, files outside the project). Gutter markers stay: in library files ↓ is asked for classes and interfaces only, and in-flight marker requests are cancelled while a navigation gesture runs and asked again afterwards.
2026-11-21 13:38:13 +08:00
Mollo-i d34252c80a fix(editor): keep Java annotations on their line's indentation after Enter (#4956)
Enter after a Java annotation added an indentation level, so stacked annotations above a class drifted right: the stock Java grammar parses an annotation (or an unfinished annotation type) as a Statement, which continues one level deeper. A Java-only indent service keeps the annotation line's indentation when the break follows the whole annotation; an open @Ann( and code blocks still indent.

Co-authored-by: Greenker <[email protected]>
2026-11-21 13:22:19 +08:00
l0ng-ai a60a36f052 fix(settings): align the Download JDK dialog (#4955)
Put Version first in Download JDK, followed by Vendor and Location. Use one aligned control column in the desktop dialog and put labels above their controls in narrow windows. The location field uses the regular UI font, and long help, progress, and error text can wrap within the dialog.
2026-11-21 13:20:21 +08:00
ntbang0901 939222cdfb feat(debugger): Java exception breakpoints for a chosen class (#4954)
The Breakpoints dialog gains Java Exception Breakpoints on a chosen class (subclasses included): Caught and/or Uncaught, optionally limited by class filters on the throwing code. java-debug's Caught/Uncaught filters stay as the Any exception row. java-debug has no per-class exception requests, so the jvm-inspect bundle (1.2.0) makes the JDI exception requests itself; ide-dap arms them before configurationDone (a throw on main's first line stops) and again after each setExceptionBreakpoints, which drops them. Condition and catch-class filters show disabled with the reason. The bundle jar was rebuilt from source and matches the checked-in one byte for byte.

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 13:19:21 +08:00
l0ng-ai ec0370ec23 fix(settings): fit Module Sources to the available width (#4953)
Put the folder tree and marked roots in a resizable split in Project Structure › Modules › Sources. The panels stack when the available width is too small for a side-by-side layout. The summary shows populated root groups and uses the 13 px workbench font for folder paths.
2026-11-21 12:58:16 +08:00
l0ng-ai 9243ff2eac feat(services): jump to the source of a run configuration (#4952)
Run configuration nodes in Services gain Jump to Source (F4, ⌘↓, context menu): JVM applications and Spring Boot open their main class at the declaration (the configuration's module first), npm/Bun the script in package.json, Python/Ruby/shell/pytest their file, Gradle/Maven the build file, Go the target or main.go, .NET the project file. Kinds without a file show it disabled. F4 on a run configuration no longer starts it; providers without Jump to Source keep activating.
2026-11-21 12:44:18 +08:00
l0ng-ai 143281d67e fix(settings): group Project Libraries attachments in a tree (#4951)
Project Libraries now shows class and source attachments in one expandable tree with a shared add and remove toolbar. Attachment rows use the 13 px workbench font. In narrow windows, the library list and details adapt to the available width, and long paths scroll inside the tree.
2026-11-21 12:35:29 +08:00
Zou e1f25d2747 feat(i18n): add Traditional Chinese (zh-TW) UI language (#4950)
Adds 繁體中文 to the UI languages. The catalogs are converted from the Simplified ones with OpenCC (s2twp) plus a Taiwan IT terminology pass keyed on the English source (column → 欄, undo → 復原). zh-TW, zh-HK, zh-MO and zh-Hant* resolve to it; other zh tags stay Simplified. The update source picks CNB for every zh* locale, matching the backend.

Co-authored-by: g4cj8498741 <[email protected]>
2026-11-21 12:25:12 +08:00
l0ng-ai 26fce11f94 fix(run): align the stack trace dialog (#4949)
Give the stack trace editor a 600 × 400 preferred area and use the configured editor typography, including tab width. Resizing the dialog grows the editor. At short window heights, the editor shrinks so the trace scrolls within the field and the footer stays visible.
2026-11-21 12:14:11 +08:00
Gabriel Gondim c5c2fb7c98 fix(ssh): use the agent from IdentityAgent or the login shell's SSH_AUTH_SOCK (#4939)
OpenSSH authentication asked the agent client for SSH_AUTH_SOCK from the process environment only. On macOS an app started from the Dock has launchd's socket there, so an agent exported in ~/.zshrc (Bitwarden's, in #4934) was never used. The default agent is now SSH_AUTH_SOCK as the login shell sets it (the app already reads that environment at startup), and IdentityAgent in ~/.ssh/config is honoured per host, jump hosts included (none, SSH_AUTH_SOCK, $VAR or a path with ~ and % tokens). On Windows a SSH_AUTH_SOCK that is not a pipe falls back to the OpenSSH pipe.

Co-authored-by: GGVidal <[email protected]>
2026-11-21 12:03:04 +08:00
l0ng-ai 31ca9daa61 fix(vcs): align the target changelist dialog (#4947)
Put existing and new target changelists in one editable **Name** field. Open the list to pick an existing target or enter a name to make a new one. The comment and active status sit in the same place for both choices. Undo Commit offers the commit subject as a suggested name.
2026-11-21 11:57:07 +08:00
l0ng-ai d89991168e fix(vcs): align the history commit message dialog (#4945)
Show the commit hash and author above the message editor when editing a commit. Use the same layout for the message of a squashed commit. The dialog resizes in both directions, and the text area follows the configured editor font, weight and line height.
2026-11-21 11:39:42 +08:00
l0ng-ai 16496f8001 fix(vcs): don't report the index a worktree diff refreshes as a repository change (#4946)
git diff against the working tree rewrites .git/index when it meets files with stale stat data, even with --no-optional-locks. The watcher reported that as a repository change, so the agent changes view, which re-reads on every repository change, re-ran its diffs and triggered itself again; on Windows, where git and gix disagree on stat data, it never settled and kept several git processes a second running (#4792). Every git diff that reads the working tree now records an index it rewrote as our own write, like status's write-back; this covers agent changes, compare with the working tree and the other worktree diffs.
2026-11-21 11:38:31 +08:00
l0ng-ai ce58c873da test: update two fixtures left stale by recent changes (#4944)
The commit settings default shape gained includeChangesByDefault (#4864), and New Task options now come from the project's saved catalog (#4901), so the approvals test seeds projectCatalogs instead of the removed provider-wide config. Fixes Rust checks on main for every platform.
2026-11-21 11:31:46 +08:00
l0ng-ai d069c3daff fix(vcs): align the revision comparison toolbar (#4942)
Move **Show Diff** from the desktop revision comparison footer to a compact toolbar above the changed files. The action is available when a file is selected. **Close** sits by itself at the bottom right.
2026-11-21 11:22:15 +08:00
l0ng-ai 95b71e1ffc fix(vcs): align the rebase dialog (#4940)
- Group the repository, command and target branch in one row. The row wraps when space is limited.
- Put the branch being rebased in the title. With `--onto` enabled, place the new base beside the command and label the old base on its own row.
- Move flags to **Modify options** and show active flags below the fields. Clear branch selections when switching repositories and wait for the new repository's branches.
2026-11-21 11:05:51 +08:00
l0ng-ai 732cfd6002 fix(vcs): align the unstash dialog (#4935)
- Align the repository, current branch, stash list, and branch input in two columns using the workbench form font. Put Show Changes and Drop Stash beside the list and group the restore options beneath it.
- Add a repository picker for multi-repository projects. Each repository loads its own stash list before the actions become available. After a drop, the list stays visible while the actions wait for the refreshed selection. The fields stack on narrow windows.
2026-11-21 10:48:32 +08:00
Akbar Husain 189879f0fa perf(vfs): coalesce the pre-debounce watcher queue per path (#4032)
Raw notify events were queued one by one until the debounce window closed, so an event storm grew the queue without bound. Events are now classified in the notify callback and coalesced per path, keeping each path's distinct transitions in order, so the batch sees the same result while memory is bounded by paths touched (100,000 writes over 1,000 paths: 100,000 entries before, 1,000 after). Coalesced VCS changes replay as creates so directory changes under .git are not dropped as lock-file touches.

Co-authored-by: akbar1214 <[email protected]>
2026-11-21 10:47:34 +08:00
l0ng-ai f0a412f3e2 fix(vcs): align the worktrees panel (#4937)
- Place the actions on the left of the Worktrees tree in both the dialog and the Git tool window.
- Show the checkout name above its branch and path, with the same UI font size for the checkout name and branch. Current, locked, and prunable worktrees have status icons. The tree supports searching by either checkout name or branch.
2026-11-21 10:40:52 +08:00
Gabriel Gondim 1a470e2a23 fix(window): host system buttons in the macOS fullscreen title bar (#4923)
In native full screen on macOS, the window buttons lived in the title bar strip AppKit slides down with the menu bar, which showed up as a dark band over the IDE's own title bar. Full screen now hosts system window buttons made by standardWindowButton:forStyleMask: in the slot the page keeps for them, and hides that strip. The strip is re-hidden from its own window notifications (no polling), matched by its exact class, and only for the window in full screen.

Fixes #4746

Co-authored-by: GGVidal <[email protected]>
2026-11-21 10:28:43 +08:00
l0ng-ai 793c720f7f fix(vcs): align the reset dialog (#4932)
- Align the Reset HEAD fields in two columns and use the workbench form font throughout. Show the current branch and the selected reset mode's effect, and stack the fields on narrow windows.
- Let the user choose the repository in a multi-repository project. A repository change resets the typed revision to HEAD.
- In Reset to Here, put the repository, branch, and fixed commit above the mode choices.
2026-11-21 09:53:24 +08:00
l0ng-ai 93c7f8b7fd fix(vcs): align the merge dialog (#4930)
- Put the repository and searchable branch picker on the same line as the Git command. The row wraps on narrow windows.
- Move the merge flags into the Modify options menu and show the selected flags below the command row. Choosing a custom commit message opens a multiline field.
2026-11-21 09:40:19 +08:00
l0ng-ai 3e37b60505 refactor(settings): remove the unused RadioRow control (#4931)
The settings pages that used RadioRow now lay out their radio groups themselves, so it had no callers left and knip failed on main. Removes it with its RadioChoice type.
2026-11-21 09:33:05 +08:00
weigramandweigram a5c8fe17fd feat(services): drag a run type's group to reorder it (#4929)
The Services tree persists the order of its run type groups per project, but only configurations inside a group could be moved. Groups now reorder among each other by drag or with Move Up / Move Down, using the project's type list as their order, so the new position survives reopening.

Co-authored-by: weigram <[email protected]>
2026-11-21 09:32:07 +08:00
l0ng-ai 0684795334 fix(vcs): align the new branch dialog (#4924)
New Branch used a stacked prompt with a small label above the name field and the creation options at the left edge. The dialog now puts the label beside the field, uses the workbench UI font for both, and aligns validation and options with the field. On narrow windows the label stacks above the field and the checkboxes can wrap.
2026-11-21 09:31:00 +08:00
l0ng-ai 30cbb80f22 fix(history): align the recent changes chooser (#4917)
fix(history): align the recent changes chooser
2026-11-21 09:30:49 +08:00
weigramandweigram 5cfb0d3311 feat(settings): reopen Settings on the page it was closed on (#4927)
Settings now records the page it shows (when it opens and on each navigation) and reopens there, in the separate Settings window and across restarts. The page is UI state and stays in localStorage; Settings for New Projects keeps its own pages out of it, and an id that no longer exists falls back to the first page.

Co-authored-by: weigram <[email protected]>
2026-11-21 09:22:16 +08:00
l0ng-ai bccf1bd7d6 fix(vcs): align the tag dialog (#4926)
- Align the Tag dialog's labels and controls in two columns, use the workbench font throughout, and stack the fields on narrow windows.
- Show the selected repository and its current branch above the tag fields. Keep the duplicate-name message and Force checkbox under the tag name.
2026-11-21 09:18:46 +08:00
l0ng-ai 3d79454be8 fix(vcs): align the changelist form (#4925)
The changelist form stacked small labels above each field and left room for only three lines of comments. The Name and Comment labels now sit beside a shared field column at the workbench UI size. The comment field starts at four lines, and the fields stack on narrow windows. The same form is available when creating, editing or moving changes to a new list.
2026-11-21 08:59:25 +08:00
l0ng-ai 46e4af2b32 fix(vfs): ignore Git metadata directory touches (#4922)
Git for Windows reports a parent directory modification when Git creates or removes a lock. The watcher treated these notifications as repository changes and refreshed Git status even when the index was identical. Refresh Git status on metadata file changes and directory creation or removal. Skip directory modifications caused by the changed entries.
2026-11-21 08:43:26 +08:00
l0ng-ai 067edb7d60 fix(vcs): align the Git annotation gutter (#4921)
Git annotations displayed only the first part of each author's name, and variable-width dates pushed the author column out of alignment. The gutter now uses the workbench UI font and sizes the columns from the file's annotations. Authors are shown by full name, with a width cap for long labels. When enabled, the revision column leads the row.
2026-11-21 08:25:00 +08:00
l0ng-ai 0a4abf1705 fix(vcs): align the file history layout (#4920)
File History inherited the repository log's sidebars, which left little room for the revision list or commit message. It now uses a full-width toolbar and revision list, with author and date before the subject by default. A resizable pane below puts the selected commit message beside the changed files and remembers its size independently. The repository log and directory history keep their current layout.
2026-11-21 08:06:50 +08:00
l0ng-ai d31699c86a fix(vcs): align the file revision chooser (#4919)
fix(vcs): align the file revision chooser
2026-11-21 07:59:59 +08:00
Gabriel Gondim 9467c4ea1b fix(plugins): install-dir reads and default editors over associated apps (#4918)
A plugin's fs.read-*, editor.open and views.open-location rejected absolute paths under its own install (package) directory, so a linked plugin could not open files bundled next to its component. The install directory is now readable like fs.plugin-dir() (writes still need an fs.write grant). Custom editors with priority "default" now open in the IDE ahead of the Files opened in associated applications list, so a PDF editor plugin is not bypassed by the built-in *.pdf association. The SDK carries the updated WIT docs and the plugin components are rebuilt.

Fixes #4167

Co-authored-by: GGVidal <[email protected]>
2026-11-21 07:58:50 +08:00
l0ng-ai 7c12c58874 fix(vcs): align the operations chooser (#4915)
fix(vcs): align the operations chooser
2026-11-21 07:29:12 +08:00
l0ng-ai 9f47ef0991 style(settings): format the Git settings imports (#4916)
Formats an import line that came out of a merge too long for oxfmt. No behaviour change.
2026-11-21 07:26:17 +08:00
l0ng-ai 3b614dda7a fix(diff): clarify clipboard comparison labels (#4911)
fix(diff): clarify clipboard comparison labels
2026-11-21 07:25:45 +08:00
l0ng-ai 5acd778340 fix(navigation): align the Select In chooser (#4909)
fix(navigation): align the Select In chooser
2026-11-21 07:25:17 +08:00
l0ng-ai 7c682a580f fix(editor): group the Refactor This actions (#4906)
Refactor This uses a compact action list with an Extract/Introduce section and dividers for the related action groups. Filtering keeps captions only for groups with matching actions. The number beside each action still selects that action directly.
2026-11-21 07:25:05 +08:00
l0ng-ai dc07691279 fix(run): align the run configuration chooser (#4904)
The run configuration chooser adapts its width to configuration names and leaves room for the row actions. At large zoom or in a short viewport, the configuration list scrolls while the search field and keyboard shortcuts stay visible.
2026-11-21 07:24:47 +08:00
l0ng-ai 2d04a3d9bc fix(editor): align the Quick Definition preview (#4903)
Quick Definition opens with a toolbar above a resizable code preview. The header shows the symbol and its source location, with previous and next controls when several results are available. The preview uses the source editor's font size, line height, and zoom.
2026-11-21 07:24:36 +08:00
l0ng-ai 8f9b9b1016 fix(workbench): group commands in the tool window layouts menu (#4902)
Window → Tool Window Layouts groups commands under each saved layout and marks the active layout. The default layout is at the top, with commands for the current arrangement below the saved layouts. Rename opens the name field for the selected layout directly.
2026-11-21 07:24:18 +08:00
l0ng-ai 096964c798 fix(workbench): align the toolbar customization dialog (#4898)
Move the add, remove, reorder, transfer, and restore controls into a compact toolbar above the lists. Keep the left and right groups side by side when there is room, and stack them in narrow windows so the labels have more space. The add picker opens directly below its command.
2026-11-21 07:24:08 +08:00
l0ng-ai f1bfd5db52 fix(workbench): center and label Quick Switch Scheme (#4897)
Quick Switch Scheme now opens in the center of the window and stays there when the window is resized. A title identifies the popup, and a numeric column shows shortcuts 1–4 for opening its categories. Theme previews and editor focus still restore when the popup closes.
2026-11-21 07:23:50 +08:00
l0ng-ai a17af582f3 fix(settings): align the Date Formats layout (#4894)
Place the date pattern help beside the input when there is room and let it wrap under the input in narrow windows. Put the live examples just below the time format control in smaller, secondary text. Pretty formatting remains a separate setting and still updates both examples.
2026-11-21 07:23:32 +08:00
l0ng-ai 47f018d8b5 fix(settings): align the External Tools form (#4893)
Pair Name and Group when the form has room and put Description on its own row. Tool Settings contains the command fields, while the execution checkboxes sit in a collapsible Advanced options section that opens for matching settings searches. The fields and macro buttons adapt to the available width.
2026-11-21 07:23:22 +08:00
l0ng-ai 94aa62430c fix(settings): align the System Settings layout (#4890)
Put exit confirmation before Project, then place file saving and synchronization in a Files section before Caches. In narrow windows, the project-opening choices use less vertical space, the directory field keeps its browse button beside it, and the idle timeout keeps its unit. The existing Autosave search term still finds the page.
2026-11-21 07:23:03 +08:00
l0ng-ai 4242c94bfc fix(settings): align the Updates settings layout (#4889)
Put Check Now and Last checked on the same row, below automatic checks and the update source. The last-checked timestamp uses secondary text and follows the button as the window narrows. The release notes preference sits below the manual check.
2026-11-21 07:22:44 +08:00
l0ng-ai 8864ff595d fix(settings): align the Maven settings layout (#4886)
Put the snapshot option and a compact thread count at the top. Group Maven home, user settings, the local repository, and toolchains under Environment. Put source downloads under Importing, with build delegation, JRE, and profiles together under Runner.

Environment and Runner put labels above their fields in narrow windows. Browse buttons stay beside their paths, and Maven Daemon controls are available below Runner.
2026-11-21 07:22:34 +08:00
l0ng-ai 0a08d9f4ce fix(settings): align the Gradle settings layout (#4885)
Place Gradle user home at the top of the page, with separate sections for Build and Run and the Gradle runtime. Keep the local installation path and Browse button beside Distribution when there is room. In narrow windows the path field moves below the selector and stays next to Browse. The Gradle JVM picker sits below the distribution controls.
2026-11-21 07:22:23 +08:00
l0ng-ai 7dbfe8852e fix(settings): align the Spelling settings layout (#4884)
Place custom dictionary files above the accepted words. Give both lists the available pane width, with monospaced paths and standard UI text for words. A tab selects the project or application dictionary within the accepted words section. Settings for New Projects shows the application dictionary directly.
2026-11-21 07:22:13 +08:00
l0ng-ai ae97d5f1c2 fix(settings): group the debugger Data Views controls (#4883)
Group inline values and value tooltips under Editor. Keep the hover delay beside its checkbox in wide windows and below it in narrow windows. Turning off hover dims the delay field and keeps its value for when hover is enabled again. Sort order and live watches sit at the top of the page.
2026-11-21 07:21:54 +08:00
l0ng-ai 4340a96c59 fix(settings): align the Terminal settings layout (#4882)
Group the primary font, fallback font, and sizing controls above Application Settings. Let the start directory and default tab name use the available width. Keep the shell path, installed-shell menu, and Browse button together. Narrow windows place text fields below their labels and show the application checkboxes in one column.
2026-11-21 07:21:17 +08:00
l0ng-ai 0af7bcc7cf fix(settings): align the VCS confirmation settings (#4878)
The file creation and deletion policies use aligned selectors in Version Control settings. They fit on separate rows at narrow widths. The patch creation and history controls follow the Changes group as separate settings.
2026-11-21 07:21:07 +08:00
l0ng-ai 4f52f5ebfa fix(vcs): align the directory comparison layout (#4875)
fix(vcs): align the directory comparison layout
2026-11-21 07:20:29 +08:00
l0ng-ai f284633162 fix(settings): align the Appearance controls (#4867)
fix(settings): align the Appearance controls
2026-11-21 07:20:18 +08:00
l0ng-ai 0ceda2c385 fix(settings): align the Git settings controls (#4865)
fix(settings): align the Git settings controls
2026-11-21 07:20:07 +08:00
l0ng-ai 8b3f55dfb4 fix(settings): align the HTTP Proxy form (#4863)
fix(settings): align the HTTP Proxy form
2026-11-21 07:19:48 +08:00
l0ng-ai c0e888dd2f fix(settings): align the Console settings layout (#4861)
fix(settings): align the Console settings layout
2026-11-21 07:19:37 +08:00
l0ng-ai 04bed01942 fix(vcs): align the Apply Patch preview (#4860)
fix(vcs): align the Apply Patch preview
2026-11-21 07:19:24 +08:00
weigramandweigram dfafe6c767 fix(app): bring the window forward before the quit prompts ask (#4913)
Confirm Exit and the Terminate / Unsaved Changes prompts of a quit are drawn inside the window, but a quit can start outside it (the Dock, a logout, another window). A minimized or covered window asked with nothing on screen and the app looked hung. The window is now unminimized, shown and focused right before a quit prompt; a window with nothing to ask is left where it is.

Fixes #4912

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

Co-authored-by: weigram <[email protected]>
2026-11-21 07:06:44 +08:00
Vladislav Kuzmin 461c71a50b test(settings): measure notification labels in the group list (#4892)
#4810 replaced the notification group table with a listbox, and the compact settings test still waited for a table cell, so it timed out before measuring anything. It now measures the group labels inside the listbox.

Fixes #4891

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

Co-authored-by: principalwater <[email protected]>
2026-11-21 06:55:23 +08:00
l0ng-ai 82085a227e fix(agents): record a task's turns across nested repositories (#4910)
A local task in a project with nested git repositories recorded no turns, so the Changes pane's last-turn scope stayed empty there and the whole-task list no longer kept to the files the task touched. A turn now records each repository's HEAD as it starts; the files a turn changed, their text when it began and its rollback come from the repository holding each file, including commits made in a nested one.
2026-11-21 06:38:07 +08:00
Paweł SzymańskiandPawelSzymanski89 c3f420374c fix(agents): list task changes per repository, including nested repos (#4543)
A local agent task in a project that holds nested git repositories (an own .git below the project root, not a submodule) only saw the changes of the repository at its root. Its changes are now read from every repository under the root, each against its own HEAD; the Changes pane groups them under a row per repository when there are several, and a rollback reads each file from its own repository.

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

Co-authored-by: PawelSzymanski89 <[email protected]>
2026-11-21 06:32:34 +08:00
faysouandfaysou 6bf7bc8c2b fix(vcs): apply Directory Mappings changes to all selected roots (#4908)
Directory Mappings now supports multi-row selection with Cmd/Ctrl and Shift. Minus moves the selected Git roots to an Unregistered roots section instead of only removing manually added ones, and plus registers the selected unregistered roots again in one step. Applying a removal refreshes Git status and branches: removing the selected repository switches to the remaining one, and removing the last repository clears the previous Git state and decorations.

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

Co-authored-by: faysou <[email protected]>
2026-11-21 06:18:36 +08:00
faysouandfaysou 34dfc166db fix(vcs): keep Git Log paths and branches in sync (#4907)
The Paths filter of the Git Log now holds the repository checkboxes, path entry, the file and folder tree and recent paths. Selecting paths replaces the repository selection, so a path in another repository no longer leaves the log empty, and the commit log and the Branches panel are scoped to the repositories the paths belong to.

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

Co-authored-by: faysou <[email protected]>
2026-11-21 06:15:44 +08:00
Chris Schofield 64632dc4d7 feat(editor): JSX/TSX tag editing — linked tag rename, prop values, Emmet (#4905)
JSX/TSX editing like the HTML modes: editing an opening or closing tag's name renames its partner (Simultaneous <tag></tag> editing), Enter between a tag pair puts the caret on an indented line with the closing tag below, and JSX tag pairs are matched. Typing = after a value-less prop inserts "" for string-typed props and {} otherwise (type from the server's hover, {} after 500 ms), following Pair quotes / Pair brackets. Emmet expands with Tab among an element's children and after return / => (className, self-closing void elements). Under TypeScript 7 the native server is asked for jsxAttributeCompletionStyle auto, so prop completion inserts the value delimiters as vtsls does.

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

Co-authored-by: ChildishForces <[email protected]>
2026-11-21 05:45:10 +08:00
Mr0Bread f484fd6802 fix(agents): let chats select any model their agent's catalog lists (#4901)
An existing agent chat listed models from the agent's catalog but refused to switch to them unless the catalog was under 15 minutes old and matched the launch fingerprint. A model the picker lists is now always selectable. The chat's picker offers the agent's current catalog plus the model the chat runs, and falls back to the session's own list when there is no catalog. The per-task copy of models and effort levels is removed, so the project catalog is the only source of available models and efforts.

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

Co-authored-by: Mr0Bread <[email protected]>
2026-11-21 04:50:52 +08:00
l0ng-ai 8121dc87f1 test(e2e): wait for the Run window to take focus before toggling it (#4900)
The tool-window shortcut hides a window only once it is active, and activation focuses it on the next frame; under load the test pressed Cmd+4 or Shift+Escape before that, so the window stayed open. The test now waits for focus inside the Run window first.
2026-11-21 04:27:03 +08:00
l0ng-ai 97f78908a1 fix(terminal): don't take focus that moved elsewhere while the view loaded (#4899)
A focus request made before xterm opened was applied whenever it opened, so a terminal still loading took the caret back from a view the user had clicked meanwhile. The deferred focus now applies only while focus is where it was when requested, on the page, or inside the terminal's own tool window.
2026-11-21 04:23:06 +08:00
faysouandfaysou e7aec17d46 Match backtick runs in protected inline Markdown math (#4895)
Protected inline math ($`...`$) now matches the opening backtick run to the first closing run of the same length, as Markdown code spans do: ($``x` + y``$) renders as math, while ($`x` `y`$) keeps two code spans and literal dollars.

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

Co-authored-by: faysou <[email protected]>
2026-11-21 03:56:06 +08:00
l0ng-ai cb24f252c5 fix(vcs): keep focus on the commit message when the Commit window opens (#4896)
Activating a tool window focuses its first field or tree on the next frame unless its content marks a data-autofocus target. The Commit window's message wasn't marked, so after Cmd+K focused the message, activation could move focus to the Changes tree depending on timing. The message is now the window's preferred focus, also when the window is activated from its stripe button.
2026-11-21 03:55:28 +08:00
faysouandfaysou 8557b8d21e feat(vcs): make default Commit inclusion configurable (#4864)
Settings > Version Control > Commit gets Include changes in the commit by default. It is on by default, which keeps the current behaviour (the active changelist's changes start checked). Turned off, the Commit view starts with every file unchecked, partially staged files included. Explicit selections still apply, and staging-area mode still follows the Git index.

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

Co-authored-by: faysou <[email protected]>
2026-11-21 03:32:16 +08:00
l0ng-ai 99a8f8feaa fix(completion): put the caret inside a Kotlin call that takes arguments (#4888)
Refs #3447

kotlin-lsp inserts a picked item itself, parentheses included, and the caret was moved after the whole edit (read()| for read(name: String)), so typed arguments went after the call. When the item's signature lists parameters and the server's edit ends with (), the caret now goes between the parentheses, as it does for items inserted on the client.
2026-11-21 02:50:55 +08:00
l0ng-ai 4b76566af4 fix(editor): write failed saves to the log with their stack (#4887)
Refs #3447

A failed save only showed its message in the Could not save notification, and a failed autosave of a closed tab went to the console. Both are now written to the log file with their stack, so a report's log shows where the save failed.
2026-11-21 02:49:14 +08:00
Emir 51bab9a25b feat(i18n): add Turkish localization (#4881)
Turkish joins the UI languages (Settings > Appearance > Language), with the key catalog and the source-text catalog; tr / tr-TR system locales resolve to it.

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

Co-authored-by: laot7490 <[email protected]>
2026-11-21 02:01:59 +08:00
Vadim LazukandInf1mum 302c4068cf feat(agents): skills hub for every CLI, per-workspace modes, and per-session skills picker (#4879)
Fixes #3897 (phase 1)

Settings > Agents > Skills lists every skill found in the workspace (.agents/skills, .openidea/skills and each CLI's folder) and the user's folders (~/.agents/skills, ~/.claude/skills, ~/.copilot, ~/.codex, ~/.cursor), with symlinked copies collapsed and SKILL.md validated. Each skill can be auto, slash only or off, globally or per workspace ([agents.skills.<name>] in settings.toml). SKILL.md files are never edited. An untrusted workspace can only turn skills off. The composer gets a per-session Skills picker and /skills, and / completion offers active skills for every agent.

Sessions get their skills through a per-task folder that is rebuilt on each start: Claude Code via --add-dir and --settings skillOverrides, Copilot via skillDirectories/disabledSkills, Codex via skills/extraRoots/set and skills.config. Other ACP agents only get their / menu filtered.

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

Co-authored-by: Inf1mum <[email protected]>
2026-11-21 01:57:18 +08:00
l0ng-ai ff11932a65 fix(vcs): keep git status from rewriting the index (#4880)
Refs #4792

The dirty-scope status refresh (and the full one when gitoxide can't read the tree) ran git status, which writes refreshed stat data back to .git/index. The watcher can't tell that write from an external one, so it scheduled another refresh that could run git again. git status now runs with GIT_OPTIONAL_LOCKS=0 and leaves the index alone; our own gitoxide write-back is unchanged.
2026-11-21 01:45:09 +08:00
Ernstjan FreriksandEjaYF 745038b4e2 fix(markdown): zoom preview images with ⌘/Ctrl+wheel like Mermaid diagrams (#4729)
Images in the Markdown preview get the pan/zoom Mermaid diagrams already have: Cmd/Ctrl+wheel zooms the image at the cursor, drag pans once zoomed, double-click resets; the image keeps its place and size in the page and font zoom still scales it.

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

Co-authored-by: EjaYF <[email protected]>
2026-11-21 01:41:13 +08:00
Vladislav Kuzmin 3c3b26b419 fix(settings): wrap radio labels in narrow System Settings (#4841)
In a narrow Settings window, System Settings clipped the Open project in radio labels because they could not wrap; the labels now wrap within the group.

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

Co-authored-by: principalwater <[email protected]>
2026-11-21 01:39:48 +08:00
ntbang0901 1189a71205 fix(search): match Words like IntelliJ when the text starts or ends with punctuation (#4873)
With Words on, Find and Replace in Files missed matches whose text starts or ends with punctuation (doWork( in doWork(arg), [] in string[]) because ripgrep's word rule wants non-word characters on both sides. The whole-word check now follows the editor's rule: an identifier-character edge must not touch another identifier character (escapes like \n excepted), any other edge only needs a different neighbour, and a rejected match is retried from its next character; it sits in the shared match iteration so search, Replace, match_ranges and replace_in_text agree. $ counts as an identifier character.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 01:38:57 +08:00
ntbang0901 f27dea2d8a fix(search): Replace All past the match limit keeps to the search context (#4872)
Replace All after the search hit its match limit ignored the Search Context (e.g. In Comments also rewrote code and string literals): past the limit the scope is searched again to find files, and the replace step had no comment/string filter. The filter now lives in SearchContext::keeps, used by both the search engine and replace_files_in_context, with comments and string literals from the same literals_of in ide-host.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 01:37:09 +08:00
ntbang0901 7b5ff4e4b5 fix(search): list and replace every match of a very long line (#4871)
Find in Files dropped every match outside the window kept around the first match of a line longer than 500 UTF-16 units, so long lines showed one match and Replace All replaced only that one. Such a line now yields one LineMatch per window, so each match is listed, counted, navigable and replaceable with its own context; result rows are keyed by line and column, and the MCP text search matches each long line once.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 01:33:56 +08:00
ntbang0901 e94dc1baae fix(refactor): keep editors on files a refactoring renames or moves (#4868)
Renaming or moving a class through a refactoring closed the editor of the old file and never opened the new one: workspace edits applied through Documents::apply_workspace_edit_as reported only the affected paths, so the editor saw just the watcher's removal. WorkspaceEditApplied now carries the edit's file moves, and WorkspaceHistory makes open editors follow them on apply, Undo and Redo using the Project view's helper (moved to src/editor/fileMoves.ts), which now waits for the old tab to close before reopening and settles the record before reopening on Undo/Redo.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 01:30:12 +08:00
l0ng-ai 3228da223e fix(build): align the Dependency Analyzer panes (#4856)
Dependency Analyzer keeps module selection, search, scope or configuration, and conflict filtering in the main toolbar; the pane headers align the resolved dependency list with the selected dependency's usages, with list and tree controls beside the list, and narrow editors stack both panes.
2026-11-21 01:28:47 +08:00
ntbang0901 332334fb4f fix(outline): show type aliases a language server reports as variables (#4869)
TypeScript type aliases showed as variables in the Structure view and breadcrumbs, and Rust type aliases / associated types had no usages lens, because LSP has no kind for type aliases and servers report Variable or TypeParameter. doc_outline now takes the syntax tree's type kind (merge_kinds) where the server reported one of those placeholder kinds for a declaration the syntax outline types at the same name and position.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 01:26:41 +08:00
ntbang0901 047ec9d6bc fix(navigation): name a target's container only from a type whose body holds it (#4870)
Navigation choosers and gutter marker names took a target's container from the nearest type declaration above it without checking that its body was still open, so targets after a closed type got that type's name. enclosingType now uses a declaration only when its body holds the target: brace bodies count braces up to the target column (ignoring string literals), others use indentation; Go methods still use their receiver.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 01:25:20 +08:00
ntbang0901 912c710096 fix(agents): open binary session artifacts through the checked backend command (#4866)
Clicking a binary artifact (Word, Excel...) in an agent session's Artifacts popup always opened it as text: SessionAssets called the opener plugin's openPath, which the app capability does not grant. It now goes through fs_open_with_system, the checked command Open in Associated Application uses (local window, trusted project, existing file inside the project or its content roots), and still falls back to the editor when the backend refuses.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 01:24:27 +08:00
ntbang0901 38f1c4810c fix(run): rerun a root Gradle test run's failed tests in their own subprojects (#4862)
After a run of a multi-project Gradle build's plain test task, Rerun Failed Tests and running a selection from the test tree put every --tests filter on that plain task, so the first subproject without a match failed the build. Each failed class is now resolved to its module (the source lookup Application configurations use, now classModules) and its filter goes on that subproject's own test task (:alpha:test --tests A :beta:test --tests B --continue); the command line is unchanged when a class is not found in exactly one module, all tests are the root project's, or the run already names a task.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 01:23:57 +08:00
l0ng-ai 7fe7ec0fea style(cucumber): format the Python step files (#4877)
Runs oxfmt on the Python step files from #4859, which were merged unformatted and failed pnpm format:check on main.
2026-11-21 01:22:37 +08:00
l0ng-ai 423bf2c733 fix(settings): align Code Completion case choices (#4852)
Settings > Editor > General > Code Completion shows both case-matching choices beside the Match case checkbox; the options wrap when space is limited and stay visible when disabled, so the saved choice is easy to see.
2026-11-21 01:11:23 +08:00
l0ng-ai 73d1470940 fix(settings): align Actions on Save in a table (#4848)
Settings > Tools > Actions on Save groups the three save preferences in a table: each row keeps its description with the checkbox and shows Save or Save All in the trigger column while enabled; the scope switch and the whitespace settings link stay below the table.
2026-11-21 00:57:56 +08:00
l0ng-ai c83b0b1442 fix(settings): pair postfix templates with a code preview (#4843)
Settings > Editor > General > Postfix Completion puts the template list beside a preview of the selected template, showing the typed expression and its expansion from the existing template body; in narrow panes the preview moves below the list.
2026-11-21 00:41:46 +08:00
l0ng-ai d16993e175 fix(lsp): end a cancelled server task the server never ends (#4842)
Cancelling a server-reported background task (window/workDoneProgress/cancel) left it on Cancelling for good when the server never sent end, e.g. Pyright stuck before loading its workspace. The server now gets five seconds to end the task; after that the IDE ends it and clears the server's busy state, ignoring later reports on that token.
2026-11-21 00:36:53 +08:00
l0ng-ai 5d4cdac3c7 fix(settings): align the File Colors rules table (#4839)
Settings > Editor > File Colors puts the placement switches together above the rules; a table keeps scope names aligned with their swatches and colour names, with the toolbar and headings sticky while the rules scroll. The selected rule's editor sits directly below the table, and the colour controls wrap in narrow panes so the full hex value stays visible.
2026-11-21 00:25:48 +08:00
l0ng-ai 9c414cc75c fix(settings): align Editor General controls (#4827)
Settings > Editor > General: the mouse-wheel zoom scope choices sit beneath their checkbox as radio buttons, the soft-wrap file patterns field sits beside its checkbox (wrapping underneath in a narrow pane), and Scrolling follows Virtual Space with each caret behaviour on its own line.
2026-11-21 00:10:18 +08:00
Vladislav Kuzmin 3bbc90d750 test(debugger): expect watch for explicit Quick Evaluate (#4837)
Explicit Quick Evaluate sends DAP context watch since #4801 so method calls can run; the layout e2e test now expects watch for both evaluations.

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

Co-authored-by: principalwater <[email protected]>
2026-11-21 00:03:02 +08:00
ntbang0901 6d157c8b71 fix(debugger): stop at an uncaught exception from a traced stream so its records stay (#4851)
When a traced stream's terminal operation threw something the program does not catch, the trace lost its records: ide-dap reads them in the stop after its stepOut, and an uncaught exception ends the thread without one. Before parking a trace whose terminal threw, the jvm-inspect bundle now adds an uncaught-only ExceptionRequest on the traced thread (unless an enabled java-debug request already stops there), so the program stops at that throw and the trace shows the records with the exception. Bundle 1.1.1; the jar was rebuilt from source and matches byte for byte.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-20 23:57:05 +08:00
l0ng-ai f2c0fcdc96 fix(settings): align Smart Keys backspace and paste controls (#4823)
Settings > Editor > General > Smart Keys places the Backspace and paste formatting controls directly below the Enter options; the two controls share a label column and the paste escaping option sits below the formatting control.
2026-11-20 23:54:10 +08:00
ntbang0901 a4574fdc92 fix(debugger): show toString() of Java values instead of a nameless child row (#4857)
Java values whose class overrides toString() showed without their text, and opening them showed one nameless row with the fields a level deeper. java-debug marks these values with DAP presentationHint.lazy and the IDE ignored it. Variables now carry lazy; debug_resolve_variable merges the adapter's single inner variable into the row; debugger configs can declare resolve-lazy-variables (on for java-debug) so variables/evaluate return resolved values; other adapters resolve a lazy row in place when it is opened or its (...) marker is clicked.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-20 23:53:34 +08:00
ntbang0901 4bc87f5d84 fix(debugger): stay suspended on a thread its breakpoint still holds after another resumes (#4858)
Java debugging suspends only the thread that hits a breakpoint, but the Debug window tracked one stopped thread: after resuming it, the window showed Running with Resume and Step disabled while another thread was still stopped. The session now tracks every thread stopped alone (stopped adds, continued removes) and moves to a remaining stopped thread when the shown one continues; steps report all_threads_continued false since they run only their thread.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-20 23:50:14 +08:00
ntbang0901 39671ff55b fix(vcs): merge and rebase branches by their short name (#4850)
Merging a branch from the Branches popup recorded "Merge branch 'refs/heads/feature'" (and the rebase reflog "checkout refs/heads/feature") because the popup passes the full ref to avoid tags of the same name. Merge and rebase now pass the short name when it resolves to that same branch, and keep the full ref when a tag shares the name.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-20 23:47:32 +08:00
ntbang0901 881812547d fix(vcs): open the Conflicts dialog when an unstash stops on conflicts (#4849)
Applying or popping a stash that conflicts with the working tree showed an error balloon instead of the conflict resolver. unstash() was the only operation that can stop on conflicts without the conflict handler; it now uses conflictsInstead like merge, rebase and unshelve, so the Conflicts dialog opens. Other unstash failures still report the error.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-20 23:46:47 +08:00
ntbang0901 9c145ea258 fix(run): run a Gradle subproject's tests with that subproject's test task (#4846)
In a Gradle multi-project build, gutter class/method runs, Run on a test file and JUnit configurations used the build's plain test task, so --tests filtered every subproject and the first one without a match failed the build before the subproject holding the test ran. They now share inGradleModule (the lookup directory runs already used) and run :<subproject>:test --tests ...; reruns and test-tree selections inherit that task.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-20 23:45:45 +08:00
ntbang0901 4f192a12bc fix(run): let Maven reactor modules without the selected tests pass in every test run (#4845)
In a Maven multi-module project, Rerun Failed Tests and Run on a test file failed before the selected tests ran: -Dtest reached the first module without a matching test and Surefire stopped the build, skipping the module with the test. Those two paths built -Dtest themselves without -Dsurefire.failIfNoSpecifiedTests=false; every Maven test selection now goes through withMavenTests, which replaces an earlier -Dtest and always adds the flag.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-20 23:44:02 +08:00
ntbang0901 1d857375dc fix(vcs): open a multi-line selection's lines on the Git remote from Open In (#4844)
Editor > Open In > GitHub / GitLab / Bitbucket opened only the caret line even with several lines selected. The editor menu passed the caret line only and vcs.openOnRemote dropped endLine; the menu now takes its lines from the helper Copy Path/Reference uses (moved to selectedLines.ts) and Open In keeps endLine.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-20 23:43:20 +08:00
Vladislav Kuzmin 6543cdb36b test(debugger): expect unquoted strings in the value dialog (#4836)
The full-value dialog shows a string without its adapter quotes; the debugger layout e2e test now asserts the unquoted text there and keeps the quoted value in the Variables row.

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

Co-authored-by: principalwater <[email protected]>
2026-11-20 23:42:46 +08:00
Vladislav Kuzmin 684c92ce90 test(settings): target the exact font preview textbox (#4833)
The font-family e2e test matched both the editable preview and its resize handle through a substring label lookup; it now targets the textbox by its exact accessible name.

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

Co-authored-by: principalwater <[email protected]>
2026-11-20 23:42:38 +08:00
l0ng-ai 9a77a95180 feat(cucumber): behave and pytest-bdd step definitions in Python (#4859)
Python step definitions for Gherkin: behave decorators with its parse / cfparse / re matchers (use_step_matcher switches them), and pytest-bdd's exact strings and parsers.parse / cfparse / re. Covers navigation both ways, the Undefined step check and Create step definition (pending step_impl for behave, def _() for pytest-bdd, decorator added to the existing import). The backend scan reads .py files with a step decorator and skips site-packages.
2026-11-20 23:41:43 +08:00
l0ng-ai 1000ef0fa0 fix(editor): align code folding controls and arrow visibility (#4820)
Settings > Editor > General > Code Folding puts the outline visibility next to Show code folding outline (On hover / Always, new editor setting folding.outlineVisibility, default On hover) and lists the Fold by default options in one column. With Always, open fold arrows stay visible without hovering the gutter.
2026-11-20 23:40:32 +08:00
l0ng-ai 654da3e1ef feat(editor): spinner in progress hints (#4854)
Pending editor hints (Finding navigation target and other progress hints) start with the ring spinner used elsewhere in the UI; final hints are unchanged.
2026-11-20 23:21:16 +08:00
l0ng-ai ba6ccaf9b2 feat(vcs): option to open diffs in a separate window (#4853)
Adds Settings > Version Control > Confirmation > Open diff as editor tab (default on, client-side workflow setting vcs.diffAsEditorTab). When off, diffs opened from the Commit tool window, history, log and Compare show in a separate Diff window; combined multi-file diffs still open as a tab.
2026-11-20 23:17:37 +08:00
l0ng-ai 3ec631f0c0 fix(settings): pair inlay hint categories with a preview (#4815)
Settings › Editor › Inlay Hints lists the hint categories beside the selected category's toggle and a preview that uses the editor font and shows or hides the sample hint, instead of nested checkboxes. Searching selects the matching category.
2026-11-20 22:48:54 +08:00
Bert Verhelstandbertyhell f64796607c fix(linux): keep selections while a dead key is pending on Wayland with IBus (#4830)
On Linux Wayland with IBus, a pending dead key made WebKitGTK collapse every new selection in the window (Select All, mouse drags, text fields) through GTK's compositor input method (text-input-v3). Startup now selects GTK's own IBus module (GTK_IM_MODULE=ibus) on a Wayland session whose input method is IBus, unless GTK_IM_MODULE is already set or ibus-gtk3 isn't installed.

Co-authored-by: bertyhell <[email protected]>
2026-11-20 22:45:56 +08:00
Shohruh Ismoilovandshohruh-genius 5baaf5b7de fix(vcs): keep recent commits visible in workspace Git Log (#4826)
With Incoming Commits First, an older branch at the front of one repository's history could push that repository's latest commits out of the first page of a workspace Git Log. Each row now carries the newest commit time at or after it (logMergeTimeMs), and the multi-repository merge ranks by it, so recent commits stay visible while each repository keeps its selected order.

Co-authored-by: shohruh-genius <[email protected]>
2026-11-20 22:43:30 +08:00
faysouandfaysou 95f88f6ffb fix(vcs): clarify Project tree Git indicators (#4818)
The Project tree's Git suffix shows the branch, then the incoming / outgoing commit counts, then the working-tree state after a slash: ∅ when no files changed (also when the branch is ahead or behind), else the changed-file count with Δ. The color scheme preview shows the same markers. The changed-files tooltip keeps its text-catalog key.

Co-authored-by: faysou <[email protected]>
2026-11-20 22:40:29 +08:00
Bert Verhelstandbertyhell 06b7c3a826 feat(keymap): find actions by typing their shortcut in the search field (#4817)
The Keymap search field also matches typed shortcut text: ctrl+shift+n, Shift+Ctrl+N, ctrl shift n, cmd+shift+o and ⇧⌘O all work, with aliases such as control, cmd, option and esc. Modifiers alone list every shortcut holding them; once a key is typed the modifiers must match exactly, and chords match stroke by stroke. Plain words still search action names only.

Co-authored-by: bertyhell <[email protected]>
2026-11-20 22:40:19 +08:00
Vladislav Kuzmin e9335f032d fix(database): support strict read-only ClickHouse without affinity (#4788)
A strict read-only ClickHouse account rejects the driver's per-request result settings (code 164), so stateless sources behind a load balancer could not connect. With use_http_session=false and Read-only enabled, the connection check is repeated without the driver's result-limit and number-format settings; every request still sends readonly=1, the client-side write guard stays on, the grid keeps only the requested rows, and KILL QUERY also carries readonly=1.

Closes #4783

Co-authored-by: principalwater <[email protected]>
2026-11-20 22:36:23 +08:00
Vladislav Kuzmin d09fdc8c7e fix(database): clarify the JDBC cancellation timeout (#4749)
When a JDBC statement misses the cancellation deadline the session is closed; the error now says to check the statement's status on the server before running it again and that the next query reconnects on its own, instead of asking for a manual reconnect.

Closes #4742

Co-authored-by: principalwater <[email protected]>
2026-11-20 22:35:52 +08:00
l0ng-ai 54e69973c8 fix(settings): fit notification group controls in the settings pane (#4810)
Settings › Appearance & Behavior › Notifications shows the notification groups as a list beside the selected group's popup type and tool window option instead of a wide table, and stacks them in a narrow settings pane. Searching selects the matching group.
2026-11-20 22:32:08 +08:00
l0ng-ai 91d37aa4bf fix(templates): fit File and Code Templates in narrow settings (#4805)
Settings › Editor › File and Code Templates uses the shared compact tabs and a resizable list / editor split that keeps the editor usable in narrow settings windows.
2026-11-20 22:30:34 +08:00
l0ng-ai e149ba2ab3 fix(editor): keep completion aligned on first paint (#4797)
The completion list could paint one icon column right of the caret and then jump into place. The editor now positions it before the first paint, also when local suggestions arrive while a language server is still responding, and repositions it in the same frame when its size changes.
2026-11-20 22:28:14 +08:00
l0ng-ai fc6de7d0e4 fix(lsp): send language servers their configuration once initialized (#4831)
Pyright, given a client with workspace folders, asks for its configuration and loads the workspace only after workspace/didChangeConfiguration. The notification was sent only when a server had user settings, so Pyright stayed idle and navigation, references and diagnostics never answered. Send it to every server after initialized.
2026-11-20 22:27:10 +08:00
l0ng-ai 76ef8c9b05 fix(templates): stack the Live Templates list and editor (#4802)
Settings › Editor › Live Templates stacks the template list above the editor in a resizable split, puts Abbreviation and Description on one row (stacked in narrow settings), labels the template text, and keeps the variables table within the pane.
2026-11-20 22:25:10 +08:00
l0ng-ai 0344553652 fix(refactor): align the Safe Delete dialogs (#4800)
The Safe Delete confirmation and the Usages Detected question use the form layout: the usage count as a heading, the detail below it, and no question icon.
2026-11-20 22:19:48 +08:00
l0ng-ai cf15013b49 fix(templates): align and scroll the Surround With menu (#4796)
Surround With gets a separate shortcut column and uses the UI font for action labels. The list scrolls within the space beside the caret, and the title stays visible while the keyboard moves through it.
2026-11-20 22:18:11 +08:00
l0ng-ai eb985cda28 fix(project-view): keep the tree from scrolling sideways while dragging (#4828)
WebKit autoscrolls the pressed tree toward a pointer right of it, so dragging a file to the editor, terminal or out of the window scrolled long rows out of view. The drag now holds the horizontal scroll position for its whole length, as it already held the vertical one outside the tree.
2026-11-20 22:12:42 +08:00
Bert Verhelstandbertyhell 212ee03d71 feat(project-view): drag files out to other apps (#4245)
When a drag from the Project view leaves the window it becomes an OS file drag (copy only) of the selected local files and folders: AppKit dragging session on macOS, OLE CF_HDROP on Windows, GTK on Linux, in the new ide-drag-out crate behind the window_drag_files command. A drop back on the window itself is ignored, and remote projects keep the in-window drag only.

Closes #2867

Co-authored-by: bertyhell <[email protected]>
2026-11-20 22:10:02 +08:00
l0ng-ai b721fe09db fix(debugger): drop grandchild sessions and overwrite progress lines (#4825)
Removing a debug session dropped only its direct children, so js-debug's grandchild sessions (pnpm run dev -> pnpm.cjs -> rspack.js) were orphaned and piled up with every rerun; a session now goes with all its descendants. The debug console also appended text after a carriage return instead of replacing the line; as in the Run console, a carriage return or erase-line now makes the next text replace it, so progress bars update in place.
2026-11-20 21:57:09 +08:00
l0ng-ai 6ffb4c22f0 fix(editor): keep syntax highlighting after reformatting JavaScript (#4822)
Re-parsing after an edit could reuse a whole doc comment (a skipped node) from the old tree. @lezer/lr's Stack.useNode then moved reducePos past it and storeNode didn't move reused skipped nodes out of the node being reduced, so the declaration before the comment swallowed the rest of the file and highlighting vanished until the next edit. A pnpm patch for @lezer/lr fixes both; a regression test compares the incremental tree with a fresh parse.
2026-11-20 21:50:50 +08:00
l0ng-ai dc38b0b081 fix(vcs): stop Git Log panes flashing a scrollbar while resizing (#4821)
The split panels' own overflow: auto showed a native scrollbar whenever a fractional panel height left 1px of rounding overflow, so it flickered while the tool window was dragged. The log's panes scroll themselves; their panels now clip instead.
2026-11-20 21:45:39 +08:00
l0ng-ai 3cbc9d7f75 perf(index,vcs): cut backend memory after indexing large folders (#4814)
Opening a folder with many large Git repositories kept the backend at about 2.2 GB after indexing. redb's page caches (1 GiB default per database) are capped at 64 MiB for the symbol index and 32 MiB per repository commit log, and after a full scan the backend returns freed heap pages to the OS (malloc_zone_pressure_relief on macOS, malloc_trim on glibc). On 16 repositories / 152k files the footprint after a cold index dropped from 2226 MB to 1078 MB with unchanged index and log query times.
2026-11-20 21:02:17 +08:00
l0ng-ai 2ec2a6c262 feat(run): insert path macros into a run configuration's working directory (#4816)
A + button next to the working directory field lists the supported path macros ($USER_HOME$ only on a local project) and inserts the chosen one at the caret.
2026-11-20 20:50:49 +08:00
C3B6 11dca3ab42 feat(agents): check and update local npm CLI installs (#4778)
A built-in agent's settings page can check its global npm installation for a newer release and update it. The backend (ide-agent cli_update) runs npm prefix/view/install as cancellable requests, and only touches the installation the launcher actually runs: the executable must be the npm-generated link of that exact package, the prefix must be writable, and the install verifies the version afterwards. Native installs and pre-release channels are left to their own installers.

Co-authored-by: 0xC3B6 <[email protected]>
2026-11-20 20:43:50 +08:00
faysouandfaysou f9044dcc00 fix(markdown): scope the split divider cursor (#4811)
The splitter library applied a document-wide resize cursor while the pointer was near the divider, so it showed over the source editor's scrollbar. The Markdown split now keeps the divider's own hover cursor and shows the resize cursor only inside the split while dragging.

Co-authored-by: faysou <[email protected]>
2026-11-20 20:38:01 +08:00
l0ng-ai a7d7293b2f feat(run): expand path macros in a run configuration's working directory (#4813)
A run configuration's working directory may use $PROJECT_DIR$, $ContentRoot$, $MODULE_DIR$, $MODULE_WORKING_DIR$ and $USER_HOME$, expanded when it runs or is debugged; the stored value keeps them. An unknown macro, or one without a value in a remote project, stops the start with a notification naming it.
2026-11-20 20:35:24 +08:00
faysouandfaysou a5280c50f7 feat(vcs): show changed file counts for repos and folders (#4806)
The Changes tree showed a file count only on change-list groups. Repository and directory rows now show how many changed files they hold, subdirectories included; repository rows keep the branch after the count.

Co-authored-by: faysou <[email protected]>
2026-11-20 20:23:47 +08:00
l0ng-ai dd0578979a feat(spelling): load custom Hunspell dictionaries with their affix rules (#4808)
Custom .dic files were read as flat word lists, dropping /FLAGS and ignoring the .aff beside them, so inflected forms and compounds were flagged and suggestions were English only. A .dic with a sibling .aff now loads as a full Hunspell dictionary, and suggestions merge the English and custom Hunspell dictionaries.
2026-11-20 20:22:23 +08:00
l0ng-ai e96b0483ac feat(go): show the values of constants as inlay hints (#4807)
gopls computes constant values, iota sequences included, but reports them as inlay hints only with its constantValues hint on; the Go language definition now enables it.
2026-11-20 20:16:41 +08:00
Yann 608b292510 fix(agents): keep context menus from switching conversations (#4804)
Right-clicking another task in Agents selected it through the same callback that opens conversations, replacing the current chat or file. Tree now marks context-menu selections (right-click, and Control-click on macOS) so the Agents view updates the menu target without navigating; ordinary clicks, keyboard activation and multi-selection are unchanged.

Co-authored-by: YannABC <[email protected]>
2026-11-20 20:02:25 +08:00
l0ng-ai dd6d83fd2c feat(services): show the debugger of a service in the Services tool window (#4803)
Debugging from Services showed only the console in the detail pane and the first breakpoint switched to the Debug tool window. The detail pane of a configuration being debugged now shows the whole debugger for that session (an attached run's console stays its Console tab), and a session started in place from Services reveals Services on a stop and reruns in place.
2026-11-20 20:01:08 +08:00
l0ng-ai b89febd61f fix(debugger): quick-evaluate the whole method call under the mouse (#4801)
Quick Evaluate built the expression from the identifier and its member chain only, so on o.getX() it sent o.getX, which Java adapters resolve as a field, and it evaluated with the hover context, in which adapters refuse to call methods. Quick Evaluate and the Evaluate dialog seed now take the call of the clicked identifier and member chains through calls and indexing, and Quick Evaluate uses the watch context. Plain hovers and value-on-selection stay side-effect free.
2026-11-20 19:55:07 +08:00
faysouandfaysou 99ca421a0e fix(markdown): keep the preview live after scrolling (#4798)
The live preview plugin read editor geometry inside a CodeMirror update after the source scrolled, so CodeMirror threw and disabled the plugin and the preview stopped following Find and edits. The top-line read now goes through requestMeasure.

Co-authored-by: faysou <[email protected]>
2026-11-20 19:45:01 +08:00
l0ng-ai e6fd000bb7 fix(coverage): keep statistics aligned in the tool window (#4794)
The coverage tool window keeps its statistics columns aligned with the tree rows at every width.
2026-11-20 19:41:48 +08:00
l0ng-ai 9e2e229a56 fix(project-trust): show the selected trust scope in the open prompt (#4789)
The open-project trust prompt shows the selected trust scope: checking Trust projects in names the folder and the primary button becomes Trust Folder.
2026-11-20 19:41:39 +08:00
l0ng-ai 60564f4b33 Show an editor-sized tree for Quick Evaluate objects (#4784)
Quick Evaluate shows an object as an editor-sized tree that fits the window instead of a cramped popup.
2026-11-20 19:41:31 +08:00
l0ng-ai db1fff2f6a Align inline Git change previews with the editor (#4780)
Inline Git change previews from the gutter now use the editor's font, line height and widths, so the previewed lines line up with the editor.
2026-11-20 19:41:23 +08:00
l0ng-ai 1c09fbe28a Align the Rollback Changes dialog (#4770)
The Rollback Changes dialog gets a consistent layout with a change summary and an explanation of what rollback discards.
2026-11-20 19:40:42 +08:00
l0ng-ai 834fac89b4 Align selection history preview and revision table (#4764)
The selection history dialog aligns its preview and revision table and keeps both usable in narrow panes.
2026-11-20 19:40:33 +08:00
l0ng-ai 844e290729 Keep the scratch language chooser usable in short windows (#4750)
The scratch file language chooser keeps its search field and list usable in short windows instead of overflowing.
2026-11-20 19:40:24 +08:00
l0ng-ai a1ab5b6c29 Wrap diagnostic hovers and quick fixes inside the editor pane (#4745)
Diagnostic hovers now fit the editor pane: long messages and quick-fix labels wrap, text aligns with the severity icon, shortcuts are smaller and muted, and a divider separates overlapping diagnostics.
2026-11-20 19:40:16 +08:00
Yann 9797598864 feat(agents): open conversations in separate windows (#4790)
Open in New Window moves an agent conversation to a lightweight editor window while its task and agent process keep running. The agent manager now keeps one event sink per window instead of a single one, lightweight windows keep their launch across webview reloads, and the project window keeps the task list, notifications and a copy of the unsent draft; closing the window brings the conversation and its draft back.

Co-authored-by: YannABC <[email protected]>
2026-11-20 19:36:19 +08:00
faysouandfaysou 21a8856dfd fix(markdown): render protected inline math (#4787)
GitHub-style protected inline math ($`...`$) passed the backticks to KaTeX. The math tokenizer now matches the protected form first, passes only the formula, and keeps nearby prices, emphasis and unfinished delimiters intact.

Co-authored-by: faysou <[email protected]>
2026-11-20 19:21:41 +08:00
faysouandfaysou 9c523bba36 fix(markdown): keep Mermaid math labels inside nodes (#4786)
WebKit painted relatively positioned native MathML wrappers in Mermaid labels at the SVG origin, leaving nodes empty. Native MathML KaTeX labels inside foreignObject are now statically positioned so each formula paints inside its node.

Co-authored-by: faysou <[email protected]>
2026-11-20 19:21:34 +08:00
l0ng-ai 8f3e20cdf8 fix(debugger): show and copy the whole value of a long string (#4795)
The value popup showed the adapter's truncated, escaped value in a modal only its close button dismissed. It now re-evaluates the variable in the clipboard context for the full value, shows strings unescaped with real line breaks, and closes on an outside click; Copy Value of a string gets the full value too.
2026-11-20 19:08:31 +08:00
l0ng-ai affee5452d fix(settings): flag a Maven thread count Maven would not accept (#4793)
Settings › Maven › Thread count drops any value Maven would not accept as -T (a count or a core multiplier) so it cannot break builds, but said nothing, leaving builds serial. The field now marks such a value invalid and explains the accepted forms, using the same rule as the backend's thread_count().
2026-11-20 19:01:43 +08:00
l0ng-ai 4149c1b5d7 fix(http): follow system proxy changes in Auto proxy mode (#4791)
In Auto-detect proxy mode the shared HTTP client was cached per proxy setting and kept the system proxy it saw when first built, so a proxy app switching the system proxy on after launch left plugin downloads going direct until a restart (Check connection, a fresh client, worked). The cached client now remembers the system proxy it was built with, re-read at most every 3 seconds, and is rebuilt when it changes.
2026-11-20 18:53:44 +08:00
l0ng-ai 52010b95b1 Keep navigation bar child lists within the viewport (#4740)
The floating navigation bar keeps its path visible while a segment's child list is open: the list anchors to that segment and scrolls within the viewport. Both navigation bar placements share compact row spacing and font size, keep full names on hover, and open toward the editor.
2026-11-20 18:45:16 +08:00
l0ng-ai 9e530a9024 fix(debugger): enable Stop for the selected debug session only (#4785)
Stop in the Debug tool window was enabled whenever any session was live, so a finished session's tab showed an active Stop that did nothing. It now follows the selected tab like Rerun, Resume, Pause and the step buttons; with no tab selected it still acts on any live session.
2026-11-20 18:34:04 +08:00
eclix-del aebc7f7f99 fix(database): quote completions of custom JDBC sources by their URL's dialect (#4765)
A custom JDBC source has driver "jdbc", so completion quoted only names that aren't plain words. On Oracle (and other case-folding servers) a mixed-case table such as BAS_MeterUnit was inserted bare and folded to BAS_METERUNIT (ORA-00942).

Completion now takes the dialect from the source's URL scheme (jdbc:oracle:thin:@…, jdbc:postgresql://…), using the vendor scheme table Data Source from URL already uses, and quotes table, column and JOIN candidates the way that dialect needs. Unknown schemes keep the previous behaviour.

Co-authored-by: eclix-del <[email protected]>
2026-11-20 18:27:18 +08:00
eclix-del 1586738468 fix(database): complete only the schemas a data source selects (#4766)
JDBC completion read the columns of every schema on the server. The JDBC bridge runs one command at a time, so on a large Oracle instance (dozens of system schemas, minutes of metadata) the user's statements queued behind it.

Completion now reads only the schemas the data source's Schemas tab picks, matched the way the database tree matches them (exact names, `*` / `?` patterns); sources that show all schemas behave as before.

Co-authored-by: eclix-del <[email protected]>
2026-11-20 18:25:54 +08:00
akshathayadav378-boopandakshathayadav378-boop 7ec5080047 fix(database): preserve table horizontal scroll position (#4779)
Database table tabs remember their horizontal scroll offset when the tab is mounted again (more than five kept table tabs, or the table opened in a split pane), alongside the page, sort and filter they already remembered.

The offset lives in a ref and is written straight into the remembered view state, so scrolling sideways doesn't re-render the editor; the grid restores it once on mount, retrying as the columns are measured.

Co-authored-by: akshathayadav378-boop <[email protected]>
2026-11-20 18:21:33 +08:00
akshathayadav378-boopandakshathayadav378-boop 06d7487913 perf(events): coalesce diagnostics within a frame (#4767)
Diagnostics events are full replacements for one (path, source), but the desktop sink serialized and emitted each one immediately. Repeated diagnostics now collapse to the latest within a 16 ms window, any other event flushes pending diagnostics first so ordering is kept, and the buffer flushes at 4,096 keys instead of dropping. Installed on the global and per-window sinks; part of #3937.

Co-authored-by: akshathayadav378-boop <[email protected]>
2026-11-20 18:13:40 +08:00
zhzhsxandzhzhsx e676138956 fix(editor): go to implementation falls back to the declaration (#4768)
Go to Implementation on a reference to a symbol with no implementations now navigates to the symbol's declaration instead of stopping on No implementations found, including servers that fail the request rather than answer empty (gopls). On the declaration itself it still reports nothing found.

Co-authored-by: zhzhsx <[email protected]>
2026-11-20 18:02:00 +08:00
Muuandmuutot 1a1ea14b9c fix(vcs): allow Add to .gitignore for attached projects' repositories (#4751)
In a window with an attached project, Add to .gitignore / .git/info/exclude on an untracked file of the attached repository failed with Ignore selection is outside the project: the guard checked the project folder only. It now also accepts any path in one of the window's repositories, the set the Changes view lists; paths inside the project folder stay accepted before that set is discovered.

Co-authored-by: muutot <[email protected]>
2026-11-20 17:59:44 +08:00
l0ng-ai 5c0917b849 feat(vcs): ⌘/Ctrl-click a repository in the log filter to see only it (#4774)
Cmd-click (macOS) or Ctrl-click on a repository in the Git Log's Repository filter now shows only that repository; a plain click still adds or removes it, and each row's tooltip says so. Menu items gain an optional modifier-click action and a row tooltip.
2026-11-20 17:55:52 +08:00
l0ng-ai 19f2c0ef5d feat(http-client): Reformat Code formats JSON request bodies (#4771)
Reformat Code in an .http file reported No language server available. The HTTP Client now contributes a formatter that re-indents each request's JSON body, keeping {{variables}} and number literals as written and leaving headers, response handlers, references and file inputs alone.
2026-11-20 17:50:24 +08:00
l0ng-ai 8c696b8fe7 test(e2e): follow the split panes of the Inspections and Plugins settings (#4769)
#4629 and #4636 moved the Inspections and Plugins settings into resizable split panels; the shared settings layout specs now select the details section and profile label through the new structure.
2026-11-20 17:44:36 +08:00
l0ng-ai deecdbbf4f test(e2e): fix the Python highlighting and Recent Locations specs (#4752)
pythonHighlight: the fixture's Darcula-based scheme doesn't name NOT_USED_ELEMENT_ATTRIBUTES, which since #4737 comes from Darcula (#72737A). recentNavigationLayout: the snippet height check allows a fractional pixel (89.94px vs 90px).
2026-11-20 17:29:09 +08:00
Muuandmuutot 802400c324 fix(editor): keep long blame tooltips inside a scroll container (#4741)
Hovering the inline blame label of a commit with a long message spilled the tooltip over the workbench: it had only a max-width, and the shared editor theme never made the hover host a column flex container, so CodeMirror's height cap near the window edge did not clip it. The blame tooltip now caps its height and scrolls inside, and the base editor theme lets hover sections shrink inside the squeezed host (the rules LSP hovers already had).

Co-authored-by: muutot <[email protected]>
2026-11-20 17:24:40 +08:00
Ziop edc6a522ee fix(search): find a pasted Windows absolute path by its project-relative path (#4739)
On Windows, pasting a plain absolute path such as E:\work\project\pkg\Config.go into Search Everywhere found nothing: backslashes were converted only when the paste had no forward slash, the project-root prefix was compared case-sensitively although drive-letter paths are not, and a \\?\ prefix was kept. The query parser and the index now reduce an absolute path below the project root to its project-relative form (case-insensitively for drive-letter roots), with mixed separators and verbatim prefixes handled.

Co-authored-by: wangpi26 <[email protected]>
2026-11-20 17:14:43 +08:00
Vladislav Kuzmin 0c7a278ca6 fix(database): execute SQL from read-only editor files (#4608)
Running SQL with Cmd+Enter in a read-only SQL file left Results stuck on Executing: the file lock removes the SQL editor's run-state field, so setting up the progress marks threw before execution. The marks are now skipped when the field is absent, and a failure while setting them up still clears the running request.

Co-authored-by: principalwater <[email protected]>
2026-11-20 17:12:51 +08:00
l0ng-ai 8c93136063 feat(remote): Download to… in a remote project's Project view (#4748)
In an SSH project window, the Project view's context menu and the action Download to… copy the selection into a local folder over the window's SSH session (new desktop command remote_download_local), with a cancellable progress task and a failure report. The download loop of Remote Host › Download to… is shared, including its guard against writing outside the chosen folder.
2026-11-20 17:11:40 +08:00
l0ng-ai e20e7b04bc feat(run): Diagnose with Agent on a failed test (#4744)
A failed test's context menu in the test tree gets Diagnose with Agent while the agents feature is active. It appends the failure (test name, source location reference, expected/actual when the framework names them, first 60 output lines) to the agent message typed last and opens it for review.
2026-11-20 16:54:20 +08:00
l0ng-ai f325e8c9d6 Align Inspection Results panes and actions (#4734)
Inspection Results aligns its result tree, detail pane and action toolbar: the panes keep usable widths and the actions stay grouped and labelled for assistive technology.
2026-11-20 16:41:33 +08:00
persicaTaoandpersicaTao 84edcc03a4 fix(run): pass the tool search path to script launches (#4732)
On Windows an auto-detected npm run start found npm.cmd on the login-shell and user PATH and started it by full path, but the script it ran only inherited the IDE process PATH, so 'node' was not recognized. A run now passes the same search path it used to resolve its program to the child, unless the configuration sets PATH itself or turns off the system environment.

Co-authored-by: persicaTao <[email protected]>
2026-11-20 16:40:37 +08:00
youngledoandyoungledo 4146ca2041 fix(app): list open projects in the macOS Window menu (#4736)
On macOS the Window menu did not list open project windows: the submenu was registered as the application's windows menu while the menu was still being built, before set_menu attached it to NSApp, so muda skipped it. It is now registered after the menu bar is installed, and AppKit lists each window by its title (project or workspace name, plus the current file).

Co-authored-by: youngledo <[email protected]>
2026-11-20 16:39:02 +08:00
l0ng-ai 105c37360b fix(editor): give Darcula-based imported schemes Darcula's colours (#4737)
An exported IntelliJ scheme lists only what differs from its parent. One based on Darcula that left TEXT out got Islands Dark's editor background (#191a1c) instead of Darcula's #2b2b2b, and likewise for every attribute it left out. Attributes a Darcula-based scheme doesn't name now come from Darcula, in both Color Scheme import and IntelliJ theme plugin import; exports write an empty value for an attribute they have nothing for so the parent can't show through on re-import; and an imported scheme's gutter follows its editor background unless it sets its own.
2026-11-20 16:26:23 +08:00
TWINKLE 567b432468 fix(terminal): upgrade xterm to 6.1 for the IME anchor and viewport fixes (#4714)
xterm 6.0.0 anchors the IME candidate window and preedit to its helper textarea, which only follows the cursor while no composition runs. Agent TUIs park the cursor at the end of a chunked redraw, so a composition starting then appeared at the far edge. 6.0.0 also left the viewport at line 0 after ESC[3J trimmed the scrollback. Both are fixed upstream in 6.1 (xtermjs#5759, #6046), which is only available as a beta.

- Move @xterm/xterm, addon-fit and addon-search to the 6.1 betas, pinned to exact versions until 6.1 is stable.
- Adapt to overviewRuler -> scrollbar (option and DOM class names) and to the DOM renderer's new createRow blink arguments in the cached renderRows; the version guard refuses renderers without them.
- Re-check the IME patches against 6.1 and update their rationale.
- Stub a 2D canvas context in the test setup, which 6.1's renderer needs under jsdom.

Co-authored-by: H-TWINKLE <[email protected]>
2026-11-20 16:09:13 +08:00
l0ng-ai f13d2b46cd Align the Scopes settings list and editor (#4731)
Scopes settings place the scope list beside the Name and Pattern fields in wide windows and stack them in narrow ones. Scope names use the standard UI text size with the full name and pattern on hover, keyboard selection stays visible, and adding a scope selects its default name for editing.
2026-11-20 16:07:25 +08:00
l0ng-ai 266bd35a3d Keep Attach to Process columns readable in compact windows (#4726)
Attach to Process uses a resizable dialog with Executable, PID and Command line columns; the list scrolls under a fixed header while the filter and actions stay in view. Compact dialogs show the debug port beside the command line with the full endpoint on hover, and long executables and commands have tooltips.
2026-11-20 15:51:30 +08:00
l0ng-ai 330d45279b Align the Git Remotes table and edit form (#4724)
Git Remotes uses dedicated Name and URL columns with a fixed header; long values keep their own space and show in full on hover. The list scrolls inside a resizable dialog with the toolbar and footer in view, keyboard selection brings the row into view, and the edit form aligns both labels beside their fields.
2026-11-20 15:39:03 +08:00
shanyuea af0e9c9a55 feat(vcs): synchronous branch control for projects with several repositories (#4723)
In a project with several Git repositories, branch operations follow a new setting, Settings > Version Control > Git > Execute branch operations on all repositories (on by default). On: the branches popup lists branches common to all repositories and acts on all of them, also when they are on different branches (it says Branches have diverged, and checking out a common branch moves only the repositories not on it); common branches gain Rename and Checkout and Rebase onto Current; each multi-repository operation can be rolled back when one repository fails. Off: the popup acts on the selected repository only. The Git log's Branches pane lists each branch once with the repositories that have it, with Group by Repository to switch back.

Co-authored-by: shanyuea <[email protected]>
2026-11-20 15:37:18 +08:00
l0ng-ai 0e1a5e47d3 Keep keyboard-selected menu rows visible and align shortcuts (#4721)
The shared action menu scrolls the keyboard-focused row into view when the menu is taller than the window. Shortcuts share a right edge with a separate column for submenu arrows, long shortcuts truncate while leaving room for the label, and rows use the standard UI text size.
2026-11-20 15:30:36 +08:00
l0ng-ai 5226443670 Keep Extract Interface members readable in short windows (#4720)
The Extract Interface dialog keeps its member table readable in short windows: the table takes the remaining height with a Member header and scrolls, while the name and package fields stay in view.
2026-11-20 15:28:44 +08:00
l0ng-ai 07191394a5 Align the Environment Variables editor in run configurations (#4715)
The run configuration Environment Variables editor aligns its table, toolbar and options in a fixed-height dialog, with the focused row outlined, so long lists and values stay readable.
2026-11-20 15:27:46 +08:00
l0ng-ai 882a08c5a4 fix(java): honor the java-analyzer debug fallback (#4719)
When JDT LS is enabled but missing (e.g. on a WSL remote host), the editor falls back to java-analyzer, but Run and Debug still treated jdtls as serving the module and failed with 'jdtls is not installed'. Choosing the server for the classpath and debugger now skips a jdtls that gave up starting.
2026-11-20 15:26:35 +08:00
Muuandmuutot 8b5a9f582f fix(sdk): resolve the effective Python interpreter off the main thread (#4713)
sdk_python_effective was a sync command, so Tauri ran it on the main thread, where merging a workspace member's settings from scratch could overflow the remaining stack inside a WebView2 IPC callback and crash on start-up. It now runs on the blocking pool like the other SDK probes, and a workspace file that fails to load falls back to the primary project's interpreter.

Co-authored-by: muutot <[email protected]>
2026-11-20 15:24:54 +08:00
akshathayadav378-boopandakshathayadav378-boop 1a430e5fdb fix(settings): show inherited static symbol italics (#4722)
Static symbols render italic by default, but the color scheme settings reported the inherited value as not italic, so the Italic checkbox showed unchecked and unchecking it changed nothing. Static symbol, and PHP's Static field that inherits it, now declare the renderer's italic default, so the page shows the applied state and unchecking writes an explicit upright override.

Co-authored-by: akshathayadav378-boop <[email protected]>
2026-11-20 15:19:34 +08:00
C3B6 7b2ba44a8d feat(agents): show the Claude Code context window breakdown (#4710)
Clicking the agent status bar's context meter in a Claude Code session opens a breakdown of the context window read on demand from the CLI's get_context_usage control request (system prompt, tools, MCP, memory files, skills, messages, autocompact buffer, free space), with the auto-compact threshold and a Compact session button when the session offers /compact. Other providers keep the plain meter with its tooltip.

Co-authored-by: 0xC3B6 <[email protected]>
2026-11-20 14:46:35 +08:00
l0ng-ai e6905f288e fix(vcs): align the Git Conflicts dialog (#4709)
The Conflicts dialog puts the merge status and file count above a larger, resizable file list; the resolution actions sit beside the list and move below it in narrow windows, and file names keep their width before long directory paths are shortened.
2026-11-20 14:38:59 +08:00
l0ng-ai 1828601b2a fix(project): align the file Copy dialog (#4706)
The Copy dialog states what it copies (file, directory or item count) above aligned New name / To directory fields, with the directory hint under its field and the Open copy in editor option in the footer.
2026-11-20 14:30:52 +08:00
l0ng-ai 463b13b6b5 fix(project): align the file deletion confirmation (#4703)
Message dialogs gain a form presentation: a titled dialog with the message and checkbox stacked in the body instead of an icon layout with the checkbox in the footer. The project tree's Delete confirmation uses it when Safe delete is offered.
2026-11-20 14:29:27 +08:00
l0ng-ai 84cdfa2136 fix(settings): align Gutter Icons in a preview list (#4702)
Gutter Icons puts its five options in one bordered list under the master checkbox, each with a representative icon or color swatch, aligned checkboxes and labels at the standard settings font size, keeping search matches visible in a narrow pane.
2026-11-20 14:28:25 +08:00
l0ng-ai 2bb93366bb fix(editor): show encodings in one searchable picker (#4697)
The status-bar encoding item opens a searchable Change File Encoding popup (checked current encoding, BOM toggle, link to File Encodings settings). Picking an encoding asks whether to reload the file in it or convert the current text on save.
2026-11-20 14:27:01 +08:00
l0ng-ai 7ee0a99853 fix(settings): keep Directory Mappings readable while scrolling (#4695)
Directory Mappings is a table with Directory and VCS columns that stays readable while scrolling, with add and remove in its toolbar.
2026-11-20 14:22:43 +08:00
l0ng-ai 7f21fdbe4d test(settings): expect the New tab choice in Open project in (#4708)
The Settings dialog test still expected exactly three Open project in choices after New tab in current window was added.
2026-11-20 14:21:49 +08:00
l0ng-ai d47e9688cb fix(editor): align the line and column dialog (#4693)
Go to Line puts its label and coordinate field on one row in the workbench UI font, and opening it selects the current coordinates so they can be typed over.
2026-11-20 14:17:45 +08:00
l0ng-ai 94e318e740 fix(templates): align the new file name and kind picker (#4690)
The new-file naming popup opens centered with an inset name field, template icon and divider above the kind list; the kind list uses standard selection rows, scrolls in short windows, and arrow keys keep the selected kind in view while the name field keeps focus.
2026-11-20 14:15:56 +08:00
l0ng-ai 6303cd5aef feat(editor): load or keep a file that changed on disk with unsaved edits (#4707)
A file changed on disk while its buffer had unsaved changes was reported with a fixed English notification and no way to take the disk version. The backend now emits DocDiskConflict and the editor shows a localized prompt with Load Changes from Disk (new doc_reload_from_disk: drops the buffer's changes and reads the file again) and Keep Editor Changes.
2026-11-20 14:12:14 +08:00
l0ng-ai 748f567abc fix(run): detect Spring Boot applications from Spring Boot on the classpath (#4705)
A @SpringBootApplication main class only became a Spring Boot configuration when its module or a parent POM applied spring-boot-maven-plugin, so modules that get Spring Boot as a dependency (directly, from spring-boot-starter-parent, or through the BOM) stayed plain Java applications. A module now counts when its build or a parent build in the project references Spring Boot outside <pluginManagement>; Gradle modules also count with an org.springframework.boot dependency.
2026-11-20 13:58:56 +08:00
l0ng-ai 9fe1dd8d7b feat(run): expand multi-line run configuration fields into a larger editor (#4704)
VM options and the other multi-line run configuration fields get an Expand button (Shift+Enter) opening a resizable editor where each line stays on one visual line and scrolls sideways, so a long JVM argument isn't wrapped into what looks like several. OK applies; Cancel or OK without edits leaves the field unchanged.
2026-11-20 13:49:43 +08:00
langxpandkradme c0b243f020 feat(maven): add POM artifact and managed-version navigation (#4699)
Go to Declaration on a dependency, plugin or <parent> in a POM opens the artifact's own POM (a workspace module with matching coordinates first, then the local repository), and unversioned dependencies and plugins get a gutter icon that opens the management entry supplying their version, through active profiles (including JDK-activated ones), parent POMs, imported BOMs and plugin management. Maven element values are underlined whole, and contributed definition/hover providers that decline a position let the next one answer. Review fix: a BOM import without a version no longer ends the management search.

Co-authored-by: kradme <[email protected]>
2026-11-20 13:45:47 +08:00
l0ng-ai 96f3818bf2 feat(vcs): setting to hide the Generate Commit Message with Agent button (#4701)
Version Control > Commit > Commit Message Generation gets "Show the Generate Commit Message with Agent button" (on by default). Off hides the button above the commit message in the Commit tool window and dialog; the action stays available from Find Action and its shortcut.
2026-11-20 13:29:32 +08:00
l0ng-ai adf17d030e feat(workbench): open projects in a new tab of the current window by default (#4700)
"Open project in" gets "New tab in current window", and Don't ask again in the Open Project dialog now remembers New Tab too, so opening further projects adds project tabs to the current window without asking. A window without its own project, or a remote project, falls back to a new window. Attach stays a one-off choice.
2026-11-20 13:26:06 +08:00
l0ng-ai 815bebf4ec fix(editor): keep in-file Find responsive in large files (#4698)
CodeMirror compares a plain-text query one character at a time; a pass over a 50 MB log took ~850 ms and each find-bar keystroke runs several, freezing the editor for seconds. Plain-text queries now run as an escaped regular expression (~35 ms per pass) with a literal replacement. Find Previous no longer uses CodeMirror's quadratic backward regex search; one forward pass finds the previous match.
2026-11-20 13:19:51 +08:00
l0ng-ai 2b75b79ea0 fix(run): import a Maven module by its artifactId before a same-named folder (#4696)
IDEA names a Maven module after its artifactId. The JetBrains run-configuration importer accepted a folder name or an artifactId in one breadth-first search, so a project folder named like a child module's artifactId resolved to the root module. Search artifactIds first, then folder names, then the Gradle source-set fallback.
2026-11-20 13:07:13 +08:00
l0ng-ai 2c6329012a fix(vcs): keep each repository's branch submenu expansion separate (#4694)
In multi-repository projects every repository's branch submenu read and wrote the same expansion state, so expanding Remote or a folder in one (e.g. to check out a remote branch) expanded it in all others. Each repository's submenu now keeps its own expansion (keys scoped by repository root); the single-repository popup keeps its saved state.
2026-11-20 12:57:30 +08:00
l0ng-ai f40bcd747f fix(database): complete columns of custom JDBC data sources (#4692)
SQL completion for custom JDBC data sources knew tables but no columns: the JDBC completion model left every table's columns empty (no alias. members, no WHERE columns, no SELECT * expansion). The bridge returns a namespace's columns in one DatabaseMetaData.getColumns call (schemaColumns) and the model fills each table; a driver refusing it still completes tables.
2026-11-20 12:27:41 +08:00
l0ng-ai c752f007be fix(run): show the compile errors when Update Application's build fails (#4691)
A failed Spring Boot / Tomcat update build only said "Application update build failed" and the Run tool window returned to the app's tab, hiding the reason. The notification now lists the compiler errors: from the Java language server's build, and from the Maven/Gradle update build's output (Maven, javac and Kotlin error lines, ANSI-stripped, de-duplicated, first ten). Notification bodies keep their line breaks.
2026-11-20 12:23:04 +08:00
l0ng-ai bcdff6886f fix(settings): organize editor appearance controls (#4687)
Editor > General > Appearance gets four titled sections (caret behavior, code structure, presentation, code assistance): line numbers and indent guides sit together, whitespace controls stay indented under their toggle, using the existing Settings section typography and spacing.
2026-11-20 12:21:02 +08:00
Deng Liuanddengliu b7e9276b0f feat(agents): open model settings from the picker and composer (#4689)
The model picker showed settings only for the active model. Clicking the effort/context summary beside the model name now edits the current model directly, and each model row has an arrow that opens that model's settings without selecting it; changing a setting there selects the model and keeps the panel open, Back/Escape without an edit leaves the selection alone. Works in New Task and existing chats without sending the draft.

Co-authored-by: dengliu <[email protected]>
2026-11-20 12:19:53 +08:00
Muuandmuutot 6023e391bc fix(editor): keep line-end annotations clear of a folded chip (#4688)
A header-line fold's chip is drawn at the same position as the zero-width anchors of line-end annotations, so the Code Vision hint, plugin line-end messages and inline blame painted over the chip and took its clicks. A shared foldChipWidth helper measures a chip drawn after an anchor and all three consumers step past it (Code Vision gains the MutationObserver the others already had).

Co-authored-by: muutot <[email protected]>
2026-11-20 12:15:57 +08:00
l0ng-ai 3d80e661b7 fix(search): keep Find results usable in narrow docks (#4681)
The pinned Find tool window moves its result actions to a vertical toolbar and the replacement controls to a wrapping footer. Wide docks show results beside the source preview, narrow docks stack them and remember the divider per layout; result rows use the editor code size and truncate long paths before file names and match counts.
2026-11-20 11:52:49 +08:00
zhzhsxandzhzhsx b66439ceda fix(editor): keep the hover documentation from moving as it opens (#4682)
The hover documentation was placed twice: create() returned a popup holding only its toolbar, CodeMirror measured and placed it, and it moved once the text arrived. The body is now built in a layout effect and rendered before create() returns (flushSync), so the tooltip is measured once at its final size; the F1 popup and Documentation tool window share DocView and lose their empty first frame too.

Co-authored-by: zhzhsx <[email protected]>
2026-11-20 11:50:04 +08:00
l0ng-ai 899fe888b7 fix(docker): show container logs, processes and image layers without the docker CLI (#4686)
Engine API connections (SSH tunnel, socket, TCP) still ran docker logs / top / image history, failing on machines without the docker CLI. These now use the Engine API when the CLI is missing: logs stream and follow over their own connection (chunked encoding and per-stream frames, or a TTY's raw stream, cancellable); processes and image layers come from /top and /history. Refs #4648.
2026-11-20 11:46:36 +08:00
l0ng-ai e7de2aaf6d fix(docker): disable a container's actions while one runs on it (#4685)
Container actions gave no feedback while a slow (remote) daemon worked, inviting repeated or conflicting clicks. A container is now held busy from the request until the following snapshot: its actions are disabled in the dashboard, Services toolbar and context menu, the running one shows a spinner, and a second request is ignored. Compose actions are disabled while a Docker task runs. Refs #4648.
2026-11-20 11:46:30 +08:00
l0ng-ai 9293b13737 feat(vcs): show the Rollback Changes files as a checkable tree (#4684)
Rollback Changes listed the files flat. It now uses the checkable change tree of the Shelve and Create Patch dialogs: files grouped by directory under the repository, with tri-state boxes on repository and directory rows; the summary follows the selection.
2026-11-20 11:45:27 +08:00
l0ng-ai d1f79d05b3 fix(project-tree): add Manage Remotes and Clone to the Project view's Git menu (#4680)
The Project view's Git submenu stopped at Stash / Unstash; it now ends with Manage Remotes… and Clone…, like the editor's Git submenu and IDEA's Git context menu. Covered by a new e2e test in editorGitMenu.spec.ts.
2026-11-20 11:39:28 +08:00
l0ng-ai 176c43c908 fix(editor): make the paste history preview resizable (#4677)
Paste from History gives the preview more room by default and remembers the divider position (a resizable split). Delete moves beside the filter as a toolbar button; the snippets and preview use the active editor's font and zoom, and the preview drops line numbers to use its full width.
2026-11-20 11:33:27 +08:00
Nc 20b6b0aed5 fix(maven): sort sidebar profiles by ID (#4679)
The Maven sidebar listed profiles in model order. Profiles within each project group now sort by ID ignoring case, as IntelliJ's Maven tool window does; the -P argument keeps the model order.

Co-authored-by: qiany-sui <[email protected]>
2026-11-20 11:30:31 +08:00
l0ng-ai 101a0862e4 fix(database): reconnect a custom JDBC data source whose session was lost (#4675)
When a proxy or tunnel dropped an idle custom JDBC connection, every later statement failed and the source still showed Connected: the cached pool was only marked closed when the IDE closed it. After a failed statement the bridge now checks Connection.isValid (new valid op); an invalid or orphaned session closes the pool so the next statement or Connect reconnects. Keep-alive for JDBC uses the same check (and its option shows in the dialog); failures log at info.
2026-11-20 11:29:35 +08:00
Bin b48f0b6071 fix(vcs): enlarge deleted line marker hit area (#4669)
The deleted-lines marker is drawn above its gutter row, but clicks were resolved from the pointer's row, so clicking the triangle near the line boundary could miss the deletion. The marker gets a 12x12 transparent hit area (same triangle) with a pointer cursor, and clicks on it resolve to the deletion's row. Verified with vcs hunks and editor cm vitest, typecheck, and in the app (clicking the marker's upper half opens the Deleted lines popup).

Co-authored-by: ffgenius <[email protected]>
2026-11-20 11:23:37 +08:00
l0ng-ai a9b16c3e06 fix(debugger): keep call stack locations visible in narrow docks (#4671)
Call stack locations stay visible in narrow debug docks. Verified with e2e debugStackLayout, debugger vitest and typecheck.
2026-11-20 11:13:32 +08:00
l0ng-ai abd55f88b5 fix(search): make the editor switcher fit the workbench (#4660)
The editor switcher fits the workbench. Verified with e2e switcherLayout, search vitest and typecheck.
2026-11-20 11:13:20 +08:00
l0ng-ai dac4db0994 fix(settings): separate file type associations from ignore rules (#4657)
File Types settings separate file type associations from ignore rules. Verified with e2e fileTypesLayout, settings/locales vitest and typecheck.
2026-11-20 11:13:08 +08:00
Deng Liuanddengliu b0d0ea868b feat(agents): configure GitHub Copilot authentication account (#4663)
Copilot launched with whichever GitHub CLI account was active outside the IDE. GitHub Copilot's settings get a GitHub account field: at launch the IDE asks gh for that account's token and passes it as COPILOT_GITHUB_TOKEN, without storing it; the account (not a credential) is kept with the agent's settings and scopes the catalog cache. Also adds the field's text to the en/zh catalog. Verified with cargo test -p ide-agent, clippy, agents and locale vitest, typecheck, and the field in Settings › Agents › Coding Agents.

Co-authored-by: dengliu <[email protected]>
2026-11-20 11:11:05 +08:00
Deng Liuanddengliu d86ff872af fix(agents): recover model controls for fallback sessions (#4662)
A session whose agent fell back to a configuration without a model option kept a stale model label and offered no way to pick another model. The composer rebuilds the model control from the provider's catalog and set_config accepts a model from that catalog, switching through the same path as other discovered models. Verified with cargo test -p ide-agent, clippy, agents vitest and typecheck.

Co-authored-by: dengliu <[email protected]>
2026-11-20 11:07:37 +08:00
Deng Liuanddengliu dbef3cdc96 fix(agents): support Auto-only Copilot catalogs (#4661)
Copilot can return an enabled Auto tier with an empty direct-model list; the catalog parser treated that as an empty catalog and forced the fallback transport. An enabled Auto tier now yields the auto model. Verified with cargo test -p ide-agent copilot and clippy.

Co-authored-by: dengliu <[email protected]>
2026-11-20 11:06:32 +08:00
C3B6 c483c3b76f perf(http-client): limit cached response details to four (#4659)
The HTTP Client kept every exchange's full request and response in memory for the whole session, even after its row left the backend's 100-entry history. The history list is capped at 100 like the backend, and only the four most recently viewed exchanges keep their details; older rows reload theirs from the saved history (which stores the full exchange) when selected. Verified with http-client vitest and typecheck.

Co-authored-by: 0xC3B6 <[email protected]>
2026-11-20 11:05:24 +08:00
HEOJUNFO da79a73def fix(http-client): keep the whole value of a Spring params/headers condition (#4666)
Spring params/headers conditions were split with split("=", 2), which drops everything after a second '='; only the first '=' divides name and value now, as in Spring. Verified with http-client vitest.

Co-authored-by: HEOJUNFO <[email protected]>
2026-11-20 11:04:44 +08:00
akshathayadav378-boopandakshathayadav378-boop 2cc54b35f6 test(markdown): allow large render test to finish (#4664)
The large Markdown re-render test renders plugins/README.md repeatedly and can exceed Vitest's default 5 s timeout under full-suite load; it gets a 20 s timeout like other heavy tests.

Co-authored-by: akshathayadav378-boop <[email protected]>
2026-11-20 11:04:36 +08:00
zhzhsxandzhzhsx 097221c1b3 fix(editor): colour Go's default like the other keywords (#4654)
@lezer/go tags every keyword except default, and gopls sends no keyword semantic tokens, so default in a Go switch/select rendered as plain text. Go now gets an extra style tag for default. Verified with editor cm vitest and typecheck.

Co-authored-by: zhzhsx <[email protected]>
2026-11-20 10:25:05 +08:00
l0ng-ai 1bb4ffe6b2 Keep the color scheme preview visible while editing (#4653)
The color scheme preview stays visible while editing scheme options. Verified with e2e colorSchemeLayout/editorFontLayout, settings and platform vitest and typecheck; main merged in (locale conflict resolved).
2026-11-20 10:22:05 +08:00
l0ng-ai 51e525336b Keep Welcome project search and actions in one row (#4652)
Welcome project search and actions stay in one row. Verified with e2e welcomeProjectsLayout, full vitest and typecheck.
2026-11-20 10:21:06 +08:00
l0ng-ai 1b47bc2c14 Keep the editor font preview visible while changing settings (#4649)
The editor font preview stays visible while changing font settings. Verified with e2e editorFontLayout, full vitest and typecheck.
2026-11-20 10:20:59 +08:00
l0ng-ai aa1326496b Show both commit ranges in Git branch comparisons (#4642)
Git branch comparison shows both commit ranges side by side in resizable panes. Verified with e2e branchCompareLayout, full vitest and typecheck.
2026-11-20 10:20:51 +08:00
leenandleen2175 7850429174 fix(vcs): open existing worktrees over SSH (#4465)
Opening a linked worktree from an SSH or WSL project treated the remote directory as a local path. The Worktrees toolbar, row double-click and the checkout prompt's Open now go through openWorktree, which reuses the session's remote target and opens a remote window; local projects are unchanged. Verified with vcs and remote-dev vitest and typecheck on macOS (local path); the SSH flow was verified by the author in the native Linux app.

Co-authored-by: leen2175 <[email protected]>
2026-11-20 10:17:09 +08:00
Mansur Akhmadiandmansur-akhmadi 3dd5c75fa0 feat(debugger): Remove All Watches in the Variables view's context menu (#4647)
A watch row's context menu in the Variables view gets Remove All Watches next to Remove Watch; it empties the project's stored watch list. Verified with debugger and locale vitest and typecheck; main merged in (locale conflict resolved).

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-20 10:15:56 +08:00
Mansur Akhmadiandmansur-akhmadi 36ecb53159 feat(run): Fold Lines Like This in the Run console's context menu (#4635)
The Run console's context menu gets Fold Lines Like This: it opens Settings › Build, Execution, Deployment › Console with the selected single-line text, or the right-clicked line, added to the fold patterns. Verified with full vitest, typecheck, and in the app (pattern added, Cancel leaves settings unchanged).

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-20 10:15:00 +08:00
006405ca11 fix(remote): restore WSL projects onto a live connection (#4103)
* fix(remote): restore WSL projects onto a live connection

A reopened WSL window kept sending commands to a remote host it was no
longer connected to. Remember the remote location, and do not drop a
connection that a later open or a superseded attempt still needs.

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

* Use ? for the last remote location prefix (clippy::question_mark)

* fix(remote): save window session after connecting

---------

Co-authored-by: 胡长贵 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: l0ng-ai <[email protected]>
2026-11-20 10:12:35 +08:00
Mollo-i 40b95650cf fix(maven): custom project.* properties and bare built-in shorthands resolve to their definition (#4651)
Every project.* name was treated as a Maven built-in, so custom properties such as project.port never navigated, and the bare built-in shorthand (@artifactId@) did not either. Non-coordinate project.* names now fall through to the <properties> lookup along the parent chain, and the bare shorthand resolves to the pom's own coordinate unless a custom property of that name exists. Verified with cargo test -p ide-build (maven tests pass; the one failing Go workspace test is unrelated to this change and fails from the local go toolchain) and clippy.

Co-authored-by: Greenker <[email protected]>
2026-11-20 10:08:09 +08:00
zhzhsxandzhzhsx 0a571c0b4d fix(libraries): keep a Go module inside the project editable (#4639)
go list -m reports a replace target's own folder as the module's Dir, so a local replacement inside the project was registered as a read-only library root. Modules whose source sits inside the opened project (outside vendor/) are no longer library roots. Also passes the project root in the zig_groups test added on main. Verified with cargo test -p ide-sdk (new go_modules test passes; three go command tests fail the same way without this change, from the local go shim) and clippy.

Co-authored-by: zhzhsx <[email protected]>
2026-11-20 10:06:44 +08:00
l0ng-ai b1f88bf79c Separate shelves from the files they contain (#4640)
Shelf tool window separates the list of shelves from the files of the selected shelf in resizable panes. Verified with e2e shelfLayout, full vitest and typecheck.
2026-11-20 09:21:25 +08:00
l0ng-ai 0a6b3d011f Keep plugin list and details visible in narrow settings (#4636)
Plugins settings keep the list and details visible in narrow settings with a resizable split. Verified with e2e pluginsLayout, plugins/settings/locales vitest and typecheck.
2026-11-20 09:17:56 +08:00
l0ng-ai fd9b20fa05 Give interactive rebase plans and messages separate panes (#4637)
Interactive rebase shows the plan and the commit message in separate resizable panes. Verified with e2e interactiveRebaseLayout, full vitest and typecheck.
2026-11-20 09:17:14 +08:00
l0ng-ai 4f5622d72c refactor(agents): remove playful words from the working status (#4555)
Removes Settings › Agents › Working Status and its playfulStatus / playfulAfterSeconds / playfulWords settings. The line under a working conversation keeps saying what the agent is doing (Reading…, Running a command…); stored values of the removed settings are ignored.
2026-11-20 09:13:57 +08:00
l0ng-ai f4a7a7bafb perf(ui): smoother editor scrolling, tab switching and first file open (#4633)
Removes selectors that restyled whole subtrees on every inserted editor line or focus change (CodeMirror via a pnpm patch; selectorCost.test.ts guards them), measures space width once per font, shares one tooltip host, builds tab menus lazily, caches parsed SVG icons, prewarms an off-screen editor at idle, stats project-tree entries in parallel, and keeps the Git tool window at its size during a live window resize. Verified with full vitest, typecheck, ide-vfs cargo test and clippy, gitLog e2e, and a window resize in the app.
2026-11-20 09:13:29 +08:00
l0ng-ai 737afc6a8d Keep keymap search and shortcuts readable in narrow settings (#4632)
Keymap settings group the scheme selector with its actions and move the search controls to a second line in narrow settings; long action names scroll inside the tree. Verified with e2e keymapLayout/compactSettingsControls, settings vitest and typecheck.
2026-11-20 09:11:52 +08:00
l0ng-ai 6bf75155b6 Keep hierarchy symbols and source context readable (#4630)
Hierarchy view keeps symbol names and source context readable in narrow panes. Verified with e2e hierarchyLayout, code-insight vitest and typecheck.
2026-11-20 08:26:29 +08:00
l0ng-ai bbedf7e1f6 Make Inspections panes fit narrow settings windows (#4629)
Inspections settings panes resize and fit narrow settings windows. Verified with e2e inspectionsLayout/settingsFormLayout, full vitest and typecheck.
2026-11-20 08:26:21 +08:00
l0ng-ai 42fd0fa8e0 Organize Code Style settings into tabs (#4627)
Code Style settings are organized into tabs. Verified with e2e codeStyleLayout, settings vitest and typecheck.
2026-11-20 08:22:50 +08:00
l0ng-ai 97a41ae983 Give line bookmark text room in the tool window (#4624)
Bookmarks tool window rows give line bookmark text room. Verified with e2e bookmarkTreeLayout, search vitest and typecheck.
2026-11-20 08:22:42 +08:00
l0ng-ai f29903b698 Give the Stash dialog room for branch names and messages (#4623)
Stash dialog gives branch names and the message field room. Verified with e2e stashDialogLayout, vcs vitest and typecheck.
2026-11-20 08:22:35 +08:00
l0ng-ai 610fe23f88 Make the Pull dialog fit long branch names (#4622)
Pull dialog wraps long branch names instead of overflowing. Verified with e2e pullDialogLayout, vcs vitest and typecheck.
2026-11-20 08:22:26 +08:00
l0ng-ai 59376b9718 Improve the Update Project dialog layout (#4621)
Update Project dialog options and actions lay out cleanly at any width. Verified with e2e updateProject, vcs vitest and typecheck.
2026-11-20 08:22:18 +08:00
l0ng-ai 170fd735dd fix(vcs): keep clone fields usable in narrow dialogs (#4618)
Clone dialog fields stay usable and inside the dialog in narrow windows. Verified with e2e cloneLayout, vcs vitest and typecheck.
2026-11-20 08:22:11 +08:00
l0ng-ai e0ae9e764c fix(app): fit the New Project wizard in narrow windows (#4617)
The New Project wizard's template form fits narrow windows and keeps edits when resized. Verified with e2e newProjectLayout, app vitest and typecheck.
2026-11-20 08:07:19 +08:00
l0ng-ai 19c1b72650 fix(settings): fit SDK details within Project Structure (#4616)
Project Structure SDK details now wrap and stay inside the pane in narrow windows; the Home Path row reuses the shared path field. Verified with e2e projectSdkLayout/sdkFieldLayout, settings vitest and typecheck.
2026-11-20 07:53:11 +08:00
lleviathe 06ff2e51c3 fix(editor): even out the spacing of editor tabs (#4606)
Editor tabs sit 4px apart and keep an 18px close slot at one edge: before the icon when the close button is on the left, after the label when it is on the right, so switching sides no longer resizes tabs. The drag ghost keeps the strip's classes so it renders with the same layout. Verified with e2e editorTabClose/editor, src/ui vitest, typecheck, and both close positions in the app.

Co-authored-by: lleviathe <[email protected]>
2026-11-20 07:52:02 +08:00
l0ng-ai 6ae31b8148 test(keymap): list Shelve/Unshelve Silently in the VS Code and Eclipse presets (#4628)
#4620 added vcs.shelveSilently and vcs.unshelveSilently to the IntelliJ keymaps only, so the check that the VS Code preset covers every IntelliJ action id failed on main. Both the VS Code (macOS) and Eclipse (Windows) presets now list them unbound, like the other changelist actions.
2026-11-20 07:42:36 +08:00
Mansur Akhmadiandmansur-akhmadi 3783b601b5 feat(vcs): copy a path from its repository's root in Copy Path/Reference… (#4626)
Copy Path/Reference... gains Path From Repository Root, as in IDEA: each selected path relative to the root of the Git repository holding it (innermost for nested repositories, a repository root as '.'), one per line, through the same copyPath menu group the hosting link uses. Paths outside every repository are left out, and the item is hidden when none is inside one.

Closes #4625

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-20 07:38:35 +08:00
l0ng-ai 37044dcd89 fix(vcs): give Local History diffs room in narrow panes (#4613)
Local History gave its revision list a fixed share of the pane, so in narrow panes the diff had little room and long labels were clipped. The list and diff are now a resizable split with sensible minimums, revision rows truncate with full text in tooltips, and the diff keeps room in narrow panes.
2026-11-20 07:37:21 +08:00
l0ng-ai 1a2adab237 fix(editor): align Reformat Code dialog groups and controls (#4611)
The Reformat Code dialog's option groups and controls were laid out ad hoc, so labels and checkboxes misaligned and the scope group wrapped awkwardly. The dialog now uses shared dialog fieldsets with aligned groups and controls, the same as the other analysis dialogs.
2026-11-20 07:12:25 +08:00
l0ng-ai 9ed87d77a7 fix(project-tree): make the Move dialog readable in narrow windows (#4609)
The Move dialog's title, target field and validation were laid out for a wide window, so in narrow ones the path and Browse button were clipped. The dialog now names what it moves (file, directory or N items), the target row wraps with its Browse button, and invalid targets (a folder into itself, the same directory) are explained inline.
2026-11-20 06:55:23 +08:00
Mansur Akhmadiandmansur-akhmadi 9f4731189d feat(vcs): Shelve Silently and Unshelve Silently (#4620)
Shelving and unshelving always opened a dialog. As in IDEA, Shelve Silently (Changes toolbar, Ctrl+Shift+H / Shift+Cmd+H) shelves the Commit selection, or the active changelist, without a dialog, one shelf per changelist named as the Shelve dialog would suggest; Unshelve Silently (Ctrl+Alt+U / Opt+Cmd+U in the Shelf) applies the selected shelf or file into the matching changelist and honours Remove applied files from the shelf. The Shelve and Unshelve dialogs share the same helpers, and both actions are in the IntelliJ keymaps and IDEA_ACTIONS.

Closes #4619

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-20 06:39:35 +08:00
l0ng-ai 92ccfac192 fix(debugger): keep breakpoint details usable in narrow windows (#4605)
The Breakpoints dialog had a fixed list width beside the details, so in narrow windows locations were clipped and the details' controls ran off the dialog. The list and details are now a resizable split that stacks vertically below 560px (each layout remembered), the dialog itself can be resized, and locations show the file name and line with the full path in the tooltip.
2026-11-20 06:38:09 +08:00
l0ng-ai 60d335eec0 fix(refactor): keep the Change Signature parameter table readable (#4602)
The Change Signature dialog's parameter table had fixed column widths and a one-line preview, so in narrow windows types and names were clipped and long signatures ran off the preview. The table columns now share the width with truncation, the preview puts each parameter on its own line as IDEA's does, and the dialog's sections keep their controls visible.
2026-11-20 06:05:24 +08:00
Hafiz Faizan ul hassanandfaizanalhassan a679e8086f feat(database): pick data source, then database and schema in the query console (#4614)
The query console's Data source dropdown mixed databases into the source list, and SQL Server's second dropdown listed databases. As in DataGrip, the dropdown now lists data sources only, and a database.schema switcher next to it opens a searchable database -> schema tree that loads a database's schemas on expand and moves the console to the picked database; one-level drivers keep a flat schema list and SQLite has none. SQL Server's console schema is now a real schema (SCHEMA_NAME()) that scopes resolution and completion, since a session's default schema can't be changed, while the pooled connection still returns to its database. Tree speed search also opens with Cmd/Ctrl+F, as in IDEA.

Closes #4577

Co-authored-by: faizanalhassan <[email protected]>
2026-11-20 06:04:34 +08:00
Mr0Bread 4c20aa5c8d test(editor): cover missing-file and malformed session restore (#4615)
Adds regression tests for editor session recovery: a deleted selected file is dropped quietly and the remaining tab restores with its caret, a permission-denied tab stays open with its error inline, and truncated session JSON loads as null without writing storage until a valid session replaces it. No production changes.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 06:00:56 +08:00
l0ng-ai d19d74120b fix(debugger): keep values visible in narrow variables panes (#4600)
In narrow Variables panes the name and type kept their full width, so values were cut to nothing and the Show button could be pushed out. Names and types now truncate within caps, the value and its Show button share a group that keeps a minimum width, overflow is measured against that group, and full names and types are in tooltips.
2026-11-20 06:00:12 +08:00
Mr0Bread 4e1cec5233 refactor(ipc): enforce typed error-kind comparisons (#4612)
IPC error kinds were compared as untyped strings (`(e as { kind?: string }).kind === "notFound"`), so a misspelt kind compiled and silently never matched. A typed `isErrorKind(error, kind)` helper, taking a kind from the generated `IdeError["kind"]`, now handles wrapped and raw IPC errors in document sync, editor session restore, Spring service identity, plugin commands and recent projects.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 05:41:29 +08:00
l0ng-ai 150eacc3de fix(editor): keep parameter info readable in narrow panes (#4599)
Parameter Info had a fixed 640px cap and a 12-signature window, so in narrow panes it overflowed the editor and long signatures were clipped. The popup now fits the editor's tooltip bounds and height, uses the editor's current font size, wraps long signatures with a hanging indent, scrolls when needed and keeps the current parameter in view.
2026-11-20 05:40:20 +08:00
l0ng-ai d1cc3cf68a fix(vcs): make merge panes resizable and keep actions visible (#4597)
The merge editor's three panes had fixed widths with decorative dividers, so in narrow windows they could not be resized and the toolbar actions overflowed. The panes are now a SplitGroup whose two handles carry the connector bands, each pane has its own title (branch and side), and the toolbar status is announced.
2026-11-20 05:25:12 +08:00
Mr0Bread 7c00ce4fa1 test(e2e): enforce TypeScript contract checking (#4610)
The e2e TypeScript project was never type checked: its tsconfig didn't inherit the app's settings, so @/ imports didn't resolve and hundreds of diagnostics went unnoticed. e2e/tsconfig.json now extends the root config (plus Node/Vite types and ES2024), pnpm typecheck runs tsrs -p e2e, and the remaining real type errors in the specs and fixtures are fixed; the code-style docs list the new project.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 05:19:07 +08:00
l0ng-ai 6539a95cb8 fix(vcs): keep push review readable in narrow windows (#4594)
The Push dialog's commits, changed files and diff panes had pixel minimums and fixed options rows, so narrow or short windows clipped the review and the target controls. The commits and changes now stack vertically below 640px with their own remembered split, the changed files come before the commit details, panes use relative minimums, and the target bar, options and tag options wrap.
2026-11-20 05:07:24 +08:00
l0ng-ai 08613ca800 fix(debugger): keep evaluation results readable in short dialogs (#4592)
The Evaluate dialog's result had a 220px minimum height, so in short windows the dialog overflowed and the result and buttons were cut off. The dialog now caps its height to the window, the expression field scrolls within half of it, imports wrap, and the result takes the remaining space; the expression uses the editor font and its label is tied to the field.
2026-11-20 04:49:29 +08:00
l0ng-ai 1ad8b06a1a fix(markdown): keep the Project view clickable in Preview only (#4604)
In Preview only the editor panel stays mounted but hidden, with no separator. react-resizable-panels adds an implicit resize region between two enabled panels without a separator; with the hidden panel's rect at zero it spanned everything left of the preview, showing a resize cursor and swallowing clicks in the Project view. The hidden editor panel is now disabled, leaving the group a single resizable panel.

Fixes #4589
2026-11-20 04:35:55 +08:00
l0ng-ai 2ca0e195e5 fix(editor): keep inline find controls inside narrow panes (#4588)
The inline find/replace bar used a fixed grid with a 220px minimum field, so in narrow editor panes the counter, option buttons and Close spilled outside the pane. The bar is now a container-query layout: fields shrink, the action groups wrap, and below 500px (and again below 224px) the actions and replace field move to their own rows while Show Replace and Close stay reachable.
2026-11-20 04:33:34 +08:00
Mr0Bread 750d35dd6e fix(vcs): discard stale status after project switch (#4598)
The VCS store reset on project switch, but replies to refreshes started for the previous project still wrote to it, restoring its branch, changed files and decorations and firing conflict notifications. A project generation, bumped on every switch (also when reopening the same folder), now gates full and incremental refresh results, errors and discovered roots; queued paths are dropped on switch, and the refresh queue still drains for the active project.

Closes #4596

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 04:10:23 +08:00
l0ng-ai f0273690b9 fix(run): keep test results readable in narrow panes (#4586)
The test tree's header held the counts, duration and every toolbar action in one 28px row, so narrow Run panes clipped the counts and buttons. As in IDEA's new layout, the status (icon, counts, total duration) now sits above the console, Expand All, Collapse All and Export Test Results move into a More Actions menu, and the tree and console stack vertically below 560px with their own remembered split.
2026-11-20 04:07:52 +08:00
l0ng-ai 04611c0388 fix(database): show a running SQL statement in the editor and results (#4601)
The console tracked the running request only for Run and Cancel; statement marks and result tabs arrived after it ended, and the Results view said "No results" meanwhile. While a request runs, the submitted statements are highlighted with a gutter spinner and a ticking elapsed time, and the Results view opens with an executing bar above the previous result. Edits during the run move the marks and the outcomes land on their statements; cancel or an error clears the indication and keeps the previous result.

Fixes #4565
2026-11-20 04:06:41 +08:00
l0ng-ai 1cfc71ae58 fix(editor): make symbol rename and its preview readable in narrow windows (#4583)
The symbol rename prompt was a caret-anchored popup that could be clipped in narrow windows, and its preview truncated long names. When in-place rename isn't available, Rename now opens a dialog with the symbol context, a New name field in the editor font, and an optional note; the refactoring preview keeps the context, wraps occurrence snippets in the editor font and theme, and truncates long file names with the full path in the tooltip.
2026-11-20 03:56:29 +08:00
l0ng-ai 8daaef38d9 fix(run): keep Run Anything controls visible on short windows (#4581)
Run Anything had a fixed 620px popup with a 360px list cap and a footer that could fall off short windows. The popup now fits the viewport as a column whose list shrinks, uses the shared search field with combobox semantics, shows the completion of the selected entry in the field, pages by the visible row count (compact-aware), and keeps a wrapping footer with the navigation hints.
2026-11-20 03:39:37 +08:00
Chris Schofield efd4e454ee feat(appearance): make Compact Mode match IntelliJ's compact density (#4593)
Compact Mode only lowered the title bar and narrowed the stripes: row heights, toolbar widgets and icons were fixed in code, and nothing in JS (where virtualised list row heights are set) could tell whether the mode was on. A small density store now mirrors the setting for JS, and Compact Mode uses IntelliJ's *.compact theme values: tree/list rows 22 (VCS log 24), toolbar widgets 26, toolbar and stripe icons 16, status bar 24, island gap 4, and chrome text 1px smaller.

Co-authored-by: ChildishForces <[email protected]>
2026-11-20 03:26:32 +08:00
l0ng-ai 0379c37a49 fix(usages): keep results and previews readable in narrow windows (#4580)
The Show Usages popup and the Find usages view used fixed header heights, a flexible spacer and a fixed preview height, so in narrow windows the title, file names and line numbers were clipped and the preview pushed results off screen. Headers now wrap their actions, rows use a file / line / text grid with truncation, and the preview shrinks with the viewport.
2026-11-20 03:21:33 +08:00
l0ng-ai 98da80b2b3 fix(editor): keep the current breadcrumb visible (#4579)
Long breadcrumb trails hid the current file or symbol when the editor or status bar ran out of room. Both trails now scroll to the current location (with edge fades) and keep earlier entries reachable by wheel, trackpad or keyboard. The status bar reserves a minimum width for the path and moves lower-priority widgets into its overflow menu. Code breadcrumbs use the editor font and highlight the symbol at the caret.
2026-11-20 03:05:31 +08:00
l0ng-ai 5c2e7ff92a fix(editor): fit intention previews beside or below the list (#4578)
The intention preview had a fixed 420px width beside the list, which pushed the action list away from the caret or got clipped in narrow windows. The preview now opens to the right when there is room, to the left when that keeps the list by the caret, and below the list in narrow windows. Preview code follows the editor's font settings and theme and wraps long lines.
2026-11-20 02:54:44 +08:00
l0ng-ai e86a853048 fix(run): keep configuration names visible in narrow sidebars (#4573)
A long run target could take the whole row in the Run/Debug Configurations sidebar, leaving the configuration name at zero width and forcing horizontal scrolling. Target labels now truncate in wide panes, narrow panes (container query) hide the muted target and scope, and the row tooltip carries the full name, target, scope and command. Type headings are semibold.
2026-11-20 02:53:44 +08:00
l0ng-ai fd8f0eb99c fix(editor): make quick documentation fit narrow windows (#4568)
Quick Documentation used a fixed 600px cap and kept its caret anchor after the window shrank, so short documents looked cramped and the actions could end up off screen. The popup now sizes to a 300-500px content width, keeps its actions together in the lower-right corner while the document scrolls, and clamps the anchor to the current viewport.
2026-11-20 02:52:46 +08:00
l0ng-ai 121e1fa535 fix(completion): fit the lookup to the editor and its font (#4566)
The lookup reserved a fixed 420px row, so long names pushed the signature and type past the editor edge, and the body-level tooltip ignored temporary editor zoom. It now sizes to its content within the editor's tooltip bounds, truncates each field, applies the label alignment through CodeMirror's own offset so the viewport clamp accounts for it, and follows the editor's current font size.
2026-11-20 02:51:47 +08:00
2988 changed files with 273488 additions and 35033 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

+95 -32
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
@@ -65,8 +67,9 @@ jobs:
plugin_web='^plugins/official/[^/]+/web-src/'
# Paths the frontend checks never read...
backend='^(crates/|src-tauri/|sdk/|wit/|java/|fixtures/|Cargo\.(toml|lock)$|deny\.toml$|rustfmt\.toml$|rust-toolchain(\.toml)?$|\.cargo/)'
# ...except these, which frontend tests and e2e fixtures load.
read_by_web='^(fixtures/(folding|django-app)/|crates/ide-plugin/tests/fixtures/|crates/ide-db/(src|tests/fixtures)/snowflake/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
# ...except these, which frontend tests and e2e fixtures load (the crate manifests:
# scripts/smoke-paths.test.ts, through cargo metadata).
read_by_web='^(fixtures/(folding|django-app)/|(crates/[^/]+/)?Cargo\.toml$|crates/ide-plugin/tests/fixtures/|crates/ide-db/(src|tests/fixtures)/snowflake/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
# What the browser app and its e2e tests are built from.
app='^(src/|e2e/|public/|index\.html$|vite\.config\.ts$|tsconfig\.json$|playwright\.config\.ts$|package\.json$|pnpm-(lock|workspace)\.yaml$|crates/ide-plugin/tests/fixtures/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
# The plugin workspaces: the SDK, the plugins, their interface and the host's fixture plugins.
@@ -101,30 +104,50 @@ jobs:
name: Rust (${{ matrix.os }})
needs: changes
if: needs.changes.outputs.rust == 'true'
permissions:
contents: read
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
os: [macos-latest, ubuntu-22.04, windows-latest]
runs-on: ${{ matrix.os }}
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-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
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' }}
- uses: dtolnay/rust-toolchain@stable
with: { components: "clippy, rustfmt" }
# Only main saves the cache (saving takes minutes on Windows); PRs restore main's.
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
# (only main saves it because saving takes minutes on Windows; PRs restore main's).
- uses: Swatinem/rust-cache@v2
if: runner.environment != 'self-hosted'
with:
save-if: ${{ github.ref == 'refs/heads/main' }}
# The persistent target dir makes incremental builds pay off; cap its size so it can't fill the disk.
- name: Persistent Cargo target dir
if: runner.environment == 'self-hosted'
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
- uses: taiki-e/install-action@nextest
- 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
@@ -134,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
@@ -148,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:
@@ -165,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.
@@ -183,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: |
@@ -211,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
@@ -235,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
@@ -247,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
@@ -268,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:
+127 -26
View File
@@ -8,6 +8,9 @@ name: Language smoke
# (Run, Run tests, the test tree, Rerun Failed Tests): smoke/run.test.ts; and debugging its
# entry point with the debugger the IDE installs (breakpoint, frames, variables, evaluate,
# Step Over, Resume): smoke/debug.test.ts.
# The paths below and the Changes step's patterns must cover every file the smoke loads and
# every crate it runs: scripts/smoke-paths.test.ts checks them (`node scripts/smoke-paths.ts
# [file…]` lists what they miss, or the languages a change runs).
on:
push:
branches: [main]
@@ -20,10 +23,33 @@ on:
- "Cargo.lock"
- "src/features/run/**"
- "src/features/debugger/**"
- "src/features/build/**"
- "src/features/build-tools/**"
- "src/platform/**"
- "src/workbench/**"
- "src/ui/**"
- "src/editor/api.ts"
- "src/editor/navigationProviders.ts"
- "src/editor/relatedProviders.ts"
- "src/editor/core/cm/cornerInset.ts"
- "src/editor/core/cm/iconArea.ts"
- "src/editor/lsp/availability.ts"
- "src/editor/lsp/diagnostics.ts"
- "src/editor/lsp/files.ts"
- "src/editor/lsp/hint.ts"
- "src/editor/lsp/lsp.ts"
- "src/editor/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.yaml"
- "pnpm-workspace.yaml"
- "patches/**"
- ".github/workflows/language-smoke.yml"
- ".github/tool-versions.env"
pull_request:
@@ -32,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).
@@ -47,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
@@ -70,10 +101,12 @@ jobs:
--jq '.[] | .filename, (.previous_filename // empty)' > files.txt
cat files.txt
# Crates outside what the smoke runs (language servers, debuggers, run configurations,
# SDKs, build tools and the project model): cargo metadata, deps of ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-search|ide-spell|ide-ssh|ide-streams|ide-vcs|ide-web)/'
# SDKs, build tools, the project model, Find Usages candidates, debug stream traces):
# cargo metadata, ide-host's direct deps ide-search/ide-streams and the deps of
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger)/|src/platform/|smoke/|package\.json$|pnpm-lock\.yaml$|\.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
@@ -105,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
@@ -158,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"
@@ -182,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"
}
}
]
}
-147
View File
@@ -1,147 +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
- `pnpm tauri dev` — run the app with worktree isolation (Node 22.18+).
`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.
- `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
+154 -150
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",
@@ -1203,27 +1203,27 @@ dependencies = [
[[package]]
name = "cranelift-assembler-x64"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aecefa88696b62f833cc0c997d19c93246b0268e2aaf23e0e8692e527f6de088"
checksum = "c19fba13ee427c4dd29488ea51127e945bf07fd9d79093f14c9cc57f74acf757"
dependencies = [
"cranelift-assembler-x64-meta",
]
[[package]]
name = "cranelift-assembler-x64-meta"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1391a2546f5edf06a0ff5e9430d73c2713fd536aefec53200dc21846d1467f53"
checksum = "dd88c766346fcc14bbadbd68cb11e9bc1e555e99f7e8f6b1f4c27a73ca659bec"
dependencies = [
"cranelift-srcgen",
]
[[package]]
name = "cranelift-bforest"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9528915fbc2c950702329e08c6d72aaff8ece9b7ecdbd225742825c09a445227"
checksum = "f19d43d75dd963d6b1a653f2e03d4eed4365ca2e598ec57e52c15afdad6c3276"
dependencies = [
"cranelift-entity",
"wasmtime-internal-core",
@@ -1231,9 +1231,9 @@ dependencies = [
[[package]]
name = "cranelift-bitset"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9dd69a6db85c1bcff989809e0e0b3b06506425f32b545c46aeafda5fe7775d6a"
checksum = "45d0b93e50856858c89c61cbe3f6d4b07596da22eb5a03a95b19420e1d08a275"
dependencies = [
"serde",
"serde_derive",
@@ -1242,9 +1242,9 @@ dependencies = [
[[package]]
name = "cranelift-codegen"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24c2db6c26cd96393cf785c4b51b900738963cc7422aa0045416a7641ae2f6cd"
checksum = "efbdff32d3b6b4f33f1ba8a4ac747b97ce569b1d6834c3089c1c0933b94e618c"
dependencies = [
"bumpalo",
"cranelift-assembler-x64",
@@ -1273,9 +1273,9 @@ dependencies = [
[[package]]
name = "cranelift-codegen-meta"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e284270142e7f1dcb73a992a62a8b3716b4062a65a52d8f2732c6ebf6f7f342f"
checksum = "67fd11ff24916a2c1ff852ce4bb664fcf2c2970ed551de44dd5b573321123703"
dependencies = [
"cranelift-assembler-x64-meta",
"cranelift-codegen-shared",
@@ -1286,24 +1286,24 @@ dependencies = [
[[package]]
name = "cranelift-codegen-shared"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6595667b7d505cf85d5bdd014e6f57ad6128183238f8e372319d9384782472f5"
checksum = "ba5d321229c3e00a17d7bb3633529ffdf97a13bcf4962fd2e92f1e0fd39360aa"
[[package]]
name = "cranelift-control"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26ffdbfcd24c3833d730849e6d132af34a400a2b89b44446015c01eecbea21d"
checksum = "71cd63450256d0f80f7a0527e133452f84fa6e1ca73c7db6ca2a9e8cc89d1c18"
dependencies = [
"arbitrary",
]
[[package]]
name = "cranelift-entity"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ffb08ccd8a77fb31cdbbda2afa2333d8f85299b1bc0d1c194259ba66d160d74"
checksum = "18d2f259130db1bbb89500d26944971a9beeb410de91ff14039203f055d7f9f0"
dependencies = [
"cranelift-bitset",
"serde",
@@ -1313,9 +1313,9 @@ dependencies = [
[[package]]
name = "cranelift-frontend"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b447e4f2bb44b1188185a77f478e5a91b7723a40b3b58c3e2d5b26df2ed5a665"
checksum = "cf37a38d982d45fe2c065d55e4de76e596b443b6acceb3ca726c2072c8ba6d7b"
dependencies = [
"cranelift-codegen",
"hashbrown 0.17.1",
@@ -1326,15 +1326,15 @@ dependencies = [
[[package]]
name = "cranelift-isle"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f0989e943f3a9d41989595826bba544df9fda64bcddd4df0c06fb2e26af3cb3"
checksum = "8ce8f84e2d44326879e18016d763457a2cb5d775e4a5822cd7473fc171fca063"
[[package]]
name = "cranelift-native"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fa10df59e776c42dae5b6ba5216ba5321707a2136abd2219e615c54b234fc1b"
checksum = "df64a0392edac7b38fb2965ce8e205e7c5e219e4c531ed3cd1929c782f21853d"
dependencies = [
"cranelift-codegen",
"libc",
@@ -1343,9 +1343,9 @@ dependencies = [
[[package]]
name = "cranelift-srcgen"
version = "0.136.6"
version = "0.136.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36508559c8839a8b6ee091f9deaa9cfe620a82f1abb5e358a0a0c65290583622"
checksum = "3748e3c77c0717359cd4c089e1dc057221eb8598a9c18b0b5afccb5685975abb"
[[package]]
name = "crc"
@@ -2154,7 +2154,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -2361,9 +2361,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
dependencies = [
"percent-encoding",
]
@@ -2386,7 +2386,7 @@ checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
dependencies = [
"io-lifetimes 2.0.4",
"rustix",
"windows-sys 0.59.0",
"windows-sys 0.52.0",
]
[[package]]
@@ -4144,8 +4144,9 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"blake3",
"dunce",
"encoding_rs",
@@ -4156,6 +4157,8 @@ dependencies = [
"ide-vcs",
"ide-vfs",
"parking_lot",
"rustix",
"semver",
"serde",
"serde_json",
"specta",
@@ -4169,7 +4172,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4177,13 +4180,11 @@ dependencies = [
"rayon",
"serde",
"specta",
"tracing",
"tree-sitter",
]
[[package]]
name = "ide-android"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"ide-core",
"serde",
@@ -4194,7 +4195,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"blake3",
"chardetng",
@@ -4212,7 +4213,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4226,7 +4227,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4237,7 +4238,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -4248,24 +4249,29 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.49"
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.49"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-run",
@@ -4274,12 +4280,11 @@ dependencies = [
"serde_json",
"specta",
"tempfile",
"tracing",
]
[[package]]
name = "ide-dap"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4308,12 +4313,11 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"bb8",
"blake3",
"dirs 6.0.0",
"dunce",
"flate2",
"futures",
@@ -4321,6 +4325,7 @@ dependencies = [
"ide-http",
"ide-sdk",
"ide-ssh",
"libc",
"notify",
"open",
"oracledb",
@@ -4340,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.49"
version = "0.1.51"
dependencies = [
"ide-core",
"serde",
@@ -4357,15 +4363,28 @@ dependencies = [
"which",
]
[[package]]
name = "ide-drag-out"
version = "0.1.51"
dependencies = [
"gtk",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"raw-window-handle",
"tempfile",
"windows",
"windows-core",
]
[[package]]
name = "ide-extension"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"blake3",
"dunce",
"ed25519-dalek",
"ide-core",
"parking_lot",
"semver",
"serde",
@@ -4380,7 +4399,7 @@ dependencies = [
[[package]]
name = "ide-flutter"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"ide-android",
"ide-core",
@@ -4391,7 +4410,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4403,7 +4422,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4416,10 +4435,11 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"criterion",
"ide-core",
"ide-heap",
"libc",
"memmap2",
"proptest",
@@ -4434,7 +4454,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4502,6 +4522,7 @@ dependencies = [
"toml 0.9.12+spec-1.1.0",
"tracing",
"tracing-subscriber",
"url",
"uuid",
"windows-sys 0.61.2",
"zip",
@@ -4509,8 +4530,9 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"hyper-util",
"ide-core",
"ide-vfs",
"parking_lot",
@@ -4522,19 +4544,19 @@ dependencies = [
"specta",
"tempfile",
"tokio",
"tracing",
"uuid",
]
[[package]]
name = "ide-index"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"blake3",
"criterion",
"dunce",
"globset",
"ide-core",
"ide-index",
"ide-language",
"ignore",
"nucleo-matcher",
@@ -4550,7 +4572,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4562,10 +4584,9 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"encoding_rs",
"futures",
"ide-core",
"parking_lot",
"serde",
@@ -4579,7 +4600,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"libc",
"tempfile",
@@ -4588,7 +4609,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"futures",
"serde",
@@ -4599,7 +4620,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"blake3",
"criterion",
@@ -4658,7 +4679,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"criterion",
"dunce",
@@ -4687,7 +4708,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"bytes",
"dunce",
@@ -4706,9 +4727,8 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"futures",
"ide-core",
"ide-vfs",
"jupyter-protocol",
@@ -4721,7 +4741,6 @@ dependencies = [
"specta-typescript",
"tempfile",
"tokio",
"tracing",
"uuid",
"windows-sys 0.61.2",
"zeromq",
@@ -4729,7 +4748,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"blake3",
"dunce",
@@ -4741,7 +4760,6 @@ dependencies = [
"serde_json",
"specta",
"tempfile",
"thiserror 2.0.21",
"tokio",
"tracing",
"url",
@@ -4752,7 +4770,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4766,7 +4784,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"dunce",
"futures",
@@ -4786,7 +4804,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"dunce",
"encoding_rs",
@@ -4810,7 +4828,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-tools",
@@ -4826,8 +4844,10 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
"dunce",
"flate2",
"ide-core",
@@ -4838,6 +4858,7 @@ dependencies = [
"quick-xml 0.42.0",
"serde",
"serde_json",
"sha2 0.10.9",
"specta",
"tar",
"tempfile",
@@ -4849,7 +4870,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"criterion",
"encoding_rs",
@@ -4870,7 +4891,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"ide-core",
"parking_lot",
@@ -4883,7 +4904,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4908,7 +4929,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-language",
@@ -4921,7 +4942,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"ide-core",
"ide-language",
@@ -4936,7 +4957,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"ide-core",
"libc",
@@ -4950,7 +4971,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"criterion",
"ide-core",
@@ -4963,7 +4984,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"flate2",
"hex",
@@ -4984,7 +5005,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"blake3",
"dunce",
@@ -4993,6 +5014,7 @@ dependencies = [
"ide-core",
"ignore",
"libc",
"notify",
"redb",
"regex-lite",
"serde",
@@ -5005,7 +5027,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"chardetng",
"dunce",
@@ -5017,6 +5039,7 @@ dependencies = [
"ignore",
"notify",
"parking_lot",
"rayon",
"rustix",
"serde",
"serde_json",
@@ -5031,7 +5054,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5047,7 +5070,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"blake3",
"dunce",
@@ -5209,7 +5232,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
dependencies = [
"io-lifetimes 3.0.1",
"windows-sys 0.60.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -5247,7 +5270,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
dependencies = [
"hermit-abi",
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -6676,7 +6699,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -6685,40 +6708,30 @@ 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",
"ide-drag-out",
"ide-extension",
"ide-fonts",
"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",
@@ -7405,9 +7418,9 @@ dependencies = [
[[package]]
name = "pulley-interpreter"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "335e459f9c7809af04768799880504d014d07e8e2fc6ae682fe2a105d8ced33f"
checksum = "99ecf828c291348e4066f8e45bf37c35ea6012b07a9201e7911c21f03ad1af3e"
dependencies = [
"cranelift-bitset",
"log",
@@ -7417,9 +7430,9 @@ dependencies = [
[[package]]
name = "pulley-macros"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd492ac929a6ca0357362d9fa0a09e31290feac5914550ccfb539b21f89c4b9e"
checksum = "20e35ece122b2e8bbd7ea9db0709b3d32f20555b73985efc3eaf6afa4ef2ecdf"
dependencies = [
"proc-macro2",
"quote",
@@ -7949,7 +7962,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -8017,7 +8030,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -9764,7 +9777,7 @@ dependencies = [
"getrandom 0.3.4",
"once_cell",
"rustix",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -10805,9 +10818,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
version = "2.5.8"
version = "2.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
dependencies = [
"form_urlencoded",
"idna",
@@ -11098,9 +11111,9 @@ dependencies = [
[[package]]
name = "wasmtime"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f32390bdc8d7cdb6259a1b855178bfed88226b4004b209fd48fb30e0deb01cd3"
checksum = "263d6a66a772efff2c98a1aa367e8e61dae32d2ecf95f85f4776733762322aa7"
dependencies = [
"addr2line",
"async-trait",
@@ -11140,9 +11153,9 @@ dependencies = [
[[package]]
name = "wasmtime-environ"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c10f8ef1c9ee5e0f125c775fe56a4d07b8525db30a96e6358c61d93bd11dee4"
checksum = "5f2f0898bedc77f110dca6f70394780f89af68a8ca19e12559ee73d4187a6fe9"
dependencies = [
"anyhow",
"cpp_demangle",
@@ -11171,9 +11184,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-component-macro"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "620c53182ebd26c9fff5b90dd53cf8ec3103c381403fd32f8d395da31a9e4a46"
checksum = "b140c28283bd2255a4bb8834621f7200bbe7581cbca91d803b5ba4adf9119a5e"
dependencies = [
"anyhow",
"proc-macro2",
@@ -11186,15 +11199,15 @@ dependencies = [
[[package]]
name = "wasmtime-internal-component-util"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "011e31ca343d9ba0ec623153cd94131b6f03973ef1a0ab791161f642e4a16a93"
checksum = "853075a197694ba7f0749e7af78b59e12c0956dff5b16dafbfc49c3b90cdbc93"
[[package]]
name = "wasmtime-internal-core"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab15e50a060b746493e6e95ef3ce4e6e7ebfdd7cc336a7dff0f0277e01b447ef"
checksum = "e6e13ab3aa598d863643ef9ec043d63fde7effca4465270446d5b868936b27a6"
dependencies = [
"hashbrown 0.17.1",
"libm",
@@ -11203,9 +11216,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-cranelift"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc3d27440a83fba26dd2784a997e13d9acb3606a75fb127c324929b52221c5c5"
checksum = "660103cff91df46f9f06568f3889b8b59a6ae0f56756abfcc002a0a69974cc9f"
dependencies = [
"cranelift-codegen",
"cranelift-control",
@@ -11229,9 +11242,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-fiber"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e54b28d0d453ca8932e4504065ae66a78f01fcb22b1a2ee287128d732fa9d6f"
checksum = "c4d0e958516bdf283b83015283774e11c86b66f2f4bd7d2ea52e9799fa59cddb"
dependencies = [
"cc",
"libc",
@@ -11243,9 +11256,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-jit-debug"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9293e75a3048b900f7b7c524702abca16d8a2332f970324eefc519f454cd5d69"
checksum = "ad61b1e661871bb7d11b5543202a05c44ed8682806b438f68ced629a22719463"
dependencies = [
"cc",
"wasmtime-internal-versioned-export-macros",
@@ -11253,9 +11266,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-jit-icache-coherence"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b852e568831b913d410541bb37edc45a5002e472208fbdbaf844ed801dd4255f"
checksum = "52c641b9e1bab449c7316896f01d4a0c426e2a502a5a8098e1af4a0392053e7a"
dependencies = [
"libc",
"wasmtime-internal-core",
@@ -11264,9 +11277,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-unwinder"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1f7349c9834a542275ad757340079e6453fccb429efce581454d23f85af92c0"
checksum = "03303a9abd333edcbd44fee3b1e0905ad156d3bcec311323d061cdff92e7d1f3"
dependencies = [
"cranelift-codegen",
"log",
@@ -11276,9 +11289,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-versioned-export-macros"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30b3e0768a450d9dea3e16b83f2498f0b08db0e32bad695e35564eef017be3f1"
checksum = "8db0c7f417e5ca3ba92d127d17b980529455d01c141be99204e6d309630c42de"
dependencies = [
"proc-macro2",
"quote",
@@ -11287,9 +11300,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-wit-bindgen"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d085c540b95d0ffebf98c266e6f152e1acf96a9f676f224a74307b9d422c15"
checksum = "6292ee4f797f9befb64aa2b3477ec8576501d6302ec21fd2785a8d3f94cf8717"
dependencies = [
"anyhow",
"bitflags 2.13.2",
@@ -11301,9 +11314,9 @@ dependencies = [
[[package]]
name = "wasmtime-wasi"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17f8ce6b9e77539b5f52d440346f876a84c513ec1b07162845282f8652f7f7f9"
checksum = "3175ff29e2992269f51ec372f7757941f11f87b265a614761726960d42ef6e4d"
dependencies = [
"async-trait",
"bitflags 2.13.2",
@@ -11325,9 +11338,9 @@ dependencies = [
[[package]]
name = "wasmtime-wasi-io"
version = "49.0.6"
version = "49.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da9f90eb7ce6edbead27dba3a58843398875defa73b8dce4bbc29d0ce3dc9b40"
checksum = "3bb561839e32b61bf0cdd51efe3874fac5de1bd5775a5b7c41bdf70993e367ea"
dependencies = [
"async-trait",
"bytes",
@@ -11601,7 +11614,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -11769,15 +11782,6 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.60.2"
@@ -12050,7 +12054,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"
dependencies = [
"bitflags 2.13.2",
"windows-sys 0.59.0",
"windows-sys 0.52.0",
]
[[package]]
+2 -3
View File
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.49"
version = "0.1.51"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
@@ -38,6 +38,7 @@ ide-web = { path = "crates/ide-web" }
ide-spell = { path = "crates/ide-spell" }
ide-agent = { path = "crates/ide-agent" }
ide-clipboard = { path = "crates/ide-clipboard" }
ide-drag-out = { path = "crates/ide-drag-out" }
ide-fonts = { path = "crates/ide-fonts" }
ide-ssh = { path = "crates/ide-ssh" }
ide-remote = { path = "crates/ide-remote" }
@@ -68,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)。
+10 -2
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
@@ -35,7 +42,8 @@ icon set, copied unmodified (some renamed) from JetBrains' open-source repositor
→ `maven/`); `plugins/gradle` (`icons/expui/gradle` → `toolwindows/gradle`,
`icons/expui/gradleLoadChanges` → `build/gradleLoadChanges`,
`icons/expui/gradle`, `icons/gradleSubproject` → `gradle/`);
`platform/external-system-impl` (`icons/newui/task` → `externalSystem/task`).
`platform/external-system-impl` (`icons/newui/task` → `externalSystem/task`);
`platform/dvcs-impl` (`icons/new/cherryPick` → `vcs/cherryPick`).
Copyright 2000-2026 JetBrains s.r.o. and contributors. Apache License 2.0 (below).
- [intellij-plugins](https://github.com/JetBrains/intellij-plugins) (each plugin
carries its own licence): `protobuf/protoeditor-core` (`newui/protoFile` →
@@ -65,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.
+5
View File
@@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
encoding_rs.workspace = true
base64.workspace = true
blake3.workspace = true
ide-vfs.workspace = true
ide-core.workspace = true
@@ -25,6 +26,10 @@ dunce.workspace = true
uuid.workspace = true
tempfile.workspace = true
which = "8"
semver = "1"
[target.'cfg(unix)'.dependencies]
rustix = { version = "1", features = ["fs"] }
[dev-dependencies]
tokio = { workspace = true, features = ["test-util"] }
+3 -3
View File
@@ -51,7 +51,7 @@ async fn run_once(
move || launch.resolve_for_launch_with_copilot_env(&root, strip_ambient)
})
.await
.map_err(|e| e.to_string())?;
.map_err(|e| e.to_string())??;
let cwd = dunce::canonicalize(&root).unwrap_or(root);
let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), ..Default::default() });
let client = Dialect::wrap(updates.clone());
@@ -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")));
}
+40 -52
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 {
@@ -194,14 +198,21 @@ impl AgentCatalogs {
(shared.paths.models_file.clone(), shared.paths.project_root.clone(), provider.to_owned())
}
fn fallback(shared: &Shared, provider: &str) -> CatalogData {
/// The catalog saved for this project, for before this run looked anything up.
fn saved(shared: &Shared, provider: &str) -> CatalogData {
let cache = shared.known.lock();
let Some(known) = cache.get(provider) else { return CatalogData::default() };
known.catalogs.get(&shared.root_key()).map(|saved| saved.catalog.clone()).unwrap_or_else(|| CatalogData {
config: known.config.clone(),
thought_levels: known.thought_levels.clone(),
refreshed_at_ms: None,
})
cache
.get(provider)
.and_then(|known| known.catalogs.get(&shared.root_key()))
.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()
}
pub(crate) fn cached(&self, shared: &Shared, provider: &str) -> CatalogData {
@@ -210,32 +221,14 @@ impl AgentCatalogs {
.entries
.get(&Self::key(shared, provider))
.and_then(|e| e.catalog.clone())
.unwrap_or_else(|| Self::fallback(shared, provider))
.unwrap_or_else(|| Self::saved(shared, provider))
}
/// Availability for an explicit session switch must come from a recent discovery for this
/// launch, not from the display fallback or a different project's session report.
pub(super) fn fresh_model(
&self,
shared: &Shared,
spec: &provider::ProviderSpec,
model: &str,
) -> Option<crate::AgentConfigValue> {
let context = LaunchContext::new(spec.clone(), &shared.paths.project_root);
let select = |catalog: &CatalogData| {
let age = self.epoch_ms() - catalog.refreshed_at_ms?;
if !(0.0..FRESH_FOR.as_millis() as f64).contains(&age) {
return None;
}
catalog.model_option()?.values.iter().find(|value| value.value == model).cloned()
};
let state = self.state.lock();
if let Some(entry) = state.entries.get(&Self::key(shared, &spec.id)) {
return select(entry.catalog.as_ref().filter(|_| entry.context == context)?);
}
let cache = shared.known.lock();
let saved = cache.get(&spec.id)?.catalogs.get(&shared.root_key())?;
(saved.fingerprint == context.fingerprint()).then(|| select(&saved.catalog)).flatten()
/// The entry a chat may switch to: exactly what the picker offers from the cached catalog,
/// however long ago it was read. Refreshing keeps that catalog current; a listed model is
/// never refused because the catalog aged.
pub(super) fn listed_model(&self, shared: &Shared, provider: &str, model: &str) -> Option<crate::AgentConfigValue> {
self.cached(shared, provider).model_option()?.values.iter().find(|value| value.value == model).cloned()
}
pub(crate) fn levels(&self, shared: &Shared, provider: &str, model: &str) -> Option<Vec<AgentConfigOption>> {
@@ -246,14 +239,8 @@ impl AgentCatalogs {
}
drop(state);
let cache = shared.known.lock();
let known = cache.get(provider)?;
known
.catalogs
.get(&shared.root_key())
.map(|saved| &saved.catalog.thought_levels)
.unwrap_or(&known.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(
@@ -297,7 +284,7 @@ impl AgentCatalogs {
}
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
let catalog = entry.catalog.clone().unwrap_or_else(|| Self::fallback(shared, provider));
let catalog = entry.catalog.clone().unwrap_or_default();
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
let unknown_model = entry
.requested_model
@@ -306,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
@@ -343,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)
@@ -382,12 +371,11 @@ impl AgentCatalogs {
},
);
}
let fallback =
state.entries.get(&key).filter(|entry| entry.catalog.is_none()).map(|_| Self::fallback(shared, &spec.id));
state.generation += 1;
let generation = state.generation;
let entry = state.entries.get_mut(&key).expect("catalog entry");
let catalog = entry.catalog.as_ref().or(fallback.as_ref()).expect("cached catalog");
let empty = CatalogData::default();
let catalog = entry.catalog.as_ref().unwrap_or(&empty);
let fresh = entry.successful.is_some_and(|at| now.duration_since(at) < FRESH_FOR);
let target = model
.filter(|model| {
@@ -496,7 +484,7 @@ impl AgentCatalogs {
entry.flight_model = None;
let success = match result {
Ok(found) => {
let previous = entry.catalog.take().unwrap_or_else(|| Self::fallback(shared, &key.2));
let previous = entry.catalog.take().unwrap_or_default();
let mut cache = shared.known.lock();
let known = cache.entry(key.2.clone()).or_default();
let mut catalog = CatalogData {
@@ -510,16 +498,16 @@ impl AgentCatalogs {
catalog.thought_levels.insert(model, levels);
}
}
known.config = catalog.config.clone();
known.thought_levels = catalog.thought_levels.clone();
if let Some(commands) = found.commands {
known.commands.insert(shared.root_key(), commands);
}
known.authoritative = true;
known.refreshed_at_ms = catalog.refreshed_at_ms;
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);
+32 -18
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
}
@@ -230,11 +233,9 @@ async fn successful_refresh_replaces_models_and_efforts_and_old_sessions_cannot_
let manager = make_manager(tmp.path(), catalogs.clone(), &harness);
let mut events = events(&manager);
let old = config::options_of(&response(&["old", "retained"], &["low", "high"]));
manager.shared.remember(PROVIDER, Some(&old), None, Some("old"));
let cached = manager.refresh_models(PROVIDER, false, None).unwrap();
assert!(cached.refreshing);
assert_eq!(model_values(&cached), ["old", "retained"]);
assert!(cached.refreshed_at_ms.is_none(), "session reports are not fresh discovery");
assert!(model_values(&cached).is_empty(), "nothing is offered before the first discovery");
let pending = harness.next().await;
assert_eq!(pending.params["mcpServers"], json!([]));
pending.reply.send(Ok(response(&["retained", "new"], &["medium"]))).unwrap();
@@ -258,7 +259,10 @@ async fn successful_refresh_replaces_models_and_efforts_and_old_sessions_cannot_
assert_eq!(provider.config, fresh.config);
restored.shared.remember(PROVIDER, Some(&old), None, Some("old"));
assert_eq!(restored.shared.known_config(PROVIDER), fresh.config);
assert_eq!(restored.shared.known.lock()[PROVIDER].refreshed_at_ms, fresh.refreshed_at_ms);
assert_eq!(
restored.shared.paths.catalogs.cached(&restored.shared, PROVIDER).refreshed_at_ms,
fresh.refreshed_at_ms
);
assert!(!tmp.path().join("store").exists(), "refresh never creates tasks");
}
@@ -308,6 +312,11 @@ async fn discovered_model_reloads_the_same_session_on_the_next_message() {
switch_chat_model(ChatSwitch::Resume).await;
}
#[tokio::test]
async fn discovered_model_from_an_aged_catalog_can_still_be_selected() {
switch_chat_model(ChatSwitch::Aged).await;
}
#[tokio::test]
async fn discovered_model_leaves_the_original_session_intact_after_resume_failure() {
switch_chat_model(ChatSwitch::ResumeFails).await;
@@ -356,6 +365,7 @@ async fn discovered_model_lookup_does_not_overwrite_a_newer_selection() {
#[derive(Clone, Copy)]
enum ChatSwitch {
Live,
Aged,
Resume,
ResumeFails,
Unavailable,
@@ -376,7 +386,8 @@ async fn switch_chat_model(scenario: ChatSwitch) {
let mut harness = Harness::with_initialize(json!({
"protocolVersion": 1, "agentCapabilities": { "loadSession": true }
}));
let mut manager = make_manager(tmp.path(), Arc::default(), &harness);
let catalogs = Arc::new(AgentCatalogs::default());
let mut manager = make_manager(tmp.path(), catalogs.clone(), &harness);
let task = manager
.create(NewAgentTask {
prompt: AgentPrompt { text: "first".into(), ..Default::default() },
@@ -443,7 +454,11 @@ async fn switch_chat_model(scenario: ChatSwitch) {
}
assert_eq!(manager.task(&task.id).unwrap().state.lock().task.config, before_config);
let live = matches!(scenario, ChatSwitch::Live);
let live = matches!(scenario, ChatSwitch::Live | ChatSwitch::Aged);
if matches!(scenario, ChatSwitch::Aged) {
// The catalog stays what the picker offers however long ago it was read.
advance(&catalogs, 20 * 60);
}
let resumed_launch = if missing_settings { 3 } else { 2 };
let load_fails = matches!(scenario, ChatSwitch::ResumeFails);
let unavailable = matches!(scenario, ChatSwitch::Unavailable);
@@ -477,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;
@@ -486,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());
@@ -517,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" }));
@@ -684,7 +699,7 @@ async fn next_chat_request(
}
#[tokio::test]
async fn legacy_cache_loads_without_claiming_authoritative_freshness() {
async fn a_cache_from_before_project_catalogs_offers_nothing_until_discovery_succeeds() {
let tmp = tempfile::tempdir().unwrap();
configure(tmp.path(), "one");
let options = config::options_of(&response(&["legacy"], &["low"]));
@@ -700,12 +715,11 @@ async fn legacy_cache_loads_without_claiming_authoritative_freshness() {
let manager = make_manager(tmp.path(), Arc::default(), &harness);
let mut events = events(&manager);
let cached = manager.refresh_models(PROVIDER, false, None).unwrap();
assert_eq!(model_values(&cached), ["legacy"]);
assert!(model_values(&cached).is_empty());
assert!(cached.refreshing && cached.refreshed_at_ms.is_none());
harness.next().await.reply.send(Err("Sign in required".into())).unwrap();
let failed = completed(&mut events).await;
assert_eq!(failed.config, cached.config);
assert!(failed.error.as_deref().unwrap().contains("Sign in required"));
harness.next().await.reply.send(Ok(response(&["current"], &["low"]))).unwrap();
let found = completed(&mut events).await;
assert_eq!(model_values(&found), ["current"]);
}
#[tokio::test]
+395
View File
@@ -0,0 +1,395 @@
//! Checks and updates only the global npm installation selected by the agent launcher.
use crate::{AgentManager, AgentSource, provider};
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use specta::Type;
use std::{
fs, io,
path::{Path, PathBuf},
process::Command,
};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct AgentCliOffer {
pub current: String,
pub latest: String,
pub prefix: PathBuf,
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "status", rename_all = "camelCase")]
pub enum AgentCliUpdateResult {
Available(AgentCliOffer),
Permission(AgentCliOffer),
Current { current: String },
Channel { current: String },
Updated { current: String },
Unmanaged,
Error { code: String },
}
pub(crate) fn package(id: &str) -> Option<&'static str> {
Some(match id {
"claude" => "@anthropic-ai/claude-code",
"codex" => "@openai/codex",
"gemini" => "@google/gemini-cli",
"opencode" => "opencode-ai",
"copilot" => "@github/copilot",
"qwen" => "@qwen-code/qwen-code",
"auggie" => "@augmentcode/auggie",
"qoder" => "@qoder-ai/qodercli",
"omp" => "@oh-my-pi/pi-coding-agent",
_ => return None,
})
}
impl AgentManager {
pub fn cli_update(
&self,
id: &str,
offer: Option<&AgentCliOffer>,
cancel: &CancellationToken,
) -> IdeResult<AgentCliUpdateResult> {
let spec = self.shared.spec(id).ok_or_else(|| IdeError::invalid(format!("unknown agent {id}")))?;
let (Some(pkg), Some(builtin)) = (package(id), provider::builtin_spec(id)) else {
return Ok(AgentCliUpdateResult::Unmanaged);
};
if spec.source != AgentSource::Builtin {
return Ok(AgentCliUpdateResult::Unmanaged);
}
let Ok(npm) = which::which("npm") else { return Ok(AgentCliUpdateResult::Unmanaged) };
let program = spec.resolve_for_launch(&self.shared.paths.project_root).command;
match maintain(&npm, Path::new(&program), &builtin.command, pkg, offer, cancel) {
Err(e) if e.kind == ErrorKind::Unavailable => Ok(AgentCliUpdateResult::Error { code: e.message }),
result => result,
}
}
}
struct Installation {
modules: PathBuf,
folder: PathBuf,
link: PathBuf,
}
impl Installation {
fn at(prefix: &Path, pkg: &str, bin: &str) -> Self {
let modules = prefix.join(if cfg!(windows) { "node_modules" } else { "lib/node_modules" });
let link = if cfg!(windows) { prefix.join(format!("{bin}.cmd")) } else { prefix.join("bin").join(bin) };
Self { folder: modules.join(pkg), modules, link }
}
fn version(&self, program: &Path, pkg: &str, bin: &str) -> IdeResult<Option<String>> {
if !program.is_absolute() || !self.folder.try_exists()? || !self.link.try_exists()? || !program.try_exists()? {
return Ok(None);
}
let folder = dunce::canonicalize(&self.folder)?;
if fs::symlink_metadata(&self.folder)?.is_symlink()
|| dunce::canonicalize(program)? != dunce::canonicalize(&self.link)?
{
return Ok(None);
}
let manifest = self.folder.join("package.json");
if !manifest.try_exists()? {
return Ok(None);
}
let manifest: Value = serde_json::from_slice(&fs::read(manifest)?)
.map_err(|_| IdeError::invalid("Invalid npm package manifest"))?;
let entry = manifest["bin"].as_str().or_else(|| manifest["bin"][bin].as_str());
let Some(entry) = entry.filter(|_| manifest["name"] == pkg) else { return Ok(None) };
let Some(version) = manifest["version"].as_str() else {
return Err(IdeError::invalid("Missing npm package version"));
};
let entry = folder.join(entry);
if !entry.try_exists()? {
return Ok(None);
}
let entry = dunce::canonicalize(entry)?;
if !entry.starts_with(&folder) {
return Ok(None);
}
#[cfg(unix)]
let owns = fs::symlink_metadata(&self.link)?.is_symlink() && dunce::canonicalize(&self.link)? == entry;
#[cfg(windows)]
let owns = {
let prefix = dunce::canonicalize(self.link.parent().unwrap())?;
let Ok(target) = entry.strip_prefix(prefix) else { return Ok(None) };
let needle = format!("%dp0%\\{}\"", target.display()).to_lowercase();
fs::read_to_string(&self.link)?.replace('/', "\\").to_lowercase().contains(&needle)
};
Ok(owns.then(|| version.to_owned()))
}
fn writable(&self) -> io::Result<bool> {
for dir in [&*self.folder, self.folder.parent().unwrap(), &self.modules, self.link.parent().unwrap()] {
#[cfg(unix)]
let access: io::Result<()> =
rustix::fs::accessat(rustix::fs::CWD, dir, rustix::fs::Access::WRITE_OK, rustix::fs::AtFlags::empty())
.map_err(Into::into);
#[cfg(windows)]
let access = tempfile::tempfile_in(dir).map(drop);
match access {
Err(e) if matches!(e.kind(), io::ErrorKind::PermissionDenied | io::ErrorKind::ReadOnlyFilesystem) => {
return Ok(false);
}
other => other?,
}
}
Ok(true)
}
}
fn stable(version: &str) -> Option<semver::Version> {
semver::Version::parse(version).ok().filter(|v| v.pre.is_empty() && v.build.is_empty())
}
fn maintain(
npm: &Path,
program: &Path,
bin: &str,
pkg: &str,
approved: Option<&AgentCliOffer>,
cancel: &CancellationToken,
) -> IdeResult<AgentCliUpdateResult> {
use AgentCliUpdateResult::*;
let run = |args: &[&str]| {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut cmd = Command::new(npm);
cmd.args(args)
.current_dir(npm.parent().unwrap())
.env("NPM_CONFIG_UPDATE_NOTIFIER", "false")
.env("NPM_CONFIG_LOGLEVEL", "error");
ide_tools::run_streamed(cmd, cancel, &|_| {}).map_err(|e| {
if e.kind == ErrorKind::Cancelled {
return e;
}
// npm diagnostics can contain private registry URLs; expose only known codes.
let code = e
.message
.split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
.find(|w| {
matches!(
*w,
"EACCES"
| "EPERM"
| "EROFS"
| "ENOTFOUND"
| "EAI_AGAIN"
| "ETIMEDOUT"
| "E404"
| "E401"
| "E403"
)
})
.unwrap_or("npm");
IdeError::unavailable(code)
})
};
let output = run(&["prefix", "-g"])?;
let prefix = Path::new(output.trim_end());
if !prefix.is_absolute() {
return Err(IdeError::invalid("Invalid npm global prefix"));
}
let installation = Installation::at(prefix, pkg, bin);
let Some(current) = installation.version(program, pkg, bin)? else { return Ok(Unmanaged) };
let latest: String = serde_json::from_str(&run(&["view", &format!("{pkg}@latest"), "version", "--json"])?)
.map_err(|_| IdeError::invalid("Invalid npm version response"))?;
let (Some(before), Some(after)) = (stable(&current), stable(&latest)) else {
return Ok(Channel { current });
};
if before >= after {
return Ok(Current { current });
}
let offer = AgentCliOffer { current, latest, prefix: prefix.to_owned() };
if !installation.writable()? {
return Ok(Permission(offer));
}
if approved != Some(&offer) {
return Ok(Available(offer));
}
run(&[
"install",
"-g",
"--prefix",
prefix.to_str().unwrap(),
"--no-audit",
"--no-fund",
&format!("{pkg}@{}", offer.latest),
])?;
if installation.version(program, pkg, bin)?.as_ref() != Some(&offer.latest) {
return Err(IdeError::invalid("npm installation verification failed"));
}
Ok(Updated { current: offer.latest })
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use tempfile::TempDir;
const PKG: &str = "@anthropic-ai/claude-code";
struct Fixture {
root: TempDir,
install: Installation,
}
impl Fixture {
fn new() -> Self {
let root = tempfile::Builder::new().prefix("全局 prefix ").tempdir().unwrap();
let install = Installation::at(root.path(), PKG, "claude");
fs::create_dir_all(&install.folder).unwrap();
fs::create_dir_all(install.link.parent().unwrap()).unwrap();
fs::write(install.folder.join("entry.js"), "").unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink(install.folder.join("entry.js"), &install.link).unwrap();
#[cfg(windows)]
fs::write(&install.link, r#"@"%dp0%\node_modules\@anthropic-ai\claude-code\entry.js""#).unwrap();
let fixture = Self { root, install };
fixture.manifest(PKG, "2.1.9");
fixture
}
fn manifest(&self, name: &str, version: &str) {
fs::write(
self.install.folder.join("package.json"),
json!({"name":name,"version":version,"bin":{"claude":"entry.js"}}).to_string(),
)
.unwrap();
}
fn version(&self) -> Option<String> {
self.install.version(&self.install.link, PKG, "claude").unwrap()
}
#[cfg(unix)]
fn npm(&self, script: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let path = self.root.path().join("npm");
fs::write(&path, format!("#!/bin/sh\nset -eu\n{script}\n")).unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
path
}
}
#[test]
fn requires_the_selected_install_and_its_exact_package_entry() {
let f = Fixture::new();
assert_eq!(f.version().as_deref(), Some("2.1.9"));
let other = f.root.path().join("other");
fs::write(&other, "").unwrap();
assert_eq!(f.install.version(&other, PKG, "claude").unwrap(), None);
f.manifest("other-package", "2.1.9");
assert_eq!(f.version(), None);
f.manifest(PKG, "2.1.9");
fs::remove_file(&f.install.link).unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink(&other, &f.install.link).unwrap();
#[cfg(windows)]
fs::write(&f.install.link, r#"@"%dp0%\other""#).unwrap();
assert_eq!(f.version(), None);
}
#[cfg(unix)]
const NPM: &str = r#"case "$1" in
prefix) pwd -P ;;
view) cat latest ;;
install)
test "$2" = "-g" && test "$3" = "--prefix" && test "$4" = "$(pwd -P)"
test "$7" = "@anthropic-ai/[email protected]"
cp updated.json "$4/lib/node_modules/@anthropic-ai/claude-code/package.json"
touch installed ;;
*) exit 2 ;;
esac"#;
#[cfg(unix)]
#[test]
fn installs_only_the_confirmed_offer_and_rechecks_ownership() {
use AgentCliUpdateResult::*;
let f = Fixture::new();
let npm = f.npm(NPM);
let cancel = CancellationToken::new();
let run =
|offer: Option<&AgentCliOffer>| maintain(&npm, &f.install.link, "claude", PKG, offer, &cancel).unwrap();
let latest = f.root.path().join("latest");
fs::write(&latest, r#""2.1.12""#).unwrap();
let Available(offer) = run(None) else { panic!("expected an offer") };
for different in [
AgentCliOffer { prefix: PathBuf::from("/other"), ..offer.clone() },
AgentCliOffer { current: "2.0.0".into(), ..offer.clone() },
] {
assert_eq!(run(Some(&different)), Available(offer.clone()));
}
fs::write(&latest, r#""2.2.0""#).unwrap();
assert!(matches!(run(Some(&offer)), Available(new) if new.latest == "2.2.0"));
fs::write(&latest, r#""2.0.0""#).unwrap();
assert!(matches!(run(Some(&offer)), Current { .. }));
fs::write(&latest, r#""2.2.0-beta.1""#).unwrap();
assert!(matches!(run(Some(&offer)), Channel { .. }));
fs::write(&latest, r#""2.1.12""#).unwrap();
f.manifest("other-package", "2.1.9");
assert_eq!(run(Some(&offer)), Unmanaged);
assert!(!f.root.path().join("installed").exists());
f.manifest(PKG, "2.1.12");
fs::copy(f.install.folder.join("package.json"), f.root.path().join("updated.json")).unwrap();
f.manifest(PKG, "2.1.9");
assert_eq!(run(Some(&offer)), Updated { current: "2.1.12".into() });
assert!(f.root.path().join("installed").exists());
assert_eq!(run(None), Current { current: "2.1.12".into() });
}
#[cfg(unix)]
#[test]
fn permission_failure_never_starts_an_install() {
use std::os::unix::fs::PermissionsExt;
let f = Fixture::new();
let npm = f.npm(NPM);
fs::write(f.root.path().join("latest"), r#""2.1.12""#).unwrap();
let run = |offer: Option<&AgentCliOffer>| {
maintain(&npm, &f.install.link, "claude", PKG, offer, &CancellationToken::new()).unwrap()
};
let AgentCliUpdateResult::Available(offer) = run(None) else { panic!("expected an offer") };
fs::set_permissions(&f.install.folder, fs::Permissions::from_mode(0o555)).unwrap();
// root can write even when no mode bit grants write permission.
if tempfile::tempfile_in(&f.install.folder).is_err() {
assert_eq!(run(Some(&offer)), AgentCliUpdateResult::Permission(offer));
}
fs::set_permissions(&f.install.folder, fs::Permissions::from_mode(0o755)).unwrap();
assert!(!f.root.path().join("installed").exists());
}
#[cfg(unix)]
#[test]
fn cancellation_stops_a_running_npm_process() {
use std::time::{Duration, Instant};
let f = Fixture::new();
let npm = f.npm(
r#"case "$1" in
prefix) pwd -P ;;
view) echo '"2.1.12"' ;;
install) touch started; exec sleep 30 ;;
esac"#,
);
let cancel = CancellationToken::new();
let AgentCliUpdateResult::Available(offer) =
maintain(&npm, &f.install.link, "claude", PKG, None, &cancel).unwrap()
else {
panic!("expected an offer")
};
let started = f.root.path().join("started");
std::thread::scope(|s| {
let op = s.spawn(|| maintain(&npm, &f.install.link, "claude", PKG, Some(&offer), &cancel));
let deadline = Instant::now() + Duration::from_secs(5);
while !started.exists() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
cancel.cancel();
assert!(started.exists());
assert_eq!(op.join().unwrap().unwrap_err().kind, ErrorKind::Cancelled);
});
assert_eq!(f.version().as_deref(), Some("2.1.9"));
}
}
+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}"))
}
+143 -1
View File
@@ -45,6 +45,8 @@ pub struct AgentCapabilities {
pub steer: bool,
/// It reports its background tasks and stops them one by one.
pub background_tasks: bool,
/// The connected agent can report a breakdown of its context window.
pub context_usage: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -108,6 +110,9 @@ pub struct AgentTask {
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub mcp_overrides: BTreeMap<String, bool>,
/// Per-session skill modes (`skill name` -> mode), on top of the settings' policies.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
/// Token counts of the last turn and context compressions, when the agent reports them.
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
#[serde(default)]
@@ -275,6 +280,24 @@ pub struct AgentUsage {
pub cost: Option<Box<AgentCost>>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentContextUsage {
pub categories: Vec<AgentContextCategory>,
pub total_tokens: u32,
pub max_tokens: u32,
pub model: String,
pub is_auto_compact_enabled: Option<bool>,
pub auto_compact_threshold: Option<u32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
pub struct AgentContextCategory {
pub name: String,
pub tokens: u32,
pub kind: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentCost {
@@ -513,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>,
@@ -594,6 +620,9 @@ pub struct AgentProvider {
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
/// Whether the command was found (on `PATH`).
pub installed: bool,
/// The built-in command can be owned by a global npm package.
#[serde(default)]
pub can_check_cli_update: bool,
/// Environment variables it starts with (from its agent file).
pub env: BTreeMap<String, String>,
/// Settings (models, modes…) the agent offered last time it ran; empty before its first session.
@@ -664,6 +693,9 @@ pub struct NewAgentTask {
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`).
#[serde(default)]
pub mcp_overrides: BTreeMap<String, bool>,
/// Per-session skill modes (`skill name` -> mode).
#[serde(default)]
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
/// Creates the task without sending `prompt` (it only names the task): the composer's
/// `!` command runs in it first.
#[serde(default)]
@@ -682,6 +714,8 @@ pub struct AgentChange {
pub removed: u32,
/// Path before a rename; the left side of its diff reads this path.
pub old_path: Option<String>,
/// The repository the file is in, when the task's project holds nested repositories.
pub repo: Option<IpcPath>,
}
/// A commit made while the task ran, with the files it changed against its first parent.
@@ -735,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 {
@@ -767,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,
@@ -856,6 +900,104 @@ fn default_true() -> bool {
true
}
pub use ide_core::settings::{AgentSkillMode, AgentSkillPolicy};
/// Which CLI's own folders a skill was discovered in (Settings › Agents › Skills groups by it).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentSkillSource {
/// The project's `.agents/skills` and `.openidea/skills`.
#[default]
Workspace,
/// The user's `~/.agents/skills` (what `npx skills add` fills).
User,
/// Contributed by an enabled OpenIDEA plugin (`[[contributes.skills]]`).
Plugin,
/// The project's `.claude/skills`.
ClaudeWorkspace,
/// `~/.claude/skills`.
ClaudeUser,
/// The project's `.github/skills` (Copilot's repository skills).
GithubWorkspace,
/// `~/.copilot/skills` and `~/.copilot/installed-plugins/*`.
CopilotUser,
/// The project's `.codex/skills`.
CodexWorkspace,
/// `~/.codex/skills`.
CodexUser,
/// The project's `.cursor/skills`.
CursorWorkspace,
/// `~/.cursor/skills`.
CursorUser,
}
impl AgentSkillSource {
/// Whether skills of this source are only read, never delivered by OpenIDEA: the CLI
/// discovers them itself, so "off" holds only where the CLI supports a native disable.
pub fn discovered(&self) -> bool {
!matches!(self, Self::Workspace | Self::User | Self::Plugin)
}
}
/// One discovered skill: a folder with a `SKILL.md`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentSkill {
/// The frontmatter `name`, else the folder's name.
pub name: String,
pub description: String,
/// Optional `argument-hint` from frontmatter, completed in the `/` menu.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hint: Option<String>,
/// Canonical folder holding `SKILL.md` (symlinks resolved, so duplicates collapse).
pub path: IpcPath,
pub source: AgentSkillSource,
/// Other skill roots whose symlinked entry resolved to this same canonical `path`.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub also_in: Vec<AgentSkillSource>,
/// False when frontmatter sets `user-invocable: false` (omitted from `/` completion).
#[serde(default = "default_true")]
pub user_invocable: bool,
/// True when frontmatter sets `disable-model-invocation: true` (defaults to `slashOnly`).
#[serde(default)]
pub disable_model_invocation: bool,
/// True when frontmatter sets `context: fork` (passed through natively to supporting CLIs).
#[serde(default)]
pub context_fork: bool,
/// Optional `paths` / `globs` patterns from frontmatter (passed through natively to supporting CLIs).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub paths: Vec<String>,
/// The `SKILL.md` passes validation (`name` matches its folder, `description` present).
pub valid: bool,
/// What validation found (`name` mismatch, missing or over-long description…).
pub warnings: Vec<String>,
}
/// A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
/// which layer decided it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentSkillState {
pub skill: AgentSkill,
pub mode: AgentSkillMode,
/// What set `mode`: a session override, the workspace, the user's settings, workspace
/// trust, or nothing (the default `auto`).
pub origin: AgentSkillOrigin,
}
/// Which layer decided a skill's [`AgentSkillState::mode`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentSkillOrigin {
#[default]
None,
Session,
Workspace,
User,
/// An untrusted workspace's skills and policies may only turn skills off.
Trust,
}
/// An external MCP configuration file discovered on disk (user CLI config or workspace file).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+64 -2
View File
@@ -172,6 +172,12 @@ struct Session {
mcp_config: Option<tempfile::TempPath>,
/// MCP servers switched off for this session (`--disallowedTools`), its own config's too.
mcp_off: Vec<String>,
/// The staged skills folder passed as `--add-dir` (its `.claude/skills` holds the copies).
skills_add_dir: Option<PathBuf>,
/// The workspace's other roots, each passed as `--add-dir`.
additional_dirs: Vec<String>,
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
skills_settings: Option<String>,
shim: Weak<Shim>,
st: Mutex<State>,
/// Serializes (re)starting the process.
@@ -356,10 +362,14 @@ impl Shim {
None
}
});
let skills = params.pointer("/_meta/openidea/skills");
let session = Arc::new(Session {
id: id.to_owned(),
mcp_config,
mcp_off,
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
additional_dirs: additional_dirs(params),
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
shim: Arc::downgrade(self),
st: Mutex::new(State {
proc: None,
@@ -405,9 +415,9 @@ impl Shim {
"agentCapabilities": {
"loadSession": true,
"promptCapabilities": { "image": true, "embeddedContext": true },
"sessionCapabilities": { "fork": {} },
"sessionCapabilities": { "fork": {}, "additionalDirectories": {} },
"mcpCapabilities": { "stdio": true, "http": true, "sse": true },
"_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true } },
"_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true, "contextUsage": true } },
},
"agentInfo": { "name": "claude", "title": "Claude Code", "version": self.version() },
"authMethods": [],
@@ -492,6 +502,11 @@ impl Shim {
session.steer(params.get("prompt").cloned().unwrap_or_default()).map_err(invalid)?;
Ok(json!({}))
}
"_openidea/context_usage" => {
let session = self.session(&params)?;
let proc = session.st.lock().proc.clone().ok_or_else(|| internal("Claude Code is not running"))?;
rt.block_on(proc.control(json!({ "subtype": "get_context_usage" }))).map_err(internal)
}
"_openidea/stop_task" => {
let session = self.session(&params)?;
let task = params.get("taskId").and_then(Value::as_str).ok_or_else(|| invalid("no taskId"))?;
@@ -668,6 +683,17 @@ impl Session {
if !self.mcp_off.is_empty() {
args.extend(["--disallowedTools".to_owned(), self.mcp_off.join(",")]);
}
// The staged skills: `.claude/skills` of the added directory is discovered like the
// project's own, and the settings hold the modes of the skills it sees natively too.
if let Some(dir) = &self.skills_add_dir {
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
}
for dir in &self.additional_dirs {
args.extend(["--add-dir".to_owned(), dir.clone()]);
}
if let Some(settings) = &self.skills_settings {
args.extend(["--settings".to_owned(), settings.clone()]);
}
args.extend(start.args());
let launch =
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
@@ -981,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"));
}
@@ -1089,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
@@ -1502,6 +1558,12 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
/// Claude Code's own configuration stays off too.
/// The session's `additionalDirectories`: the workspace's other roots.
fn additional_dirs(params: &Value) -> Vec<String> {
let dirs = params.get("additionalDirectories").and_then(Value::as_array);
dirs.into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect()
}
fn mcp_off(params: &Value) -> Vec<String> {
params
.pointer("/_meta/openidea/mcpServersOff")
@@ -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);
@@ -1275,3 +1325,10 @@ fn mcp_servers_become_an_mcp_config() {
drop(path);
assert!(!kept.exists());
}
#[test]
fn additional_directories_are_read_from_the_session_params() {
let params = json!({ "cwd": "/w/api", "additionalDirectories": ["/w/web", 3, "/w/docs"] });
assert_eq!(additional_dirs(&params), ["/w/web", "/w/docs"]);
assert!(additional_dirs(&json!({ "cwd": "/w/api" })).is_empty());
}
@@ -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
+64 -10
View File
@@ -334,6 +334,38 @@ fn str_param<'a>(params: &'a Value, key: &str) -> Result<&'a str, ResponseError>
params.get(key).and_then(Value::as_str).ok_or_else(|| invalid(format!("missing {key}")))
}
/// Fills a `thread/start`/`thread/resume`/`thread/fork` request's `config` with the session's
/// MCP servers and its staged skills: the off ones, by path (`skills.config` entries with
/// `enabled = false`, which the CLI honors for the copies it discovers natively too).
fn apply_thread_config(params: &Value, request: &mut Value) {
let mut config = translate::mcp_config(params).unwrap_or_else(|| json!({}));
let off: Vec<Value> = params
.pointer("/_meta/openidea/skills/codexOff")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|entry| {
let path = entry.get(1)?.as_str()?;
Some(json!({ "path": path, "enabled": false }))
})
.collect();
if !off.is_empty()
&& let Some(map) = config.as_object_mut()
{
map.insert("skills".into(), json!({ "config": off }));
}
if !config.as_object().is_some_and(|m| m.is_empty()) {
request["config"] = config;
}
// The workspace's other roots join the thread's own: they are where `workspace-write`
// may write and what the model is told the workspace holds.
if let Some(extra) = params.get("additionalDirectories").and_then(Value::as_array).filter(|a| !a.is_empty())
&& let Some(cwd) = params.get("cwd").filter(|c| c.is_string())
{
request["runtimeWorkspaceRoots"] = std::iter::once(cwd).chain(extra).cloned().collect();
}
}
impl CodexShim {
fn codex(&self) -> &Peer {
self.codex.get().expect("attached before any message")
@@ -381,7 +413,7 @@ impl CodexShim {
"loadSession": true,
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
"mcpCapabilities": { "http": false, "sse": false, "stdio": true },
"sessionCapabilities": { "fork": {}, "close": {} },
"sessionCapabilities": { "fork": {}, "close": {}, "additionalDirectories": {} },
"_meta": { "openidea": { "rollback": true, "steer": true } },
},
"agentInfo": { "name": "codex", "title": "Codex", "version": version },
@@ -414,6 +446,31 @@ impl CodexShim {
}
}
/// Hands the session's staged skills to the app-server: the farm's `codex` tree joins
/// its discovery roots. Best-effort: a CLI version without `skills/extraRoots/set`
/// (the method arrived later than some pinned installs) runs without the farm, as
/// before.
async fn apply_skill_roots(&self, session: &str, params: &Value) {
let roots = params
.pointer("/_meta/openidea/skills/codexExtraRoots")
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>())
.unwrap_or_default();
if roots.is_empty() {
return;
}
let set = tokio::time::timeout(
Duration::from_secs(5),
self.call("skills/extraRoots/set", json!({ "extraRoots": roots })),
)
.await;
match set {
Ok(Ok(_)) => {}
Ok(Err(e)) => tracing::info!("codex session {session}: could not set the extra skill roots: {}", e.message),
Err(e) => tracing::info!("codex session {session}: could not set the extra skill roots: {e}"),
}
}
/// Registers a thread codex opened for a session of its own; returns its `configOptions`.
fn open_thread(&self, result: &Value, models: &[ModelInfo], settings: Option<Settings>) -> (String, Value) {
let thread = result.get("thread").unwrap_or(&Value::Null);
@@ -434,14 +491,13 @@ impl CodexShim {
let models = self.models().await?;
self.prepare_project_trust(params).await;
let mut request = json!({ "cwd": params.get("cwd") });
if let Some(config) = translate::mcp_config(params) {
request["config"] = config;
}
apply_thread_config(params, &mut request);
let result = self.call("thread/start", request).await?;
let (id, options) = self.open_thread(&result, &models, None);
if id.is_empty() {
return Err(error(codes::INTERNAL_ERROR, "codex started no thread"));
}
self.apply_skill_roots(&id, params).await;
self.publish_skills(&id).await;
Ok(json!({ "sessionId": id, "configOptions": options }))
}
@@ -452,9 +508,7 @@ impl CodexShim {
let models = self.models().await?;
self.prepare_project_trust(params).await;
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
if let Some(config) = translate::mcp_config(params) {
request["config"] = config;
}
apply_thread_config(params, &mut request);
let result = self.call("thread/resume", request).await?;
let (_, options) = self.open_thread(&result, &models, None);
let cwd = self.state.lock().threads.get(id).and_then(|t| t.cwd.clone());
@@ -462,6 +516,7 @@ impl CodexShim {
for update in translate::history(thread, cwd.as_deref()) {
self.emit(id, update);
}
self.apply_skill_roots(id, params).await;
self.publish_skills(id).await;
Ok(json!({ "configOptions": options }))
}
@@ -472,9 +527,7 @@ impl CodexShim {
self.prepare_project_trust(params).await;
let settings = self.state.lock().threads.get(source).and_then(|t| t.settings.clone());
let mut request = json!({ "threadId": source, "cwd": params.get("cwd") });
if let Some(config) = translate::mcp_config(params) {
request["config"] = config;
}
apply_thread_config(params, &mut request);
if let Some(s) = &settings {
request["model"] = json!(s.model_slug(&models));
request["approvalPolicy"] = json!(s.mode.approval_policy());
@@ -482,6 +535,7 @@ impl CodexShim {
}
let result = self.call("thread/fork", request).await?;
let (id, options) = self.open_thread(&result, &models, settings);
self.apply_skill_roots(&id, params).await;
self.publish_skills(&id).await;
Ok(json!({ "sessionId": id, "configOptions": options }))
}
@@ -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(
@@ -1847,3 +1880,14 @@ fn skills_become_commands_with_their_invocation_names() {
assert!(skill_commands(&json!({"data": []})).unwrap()["availableCommands"].as_array().unwrap().is_empty());
assert!(skill_commands(&json!({})).is_none());
}
#[test]
fn workspace_roots_join_the_thread_roots() {
let params = json!({ "cwd": "/w/api", "mcpServers": [], "additionalDirectories": ["/w/web"] });
let mut request = json!({});
apply_thread_config(&params, &mut request);
assert_eq!(request["runtimeWorkspaceRoots"], json!(["/w/api", "/w/web"]));
let mut request = json!({});
apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request);
assert!(request.get("runtimeWorkspaceRoots").is_none());
}
+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));
}
+22 -1
View File
@@ -144,7 +144,8 @@ async fn discover_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) ->
move || spec.resolve_for_launch_with_copilot_env(&cwd, strip_ambient)
})
.await
.map_err(|e| DiscoverError { message: e.to_string(), allow_acp_fallback: false })?;
.map_err(|e| DiscoverError { message: e.to_string(), allow_acp_fallback: false })?
.map_err(|e| DiscoverError { message: e, allow_acp_fallback: false })?;
let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd);
let args = headless_args(&launch.args);
let peer = Peer::spawn_framed(
@@ -371,6 +372,24 @@ fn error(code: i64, message: impl Into<String>) -> ResponseError {
ResponseError { code, message: message.into(), data: None }
}
/// Adds the session's staged skills to a `session.create`/`session.resume` request:
/// `skillDirectories` (the farm's `copilot` tree) and `disabledSkills` (the off and
/// slash-only ones; Copilot invokes skills with the model only, so a slash-only skill has
/// no other switch here).
fn apply_skills(params: &Value, req: &mut Value) {
let skills = params.pointer("/_meta/openidea/skills");
if let Some(dirs) = skills.and_then(|s| s.get("copilotSkillDirectories")).and_then(Value::as_array)
&& !dirs.is_empty()
{
req["skillDirectories"] = json!(dirs.iter().filter_map(Value::as_str).collect::<Vec<_>>());
}
if let Some(disabled) = skills.and_then(|s| s.get("copilotDisabledSkills")).and_then(Value::as_array)
&& !disabled.is_empty()
{
req["disabledSkills"] = json!(disabled.iter().filter_map(Value::as_str).collect::<Vec<_>>());
}
}
fn invalid(message: impl Into<String>) -> ResponseError {
error(codes::INVALID_PARAMS, message)
}
@@ -495,6 +514,7 @@ impl CopilotShim {
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
let created = self.call("session.create", req).await?;
let session_id = created
@@ -545,6 +565,7 @@ impl CopilotShim {
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
let resumed = self.call("session.resume", req).await?;
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
+14 -2
View File
@@ -312,7 +312,7 @@ impl Settings {
}
/// Parses `models.list` + optional `models.listTokenPriceUnits` into catalog entries,
/// prepending `"auto"` when not already in the list.
/// prepending `"auto"` when direct models are present or Copilot advertises an enabled Auto tier.
pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<ModelEntry> {
let units = parse_price_units(price_units);
let raw = list
@@ -322,7 +322,7 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo
.map(Vec::as_slice)
.unwrap_or_default();
let mut out = Vec::new();
if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && !raw.is_empty() {
if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && (!raw.is_empty() || auto_model_available(list)) {
out.push(ModelEntry {
id: "auto".into(),
name: "Auto".into(),
@@ -344,6 +344,18 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo
out
}
fn auto_model_available(list: &Value) -> bool {
let Some(auto) = list.get("auto") else { return false };
if auto.get("enabled").or_else(|| auto.pointer("/status/enabled")).and_then(Value::as_bool) == Some(false) {
return false;
}
let Some(tiers) = auto.get("tiers").and_then(Value::as_array) else { return auto.is_object() };
tiers.is_empty()
|| tiers.iter().any(|tier| {
tier.get("enabled").or_else(|| tier.pointer("/status/enabled")).and_then(Value::as_bool) != Some(false)
})
}
fn parse_model(m: &Value, units: &HashMap<String, PriceUnit>) -> Option<ModelEntry> {
let id = str_of(m, "id")?.to_owned();
if m.get("model_picker_enabled").and_then(Value::as_bool) == Some(false)
@@ -110,6 +110,72 @@ fn sample_price_units() -> Value {
})
}
#[test]
fn parses_an_enabled_auto_only_catalog() {
let list = json!({
"models": [],
"auto": {
"defaultTier": "balance",
"tiers": [
{
"id": "balance",
"displayName": "Standard",
"type": "auto",
"fusionTier": "standard",
"status": { "enabled": true, "pickerVisible": true }
},
{
"id": "hydrafusion",
"displayName": "High",
"type": "fusion",
"fusionTier": "high",
"status": {
"enabled": false,
"pickerVisible": true,
"reason": "user_not_eligible"
}
},
{
"id": "fast",
"displayName": "Fast",
"type": "auto",
"status": { "enabled": true, "pickerVisible": false }
}
],
"providerId": "copilot"
},
"imageModels": []
});
let catalog = models::parse_catalog(&list, None);
assert_eq!(catalog.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["auto"]);
assert_eq!(Settings::new(&catalog, &UserDefaults::default()).model, "auto");
let options =
config::parse_options(&models::config_options(&catalog, &Settings::new(&catalog, &UserDefaults::default())));
let model = options.iter().find(|option| option.id == MODEL).unwrap();
assert_eq!(model.current.as_deref(), Some("auto"));
assert_eq!(model.values.iter().map(|value| value.value.as_str()).collect::<Vec<_>>(), ["auto"]);
}
#[test]
fn rejects_an_auto_only_catalog_when_every_tier_is_disabled() {
let list = json!({
"models": [],
"auto": {
"defaultTier": "balance",
"tiers": [
{
"id": "balance",
"status": { "enabled": false, "pickerVisible": true }
}
]
}
});
assert!(models::parse_catalog(&list, None).is_empty());
}
#[test]
fn parses_tiered_context_windows_pricing_and_uses_copilots_own_defaults() {
let catalog = models::parse_catalog(&sample_models_list(), Some(&sample_price_units()));
+130 -2
View File
@@ -9,6 +9,8 @@ use serde_json::Value;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
pub(crate) const COPILOT_GITHUB_ACCOUNT_ENV: &str = "OPENIDEA_COPILOT_GITHUB_ACCOUNT";
/// The protocol an agent speaks. Native ones run behind an in-process ACP endpoint
/// (`native`), so tasks see every agent as ACP and read features from its capabilities.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
@@ -138,15 +140,31 @@ impl ProviderSpec {
/// Resolve once before connecting, so authentication guidance names that same install.
pub(crate) fn resolve_for_launch(self, cwd: &Path) -> Self {
let strip = prefer_stored_copilot_auth();
self.resolve_for_launch_with_copilot_env(cwd, strip)
self.resolve_for_launch_base(cwd, strip)
}
pub(crate) fn resolve_for_launch_with_copilot_env(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
pub(crate) fn resolve_for_launch_with_copilot_env(
self,
cwd: &Path,
strip_ambient_tokens: bool,
) -> Result<Self, String> {
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
if let Some(account) = account {
let token = github_token_for_account(&account)?;
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
}
Ok(resolved)
}
fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
if self.driver != Driver::Acp {
self.command = crate::native::newest_install(&self.command);
}
if is_copilot_provider(&self.id) {
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
}
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
self.command =
@@ -164,6 +182,50 @@ pub(crate) fn is_copilot_provider(id: &str) -> bool {
id == "copilot" || id.starts_with("copilot-")
}
pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String> {
env.iter()
.rev()
.find(|(name, _)| name == COPILOT_GITHUB_ACCOUNT_ENV)
.map(|(_, value)| value.trim())
.filter(|value| !value.is_empty())
.map(str::to_owned)
}
fn github_token_for_account(account: &str) -> Result<String, String> {
let path = ide_core::process::shell_env()
.find(|(name, _)| name == "PATH")
.map(|(_, value)| value)
.or_else(|| ide_core::process::host_var_os("PATH"));
let program = path
.as_deref()
.and_then(|path| ide_core::process::find_executable("gh", path))
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
let mut command = std::process::Command::new(program);
command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env());
for name in AMBIENT_COPILOT_AUTH_VARS {
command.env_remove(name);
}
let output = command
.output()
.map_err(|error| format!("Couldn't read GitHub authentication for account {account}: {error}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let detail = stderr.trim();
return Err(if detail.is_empty() {
format!("GitHub CLI has no authenticated account named {account}")
} else {
format!("Couldn't use GitHub account {account}: {detail}")
});
}
let token = String::from_utf8(output.stdout)
.map_err(|_| format!("GitHub CLI returned a non-text token for account {account}"))?;
let token = token.trim();
if token.is_empty() {
return Err(format!("GitHub CLI returned no token for account {account}"));
}
Ok(token.to_owned())
}
pub(crate) fn prefer_stored_copilot_auth() -> bool {
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
}
@@ -311,6 +373,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
command_editable: reason.is_none(),
command_read_only_reason: reason,
installed: installed(&spec.command),
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
env: spec.env.iter().cloned().collect(),
config: vec![],
thought_levels: BTreeMap::new(),
@@ -339,6 +402,31 @@ pub(crate) fn set_builtin_env(
id: &str,
env: BTreeMap<String, String>,
) -> IdeResult<()> {
if id == "copilot" {
let file = custom_dir.join("copilot.toml");
if file.try_exists()?
&& let mut agent = CustomAgent::read_with(&file, id, secrets).map_err(IdeError::invalid)?
&& agent.registry.is_some()
{
let existing = agent.env.clone();
let mut existing_launch_env = existing.clone();
let mut next_launch_env = env.clone();
existing_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
next_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
if existing_launch_env != next_launch_env {
return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry")));
}
match env.get(COPILOT_GITHUB_ACCOUNT_ENV).filter(|value| !value.trim().is_empty()) {
Some(account) => {
agent.env.insert(COPILOT_GITHUB_ACCOUNT_ENV.into(), account.trim().into());
}
None => {
agent.env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
}
}
return agent.write(&file).map_err(Into::into);
}
}
update_builtin(custom_dir, secrets, id, |agent, _| agent.env = env)
}
@@ -955,6 +1043,46 @@ mod tests {
set_builtin_env(dir.path(), None, "not-a-builtin", env).unwrap_err();
}
#[test]
fn registry_copilot_allows_only_the_github_account_override() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("copilot.toml");
CustomAgent {
name: Some("GitHub Copilot".into()),
driver: Driver::Acp,
command: "/tools/copilot".into(),
args: vec!["--acp".into()],
env: BTreeMap::from([("REGISTRY_SETTING".into(), "kept".into())]),
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.0".into() }),
}
.write(&file)
.unwrap();
set_builtin_env(
dir.path(),
None,
"copilot",
BTreeMap::from([
("REGISTRY_SETTING".into(), "kept".into()),
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()),
]),
)
.unwrap();
let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap();
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
.unwrap_err();
}
#[test]
fn launch_metadata_never_passes_the_github_account_control_to_copilot() {
let mut spec = builtin_spec("copilot").unwrap();
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
let resolved = spec.resolve_for_launch(Path::new("."));
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
}
#[test]
fn acp_adapters_of_native_agents_are_unlisted_until_customized() {
let dir = tempfile::tempdir().unwrap();
+8
View File
@@ -537,6 +537,14 @@ fn install_entry_with(
return Err(e);
}
};
let github_account = (entry.id == "copilot")
.then(|| CustomAgent::read(&file).ok())
.flatten()
.and_then(|agent| agent.env.get(provider::COPILOT_GITHUB_ACCOUNT_ENV).cloned());
let mut env = env;
if let Some(account) = github_account {
env.insert(provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account);
}
let agent = CustomAgent {
name: Some(entry.name.clone()),
driver: Driver::Acp,
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
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();
+568 -90
View File
@@ -25,6 +25,116 @@ fn discover(path: &Path) -> IdeResult<Option<Repo>> {
Ok(repo)
}
/// The repositories of a project with nested ones (an own `.git` under the project root, not a
/// submodule), with the folder their files are named from: the root of the repository holding
/// `cwd`, else `cwd`. `None` when only the repository holding `cwd` (if any) is there.
fn nested_repos(cwd: &Path) -> IdeResult<Option<(PathBuf, Vec<Repo>)>> {
let Ok(cwd) = dunce::canonicalize(cwd) else { return Ok(None) };
let found = ide_vcs::Repos::discover(&cwd, &|_| false)?;
if found.all().iter().all(|r| cwd.starts_with(r.root())) {
return Ok(None);
}
let base = found.all().iter().map(|r| r.root()).filter(|r| cwd.starts_with(r)).max().unwrap_or(&cwd).to_path_buf();
let mut repos = Vec::new();
for r in found.all() {
repos.extend(discover(r.root())?);
}
Ok(Some((base, repos)))
}
/// Whether the project at `cwd` holds repositories nested in it: its changes are each one's.
pub(crate) fn spans_repos(cwd: &Path) -> bool {
nested_repos(cwd).is_ok_and(|r| r.is_some())
}
/// The repositories a turn's files are in, and the folder those files are named from.
struct TurnRepos {
base: PathBuf,
repos: Vec<Repo>,
/// The project holds nested repositories: each one's `HEAD` is recorded on its own.
nested: bool,
}
impl TurnRepos {
fn of(cwd: &Path) -> IdeResult<Option<Self>> {
if let Some((base, repos)) = nested_repos(cwd)? {
return Ok(Some(Self { base, repos, nested: true }));
}
Ok(discover(cwd)?.map(|repo| Self { base: repo.root().to_path_buf(), repos: vec![repo], nested: false }))
}
/// The innermost repository holding `path`.
fn owner(&self, path: &Path) -> Option<&Repo> {
owning_repo(&self.repos, path)
}
/// `repo`'s `HEAD` as the turn `start` began.
fn head_then<'a>(&self, start: &'a TurnStart, repo: &Repo) -> Option<&'a str> {
if self.nested { start.heads.get(&root_key(repo.root())) } else { start.head.as_ref() }.map(String::as_str)
}
}
fn root_key(root: &Path) -> String {
root.to_string_lossy().into_owned()
}
fn owning_repo<'a>(repos: &'a [Repo], path: &Path) -> Option<&'a Repo> {
repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().as_os_str().len())
}
/// `path` as a task in `base` names it, if it is not in a repository nested below `repo` (that
/// one lists it itself; to `repo` its folder is untracked).
fn nested_rel(base: &Path, repo: &Repo, roots: &[PathBuf], path: &Path) -> Option<String> {
let rel = path.strip_prefix(base).ok()?;
if path.is_dir()
|| roots.iter().any(|n| n.as_path() != repo.root() && n.starts_with(repo.root()) && path.starts_with(n))
{
return None;
}
Some(rel.to_string_lossy().replace('\\', "/"))
}
/// The uncommitted changes in every repository of the project, against each one's `HEAD`.
fn nested_changes(base: &Path, repos: &[Repo], touched: Option<&BTreeSet<String>>) -> IdeResult<Vec<AgentChange>> {
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
// Match deletions too: find the owner by path components, not by opening the file.
// Display paths use slash separators and lossy Unicode (see nested_rel). If a checkout's
// name cannot round-trip from that representation, keep the full-read fallback.
let owners = touched
.filter(|_| {
roots.iter().all(|root| {
root.strip_prefix(base).is_ok_and(|rel| base.join(rel.to_string_lossy().replace('\\', "/")) == *root)
})
})
.map(|paths| {
paths.iter().filter_map(|rel| owning_repo(repos, &base.join(rel)).map(Repo::root)).collect::<BTreeSet<_>>()
});
let mut out: Vec<AgentChange> = Vec::new();
for repo in repos {
if owners.as_ref().is_some_and(|owners| !owners.contains(repo.root())) {
continue;
}
let listed = match repo.head()?.1 {
Some(head) => changes(repo.root(), &head)?,
None => {
repo.status()?.into_iter().filter(|s| s.path.is_file()).map(|s| added(s.path, s.rel_path)).collect()
}
};
for mut c in listed {
let Some(rel) = nested_rel(base, repo, &roots, &c.path.0) else { continue };
if out.iter().any(|o| o.path == c.path) {
continue;
}
c.rel_path = rel;
c.old_path = None;
c.repo = Some(IpcPath(repo.root().to_path_buf()));
out.push(c);
}
}
out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
Ok(out)
}
fn repo_at(path: &Path) -> IdeResult<Repo> {
discover(path)?.ok_or_else(|| IdeError::unavailable(format!("{} is not in a git repository", path.display())))
}
@@ -38,6 +148,9 @@ pub(crate) fn head_of(path: &Path) -> IdeResult<(String, String)> {
/// `HEAD`'s commit in `cwd`, `None` outside a repository or before its first commit.
pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
if spans_repos(cwd) {
return Ok(Some("HEAD".to_owned()));
}
match discover(cwd)? {
Some(repo) => Ok(repo.head()?.1),
None => Ok(None),
@@ -127,6 +240,7 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
added,
removed,
old_path: f.old_path,
repo: None,
}
})
.collect();
@@ -143,6 +257,9 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
/// Files renamed since `rev`, by their new repository-relative path: the old path, as a deletion
/// to roll back along with the rename.
pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String, AgentChange>> {
if spans_repos(cwd) {
return Ok(BTreeMap::new());
}
let Some(repo) = discover(cwd)? else { return Ok(BTreeMap::new()) };
let root = repo.root().to_path_buf();
Ok(repo
@@ -157,6 +274,7 @@ pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String
added: 0,
removed: 0,
old_path: None,
repo: None,
};
Some((f.path, source))
})
@@ -165,7 +283,7 @@ pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String
fn added(path: IpcPath, rel_path: String) -> AgentChange {
let added = std::fs::read_to_string(&*path).map_or(0, |t| t.lines().count() as u32);
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0, old_path: None }
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0, old_path: None, repo: None }
}
/// The commits from `base` (exclusive) to `head` (inclusive) in `cwd`, newest first, each
@@ -201,6 +319,7 @@ pub(crate) fn commits(cwd: &Path, base: &str, head: &str) -> IdeResult<Vec<Agent
added,
removed,
old_path: f.old_path,
repo: None,
}
})
.collect();
@@ -263,10 +382,30 @@ impl TaskBase {
}
/// The files the task changed, less those changed before it started and untouched since.
pub(crate) fn changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<Vec<AgentChange>> {
pub(crate) fn changes(
&self,
before: &BTreeMap<String, Stamp>,
touched: Option<&BTreeSet<String>>,
) -> IdeResult<Vec<AgentChange>> {
if touched.is_some_and(BTreeSet::is_empty) {
return Ok(Vec::new());
}
Ok(made_by_task(self.read_changes(before, touched)?, touched))
}
fn read_changes(
&self,
before: &BTreeMap<String, Stamp>,
touched: Option<&BTreeSet<String>>,
) -> IdeResult<Vec<AgentChange>> {
let (cwd, start) = match self {
Self::Worktree { cwd, base } => return Ok(without_untouched(changes(cwd, base)?, before)),
Self::Local { cwd, start } => (cwd, start.as_deref()),
Self::Local { cwd, start } => {
if let Some((base, repos)) = nested_repos(cwd)? {
return Ok(without_untouched(nested_changes(&base, &repos, touched)?, before));
}
(cwd, start.as_deref())
}
};
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
// What is uncommitted, as the Commit tool window lists it: commits made since the task
@@ -324,6 +463,9 @@ impl TaskBase {
/// reads cannot put a file in both lists.
pub(crate) fn grouped_changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<AgentChanges> {
let cwd = self.cwd();
if spans_repos(cwd) {
return Ok(AgentChanges { uncommitted: self.changes(before, None)?, commits: Vec::new() });
}
let Some(repo) = discover(cwd)? else { return Ok(AgentChanges::default()) };
let head = repo.head()?.1;
let uncommitted = match &head {
@@ -353,6 +495,8 @@ impl TaskBase {
pub(crate) fn rev(&self) -> IdeResult<Option<String>> {
let (cwd, start) = match self {
Self::Worktree { base, .. } => return Ok(Some(base.clone())),
// Each repository goes back to its own `HEAD`.
Self::Local { cwd, .. } if spans_repos(cwd) => return Ok(Some("HEAD".to_owned())),
Self::Local { cwd, start } => (cwd, start.as_deref()),
};
let Some(repo) = discover(cwd)? else { return Ok(None) };
@@ -545,8 +689,32 @@ pub(crate) fn stamp(path: &Path) -> Stamp {
pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, Stamp>> {
// Paths and stamps only: no diff and no line counts, which read every untracked file
// and held up starting a task in a checkout with many of them.
if let Some((base, repos)) = nested_repos(cwd)? {
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
let mut out = BTreeMap::new();
for repo in &repos {
for s in repo.status()? {
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,
@@ -587,10 +755,16 @@ fn saved_name(rel: &str) -> String {
/// into `dir`, so rolling back the task's changes to them restores the user's own edits.
/// Whether anything was saved.
pub(crate) fn save_before(cwd: &Path, before: &BTreeMap<String, Stamp>, dir: &Path) -> IdeResult<bool> {
let Some(repo) = Repo::discover(cwd)? else { return Ok(false) };
let root = match nested_repos(cwd)? {
Some((base, _)) => base,
None => match Repo::discover(cwd)? {
Some(repo) => repo.root().to_path_buf(),
None => return Ok(false),
},
};
let mut saved = false;
for (rel, stamp) in before {
let path = repo.root().join(rel);
let path = root.join(rel);
if stamp.is_none() || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) {
continue;
}
@@ -601,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).
@@ -611,27 +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 repo = Repo::discover(cwd)?.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.
@@ -656,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)]
@@ -665,6 +877,9 @@ pub(crate) struct TurnStart {
/// `HEAD` then (`None` outside a repository or before its first commit).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub head: Option<String>,
/// With nested repositories, each one's `HEAD` then, by its root.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub heads: BTreeMap<String, String>,
/// The files already changed then, stamped.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub before: BTreeMap<String, Stamp>,
@@ -674,48 +889,146 @@ 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(repo) = discover(cwd)? else { return Ok(TurnStart::default()) };
let head = repo.head()?.1;
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 {
heads.extend(repo.head()?.1.map(|h| (root_key(repo.root()), h)));
}
None
} else {
at.repos[0].head()?.1
};
// 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 = repo.root().join(rel);
if stamp.is_none()
|| saved.contains(rel)
|| !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX)
{
let path = at.base.join(rel);
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, 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
@@ -724,32 +1037,45 @@ pub(crate) fn changed_in_turn(cwd: &Path, start: &TurnStart) -> IdeResult<(Vec<S
let end = snapshot(cwd)?;
let worktree = changed_between(&start.before, &end);
let mut all: BTreeSet<String> = worktree.iter().cloned().collect();
if let Some(repo) = discover(cwd)?
&& let (Some(from), Some(to)) = (&start.head, repo.head()?.1)
&& *from != to
{
let Some(at) = TurnRepos::of(cwd)? else { return Ok((worktree, all)) };
for repo in &at.repos {
let (Some(from), Some(to)) = (at.head_then(start, repo), repo.head()?.1) else { continue };
if from == to {
continue;
}
// Named from the base, as the working tree's files are.
let prefix = rel_in(&at.base, repo.root())?;
let named = |rel: String| if prefix.is_empty() { rel } else { format!("{prefix}/{rel}") };
for f in repo.diff_revisions(from, &to)? {
all.extend(f.old_path);
all.insert(f.path);
all.extend(f.old_path.map(named));
all.insert(named(f.path));
}
}
Ok((worktree, all))
}
/// The content of `rel` as the turn `start` began (`None`: no file), its copies in `dir`.
fn at_turn_start(repo: &Repo, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
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"
))),
},
None => match &start.head {
Some(head) => repo.file_bytes_at(&repo.root().join(rel), Some(head)),
None => Ok(None),
},
None => {
let path = at.base.join(rel);
match at.owner(&path).and_then(|repo| Some((repo, at.head_then(start, repo)?))) {
Some((repo, head)) => repo.file_bytes_at(&path, Some(head)),
None => Ok(None),
}
}
}
}
@@ -771,13 +1097,13 @@ pub(crate) fn turn_changes(
dir: &Path,
changed: &BTreeSet<String>,
) -> IdeResult<Vec<AgentChange>> {
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
let Some(at) = TurnRepos::of(cwd)? else { return Ok(Vec::new()) };
let mut out = Vec::new();
for rel in changed {
let path = repo.root().join(rel);
let path = at.base.join(rel);
// A folder (a submodule, say) or a file that can't be read has nothing to compare.
let Some(now) = existing(&path) else { continue };
let (kind, (added, removed)) = match at_turn_start(&repo, rel, start, dir) {
let (kind, (added, removed)) = match at_turn_start(&at, rel, start, dir) {
Ok(then) if then == now => continue,
Ok(then) => {
let kind = match (&then, &now) {
@@ -790,19 +1116,29 @@ pub(crate) fn turn_changes(
// Its start wasn't saved: listed, without counts.
Err(_) => (ChangeKind::Modified, (0, 0)),
};
out.push(AgentChange { path: IpcPath(path), rel_path: rel.clone(), kind, added, removed, old_path: None });
out.push(AgentChange {
rel_path: rel.clone(),
kind,
added,
removed,
old_path: None,
repo: at.nested.then(|| at.owner(&path).map(|r| IpcPath(r.root().to_path_buf()))).flatten(),
path: IpcPath(path),
});
}
Ok(out)
}
/// The text of `path` as the turn `start` began, `None` when there was no file.
pub(crate) fn turn_text(cwd: &Path, path: &Path, start: &TurnStart, dir: &Path) -> IdeResult<Option<String>> {
let Some(repo) = discover(cwd)? else { return Ok(None) };
let rel = rel_in(repo.root(), path)?;
if let (None, Some(head)) = (start.before.get(&rel), &start.head) {
let Some(at) = TurnRepos::of(cwd)? else { return Ok(None) };
let rel = rel_in(&at.base, path)?;
if !start.before.contains_key(&rel)
&& let Some(head) = at.owner(&at.base.join(&rel)).and_then(|repo| at.head_then(start, repo))
{
return file_at(cwd, path, head);
}
let Some(bytes) = at_turn_start(&repo, &rel, start, dir)? else { return Ok(None) };
let Some(bytes) = at_turn_start(&at, &rel, start, dir)? else { return Ok(None) };
let encoding = match ide_vfs::load_text(path) {
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
Err(_) => ide_vfs::detect_encoding(&bytes, None),
@@ -828,12 +1164,15 @@ fn rel_in(root: &Path, path: &Path) -> IdeResult<String> {
/// Puts `change` back as it was when the turn `start` began.
pub(crate) fn restore_turn(cwd: &Path, start: &TurnStart, dir: &Path, change: &AgentChange) -> IdeResult<()> {
let repo = repo_at(cwd)?;
put(&change.path.0, at_turn_start(&repo, &change.rel_path, start, dir)?)
let at = TurnRepos::of(cwd)?
.ok_or_else(|| IdeError::unavailable(format!("{} is not in a git repository", cwd.display())))?;
put(&change.path.0, at_turn_start(&at, &change.rel_path, start, dir)?)
}
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
let Some(repo) = discover(cwd)? else { return Ok(None) };
// With nested repositories, the file's own one.
let at = if spans_repos(cwd) { path.parent().unwrap_or(cwd) } else { cwd };
let Some(repo) = discover(at)? else { return Ok(None) };
let encoding = match ide_vfs::load_text(path) {
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
Err(_) => ide_vfs::detect_encoding(&repo.file_bytes_at(path, Some(rev))?.unwrap_or_default(), None),
@@ -962,6 +1301,111 @@ mod tests {
assert!(ok, "git {args:?}");
}
#[cfg(unix)]
#[test]
fn attributed_changes_only_diff_the_owning_checkout() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
for n in 0..15 {
let repo = root.join(format!("repo{n:02}"));
std::fs::create_dir_all(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
git(&repo, &["add", "a.txt"]);
git(&repo, &["commit", "-q", "-m", "initial"]);
std::fs::write(repo.join("a.txt"), "two\n").unwrap();
}
// Count real Git diff processes, not walks to discover the topology.
let git = tmp.path().join("count-git");
let log = tmp.path().join("count-git.log");
std::fs::write(
&git,
"#!/bin/sh\nfor arg do\nif [ \"$arg\" = diff ]; then pwd >> \"$0.log\"; break; fi\ndone\nexec git \"$@\"\n",
)
.unwrap();
std::fs::set_permissions(&git, std::fs::Permissions::from_mode(0o700)).unwrap();
let at = TaskBase::Local { cwd: root, start: None };
let before = BTreeMap::new();
let one = BTreeSet::from(["repo07/a.txt".to_owned()]);
let read = |touched: Option<&BTreeSet<String>>| {
std::fs::write(&log, "").unwrap();
let start = std::time::Instant::now();
let changes = ide_vcs::with_git_executable(Some(&git), || at.changes(&before, touched).unwrap());
let elapsed = start.elapsed();
let calls = std::fs::read_to_string(&log).unwrap();
eprintln!("change read: touched={:?} elapsed={elapsed:?}", touched.map(BTreeSet::len));
(changes, calls.lines().count())
};
let (all, full_calls) = read(None);
let (selected, selected_calls) = read(Some(&one));
let (empty, empty_calls) = read(Some(&BTreeSet::new()));
assert_eq!(all.len(), 15);
assert_eq!(
serde_json::to_value(selected).unwrap(),
serde_json::to_value(made_by_task(all, Some(&one))).unwrap()
);
assert!(empty.is_empty());
eprintln!("git diff children: full {full_calls}, one touched {selected_calls}, none touched {empty_calls}");
assert!(selected_calls > 0);
assert_eq!(selected_calls * 15, full_calls);
assert_eq!(empty_calls, 0);
}
#[test]
fn a_project_with_nested_repositories_sees_changes_in_each_one() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let (nested, deeper) = (root.join("libs/validation"), root.join("libs/validation/pkg/sdk"));
for repo in [&root, &nested, &deeper] {
std::fs::create_dir_all(repo).unwrap();
git(repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
git(repo, &["add", "a.txt"]);
git(repo, &["commit", "-q", "-m", "init"]);
}
assert!(spans_repos(&root));
std::fs::write(root.join("mine.txt"), "the user's\n").unwrap();
let before = snapshot(&root).unwrap();
assert_eq!(before.keys().collect::<Vec<_>>(), ["mine.txt"]);
std::fs::write(root.join("a.txt"), "two\n").unwrap();
std::fs::write(nested.join("a.txt"), "two\n").unwrap();
std::fs::write(nested.join("b.txt"), "new\n").unwrap();
std::fs::write(deeper.join("a.txt"), "two\n").unwrap();
let at = TaskBase::Local { cwd: root.clone(), start: None };
let changed = at.changes(&before, None).unwrap();
let listed: Vec<(&str, &Path)> =
changed.iter().map(|c| (c.rel_path.as_str(), c.repo.as_ref().unwrap().0.as_path())).collect();
assert_eq!(
listed,
[
("a.txt", root.as_path()),
("libs/validation/a.txt", nested.as_path()),
("libs/validation/b.txt", nested.as_path()),
("libs/validation/pkg/sdk/a.txt", deeper.as_path()),
]
);
assert_eq!(at.grouped_changes(&before).unwrap().uncommitted.len(), 4);
assert_eq!(file_at(&root, &nested.join("a.txt"), "HEAD").unwrap().as_deref(), Some("one\n"));
let rev = at.rev().unwrap();
for change in &changed {
restore(&root, rev.as_deref(), change, &before, None).unwrap();
}
for repo in [&root, &nested, &deeper] {
assert_eq!(std::fs::read_to_string(repo.join("a.txt")).unwrap(), "one\n");
}
assert!(!nested.join("b.txt").exists());
assert!(root.join("mine.txt").exists(), "the user's own change stays");
// A deleted file cannot be canonicalized, but still belongs to its innermost repo.
std::fs::remove_file(deeper.join("a.txt")).unwrap();
let removed = at.changes(&before, Some(&BTreeSet::from(["libs/validation/pkg/sdk/a.txt".into()]))).unwrap();
assert_eq!(removed.len(), 1);
assert_eq!(removed[0].repo.as_ref().unwrap().0, deeper);
assert_eq!(removed[0].kind, ChangeKind::Deleted);
}
#[test]
fn worktree_changes_are_listed_against_the_base() {
let tmp = tempfile::tempdir().unwrap();
@@ -1012,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)]
@@ -1050,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()),
]);
+199 -32
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, 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());
@@ -916,6 +916,47 @@ fn launch_plan(
Ok(plan)
}
/// Directory of the linked Maven reactor that builds the launch module at `module`;
/// launches of one reactor can share a build ([`build_for_launches`]).
pub fn launch_reactor(root: &Path, model: &BuildModel, module: &Path) -> Option<String> {
maven_reactor(model.maven.as_ref()?, &rel_str(root, module)).map(|top| top.dir.clone())
}
/// One Maven step building every module of `modules` (all of one reactor) with what they
/// depend on: `-pl a,b -am`, so their shared upstream modules build once (#3971).
fn merged_launch_plan(
root: &Path,
model: &BuildModel,
modules: &[PathBuf],
test: bool,
kind: BuildKind,
cancel: &CancellationToken,
) -> IdeResult<BuildPlan> {
let mut plan = launch_plan(root, model, &modules[0], test, kind, cancel)?;
if plan.system != BuildSystem::Maven || modules.len() == 1 {
return Ok(plan);
}
let mut selection = Vec::new();
for module in modules {
let one = launch_plan(root, model, module, test, kind, cancel)?;
if one.steps.len() != 1 || one.steps[0].cwd != plan.steps[0].cwd {
return Err(IdeError::invalid("launch modules belong to different Maven reactors"));
}
match one.steps[0].args.iter().position(|a| a == "-pl") {
Some(i) => selection.push(one.steps[0].args[i + 1].clone()),
// The reactor root itself builds every module.
None => return Ok(one),
}
}
selection.sort();
selection.dedup();
let step = &mut plan.steps[0];
if let Some(i) = step.args.iter().position(|a| a == "-pl") {
step.args[i + 1] = selection.join(",");
}
Ok(plan)
}
#[derive(Debug)]
pub struct LaunchBuild {
pub class_dirs: Vec<PathBuf>,
@@ -924,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,
@@ -931,9 +973,25 @@ pub fn build_for_launch(
test: bool,
kind: BuildKind,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<LaunchBuild> {
let plan = launch_plan(root, model, module, test, kind, cancel)?;
let result = run(root, &plan, cancel, &|_| {})?;
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel, on_event)?;
Ok(built.pop().unwrap())
}
/// [`build_for_launch`] of several modules of one Maven reactor in a single Maven run:
/// one result per module, in order, sharing the build's failure.
pub fn build_for_launches(
root: &Path,
model: &BuildModel,
modules: &[PathBuf],
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, on_event)?;
let failure = if !result.success {
let errors: Vec<String> = result
.messages
@@ -949,17 +1007,70 @@ pub fn build_for_launch(
} else {
None
};
let class_dirs = 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()
} else {
launch_class_dirs(plan.system, module, test)
let class_dirs = |module: &Path| {
if plan.system == BuildSystem::Maven
&& let Some(m) = &model.maven
{
maven_launch_output_dirs(root, m, module, test).into_iter().filter(|dir| dir.is_dir()).collect()
} else {
launch_class_dirs(plan.system, module, test)
}
};
Ok(LaunchBuild { class_dirs, failure })
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> {
@@ -972,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()
@@ -1659,6 +1769,46 @@ mod tests {
}
}
#[test]
fn launches_of_one_reactor_merge_into_one_module_selection() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
for dir in ["app", "lib", "unrelated"] {
write(root, &format!("{dir}/pom.xml"), "<project/>");
}
let mut model = reactor_model();
let cancel = CancellationToken::new();
let modules = |dirs: &[&str]| dirs.iter().map(|d| root.join(d)).collect::<Vec<_>>();
let selection = |plan: BuildPlan| {
let args = &plan.steps[0].args;
args.iter().position(|a| a == "-pl").map(|i| (args[i + 1].clone(), args[i + 2].clone(), args.len()))
};
assert_eq!(launch_reactor(root, &model, &root.join("lib")).as_deref(), Some(""));
let plan = merged_launch_plan(root, &model, &modules(&["lib", "app", "lib"]), false, BuildKind::Build, &cancel)
.unwrap();
assert_eq!(plan.steps.len(), 1);
assert_eq!(plan.steps[0].args.last().unwrap(), "compile");
assert_eq!(selection(plan), Some(("app,lib".into(), "-am".into(), 10)));
// One module: exactly the single launch's step.
let single = merged_launch_plan(root, &model, &modules(&["app"]), true, BuildKind::Rebuild, &cancel).unwrap();
let expected = launch_plan(root, &model, &root.join("app"), true, BuildKind::Rebuild, &cancel).unwrap();
assert_eq!(single.steps[0].args, expected.steps[0].args);
// The reactor root among them builds the whole reactor.
model.maven.as_mut().unwrap().projects[0].packaging = "jar".into();
let whole = merged_launch_plan(root, &model, &modules(&["app", ""]), false, BuildKind::Build, &cancel).unwrap();
assert_eq!(selection(whole), None);
// Another linked reactor can't join the step.
let m = model.maven.as_mut().unwrap();
m.projects[4].aggregated = false;
m.projects[4].command = "other".into();
m.projects[0].modules.retain(|p| p != "unrelated/pom.xml");
assert_eq!(launch_reactor(root, &model, &root.join("unrelated")).as_deref(), Some("unrelated"));
assert!(
merged_launch_plan(root, &model, &modules(&["app", "unrelated"]), false, BuildKind::Build, &cancel)
.is_err()
);
}
#[cfg(unix)]
#[test]
fn external_launch_returns_upstream_outputs_and_blocks_failure_or_cancellation() {
@@ -1675,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"]
@@ -1687,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(
+499 -93
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.
@@ -129,31 +214,75 @@ pub fn module_classpath(
cache: &Path,
cancel: &ide_core::CancellationToken,
) -> IdeResult<String> {
let target = module_target(root, model, module, test)?;
let fingerprint = launch_fingerprint(root, model, &target.module, test, local_repo, cancel)?;
let cache_path = classpath_cache_path(root, cache, &target.module, test);
if let (Some(fingerprint), Some(path)) = (&fingerprint, &cache_path)
&& let Ok(bytes) = fs::read(path)
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
&& cached.version == CLASSPATH_CACHE_VERSION
&& cached.fingerprint == *fingerprint
&& classpath_entries_exist(root, &cached.classpath)
{
return Ok(cached.classpath);
module_classpaths(root, model, &[module.to_path_buf()], test, local_repo, cache, cancel)
}
/// [`module_classpath`] of `modules[0]`. The other modules, launched together with it
/// (#3971), share its Maven probe when they have no cached classpath, which leaves
/// theirs cached for their own launches.
pub fn module_classpaths(
root: &Path,
model: &BuildModel,
modules: &[PathBuf],
test: bool,
local_repo: Option<PathBuf>,
cache: &Path,
cancel: &ide_core::CancellationToken,
) -> IdeResult<String> {
let mut probes: Vec<Probe> = Vec::new();
for (i, module) in modules.iter().enumerate() {
let target = match module_target(root, model, module, test) {
Ok(target) => target,
Err(e) if i == 0 => return Err(e),
Err(_) => continue,
};
if i > 0 && (target.top.dir != probes[0].0.top.dir || probes.iter().any(|p| p.0.module == target.module)) {
continue;
}
let fingerprint = launch_fingerprint(root, model, &target.module, test, local_repo.clone(), cancel)?;
let cache_path = classpath_cache_path(root, cache, &target.module, test);
if let (Some(fingerprint), Some(path)) = (&fingerprint, &cache_path)
&& let Ok(bytes) = fs::read(path)
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
&& cached.version == CLASSPATH_CACHE_VERSION
&& cached.fingerprint == *fingerprint
&& classpath_entries_exist(root, &cached.classpath)
{
if i == 0 {
return Ok(cached.classpath);
}
continue;
}
probes.push(Probe(target, fingerprint, cache_path));
}
let classpath = classpath(root, model, &target, if test { "test" } else { "runtime" }, true)?;
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, 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, cancel)?
}
Err(e) => return Err(e),
};
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if let (Some(fingerprint), Some(path)) = (fingerprint, cache_path) {
let cached = CachedClasspath { version: CLASSPATH_CACHE_VERSION, fingerprint, classpath: classpath.clone() };
if let Err(error) = cache_classpath(&path, &cached) {
tracing::debug!(path = %path.display(), %error, "Cannot cache the Java launch classpath");
for (Probe(_, fingerprint, cache_path), classpath) in probes.into_iter().zip(&classpaths) {
if let (Some(fingerprint), Some(path)) = (fingerprint, cache_path) {
let cached =
CachedClasspath { version: CLASSPATH_CACHE_VERSION, fingerprint, classpath: classpath.clone() };
if let Err(error) = cache_classpath(&path, &cached) {
tracing::debug!(path = %path.display(), %error, "Cannot cache the Java launch classpath");
}
}
}
Ok(classpath)
Ok(classpaths.into_iter().next().unwrap())
}
/// A module whose classpath the Maven probe resolves, with its cache key and file.
struct Probe(SingleFileTarget, Option<LaunchFingerprint>, Option<PathBuf>);
/// One cache file per module and scope. Mirroring the module path keeps nested
/// modules and their different dependency scopes from overwriting each other.
fn classpath_cache_path(root: &Path, cache: &Path, module: &Path, test: bool) -> Option<PathBuf> {
@@ -194,7 +323,68 @@ fn classpath(
target: &SingleFileTarget,
scope: &str,
compile_first: bool,
cancel: &CancellationToken,
) -> IdeResult<String> {
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.
fn classpaths(
root: &Path,
model: &BuildModel,
targets: &[&SingleFileTarget],
scope: &str,
compile_first: bool,
cancel: &CancellationToken,
) -> IdeResult<Vec<String>> {
let top = &targets[0].top;
let probe = CP_FILE;
let mut args = vec!["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG];
args.extend(top.options.iter().map(String::as_str));
// The reactor root among them builds every module.
let selection = if targets.iter().any(|t| t.pl.is_empty()) {
String::new()
} else {
let mut pl: Vec<&str> = targets.iter().map(|t| t.pl.as_str()).collect();
pl.sort();
pl.dedup();
pl.join(",")
};
if !selection.is_empty() {
args.extend(["-pl", selection.as_str(), "-am"]);
}
let output_arg = format!("-Dmdep.outputFile={probe}");
let scope_arg = format!("-Dmdep.includeScope={scope}");
// A launch build may only have reached `compile`. Running `compile` in this
// same Maven session lets the dependency plugin resolve Reactor siblings from
// their target/classes without paying for package-phase plugins.
if compile_first {
args.push("compile");
}
let build_classpath =
maven::plugin_goal("dependency:build-classpath", maven::local_repository_for(&top.options).as_deref());
args.extend([build_classpath.as_str(), output_arg.as_str(), scope_arg.as_str(), "-q"]);
let top_dir = subdir(root, &top.dir);
let owned_args: Vec<String> = args.into_iter().map(str::to_owned).collect();
let out = process::run_bounded(&top.command, &owned_args, &top_dir, &top.env, cancel, |_, _| {}).map_err(|e| {
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> = 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}")));
}
targets.iter().map(|target| target_classpath(root, model, target)).collect()
}
/// The classpath of `target` after a probe: its reactor class directories, then
/// the dependencies Maven wrote to the module's probe file.
fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget) -> IdeResult<String> {
let mut entries: Vec<String> = Vec::new();
// The module's own classes first: the file almost always uses classes next to it.
let own: &[&str] = if target.test { &["target/test-classes", "target/classes"] } else { &["target/classes"] };
@@ -220,75 +410,21 @@ fn classpath(
}
}
}
let probe = CP_FILE;
let mut args = vec!["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG];
args.extend(target.top.options.iter().map(String::as_str));
if !target.pl.is_empty() {
args.extend(["-pl", target.pl.as_str(), "-am"]);
}
let output_arg = format!("-Dmdep.outputFile={probe}");
let scope_arg = format!("-Dmdep.includeScope={scope}");
// A launch build may only have reached `compile`. Running `compile` in this
// same Maven session lets the dependency plugin resolve Reactor siblings from
// their target/classes without paying for package-phase plugins.
if compile_first {
args.push("compile");
}
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
let top_dir = subdir(root, &target.top.dir);
let mut command = ProcCommand::new(&target.top.command);
command.args(&args).envs(&target.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);
// 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 = tail.iter().rev().take(5).rev().cloned().collect::<Vec<_>>().join("\n");
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
}
// With `-am` every visited module writes its own file; only this module's counts.
let cp_file = target.module.join(probe);
let cp_file = target.module.join(CP_FILE);
let content = fs::read_to_string(&cp_file).map_err(|e| {
IdeError::internal(format!("cannot resolve the compile classpath: {} ({e})", cp_file.display()))
})?;
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
@@ -314,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 {
@@ -325,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::*;
@@ -370,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"));
@@ -384,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());
@@ -396,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();
@@ -432,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(
@@ -463,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();
@@ -470,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.
@@ -479,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(
@@ -528,6 +816,48 @@ mod tests {
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
}
/// Modules launched together resolve their classpaths in one Maven probe and leave
/// the others' cached; a probe another module breaks still resolves the first one.
#[cfg(unix)]
#[test]
fn launch_modules_share_one_classpath_probe() {
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();
fixture(root);
write(root, "lib/src/main/java/demo/Lib.java", "class Lib {}");
let script = root.join("mvnw");
fs::write(
&script,
"#!/bin/sh\necho \"$@\" >> calls.txt\npl='.'\nwhile [ $# -gt 0 ]; do\nif [ \"$1\" = \"-pl\" ]; then pl=\"$2\"; shift 2; else shift; fi\ndone\ncase \"$pl\" in *lib*) [ -f lib/broken ] && exit 1;; esac\nfor m in $(echo \"$pl\" | tr ',' ' '); do mkdir -p \"$m/target\" repo; touch \"repo/$m.jar\"; printf \"$PWD/repo/$m.jar\" > \"$m/target/ide-compile-cp.txt\"; done\n",
)
.unwrap();
fs::set_permissions(&script, 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 calls = || fs::read_to_string(root.join("calls.txt")).unwrap_or_default().lines().count();
let modules = [root.join("app"), root.join("lib"), root.join("app")];
let app = module_classpaths(root, &model, &modules, false, None, &cache, &cancel).unwrap();
assert!(app.contains("/repo/app.jar") && !app.contains("repo/lib.jar"), "{app}");
assert_eq!(calls(), 1);
assert!(fs::read_to_string(root.join("calls.txt")).unwrap().contains("-pl app,lib -am compile"));
let lib = module_classpath(root, &model, &root.join("lib"), false, None, &cache, &cancel).unwrap();
assert!(lib.contains("/repo/lib.jar"), "{lib}");
assert_eq!(calls(), 1, "lib's classpath came from the shared probe");
// A probe another module breaks is retried for the first module alone.
write(root, "lib/src/main/java/demo/Lib.java", "class Lib { int changed; }");
write(root, "lib/broken", "");
let app = module_classpaths(root, &model, &[root.join("app"), root.join("lib")], false, None, &cache, &cancel)
.unwrap();
assert!(app.contains("/repo/app.jar"), "{app}");
assert_eq!(calls(), 3, "the shared probe failed, then app was probed alone");
// The first module's own failure stays its failure.
assert!(module_classpath(root, &model, &root.join("lib"), false, None, &cache, &cancel).is_err());
}
/// The launch classpath follows the Maven runner JDK and is reused until that
/// build input changes; the probe does not run packaging plugins.
#[cfg(unix)]
@@ -536,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
@@ -602,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])
}
+14 -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;
@@ -82,11 +83,23 @@ pub fn load_linked(
maven_repo: Option<PathBuf>,
settings: &ide_core::settings::MavenSettings,
gradle_settings: &ide_core::settings::GradleSettings,
) -> BuildModel {
load_linked_with_jdk(root, cache_dir, maven_repo, settings, gradle_settings, None)
}
/// [`load_linked`] with the JDK Maven runs on, for JDK-activated Maven profiles.
pub fn load_linked_with_jdk(
root: &Path,
cache_dir: &Path,
maven_repo: Option<PathBuf>,
settings: &ide_core::settings::MavenSettings,
gradle_settings: &ide_core::settings::GradleSettings,
maven_jdk_version: Option<u32>,
) -> BuildModel {
let maven = maven::has_projects(root, settings).then(|| {
let profiles = settings.profiles(&sync::maven_profiles(cache_dir));
let repo = maven_repo.or_else(maven::default_local_repo);
let mut m = maven::load_with_linked(root, repo, &profiles, &settings.linked_projects);
let mut m = maven::load_with_linked_jdk(root, repo, &profiles, maven_jdk_version, &settings.linked_projects);
maven::UnlinkedProjects::from_model(&m, settings).filter(&mut m);
// The user settings' profiles can be chosen too (`-P` applies to them as well).
for p in maven::user_settings_file(root, settings).map(|f| maven::settings_profiles(&f)).unwrap_or_default() {
File diff suppressed because it is too large. Load diff
+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)
);
}
}
+148 -9
View File
@@ -24,6 +24,21 @@ pub(crate) const MAX_LINE_BYTES: usize = 1024 * 1024;
/// `Output::text` stops growing past this while the pipes keep draining: a chatty build can
/// print far more than is ever parsed back out of the retained copy.
pub(crate) const MAX_TEXT_BYTES: usize = 32 * 1024 * 1024;
/// Lines the pipe readers may queue ahead of the consumer. A build printing faster than
/// `on_line` takes its lines waits on its full pipe, as it would on a terminal, instead of
/// the lines piling up in memory (a line is at most [`MAX_LINE_BYTES`] in [`run_bounded`]).
const LINE_QUEUE: usize = 64;
/// What [`pump_bounded`] reads from a pipe at a time.
const PUMP_CHUNK: usize = 64 * 1024;
/// One line of a child's output, with the stream it came from.
type Line = (Stream, String);
/// The queue from the pipe readers to the consumer: bounded, so the readers wait while the
/// consumer is behind.
fn line_queue() -> (mpsc::SyncSender<Line>, mpsc::Receiver<Line>) {
mpsc::sync_channel(LINE_QUEUE)
}
pub(crate) struct Output {
pub success: bool,
@@ -33,20 +48,20 @@ pub(crate) struct Output {
pub truncated: bool,
}
/// Bounded pump for callers that stream every line and only summarize errors: reads fixed
/// 64 KiB chunks, splits newline-free runs at a UTF-8 char boundary at the line cap, and
/// never grows one line buffer without bound.
fn pump_bounded(stream: Box<dyn Read + Send>, kind: Stream, tx: &mpsc::Sender<(Stream, String)>) {
/// Bounded pump for callers that stream every line and only summarize errors: reads
/// [`PUMP_CHUNK`] chunks, splits newline-free runs at a UTF-8 char boundary at the line cap,
/// and never grows one line buffer without bound.
fn pump_bounded(stream: Box<dyn Read + Send>, kind: Stream, tx: &mpsc::SyncSender<Line>) {
let mut reader = BufReader::new(stream);
// `terminated`: the buffer ends in the stream's newline. A segment cut from a
// newline-free run at the line cap must keep a trailing `\r` — it is data.
let send = |buf: &mut Vec<u8>, terminated: bool, tx: &mpsc::Sender<(Stream, String)>| {
let send = |buf: &mut Vec<u8>, terminated: bool, tx: &mpsc::SyncSender<Line>| {
let line = ide_core::output_encoding::decode_tool_output(buf);
let line = if terminated { line.trim_end_matches(['\n', '\r']).to_owned() } else { line };
buf.clear();
tx.send((kind, line)).is_ok()
};
let mut chunk = vec![0u8; 64 * 1024];
let mut chunk = vec![0u8; PUMP_CHUNK];
let mut line: Vec<u8> = Vec::with_capacity(256);
'read: loop {
let n = match reader.read(&mut chunk) {
@@ -179,8 +194,8 @@ fn run_with_env_capture(
}
let mut child =
command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {}: {e}", program.display())))?;
let (tx, rx) = mpsc::channel::<(Stream, String)>();
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::Sender<(Stream, String)>| {
let (tx, rx) = line_queue();
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::SyncSender<Line>| {
std::thread::spawn(move || {
if bounded {
pump_bounded(stream, kind, &tx);
@@ -212,7 +227,8 @@ fn run_with_env_capture(
// Retained copy of the output: the first half of the cap, then — once output overflows —
// a rolling tail instead of the middle. Error summaries read the end of the output, while
// listings parsed out of a successful run read from the start. The pipes keep draining
// either way: `on_line` still sees every line, so the child never blocks on a full pipe.
// either way: `on_line` still sees every line, and the child waits on its pipe only
// while `on_line` is behind, never because the retained copy is full.
let cap = MAX_TEXT_BYTES / 2;
let mut head = String::new();
let mut tail: std::collections::VecDeque<Vec<u8>> = Default::default();
@@ -295,6 +311,9 @@ fn run_with_env_capture(
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Instant;
#[test]
fn a_model_line_over_one_mebibyte_is_kept_whole_for_the_parsers() {
@@ -500,4 +519,124 @@ mod tests {
assert!(out.text.starts_with("pad\n"));
assert!(out.text.ends_with("FATAL: the real error\n"));
}
/// Numbered lines of `LINE_LEN` bytes each, counting the bytes taken: a pipe stand-in that
/// reports when it is dropped, which is when the pump owning it ends.
const LINE_LEN: usize = 100;
struct NumberedLines {
next: usize,
lines: usize,
taken: Arc<AtomicUsize>,
gone: mpsc::Sender<()>,
}
fn numbered(n: usize) -> String {
format!("{n:0width$}", width = LINE_LEN - 1)
}
impl Read for NumberedLines {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let mut n = 0;
while self.next < self.lines && n + LINE_LEN <= buf.len() {
buf[n..n + LINE_LEN - 1].copy_from_slice(numbered(self.next).as_bytes());
buf[n + LINE_LEN - 1] = b'\n';
self.next += 1;
n += LINE_LEN;
}
self.taken.fetch_add(n, Ordering::SeqCst);
Ok(n)
}
}
impl Drop for NumberedLines {
fn drop(&mut self) {
let _ = self.gone.send(());
}
}
#[test]
fn a_slow_consumer_holds_the_pump_back_instead_of_queueing_every_line() {
const LINES: usize = 50_000;
let taken = Arc::new(AtomicUsize::new(0));
let (gone, _) = mpsc::channel();
let pipe = NumberedLines { next: 0, lines: LINES, taken: taken.clone(), gone };
let (tx, rx) = line_queue();
let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx));
let (mut count, mut peak) = (0usize, 0usize);
loop {
match rx.recv_timeout(Duration::from_secs(60)) {
Ok((stream, line)) => {
assert_eq!(stream, Stream::Stdout);
assert_eq!(line, numbered(count), "a line arrived out of order or damaged");
// Read from the pipe but not yet handed over: the rest of the chunk the pump
// is cutting into lines, and the queue.
peak = peak.max(taken.load(Ordering::SeqCst) - count * LINE_LEN);
count += 1;
// A consumer that cannot keep up with the process.
if count.is_multiple_of(LINE_QUEUE) {
std::thread::sleep(Duration::from_millis(1));
}
}
Err(mpsc::RecvTimeoutError::Disconnected) => break,
Err(mpsc::RecvTimeoutError::Timeout) => panic!("the pump stalled"),
}
}
pump.join().unwrap();
assert_eq!(count, LINES);
let bound = PUMP_CHUNK + (LINE_QUEUE + 2) * LINE_LEN;
assert!(peak <= bound, "{peak} bytes read ahead of the consumer, more than {bound}");
}
#[test]
fn a_pump_blocked_on_a_full_queue_ends_when_the_consumer_is_gone() {
let taken = Arc::new(AtomicUsize::new(0));
let (gone_tx, gone) = mpsc::channel();
// Far more than the queue and a few chunks hold.
let pipe = NumberedLines { next: 0, lines: 100_000, taken: taken.clone(), gone: gone_tx };
let (tx, rx) = line_queue();
let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx));
// A consumer that takes nothing: the queue fills, with the pump inside its first chunk.
let deadline = Instant::now() + Duration::from_secs(30);
while taken.load(Ordering::SeqCst) == 0 {
assert!(Instant::now() < deadline, "the pump never read");
std::thread::sleep(Duration::from_millis(1));
}
// Time for a pump that does not wait to run ahead.
std::thread::sleep(Duration::from_millis(100));
assert!(taken.load(Ordering::SeqCst) <= PUMP_CHUNK, "the pump read past a full queue");
assert!(gone.try_recv().is_err(), "the pump ended while its consumer was still there");
drop(rx);
gone.recv_timeout(Duration::from_secs(30)).expect("the pump stayed blocked after the consumer was gone");
pump.join().unwrap();
}
#[test]
fn a_slow_on_line_still_sees_every_line_in_order_and_the_exit_status() {
if cfg!(windows) {
return;
}
let tmp = tempfile::tempdir().unwrap();
let args = ["-c".into(), "awk 'BEGIN{for(i=1;i<=300000;i++)print i}'; exit 4".into()];
for bounded in [false, true] {
let mut next = 1usize;
let on_line = |stream: Stream, line: &str| {
assert_eq!(stream, Stream::Stdout);
assert_eq!(line, next.to_string());
next += 1;
if next.is_multiple_of(1000) {
std::thread::sleep(Duration::from_millis(1));
}
};
let cancel = CancellationToken::new();
let out = if bounded {
run_bounded("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line)
} else {
run("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line)
}
.unwrap();
assert!(!out.success);
assert_eq!(next, 300_001, "lines were lost");
}
}
}
+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())
}
}
+73 -1
View File
@@ -197,17 +197,34 @@ pub enum ImportsOnPaste {
#[serde(default, rename_all = "camelCase")]
pub struct FoldingSettings {
pub show_outline: bool,
pub outline_visibility: FoldingOutlineVisibility,
pub file_header: bool,
pub imports: bool,
pub doc_comments: bool,
pub go_short_blocks: bool,
}
impl Default for FoldingSettings {
fn default() -> Self {
Self { show_outline: true, file_header: true, imports: true, doc_comments: false }
Self {
show_outline: true,
outline_visibility: FoldingOutlineVisibility::Hover,
file_header: true,
imports: true,
doc_comments: false,
go_short_blocks: true,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum FoldingOutlineVisibility {
#[default]
Hover,
Always,
}
/// Editor › General › Editor Tabs.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -273,6 +290,8 @@ pub struct SmartKeysSettings {
pub pair_quotes: bool,
pub surround_selection: bool,
pub tab_out_of_pair: bool,
/// A `;` typed before the closing `)` of a statement goes to the end of the statement.
pub semicolon_at_statement_end: bool,
/// Simultaneous `<tag></tag>` editing: renaming a tag renames its matching tag.
pub simultaneous_tag_editing: bool,
/// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
@@ -294,6 +313,7 @@ impl Default for SmartKeysSettings {
pair_quotes: true,
surround_selection: true,
tab_out_of_pair: true,
semicolon_at_statement_end: true,
simultaneous_tag_editing: true,
reformat_on_paste: "indentEachLine".into(),
escape_on_paste: true,
@@ -318,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 {
@@ -330,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(),
}
}
}
@@ -342,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,
@@ -374,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,
@@ -420,6 +445,9 @@ pub struct TextAttributesOverride {
pub effect: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub effect_color: Option<String>,
/// IDEA's `ERROR_STRIPE_COLOR`: the diff overview-lane marker of a change type.
#[serde(skip_serializing_if = "Option::is_none")]
pub error_stripe_color: Option<String>,
}
/// Editor › Code Style › <Language> › Tabs and Indents (unset fields inherit).
@@ -452,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).
@@ -543,3 +577,41 @@ mod auto_import_tests {
}
}
}
#[cfg(test)]
mod folding_tests {
use super::{FoldingOutlineVisibility, FoldingSettings};
#[test]
fn folding_outline_defaults_to_hover_for_existing_settings() {
let settings: FoldingSettings = serde_json::from_str(r#"{"showOutline":false}"#).unwrap();
assert!(!settings.show_outline);
assert_eq!(settings.outline_visibility, FoldingOutlineVisibility::Hover);
}
#[test]
fn folding_outline_visibility_round_trips() {
for mode in ["hover", "always"] {
let json = serde_json::json!({ "outlineVisibility": mode });
let settings: FoldingSettings = serde_json::from_value(json).unwrap();
assert_eq!(serde_json::to_value(settings).unwrap()["outlineVisibility"], mode);
}
}
}
#[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);
}
}
+81 -2
View File
@@ -20,7 +20,77 @@ pub struct IdeError {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum ErrorData {
Tool { tool: String, missing: bool },
Tool {
tool: String,
missing: bool,
},
/// A non-fast-forward push from the current branch to its configured upstream.
PushRejected {
source: String,
upstream: String,
divergence: Option<Box<PushDivergence>>,
/// Other refs may already have been published in the same push.
#[specta(optional)]
report: Option<Box<PushReport>>,
},
/// Git updated some refs before a later ref or push URL failed.
PushPartiallyApplied {
report: Box<PushReport>,
},
/// A conflicted history replay left an amend commit ready to keep separately.
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
/// report more than one result for the same ref.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct PushReport {
pub remote: Option<String>,
pub refs: Vec<PushRefResult>,
}
impl PushReport {
pub fn new(remote: Option<String>) -> Self {
Self { remote, refs: Vec::new() }
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct PushRefResult {
pub reference: String,
pub status: PushRefStatus,
/// The number of commits between the tips Git reports for a fast-forward.
pub commits: Option<u32>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum PushRefStatus {
FastForward,
Forced,
Created,
UpToDate,
Deleted,
}
/// The two tips shown in the rejected-push dialog. A retry must use this lease
/// even if a fetch advances the remote-tracking branch while the dialog is open.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PushDivergence {
pub source: String,
pub remote: String,
pub target: String,
pub local_tip: String,
pub remote_tip: String,
pub remote_commits: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -30,7 +100,7 @@ pub enum ErrorKind {
AlreadyExists,
PermissionDenied,
InvalidInput,
/// Document version mismatch; the UI must resync the full text.
/// The requested state is stale; the UI must use the current snapshot.
OutOfSync,
Cancelled,
TimedOut,
@@ -115,4 +185,13 @@ mod tests {
serde_json::json!({"kind":"unavailable","message":"no server","data":null})
);
}
#[test]
fn older_tracked_push_rejections_need_no_report() {
let data: ErrorData = serde_json::from_str(
r#"{"type":"pushRejected","source":"main","upstream":"origin/main","divergence":null}"#,
)
.unwrap();
assert!(matches!(data, ErrorData::PushRejected { report: None, .. }));
}
}
+31 -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,
@@ -92,10 +93,18 @@ pub enum IdeEvent {
/// Text version when this transition occurred, including when it was saved.
version: u32,
},
/// An open document's file changed on disk while the buffer had unsaved changes. The buffer
/// keeps them (autosave leaves the file alone); the UI offers to load the disk version.
DocDiskConflict {
doc: DocId,
path: String,
},
/// A complete workspace edit can be undone as one operation.
WorkspaceEditApplied {
id: u32,
paths: Vec<crate::IpcPath>,
/// Files the edit renamed, as the edit named them: editors open on them follow.
moves: Vec<crate::FileMove>,
/// Made by an agent through the MCP server's tools: undoable like a refactoring, but
/// not announced as one.
by_agent: bool,
@@ -255,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`].
@@ -280,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`].
@@ -316,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}]");
}
}
+6
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,9 +13,11 @@ 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;
pub mod memory;
pub mod output_encoding;
pub mod platform;
pub mod process;
@@ -22,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;
@@ -29,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;
@@ -36,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;
+20
View File
@@ -0,0 +1,20 @@
//! Returning freed heap pages to the OS.
/// Hands pages the allocator has freed but kept back to the OS. Call after a burst of
/// short-lived allocations (a full index scan); until then they still count towards the
/// process's memory footprint.
pub fn release_free_pages() {
#[cfg(target_os = "macos")]
{
unsafe extern "C" {
fn malloc_zone_pressure_relief(zone: *mut std::ffi::c_void, goal: usize) -> usize;
}
// SAFETY: a null zone covers every zone; a zero goal releases as much as possible.
unsafe { malloc_zone_pressure_relief(std::ptr::null_mut(), 0) };
}
#[cfg(all(target_os = "linux", target_env = "gnu"))]
// SAFETY: malloc_trim only returns free memory to the OS.
unsafe {
libc::malloc_trim(0);
}
}
+29
View File
@@ -72,6 +72,16 @@ impl WindowButtonLayout {
let right = side(parts.next());
(!left.is_empty() || !right.is_empty()).then_some(Self { left, right })
}
/// The layout on Linux: the desktop's `gtk-decoration-layout` when a desktop session is running.
/// Without one (WSLg, a bare compositor) GTK reports its built-in fallback, close only, which
/// leaves no way to minimise or maximise the frameless window, so the default applies.
pub fn for_linux(gtk_layout: Option<&str>, var: impl Fn(&str) -> Option<String>) -> Self {
let desktop = ["XDG_CURRENT_DESKTOP", "XDG_SESSION_DESKTOP", "DESKTOP_SESSION"]
.iter()
.any(|key| var(key).is_some_and(|value| !value.trim().is_empty()));
gtk_layout.filter(|_| desktop).and_then(Self::from_gtk_decoration_layout).unwrap_or_default()
}
}
#[cfg(test)]
@@ -118,6 +128,25 @@ mod tests {
}
}
#[test]
fn linux_layout_needs_a_desktop_session() {
let env = |vars: &'static [(&'static str, &'static str)]| {
move |key: &str| vars.iter().find(|(k, _)| *k == key).map(|(_, v)| v.to_string())
};
let gnome = env(&[("XDG_CURRENT_DESKTOP", "ubuntu:GNOME")]);
assert_eq!(WindowButtonLayout::for_linux(Some("appmenu:close"), gnome), layout(&[], &[Close]).unwrap());
let kde = env(&[("DESKTOP_SESSION", "plasma")]);
assert_eq!(
WindowButtonLayout::for_linux(Some("close,maximize,minimize:icon"), kde),
layout(&[Close, Maximize, Minimize], &[]).unwrap()
);
// WSLg: no desktop session, GTK's fallback layout.
let wslg = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("XDG_CURRENT_DESKTOP", " ")]);
assert_eq!(WindowButtonLayout::for_linux(Some("menu:close"), wslg), WindowButtonLayout::default());
let gnome = env(&[("XDG_SESSION_DESKTOP", "gnome")]);
assert_eq!(WindowButtonLayout::for_linux(None, gnome), WindowButtonLayout::default());
}
#[test]
fn default_layout_is_on_the_right() {
assert_eq!(WindowButtonLayout::default(), layout(&[], &[Minimize, Maximize, Close]).unwrap());
+62 -2
View File
@@ -5,6 +5,10 @@ use std::path::Path;
#[cfg(windows)]
use std::process::Stdio;
use std::process::{Child, Command};
pub const ASKPASS_PORT_ENV: &str = "OPENIDEA_ASKPASS_PORT";
/// The IDE's askpass helper may answer with saved credentials only.
pub const ASKPASS_SILENT_ENV: &str = "OPENIDEA_ASKPASS_SILENT";
use std::sync::{Arc, RwLock};
use std::time::Duration;
@@ -398,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
@@ -506,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
@@ -1330,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")]
+122 -17
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.
@@ -100,16 +101,6 @@ pub struct AgentSettings {
pub smooth_text: bool,
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
pub fit_window_width: bool,
/// While the agent works, playful words fill the pauses in what it reports.
pub playful_status: bool,
/// Seconds the agent reports nothing new before the playful words take over; 0 shows them
/// from the start.
pub playful_after_seconds: u32,
/// The user's playful words by activity (`working`, `thinking`, `reading`, …), replacing
/// the built-in ones of that activity; an empty list keeps its status factual.
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, Vec<String>>)]
pub playful_words: BTreeMap<String, Vec<String>>,
#[serde(deserialize_with = "or_default")]
#[specta(type = ThinkingDisplay)]
pub thinking: ThinkingDisplay,
@@ -140,6 +131,11 @@ pub struct AgentSettings {
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, AgentMcpServer>)]
pub mcp_servers: BTreeMap<String, AgentMcpServer>,
/// How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
/// files on disk are never modified.
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, AgentSkillPolicy>)]
pub skills: BTreeMap<String, AgentSkillPolicy>,
}
impl Default for AgentSettings {
@@ -149,12 +145,9 @@ 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,
playful_status: false,
playful_after_seconds: 0,
playful_words: BTreeMap::new(),
thinking: ThinkingDisplay::Auto,
tool_calls: ToolCallDisplay::Grouped,
expand_tool_output: false,
@@ -163,6 +156,7 @@ impl Default for AgentSettings {
new_task_approvals: NewTaskApprovals::Bypass,
defaults: BTreeMap::new(),
mcp_servers: BTreeMap::new(),
skills: BTreeMap::new(),
}
}
}
@@ -218,6 +212,34 @@ impl Default for AgentMcpServer {
}
}
/// How an agent skill may run (`[agents.skills.<name>] mode = …`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentSkillMode {
/// The model decides when to use it.
#[default]
Auto,
/// Only when the user invokes it with `/name`.
SlashOnly,
/// Never.
Off,
}
/// A skill's policy in Settings › Agents › Skills, stored without touching its `SKILL.md`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentSkillPolicy {
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentSkillMode)]
pub mode: AgentSkillMode,
}
impl Default for AgentSkillPolicy {
fn default() -> Self {
Self { mode: AgentSkillMode::Auto }
}
}
/// A hand-edited value these settings don't know reads as the default, rather than
/// failing the whole settings file.
fn or_default<'de, D, T>(d: D) -> Result<T, D::Error>
@@ -557,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(),
@@ -918,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>,
@@ -1185,12 +1210,15 @@ pub struct LanguagesSettings {
pub typescript: TypeScriptSettings,
pub prettier: ExternalFormatterSettings,
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 {
@@ -1205,15 +1233,24 @@ impl Default for LanguagesSettings {
typescript: TypeScriptSettings::default(),
prettier: ExternalFormatterSettings::default(),
oxfmt: ExternalFormatterSettings::default(),
biome: ExternalFormatterSettings {
languages: BIOME_LANGUAGES.iter().map(|&l| l.into()).collect(),
..ExternalFormatterSettings::default()
},
ruff: ExternalFormatterSettings {
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(),
}
}
}
@@ -1233,6 +1270,7 @@ pub struct ArduinoSettings {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct MarkdownSettings {
pub preview_layout: MarkdownPreviewLayout,
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
pub preview_font_size: Option<u32>,
/// "Detect commands that can be run right from Markdown files": gutter run icons on
@@ -1244,10 +1282,23 @@ pub struct MarkdownSettings {
impl Default for MarkdownSettings {
fn default() -> Self {
Self { preview_font_size: None, run_commands: true, command_directory: None }
Self {
preview_layout: MarkdownPreviewLayout::default(),
preview_font_size: None,
run_commands: true,
command_directory: None,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MarkdownPreviewLayout {
#[default]
SideBySide,
Stacked,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "lowercase")]
pub enum MarkdownCommandDirectory {
@@ -1262,7 +1313,9 @@ impl LanguagesSettings {
match tool {
ExternalFormatter::Prettier => &self.prettier,
ExternalFormatter::Oxfmt => &self.oxfmt,
ExternalFormatter::Biome => &self.biome,
ExternalFormatter::Ruff => &self.ruff,
ExternalFormatter::Black => &self.black,
}
}
}
@@ -1273,7 +1326,9 @@ impl LanguagesSettings {
pub enum ExternalFormatter {
Prettier,
Oxfmt,
Biome,
Ruff,
Black,
}
impl ExternalFormatter {
@@ -1282,16 +1337,22 @@ impl ExternalFormatter {
match self {
Self::Prettier => "prettier",
Self::Oxfmt => "oxfmt",
Self::Biome => "biome",
Self::Ruff => "ruff",
Self::Black => "black",
}
}
}
/// An external formatter (Prettier, oxfmt, Ruff) and the languages it formats.
/// The languages Biome formats (of those Prettier formats).
pub const BIOME_LANGUAGES: [&str; 8] =
["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"];
/// 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 {
/// Empty path: project node_modules (Prettier/oxfmt), managed installation, then PATH.
/// Empty path: project node_modules (Prettier/oxfmt/Biome), managed installation, then PATH.
pub path: String,
/// Ruff only: directory containing its configuration, or a configuration file.
pub configuration_directory: String,
@@ -1349,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 {
@@ -1360,6 +1424,7 @@ impl Default for PythonSettings {
hidden_interpreters: Vec::new(),
hide_other_project_interpreters: false,
show_interpreter_paths: true,
interpreter_paths: BTreeMap::new(),
}
}
}
@@ -1452,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 {
@@ -1594,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 {
@@ -1868,6 +1956,20 @@ mod tests {
}
}
#[test]
fn markdown_preview_layout_defaults_and_round_trips() {
let old: Settings = serde_json::from_str(r#"{"languages":{"markdown":{"previewFontSize":16}}}"#).unwrap();
assert_eq!(old.languages.markdown.preview_layout, MarkdownPreviewLayout::SideBySide);
assert_eq!(old.languages.markdown.preview_font_size, Some(16));
let stacked: Settings =
serde_json::from_str(r#"{"languages":{"markdown":{"previewLayout":"stacked"}}}"#).unwrap();
assert_eq!(stacked.languages.markdown.preview_layout, MarkdownPreviewLayout::Stacked);
let saved = serde_json::to_value(&stacked).unwrap();
assert_eq!(saved["languages"]["markdown"]["previewLayout"], "stacked");
assert_eq!(serde_json::from_value::<Settings>(saved).unwrap().languages.markdown, stacked.languages.markdown);
}
#[test]
fn cmake_profile_argument_arrays_round_trip() {
let mut settings = Settings::default();
@@ -2022,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;
@@ -2241,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();
+19
View File
@@ -110,6 +110,17 @@ pub struct WorkspaceEditPrecondition {
}
impl WorkspaceEdit {
/// The files and folders the edit renames, in order.
pub fn moves(&self) -> Vec<FileMove> {
self.files
.iter()
.filter_map(|f| match f {
FileEdit::Rename { from, to } => Some(FileMove { from: from.clone(), to: to.clone() }),
_ => None,
})
.collect()
}
/// Coalesces aliases of the same file before applying edits against its original text.
/// Resource operations separate batches because later edits may use the new contents.
pub fn deduplicate(&mut self) {
@@ -184,6 +195,14 @@ pub enum FileEdit {
},
}
/// One file or folder move.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FileMove {
pub from: crate::IpcPath,
pub to: crate::IpcPath,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum Severity {
@@ -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()
}
+142 -1
View File
@@ -11,6 +11,9 @@ use std::collections::BTreeMap;
pub struct VcsSettings {
/// Colour folders that contain changed files (project tree, tabs).
pub show_dirty_directories: bool,
pub create_changelists_automatically: bool,
/// Diffs the user opens show in an editor tab; off, in a separate window.
pub diff_as_editor_tab: bool,
/// Stop file history (Show History) after `history_limit` commits.
pub limit_history: bool,
pub history_limit: u32,
@@ -55,6 +58,8 @@ impl Default for VcsSettings {
Self {
// IDEA's VcsConfiguration.SHOW_DIRTY_RECURSIVELY is off by default.
show_dirty_directories: false,
create_changelists_automatically: false,
diff_as_editor_tab: true,
limit_history: true,
history_limit: 1000,
git: GitSettings::default(),
@@ -67,31 +72,99 @@ impl Default for VcsSettings {
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum EmptyCherryPickAction {
#[default]
Skip,
CreateEmpty,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum StashDiffTarget {
#[default]
Local,
Parent,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum GitSaveChangesPolicy {
#[default]
Shelve,
Stash,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum FetchTagsMode {
#[default]
Auto,
Sync,
Always,
Never,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum GitAnnotateMovement {
#[default]
None,
WithinFile,
AcrossFiles,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GitAnnotateSettings {
pub ignore_whitespace: bool,
pub movement: GitAnnotateMovement,
}
impl Default for GitAnnotateSettings {
fn default() -> Self {
Self { ignore_whitespace: true, movement: GitAnnotateMovement::None }
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GitSettings {
pub annotate: GitAnnotateSettings,
/// Show blame after the current editor line.
pub inline_blame: bool,
/// A click (or Enter / Space) on the inline blame label opens its commit; off, the
/// label is plain text and a click on it places the caret as past the line end.
pub inline_blame_clickable: bool,
pub show_branch_in_project_view: bool,
/// Branch operations from the branches popup act on every repository of the project.
pub sync_branch_operations: bool,
/// Path to the git executable; empty = auto-detect.
pub executable: String,
/// Clone all submodules along with the root repository.
pub clone_submodules: bool,
/// Default of Update Project: `merge` | `rebase`.
pub update_method: String,
/// Where Git operations keep local changes temporarily.
pub save_changes_policy: GitSaveChangesPolicy,
/// Push rejected (non-fast-forward): update the branch and push again.
pub auto_update_on_push_rejected: bool,
pub warn_crlf: bool,
pub warn_detached_head: bool,
/// Background check for incoming commits: `auto` | `always` | `never`.
/// Background check for incoming commits: `auto` | `always` | `check` | `never`.
pub incoming_check: String,
/// Minutes between background checks for incoming commits.
pub incoming_check_interval: u32,
/// How an explicit fetch or project update handles remote tags.
pub fetch_tags_mode: FetchTagsMode,
/// Branch name globs, `;`/`,`-separated; force push to them is prohibited.
pub protected_branches: String,
/// Initial state of Commit Options › Sign-off Commit.
pub sign_off: bool,
/// Add Git's origin line when cherry-picking commits from protected remote branches.
pub add_cherry_pick_origin: bool,
pub empty_cherry_pick: EmptyCherryPickAction,
/// Ask before committing files larger than `large_file_mb`.
pub warn_large_files: bool,
pub large_file_mb: u32,
@@ -103,6 +176,8 @@ pub struct GitSettings {
pub push_dialog_only_protected: bool,
/// Stashes and shelves share one tab.
pub combine_stash_and_shelf: bool,
/// What the stash browser compares its saved files against.
pub stash_diff_target: StashDiffTarget,
/// The non-modal Commit tool window works on the index: Staged / Unstaged groups,
/// stage and unstage instead of inclusion checkboxes, and no change lists.
pub staging_area: bool,
@@ -114,24 +189,32 @@ pub struct GitSettings {
impl Default for GitSettings {
fn default() -> Self {
Self {
annotate: GitAnnotateSettings::default(),
inline_blame: false,
inline_blame_clickable: true,
show_branch_in_project_view: false,
sync_branch_operations: true,
executable: String::new(),
clone_submodules: true,
update_method: "merge".into(),
save_changes_policy: GitSaveChangesPolicy::default(),
auto_update_on_push_rejected: false,
warn_crlf: true,
warn_detached_head: true,
incoming_check: "auto".into(),
incoming_check_interval: 15,
fetch_tags_mode: FetchTagsMode::Auto,
protected_branches: "master; main".into(),
sign_off: false,
add_cherry_pick_origin: true,
empty_cherry_pick: EmptyCherryPickAction::Skip,
warn_large_files: true,
large_file_mb: 50,
warn_bad_file_names: true,
show_push_dialog: true,
push_dialog_only_protected: false,
combine_stash_and_shelf: false,
stash_diff_target: StashDiffTarget::default(),
staging_area: false,
cli_status: false,
}
@@ -145,9 +228,12 @@ pub struct CommitSettings {
/// Commit from the Commit tool window; off = Local Changes in the Git tool
/// window and a Commit dialog.
pub non_modal: bool,
pub include_changes_by_default: bool,
pub commit_all_when_nothing_staged: bool,
/// Start with an empty message instead of the last one / the changelist's.
pub clear_initial_message: bool,
pub analyze_code: bool,
pub postpone_slow_checks: bool,
pub check_todo: bool,
pub reformat: bool,
pub optimize_imports: bool,
@@ -176,14 +262,19 @@ pub struct CommitSettings {
pub agent_model: String,
/// That model's thinking level for commit messages; empty keeps the agent's.
pub agent_effort: String,
/// Show the Generate Commit Message with Agent button above the commit message.
pub agent_button: bool,
}
impl Default for CommitSettings {
fn default() -> Self {
Self {
non_modal: true,
include_changes_by_default: true,
commit_all_when_nothing_staged: true,
clear_initial_message: false,
analyze_code: true,
postpone_slow_checks: true,
check_todo: true,
reformat: false,
optimize_imports: false,
@@ -201,6 +292,7 @@ impl Default for CommitSettings {
agent: String::new(),
agent_model: String::new(),
agent_effort: String::new(),
agent_button: true,
}
}
}
@@ -368,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")]
@@ -395,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,
}
@@ -416,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(),
}
}
@@ -606,3 +711,39 @@ impl Default for AgentSecuritySettings {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clone_submodules_defaults_on_and_can_be_disabled() {
let missing: GitSettings = serde_json::from_str("{}").unwrap();
let off: GitSettings = serde_json::from_str(r#"{"cloneSubmodules":false}"#).unwrap();
assert!(missing.clone_submodules);
assert!(!off.clone_submodules);
}
#[test]
fn git_settings_without_sync_key_execute_on_all_repositories() {
let missing: GitSettings = serde_json::from_str("{}").unwrap();
assert!(missing.sync_branch_operations);
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
Loaded 100 of 2988 files, more files were not shown because too many files have changed in this diff. Show more