Compare commits

...
Author SHA1 Message Date
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
575 changed files with 43088 additions and 4597 deletions

No files matched your search

Generated
+115 -124
View File
@@ -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]]
@@ -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,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"blake3",
"dunce",
@@ -4171,7 +4171,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4185,7 +4185,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"serde",
@@ -4196,7 +4196,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"blake3",
"chardetng",
@@ -4214,7 +4214,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4228,7 +4228,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4239,7 +4239,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -4250,7 +4250,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"dunce",
"encoding_rs",
@@ -4267,7 +4267,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-run",
@@ -4281,7 +4281,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4310,7 +4310,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4348,7 +4348,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"serde",
@@ -4361,7 +4361,7 @@ dependencies = [
[[package]]
name = "ide-drag-out"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4375,7 +4375,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4396,7 +4396,7 @@ dependencies = [
[[package]]
name = "ide-flutter"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-android",
"ide-core",
@@ -4407,7 +4407,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4419,7 +4419,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4432,7 +4432,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"criterion",
"ide-core",
@@ -4450,7 +4450,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4525,7 +4525,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"hyper-util",
"ide-core",
@@ -4545,7 +4545,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"blake3",
"criterion",
@@ -4567,7 +4567,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4579,7 +4579,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"encoding_rs",
"futures",
@@ -4596,7 +4596,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"libc",
"tempfile",
@@ -4605,7 +4605,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"futures",
"serde",
@@ -4616,7 +4616,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"blake3",
"criterion",
@@ -4675,7 +4675,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"criterion",
"dunce",
@@ -4704,7 +4704,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"bytes",
"dunce",
@@ -4723,7 +4723,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"futures",
"ide-core",
@@ -4746,7 +4746,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"blake3",
"dunce",
@@ -4769,7 +4769,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4783,7 +4783,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"dunce",
"futures",
@@ -4803,7 +4803,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"dunce",
"encoding_rs",
@@ -4827,7 +4827,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-tools",
@@ -4843,7 +4843,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"dunce",
"flate2",
@@ -4866,7 +4866,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"criterion",
"encoding_rs",
@@ -4887,7 +4887,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"parking_lot",
@@ -4900,7 +4900,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4925,7 +4925,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-language",
@@ -4938,7 +4938,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"ide-language",
@@ -4953,7 +4953,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"ide-core",
"libc",
@@ -4967,7 +4967,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"criterion",
"ide-core",
@@ -4980,7 +4980,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"flate2",
"hex",
@@ -5001,7 +5001,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"blake3",
"dunce",
@@ -5022,7 +5022,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"chardetng",
"dunce",
@@ -5049,7 +5049,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5065,7 +5065,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"blake3",
"dunce",
@@ -5227,7 +5227,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]]
@@ -5265,7 +5265,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
dependencies = [
"hermit-abi",
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -6694,7 +6694,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.49"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -7424,9 +7424,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",
@@ -7436,9 +7436,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",
@@ -7968,7 +7968,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -8036,7 +8036,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -9783,7 +9783,7 @@ dependencies = [
"getrandom 0.3.4",
"once_cell",
"rustix",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -11117,9 +11117,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",
@@ -11159,9 +11159,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",
@@ -11190,9 +11190,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",
@@ -11205,15 +11205,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",
@@ -11222,9 +11222,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",
@@ -11248,9 +11248,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",
@@ -11262,9 +11262,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",
@@ -11272,9 +11272,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",
@@ -11283,9 +11283,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",
@@ -11295,9 +11295,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",
@@ -11306,9 +11306,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",
@@ -11320,9 +11320,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",
@@ -11344,9 +11344,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",
@@ -11620,7 +11620,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]]
@@ -11788,15 +11788,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"
@@ -12069,7 +12060,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]]
+1 -1
View File
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.49"
version = "0.1.50"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+18 -48
View File
@@ -194,14 +194,14 @@ 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| saved.catalog.clone())
.unwrap_or_default()
}
pub(crate) fn cached(&self, shared: &Shared, provider: &str) -> CatalogData {
@@ -210,32 +210,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 +228,7 @@ 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()
cache.get(provider)?.catalogs.get(&shared.root_key())?.catalog.thought_levels.get(model).cloned()
}
pub(super) async fn load_levels(
@@ -297,7 +272,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
@@ -382,12 +357,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 +470,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,13 +484,9 @@ 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() },
+23 -12
View File
@@ -230,11 +230,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 +256,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 +309,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 +362,7 @@ async fn discovered_model_lookup_does_not_overwrite_a_newer_selection() {
#[derive(Clone, Copy)]
enum ChatSwitch {
Live,
Aged,
Resume,
ResumeFails,
Unavailable,
@@ -376,7 +383,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 +451,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);
@@ -684,7 +696,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 +712,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]
+193 -60
View File
@@ -23,7 +23,7 @@ mod provider;
pub mod registry;
pub mod security;
mod shell;
mod skills;
pub mod skills;
mod timeline;
mod worktree;
@@ -131,6 +131,19 @@ pub type McpServersFn = dyn Fn() -> Vec<McpServer> + Send + Sync;
/// Returns the executable of the running built-in MCP server, if any.
pub type McpExecutableFn = dyn Fn() -> Option<PathBuf> + Send + Sync;
/// The `[agents.skills.<name>]` policies a session resolves against: the user's (global
/// `settings.toml`), the workspace's (`.openidea/settings.toml`), and whether the workspace
/// is trusted (an untrusted one can only turn skills off).
#[derive(Clone, Debug, Default)]
pub struct SkillsPolicy {
pub user: BTreeMap<String, AgentSkillPolicy>,
pub workspace: BTreeMap<String, AgentSkillPolicy>,
pub workspace_trusted: bool,
}
/// Returns the skill policies for this project.
pub type SkillsPolicyFn = dyn Fn() -> SkillsPolicy + Send + Sync;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct CopilotBinaryKey {
command: String,
@@ -156,27 +169,18 @@ struct Shared {
idle_release_ms: AtomicU64,
mcp_servers_hook: RwLock<Option<Arc<McpServersFn>>>,
mcp_executable_hook: RwLock<Option<Arc<McpExecutableFn>>>,
skills_policy_hook: RwLock<Option<Arc<SkillsPolicyFn>>>,
/// Monotonic id for [`AgentEvent::Attention`] episodes.
attention_seq: AtomicU64,
}
/// What an agent offered in its last session, for the New Task page.
/// What an agent offered, for the New Task page.
#[derive(Clone, Default, Serialize, Deserialize)]
struct Known {
#[serde(default)]
config: Vec<AgentConfigOption>,
/// Thinking levels reported for each model value, including its last choice.
#[serde(default, rename = "thoughtLevels")]
thought_levels: BTreeMap<String, Vec<AgentConfigOption>>,
/// By project root: skills and custom commands differ per project.
#[serde(default, rename = "projectCommands")]
commands: HashMap<String, Vec<AgentCommand>>,
/// Successful discovery, unlike a session report, owns availability.
#[serde(default)]
authoritative: bool,
#[serde(default, rename = "refreshedAtMs")]
refreshed_at_ms: Option<f64>,
/// Authoritative availability and freshness are scoped to project and launch context.
/// Model catalogs by project root, valid for the launch context they were read with.
#[serde(default, rename = "projectCatalogs")]
catalogs: HashMap<String, catalogs::SavedCatalog>,
}
@@ -294,7 +298,8 @@ impl Shared {
self.paths.project_root.to_string_lossy().into_owned()
}
/// Cache levels only when `model` confirms which model the session reported them for.
/// Keeps the commands a session offered and the effort levels it reported for `model`, the
/// only model whose levels it describes.
fn remember(
&self,
provider: &str,
@@ -303,43 +308,22 @@ impl Shared {
model: Option<&str>,
) {
let acp = self.spec(provider).is_some_and(|spec| spec.driver == provider::Driver::Acp);
let mut cache = self.known.lock();
let known = cache.entry(provider.to_owned()).or_default();
let mut changed = false;
// Running tasks retain their own reported settings. Once discovery has
// succeeded, a session's older list/defaults cannot change New Task choices.
if !known.authoritative
&& let Some(config) = config.filter(|c| !c.is_empty())
{
if let Some(model) = model {
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
if known.thought_levels.get(model) != Some(&levels) {
known.thought_levels.insert(model.to_owned(), levels);
changed = true;
}
}
if known.config != config {
known.config = config.to_vec();
if let Some(commands) = commands.filter(|c| !c.is_empty()) {
let mut cache = self.known.lock();
let known = cache.entry(provider.to_owned()).or_default();
if known.commands.get(&self.root_key()).map(Vec::as_slice) != Some(commands) {
known.commands.insert(self.root_key(), commands.to_vec());
self.persist_known(&cache);
changed = true;
}
}
// Discovery reads one model's options; a session on another model reports that model's.
let learned = model.filter(|_| acp && known.authoritative).zip(config).map(|(model, config)| {
if acp && let Some((model, config)) = model.zip(config) {
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
(model, levels)
});
if let Some(commands) = commands.filter(|c| !c.is_empty())
&& known.commands.get(&self.root_key()).map(Vec::as_slice) != Some(commands)
{
known.commands.insert(self.root_key(), commands.to_vec());
changed = true;
}
if changed {
self.persist_known(&cache);
}
drop(cache);
if let Some((model, levels)) = learned.filter(|(_, levels)| !levels.is_empty()) {
self.paths.catalogs.learn_levels(self, provider, model, levels);
if !levels.is_empty() {
self.paths.catalogs.learn_levels(self, provider, model, levels);
}
}
if changed {
self.emit(AgentEvent::Providers);
@@ -528,6 +512,8 @@ struct Task {
idle_epoch: AtomicU64,
/// Turned on when per-session MCP overrides changed while a turn was busy; dropped once idle.
mcp_reload_pending: AtomicBool,
/// Turned on when per-session skill overrides changed while a turn was busy; dropped once idle.
skills_reload_pending: AtomicBool,
/// Settings already sent this session (`(option, value)`), so a refusal is not retried.
config_sent: Mutex<HashSet<(String, String)>>,
dirty: Mutex<BTreeSet<(Session, usize)>>,
@@ -575,6 +561,7 @@ impl AgentManager {
idle_release_ms: AtomicU64::new(IDLE_RELEASE.as_millis() as u64),
mcp_servers_hook: RwLock::new(None),
mcp_executable_hook: RwLock::new(None),
skills_policy_hook: RwLock::new(None),
attention_seq: AtomicU64::new(0),
});
shared.paths.catalogs.subscribe(&shared);
@@ -724,10 +711,15 @@ impl AgentManager {
*self.shared.mcp_executable_hook.write() = Some(Arc::from(hook));
}
/// Provides the user and workspace skill policies and the workspace's trust.
pub fn set_skills_policy_hook(&self, hook: Box<SkillsPolicyFn>) {
*self.shared.skills_policy_hook.write() = Some(Arc::from(hook));
}
/// The slash commands to complete for `provider`, in `task`'s directory or (without one)
/// in the project: what the agent offered last time there, unadvertised builtins,
/// and, for Claude Code, skills and custom commands on disk it has not listed (for Hermes,
/// its profile's skills).
/// for Claude Code the skills and custom commands on disk it has not listed (for
/// Hermes, its profile's skills), and the skills hub's active skills for every agent.
pub async fn commands(&self, provider: &str, task: Option<&str>) -> IdeResult<Vec<AgentCommand>> {
let (provider, offered, cwd) = match task {
Some(id) => {
@@ -770,11 +762,44 @@ impl AgentManager {
.await?;
return Ok(skills::merge(offered, found));
}
if provider != "claude" && provider != "claude-acp" {
return Ok(offered);
if provider == "claude" || provider == "claude-acp" {
let claude_cwd = cwd.clone();
let found = blocking(move || Ok(skills::discover(&claude_cwd, home.as_deref()))).await?;
offered = skills::merge(offered, found);
}
let found = blocking(move || Ok(skills::discover(&cwd, home.as_deref()))).await?;
Ok(skills::merge(offered, found))
// The hub's active skills complete on every agent; its `off` ones drop out here,
// which is all the enforcement an ACP agent gets.
let holder = self.task_for_commands(&provider, task);
let states = match holder {
Some(holder) => holder.skill_states().await,
None => {
let (policy, root) = {
let shared = &self.shared;
let policy = shared.skills_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
(policy, shared.paths.project_root.clone())
};
let home = self.shared.paths.home_dir.clone();
blocking(move || {
Ok(skills::resolve(
skills::discover_skills(&root, home.as_deref()),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
.unwrap_or_default()
}
};
Ok(skills::menu_commands(offered, &states))
}
/// The task to resolve skills for, when the commands are for one and its provider matches.
fn task_for_commands(&self, provider: &str, task: Option<&str>) -> Option<Arc<Task>> {
let task = self.task(task?).ok()?;
let matches = task.state.lock().task.provider == provider;
matches.then_some(task)
}
fn task(&self, id: &str) -> IdeResult<Arc<Task>> {
@@ -858,6 +883,7 @@ impl AgentManager {
retry: None,
background: Box::default(),
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
stats: Box::default(),
};
let file = TaskFile {
@@ -976,6 +1002,7 @@ impl AgentManager {
retry: None,
background: Box::default(),
mcp_overrides: req.mcp_overrides,
skill_overrides: req.skill_overrides,
stats: Box::default(),
};
let file = TaskFile {
@@ -1319,13 +1346,14 @@ impl AgentManager {
(s.task.cwd.0.clone(), s.task.provider.clone(), s.task.mcp_overrides.clone())
};
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
let reply: Value = live
.peer
.request(
"session/fork",
{
let mut params = session_params(&cwd_s, &mcp_servers);
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
params["sessionId"] = json!(live.session);
params
},
@@ -1726,6 +1754,7 @@ impl AgentManager {
*task.deleted.lock() = true;
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json")));
let _ = std::fs::remove_dir_all(task.turn_dir());
skills::remove_farm(&self.shared.paths.store_dir, id);
let saved = task.state.lock().saved.clone();
if let Some(saved) = saved
&& !self.tasks.read().values().any(|t| t.state.lock().saved.as_ref() == Some(&saved))
@@ -1987,6 +2016,38 @@ impl AgentManager {
Ok(out)
}
/// Sets the session's skill modes; like MCP overrides, a change reaches the agent when
/// its idle session is recycled and the next turn starts fresh.
pub fn set_skill_overrides(&self, id: &str, overrides: BTreeMap<String, AgentSkillMode>) -> IdeResult<AgentTask> {
let task = self.task(id)?;
let cleaned: BTreeMap<String, AgentSkillMode> = overrides
.into_iter()
.filter_map(|(k, v)| (!k.trim().is_empty()).then(|| (k.trim().to_owned(), v)))
.collect();
let (changed, busy, has_bg, out) = {
let mut s = task.state.lock();
if s.task.status == AgentStatus::Archived {
return Err(IdeError::invalid("the task is archived"));
}
let changed = s.task.skill_overrides != cleaned;
if changed {
s.task.skill_overrides = cleaned;
s.task.updated_ms = now_ms();
}
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
};
if changed {
task.persist();
task.emit_task();
if busy || has_bg || !task.permissions.lock().is_empty() {
task.skills_reload_pending.store(true, Ordering::Release);
} else {
task.recycle_resumable_session();
}
}
Ok(out)
}
/// Recycles idle resumable live sessions (or schedules reload after the running turn) when
/// global, workspace, or built-in IDE MCP server settings change.
pub fn notify_mcp_servers_changed(&self) {
@@ -2019,6 +2080,55 @@ impl AgentManager {
}
impl Task {
/// The skills offered in this project: every discovery resolved against the policies
/// and the task's overrides.
async fn skill_states(&self) -> Vec<AgentSkillState> {
let (policy, overrides, home, root) = {
let shared = &self.shared;
let policy = shared.skills_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
let overrides = self.state.lock().task.skill_overrides.clone();
(policy, overrides, shared.paths.home_dir.clone(), shared.paths.project_root.clone())
};
blocking(move || {
Ok(skills::resolve(
skills::discover_skills(&root, home.as_deref()),
Some(&overrides),
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
.unwrap_or_default()
}
/// Stages the session's skills into the task's farm and reports what its CLI takes.
/// Nothing staged for an ACP agent (its `/` menu is filtered instead), and a failed
/// stage (locked files, full disk) runs the session without the farm.
async fn stage_skills(&self, provider: &str, cwd: &Path) -> Option<skills::Delivery> {
let states = self.skill_states().await;
let (farm, home, out_cwd) = {
(
skills::farm_dir(&self.shared.paths.store_dir, &self.id),
self.shared.paths.home_dir.clone(),
cwd.to_path_buf(),
)
};
let provider = provider.to_owned();
match blocking(move || {
skills::stage(&farm, &provider, &states, &out_cwd, home.as_deref())
.map_err(|e| IdeError::internal(e.to_string()))
})
.await
{
Ok(delivery) => Some(delivery),
Err(e) => {
tracing::warn!("agent task {}: staging its skills failed: {e}", self.id);
None
}
}
}
fn restore(file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
let mut task = file.task;
config::add_client_options(&task.provider, &mut task.config);
@@ -2075,6 +2185,7 @@ impl Task {
turns: AtomicU64::new(0),
idle_epoch: AtomicU64::new(0),
mcp_reload_pending: AtomicBool::new(false),
skills_reload_pending: AtomicBool::new(false),
config_sent: Mutex::new(HashSet::new()),
dirty: Mutex::new(BTreeSet::new()),
streamed: Mutex::new(HashMap::new()),
@@ -2366,7 +2477,8 @@ impl Task {
if stop != "cancelled" {
self.emit_attention(AgentAttentionReason::Finished);
}
if self.mcp_reload_pending.swap(false, Ordering::AcqRel)
if (self.mcp_reload_pending.swap(false, Ordering::AcqRel)
|| self.skills_reload_pending.swap(false, Ordering::AcqRel))
&& self.state.lock().background_tasks.is_empty()
{
self.recycle_resumable_session();
@@ -2395,8 +2507,7 @@ impl Task {
async fn switch_discovered_model(&self, target: AgentConfigOption, value: String) -> IdeResult<()> {
let provider = self.state.lock().task.provider.clone();
let spec = self.shared.spec(&provider).ok_or_else(|| IdeError::not_found("no such agent"))?;
let candidate = self.shared.paths.catalogs.fresh_model(&self.shared, &spec, &value).ok_or_else(|| {
let candidate = self.shared.paths.catalogs.listed_model(&self.shared, &provider, &value).ok_or_else(|| {
IdeError::invalid(format!("{} has no value {value} in the current model catalog", target.name))
})?;
let selection = {
@@ -2884,6 +2995,7 @@ impl Task {
let (capabilities, embedded) = capabilities_of(&init);
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
let mcp_servers = self.shared.mcp_servers_for_session(provider_id, &init, &mcp_overrides);
let skills_delivery = self.stage_skills(stage_key(spec.driver), cwd).await;
// Agents that compare canonical paths fail in a symlinked directory (macOS `/tmp`).
let cwd_s = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()).to_string_lossy().into_owned();
@@ -2898,7 +3010,7 @@ impl Task {
}
if let (Some(id), true, false) = (saved, can_load, start_fresh) {
self.replaying.store(true, Ordering::Release);
let mut params = session_params(&cwd_s, &mcp_servers);
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
params["sessionId"] = json!(&id);
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
tokio::time::sleep(REPLAY_GRACE).await;
@@ -2938,7 +3050,7 @@ impl Task {
let (session_id, result) = match session {
Some(s) => s,
None => {
let params = session_params(&cwd_s, &mcp_servers);
let params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
let v = self.request_with_auth(&peer, &init, &mut tried_auth, "session/new", params).await.map_err(
|e| match self.sign_in_error(&e, Some(&sign_in_message)) {
Some(msg) => SessionOpenError { message: msg, allow_acp_fallback: false },
@@ -3914,13 +4026,34 @@ struct McpForSession {
off: Vec<String>,
}
/// The driver a session's staged skills are staged for (`skills::stage` matches on it):
/// the native CLIs take the farm, everything else (an ACP agent) gets the `/` menu filter.
fn stage_key(driver: provider::Driver) -> &'static str {
match driver {
provider::Driver::Claude => "claude",
provider::Driver::Codex => "codex",
provider::Driver::Copilot => "copilot",
provider::Driver::Acp => "acp",
}
}
/// The session parameters `session/new`, `session/load` and `session/fork` share: the MCP
/// servers, and the ones off for this session, so an agent that also loads its own
/// configuration (Claude Code) can keep a same-named server of it off too.
fn session_params(cwd: &str, mcp: &McpForSession) -> Value {
/// configuration (Claude Code) can keep a same-named server of it off too — plus the
/// session's staged skills for the drivers that take them.
fn session_params(cwd: &str, mcp: &McpForSession, skills: Option<&skills::Delivery>) -> Value {
let mut params = json!({ "cwd": cwd, "mcpServers": mcp.servers });
let mut meta = json!({});
if !mcp.off.is_empty() {
params["_meta"] = json!({ "openidea": { "mcpServersOff": mcp.off } });
meta["mcpServersOff"] = json!(mcp.off);
}
if let Some(skills) = skills
&& let Ok(v) = serde_json::to_value(skills)
{
meta["skills"] = v;
}
if !meta.is_null() && meta.as_object().is_some_and(|m| !m.is_empty()) {
params["_meta"] = json!({ "openidea": meta });
}
params
}
+86
View File
@@ -110,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)]
@@ -687,6 +690,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)]
@@ -705,6 +711,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.
@@ -879,6 +887,84 @@ 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,
/// 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)
}
}
/// 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,
/// Canonical folder holding `SKILL.md` (symlinks resolved, so duplicates collapse).
pub path: IpcPath,
pub source: AgentSkillSource,
/// 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")]
+15
View File
@@ -172,6 +172,10 @@ 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 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 +360,13 @@ 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),
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,
@@ -673,6 +680,14 @@ 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()]);
}
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() };
+56 -9
View File
@@ -334,6 +334,31 @@ 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;
}
}
impl CodexShim {
fn codex(&self) -> &Peer {
self.codex.get().expect("attached before any message")
@@ -414,6 +439,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 +484,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 +501,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 +509,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 +520,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 +528,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 }))
}
@@ -372,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)
}
@@ -496,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
@@ -546,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 {
+604 -7
View File
@@ -1,11 +1,17 @@
//! Claude Code's slash commands on disk, for completion before (or without) a session:
//! skills (`.claude/skills/<dir>/SKILL.md`) and custom commands (`.claude/commands/**/*.md`)
//! of the working directory and every directory above it, then the user's `~/.claude`; and
//! the skills of a Hermes profile (`<profile>/skills`).
//! Slash commands and skills on disk. Claude Code's own discovery (`.claude/skills` and
//! `.claude/commands` of the working directory tree and `~/.claude`, and a Hermes profile's
//! `skills`) for completion before (or without) a session, plus the multi-level skills hub
//! of #3897: every CLI's skill folders discovered once, deduplicated by canonical path,
//! resolved against the `[agents.skills.<name>]` policies of the global and workspace
//! settings, and staged into a per-session folder the CLIs each receive their own way.
use crate::{AgentCommand, AgentCommandSource};
use std::collections::HashSet;
use std::path::Path;
use crate::{
AgentCommand, AgentCommandSource, AgentSkill, AgentSkillMode, AgentSkillOrigin, AgentSkillPolicy, AgentSkillSource,
AgentSkillState,
};
use ide_core::output_encoding::strip_ansi;
use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
const MAX_DESCRIPTION: usize = 200;
/// Command directories nest this deep at most (`a/b/c.md` → `a:b:c`).
@@ -200,6 +206,370 @@ fn truncate(s: &str) -> String {
}
}
// ─── The skills hub (#3897): discovery, policy, delivery ────────────────────────────
/// A skill's `name` must be this and lowercase letters, digits and hyphens only.
fn valid_name(name: &str) -> bool {
(1..=64).contains(&name.len()) && name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}
/// A `SKILL.md`'s description is at most this many characters.
const MAX_SKILL_DESCRIPTION: usize = 1024;
/// The workspace folders skills are discovered in, by the source they report.
const WORKSPACE_ROOTS: &[(&str, AgentSkillSource)] = &[
(".agents/skills", AgentSkillSource::Workspace),
(".openidea/skills", AgentSkillSource::Workspace),
(".claude/skills", AgentSkillSource::ClaudeWorkspace),
(".github/skills", AgentSkillSource::GithubWorkspace),
(".codex/skills", AgentSkillSource::CodexWorkspace),
(".cursor/skills", AgentSkillSource::CursorWorkspace),
];
/// The home folders skills are discovered in, by the source they report.
const HOME_ROOTS: &[(&str, AgentSkillSource)] = &[
(".agents/skills", AgentSkillSource::User),
(".claude/skills", AgentSkillSource::ClaudeUser),
(".copilot/skills", AgentSkillSource::CopilotUser),
(".codex/skills", AgentSkillSource::CodexUser),
(".cursor/skills", AgentSkillSource::CursorUser),
];
/// Every skill found under `workspace` (a project, scanned even for a worktree task, whose
/// checkout lacks untracked skills) and `home`, in source precedence order, symlinked
/// duplicates collapsed by canonical path: the first of a path wins, and so does the first
/// of a name (the higher source), so a session never sees one skill twice.
pub fn discover_skills(workspace: &Path, home: Option<&Path>) -> Vec<AgentSkill> {
let mut out: Vec<AgentSkill> = Vec::new();
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
let mut seen_names: HashSet<String> = HashSet::new();
let mut roots: Vec<(PathBuf, AgentSkillSource)> = Vec::new();
roots.extend(WORKSPACE_ROOTS.iter().map(|(rel, source)| (workspace.join(rel), *source)));
let mut plugin_roots = Vec::new();
if let Some(home) = home {
roots.extend(HOME_ROOTS.iter().map(|(rel, source)| (home.join(rel), *source)));
// `copilot install` unpacks plugins under `installed-plugins/<plugin>/`, whose skills
// sit in a `skills` folder (or directly in the plugin folder).
let plugins = home.join(".copilot/installed-plugins");
if let Ok(plugins) = plugins.read_dir() {
for plugin in plugins.flatten() {
if plugin.path().is_dir() {
plugin_roots.push((plugin.path().join("skills"), AgentSkillSource::CopilotUser));
plugin_roots.push((plugin.path(), AgentSkillSource::CopilotUser));
}
}
}
}
roots.extend(plugin_roots);
for (root, source) in roots {
for skill in skills_of(&root, source) {
let path = dunce::canonicalize(&skill.path.0).unwrap_or_else(|_| skill.path.0.clone());
if !seen_paths.insert(path.clone()) || !seen_names.insert(skill.name.clone()) {
continue;
}
out.push(AgentSkill { path: path.into(), ..skill });
}
}
out
}
/// The skills of one root: `<name>/SKILL.md` folders, validated.
fn skills_of(root: &Path, source: AgentSkillSource) -> Vec<AgentSkill> {
let mut out: Vec<AgentSkill> = Vec::new();
let Ok(entries) = std::fs::read_dir(root) else { return out };
for entry in entries.flatten() {
let dir = entry.path();
let Some(folder) = dir.file_name().and_then(|n| n.to_str()).map(str::to_owned) else { continue };
if !dir.is_dir() || folder.starts_with('.') {
continue;
}
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
let meta = Frontmatter::parse(&text);
let name = meta.get("name").filter(|n| !n.is_empty()).map(str::to_owned).unwrap_or_else(|| folder.clone());
let mut warnings = Vec::new();
if !valid_name(&name) {
warnings.push(format!("`name: {name}` is not 1-64 lowercase letters, digits or hyphens"));
}
if name != folder {
warnings.push(format!("`name: {name}` does not match the folder `{folder}`"));
}
let description = meta.get("description").unwrap_or_default();
let description = strip_ansi(description).trim().to_owned();
if description.is_empty() {
warnings.push("no `description`: the model never sees when to use it".into());
} else if description.chars().count() > MAX_SKILL_DESCRIPTION {
warnings.push(format!("`description` is over {MAX_SKILL_DESCRIPTION} characters"));
}
out.push(AgentSkill {
name,
description: truncate(&description),
path: dir.into(),
source,
valid: warnings.is_empty(),
warnings,
});
}
out.sort_by(|a, b| a.name.cmp(&b.name));
out
}
/// A skill's mode, as one policy layer of the settings has it.
type Policies = BTreeMap<String, AgentSkillPolicy>;
/// Resolves every skill's mode: a session override, then the workspace's and the user's
/// `[agents.skills.<name>]` policy, then the default `auto` — with an untrusted workspace
/// able to turn skills off only: its own skills stay off (whatever the session chose), and
/// its policies hold only when they turn a skill off.
pub fn resolve(
skills: Vec<AgentSkill>,
session: Option<&BTreeMap<String, AgentSkillMode>>,
workspace: &Policies,
user: &Policies,
workspace_trusted: bool,
) -> Vec<AgentSkillState> {
let mut out = Vec::new();
for skill in skills {
let workspace_skill = matches!(
skill.source,
AgentSkillSource::Workspace
| AgentSkillSource::ClaudeWorkspace
| AgentSkillSource::GithubWorkspace
| AgentSkillSource::CodexWorkspace
| AgentSkillSource::CursorWorkspace
);
let (mode, origin) = if workspace_skill && !workspace_trusted {
// Workspace trust gates the workspace's own skills, whatever else says.
(AgentSkillMode::Off, AgentSkillOrigin::Trust)
} else if let Some(chosen) = session.and_then(|s| s.get(&skill.name)) {
(*chosen, AgentSkillOrigin::Session)
} else if let Some(policy) =
workspace.get(&skill.name).filter(|p| workspace_trusted || p.mode == AgentSkillMode::Off)
{
(policy.mode, AgentSkillOrigin::Workspace)
} else if let Some(policy) = user.get(&skill.name) {
(policy.mode, AgentSkillOrigin::User)
} else {
(AgentSkillMode::Auto, AgentSkillOrigin::None)
};
out.push(AgentSkillState { skill, mode, origin });
}
out
}
/// What one CLI session receives for its active skills. Sent to the shims in
/// `session/new`'s `_meta.openidea.skills`, so each driver applies its own fields.
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Delivery {
/// Claude Code: the farm passed as `--add-dir` (its `.claude/skills` holds the staged copies).
#[serde(skip_serializing_if = "Option::is_none")]
pub claude_add_dir: Option<PathBuf>,
/// Claude Code: the `--settings` JSON with `skillOverrides` (the native skills too).
#[serde(skip_serializing_if = "Option::is_none")]
pub claude_settings: Option<String>,
/// Copilot: `skillDirectories` (the farm's `copilot` tree).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub copilot_skill_directories: Vec<String>,
/// Copilot: `disabledSkills`, spelled as the skills are.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub copilot_disabled_skills: Vec<String>,
/// Codex: `skills/extraRoots/set` roots (the farm's `codex` tree).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub codex_extra_roots: Vec<String>,
/// Codex: `skills.config` entries turning skills off by path.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub codex_off: Vec<(String, String)>,
}
/// Stages the skills a session of `provider` runs with into `farm` — linking (copying on
/// Windows, where directory symlinks need Developer Mode) every active skill folder into
/// the CLI's tree — and reports what to hand the CLI. Skills the CLI discovers natively
/// (its own folders of the working directory and the home) are not staged again: it already
/// sees them, and seeing both would list one skill twice. Skills `off` are never staged;
/// the CLI's native disable (where it has one) receives their names or paths. An ACP
/// agent gets nothing here: its `/` menu is filtered instead.
pub fn stage(
farm: &Path,
provider: &str,
states: &[AgentSkillState],
cwd: &Path,
home: Option<&Path>,
) -> std::io::Result<Delivery> {
let mut out = Delivery::default();
let cwd = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf());
// Only the native drivers take the farm, each its own tree; `provider` is their key
// (`claude`, `copilot`, `codex`), anything else (an ACP agent) gets the `/` menu filter.
let (claude_tree, copilot_tree, codex_tree) = match provider {
"claude" => (Some(farm.join(".claude/skills")), None, None),
"copilot" => (None, Some(farm.join("copilot")), None),
"codex" => (None, None, Some(farm.join("codex"))),
_ => return Ok(out),
};
// Restage from scratch: a skill turned off or deleted since the last session must not
// linger in the tree. Removing a tree removes its links, never the skills they point at.
for tree in [&claude_tree, &copilot_tree, &codex_tree].into_iter().flatten() {
match std::fs::remove_dir_all(tree) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
_ => {}
}
}
for state in states {
let name = state.skill.name.as_str();
let path = state.skill.path.0.as_path();
match state.mode {
AgentSkillMode::Off => {
out.codex_off.push((name.to_owned(), state.skill.path.to_string_lossy().into_owned()));
}
// Claude Code runs a slash-only skill on `/name`, so it has to see the folder;
// Copilot and Codex have no such mode and get it disabled or left out.
AgentSkillMode::SlashOnly => {
if let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home)) {
link_skill(&tree.join(name), path)?;
}
}
AgentSkillMode::Auto => {
if let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home)) {
link_skill(&tree.join(name), path)?;
}
if let Some(tree) = copilot_tree.as_ref().filter(|_| !native_copilot(&state.skill, &cwd, home)) {
link_skill(&tree.join(name), path)?;
}
if let Some(tree) = codex_tree.as_ref().filter(|_| !native_codex(&state.skill, &cwd, home)) {
link_skill(&tree.join(name), path)?;
}
}
}
}
if claude_tree.as_ref().is_some_and(|t| t.exists()) {
out.claude_add_dir = Some(farm.to_path_buf());
}
if let Some(tree) = copilot_tree.as_ref().filter(|t| t.exists()) {
out.copilot_skill_directories.push(tree.to_string_lossy().into_owned());
}
if let Some(tree) = codex_tree.as_ref().filter(|t| t.exists()) {
out.codex_extra_roots.push(tree.to_string_lossy().into_owned());
}
// Claude Code's `skillOverrides` and Copilot's `disabledSkills` take the names of the
// off and slash-only skills — the native copies included.
let off: Vec<&str> =
states.iter().filter(|s| s.mode == AgentSkillMode::Off).map(|s| s.skill.name.as_str()).collect();
let slash: Vec<&str> =
states.iter().filter(|s| s.mode == AgentSkillMode::SlashOnly).map(|s| s.skill.name.as_str()).collect();
if !off.is_empty() || !slash.is_empty() {
let mut overrides = serde_json::Map::new();
for (name, mode) in off.iter().map(|n| (*n, "off")).chain(slash.iter().map(|n| (*n, "user-invocable-only"))) {
overrides.insert(name.to_owned(), serde_json::Value::String(mode.to_owned()));
}
out.claude_settings = Some(
serde_json::to_string(&serde_json::json!({ "skillOverrides": overrides })).expect("settings serialize"),
);
out.copilot_disabled_skills = off.iter().chain(slash.iter()).map(|n| (*n).to_owned()).collect();
out.copilot_disabled_skills.sort();
}
Ok(out)
}
/// Claude Code sees this skill without the farm: its own `.claude/skills` of the working
/// directory (a worktree lacks the untracked originals) or the home.
fn native_claude(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
match skill.source {
AgentSkillSource::ClaudeWorkspace => is_under(skill.path.0.as_path(), cwd),
AgentSkillSource::ClaudeUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".claude"))),
_ => false,
}
}
/// Copilot reads the repository's `.github/skills` and the home's `.copilot` itself.
fn native_copilot(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
match skill.source {
AgentSkillSource::GithubWorkspace => is_under(skill.path.0.as_path(), cwd),
AgentSkillSource::CopilotUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".copilot"))),
_ => false,
}
}
/// Codex reads its own folders itself.
fn native_codex(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
match skill.source {
AgentSkillSource::CodexWorkspace => is_under(skill.path.0.as_path(), cwd),
AgentSkillSource::CodexUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".codex"))),
_ => false,
}
}
fn is_under(path: &Path, root: &Path) -> bool {
path.starts_with(root)
}
/// Puts `name` into the farm tree: a directory symlink where they work, a copy otherwise
/// (Windows needs Developer Mode for directory symlinks).
fn link_skill(link: &Path, target: &Path) -> std::io::Result<()> {
let _ = std::fs::remove_file(link);
if let Some(parent) = link.parent() {
std::fs::create_dir_all(parent)?;
}
#[cfg(unix)]
{
std::os::unix::fs::symlink(target, link)
}
#[cfg(windows)]
{
copy_dir_all(target, link)
}
}
#[cfg(windows)]
fn copy_dir_all(from: &Path, to: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(to)?;
for entry in std::fs::read_dir(from)?.flatten() {
let path = entry.path();
let dest = to.join(entry.file_name());
if path.is_dir() {
copy_dir_all(&path, &dest)?;
} else {
std::fs::copy(&path, &dest)?;
}
}
Ok(())
}
/// Removes a task's farm (task deleted or archived); missing is fine.
pub fn remove_farm(store_dir: &Path, task: &str) {
let farm = farm_dir(store_dir, task);
match std::fs::remove_dir_all(&farm) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => tracing::warn!("removing the session skills folder {}: {e}", farm.display()),
}
}
/// Where a task's staged skills live.
pub fn farm_dir(store_dir: &Path, task: &str) -> PathBuf {
store_dir.join("session-skills").join(sanitized(task))
}
/// A task id is a uuid, but never trust it with a path segment.
fn sanitized(id: &str) -> String {
id.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect()
}
/// The `/` menu's skills: the active ones as commands (the agent's own listing wins on a
/// name clash). `Off` ones drop out everywhere; an ACP agent gets no other enforcement, so
/// `slashOnly` ones stay listed — there is nothing to hold them back with.
pub fn menu_commands(offered: Vec<AgentCommand>, states: &[AgentSkillState]) -> Vec<AgentCommand> {
let extra = states
.iter()
.filter(|s| s.mode != AgentSkillMode::Off)
.map(|s| AgentCommand {
name: s.skill.name.clone(),
description: s.skill.description.clone(),
hint: None,
source: AgentCommandSource::Skill,
})
.collect();
merge(offered, extra)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -333,4 +703,231 @@ mod tests {
assert_eq!(f.get("name"), Some("quoted"));
assert_eq!(truncate(&"é".repeat(MAX_DESCRIPTION + 5)).chars().count(), MAX_DESCRIPTION + 1);
}
fn skill(name: &str, source: AgentSkillSource, root: &Path) -> AgentSkill {
AgentSkill {
name: name.into(),
description: format!("{name} does things"),
path: root.join(name).into(),
source,
valid: true,
warnings: Vec::new(),
}
}
fn policy(mode: AgentSkillMode) -> Option<AgentSkillPolicy> {
Some(AgentSkillPolicy { mode })
}
#[test]
fn hub_discovery_scans_every_root_and_collapses_symlinks() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
let repo = tmp.path().join("work/app");
std::fs::create_dir_all(&repo).unwrap();
write(&repo.join(".agents/skills/dep/SKILL.md"), "---\nname: dep\ndescription: From the standard root\n---\n");
write(&repo.join(".openidea/skills/local/SKILL.md"), "---\nname: local\ndescription: OpenIDEA's own\n---\n");
write(&repo.join(".claude/skills/claudey/SKILL.md"), "---\nname: claudey\ndescription: Claude's\n---\n");
write(&repo.join(".github/skills/gh/SKILL.md"), "---\nname: gh\ndescription: Copilot's repo one\n---\n");
write(
&home.join(".agents/skills/shared/SKILL.md"),
"---\nname: shared\ndescription: From npx skills add\n---\n",
);
write(&home.join(".codex/skills/codexy/SKILL.md"), "---\nname: codexy\ndescription: Codex's\n---\n");
write(&home.join(".cursor/skills/cursory/SKILL.md"), "---\nname: cursory\ndescription: Cursor's\n---\n");
// A symlink to `dep` in the home (the same canonical folder): collapsed.
#[cfg(unix)]
{
std::fs::create_dir_all(home.join(".claude/skills")).unwrap();
std::os::unix::fs::symlink(repo.join(".agents/skills/dep"), home.join(".claude/skills/dep")).unwrap();
}
// Hidden folders and files are not skills.
write(&repo.join(".agents/skills/.stash/SKILL.md"), "---\nname: hidden\ndescription: x\n---\n");
write(&repo.join(".agents/skills/loose.txt"), "not a folder");
// Same name from a lower-precedence source: the workspace one wins.
write(&home.join(".cursor/skills/local/SKILL.md"), "---\nname: local\ndescription: from cursor\n---\n");
let found = discover_skills(&repo, Some(&home));
assert_eq!(
found.iter().map(|s| (s.name.as_str(), s.source)).collect::<Vec<_>>(),
[
("dep", AgentSkillSource::Workspace),
("local", AgentSkillSource::Workspace),
("claudey", AgentSkillSource::ClaudeWorkspace),
("gh", AgentSkillSource::GithubWorkspace),
("shared", AgentSkillSource::User),
("codexy", AgentSkillSource::CodexUser),
("cursory", AgentSkillSource::CursorUser),
],
"symlinks collapse and the first of a name wins"
);
assert!(found.iter().all(|s| s.valid), "{:?}", found.iter().flat_map(|s| &s.warnings).collect::<Vec<_>>());
}
#[test]
fn hub_discovery_validates_and_reports() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("app");
std::fs::create_dir_all(&repo).unwrap();
write(&repo.join(".agents/skills/bad-name/SKILL.md"), "---\nname: Bad_Name\ndescription: x\n---\n");
write(&repo.join(".agents/skills/no-desc/SKILL.md"), "---\nname: no-desc\n---\n");
write(
&repo.join(".agents/skills/verbose/SKILL.md"),
&format!("---\nname: verbose\ndescription: {}\n---\n", "x".repeat(MAX_SKILL_DESCRIPTION + 1)),
);
let found = discover_skills(&repo, None);
let by = |n: &str| found.iter().find(|s| s.name == n).unwrap();
assert!(!by("Bad_Name").valid && !by("Bad_Name").warnings.is_empty());
assert!(!by("no-desc").valid && by("no-desc").warnings.len() == 1);
assert!(!by("verbose").valid);
}
#[test]
fn hub_resolution_precedence_and_trust() {
let root = PathBuf::from("/r");
let ws = skill("tdd", AgentSkillSource::Workspace, &root);
let user = skill("lint", AgentSkillSource::User, &root);
let claude = skill("claudey", AgentSkillSource::ClaudeWorkspace, &root);
let session = BTreeMap::from([("tdd".to_owned(), AgentSkillMode::Off)]);
let workspace = BTreeMap::from([
("tdd".to_owned(), policy(AgentSkillMode::SlashOnly).unwrap()),
("lint".to_owned(), policy(AgentSkillMode::Off).unwrap()),
]);
let user_policies = BTreeMap::from([
("lint".to_owned(), policy(AgentSkillMode::SlashOnly).unwrap()),
("claudey".to_owned(), policy(AgentSkillMode::Auto).unwrap()),
]);
// Session > workspace policy > user policy.
let resolved = resolve(vec![ws.clone(), user.clone()], Some(&session), &workspace, &user_policies, true);
assert_eq!((resolved[0].mode, resolved[0].origin), (AgentSkillMode::Off, AgentSkillOrigin::Session));
assert_eq!((resolved[1].mode, resolved[1].origin), (AgentSkillMode::Off, AgentSkillOrigin::Workspace));
// Without a workspace policy the user's applies.
let resolved = resolve(vec![user.clone()], None, &BTreeMap::new(), &user_policies, true);
assert_eq!((resolved[0].mode, resolved[0].origin), (AgentSkillMode::SlashOnly, AgentSkillOrigin::User));
// Untrusted: the workspace's own skills stay off whatever the session chose, its
// policies hold only when they turn a skill off, and user skills keep resolving.
let resolved = resolve(vec![ws, user, claude], Some(&session), &workspace, &user_policies, false);
assert_eq!((resolved[0].mode, resolved[0].origin), (AgentSkillMode::Off, AgentSkillOrigin::Trust));
assert_eq!((resolved[1].mode, resolved[1].origin), (AgentSkillMode::Off, AgentSkillOrigin::Workspace));
assert_eq!((resolved[2].mode, resolved[2].origin), (AgentSkillMode::Off, AgentSkillOrigin::Trust));
}
fn listed(dir: &Path) -> Vec<String> {
let mut names: Vec<String> =
std::fs::read_dir(dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();
names.sort();
names
}
#[test]
fn hub_staging_hands_each_cli_its_own_tree() {
let tmp = tempfile::tempdir().unwrap();
// Discovery reports canonical paths (macOS's temp folder is a symlink).
let root = dunce::canonicalize(tmp.path()).unwrap();
let home = root.join("home");
let repo = root.join("app");
std::fs::create_dir_all(&repo).unwrap();
// The staged folders must exist: Windows copies them (symlinks need Developer Mode).
for path in [
repo.join(".agents/skills/tdd"),
repo.join(".agents/skills/off"),
repo.join(".github/skills/gh"),
home.join(".agents/skills/lint"),
home.join(".agents/skills/muted"),
home.join(".codex/skills/codexy"),
] {
std::fs::create_dir_all(path).unwrap();
}
let states = resolve(
vec![
skill("tdd", AgentSkillSource::Workspace, &repo.join(".agents/skills")),
skill("gh", AgentSkillSource::GithubWorkspace, &repo.join(".github/skills")),
skill("lint", AgentSkillSource::User, &home.join(".agents/skills")),
skill("codexy", AgentSkillSource::CodexUser, &home.join(".codex/skills")),
skill("muted", AgentSkillSource::User, &home.join(".agents/skills")),
skill("off", AgentSkillSource::Workspace, &repo.join(".agents/skills")),
],
None,
&BTreeMap::from([("muted".to_owned(), policy(AgentSkillMode::SlashOnly).unwrap())]),
&BTreeMap::from([("off".to_owned(), policy(AgentSkillMode::Off).unwrap())]),
true,
);
// Local (non-worktree) session: the project's GitHub skills are Copilot's own.
let farm = farm_dir(&root.join("store"), "task-1");
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
assert_eq!(delivery.claude_add_dir.as_deref(), Some(farm.as_path()));
let claude_tree = farm.join(".claude/skills");
let staged = listed(&claude_tree);
assert_eq!(
staged,
["codexy", "gh", "lint", "muted", "tdd"],
"everything but the off one: none is native to Claude here, and slash-only needs the folder"
);
let delivery = stage(&farm, "copilot", &states, &repo, Some(&home)).unwrap();
assert_eq!(delivery.copilot_skill_directories, [farm.join("copilot").to_string_lossy().into_owned()]);
assert_eq!(delivery.copilot_disabled_skills, ["muted", "off"]);
let copilot_staged = listed(&farm.join("copilot"));
assert_eq!(copilot_staged, ["codexy", "lint", "tdd"], "`gh` is native to a local Copilot session");
assert_eq!(
delivery.codex_off,
[("off".to_owned(), repo.join(".agents/skills").join("off").to_string_lossy().into_owned())]
);
// A worktree task: the repo's skills are untracked, so nothing is native any more.
let worktree = root.join("wt");
std::fs::create_dir_all(&worktree).unwrap();
let _ = stage(&farm, "copilot", &states, &worktree, Some(&home)).unwrap();
let copilot_staged = listed(&farm.join("copilot"));
assert!(copilot_staged.contains(&"gh".to_string()));
// Slash-only reaches Claude as `user-invocable-only`, off as `off`.
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
let settings: serde_json::Value = serde_json::from_str(delivery.claude_settings.as_deref().unwrap()).unwrap();
assert_eq!(settings["skillOverrides"]["muted"], "user-invocable-only");
assert_eq!(settings["skillOverrides"]["off"], "off");
// Restaging after a session turned `lint` off drops its link and leaves the skill.
let session = BTreeMap::from([("lint".to_owned(), AgentSkillMode::Off)]);
let restated = resolve(
states.iter().map(|s| s.skill.clone()).collect(),
Some(&session),
&BTreeMap::from([("muted".to_owned(), policy(AgentSkillMode::SlashOnly).unwrap())]),
&BTreeMap::from([("off".to_owned(), policy(AgentSkillMode::Off).unwrap())]),
true,
);
stage(&farm, "claude", &restated, &repo, Some(&home)).unwrap();
assert_eq!(listed(&claude_tree), ["codexy", "gh", "muted", "tdd"]);
assert!(home.join(".agents/skills/lint").is_dir());
assert!(farm.join("copilot").is_dir(), "restaging Claude's tree leaves Copilot's alone");
// An ACP agent gets no farm.
let delivery = stage(&farm, "cursor-acp", &states, &repo, Some(&home)).unwrap();
assert_eq!(delivery, Delivery::default());
// The farm goes away with the task.
remove_farm(&root.join("store"), "task-1");
assert!(!farm.exists());
}
#[test]
fn hub_menu_filters_off_and_keeps_the_agents_own() {
let root = PathBuf::from("/r");
let states = resolve(
vec![skill("tdd", AgentSkillSource::Workspace, &root), skill("lint", AgentSkillSource::User, &root)],
Some(&BTreeMap::from([("lint".to_owned(), AgentSkillMode::Off)])),
&BTreeMap::new(),
&BTreeMap::new(),
true,
);
let menu = menu_commands(vec![cmd("tdd", "from the agent itself")], &states);
assert_eq!(names(&menu), ["tdd"]);
assert_eq!(menu[0].description, "from the agent itself");
assert_eq!(menu[0].source, AgentCommandSource::Skill);
}
}
+125 -239
View File
@@ -1010,7 +1010,6 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
// Another project shares the settings but not the commands.
let mgr_b = manager_at(&b, &models, Arc::new(FakeAgent::default()));
let claude = mgr_b.providers().into_iter().find(|p| p.id == "claude").unwrap();
assert_eq!(claude.config.len(), 2);
assert!(claude.commands.is_empty());
assert!(mgr_b.commands("claude", None).await.unwrap().is_empty());
let mgr_a = manager_at(&a, &models, Arc::new(FakeAgent::default()));
@@ -1197,7 +1196,6 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
}
let providers = mgr.providers();
let claude = providers.iter().find(|p| p.id == "claude").unwrap();
assert_eq!(claude.config.iter().map(|o| o.id.as_str()).collect::<Vec<_>>(), ["model", "mode"]);
assert_eq!(claude.commands.len(), 1);
// A new manager (IDE restart) finds the task and resumes its session without duplicating history.
@@ -1206,7 +1204,6 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
let mgr2 = manager(tmp.path(), agent2.clone());
assert_eq!(mgr2.entries(&task.id, None).unwrap().len(), 5);
assert_eq!(mgr2.task(&task.id).unwrap().state.lock().task.title, "Lexer fix");
assert_eq!(mgr2.providers().iter().find(|p| p.id == "claude").unwrap().config.len(), 2);
mgr2.prompt(&task.id, text("again"), false).await.unwrap();
tokio::time::sleep(Duration::from_millis(50)).await;
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
@@ -2167,52 +2164,6 @@ async fn usage_limits_and_late_settings() {
assert!(agent.calls.lock().iter().any(|c| c == "session/set_config_option \"high\""));
let config = mgr.task(&task.id).unwrap().state.lock().task.config.clone();
assert_eq!(config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("high"));
for _ in 0..100 {
if mgr
.shared
.known
.lock()
.get("claude")
.and_then(|k| k.thought_levels.get("big"))
.and_then(|levels| levels.first())
.and_then(|o| o.current.as_deref())
== Some("high")
{
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(mgr.shared.known.lock()["claude"].thought_levels["big"][0].current.as_deref(), Some("high"));
}
#[tokio::test(flavor = "multi_thread")]
async fn remembered_settings_drop_per_model_choices_for_the_next_task() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
// The effort list depends on the model: what the last session ran means nothing once
// the user picks another model, so provider-wide defaults never include it.
*agent.extra_options.lock() = vec![json!({"id": "effort", "category": "thought_level",
"type": "select", "currentValue": "high",
"options": [{"value": "low", "name": "Low"}, {"value": "high", "name": "High"}]})];
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let provider = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
assert!(provider.config.iter().all(|o| o.id != "effort"), "a per-model option isn't offered stale");
let model = provider.config.iter().find(|o| o.id == "model").unwrap();
assert_eq!(model.current.as_deref(), Some("big"), "the model choice survives");
}
fn effort_options(levels: &[&str], current: &str) -> Vec<Value> {
@@ -2220,51 +2171,6 @@ fn effort_options(levels: &[&str], current: &str) -> Vec<Value> {
"options": levels.iter().map(|v| json!({"value": v, "name": v})).collect::<Vec<_>>()})]
}
#[tokio::test(flavor = "multi_thread")]
async fn thinking_levels_are_remembered_per_provider_and_model() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.model_options.lock() = HashMap::from([
("big".into(), effort_options(&["low", "high"], "high")),
("small".into(), effort_options(&["minimal", "medium"], "minimal")),
("plain".into(), vec![]),
]);
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.set_config(&task.id, "model", "small".into()).await.unwrap();
mgr.set_config(&task.id, "effort", "medium".into()).await.unwrap();
mgr.set_config(&task.id, "model", "plain".into()).await.unwrap();
let p = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
let big = &p.thought_levels["big"][0];
assert_eq!(big.current.as_deref(), Some("high"));
assert_eq!(big.values.iter().map(|v| v.value.as_str()).collect::<Vec<_>>(), ["low", "high"]);
let small = &p.thought_levels["small"][0];
assert_eq!(small.current.as_deref(), Some("medium"));
assert_eq!(small.values.iter().map(|v| v.value.as_str()).collect::<Vec<_>>(), ["minimal", "medium"]);
assert!(p.thought_levels["plain"].is_empty());
assert!(!p.thought_levels.contains_key("unknown"));
assert!(mgr.providers().iter().find(|p| p.id == "codex").unwrap().thought_levels.is_empty());
let saved: HashMap<String, Known> =
serde_json::from_slice(&std::fs::read(&mgr.shared.paths.models_file).unwrap()).unwrap();
assert_eq!(saved["claude"].thought_levels, p.thought_levels);
mgr.shutdown();
let restored = manager(tmp.path(), agent);
assert_eq!(restored.providers().into_iter().find(|p| p.id == "claude").unwrap().thought_levels, p.thought_levels);
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn changing_an_idle_tasks_settings_keeps_its_models_effort_levels() {
// Idle selections use cached model controls or discover them before the next prompt.
@@ -2303,12 +2209,9 @@ async fn changing_an_idle_tasks_settings_keeps_its_models_effort_levels() {
}
restored.set_config(&task.id, "model", "big".into()).await.unwrap();
restored.set_config(&task.id, option, value.into()).await.unwrap();
let p = restored.providers().into_iter().find(|p| p.id == "claude-acp").unwrap();
let big = p.thought_levels.get("big").and_then(|levels| levels.first());
assert_eq!(big.map(|o| o.values.len()), Some(2), "{option}: {:?}", p.thought_levels);
let saved: HashMap<String, Known> =
serde_json::from_slice(&std::fs::read(&restored.shared.paths.models_file).unwrap()).unwrap();
assert_eq!(saved["claude-acp"].thought_levels, p.thought_levels, "{option}");
let levels = restored.shared.paths.catalogs.cached(&restored.shared, "claude-acp").thought_levels;
let big = levels.get("big").and_then(|levels| levels.first());
assert_eq!(big.map(|o| o.values.len()), Some(2), "{option}: {levels:?}");
restored.shutdown();
}
}
@@ -2541,100 +2444,6 @@ async fn upfront_effort_is_validated_after_changing_model_before_the_prompt() {
}
}
#[tokio::test(flavor = "multi_thread")]
async fn unreported_model_switch_does_not_cache_the_previous_models_levels() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.extra_options.lock() = effort_options(&["low", "high"], "high");
let mgr = manager(tmp.path(), agent);
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.set_config(&task.id, "model", "small".into()).await.unwrap();
let p = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
assert!(!p.thought_levels.contains_key("small"));
assert_eq!(p.thought_levels["big"][0].current.as_deref(), Some("high"));
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn cached_effort_is_not_sent_without_real_session_options() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.extra_options.lock() = effort_options(&["low", "high"], "low");
let mgr = manager(tmp.path(), agent.clone());
let new = |config| NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config,
isolation: Isolation::Local,
base: None,
..Default::default()
};
let warm = mgr.create(new(vec![])).await.unwrap();
wait_for(&mgr, &warm.id, AgentStatus::Ready).await;
agent.calls.lock().clear();
agent.empty_config.store(true, Ordering::Release);
let task = mgr
.create(new(vec![
AgentConfigChoice { id: "model".into(), value: "big".into() },
AgentConfigChoice { id: "effort".into(), value: "high".into() },
]))
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert!(!agent.calls.lock().iter().any(|c| c == "session/set_config_option \"high\""));
assert!(
mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "effort"),
"remembered session settings remain visible until the agent refreshes them"
);
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn reported_levels_refresh_even_without_a_model_option() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.extra_options.lock() = effort_options(&["low", "high"], "high");
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
for levels in [effort_options(&["minimal", "medium"], "medium"), vec![]] {
agent.update("s1", json!({"sessionUpdate": "config_option_update", "configOptions": levels}));
let expected = config::parse_options(&json!(levels));
for _ in 0..100 {
if mgr.shared.known.lock()["claude"].thought_levels["big"] == expected {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(mgr.shared.known.lock()["claude"].thought_levels["big"], expected);
}
mgr.shutdown();
}
#[test]
fn retry_updates_become_a_countdown() {
let update =
@@ -3192,49 +3001,6 @@ async fn a_failed_probe_is_retried_instead_of_remembered() {
assert!(!mgr.shared.probes.lock().contains_key("claude"));
}
/// A session report that changes the cached provider config notifies subscribers,
/// so the composer re-lists models without waiting for the next task (#1490).
/// Reports that change nothing stay silent.
#[tokio::test(flavor = "multi_thread")]
async fn remembered_config_changes_notify_subscribers_once() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let events = Arc::new(Mutex::new(Vec::new()));
let sink = events.clone();
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
events.lock().clear();
let reported = config::options_of(&json!({ "configOptions": [
{ "id": "model", "category": "model", "type": "select", "currentValue": "default",
"options": [{ "value": "default" }, { "value": "custom-opus" }] },
] }));
mgr.shared.remember("claude", Some(&reported), None, Some("default"));
assert!(
events.lock().iter().any(|ev| matches!(ev, AgentEvent::Providers)),
"a first report changing the cache notifies subscribers"
);
events.lock().clear();
// The same report again: the cache is unchanged, so subscribers hear nothing.
mgr.shared.remember("claude", Some(&reported), None, Some("default"));
assert!(events.lock().is_empty(), "an unchanged report must stay silent");
// A changed model list notifies again, and providers() serves the new list.
let updated = config::options_of(&json!({ "configOptions": [
{ "id": "model", "category": "model", "type": "select", "currentValue": "default",
"options": [{ "value": "default" }, { "value": "custom-opus" }, { "value": "custom-sonnet" }] },
] }));
mgr.shared.remember("claude", Some(&updated), None, Some("default"));
assert!(
events.lock().iter().any(|ev| matches!(ev, AgentEvent::Providers)),
"a changed model list notifies subscribers"
);
let claude = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
let model = claude.config.iter().find(|o| o.category.as_deref() == Some("model")).unwrap();
let values: Vec<_> = model.values.iter().map(|v| v.value.as_str()).collect();
assert_eq!(values, ["default", "custom-opus", "custom-sonnet"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn idle_agents_stop_and_resume_their_session_on_the_next_message() {
let new = || NewAgentTask {
@@ -3868,6 +3634,123 @@ async fn turn_changed(mgr: &AgentManager, id: &str) -> Vec<(String, ide_vcs::Cha
changes.into_iter().map(|c| (c.rel_path, c.kind, c.added, c.removed)).collect()
}
#[tokio::test(flavor = "multi_thread")]
async fn a_task_lists_what_it_changed_in_a_nested_repository() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let root = base.join("project");
for repo in [root.clone(), root.join("libs/validation")] {
std::fs::create_dir_all(&repo).unwrap();
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
for args in [&["init", "-q", "-b", "main"][..], &["add", "a.txt"], &["commit", "-q", "-m", "init"]] {
let ok = std::process::Command::new("git")
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
.args(args)
.current_dir(&repo)
.status()
.unwrap()
.success();
assert!(ok, "{args:?}");
}
}
let mgr = manager(&base.join("ide"), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
project_root: Some(IpcPath(root.clone())),
prompt: text("Hello"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
one_turn(&mgr, &task.id, None, || {
std::fs::write(root.join("a.txt"), "two\n").unwrap();
std::fs::write(root.join("libs/validation/b.txt"), "new\n").unwrap();
})
.await;
let changed: Vec<(String, Option<IpcPath>)> =
mgr.changes(&task.id).await.unwrap().into_iter().map(|c| (c.rel_path, c.repo)).collect();
assert_eq!(
changed,
[
("a.txt".to_owned(), Some(IpcPath(root.clone()))),
("libs/validation/b.txt".to_owned(), Some(IpcPath(root.join("libs/validation")))),
]
);
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
assert_eq!(std::fs::read_to_string(root.join("a.txt")).unwrap(), "one\n");
assert!(!root.join("libs/validation/b.txt").exists());
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn the_last_turn_of_a_task_spans_nested_repositories() {
use ide_vcs::ChangeKind::{Added, Modified};
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let root = base.join("project");
let nested = root.join("libs/validation");
let git = |repo: &Path, args: &[&str]| {
let ok = std::process::Command::new("git")
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
.args(args)
.current_dir(repo)
.status()
.unwrap()
.success();
assert!(ok, "{args:?}");
};
for repo in [&root, &nested] {
std::fs::create_dir_all(repo).unwrap();
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
git(repo, &["init", "-q", "-b", "main"]);
git(repo, &["add", "a.txt"]);
git(repo, &["commit", "-q", "-m", "init"]);
}
let mgr = manager(&base.join("ide"), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
project_root: Some(IpcPath(root.clone())),
prompt: text("Hello"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
one_turn(&mgr, &task.id, None, || std::fs::write(root.join("a.txt"), "two\n").unwrap()).await;
one_turn(&mgr, &task.id, Some("more"), || {
std::fs::write(nested.join("a.txt"), "two\n").unwrap();
std::fs::write(nested.join("b.txt"), "new\n").unwrap();
// Committed in the nested repository: still the turn's.
std::fs::write(nested.join("c.txt"), "committed\n").unwrap();
git(&nested, &["add", "c.txt"]);
git(&nested, &["commit", "-q", "-m", "c"]);
})
.await;
// Only the second turn's files, from the nested repository, named from the project.
assert_eq!(
turn_changed(&mgr, &task.id).await,
[
("libs/validation/a.txt".into(), Modified, 1, 1),
("libs/validation/b.txt".into(), Added, 1, 0),
("libs/validation/c.txt".into(), Added, 1, 0),
]
);
let repos: Vec<_> = mgr.turn_changes(&task.id).await.unwrap().into_iter().map(|c| c.repo).collect();
assert_eq!(repos, [Some(IpcPath(nested.clone())), Some(IpcPath(nested.clone())), Some(IpcPath(nested.clone()))]);
let then = mgr.base_text(&task.id, nested.join("a.txt"), AgentChangesView::LastTurn).await.unwrap();
assert_eq!(then.as_deref(), Some("one\n"));
mgr.rollback_changes(&task.id, None, AgentChangesView::LastTurn).await.unwrap();
assert_eq!(std::fs::read_to_string(nested.join("a.txt")).unwrap(), "one\n");
assert!(!nested.join("b.txt").exists());
assert_eq!(std::fs::read_to_string(root.join("a.txt")).unwrap(), "two\n", "the first turn's change stays");
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn the_last_turn_lists_and_rolls_back_only_its_own_changes() {
use ide_vcs::ChangeKind::{Added, Deleted, Modified};
@@ -4532,6 +4415,7 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
base: None,
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
idle: false,
skill_overrides: BTreeMap::new(),
})
.await
.unwrap();
@@ -4660,6 +4544,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
base: None,
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
})
.await
.unwrap();
@@ -4685,6 +4570,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
base: None,
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
})
.await
.unwrap();
@@ -4763,10 +4649,10 @@ done
#[test]
fn session_params_name_the_servers_off() {
let mcp = McpForSession { servers: vec![json!({ "name": "docs" })], off: vec!["github".into()] };
let params = session_params("/p", &mcp);
let params = session_params("/p", &mcp, None);
assert_eq!(params["cwd"], "/p");
assert_eq!(params["mcpServers"][0]["name"], "docs");
assert_eq!(params["_meta"]["openidea"]["mcpServersOff"], json!(["github"]));
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
assert!(session_params("/p", &none).get("_meta").is_none());
assert!(session_params("/p", &none, None).get("_meta").is_none());
}
+238 -30
View File
@@ -25,6 +25,98 @@ 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> {
self.repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().as_os_str().len())
}
/// `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()
}
/// `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(cwd: &Path) -> IdeResult<Vec<AgentChange>> {
let Some((base, repos)) = nested_repos(cwd)? else { return Ok(Vec::new()) };
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
let mut out: Vec<AgentChange> = Vec::new();
for repo in &repos {
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 +130,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 +222,7 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
added,
removed,
old_path: f.old_path,
repo: None,
}
})
.collect();
@@ -143,6 +239,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 +256,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 +265,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 +301,7 @@ pub(crate) fn commits(cwd: &Path, base: &str, head: &str) -> IdeResult<Vec<Agent
added,
removed,
old_path: f.old_path,
repo: None,
}
})
.collect();
@@ -266,6 +367,9 @@ impl TaskBase {
pub(crate) fn changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<Vec<AgentChange>> {
let (cwd, start) = match self {
Self::Worktree { cwd, base } => return Ok(without_untouched(changes(cwd, base)?, before)),
Self::Local { cwd, .. } if spans_repos(cwd) => {
return Ok(without_untouched(nested_changes(cwd)?, before));
}
Self::Local { cwd, start } => (cwd, start.as_deref()),
};
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
@@ -324,6 +428,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)?, commits: Vec::new() });
}
let Some(repo) = discover(cwd)? else { return Ok(AgentChanges::default()) };
let head = repo.head()?.1;
let uncommitted = match &head {
@@ -353,6 +460,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,6 +654,18 @@ 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));
}
}
}
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())
}
@@ -587,10 +708,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;
}
@@ -625,7 +752,8 @@ pub(crate) fn restore(
}
None => match rev {
Some(rev) => {
let repo = Repo::discover(cwd)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
let at = change.repo.as_ref().map_or(cwd, |r| r.0.as_path());
let repo = Repo::discover(at)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
repo.file_bytes_at(&change.path.0, Some(rev))?
}
None => None,
@@ -665,6 +793,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>,
@@ -680,8 +811,16 @@ pub(crate) struct TurnStart {
/// The copies `previous` saved of files unchanged since are kept 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;
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart::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();
@@ -702,7 +841,7 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -
}
}
for (rel, stamp) in &before {
let path = repo.root().join(rel);
let path = at.base.join(rel);
if stamp.is_none()
|| saved.contains(rel)
|| !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX)
@@ -715,7 +854,7 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -
saved.insert(rel.clone());
}
}
Ok(TurnStart { head, before, saved, changed: None })
Ok(TurnStart { head, heads, before, saved, changed: None })
}
/// The files that changed in `cwd` since the turn `start` began: in the working tree (as
@@ -724,20 +863,25 @@ 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() {
@@ -746,10 +890,13 @@ fn at_turn_start(repo: &Repo, rel: &str, start: &TurnStart, dir: &Path) -> IdeRe
"{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 +918,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 +937,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 +985,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 +1122,54 @@ mod tests {
assert!(ok, "git {args:?}");
}
#[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).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");
}
#[test]
fn worktree_changes_are_listed_against_the_base() {
let tmp = tempfile::tempdir().unwrap();
+2
View File
@@ -102,6 +102,8 @@ pub enum IdeEvent {
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,
+34
View File
@@ -130,6 +130,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 {
@@ -150,6 +155,7 @@ impl Default for AgentSettings {
new_task_approvals: NewTaskApprovals::Bypass,
defaults: BTreeMap::new(),
mcp_servers: BTreeMap::new(),
skills: BTreeMap::new(),
}
}
}
@@ -205,6 +211,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>
+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 {
+2
View File
@@ -151,6 +151,7 @@ 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,
/// Start with an empty message instead of the last one / the changelist's.
pub clear_initial_message: bool,
pub analyze_code: bool,
@@ -190,6 +191,7 @@ impl Default for CommitSettings {
fn default() -> Self {
Self {
non_modal: true,
include_changes_by_default: true,
clear_initial_message: false,
analyze_code: true,
check_todo: true,
+90
View File
@@ -0,0 +1,90 @@
//! Exception breakpoints on a chosen class. The manager keeps one list; a session given a backend
//! for them at start arms it before `configurationDone`, so a throw in the program's first line
//! stops, and again after each `setExceptionBreakpoints`, which drops them in java-debug.
use crate::session::Session;
use crate::{DebugManager, jvm_memory};
use ide_jvm_inspect::ExceptionClassSpec;
use serde::{Deserialize, Serialize};
use specta::Type;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExceptionClassBreakpoint {
pub id: String,
/// Fully qualified binary name (`com.acme.Outer$Inner`); its subclasses stop too.
pub class_name: String,
pub caught: bool,
pub uncaught: bool,
pub enabled: bool,
/// Patterns (`com.acme.*`, `*Test`, a full name) for the class whose code throws.
pub class_filters: Vec<String>,
pub class_exclusion_filters: Vec<String>,
}
/// What a session's exception class breakpoints can do.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExceptionClassSupport {
/// Whose class names the session takes: `java`.
pub family: String,
pub condition: bool,
pub class_filters: bool,
/// Filters on the class whose code catches the exception.
pub catch_filters: bool,
}
/// The JVM backends stop through java-debug's own exception events, which a condition or a
/// catch-location filter cannot veto.
pub(crate) fn support(s: &Session) -> Option<ExceptionClassSupport> {
s.exception_classes.is_some().then(|| ExceptionClassSupport {
family: "java".into(),
condition: false,
class_filters: true,
catch_filters: false,
})
}
fn spec(b: &ExceptionClassBreakpoint) -> ExceptionClassSpec {
ExceptionClassSpec {
id: b.id.clone(),
class_name: b.class_name.clone(),
caught: b.caught,
uncaught: b.uncaught,
enabled: b.enabled,
class_filters: b.class_filters.clone(),
class_exclusion_filters: b.class_exclusion_filters.clone(),
}
}
impl DebugManager {
/// Arms the manager's list in `s`; the caller holds `s.exception_turn`. `clear`: also when the
/// list is empty, to take down what an earlier list armed.
pub(crate) async fn arm_exception_classes(&self, s: &Session, clear: bool) {
let Some(backend) = &s.exception_classes else { return };
let specs: Vec<_> = self.exception_classes.lock().iter().map(spec).collect();
// Without either, no VM is known yet: `configure` arms once it is.
let target = jvm_memory::vm_target(s);
if (specs.is_empty() && !clear) || (target.pid.is_none() && target.attach_port.is_none()) {
return;
}
match backend.set(&target, &specs).await {
Ok(states) => tracing::debug!("exception class breakpoints of session {}: {states:?}", s.id.0),
Err(e) => tracing::debug!("exception class breakpoints of session {} failed: {e}", s.id.0),
}
}
/// Stores exception breakpoints on chosen classes (kept without a session, armed on start)
/// and arms them in every session that takes them. Also in one still starting: one that has
/// armed already would miss the list, and one that has not answers `vmNotFound` until then.
pub async fn set_exception_class_breakpoints(&self, list: Vec<ExceptionClassBreakpoint>) {
*self.exception_classes.lock() = list;
for s in self.live_sessions() {
if s.exception_classes.is_none() || s.conn.is_closed() {
continue;
}
let _turn = s.exception_turn.lock().await;
self.arm_exception_classes(&s, true).await;
}
}
}
+45 -5
View File
@@ -12,6 +12,7 @@ pub mod adapter;
pub mod attach;
mod cargo;
pub mod connection;
mod exception_classes;
pub mod jdwp;
mod js_cdp;
mod js_debug;
@@ -24,6 +25,7 @@ pub mod unity;
use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
use connection::{Connection, DapError};
pub use exception_classes::{ExceptionClassBreakpoint, ExceptionClassSupport};
use futures::future::join_all;
use ide_core::{DebugSessionId, IdeError, IdeResult, SharedSink};
use ide_language::LanguageRegistry;
@@ -283,6 +285,8 @@ pub struct SessionExceptionFilters {
pub session: DebugSessionId,
pub adapter: String,
pub filters: Vec<ExceptionFilter>,
/// Set when the session takes exception breakpoints on a chosen class.
pub classes: Option<ExceptionClassSupport>,
}
/// What triggered a hot reload; `flutter debug_adapter` takes it as `reason`.
@@ -336,6 +340,7 @@ pub struct DebugManager {
states: Mutex<HashMap<PathBuf, Vec<BreakpointState>>>,
/// Explicit exception filter choices (filter id → enabled); unset filters use the adapter default.
exception_choices: Mutex<BTreeMap<String, bool>>,
exception_classes: Mutex<Vec<ExceptionClassBreakpoint>>,
function_breakpoints: Mutex<Vec<FunctionBreakpoint>>,
data_breakpoints: Mutex<Vec<DataBreakpoint>>,
/// In-flight stops, by session: a second Stop sets `stop_force`, the waiting one kills.
@@ -788,6 +793,7 @@ impl DebugManager {
breakpoints: Mutex::default(),
states: Mutex::default(),
exception_choices: Mutex::default(),
exception_classes: Mutex::default(),
function_breakpoints: Mutex::default(),
data_breakpoints: Mutex::default(),
stopping: Mutex::default(),
@@ -836,6 +842,18 @@ impl DebugManager {
config: LaunchConfig,
owner: SessionOwner,
custom_command: impl FnOnce(&str) -> Option<String>,
) -> IdeResult<DebugSessionId> {
self.start_with_exception_classes(config, owner, custom_command, None).await
}
/// [`start_with`](Self::start_with), the session arming [`Self::set_exception_class_breakpoints`]
/// through `exception_classes`.
pub async fn start_with_exception_classes(
&self,
config: LaunchConfig,
owner: SessionOwner,
custom_command: impl FnOnce(&str) -> Option<String>,
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
) -> IdeResult<DebugSessionId> {
let mut arguments = launch_arguments(&config)?;
// An IDE-side marker (never sent to the adapter): the session is a Flutter
@@ -977,7 +995,19 @@ impl DebugManager {
}
}
let port = debug_server.map(|s| s.port);
self.start_session(id, owner, config.name, config.adapter, None, config.request, arguments, spec, port).await
self.start_session(
id,
owner,
config.name,
config.adapter,
None,
config.request,
arguments,
spec,
port,
exception_classes,
)
.await
}
/// `startDebugging` reverse request: a child session on the same adapter.
@@ -1002,6 +1032,7 @@ impl DebugManager {
configuration,
parent.spec.clone(),
parent.port,
None,
)
.await
.map(|_| ())
@@ -1019,6 +1050,7 @@ impl DebugManager {
arguments: Value,
spec: AdapterSpec,
reuse_port: Option<u16>,
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
) -> IdeResult<DebugSessionId> {
if request != "launch" && request != "attach" {
return Err(IdeError::invalid(format!("request must be `launch` or `attach`, got `{request}`")));
@@ -1033,8 +1065,9 @@ impl DebugManager {
let rdbg_pid = (adapter_name == "rdbg" && request == "launch")
.then(|| io.child.as_ref().and_then(tokio::process::Child::id))
.flatten();
let session =
Arc::new(Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child));
let mut session = Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child);
session.exception_classes = exception_classes;
let session = Arc::new(session);
if let Some(launch_type) = arguments.get("type").and_then(Value::as_str) {
let _ = session.launch_type.set(launch_type.to_owned());
}
@@ -1259,8 +1292,12 @@ impl DebugManager {
tracing::debug!("setDataBreakpoints failed: {e}");
}
let has_filters = s.caps.lock().get("exceptionBreakpointFilters").and_then(Value::as_array).is_some();
if has_filters {
let _ = self.send_exception_breakpoints(s).await;
{
let _turn = s.exception_turn.lock().await;
if has_filters {
let _ = self.send_exception_breakpoints(s).await;
}
self.arm_exception_classes(s, false).await;
}
if s.supports("supportsConfigurationDoneRequest") {
if s.adapter == kotlin::ADAPTER {
@@ -1481,6 +1518,7 @@ impl DebugManager {
session: s.id,
adapter: s.adapter.clone(),
filters: exception_filters_from(&s.caps.lock()),
classes: exception_classes::support(s),
})
.collect()
}
@@ -1496,9 +1534,11 @@ impl DebugManager {
if exception_filters_from(&s.caps.lock()).is_empty() {
continue;
}
let _turn = s.exception_turn.lock().await;
if let Err(e) = self.send_exception_breakpoints(&s).await {
tracing::debug!("setExceptionBreakpoints on session {} failed: {e}", s.id.0);
}
self.arm_exception_classes(&s, false).await;
}
Ok(())
}
+7
View File
@@ -118,6 +118,11 @@ pub(crate) struct Session {
pub kotlin_mirror: Mutex<Option<crate::kotlin::SourceMirror>>,
pub jvm_memory: tokio::sync::Mutex<crate::JvmMemoryState>,
pub stream_tracer: parking_lot::Mutex<Option<Arc<dyn ide_jvm_inspect::StreamTracer>>>,
/// Given at start: the class breakpoints must be armed before `configurationDone`.
pub(crate) exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
/// Held from `setExceptionBreakpoints`, which drops the class breakpoints, until they are
/// armed again, so that the last list armed is the manager's.
pub(crate) exception_turn: tokio::sync::Mutex<()>,
pub(crate) stream_trace: parking_lot::Mutex<Option<crate::stream_trace::ActiveTrace>>,
/// The last trace that finished, until the stop its records were read in ends.
pub(crate) stream_trace_done: parking_lot::Mutex<Option<crate::stream_trace::DoneTrace>>,
@@ -286,6 +291,8 @@ impl Session {
kotlin_mirror: Mutex::new(None),
jvm_memory: tokio::sync::Mutex::default(),
stream_tracer: parking_lot::Mutex::new(None),
exception_classes: None,
exception_turn: tokio::sync::Mutex::default(),
stream_trace: parking_lot::Mutex::new(None),
stream_trace_done: parking_lot::Mutex::new(None),
quirks: kotlin_lsp::Quirks::default(),
+1
View File
@@ -1,5 +1,6 @@
//! Protocol flow against an in-memory fake adapter.
mod exception_classes;
mod jvm_inspect;
mod stream_trace;
@@ -0,0 +1,154 @@
//! Exception breakpoints on a chosen class, armed through a session's backend.
use super::*;
use ide_jvm_inspect::{ExceptionArmState, ExceptionClassBreakpoints, ExceptionClassSpec, InspectFuture, VmTarget};
/// The target, the list, and the DAP requests sent before it.
type ArmCall = (VmTarget, Vec<ExceptionClassSpec>, Vec<String>);
/// Records each list it is given with the DAP requests sent before it.
struct FakeArmer {
log: Log,
calls: Mutex<Vec<ArmCall>>,
}
impl FakeArmer {
fn new(h: &Harness) -> Arc<Self> {
Arc::new(Self { log: h.log.clone(), calls: Mutex::default() })
}
fn lists(&self) -> Vec<Vec<String>> {
self.calls.lock().iter().map(|(_, specs, _)| specs.iter().map(|s| s.class_name.clone()).collect()).collect()
}
/// The DAP requests sent before each call.
fn before(&self) -> Vec<Vec<String>> {
self.calls.lock().iter().map(|(_, _, sent)| sent.clone()).collect()
}
}
impl ExceptionClassBreakpoints for FakeArmer {
fn set<'a>(
&'a self,
target: &'a VmTarget,
breakpoints: &'a [ExceptionClassSpec],
) -> InspectFuture<'a, Vec<(String, ExceptionArmState)>> {
let sent = self
.log
.lock()
.iter()
.filter(|m| m["type"] == "request")
.map(|m| m["command"].as_str().unwrap().to_owned())
.collect();
self.calls.lock().push((target.clone(), breakpoints.to_vec(), sent));
let states = breakpoints.iter().map(|b| (b.id.clone(), ExceptionArmState::Armed)).collect();
Box::pin(async move { Ok(states) })
}
}
fn class_bp(id: &str, class_name: &str) -> ExceptionClassBreakpoint {
ExceptionClassBreakpoint {
id: id.into(),
class_name: class_name.into(),
caught: true,
uncaught: true,
enabled: true,
class_filters: vec![],
class_exclusion_filters: vec![],
}
}
/// A java-debug attach to a JVM on another machine: the target is known from the request alone.
fn attach() -> LaunchConfig {
LaunchConfig {
extra_json: Some(json!({"hostName": "10.0.0.5", "port": 5005}).to_string()),
..java_config("attach")
}
}
async fn start(h: &Harness, config: LaunchConfig, armer: &Arc<FakeArmer>) -> DebugSessionId {
let backend: Arc<dyn ExceptionClassBreakpoints> = armer.clone();
h.manager.start_with_exception_classes(config, h.owner.clone(), |_| None, Some(backend)).await.unwrap()
}
#[tokio::test]
async fn armed_after_the_exception_filters_and_before_configuration_done() {
let h = harness(Script::default());
let armer = FakeArmer::new(&h);
let filtered = ExceptionClassBreakpoint {
caught: false,
enabled: false,
class_filters: vec!["com.acme.*".into()],
class_exclusion_filters: vec!["*Test".into()],
..class_bp("b", "com.acme.Boom")
};
h.manager.set_exception_class_breakpoints(vec![class_bp("a", "java.lang.IllegalStateException"), filtered]).await;
start(&h, attach(), &armer).await;
assert_eq!(armer.before(), [["initialize", "attach", "setExceptionBreakpoints"]]);
let (target, specs, _) = armer.calls.lock()[0].clone();
assert_eq!((target.pid, target.attach_host.as_deref(), target.attach_port), (None, Some("10.0.0.5"), Some(5005)));
assert_eq!(
specs[1],
ExceptionClassSpec {
id: "b".into(),
class_name: "com.acme.Boom".into(),
caught: false,
uncaught: true,
enabled: false,
class_filters: vec!["com.acme.*".into()],
class_exclusion_filters: vec!["*Test".into()],
}
);
assert!(h.commands().contains(&"configurationDone".to_owned()));
}
#[tokio::test]
async fn armed_again_after_every_set_exception_breakpoints() {
let h = harness(Script::default());
let armer = FakeArmer::new(&h);
h.manager.set_exception_class_breakpoints(vec![class_bp("a", "com.acme.Boom")]).await;
start(&h, attach(), &armer).await;
h.manager.set_exception_breakpoints(BTreeMap::from([("raised".into(), true)])).await.unwrap();
assert_eq!(armer.lists(), [["com.acme.Boom"], ["com.acme.Boom"]]);
let last = armer.before().pop().unwrap();
assert_eq!(last.iter().filter(|c| *c == "setExceptionBreakpoints").count(), 2, "{last:?}");
}
#[tokio::test]
async fn a_new_list_reaches_the_sessions_that_take_it() {
let h = harness(Script::default());
let armer = FakeArmer::new(&h);
start(&h, attach(), &armer).await;
let other = h.start(attach()).await.unwrap();
assert!(armer.lists().is_empty(), "nothing to arm at start");
h.manager.set_exception_class_breakpoints(vec![class_bp("a", "com.acme.Boom")]).await;
h.manager.set_exception_class_breakpoints(vec![]).await;
assert_eq!(armer.lists(), [vec!["com.acme.Boom".to_owned()], vec![]], "an empty list takes them down");
let filters = h.manager.exception_filters(None);
let support = |id| filters.iter().find(|f| f.session == id).unwrap().classes.clone();
assert_eq!(support(other), None);
let java = filters.iter().find(|f| f.session != other).unwrap().session;
assert_eq!(
support(java),
Some(ExceptionClassSupport {
family: "java".into(),
condition: false,
class_filters: true,
catch_filters: false
})
);
}
#[tokio::test]
async fn nothing_is_sent_before_the_jvm_is_known() {
let h = harness(Script::default());
let armer = FakeArmer::new(&h);
h.manager.set_exception_class_breakpoints(vec![class_bp("a", "com.acme.Boom")]).await;
// The fake adapter sends no `process` event before `configurationDone`: no pid to name.
start(&h, java_config("launch"), &armer).await;
assert!(armer.lists().is_empty());
}
+2 -2
View File
@@ -72,7 +72,7 @@ pub struct Host {
/// Projects the MCP server serves without a window.
pub mcp_background: mcp::BackgroundProjects,
pub(crate) agent_catalogs: Arc<ide_agent::AgentCatalogs>,
pub trust: trust::TrustStore,
pub trust: std::sync::Arc<trust::TrustStore>,
pub(crate) mcp_approvals: Arc<trust::McpServerApprovals>,
pub config_dir: PathBuf,
/// Persistent user state, including credentials and recovery history.
@@ -169,7 +169,7 @@ impl Host {
mcp_agent_runs: Default::default(),
mcp_background: Default::default(),
agent_catalogs: Arc::default(),
trust: trust::TrustStore::load(&config_dir, &data_dir),
trust: std::sync::Arc::new(trust::TrustStore::load(&config_dir, &data_dir)),
mcp_approvals: Arc::new(trust::McpServerApprovals::load(&data_dir)),
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
proxy_session_password: Mutex::default(),
+7 -3
View File
@@ -668,8 +668,8 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
if hits.len() > limit {
break;
}
// Find in Files keeps a window of very long lines and drops the matches outside it:
// such lines are matched again in the file's whole text.
// Find in Files reports a very long line in windows cut around its matches: such lines
// are matched again in the file's whole text, so a match keeps its real end.
let long = |m: &ide_search::LineMatch| m.text_offset > 0 || m.text.encode_utf16().count() + 1 >= LINE_WINDOW;
let whole = if file.matches.iter().any(long) {
crate::ops::fs::fs_read_text(&host, call.window(), file.path.0.clone())
@@ -679,11 +679,15 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
} else {
None
};
// One window per far-apart match: a line is expanded once.
let mut expanded = std::collections::HashSet::new();
for m in &file.matches {
if let Some((ranges, text)) = &whole
&& long(m)
{
hits.extend(line_hits(path, text, ranges, m.line));
if expanded.insert(m.line) {
hits.extend(line_hits(path, text, ranges, m.line));
}
continue;
}
let line_end = m.text_offset + m.text.encode_utf16().count() as u32;
+148 -2
View File
@@ -7,8 +7,9 @@ use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe,
AgentPrompt, AgentProvider, AgentQueued, AgentTask, CustomAgentInput, ExternalSession, McpExternalSource,
McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask,
AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
CustomAgentInput, ExternalSession, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer,
McpServerInput, McpTransport, NewAgentTask, SkillsPolicy,
};
use ide_command::command;
use ide_core::error::ErrorKind;
@@ -1028,6 +1029,148 @@ pub fn agent_set_mcp_overrides(
host.project(window)?.agents.set_mcp_overrides(&task, overrides)
}
/// Updates per-session skill modes on `task`.
#[command(trust = always)]
pub fn agent_set_skill_overrides(
host: &Host,
window: &str,
task: String,
overrides: std::collections::BTreeMap<String, AgentSkillMode>,
) -> IdeResult<AgentTask> {
host.project(window)?.agents.set_skill_overrides(&task, overrides)
}
/// Every skill discovered in the project and the user's folders, with the mode a session
/// of this project runs it with (without any session's own overrides).
#[command(trust = always)]
pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult<Vec<AgentSkillState>> {
let project = host.project(window)?;
let root = project.root.clone();
let (policy, home) = (skills_policy(&project), dirs::home_dir());
tokio::task::spawn_blocking(move || {
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills(&root, home.as_deref()),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Sets how `name` may run in `scope`, in the settings file of that scope, and returns the
/// updated list. `SKILL.md` files are never touched; the default `auto` removes the entry.
#[command(trust = always)]
pub fn agent_skills_set_mode(
host: &Host,
window: &str,
name: String,
scope: McpScope,
mode: AgentSkillMode,
) -> IdeResult<Vec<AgentSkillState>> {
let name = name.trim().to_owned();
if name.is_empty() {
return Err(IdeError::invalid("a skill needs a name"));
}
let project = host.project(window).ok().filter(|p| !p.light);
let (mut user, mut workspace) = skills_maps(host, project.as_ref());
match scope {
McpScope::User => {
let changed = if mode == AgentSkillMode::Auto {
user.remove(&name).is_some()
} else {
user.insert(name, AgentSkillPolicy { mode }).map(|p| p.mode) != Some(mode)
};
if changed {
persist_skills_map(host, None, scope, &user)?;
}
}
McpScope::Workspace => {
let map =
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace skills"))?;
let changed = if mode == AgentSkillMode::Auto {
map.remove(&name).is_some()
} else {
map.insert(name, AgentSkillPolicy { mode }).map(|p| p.mode) != Some(mode)
};
if changed {
let map = map.clone();
persist_skills_map(host, project.as_ref(), scope, &map)?;
}
}
}
match project {
Some(project) => {
let root = project.root.clone();
let policy = skills_policy(&project);
let home = dirs::home_dir();
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills(&root, home.as_deref()),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
}
None => Ok(Vec::new()),
}
}
/// The user's and the workspace's skill policies (`[agents.skills.<name>]`).
fn skills_maps(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
) -> (std::collections::BTreeMap<String, AgentSkillPolicy>, Option<std::collections::BTreeMap<String, AgentSkillPolicy>>)
{
let user = host.global_settings.effective().agents.skills.clone();
let workspace =
project.map(|p| p.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.skills.clone());
(user, workspace)
}
/// Saves `map` into its scope's settings and tells the windows.
fn persist_skills_map(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
scope: McpScope,
map: &std::collections::BTreeMap<String, AgentSkillPolicy>,
) -> IdeResult<()> {
let value = if map.is_empty() {
serde_json::Value::Null
} else {
serde_json::to_value(map).map_err(|e| IdeError::invalid(e.to_string()))?
};
let event = IdeEvent::SettingsChanged { key: "agents.skills".into() };
match scope {
McpScope::User => {
host.global_settings.set(ide_workspace::settings::SettingsScope::Global, "agents.skills", value)?;
for p in host.projects() {
p.settings.reload();
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
}
McpScope::Workspace => {
let p = project.ok_or_else(|| IdeError::invalid("Open a project to configure workspace skills"))?;
p.settings.set(ide_workspace::settings::SettingsScope::Project, "agents.skills", value)?;
p.agents.notify_mcp_servers_changed();
p.sink.emit(event);
}
}
Ok(())
}
/// The skill policies a session of `project` resolves against.
fn skills_policy(project: &crate::Project) -> SkillsPolicy {
SkillsPolicy {
user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.skills.clone(),
workspace: project.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.skills.clone(),
workspace_trusted: project.trusted.load(std::sync::atomic::Ordering::Acquire),
}
}
fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::Path>) -> IdeResult<std::path::PathBuf> {
let Some(requested) = requested else {
return Ok(root.to_path_buf());
@@ -1183,6 +1326,9 @@ ide_command::domain!(
agent_set_config,
agent_set_env,
agent_set_mcp_overrides,
agent_set_skill_overrides,
agent_skills_list,
agent_skills_set_mode,
agent_stop_background,
agent_subscribe,
agent_unarchive,
+141 -22
View File
@@ -2,6 +2,7 @@
//! remote server ([`crate::rpc`]). `db_export_file` stays in the desktop
//! shell: its path comes from a local save dialog, so the export must land
//! on the user's machine, not the side the project runs on.
use super::Channel;
use crate::Host;
use ide_command::command;
use ide_core::{IdeError, IdeResult, IpcPath, RequestId};
@@ -24,6 +25,14 @@ pub struct StatementOutcome {
pub error: Option<String>,
}
#[derive(Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum ExecutionEvent {
Started { index: u32 },
Completed { index: u32, outcome: StatementOutcome },
Done { error: Option<IdeError> },
}
#[command(trust = trusted)]
pub fn db_approve_jdbc_source(host: &Host, window: &str, source: DataSource) -> IdeResult<()> {
host.project(window)?.db.approve_jdbc_source(&source)
@@ -357,36 +366,79 @@ pub async fn db_execute(
max_rows: u32,
schema: Option<String>,
) -> IdeResult<Vec<StatementOutcome>> {
// Runs `statements` in order on data source `id`, stopping at the first
// error. Each result reads past its first `skip` rows (a later page) and keeps
// `max_rows`. `schema` is the console's active context: the connection running
// each statement is put in it first. Cancel with `cancel_request(request)`.
let mut outcomes = Vec::new();
execute_statements(host, window, request, &id, statements, skip, max_rows, schema.as_deref(), |event| {
if let ExecutionEvent::Completed { outcome, .. } = event {
outcomes.push(outcome);
}
Ok(())
})
.await?;
Ok(outcomes)
}
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
pub async fn db_execute_stream(
host: &Host,
window: &str,
request: RequestId,
id: String,
statements: Vec<SqlStatement>,
max_rows: u32,
schema: Option<String>,
on_progress: Channel<ExecutionEvent>,
) -> IdeResult<()> {
let result = execute_statements(host, window, request, &id, statements, 0, max_rows, schema.as_deref(), |event| {
on_progress.send(event)
})
.await;
// The invocation reply can reach the viewer before a large result frame.
on_progress.send(ExecutionEvent::Done { error: result.err() })
}
/// Runs in order on one request and stops on cancellation or the first error.
#[allow(clippy::too_many_arguments)]
async fn execute_statements(
host: &Host,
window: &str,
request: RequestId,
id: &str,
statements: Vec<SqlStatement>,
skip: u32,
max_rows: u32,
schema: Option<&str>,
mut emit: impl FnMut(ExecutionEvent) -> IdeResult<()>,
) -> IdeResult<()> {
let db = host.project(window)?.db.clone();
let cancel = host.begin_request(request);
let mut out = Vec::new();
for statement in statements {
match db
.execute_from(&id, &statement.text, skip as usize, max_rows.max(1) as usize, &cancel, schema.as_deref())
.await
{
Ok(result) => out.push(StatementOutcome { statement, result: Some(result), error: None }),
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => {
host.end_request(request);
return Err(e);
let result = async {
for (index, statement) in statements.into_iter().enumerate() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
Err(e) if e.kind == ide_core::error::ErrorKind::PermissionDenied && out.is_empty() => {
// Not connected for lack of a password: the UI asks and retries.
host.end_request(request);
return Err(e);
}
Err(e) => {
out.push(StatementOutcome { statement, result: None, error: Some(e.message) });
emit(ExecutionEvent::Started { index: index as u32 })?;
let outcome = match db
.execute_from(id, &statement.text, skip as usize, max_rows.max(1) as usize, &cancel, schema)
.await
{
Ok(result) => StatementOutcome { statement, result: Some(result), error: None },
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => return Err(e),
// The UI may retry a login failure only before any statement has completed.
Err(e) if e.kind == ide_core::error::ErrorKind::PermissionDenied && index == 0 => return Err(e),
Err(e) => StatementOutcome { statement, result: None, error: Some(e.message) },
};
let failed = outcome.error.is_some();
emit(ExecutionEvent::Completed { index: index as u32, outcome })?;
if failed {
break;
}
}
Ok(())
}
.await;
host.end_request(request);
Ok(out)
result
}
#[allow(clippy::too_many_arguments)]
@@ -539,6 +591,7 @@ ide_command::domain!(
db_disconnect,
db_drop_database,
db_execute,
db_execute_stream,
db_explain,
db_finish_transaction,
db_history,
@@ -567,3 +620,69 @@ ide_command::domain!(
db_test_tunnel,
db_trust_ssh_host,
);
#[cfg(test)]
mod tests {
use super::*;
use crate::HostConfig;
use ide_db::DbDriver;
use std::sync::Arc;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_reporting_error_stops_the_batch_and_releases_the_request() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir(&root).unwrap();
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let window = "main";
host.open_project(window, &root).unwrap();
host.set_project_trust(&root, true, false).await.unwrap();
let id = "test";
let file = root.join("test.sqlite");
std::fs::File::create(&file).unwrap();
db_save_sources(
&host,
window,
vec![DataSource { id: id.into(), name: id.into(), file: Some(file.into()), ..Default::default() }],
)
.await
.unwrap();
let statements =
ide_db::split::split("CREATE TABLE items (n INTEGER); INSERT INTO items VALUES (1);", DbDriver::Sqlite);
let request = RequestId(1);
let error = execute_statements(&host, window, request, id, statements, 0, 10, None, |event| match event {
ExecutionEvent::Started { index: 0 } => Ok(()),
ExecutionEvent::Completed { index: 0, outcome } => {
assert!(outcome.error.is_none(), "{:?}", outcome.error);
Err(IdeError::internal("cannot report result"))
}
_ => panic!("the failed callback must stop execution"),
})
.await
.unwrap_err();
assert_eq!(error.message, "cannot report result");
// After cleanup, cancel is remembered for the next request with this id.
host.cancel_request(request);
assert!(host.begin_request(request).is_cancelled());
let query = ide_db::split::split(
"SELECT 99 AS n UNION ALL SELECT count(*) FROM items ORDER BY n DESC",
DbDriver::Sqlite,
);
let outcomes = db_execute(&host, window, RequestId(2), id.into(), query, 1, 10, None).await.unwrap();
assert_eq!(outcomes[0].result.as_ref().unwrap().rows, vec![vec![Some("0".into())]]);
}
}
+25 -1
View File
@@ -129,7 +129,8 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
};
host.require_trust(window)?;
let server_port = debug_server_port(&config);
let result = host.debugger.start_with(config, owner, custom).await;
let exception_classes = server_port.and_then(|port| exception_class_backend(host, window, port));
let result = host.debugger.start_with_exception_classes(config, owner, custom, exception_classes).await;
flush_output();
if let Ok(id) = &result {
let sink = host.window_sink(label);
@@ -208,6 +209,18 @@ fn attach_jvm_inspector(host: &Host, window: &str, session: DebugSessionId, port
}
}
/// Given before the session starts, unlike the inspector: the breakpoints are armed before
/// `configurationDone`, so a throw in `main`'s first line stops.
fn exception_class_backend(
host: &Host,
window: &str,
port: u16,
) -> Option<std::sync::Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>> {
let project = host.project(window).ok()?;
let module = project.lsp.java_debug_server_module(port)?;
Some(std::sync::Arc::new(ide_lsp::JdtExceptionBreakpoints::new(project.lsp.clone(), module)))
}
/// A JVM the debugger starts itself: an Application or Spring Boot configuration, launched by
/// java-debug, java-analyzer or the Kotlin debugger (JAR Application debugs through a run with a
/// JDWP agent).
@@ -453,6 +466,16 @@ pub async fn debug_set_exception_breakpoints(
host.debugger.set_exception_breakpoints(choices).await
}
/// Exception breakpoints on chosen classes (all sessions that take them, and later ones).
#[command(trust = trusted)]
pub async fn debug_set_exception_class_breakpoints(
host: &Host,
breakpoints: Vec<ExceptionClassBreakpoint>,
) -> IdeResult<()> {
host.debugger.set_exception_class_breakpoints(breakpoints).await;
Ok(())
}
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
pub async fn debug_set_variable(
@@ -849,6 +872,7 @@ ide_command::domain!(
debug_set_breakpoints,
debug_set_data_breakpoints,
debug_set_exception_breakpoints,
debug_set_exception_class_breakpoints,
debug_set_function_breakpoints,
debug_set_variable,
debug_stack_trace,
+6 -3
View File
@@ -85,7 +85,7 @@ pub async fn doc_set_line_ending(host: &Host, window: &str, doc: DocId, line_end
}
/// Structure view: LSP document symbols when available (with tree-sitter
/// visibility), tree-sitter otherwise.
/// visibility and type-alias kinds), tree-sitter otherwise.
/// Tree-sitter answers come from the per-document tree cache (incremental
/// re-parse); large documents get no syntax structure.
#[command(trust = always)]
@@ -113,10 +113,13 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
};
let syntax = || project.syntax.outline(doc, &snap.language, snap.version, &snap.text);
Ok(match lsp {
// Server symbols carry no visibility; borrow it from the syntax tree.
// Server symbols carry no visibility, nor a kind for type aliases; borrow them from
// the syntax tree.
Some(mut items) => {
if !snap.large {
ide_language::merge_visibility(&mut items, &syntax());
let syntax = syntax();
ide_language::merge_visibility(&mut items, &syntax);
ide_language::merge_kinds(&mut items, &syntax);
}
items
}
+65 -9
View File
@@ -301,19 +301,30 @@ fn finish_launch(
// The module/project JDK, else the JDK the Java language server builds the module with, else one
// matching its Java version.
let project_jdk = ide_sdk::apply::module_jdk(root, module, settings);
let from_server = info.java_home.as_deref().map(ide_sdk::java::java_executable).filter(|p| p.is_file());
let java = project_jdk.map(|j| ide_sdk::java::java_executable(&j.home)).or(from_server).or_else(|| {
// The build model's level includes what the module inherits from its parent POMs.
let release = model
// The build model's level includes what the module inherits from its parent POMs.
let release = || {
model
.maven
.as_ref()
.and_then(|m| m.projects.iter().find(|p| root.join(&p.dir) == module))
.and_then(|p| p.java_version)
.or_else(|| ide_sdk::java::project_java_version(module));
let jdks = ide_sdk::java::installed_jdks();
info.hints.extend(ide_sdk::java::missing_jdk_message(&jdks, release));
ide_sdk::java::pick_jdk(&jdks, release).map(|j| ide_sdk::java::java_executable(&j.home))
});
.or_else(|| ide_sdk::java::project_java_version(module))
};
let java = match project_jdk {
Some(j) => Some(ide_sdk::java::java_executable(&j.home)),
None => {
let release = release();
let server = info.java_home.as_deref().and_then(|home| server_java(home, release));
match server {
Some(java) => Some(java),
None => {
let jdks = ide_sdk::java::installed_jdks();
info.hints.extend(ide_sdk::java::missing_jdk_message(&jdks, release));
ide_sdk::java::pick_jdk(&jdks, release).map(|j| ide_sdk::java::java_executable(&j.home))
}
}
}
};
info.java_exec = Some(java.map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| "java".to_owned()));
let exec = PathBuf::from(info.java_exec.as_deref().unwrap_or("java"));
let shorten = ide_run::java_cmdline::shortening_for(&exec, &info.class_paths, &info.module_paths, cfg!(windows));
@@ -328,6 +339,19 @@ fn finish_launch(
}
}
/// The `java` of the JDK a Java language server reports, when it can run classes compiled for
/// `release`: that JDK is the one the server runs on or defaults to, not necessarily one the
/// module's bytecode loads on. A home whose version is unknown is used only when `release` is too.
fn server_java(home: &Path, release: Option<u32>) -> Option<PathBuf> {
match ide_sdk::java::jdk_at(home) {
Some(jdk) if release.is_none_or(|release| jdk.major >= release) => {
Some(ide_sdk::java::java_executable(&jdk.home))
}
Some(_) => None,
None => Some(ide_sdk::java::java_executable(home)).filter(|java| release.is_none() && java.is_file()),
}
}
/// With Settings › Maven › Delegate IDE build/run actions to Maven, javac's verdict replaces
/// JDT's. Classes JDT wrote for sources with errors look up to date to Maven's incremental
/// compiler, so a launch JDT reports errors for recompiles everything.
@@ -557,6 +581,38 @@ fn drop_processor_recreate_errors(info: &mut JavaLaunchInfo) {
mod tests {
use super::*;
fn fake_jdk(dir: &Path, version: Option<&str>) -> PathBuf {
let bin = dir.join("bin");
std::fs::create_dir_all(&bin).unwrap();
std::fs::write(bin.join(if cfg!(windows) { "java.exe" } else { "java" }), "").unwrap();
if let Some(version) = version {
std::fs::write(dir.join("release"), format!("JAVA_VERSION=\"{version}\"\n")).unwrap();
}
dir.to_path_buf()
}
#[test]
fn a_server_jdk_older_than_the_module_release_is_not_used() {
let tmp = tempfile::tempdir().unwrap();
let jdk17 = fake_jdk(&tmp.path().join("17"), Some("17.0.12"));
let jdk21 = fake_jdk(&tmp.path().join("21"), Some("21.0.4"));
let unknown = fake_jdk(&tmp.path().join("unknown"), None);
// (server JDK, module release, used?)
let cases = [
(&jdk17, Some(21), false),
(&jdk17, Some(17), true),
(&jdk17, Some(11), true),
(&jdk17, None, true),
(&jdk21, Some(21), true),
(&unknown, None, true),
(&unknown, Some(21), false),
];
for (home, release, used) in cases {
assert_eq!(server_java(home, release).is_some(), used, "{} for release {release:?}", home.display());
}
assert!(server_java(&tmp.path().join("missing"), None).is_none());
}
#[test]
fn recognises_a_processor_recreating_its_output() {
assert!(processor_recreated_a_file(
+6
View File
@@ -335,6 +335,12 @@ pub fn set_settings(
project.agents.notify_mcp_servers_changed();
}
}
// A skill policy change re-resolves the modes; an idle session restarts to pick them up.
if key == "agents" || key == "agents.skills" || key.starts_with("agents.skills.") {
for project in affected() {
project.agents.notify_mcp_servers_changed();
}
}
// A new interpreter / toolchain / server executable restarts the language servers it affects.
// So do inspections that are compiler options (`ide-sdk` `configure_java_compiler`).
let code_style = key == "editor"
+12 -4
View File
@@ -22,6 +22,17 @@ pub fn literal_range(l: ide_language::Literal) -> ide_search::LiteralRange {
ide_search::LiteralRange { start: l.start, end: l.end, kind }
}
/// Comments and string literals of `text`, for the search context of Find and Replace in Files.
pub(crate) fn literals_of(
project: &crate::project::Project,
syntax: &ide_language::Syntax,
path: &Path,
text: &str,
) -> Option<Vec<ide_search::LiteralRange>> {
let language = project.languages.detect(path, text.lines().next());
Some(syntax.literals(&language, text)?.into_iter().map(literal_range).collect())
}
/// Find in Files. Results stream through `on_event`; ends with `Done`.
/// Cancel with `cancel_request(request)`.
#[command(trust = always)]
@@ -98,10 +109,7 @@ pub(crate) fn search_project(
Some(ProjectFileSet::Test) => roots.is_test(rel),
_ => true,
};
let literals = |path: &Path, text: &str| {
let language = project.languages.detect(path, text.lines().next());
Some(syntax.literals(&language, text)?.into_iter().map(literal_range).collect())
};
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
let defaults = project.documents.file_defaults();
let decode = |path: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, defaults.fallback_for(path));
let mut total = SearchSummary::default();
+13 -3
View File
@@ -75,9 +75,19 @@ pub async fn replace_in_files(
let summary = tokio::task::spawn_blocking(move || {
let targets = if all_in_scope { scope_targets(&project, &syntax, &query, targets, &cancel)? } else { targets };
let host = DocumentsHost(&project.documents);
ide_search::replace_files(&host, &query, &replacement, preserve_case, &targets, &cancel, &|e| {
let _ = events.send(e);
})
let literals = |path: &Path, text: &str| super::literals_of(&project, &syntax, path, text);
ide_search::replace_files_in_context(
&host,
&query,
&replacement,
preserve_case,
&targets,
Some(&literals),
&cancel,
&|e| {
let _ = events.send(e);
},
)
})
.await
.map_err(|e| ide_core::IdeError::internal(e.to_string()));
+17
View File
@@ -3059,6 +3059,10 @@ impl HostApi for PluginApi {
dunce::canonicalize(files).map_err(failed)
}
fn install_dir(&self) -> Result<PathBuf, HostError> {
dunce::canonicalize(&self.pkg.dir).map_err(failed)
}
fn read_text_file(&self, real: &Path, max: usize) -> Result<String, HostError> {
// Unsaved editor contents win, as they do for project files.
if let Some(text) = self.shared.workspace().and_then(|w| w.buffer_text(real)) {
@@ -3749,6 +3753,19 @@ mod tests {
}
}
#[test]
fn install_dir_is_the_canonical_package_directory() {
let tmp = tempfile::tempdir().unwrap();
let pkg = tmp.path().join("acme.lint");
std::fs::create_dir_all(&pkg).unwrap();
std::fs::write(pkg.join("readme.pdf"), b"%PDF").unwrap();
let api = api(&pkg, Arc::default());
let install = api.install_dir().unwrap();
assert_eq!(install, dunce::canonicalize(&pkg).unwrap());
assert!(install.join("readme.pdf").is_file());
assert_ne!(install, api.plugin_dir().unwrap());
}
#[test]
fn storage_moves_an_older_storage_json_to_one_file_per_key() {
let tmp = tempfile::tempdir().unwrap();
+13
View File
@@ -738,6 +738,19 @@ impl Host {
let approvals = self.mcp_approvals.clone();
let secrets = self.agent_secrets.clone();
let root = root.to_path_buf();
// The skill policies sessions resolve against: both settings layers and the
// workspace's trust as it stands when a session starts.
let skill_settings = settings.clone();
let skill_root = root.clone();
let trust = self.trust.clone();
agents.set_skills_policy_hook(Box::new(move || {
let layer = |scope| skill_settings.layer(scope).agents.skills.clone();
ide_agent::SkillsPolicy {
user: layer(ide_workspace::settings::SettingsScope::Global),
workspace: layer(ide_workspace::settings::SettingsScope::Project),
workspace_trusted: trust.trusted(&skill_root).unwrap_or(false),
}
}));
agents.set_mcp_servers_hook(Box::new(move || {
crate::ops::agent::session_mcp_servers(&settings, &approvals, &secrets, &root)
}));
+11 -5
View File
@@ -6,15 +6,21 @@ use serde_json::json;
use std::path::Path;
use std::sync::Arc;
/// Codex's modes as it reported them last time, in "ask".
fn remember_codex_modes(data: &Path) {
/// Codex's modes as its catalog for `root` listed them last time, in "ask".
fn remember_codex_modes(data: &Path, root: &Path) {
std::fs::create_dir_all(data.join("agents")).unwrap();
let modes = json!({ "codex": { "config": [ {
let config = json!([ {
"id": "mode", "name": "Mode", "description": null, "category": "mode", "current": "ask",
"values": [ { "value": "read-only", "name": "Read Only", "description": null },
{ "value": "ask", "name": "Ask", "description": null },
{ "value": "full-access", "name": "Full Access", "description": null } ],
"via": "option" } ] } });
"via": "option" } ]);
let mut catalogs = serde_json::Map::new();
catalogs.insert(
root.to_string_lossy().into_owned(),
json!({ "fingerprint": "test", "config": config, "thoughtLevels": {} }),
);
let modes = json!({ "codex": { "projectCatalogs": catalogs } });
std::fs::write(data.join("agents/models.json"), modes.to_string()).unwrap();
}
@@ -30,7 +36,7 @@ async fn new_tasks_start_asking_for_approval_when_the_user_chose_so() {
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
std::fs::create_dir_all(root.join(".openidea")).unwrap();
let (config, data) = (tmp.path().join("config"), tmp.path().join("data"));
remember_codex_modes(&data);
remember_codex_modes(&data, &root);
std::fs::create_dir_all(&config).unwrap();
std::fs::write(config.join("settings.toml"), "[agents]\nnewTaskApprovals = \"ask\"\n").unwrap();
// A project's own settings don't choose this.
+13
View File
@@ -187,6 +187,19 @@ async fn reads_unsaved_text_and_searches_the_overlay_with_a_limit() {
assert_eq!(std::fs::read_to_string(h.root.join("src/a.txt")).unwrap(), "old text\nneedle needle\n");
}
#[tokio::test(flavor = "multi_thread")]
async fn every_match_of_a_long_line_is_found_once() {
let h = Harness::new();
std::fs::write(
h.root.join("src/min.js"),
format!("a=1;{}b='longneedle';{}longneedle\n", "x".repeat(2000), "y".repeat(2000)),
)
.unwrap();
let found = h.json("search_text", json!({"q":"longneedle","limit":20})).await;
let columns: Vec<_> = found["items"].as_array().unwrap().iter().map(|i| i["startColumn"].clone()).collect();
assert_eq!(columns, [json!(2008), json!(4020)], "{found}");
}
#[tokio::test(flavor = "multi_thread")]
async fn window_reports_supply_editor_selection_and_problems_then_disappear_on_close() {
let h = Harness::new();
+53
View File
@@ -195,3 +195,56 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
host.close_project("main");
}
/// Replace All past the limit replaces what the search lists: only the matches its Search
/// Context keeps (comments, string literals or code), as below the limit.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn replace_all_past_the_limit_keeps_to_the_search_context() {
use ide_search::SearchContext as C;
let comments = |word: &str| lines(2001, &format!("// {word}"));
let code = |name: &str, string: &str| format!("fn {name}() -> &'static str {{ \"{string}\" }}\n");
let original = format!("{}{}", comments("tok"), code("tok", "tok"));
let cases = [
(C::Any, format!("{}{}", comments("X"), code("X", "X"))),
(C::InComments, format!("{}{}", comments("X"), code("tok", "tok"))),
(C::InStringLiterals, format!("{}{}", comments("tok"), code("tok", "X"))),
(C::ExceptComments, format!("{}{}", comments("tok"), code("X", "X"))),
(C::ExceptStringLiterals, format!("{}{}", comments("X"), code("X", "tok"))),
(C::ExceptCommentsAndStringLiterals, format!("{}{}", comments("tok"), code("X", "tok"))),
];
for (context, expected) in cases {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("lib.rs"), &original).unwrap();
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
ops::search::replace_in_files(
&host,
"main",
RequestId::next(),
SearchQuery { context, ..query("tok", false) },
"X".into(),
false,
vec![],
true,
ops::Channel::new(|_| {}),
)
.await
.unwrap();
assert_eq!(std::fs::read_to_string(root.join("lib.rs")).unwrap(), expected, "{context:?}");
host.close_project("main");
}
}
+38
View File
@@ -128,6 +128,44 @@ async fn serves_projects_files_documents_search_and_runs() {
let current = invoke(&peer, "project_current", json!({})).await.unwrap();
assert_eq!(current["name"], "demo");
// A SQL batch sends each outcome precisely once before the request reply.
let file = project.join("test.sqlite");
std::fs::File::create(&file).unwrap();
let source = ide_db::DataSource {
id: "test-db".into(),
name: "Test database".into(),
file: Some(file.into()),
..Default::default()
};
invoke(&peer, "db_save_sources", json!({ "sources": [source] })).await.unwrap();
let sql = "SELECT 1 AS n; SELECT 'second' AS n";
let statements =
invoke(&peer, "db_statements", json!({ "id": "test-db", "text": sql, "from": 0, "to": sql.len() }))
.await
.unwrap();
let done = invoke(
&peer,
"db_execute_stream",
json!({ "request": 21, "id": "test-db", "statements": statements, "maxRows": 10,
"schema": null, "onProgress": { "$channel": 521 } }),
)
.await
.unwrap();
assert!(done.is_null());
let events = client
.channels
.lock()
.iter()
.filter(|frame| frame.id == 521)
.map(|frame| frame.data.clone())
.collect::<Vec<_>>();
assert_eq!(events.len(), 5);
assert_eq!(events[0], json!({ "type": "started", "index": 0 }));
assert_eq!(events[1]["outcome"]["result"]["rows"], json!([["1"]]));
assert_eq!(events[2], json!({ "type": "started", "index": 1 }));
assert_eq!(events[3]["outcome"]["result"]["rows"], json!([["second"]]));
assert_eq!(events[4], json!({ "type": "done", "error": null }));
// The built-in web server runs where the project is; the client forwards its port.
let root = std::path::PathBuf::from(opened["root"].as_str().unwrap());
let url = invoke(&peer, "web_url", json!({ "path": root.join("src/main.py") })).await.unwrap();
+41
View File
@@ -0,0 +1,41 @@
//! Exception breakpoints on a chosen class, armed inside the debuggee's VM by the debugger's own
//! connection. The adapter stops on them as on its own exception filters.
use crate::{InspectFuture, VmTarget};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExceptionClassSpec {
/// Echoed back with the breakpoint's state.
pub id: String,
/// Binary name (`com.acme.Outer$Inner`); subclasses stop too.
pub class_name: String,
pub caught: bool,
pub uncaught: bool,
pub enabled: bool,
/// JDI class patterns (`com.acme.*`, `*Test`) matched against the class whose code throws.
pub class_filters: Vec<String>,
pub class_exclusion_filters: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ExceptionArmState {
Armed,
/// No class of that name is loaded yet; it is armed when one is.
Pending,
Disabled,
/// A stream trace silences the VM's breakpoints; applied when it ends.
Deferred,
}
pub trait ExceptionClassBreakpoints: Send + Sync {
/// Replaces the VM's whole list; `(id, state)` per breakpoint, in order. The adapter can drop
/// these whenever it sets its own exception filters, so set them again after each time.
fn set<'a>(
&'a self,
target: &'a VmTarget,
breakpoints: &'a [ExceptionClassSpec],
) -> InspectFuture<'a, Vec<(String, ExceptionArmState)>>;
}
+2
View File
@@ -1,9 +1,11 @@
//! Types and the [`JvmInspector`] trait for reading live JVM objects while a debug session is
//! suspended. Implementations live elsewhere (jdtls bundle for Java, JDWP link for Kotlin).
mod exceptions;
mod names;
mod stream;
pub use exceptions::{ExceptionArmState, ExceptionClassBreakpoints, ExceptionClassSpec};
pub use names::{is_boxed, name_to_signature, signature_to_name, string_length};
pub use stream::{AbortState, CollectedTerminal, StreamTracer, TraceCollected, TraceId, TraceState};
+1 -1
View File
@@ -25,7 +25,7 @@ pub use syntax::{
CSS_CLASS, CSS_ID, CSS_VARIABLE, ClassBases, ConfigurationKey, ExternalFold, ExternalSymbol, ExternalSyntax,
ExternalToken, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, SpellingKind,
SpellingRegion, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError,
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_visibility,
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_kinds, merge_visibility,
set_external_syntax, shift_pos, shift_range,
};
pub use syntax::{MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts};
+1 -1
View File
@@ -28,7 +28,7 @@ use ide_core::{LanguageId, OutlineItem, Pos, Range};
pub use inheritance::ClassBases;
pub use lines::{shift_pos, shift_range};
pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
pub use outline::merge_visibility;
pub use outline::{merge_kinds, merge_visibility};
pub use php_align::PhpAlignment;
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
use std::cell::RefCell;
+30
View File
@@ -495,6 +495,36 @@ pub fn merge_visibility(target: &mut [OutlineItem], source: &[OutlineItem]) {
}
}
/// Takes the syntax tree's kind where a server reported a declared type as a value or a type
/// parameter: LSP has no kind for type aliases, so servers fall back to one of those
/// (typescript-language-server: Variable; rust-analyzer, sourcekit-lsp: TypeParameter).
/// Matched by name and position like [`merge_visibility`].
pub fn merge_kinds(target: &mut [OutlineItem], source: &[OutlineItem]) {
fn index(items: &[OutlineItem], out: &mut HashMap<(ide_core::Pos, String), SymbolKind>) {
for i in items {
if i.kind.is_type_like() {
out.insert((i.selection_range.start, i.name.clone()), i.kind);
}
index(&i.children, out);
}
}
fn apply(items: &mut [OutlineItem], map: &HashMap<(ide_core::Pos, String), SymbolKind>) {
for i in items {
if matches!(i.kind, SymbolKind::Variable | SymbolKind::TypeParameter)
&& let Some(&kind) = map.get(&(i.selection_range.start, i.name.clone()))
{
i.kind = kind;
}
apply(&mut i.children, map);
}
}
let mut map = HashMap::new();
index(source, &mut map);
if !map.is_empty() {
apply(target, &map);
}
}
/// End of `node` without trailing whitespace (C macros and others include the newline).
fn trimmed_end(node: &Node, text: &str) -> usize {
let (s, e) = (node.start_byte(), node.end_byte());
+82
View File
@@ -1476,6 +1476,88 @@ fn merge_visibility_matches_by_name_and_position() {
assert_eq!(lsp[1].visibility, None);
}
#[test]
fn merge_kinds_names_types_a_server_reported_as_values_or_type_parameters() {
fn kinds(items: &[OutlineItem], out: &mut Vec<(String, SymbolKind)>) {
for i in items {
out.push((i.name.clone(), i.kind));
kinds(&i.children, out);
}
}
/// The syntax outline with each kind replaced as a server reports it.
fn as_server(ts: &[OutlineItem], server: &[(&str, SymbolKind)]) -> Vec<OutlineItem> {
fn set(items: &mut [OutlineItem], server: &[(&str, SymbolKind)], at: &mut usize) {
for i in items {
i.kind = server[*at].1;
assert_eq!(i.name, server[*at].0);
*at += 1;
set(&mut i.children, server, at);
}
}
let mut lsp = ts.to_vec();
set(&mut lsp, server, &mut 0);
lsp
}
fn merged(language: &str, src: &str, server: &[(&str, SymbolKind)]) -> Vec<(String, SymbolKind)> {
let ts = syntax().outline(&lang(language), src);
let mut lsp = as_server(&ts, server);
crate::merge_kinds(&mut lsp, &ts);
let mut out = Vec::new();
kinds(&lsp, &mut out);
out
}
use SymbolKind as K;
let owned = |v: &[(&str, SymbolKind)]| v.iter().map(|(n, k)| (n.to_string(), *k)).collect::<Vec<_>>();
// typescript-language-server: a type alias is a Variable; `const` is one too.
let ts = "type Cents = number;\ninterface Shape {}\nconst rate = 1;\n";
assert_eq!(
merged("typescript", ts, &[("Cents", K::Variable), ("Shape", K::Interface), ("rate", K::Variable)]),
owned(&[("Cents", K::TypeAlias), ("Shape", K::Interface), ("rate", K::Variable)]),
);
// rust-analyzer: type aliases and associated types are TypeParameters, a trait an Interface.
let rs = "pub type Meters = u32;\ntrait Measure { type Unit; }\nstruct Rope;\nimpl Measure for Rope { type Unit = Meters; }\n";
assert_eq!(
merged(
"rust",
rs,
&[
("Meters", K::TypeParameter),
("Measure", K::Interface),
("Unit", K::TypeParameter),
("Rope", K::Struct),
("impl Measure for Rope", K::Variable),
("Unit", K::TypeParameter),
],
),
owned(&[
("Meters", K::TypeAlias),
("Measure", K::Interface),
("Unit", K::TypeAlias),
("Rope", K::Struct),
("impl Measure for Rope", K::Variable),
("Unit", K::TypeAlias),
]),
);
// sourcekit-lsp: typealias and associatedtype are TypeParameters.
let swift = "typealias Meters = Int\nprotocol Measure { associatedtype Unit }\n";
assert_eq!(
merged("swift", swift, &[("Meters", K::TypeParameter), ("Measure", K::Interface), ("Unit", K::TypeParameter)]),
owned(&[("Meters", K::TypeAlias), ("Measure", K::Interface), ("Unit", K::TypeAlias)]),
);
// A type kind the server chose stays: clangd's Class for a typedef, gopls's Struct.
let c = "typedef unsigned int meters;\n";
assert_eq!(merged("c", c, &[("meters", K::Class)]), owned(&[("meters", K::Class)]));
let go = "package p\n\ntype Point struct{}\n";
assert_eq!(
merged("go", go, &[("p", K::Package), ("Point", K::Struct)]),
owned(&[("p", K::Package), ("Point", K::Struct)])
);
}
#[test]
fn spelling_regions_cover_declared_names_only() {
let src = "// note\nfn parse_input(raw_text: &str) -> Value { let mut counter = helper(raw_text); \"hi\" }\n";
+1
View File
@@ -20,6 +20,7 @@ pub(crate) const SERVER: &str = "jdtls";
const GENERATED_SOURCES: &str = "openidea.java.generatedSources";
pub(crate) mod configuration;
pub(crate) mod exception_breakpoints;
mod extract_interface;
mod formatter;
mod generated;
@@ -0,0 +1,56 @@
//! [`ExceptionClassBreakpoints`] over `openidea.jvm.exceptions.set` of the JVM inspector bundle that
//! runs inside jdtls (`java/jvm-inspect`).
use super::jvm_inspect::{command_error, decode, target_json};
use crate::LspManager;
use ide_jvm_inspect::{
ExceptionArmState, ExceptionClassBreakpoints, ExceptionClassSpec, InspectError, InspectFuture, VmTarget,
};
use serde::Deserialize;
use serde_json::json;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::timeout;
/// The bundle waits for the inspect commands' turn, which a `classes` on a large heap can hold.
const COMMAND_TIMEOUT: Duration = Duration::from_secs(30);
pub struct JdtExceptionBreakpoints {
lsp: Arc<LspManager>,
/// A path inside the module whose jdtls runs the debug session.
server: PathBuf,
}
impl JdtExceptionBreakpoints {
pub fn new(lsp: Arc<LspManager>, server: PathBuf) -> Self {
Self { lsp, server }
}
}
#[derive(Deserialize)]
struct WireState {
id: String,
state: ExceptionArmState,
}
impl ExceptionClassBreakpoints for JdtExceptionBreakpoints {
fn set<'a>(
&'a self,
target: &'a VmTarget,
breakpoints: &'a [ExceptionClassSpec],
) -> InspectFuture<'a, Vec<(String, ExceptionArmState)>> {
Box::pin(async move {
let arguments = vec![target_json(target), json!({ "breakpoints": breakpoints })];
let reply = timeout(
COMMAND_TIMEOUT,
self.lsp.jdtls_command(&self.server, "openidea.jvm.exceptions.set", arguments),
)
.await
.map_err(|_| InspectError::TimedOut)?
.map_err(command_error)?;
let states: Vec<WireState> = decode(reply)?;
Ok(states.into_iter().map(|s| (s.id, s.state)).collect())
})
}
}
+1
View File
@@ -48,6 +48,7 @@ mod xml_catalog;
pub use injections::{InjectedRange, InjectionProvider, MAX_INJECTED_DOCUMENT_BYTES};
pub use inspect::{CheckedServer, DocumentCheck, FileInspection, InspectHost, InspectOptions};
pub use jdtls::exception_breakpoints::JdtExceptionBreakpoints;
pub use jdtls::jvm_inspect::JdtJvmInspector;
pub use jdtls::stream_trace::JdtStreamTracer;
pub use kotlin_lsp::{KotlinDebugServer, KotlinDebugUnavailable};
+56
View File
@@ -3714,6 +3714,62 @@ async fn stream_collect_fails_cleanly_on_a_step_beyond_u16() {
assert!(matches!(error, InspectError::Failed(ref m) if m.contains("malformed")), "{error:?}");
}
#[tokio::test(flavor = "multi_thread")]
async fn exception_breakpoints_send_the_whole_list_and_decode_states() {
use ide_jvm_inspect::{ExceptionArmState, ExceptionClassBreakpoints, ExceptionClassSpec};
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let (_, path) = h.open("Sample.java", "class Sample {}");
h.wait_status("jdtls", ServerStatus::Ready).await;
let s = h.launcher.state("jdtls");
let client = ide_lsp::JdtExceptionBreakpoints::new(h.mgr.clone(), path);
let specs = [
ExceptionClassSpec {
id: "a".into(),
class_name: "com.acme.Boom".into(),
caught: true,
uncaught: false,
enabled: true,
class_filters: vec!["com.acme.*".into()],
class_exclusion_filters: vec![],
},
ExceptionClassSpec {
id: "b".into(),
class_name: "java.lang.IllegalStateException".into(),
caught: true,
uncaught: true,
enabled: false,
class_filters: vec![],
class_exclusion_filters: vec!["*Test".into()],
},
];
s.respond(
"workspace/executeCommand",
json!({"ok": [{"id": "a", "state": "pending"}, {"id": "b", "state": "disabled"}]}),
);
let states = client.set(&stream_launch_target(), &specs).await.unwrap();
assert_eq!(states, vec![("a".into(), ExceptionArmState::Pending), ("b".into(), ExceptionArmState::Disabled)]);
let asked = s.requested("workspace/executeCommand");
assert_eq!(asked[0]["command"], "openidea.jvm.exceptions.set");
assert_eq!(
asked[0]["arguments"],
json!([
{"pid": 42, "host": null, "port": null, "generation": 3},
{"breakpoints": [
{"id": "a", "className": "com.acme.Boom", "caught": true, "uncaught": false, "enabled": true,
"classFilters": ["com.acme.*"], "classExclusionFilters": []},
{"id": "b", "className": "java.lang.IllegalStateException", "caught": true, "uncaught": true,
"enabled": false, "classFilters": [], "classExclusionFilters": ["*Test"]},
]},
])
);
s.respond("workspace/executeCommand", json!({"error": "noSession", "detail": "hotCodeReplace is never?"}));
assert_eq!(
client.set(&stream_launch_target(), &specs).await.unwrap_err(),
ide_jvm_inspect::InspectError::NoSession
);
}
#[tokio::test(flavor = "multi_thread")]
async fn debug_server_port_maps_to_module() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
+4
View File
@@ -652,6 +652,10 @@ pub trait HostApi: Send + Sync {
fn plugin_dir(&self) -> Result<PathBuf, HostError> {
Err(HostError::Failed("private plugin storage is unavailable".into()))
}
/// The plugin's install / package directory (read-only for the guest).
fn install_dir(&self) -> Result<PathBuf, HostError> {
Err(HostError::Failed("plugin install directory is unavailable".into()))
}
/// Replaces the text of a file whose real path the caller already checked:
/// in one step, keeping its encoding and BOM (a new file is UTF-8). Refused
/// while an editor holds unsaved changes for it.
+18 -9
View File
@@ -313,11 +313,11 @@ impl StoreData {
/// `path` as the real path an `fs.read:…` grant covers, or what the plugin
/// should be told instead (`denied` naming the capability to declare).
/// The private plugin-dir and the install directory are readable without a
/// grant; writing still needs `fs.write` or the private dir.
fn granted_file(&self, path: &str) -> Result<PathBuf, wit::Error> {
let mut granted = self.granted.clone();
if let Ok(dir) = self.host.plugin_dir() {
granted.push(Capability::FsRead(to_ipc(&dir)));
}
granted.extend(self.builtin_read_roots());
sandbox::resolve_granted(&granted, path).map_err(Into::into)
}
@@ -331,6 +331,19 @@ impl StoreData {
sandbox::resolve_writable(&granted, path).map_err(Into::into)
}
/// Private plugin-dir and install directory: readable without an `fs.read`
/// grant; `editor.open` / `open-location` may use them without project.read.
fn builtin_read_roots(&self) -> Vec<Capability> {
let mut roots = Vec::new();
if let Ok(dir) = self.host.plugin_dir() {
roots.push(Capability::FsRead(to_ipc(&dir)));
}
if let Ok(dir) = self.host.install_dir() {
roots.push(Capability::FsRead(to_ipc(&dir)));
}
roots
}
fn client(&self) -> Option<&str> {
self.invocation.client.as_deref()
}
@@ -1144,9 +1157,7 @@ impl StoreData {
sandbox::resolve_in_root(root, path).map_err(wit::Error::Invalid)
}
fn openable_path(&self, path: &str) -> Result<PathBuf, wit::Error> {
if let Ok(dir) = self.host.plugin_dir()
&& let Ok(real) = sandbox::resolve_granted(&[Capability::FsRead(to_ipc(&dir))], path)
{
if let Ok(real) = sandbox::resolve_granted(&self.builtin_read_roots(), path) {
return Ok(real);
}
self.require(Capability::ProjectRead)?;
@@ -2078,9 +2089,7 @@ impl views::Host for StoreData {
}
fn open_location(&mut self, path: String, line: u32, column: u32) -> Fallible<()> {
if let Ok(dir) = self.host.plugin_dir()
&& let Ok(real) = sandbox::resolve_granted(&[Capability::FsRead(to_ipc(&dir))], &path)
{
if let Ok(real) = sandbox::resolve_granted(&self.builtin_read_roots(), &path) {
if let Err(e) = self.require_interactive() {
return Ok(Err(e));
}
@@ -1 +1 @@
b59392bcc1999048f0ab922ec659bc21d9e825c696fa41d9f0a40c85627a5b2c
d442e600d82cab0f79ad6decf95ca9d06c89dcd3119c500a11f48cdc54a5d5f4
@@ -1 +1 @@
034b99891313c03eb2a6b8c3cb2e4784129e1936965be803512f1d869b1768c2
af048639f57e86262543c3dcd18bca27d384b6ad99a625af869f0812bf8ac93c
@@ -1 +1 @@
29ec0a96e2a0f6965915c7c25e35036743fc27a49037df588c217e8abfff93e3
95b7263ca584c6b1b035be4dde64c7ae57b407c6a86b5ab6fe2736134e1d7754
@@ -1 +1 @@
87b367cfdd65c360920eff7be4d6a8d6b939721f6398aa6a01e39a289590699e
1e5b10e8e77bdc7ed6bf002a415458caef7eee9a98123229dddf0d148af58f73
@@ -1 +1 @@
7d034ee1a4b99615642d5bf033802f8e4662216d45b209c4c7a24eb8f1338f48
5b3d4ad737cde32fc808bcd8c93d9cdd7d53961985db0428ab567b4e97ed4ffb
@@ -1 +1 @@
3fdf985273ec14ae623fa84602a9220cfbfb2e0e587ab192fc2bcb8d990ce9e3
04b1cbc2148cff8c0fa2d6a4f127a6a3c8ade5a7dc1541c1a16a656def299f33
@@ -1 +1 @@
8434e9271e27a6778bb3d5922e8925f3fd9f1d35377e5dddf5b5eb5416bd09bb
918c44ee3a58a073dd65e2f7e32501cf9e84a59f24452c166e75457f7c232c89
@@ -1 +1 @@
9fa7468ce385ff33c1f3b99c84711e0d11a84b10e8e4f95b358fcd2ccc96e255
c980260c235249186f754e16597de9d49663771d711ce6873bf83ebaf2a0fc34
@@ -1 +1 @@
5220a5bfb6ec0467a72e63e21d690e70b7d46b4f2eaff4116a8a79220a5eca8f
df5729d63b83fbc511e0ba8509f9d370c5124b5af4c70f286c8965d2b0d890ef
@@ -1 +1 @@
a962127d1c6e37e85b81973a272a5d6b383cc2884b41bb2d82e8640ef5f8f943
305965c6cbf2fd2b331bf9e2c473cfa9a543ab39ff0d47317ee9e28be9ea5b0f
@@ -1 +1 @@
92ad3e43e7f343004dcf26a51e282e97ed694cc9bd7325ff75aa5b18f1a2eeb6
a1bb95a8a23ddd2d55bf64c724f73debfb503f252f57d8ae46afda8a0717fc20
@@ -1 +1 @@
2200ed0d44dbafb70ad864cb9569b0b2c37cf9eec1582b05efa903a9e8ec89ee
b8be3120a468190aebb473c8f5d2e13889210241c9ab43c89cbf703c00366c8e
@@ -1 +1 @@
644612ee4228010f141042ea0eab5431b8386370f863a70b63cd3315f69d963a
9b345dec001bcb7c0d8e6e214099d597b02976f20c2449af9847e8b69d0a5ab7
@@ -1 +1 @@
2af5d46516bfc1d38ad1f24d6cf3c57e2d6db6b0d3225748f55c4f13110430fb
23e0c2ab39ba83aa332b57046b0b8c1bf236e3e61a14874ed82d20ce388873b6
@@ -1 +1 @@
0ee0773cefd61b8144d0550718e1988a1e60438bee826c3867350e28886a56f7
e2d2afeb53f0af478963cde0c97fb016b1a424bf97952c7474a18e38e9e9ed55
@@ -1 +1 @@
941cb9008aaab11464b193c37b91e2476d771ec526247713f291c6642caf5995
6bff7a7521a4a969aa8d9bd1363ef5efd544e079e77e55e51b19fff13b586b3a
@@ -1 +1 @@
06d70aae3152c88d1299a9b33f151b0baa4a77c3ca7145215c6f6e0aa40727b2
27bb4c06b18703c43155e1a45c9edfb249a19443a68e87441babeeb71cb127d9
@@ -1 +1 @@
86eb87758e4f7c0242a18f12a113c31d418da64d7198041120f19401a5707bfb
deb7995931cf8e344a486fbab275fd3ec7ddff73b05a841593e5521c4a514084
@@ -1 +1 @@
4442bb686fa18e8e8a52fd1cd8683b8767ec7908ffc1454dff476d9cb1711be9
dc6670ff6373d148430f5c9c13d1ec5407b2d94c74c2209562737076468ca79d
@@ -1 +1 @@
dd51f1b8634ff6305ba1a69c8457bd586996200a2b18e4a08d0cfa2fb60abaf6
9e111c4c541312dc231bac5a4fd1120b59191ecadce2dca73c77f4bff2a9d0e8
@@ -1 +1 @@
4319f2655ee1e240b33f4b96c23fff59c61aa62d6ccc628715e5ff9fe38c2717
caa4053cd7f0135ab14a8c5c56abe198394e370549fea6d9df4d4c11c38fcabf
@@ -1 +1 @@
50c4fd7e08a4187afae0e00c775a61578b82bbad056807ad063ee47e79e2cef1
8beb151f14b062438c4024b13bbdedbf5d65099415ad9d055fe63a4b1d64d010
@@ -1 +1 @@
220666302d814e6d8bde346954205c94c82320d5584d46f01672fd7d32400bf3
fa6a660890e0beee7599726e9c30142601fbcd6f82a519b1b5952ef30f450bfb
@@ -1 +1 @@
4ee484afaa1a1f71a9e544582d90db3260307fc89b8f514aaaff883df2761ba6
a7c1ec4814e4268fe185ae493413532528970264e84f717087b57a303ebe3591
@@ -1 +1 @@
3fba59ce802d88a2a1c026480a2cb8ce4d9539eb7b88f5a18bf6232f7adef147
450d1e698882257d6c75b16984a6086259acce2c66a92b96c76ed3d6e15a0b4d
@@ -1 +1 @@
73433da25d5304d0a3cb83d750d02feb5e270ee7e9f680c4ee9d923afa9aa066
738791aa00d63961fa7e8ed6ac7601f46848ecc0d25a498b6019eb151bf9169e
@@ -1 +1 @@
12df43f99eac93f4e1a070635780ad653932cf69a14595175d8ba6d4f0a4445c
957d02e3d72673ca4a9ca80eb7c3e63087a6d8377411fc820d3808f024326b2e
@@ -1 +1 @@
427b63c11188689262101cde971af0a92e54bd6c88a4e3cc8fdfa1a7c8c95fce
f0a57acc6ca29b0dc2803596a0a39ceb1e2185b59a44f5533e8f9b19bf214afd
@@ -1 +1 @@
07ae58fe39746b779b1e466d7bbbb666ba550f427c7bf8de97d7ede647c00bc0
7890cfd9a08b67b47ae098ce24e02551935337b8501636e29164ff4ca6244e7e
@@ -1 +1 @@
f9912644c28512e37299834123cd4c94f6ed11f29bd38ddbc1c92df168447494
769f873adfa7ed3752a059dac89e60f2203b8ce91b36fe0a7cb9c724e0cf895b
@@ -1 +1 @@
ea0eec8c07d6469d3ab63c3bb08c85b01208be1757edffe5eabcb7be79ccf537
ea31cbeefee7f219f86fc7e65315aea7efebe3b91c9cec6e12d4f551b9655d95
@@ -1 +1 @@
1ce55fabaa5ea1ddf770c8a1ad7f7b60a843c82c453d42289088c4b2fec61d84
bb30795e7d62b19b237759beeab9da6f6028fea7862d8fa83c6b3238a26f540d
@@ -1 +1 @@
3356b4ec918c668c4c249f84afb9bafcd06c073ba86235b6ceea7ef6220cdaf5
65725512c8a8d3ad6cb02a4f947541dd1688a3208e37fa4ed0474ca8197f2340
+4
View File
@@ -1337,6 +1337,10 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
cfg.args = vec!["--lsp".into(), "--stdio".into()];
cfg.display_name = Some("TypeScript 7".into());
cfg.initialization_options = None;
// Completing a JSX prop adds `=""` or `={}` by its type, as vtsls does by default;
// TypeScript 7 adds no value unless asked.
let jsx = json!({ "preferences": { "jsxAttributeCompletionStyle": "auto" } });
merge_init_options(cfg, json!({ "typescript": jsx, "javascript": jsx }));
cfg.tsserver_project = false;
return;
}
+2 -2
View File
@@ -1649,7 +1649,7 @@ pub fn jvm_inspect_bundle(data_dir: &Path) -> Option<PathBuf> {
install_bundle(
data_dir,
"jvm-inspect",
"1.1.1",
"1.2.0",
include_bytes!("../../../java/jvm-inspect/openidea-jvm-inspect.jar"),
)
}
@@ -1745,7 +1745,7 @@ mod usages_bundle_tests {
std::fs::write(dir.path().join(name), b"old").unwrap();
}
let jar = super::jvm_inspect_bundle(dir.path()).unwrap();
assert_eq!(jar, dir.path().join("jvm-inspect-1.1.1.jar"));
assert_eq!(jar, dir.path().join("jvm-inspect-1.2.0.jar"));
assert_eq!(std::fs::read(&jar).unwrap(), include_bytes!("../../../java/jvm-inspect/openidea-jvm-inspect.jar"));
assert!(!dir.path().join("jvm-inspect-0.9.0.jar").exists());
assert_eq!(std::fs::read(dir.path().join("java-usages-1.7.0.jar")).unwrap(), b"old");
+9 -1
View File
@@ -1725,7 +1725,15 @@ fn typescript_7_runs_its_own_language_server() {
assert_eq!(Path::new(&cfg.command), native, "{name}");
assert_eq!(cfg.args, ["--lsp", "--stdio"]);
assert_eq!(cfg.display_name.as_deref(), Some("TypeScript 7"));
assert!(cfg.initialization_options.is_none());
// The tsserver-based server's options don't apply; JSX prop completion adds a value.
let options = serde_json::to_value(cfg.initialization_options.as_ref().unwrap()).unwrap();
for language in ["typescript", "javascript"] {
assert_eq!(
options[language],
serde_json::json!({ "preferences": { "jsxAttributeCompletionStyle": "auto" } })
);
}
assert_eq!(options.as_object().unwrap().len(), 2, "{options}");
}
// Picked as a directory (its `lib`, as for older versions), too.
s.languages.typescript.version = modules.join("typescript/lib").to_string_lossy().into_owned();
+8 -12
View File
@@ -1,13 +1,12 @@
//! Parallel walk + per-file search.
use crate::iter::for_each_match;
use crate::line::line_match;
use crate::line::line_matches;
use crate::mask::FileMask;
use crate::pattern::ScopePattern;
use crate::query::{Compiled, line_terminator};
use crate::{
FileMatches, LineMatch, LiteralKind, LiteralRange, Literals, PathFilter, SearchContext, SearchScope, SearchSummary,
TextSource,
FileMatches, LineMatch, LiteralRange, Literals, PathFilter, SearchContext, SearchScope, SearchSummary, TextSource,
};
use grep_regex::RegexMatcher;
use grep_searcher::{BinaryDetection, Searcher, SearcherBuilder, Sink, SinkMatch};
@@ -52,6 +51,7 @@ struct Control<'a> {
matches: AtomicU32,
files: AtomicU32,
max: u32,
whole_word: bool,
}
impl Control<'_> {
@@ -131,6 +131,7 @@ pub(crate) fn run(req: Request<'_>) -> IdeResult<SearchSummary> {
matches: AtomicU32::new(0),
files: AtomicU32::new(0),
max: if req.max_matches == 0 { DEFAULT_MAX_MATCHES } else { req.max_matches },
whole_word: req.compiled.whole_word,
},
};
let mut searcher_builder = SearcherBuilder::new();
@@ -462,12 +463,6 @@ impl<'a> FileSink<'a> {
}
}
/// Kind of the comment or string literal containing byte `pos` (`literals` sorted).
fn literal_at(literals: &[LiteralRange], pos: usize) -> Option<LiteralKind> {
let i = literals.partition_point(|l| l.start <= pos);
literals[..i].last().filter(|l| pos < l.end).map(|l| l.kind)
}
impl Sink for FileSink<'_> {
type Error = io::Error;
@@ -488,12 +483,12 @@ impl Sink for FileSink<'_> {
let mut found = std::mem::take(&mut self.found);
let mut ranges = std::mem::take(&mut self.ranges);
found.clear();
for_each_match(self.matcher, &buffer[..range.end], range.start, |mm| {
for_each_match(self.matcher, self.ctl.whole_word, &buffer[..range.end], range.start, |mm| {
found.push((mm.start() - range.start, mm.end() - range.start));
});
if let Some((context, literals)) = self.context {
let block_start = usize::try_from(m.absolute_byte_offset()).unwrap_or(usize::MAX);
found.retain(|&(a, _)| context.accepts(literal_at(literals, block_start.saturating_add(a))));
found.retain(|&(a, _)| context.keeps(literals, block_start.saturating_add(a)));
}
let mut next = found.iter().copied().peekable();
@@ -521,7 +516,7 @@ impl Sink for FileSink<'_> {
if !ranges.is_empty() {
self.count = self.count.saturating_add(u32::try_from(ranges.len()).unwrap_or(u32::MAX));
let line_no = u32::try_from(line_no).unwrap_or(u32::MAX);
self.lines.push(line_match(line_no, &block[line_start..content_end], &ranges));
line_matches(line_no, &block[line_start..content_end], &ranges, &mut self.lines);
}
line_start = line_end_incl;
line_no += 1;
@@ -706,6 +701,7 @@ mod budget_tests {
matches: AtomicU32::new(0),
files: AtomicU32::new(0),
max,
whole_word: false,
}
}
+70 -7
View File
@@ -1,16 +1,27 @@
//! Match iteration that never splits a UTF-8 sequence after an empty match
//! (`grep-matcher`'s iterators advance by a single byte).
//! (`grep-matcher`'s iterators advance by a single byte), and that applies
//! IDEA's whole-word rule.
use grep_matcher::{Captures, Match, Matcher};
use grep_regex::{RegexCaptures, RegexMatcher};
/// Calls `f` for each non-overlapping match in `haystack[at..]`; `haystack[..at]`
/// is only used as look-behind context.
pub(crate) fn for_each_match(matcher: &RegexMatcher, haystack: &[u8], at: usize, mut f: impl FnMut(Match)) {
/// is only used as look-behind context. With `whole_word`, only [`is_whole_word`] matches.
pub(crate) fn for_each_match(
matcher: &RegexMatcher,
whole_word: bool,
haystack: &[u8],
at: usize,
mut f: impl FnMut(Match),
) {
let mut at = at;
let mut last_end = None;
while at <= haystack.len() {
let Ok(Some(m)) = matcher.find_at(haystack, at) else { break };
if whole_word && !is_whole_word(haystack, m) {
at = next_char(haystack, m.start());
continue;
}
at = advance(haystack, m);
if m.is_empty() && last_end == Some(m.end()) {
continue;
@@ -23,6 +34,7 @@ pub(crate) fn for_each_match(matcher: &RegexMatcher, haystack: &[u8], at: usize,
/// Like [`for_each_match`] but with capture groups.
pub(crate) fn for_each_captures(
matcher: &RegexMatcher,
whole_word: bool,
haystack: &[u8],
caps: &mut RegexCaptures,
mut f: impl FnMut(&RegexCaptures),
@@ -34,6 +46,10 @@ pub(crate) fn for_each_captures(
break;
}
let Some(m) = caps.get(0) else { break };
if whole_word && !is_whole_word(haystack, m) {
at = next_char(haystack, m.start());
continue;
}
at = advance(haystack, m);
if m.is_empty() && last_end == Some(m.end()) {
continue;
@@ -45,12 +61,59 @@ pub(crate) fn for_each_captures(
/// Where to resume after `m`: its end, or past the next char for empty matches.
fn advance(haystack: &[u8], m: Match) -> usize {
if !m.is_empty() {
return m.end();
}
let mut next = m.end() + 1;
if !m.is_empty() { m.end() } else { next_char(haystack, m.end()) }
}
/// The start of the char after the one at `at`.
fn next_char(haystack: &[u8], at: usize) -> usize {
let mut next = at + 1;
while next < haystack.len() && (haystack[next] & 0xC0) == 0x80 {
next += 1;
}
next
}
/// IDEA's whole word (`FindManagerBase.isWholeWord`): an edge where the match has an
/// identifier character must not touch another one, unless it follows an escape such as
/// `\n`; an edge with another character only must not repeat that character (`==` is not
/// in `===`).
fn is_whole_word(haystack: &[u8], m: Match) -> bool {
let (start, end) = (m.start(), m.end());
let word_start = match (char_before(haystack, start), char_at(haystack, start)) {
(Some(prev), Some(first)) if is_identifier(first) => {
let escaped = char_before(haystack, start - prev.len_utf8()) == Some('\\');
!is_identifier(prev) || escaped
}
(Some(prev), Some(first)) => prev != first,
_ => true,
};
let word_end = match (char_at(haystack, end), char_before(haystack, end)) {
(Some(next), Some(last)) if is_identifier(last) => !is_identifier(next),
(Some(next), Some(last)) => next != last,
(Some(_), None) | (None, _) => true,
};
word_start && word_end
}
/// Java's identifier part, near enough: letters, digits, `_` and `$`.
fn is_identifier(c: char) -> bool {
c.is_alphanumeric() || c == '_' || c == '$'
}
/// The char starting at byte `at` (`None` at the end or in invalid UTF-8).
fn char_at(haystack: &[u8], at: usize) -> Option<char> {
let rest = haystack.get(at..)?;
let len = rest.len().min(4);
let s = match std::str::from_utf8(&rest[..len]) {
Ok(s) => s,
Err(e) => std::str::from_utf8(&rest[..e.valid_up_to()]).ok()?,
};
s.chars().next()
}
/// The char ending at byte `at` (`None` at the start or in invalid UTF-8).
fn char_before(haystack: &[u8], at: usize) -> Option<char> {
let head = haystack.get(..at)?;
let from = head.len().saturating_sub(4);
(from..head.len()).find_map(|i| std::str::from_utf8(&head[i..]).ok().and_then(|s| s.chars().next_back()))
}
+15 -5
View File
@@ -22,7 +22,7 @@ pub use mask::FileMask;
pub use pattern::ScopePattern;
pub use replace::{
ReplaceEvent, ReplaceHost, ReplacePreview, ReplaceSummary, ReplaceTarget, apply_edits, preserve_case, preview,
replace_files, replacement_edits,
replace_files, replace_files_in_context, replacement_edits,
};
pub use words::{WordFiles, WordQuery, files_with_word};
@@ -99,8 +99,15 @@ impl SearchContext {
}
}
/// Whether a match starting at byte `at` is kept, given the file's sorted comments and
/// string literals. Find and Replace both filter with it, so they keep the same matches.
pub fn keeps(self, literals: &[LiteralRange], at: usize) -> bool {
let i = literals.partition_point(|l| l.start <= at);
self.accepts(literals[..i].last().filter(|l| at < l.end).map(|l| l.kind))
}
/// Only matches inside comments / string literals: files without any are skipped.
fn needs_literals(self) -> bool {
pub(crate) fn needs_literals(self) -> bool {
matches!(self, Self::InComments | Self::InStringLiterals)
}
}
@@ -160,7 +167,8 @@ pub type PathFilter<'a> = &'a (dyn Fn(&str) -> bool + Sync);
pub struct LineMatch {
/// 0-based line.
pub line: u32,
/// Line text, truncated around the match for very long lines.
/// Line text, truncated around the matches for very long lines: such a line comes as one
/// `LineMatch` per window, so the same `line` can repeat.
pub text: String,
/// UTF-16 column ranges within `text`.
pub ranges: Vec<(u32, u32)>,
@@ -285,7 +293,9 @@ pub fn match_ranges(text: &str, query: &SearchQuery) -> IdeResult<Vec<(usize, us
}
let compiled = query::compile(query)?;
let mut out = Vec::new();
iter::for_each_match(&compiled.matcher, text.as_bytes(), 0, |m| out.push((m.start(), m.end())));
iter::for_each_match(&compiled.matcher, compiled.whole_word, text.as_bytes(), 0, |m| {
out.push((m.start(), m.end()))
});
Ok(out)
}
@@ -308,7 +318,7 @@ pub fn replace_in_text(text: &str, query: &SearchQuery, replacement: &str) -> Id
let mut out = Vec::with_capacity(text.len());
let mut count = 0u32;
let mut last = 0;
iter::for_each_captures(matcher, haystack, &mut caps, |caps| {
iter::for_each_captures(matcher, compiled.whole_word, haystack, &mut caps, |caps| {
let Some(m) = caps.get(0) else { return };
out.extend_from_slice(&haystack[last..m.start()]);
last = m.end();
+65 -14
View File
@@ -1,5 +1,6 @@
//! Turns a matched line plus byte ranges into a [`LineMatch`] with UTF-16
//! columns, truncating very long lines to a window around the first match.
//! Turns a matched line plus byte ranges into [`LineMatch`]es with UTF-16
//! columns. A very long line is cut into windows: one around its first match
//! and the matches that fit with it, then one around each match left out.
use crate::LineMatch;
@@ -8,33 +9,57 @@ pub(crate) const MAX_LINE_LEN: usize = 500;
/// How much text before the first match a truncated line keeps.
const CONTEXT_BEFORE: usize = 100;
/// `line` excludes the line terminator; `ranges` are sorted, non-overlapping
/// Appends the matches of one line to `out`: a single [`LineMatch`], or one per window of a
/// very long line. `line` excludes the line terminator; `ranges` are sorted, non-overlapping
/// byte ranges within `line`.
pub(crate) fn line_match(line_no: u32, line: &[u8], ranges: &[(usize, usize)]) -> LineMatch {
pub(crate) fn line_matches(line_no: u32, line: &[u8], ranges: &[(usize, usize)], out: &mut Vec<LineMatch>) {
match std::str::from_utf8(line) {
Ok(s) => from_str(line_no, s, ranges),
Ok(s) => from_str(line_no, s, ranges, out),
Err(_) => {
let (s, mapped) = lossy(line, ranges);
from_str(line_no, &s, &mapped)
from_str(line_no, &s, &mapped, out)
}
}
}
fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)]) -> LineMatch {
let (start, end) = if s.len() <= MAX_LINE_LEN || utf16_len(s.as_bytes()) <= MAX_LINE_LEN {
(0, s.len())
} else {
window(s, floor_boundary(s, ranges.first().map_or(0, |r| r.0.min(s.len()))))
};
#[cfg(test)]
fn line_match(line_no: u32, line: &[u8], ranges: &[(usize, usize)]) -> LineMatch {
let mut out = Vec::new();
line_matches(line_no, line, ranges, &mut out);
out.swap_remove(0)
}
fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)], out: &mut Vec<LineMatch>) {
if s.len() <= MAX_LINE_LEN || utf16_len(s.as_bytes()) <= MAX_LINE_LEN {
out.push(in_window(line_no, s, ranges, (0, s.len())).0);
return;
}
let mut rest = ranges;
loop {
let bounds = window(s, floor_boundary(s, rest.first().map_or(0, |r| r.0.min(s.len()))));
let (m, used) = in_window(line_no, s, rest, bounds);
out.push(m);
rest = &rest[used.max(1)..];
if rest.is_empty() {
break;
}
}
}
/// The [`LineMatch`] of the text in `bounds` with the leading `ranges` that end inside it (at
/// least the first one, cut to the window), and how many ranges it took.
fn in_window(line_no: u32, s: &str, ranges: &[(usize, usize)], (start, end): (usize, usize)) -> (LineMatch, usize) {
let text = &s[start..end];
let text_offset = if start == 0 { 0 } else { utf16_len(&s.as_bytes()[..start]) };
let mut out = Vec::with_capacity(ranges.len());
let (mut pos, mut col) = (start, 0usize);
let mut used = 0;
for &(a, b) in ranges {
if a > end || (a == end && b > a) {
if a > end || (a == end && b > a) || (used > 0 && b > end) {
break;
}
used += 1;
let (a, b) = (floor_boundary(s, a.max(start)), ceil_boundary(s, b.min(end)));
if a < pos {
continue;
@@ -45,7 +70,7 @@ fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)]) -> LineMatch {
pos = b;
out.push((col_a as u32, col as u32));
}
LineMatch { line: line_no, text: text.to_owned(), ranges: out, text_offset: text_offset as u32 }
(LineMatch { line: line_no, text: text.to_owned(), ranges: out, text_offset: text_offset as u32 }, used)
}
/// Byte window `[start, end)` of at most `MAX_LINE_LEN` UTF-16 units that
@@ -186,4 +211,30 @@ mod tests {
assert_eq!(m.ranges, vec![(100, 106)]);
assert!(utf16_len(m.text.as_bytes()) <= MAX_LINE_LEN);
}
#[test]
fn matches_outside_the_first_window_get_their_own() {
// Two matches 100 apart share a window; the one 1000 further gets another.
let s = format!("{}ab{}cd{}ef{}", "x".repeat(1000), "x".repeat(100), "x".repeat(1000), "x".repeat(10));
let at = |needle: &str| s.find(needle).unwrap();
let ranges = [(at("ab"), at("ab") + 2), (at("cd"), at("cd") + 2), (at("ef"), at("ef") + 2)];
let mut out = Vec::new();
line_matches(7, s.as_bytes(), &ranges, &mut out);
let found: Vec<Vec<u32>> =
out.iter().map(|m| m.ranges.iter().map(|&(a, _)| m.text_offset + a).collect()).collect();
let col = |needle: &str| at(needle) as u32;
assert_eq!(found, vec![vec![col("ab"), col("cd")], vec![col("ef")]]);
assert!(out.iter().all(|m| m.line == 7 && utf16_len(m.text.as_bytes()) <= MAX_LINE_LEN));
assert_eq!(&out[1].text[out[1].ranges[0].0 as usize..out[1].ranges[0].1 as usize], "ef");
}
#[test]
fn a_match_longer_than_the_window_is_cut_to_it() {
let s = format!("{}{}tail", "x".repeat(100), "y".repeat(1000));
let mut out = Vec::new();
line_matches(0, s.as_bytes(), &[(100, 1100), (1100, 1104)], &mut out);
assert_eq!(out.len(), 2);
assert_eq!(out[0].ranges, vec![(100, 500)]);
assert_eq!(out[1].text_offset + out[1].ranges[0].0, 1100);
}
}
+7 -3
View File
@@ -9,6 +9,8 @@ use ide_core::{IdeError, IdeResult};
pub(crate) struct Compiled {
pub matcher: RegexMatcher,
pub multi_line: bool,
/// Keep only whole-word matches ([`crate::iter`] checks IDEA's rule on each match).
pub whole_word: bool,
}
/// The line terminator shared by the matcher and the searcher. CRLF mode lets
@@ -19,12 +21,13 @@ pub(crate) fn line_terminator() -> LineTerminator {
pub(crate) fn compile(query: &SearchQuery) -> IdeResult<Compiled> {
let multi_line = needs_multi_line(query);
let whole_word = query.whole_word;
match build(query, multi_line) {
Ok(matcher) => Ok(Compiled { matcher, multi_line }),
Ok(matcher) => Ok(Compiled { matcher, multi_line, whole_word }),
// Patterns such as `[\n]` or `\x0A` can only match across lines;
// retry in multi-line mode before reporting an error.
Err(err) if !multi_line => match build(query, true) {
Ok(matcher) => Ok(Compiled { matcher, multi_line: true }),
Ok(matcher) => Ok(Compiled { matcher, multi_line: true, whole_word }),
Err(_) => Err(invalid_pattern(query, &err)),
},
Err(err) => Err(invalid_pattern(query, &err)),
@@ -35,7 +38,8 @@ fn build(query: &SearchQuery, multi_line: bool) -> Result<RegexMatcher, grep_reg
let mut b = RegexMatcherBuilder::new();
b.case_smart(false)
.case_insensitive(!query.case_sensitive)
.word(query.whole_word)
// Not `.word()`: ripgrep's rule wants a non-word character on both sides even of
// `foo(`, IDEA's (in `iter`) only beside the match's identifier characters.
.fixed_strings(!query.is_regex)
.unicode(true)
// `^`/`$` always mean start/end of line, as in IDEA and ripgrep.
+35 -7
View File
@@ -3,7 +3,7 @@
//! (the document layer in the app, so open editors update and each file is one
//! undoable step).
use crate::{SearchQuery, iter, query};
use crate::{LiteralRange, Literals, SearchContext, SearchQuery, iter, query};
use grep_matcher::{Captures, Matcher};
use ide_core::{CancellationToken, IdeError, IdeResult, Pos, Range, TextEdit};
use serde::{Deserialize, Serialize};
@@ -128,10 +128,11 @@ pub fn replacement_edits(
preserve: bool,
only: Option<&[Pos]>,
) -> IdeResult<Vec<TextEdit>> {
edits_except(text, query, replacement, preserve, only, None)
edits_except(text, query, replacement, preserve, only, None, None)
}
/// [`replacement_edits`] leaving out the matches that start at `skip`.
/// [`replacement_edits`] leaving out the matches that start at `skip` and, given the text's
/// comments and string literals, those outside the query's [`crate::SearchContext`].
fn edits_except(
text: &str,
query: &SearchQuery,
@@ -139,6 +140,7 @@ fn edits_except(
preserve: bool,
only: Option<&[Pos]>,
skip: Option<&[Pos]>,
literals: Option<&[LiteralRange]>,
) -> IdeResult<Vec<TextEdit>> {
if query.pattern.is_empty() {
return Ok(Vec::new());
@@ -153,10 +155,13 @@ fn edits_except(
let mut caps = matcher.new_captures().map_err(|e| IdeError::internal(e.to_string()))?;
let mut edits = Vec::new();
let mut buf = Vec::new();
iter::for_each_captures(matcher, haystack, &mut caps, |caps| {
iter::for_each_captures(matcher, compiled.whole_word, haystack, &mut caps, |caps| {
let Some(m) = caps.get(0) else { return };
let start = lines.pos(m.start());
if only.as_ref().is_some_and(|o| !o.contains(&start)) || skip.contains(&start) {
if only.as_ref().is_some_and(|o| !o.contains(&start))
|| skip.contains(&start)
|| literals.is_some_and(|l| !query.context.keeps(l, m.start()))
{
return;
}
let mut new_text = if query.is_regex {
@@ -227,6 +232,23 @@ pub fn replace_files(
cancel: &CancellationToken,
on_event: &dyn Fn(ReplaceEvent),
) -> IdeResult<ReplaceSummary> {
replace_files_in_context(host, query, replacement, preserve, targets, None, cancel, on_event)
}
/// [`replace_files`] honouring [`SearchQuery::context`] with the comments and string literals
/// `literals` finds, as [`crate::search_in_context`] does; without it every match is plain code.
#[allow(clippy::too_many_arguments)]
pub fn replace_files_in_context(
host: &dyn ReplaceHost,
query: &SearchQuery,
replacement: &str,
preserve: bool,
targets: &[ReplaceTarget],
literals: Option<Literals<'_>>,
cancel: &CancellationToken,
on_event: &dyn Fn(ReplaceEvent),
) -> IdeResult<ReplaceSummary> {
let literals = literals.filter(|_| query.context != SearchContext::Any);
// Fail fast on an invalid pattern instead of once per file.
if !query.pattern.is_empty() {
query::compile(query)?;
@@ -244,8 +266,14 @@ pub fn replace_files(
if only.is_some_and(|o| o.is_empty()) {
continue;
}
let result =
host.edit_file(&target.path, &mut |text| edits_except(text, query, replacement, preserve, only, skip));
let result = host.edit_file(&target.path, &mut |text| {
let found = match literals.map(|l| l(&target.path, text)) {
// No syntax tree: nothing is in a comment or string, as in the search.
Some(None) if query.context.needs_literals() => return Ok(Vec::new()),
found => found.map(Option::unwrap_or_default),
};
edits_except(text, query, replacement, preserve, only, skip, found.as_deref())
});
match result {
Ok(n) => {
if n > 0 {
+45 -2
View File
@@ -1,7 +1,7 @@
use ide_core::{CancellationToken, IdeError, IdeResult, Pos, TextEdit};
use ide_search::{
ReplaceEvent, ReplaceHost, ReplaceTarget, SearchQuery, SearchScope, preserve_case, preview, replace_files,
replacement_edits,
LiteralKind, LiteralRange, ReplaceEvent, ReplaceHost, ReplaceTarget, SearchQuery, SearchScope, preserve_case,
preview, replace_files, replace_files_in_context, replacement_edits,
};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
@@ -169,3 +169,46 @@ fn replace_files_respects_selected_matches_and_invalid_patterns() {
let err = replace_files(&docs, &regex("("), "x", false, &t, &CancellationToken::new(), &|_| {}).unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
}
/// `// …` comments and `"…"` strings of `.rs` files; other files have no syntax tree.
fn toy_literals(path: &Path, text: &str) -> Option<Vec<LiteralRange>> {
if path.extension().is_none_or(|e| e != "rs") {
return None;
}
let mut out = Vec::new();
for (i, _) in text.match_indices("//") {
let end = text[i..].find('\n').map_or(text.len(), |n| i + n);
out.push(LiteralRange { start: i, end, kind: LiteralKind::Comment });
}
let quotes: Vec<usize> = text.match_indices('"').map(|(i, _)| i).collect();
for pair in quotes.chunks(2) {
if let [a, b] = pair {
out.push(LiteralRange { start: *a, end: b + 1, kind: LiteralKind::String });
}
}
out.sort_by_key(|l| l.start);
Some(out)
}
#[test]
fn replace_files_in_context_keeps_to_the_search_context() {
use ide_search::SearchContext as C;
let text = "foo(\"foo\"); // foo\nfoo\n";
let plain = "foo // foo\n";
let cases = [
(C::Any, "x(\"x\"); // x\nx\n", "x // x\n"),
(C::InComments, "foo(\"foo\"); // x\nfoo\n", plain),
(C::InStringLiterals, "foo(\"x\"); // foo\nfoo\n", plain),
(C::ExceptComments, "x(\"x\"); // foo\nx\n", "x // x\n"),
(C::ExceptStringLiterals, "x(\"foo\"); // x\nx\n", "x // x\n"),
(C::ExceptCommentsAndStringLiterals, "x(\"foo\"); // foo\nx\n", "x // x\n"),
];
for (context, in_rs, in_txt) in cases {
let docs = FakeDocs::with(&[("a.rs", text), ("b.txt", plain)]);
let q = SearchQuery { context, ..query("foo") };
let t = targets(&["a.rs", "b.txt"]);
replace_files_in_context(&docs, &q, "x", false, &t, Some(&toy_literals), &CancellationToken::new(), &|_| {})
.unwrap();
assert_eq!((docs.text("a.rs").as_str(), docs.text("b.txt").as_str()), (in_rs, in_txt), "{context:?}");
}
}
+65
View File
@@ -132,6 +132,36 @@ fn whole_word() {
assert_eq!(views[0].matches[0].ranges, vec![(0, 3), (27, 30), (32, 35)]);
}
/// IDEA's whole word: a word boundary is needed only at an edge where the match has an
/// identifier character; a punctuation edge only needs a different character beside it.
#[test]
fn whole_word_needs_a_boundary_only_at_identifier_edges() {
let starts = |text: &str, q: SearchQuery| -> Vec<usize> {
let q = SearchQuery { whole_word: true, ..q };
ide_search::match_ranges(text, &q).unwrap().into_iter().map(|r| r.0).collect()
};
let text = "doWork(arg); redoWork(x); list: string[] = [];";
assert_eq!(starts(text, query("doWork(")), [0]);
assert_eq!(starts(text, query("(arg)")), [6]);
assert_eq!(starts(text, query("[]")), [38, 43]);
assert_eq!(starts(text, query("list")), [26]);
assert_eq!(starts("a == b; c === d", query("==")), [2]);
// `$` is part of an identifier (Java, Kotlin, JavaScript).
assert_eq!(starts("foo$bar foo", query("foo")), [8]);
// After an escape such as `\n`, a word starts.
assert_eq!(starts(r#"s = "\nfoo";"#, query("foo")), [7]);
assert_eq!(starts("é1 1 éé", query("1")), [4]);
// Regex matches follow the same rule.
assert_eq!(starts(text, regex(r"\w+\(")), [0, 13]);
assert_eq!(starts(text, regex(r"\[\]")), [38, 43]);
let p = project(&[("a.ts", text.as_bytes())]);
let (views, summary) = run(p.path(), &SearchQuery { whole_word: true, ..query("[]") });
assert_eq!((summary.matches, views[0].matches[0].ranges.clone()), (2, vec![(38, 40), (43, 45)]));
let (out, n) = replace_in_text(text, &SearchQuery { whole_word: true, ..query("doWork(") }, "run(").unwrap();
assert_eq!((out.as_str(), n), ("run(arg); redoWork(x); list: string[] = [];", 1));
}
#[test]
fn invalid_regex_is_reported() {
let p = project(&[("a.txt", b"x\n")]);
@@ -431,6 +461,41 @@ fn long_lines_are_truncated() {
assert_eq!(second.text, "short needle");
}
#[test]
fn every_match_of_a_long_line_is_reported_in_its_own_window() {
let long = format!("a='needle';{}b='needle';{}needle!\n", "x".repeat(2000), "y".repeat(2000));
let p = project(&[("min.js", long.as_bytes())]);
let (views, summary) = run(p.path(), &query("needle"));
assert_eq!(summary.matches, 3);
let lines = &views[0].matches;
assert_eq!(lines.len(), 3, "one window per far-apart match");
let line_utf16: Vec<u16> = long.trim_end().encode_utf16().collect();
let mut starts = Vec::new();
for m in lines {
assert_eq!(m.line, 0);
assert!(m.text.encode_utf16().count() <= 500);
let [(a, b)] = m.ranges[..] else { panic!("{:?}", m.ranges) };
let text: Vec<u16> = m.text.encode_utf16().collect();
assert_eq!(String::from_utf16(&text[a as usize..b as usize]).unwrap(), "needle");
let col = (m.text_offset + a) as usize;
assert_eq!(String::from_utf16(&line_utf16[col..col + 6]).unwrap(), "needle");
starts.push(ide_core::Pos::new(0, m.text_offset + a));
}
// The reported positions are the ones Replace takes: all of them are replaced.
let edits = ide_search::replacement_edits(&long, &query("needle"), "pin", false, Some(&starts)).unwrap();
assert_eq!(edits.len(), 3);
assert!(!ide_search::apply_edits(&long, &edits).contains("needle"));
}
#[test]
fn match_limit_counts_every_match_of_a_long_line() {
let long = format!("needle{}needle{}needle\n", "x".repeat(1000), "y".repeat(1000));
let p = project(&[("min.js", long.as_bytes())]);
let (views, summary) = run(p.path(), &SearchQuery { max_matches: 2, ..query("needle") });
assert!(summary.limit_hit);
assert_eq!((summary.matches, total(&views)), (2, 2));
}
#[test]
fn multi_line_matches() {
let p = project(&[("a.rs", b"fn foo() {\n bar();\n}\nfoo\nbar\n")]);
+6 -4
View File
@@ -640,11 +640,13 @@ async fn with_key(handle: &mut Handle<Client>, user: &str, key: keys::PrivateKey
}
/// Every identity of the running SSH agent, until one is accepted.
async fn with_agent(handle: &mut Handle<Client>, user: &str) -> bool {
async fn with_agent(handle: &mut Handle<Client>, hop: &Hop) -> bool {
let user = hop.user.as_str();
let Some(socket) = hop.agent.socket() else { return false };
#[cfg(unix)]
let agent = keys::agent::client::AgentClient::connect_env().await;
let agent = keys::agent::client::AgentClient::connect_uds(socket).await;
#[cfg(windows)]
let agent = keys::agent::client::AgentClient::connect_named_pipe(r"\\.\pipe\openssh-ssh-agent").await;
let agent = keys::agent::client::AgentClient::connect_named_pipe(socket).await;
let Ok(mut agent) = agent else { return false };
let Ok(identities) = agent.request_identities().await else { return false };
let hash = rsa_hash(handle).await;
@@ -693,7 +695,7 @@ async fn authenticate(
if handle.authenticate_none(user).await.map(|r| r.success()).unwrap_or(false) {
return Ok(());
}
if with_agent(handle, user).await {
if with_agent(handle, hop).await {
return Ok(());
}
let files: Vec<PathBuf> = if hop.identity_files.is_empty() {
+95 -1
View File
@@ -53,6 +53,65 @@ pub(crate) struct Hop {
pub proxy_command: Option<String>,
pub host_key_policy: HostKeyPolicy,
pub known_hosts: Option<PathBuf>,
pub agent: Agent,
}
/// Where the SSH agent of a hop listens (`IdentityAgent`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Agent {
/// `SSH_AUTH_SOCK` (the OpenSSH pipe on Windows when it is unset).
Default,
/// `IdentityAgent none`, or an unset `$VARIABLE`.
Off,
Socket(PathBuf),
}
impl Agent {
/// The socket (or Windows pipe) to connect to, `None` for no agent.
pub fn socket(&self) -> Option<PathBuf> {
match self {
Agent::Off => None,
Agent::Socket(path) => Some(path.clone()),
Agent::Default => {
let var = env_var("SSH_AUTH_SOCK").filter(|v| !v.is_empty()).map(PathBuf::from);
if cfg!(windows) {
// Only a pipe works there; a Unix socket path comes from MSYS or WSL tools.
let pipe = var.filter(|p| p.to_string_lossy().starts_with(r"\\.\pipe\"));
Some(pipe.unwrap_or_else(|| PathBuf::from(r"\\.\pipe\openssh-ssh-agent")))
} else {
var
}
}
}
}
}
/// A variable as the user's shell sees it. An app started from Finder or the Dock has the
/// login session's environment; the shell's rc files may set another value (an SSH agent
/// socket exported in `~/.zshrc`), and that is the one `ssh` in a terminal uses.
fn env_var(name: &str) -> Option<std::ffi::OsString> {
ide_core::process::login_env()
.and_then(|vars| vars.iter().find(|(k, _)| k == name).map(|(_, v)| v.clone()))
.or_else(|| std::env::var_os(name))
}
/// `IdentityAgent`: `none`, `SSH_AUTH_SOCK`, `$VARIABLE`, or a path (`~` and `%` tokens expanded).
fn identity_agent(value: Option<&str>, expand_path: impl Fn(&str) -> PathBuf) -> Agent {
let Some(value) = value.map(str::trim).filter(|v| !v.is_empty()) else { return Agent::Default };
if value.eq_ignore_ascii_case("none") {
return Agent::Off;
}
if value == "SSH_AUTH_SOCK" {
return Agent::Default;
}
if let Some(name) = value.strip_prefix('$') {
let name = name.strip_prefix('{').and_then(|n| n.strip_suffix('}')).unwrap_or(name);
return match env_var(name).filter(|v| !v.is_empty()) {
Some(path) => Agent::Socket(expand(&path.to_string_lossy())),
None => Agent::Off,
};
}
Agent::Socket(expand_path(value))
}
/// `StrictHostKeyChecking`: what happens to a host key missing from `known_hosts`.
@@ -98,6 +157,7 @@ struct RawConfig {
proxy_command: Option<String>,
host_key_policy: Option<HostKeyPolicy>,
user_known_hosts_file: Option<String>,
identity_agent: Option<String>,
}
fn strip_quotes(s: &str) -> &str {
@@ -444,6 +504,11 @@ fn parse_config_file(
});
}
}
"identityagent" => {
if out.identity_agent.is_none() {
out.identity_agent = Some(strip_quotes(value).to_owned());
}
}
"userknownhostsfile" => {
if out.user_known_hosts_file.is_none()
&& let Some(first) = split_args(value).into_iter().next()
@@ -492,7 +557,9 @@ fn config_hop(
};
let host_key_policy =
if null_known_hosts { HostKeyPolicy::Off } else { raw.host_key_policy.unwrap_or(HostKeyPolicy::Ask) };
let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts };
let agent =
identity_agent(raw.identity_agent.as_deref(), |p| expand(&expand_tokens(p, alias, &host, port, &user, &local)));
let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts, agent };
(hop, proxy_jump)
}
@@ -529,6 +596,7 @@ pub(crate) fn resolve_hops(target: &SshTarget, config: Option<&Path>) -> IdeResu
proxy_command: None,
host_key_policy: HostKeyPolicy::Ask,
known_hosts: None,
agent: Agent::Default,
},
None,
)
@@ -594,6 +662,32 @@ mod tests {
assert!(resolve_hops(&SshTarget::default(), None).is_err());
}
#[test]
fn identity_agent_picks_the_agent_of_each_hop() {
let tmp = tempfile::tempdir().unwrap();
let config = tmp.path().join("config");
std::fs::write(
&config,
"Host vault\n IdentityAgent \"~/agents/%h.sock\"\n ProxyJump plain\n\n\
Host off\n IdentityAgent none\n\nHost shell\n IdentityAgent ${OPENIDEA_TEST_AGENT}\n\n\
Host unset\n IdentityAgent $OPENIDEA_TEST_UNSET_AGENT\n\nHost env\n IdentityAgent SSH_AUTH_SOCK\n",
)
.unwrap();
// Exported only by the shell's rc files, as a GUI app sees it (#4934).
ide_core::process::set_shell_env(vec![("OPENIDEA_TEST_AGENT".into(), "/run/agent.sock".into())]);
let agent = |host: &str| {
let target = SshTarget { host: host.into(), auth: SshAuth::OpenSsh, ..Default::default() };
resolve_hops(&target, Some(&config)).unwrap().into_iter().map(|h| h.agent).collect::<Vec<_>>()
};
let home = home().unwrap();
assert_eq!(agent("vault"), [Agent::Default, Agent::Socket(home.join("agents/vault.sock"))]);
assert_eq!(agent("off"), [Agent::Off]);
assert_eq!(agent("shell"), [Agent::Socket("/run/agent.sock".into())]);
assert_eq!(agent("unset"), [Agent::Off]);
assert_eq!(agent("env"), [Agent::Default]);
assert_eq!(Agent::Off.socket(), None);
}
#[test]
fn resolves_include_match_equals_and_proxy_command() {
let tmp = tempfile::tempdir().unwrap();
+43
View File
@@ -384,6 +384,7 @@ fn run_raw_env_once(
.stdout(Stdio::piped())
.stderr(Stdio::piped());
tracing::debug!(?args, "git");
let refresh = IndexRefresh::before(root, args, env);
let mut session = CommandSession::start(&mut cmd);
let mut child = cmd.spawn().map_err(spawn_error)?;
let writer = match (stdin, child.stdin.take()) {
@@ -401,9 +402,49 @@ fn run_raw_env_once(
let _ = w.join();
}
session.finish(out.status.success(), &String::from_utf8_lossy(&out.stderr));
refresh.after();
Ok(Output { stdout: out.stdout, stderr: out.stderr, code: out.status.code() })
}
/// `git diff` against the working tree rewrites the index when it meets files whose stat data
/// is stale (`diff.autoRefreshIndex`), even under `--no-optional-locks`. Like status's
/// write-back, that is a side effect of reading: recorded as ours, watchers don't report it as
/// a repository change. Otherwise a view that re-reads on repository changes re-triggers itself,
/// endlessly where git and gix disagree on stat data (Windows, #4792).
struct IndexRefresh(Option<(PathBuf, crate::index_writes::Stamp)>);
impl IndexRefresh {
fn before(root: &Path, args: &[&str], env: &[(&str, &std::ffi::OsStr)]) -> Self {
let reads_worktree = subcommand(args) == "diff"
&& !args.iter().any(|a| matches!(*a, "--cached" | "--staged" | "--no-index"))
&& !env.iter().any(|(k, _)| *k == "GIT_INDEX_FILE");
Self(reads_worktree.then(|| index_file(root)).flatten().map(|index| {
let stamp = crate::index_writes::stamp(&index);
(index, stamp)
}))
}
fn after(self) {
if let Some((index, stamp)) = self.0
&& !stamp.still_holds(&index)
{
crate::index_writes::lock().record(&index);
}
}
}
/// The index of the working tree at `root`: `.git/index`, or a linked worktree's own index
/// in the gitdir its `.git` file names.
fn index_file(root: &Path) -> Option<PathBuf> {
let dot_git = root.join(".git");
if dot_git.is_dir() {
return Some(dot_git.join("index"));
}
let text = std::fs::read_to_string(&dot_git).ok()?;
let dir = Path::new(text.trim().strip_prefix("gitdir:")?.trim());
Some(root.join(dir).join("index"))
}
/// Captures binary/NUL-delimited read output while allowing cancellation to kill git.
pub(crate) fn run_cancellable(root: &Path, args: &[&str], cancel: &CancellationToken) -> IdeResult<Output> {
let out = run_cancellable_raw(root, args, cancel)?;
@@ -497,6 +538,7 @@ fn run_capture(
.stdout(Stdio::piped())
.stderr(Stdio::piped());
own_group(&mut cmd);
let refresh = IndexRefresh::before(root, args, &[]);
let mut session = CommandSession::start(&mut cmd);
let mut child = cmd.spawn().map_err(spawn_error)?;
let writer = match (stdin, child.stdin.take()) {
@@ -550,6 +592,7 @@ fn run_capture(
};
let out = Output { stdout: join(stdout)?, stderr: join(stderr)?, code: status.code() };
session.finish(status.success(), &String::from_utf8_lossy(&out.stderr));
refresh.after();
if out.stdout.len() > max || out.stderr.len() > max {
return Err(IdeError::invalid(format!("git output exceeds {max} bytes")));
}
+73 -2
View File
@@ -163,7 +163,7 @@ impl Repos {
}
/// Changes of every repository. A nested repository reports its own files, so the
/// enclosing one's "untracked folder" entry for it is dropped. A repository that cannot
/// enclosing one's "untracked folder" entry for it, and its entries inside it, are dropped. A repository that cannot
/// be read (e.g. deleted since the last scan) is left out; fails only when all fail.
///
/// The reads go through [`Backend`], the Changes-view surface — repositories of a
@@ -207,10 +207,13 @@ impl Repos {
continue;
}
};
// A file belongs to its innermost repository: the nested one reports what lies
// inside it, including files the enclosing one still tracks there (#4990).
out.extend(status.into_iter().filter(|f| {
let untracked_root =
f.unstaged == Some(crate::ChangeKind::Untracked) && nested.iter().any(|n| f.path.0 == *n);
!untracked_root
let in_nested = nested.iter().any(|n| f.path.0 != *n && f.path.0.starts_with(n));
!untracked_root && !in_nested
}));
}
match first_error {
@@ -315,6 +318,74 @@ mod tests {
assert_eq!(skipped.all().len(), 2);
}
/// A workspace: members in repositories of their own (one with a nested repository, not a
/// submodule), a plain folder, and a member that is a subfolder of a bigger repository; the
/// container's agent folder links to each member and must not add a repository again.
#[cfg(unix)]
#[test]
fn workspace_members_bring_their_repositories_once() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let (api, web, plain, mono) = (base.join("api"), base.join("web"), base.join("plain"), base.join("mono"));
git_init(&api);
git_init(&api.join("libs/sdk"));
git_init(&web);
std::fs::create_dir_all(&plain).unwrap();
git_init(&mono);
let docs = mono.join("docs");
std::fs::create_dir_all(&docs).unwrap();
let container = base.join("ws");
let links = container.join(".openidea/agent-root");
std::fs::create_dir_all(&links).unwrap();
for (name, target) in [("api", &api), ("web", &web), ("plain", &plain), ("docs", &docs)] {
std::os::unix::fs::symlink(target, links.join(name)).unwrap();
// A link elsewhere in the container: never followed either.
std::os::unix::fs::symlink(target, container.join(name)).unwrap();
}
let roots = [container.clone(), api.clone(), web.clone(), plain.clone(), docs.clone()];
let repos = Repos::discover_roots(&roots, &|_| false).unwrap();
let found: Vec<&Path> = repos.all().iter().map(|r| r.root()).collect();
assert_eq!(found, [api.as_path(), &api.join("libs/sdk"), &mono, &web]);
let file = api.join("libs/sdk/lib.rs");
assert_eq!(repos.for_path(&file).unwrap().root(), api.join("libs/sdk"), "a nested file is its own repo's");
assert_eq!(repos.for_path(&docs.join("a.md")).unwrap().root(), mono, "a subfolder member is its repo's");
assert!(repos.for_path(&plain.join("x")).is_none());
}
/// A folder the enclosing repository still tracks became a repository of its own: both
/// report its files, and each file must be listed once, by its innermost repository (#4990).
#[test]
fn a_file_of_a_nested_repository_is_listed_once() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
git_init(&root);
std::fs::create_dir_all(root.join("web")).unwrap();
std::fs::write(root.join("web/page.html"), "v1").unwrap();
let git = |dir: &Path, args: &[&str]| {
let ok = Command::new("git")
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
.args(args)
.current_dir(dir)
.status()
.is_ok_and(|s| s.success());
assert!(ok, "git {args:?}");
};
git(&root, &["add", "."]);
git(&root, &["commit", "-qm", "init"]);
git_init(&root.join("web"));
std::fs::write(root.join("web/page.html"), "v2").unwrap();
std::fs::write(root.join("README.md"), "x").unwrap();
let repos = Repos::discover(&root, &|_| false).unwrap();
assert_eq!(repos.all().len(), 2);
for status in [repos.status().unwrap(), repos.status_paths(&[root.join("web/page.html")]).unwrap()] {
let page: Vec<_> = status.iter().filter(|f| f.path.0 == root.join("web/page.html")).collect();
assert_eq!(page.len(), 1, "{status:?}");
assert_eq!(page[0].rel_path, "page.html", "listed by the nested repository");
}
}
#[test]
fn side_by_side_repositories_without_an_enclosing_one() {
let tmp = tempfile::tempdir().unwrap();
+31 -2
View File
@@ -235,6 +235,12 @@ fn gix_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
Ok((map, conflicts))
}
/// Keeps `git status` from rewriting the index with refreshed stat data. Such a write is not
/// one of ours to the watcher, so it would schedule another refresh, which runs git again (#4792).
fn read_only() -> [(&'static str, &'static std::ffi::OsStr); 1] {
[("GIT_OPTIONAL_LOCKS", std::ffi::OsStr::new("0"))]
}
/// `git status --porcelain=v2`: what git lists, unreadable directories skipped.
/// In Restricted Mode git compares content without the repository's clean/process
/// filters and doesn't ask submodules for their own status (which runs their config).
@@ -245,7 +251,7 @@ fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
if !crate::execution_allowed() {
args.push("--ignore-submodules=dirty");
}
let out = crate::cli::run(r.root(), &args, None)?;
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
}
@@ -260,7 +266,7 @@ fn cli_status_paths(r: &Repo, ignored: &IgnoredNames, paths: &[String]) -> IdeRe
}
args.push("--");
args.extend(paths.iter().map(String::as_str));
let out = crate::cli::run(r.root(), &args, None)?;
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
}
@@ -397,6 +403,29 @@ mod tests {
assert!(staged.stdout.is_empty(), "{}", String::from_utf8_lossy(&staged.stdout));
}
/// #4792: the dirty-scope `git status` must not rewrite the index after refreshing stale
/// stat data, or the watcher sees a foreign index write and refreshes again.
#[test]
fn git_status_of_paths_leaves_the_index_alone() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
git(dir, &["config", "user.name", "Test User"]);
git(dir, &["config", "user.email", "[email protected]"]);
git(dir, &["config", "commit.gpgsign", "false"]);
std::fs::write(dir.join("a.txt"), "a\n").unwrap();
commit_all(dir, "base");
// Same content, new stat data: plain `git status` would refresh and write the index.
std::thread::sleep(std::time::Duration::from_millis(1100));
std::fs::write(dir.join("a.txt"), "a\n").unwrap();
let index = dir.join(".git/index");
let before = std::fs::read(&index).unwrap();
let repo = Repo::discover(dir).unwrap().expect("repository found");
assert!(status_paths(&repo, &["a.txt".to_owned()]).unwrap().is_empty());
assert_eq!(std::fs::read(&index).unwrap(), before, "git status rewrote the index");
}
/// git's porcelain answer (used when gitoxide can't read the tree) matches gitoxide's.
#[test]
fn git_and_gitoxide_report_the_same_status() {
+27
View File
@@ -2288,3 +2288,30 @@ fn status_from_the_git_command_line_matches_the_in_process_one() {
assert_eq!(from_git, in_process);
assert_eq!(from_git.len(), 4, "{from_git:#?}");
}
#[test]
fn a_worktree_diff_refreshing_the_index_is_not_reported_as_a_repository_change() {
let fx = Fixture::new();
fx.write("a.txt", "a\n");
fx.write("b.txt", "b\n");
fx.git(&["add", "."]);
fx.git(&["commit", "-qm", "init"]);
let base = fx.git(&["rev-parse", "HEAD"]);
let index = fx.dir.join(".git/index");
let backdate = |rel: &str| {
let file = std::fs::File::options().write(true).open(fx.dir.join(rel)).unwrap();
file.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(100)).unwrap();
};
// Same content, stale stat data: `git diff` refreshes and rewrites the index while reading.
backdate("a.txt");
let before = std::fs::read(&index).unwrap();
let repo = fx.repo();
assert!(repo.numstat_with_worktree(&base).unwrap().is_empty());
assert_ne!(std::fs::read(&index).unwrap(), before, "git rewrote the index");
assert!(is_own_index_write(&index));
// A write by someone else is still a change.
fx.write("b.txt", "changed\n");
fx.git(&["add", "b.txt"]);
assert!(!is_own_index_write(&index));
}
+299 -96
View File
@@ -13,7 +13,7 @@
use crate::FsBatch;
use crate::rules::{ExcludeMatcher, GitignoreStack};
use ide_core::{IdeError, IdeEvent, IdeResult, SharedSink};
use notify::event::{ModifyKind, RenameMode};
use notify::event::{CreateKind, DataChange, ModifyKind, RemoveKind, RenameMode};
use notify::{ErrorKind, Event, EventKind, PollWatcher, RecommendedWatcher, RecursiveMode, WatcherKind};
use parking_lot::{Condvar, Mutex, RwLock};
use std::collections::{BTreeMap, BTreeSet, HashSet};
@@ -238,17 +238,113 @@ fn event_handler(state: Weak<DirState>, polled: bool) -> impl FnMut(notify::Resu
match event {
Ok(event) if !is_change_event(&event) => {}
Ok(event) if polled && is_dir_touch(&event) => {}
Ok(event) => {
state.queue.lock().push(event, Instant::now());
state.wake.notify_one();
}
Ok(event) => state.enqueue(event),
Err(e) => tracing::warn!("file watcher: {e}"),
}
}
}
/// A directory's own mtime moving as entries come and go: polling sees it, the
/// OS watchers report only the entries (also seen, through that directory's watch).
/// One queued change for a path. A rename without a peer stays a rename so the batch
/// resolves its existence after the quiet window, as it always did.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PathChange {
Change(Change),
Rename,
}
/// The per-path result of one raw event, in arrival order. `merge` in the batch is
/// order-sensitive (create+remove ≠ remove+create), so a path keeps its sequence of
/// distinct changes, with repetitions collapsed. A storm repeating the same change
/// still leaves one entry per path; the order of real transitions is preserved.
#[derive(Default)]
struct QueuedChanges {
paths: BTreeMap<PathBuf, Vec<PathChange>>,
}
impl QueuedChanges {
fn push(&mut self, path: PathBuf, change: PathChange) {
let changes = self.paths.entry(path).or_default();
if changes.last() != Some(&change) {
changes.push(change);
}
}
}
/// The per-path changes one raw event contributes, classified exactly as `batch_detailed`
/// classifies it. A rename with both paths keeps from/removal and to/creation apart; one
/// without a peer is left for the batch to resolve by the path's existence.
fn queue_changes(filter: &EventFilter, event: &Event, out: &mut QueuedChanges) {
// `classify` drops `.git/info/exclude` as VCS noise (the index handles it), but
// `batch_detailed` needs the event to reload repo-level ignore rules. Keep it queued;
// classification at batch time still drops it from the reported paths.
let mut classify = |path: &Path, change: Change| {
if path.ends_with(".git/info/exclude") {
out.push(path.to_path_buf(), PathChange::Change(change));
} else {
// `classify` applies the VCS/atomic-temp filters and merges; we only need to
// know the resulting single change for this one event at this path.
let mut one = BTreeMap::new();
filter.classify(path, change, &mut one);
for (_, merged) in one {
out.push(path.to_path_buf(), PathChange::Change(merged));
}
}
};
// A rename without a peer keeps the same resolution the batch applies to its
// `Modify(Name(_))` arm (created if the path exists, removed otherwise).
let renamed = |path: &Path| {
if path.symlink_metadata().is_ok() { Change::Created } else { Change::Removed }
};
match event.kind {
EventKind::Create(_) => {
for path in &event.paths {
classify(path, Change::Created);
}
}
EventKind::Remove(_) => {
for path in &event.paths {
classify(path, Change::Removed);
}
}
EventKind::Modify(ModifyKind::Name(RenameMode::Both)) => {
if let [from, to] = event.paths.as_slice() {
classify(from, Change::Removed);
classify(to, Change::Created);
} else {
// Some backends emit a `Both` rename with a missing endpoint.
for path in &event.paths {
classify(path, renamed(path));
}
}
}
EventKind::Modify(ModifyKind::Name(RenameMode::From)) => {
for path in &event.paths {
classify(path, Change::Removed);
}
}
EventKind::Modify(ModifyKind::Name(RenameMode::To)) => {
for path in &event.paths {
classify(path, Change::Created);
}
}
EventKind::Modify(ModifyKind::Name(_)) => {
// Defer resolution: the batch checks existence after the quiet window, so a
// file created and removed within one window is not reported as created.
for path in &event.paths {
out.push(path.clone(), PathChange::Rename);
}
}
EventKind::Modify(_) | EventKind::Any | EventKind::Other => {
for path in &event.paths {
classify(path, Change::Modified);
}
}
EventKind::Access(_) => {}
}
}
/// A directory's own mtime moving as entries come and go. Polling also reports
/// each changed entry through that directory's watch.
fn is_dir_touch(event: &notify::Event) -> bool {
matches!(event.kind, EventKind::Modify(_)) && event.paths.iter().all(|p| p.is_dir())
}
@@ -280,11 +376,13 @@ fn watcher_error(what: &str, error: notify::Error) -> IdeError {
}
}
/// Only adjacent identical file modifications are redundant before classification.
/// Keep the arrival window separately so compaction cannot extend MAX_DELAY.
/// Events waiting for the debounce window, coalesced by path: each path keeps its distinct
/// changes in arrival order, so a storm repeating one change collapses to a single entry
/// while the batch still sees the exact sequence it would have received. Memory is bounded
/// by the number of paths and real transitions touched in the window, not by raw events.
#[derive(Default)]
struct PendingEvents {
events: Vec<Event>,
changes: BTreeMap<PathBuf, Vec<PathChange>>,
first: Option<Instant>,
last: Option<Instant>,
received: usize,
@@ -292,32 +390,61 @@ struct PendingEvents {
impl PendingEvents {
fn is_empty(&self) -> bool {
self.events.is_empty()
self.changes.is_empty()
}
fn push(&mut self, event: Event, now: Instant) {
fn add(&mut self, changes: QueuedChanges, now: Instant) {
self.first.get_or_insert(now);
self.last = Some(now);
self.received += 1;
let redundant = event.paths.len() == 1
&& event.flag().is_none()
&& matches!(event.kind, EventKind::Modify(ModifyKind::Any | ModifyKind::Data(_) | ModifyKind::Metadata(_)))
&& self.events.last().is_some_and(|previous| {
// Reject different spellings before Path's component-wise equality.
// Keeping a normalized alias is safe; only exact duplicates compact.
previous.paths.len() == 1
&& previous.paths[0].as_os_str() == event.paths[0].as_os_str()
&& previous == &event
&& previous.attrs.process_id() == event.attrs.process_id()
});
if !redundant {
self.events.push(event);
for (path, kinds) in changes.paths {
let queued = self.changes.entry(path).or_default();
for kind in kinds {
if queued.last() != Some(&kind) {
queued.push(kind);
}
}
}
}
fn deadline(&self) -> Option<Instant> {
Some((self.last? + DEBOUNCE).min(self.first? + MAX_DELAY))
}
/// Rebuild the events for `batch_detailed`, in the order each path received them.
/// `merge` is order-sensitive, so this preserves the exact transition sequence with
/// repetitions removed. A rename is emitted as `Modify(Name(Any))` so its existence
/// check stays in the batch, and a transient path stays a create+remove pair.
fn into_events(self) -> Vec<Event> {
self.changes
.into_iter()
.flat_map(|(path, changes)| {
changes
.into_iter()
.flat_map(|kind| {
let event = match kind {
PathChange::Rename => Event::new(EventKind::Modify(ModifyKind::Name(RenameMode::Any))),
PathChange::Change(Change::Created) => Event::new(EventKind::Create(CreateKind::File)),
PathChange::Change(Change::Removed) => Event::new(EventKind::Remove(RemoveKind::File)),
PathChange::Change(Change::Modified) => {
Event::new(EventKind::Modify(ModifyKind::Data(DataChange::Content)))
}
// Any kind classifies a VCS path as `Vcs` again, except a modified
// directory, which the batch drops as a lock-file touch.
PathChange::Change(Change::Vcs) => Event::new(EventKind::Create(CreateKind::Any)),
PathChange::Change(Change::Transient) => {
return vec![
Event::new(EventKind::Create(CreateKind::File)).add_path(path.clone()),
Event::new(EventKind::Remove(RemoveKind::File)).add_path(path.clone()),
];
}
};
vec![event.add_path(path.clone())]
})
.collect::<Vec<_>>()
})
.collect()
}
}
/// Shared with the notify callback (weakly) and the debounce thread.
@@ -340,6 +467,19 @@ impl DirState {
self.stop.load(Ordering::SeqCst)
}
/// Coalesces one raw event into the pending batch. Everything `batch_detailed` does to
/// a path (VCS metadata, atomic-save temps, `merge` of repeated changes) is applied here
/// through `classify`, so the batch gets the same final state per path it always did.
fn enqueue(&self, event: Event) {
let mut changes = QueuedChanges::default();
queue_changes(&self.filter, &event, &mut changes);
if changes.paths.is_empty() {
return;
}
self.queue.lock().add(changes, Instant::now());
self.wake.notify_one();
}
/// Debounce loop: finishes any deferred startup watches, then waits for a
/// quiet period and processes each batch. `polled` is whether the watcher
/// already polls.
@@ -372,13 +512,15 @@ impl DirState {
}
std::mem::take(&mut *q)
};
// A scan may publish a path before its create event is delivered:
// keep create + remove pairs so the consumer still sees the removal.
let processing = Instant::now();
let queue_age_ms = processing.duration_since(events.first.expect("nonempty event queue")).as_millis();
let received = events.received;
let queued = events.events.len();
let (mut batch, rule_dirs) = self.filter.batch_detailed(&events.events);
// One event can contribute two path changes (a `Both` rename), so the queued
// count can exceed the raw event count; never let the log arithmetic underflow.
let queued = events.changes.values().map(Vec::len).sum::<usize>();
let coalesced = received.saturating_sub(queued);
let events = events.into_events();
let (mut batch, rule_dirs) = self.filter.batch_detailed(&events);
if self.mode == WatchMode::PerDirectory {
self.update_watches(&mut batch, &rule_dirs);
// Again once polling: a refused directory was not read, and
@@ -393,7 +535,7 @@ impl DirState {
tracing::debug!(
received,
queued,
coalesced = received - queued,
coalesced,
queue_age_ms,
processing_ms,
callback_ms = callback.elapsed().as_millis(),
@@ -728,6 +870,9 @@ impl EventFilter {
Err(_) => None,
};
let change = match rel.and_then(Self::git_internal) {
// Windows also reports a directory modification when Git creates or removes a lock.
// The entries carry the actual changes, including edits to a linked worktree's gitfile.
Some(true) if change == Change::Modified && path.is_dir() => return,
Some(true) => Change::Vcs,
Some(false) => return,
None if crate::encoding::is_atomic_temp(path) => return,
@@ -873,78 +1018,91 @@ mod tests {
Event { kind, paths, attrs: Default::default() }
}
fn push_event(pending: &mut PendingEvents, filter: &EventFilter, event: &Event) {
let mut changes = QueuedChanges::default();
queue_changes(filter, event, &mut changes);
pending.add(changes, Instant::now());
}
/// Evidence for the bounded queue (issue #3936): 100,000 notifications over 1,000
/// distinct paths, measured before (one raw event each) and after (one change per path).
/// `cargo test -p ide-vfs --release --lib -- --ignored --nocapture storm_coalescing_numbers`
#[test]
#[ignore = "prints queued entries for a storm; see issue #3936"]
fn storm_coalescing_numbers() {
let root = PathBuf::from("/proj");
let filter = EventFilter::new(root.clone(), &[]);
let mut pending = PendingEvents::default();
for i in 0..100_000 {
let event = ev(
EventKind::Modify(ModifyKind::Data(DataChange::Content)),
vec![root.join(format!("src/{}.zig", i % 1_000))],
);
push_event(&mut pending, &filter, &event);
}
let queued = pending.changes.values().map(Vec::len).sum::<usize>();
// One entry per path: a repeat of the same change never grows the queue.
assert_eq!(queued, 1_000);
println!("100,000 raw events over 1,000 paths -> {queued} queued changes (lossless final states)");
}
#[test]
fn pending_modifications_keep_the_original_debounce_window() {
let start = Instant::now();
// ReadDirectoryChangesW reports ordinary Windows writes as Modify(Any).
let event = ev(EventKind::Modify(ModifyKind::Any), vec!["file.rs".into()]);
let mut pending = PendingEvents::default();
assert_eq!(pending.deadline(), None);
for n in 0..10_000 {
pending.push(event.clone(), start + Duration::from_micros(n * 95));
let mut changes = QueuedChanges::default();
changes.push("file.rs".into(), PathChange::Change(Change::Modified));
pending.add(changes, start + Duration::from_micros(n * 95));
}
assert_eq!(pending.received, 10_000);
assert_eq!(pending.events.len(), 1);
assert_eq!(pending.changes.len(), 1);
assert_eq!(pending.first, Some(start));
assert_eq!(pending.last, Some(start + Duration::from_micros(9_999 * 95)));
assert_eq!(pending.deadline(), Some(start + MAX_DELAY));
let drained = std::mem::take(&mut pending);
assert_eq!(drained.events, vec![event.clone()]);
assert_eq!(drained.into_events().len(), 1);
assert!(pending.is_empty());
assert_eq!(pending.deadline(), None);
pending.push(event, start + MAX_DELAY);
let mut changes = QueuedChanges::default();
changes.push("file.rs".into(), PathChange::Change(Change::Modified));
pending.add(changes, start + MAX_DELAY);
assert_eq!(pending.received, 1);
assert_eq!(pending.deadline(), Some(start + MAX_DELAY + DEBOUNCE));
}
#[test]
fn pending_events_preserve_boundaries_and_attributes() {
let now = Instant::now();
let modify = ev(EventKind::Modify(ModifyKind::Data(DataChange::Content)), vec!["a".into()]);
let variants = [
modify.clone().set_tracker(1),
modify.clone().set_info("backend detail"),
modify.clone().set_process_id(2),
modify.clone().set_flag(notify::event::Flag::Rescan),
modify.clone().add_path("b".into()),
ev(EventKind::Create(CreateKind::File), vec!["a".into()]),
ev(EventKind::Remove(RemoveKind::File), vec!["a".into()]),
ev(EventKind::Modify(ModifyKind::Name(RenameMode::Both)), vec!["a".into(), "b".into()]),
ev(EventKind::Modify(ModifyKind::Name(RenameMode::From)), vec!["a".into()]),
ev(EventKind::Modify(ModifyKind::Name(RenameMode::To)), vec!["a".into()]),
ev(EventKind::Any, vec!["a".into()]),
];
for middle in variants {
let events = vec![modify.clone(), middle, modify.clone()];
let mut pending = PendingEvents::default();
for event in &events {
pending.push(event.clone(), now);
}
assert_eq!(pending.events, events);
}
let mut interleaved = PendingEvents::default();
for event in [
modify.clone(),
modify.clone().set_kind(EventKind::Create(CreateKind::File)).add_path("b".into()),
modify.clone(),
fn pending_coalesces_a_storm_into_one_change_per_path() {
let root = PathBuf::from("/proj");
let filter = EventFilter::new(root.clone(), &[]);
let mut pending = PendingEvents::default();
// create → modify → modify → remove resolves to the final state of the path;
// the event stream is lossless for every consumer that sees that final state.
for kind in [
EventKind::Create(CreateKind::File),
EventKind::Modify(ModifyKind::Data(DataChange::Content)),
EventKind::Modify(ModifyKind::Data(DataChange::Content)),
] {
interleaved.push(event, now);
}
assert_eq!(interleaved.events.len(), 3);
let mut interleaved = PendingEvents::default();
for event in [modify.clone(), ev(modify.kind, vec!["b".into()]), modify.clone()] {
interleaved.push(event, now);
}
assert_eq!(interleaved.events.len(), 3);
for event in [
modify.set_flag(notify::event::Flag::Rescan),
ev(EventKind::Modify(ModifyKind::Name(RenameMode::From)), vec!["a".into()]),
] {
let mut pending = PendingEvents::default();
pending.push(event.clone(), now);
pending.push(event, now);
assert_eq!(pending.events.len(), 2);
push_event(&mut pending, &filter, &ev(kind, vec![root.join("a.zig")]));
}
assert_eq!(
pending.changes[&root.join("a.zig")],
vec![PathChange::Change(Change::Created), PathChange::Change(Change::Modified)]
);
push_event(&mut pending, &filter, &ev(EventKind::Remove(RemoveKind::File), vec![root.join("a.zig")]));
assert_eq!(
pending.changes[&root.join("a.zig")],
vec![
PathChange::Change(Change::Created),
PathChange::Change(Change::Modified),
PathChange::Change(Change::Removed)
]
);
push_event(&mut pending, &filter, &ev(EventKind::Create(CreateKind::File), vec![root.join("b.zig")]));
assert_eq!(pending.changes.len(), 2);
assert_eq!(pending.received, 5);
}
#[test]
@@ -958,15 +1116,16 @@ mod tests {
assert_ne!(paths[0].as_os_str(), paths[1].as_os_str());
let events: Vec<_> =
paths.into_iter().map(|path| Event::new(EventKind::Modify(ModifyKind::Any)).add_path(path)).collect();
let filter = EventFilter::new(root.clone(), &[]);
let mut pending = PendingEvents::default();
for event in &events {
pending.push(event.clone(), Instant::now());
let mut changes = QueuedChanges::default();
queue_changes(&filter, event, &mut changes);
pending.add(changes, Instant::now());
}
assert_eq!(pending.events.len(), events.len());
assert_same_batch(
&EventFilter::new(root.clone(), &[]).batch(&events),
&EventFilter::new(root, &[]).batch(&pending.events),
);
// Path equality merges the spellings; one final state is all any consumer can see.
assert_eq!(pending.changes.len(), 1);
assert_same_batch(&filter.batch(&events), &EventFilter::new(root, &[]).batch(&pending.into_events()));
}
fn assert_same_batch(left: &FsBatch, right: &FsBatch) {
@@ -995,29 +1154,37 @@ mod tests {
EventKind::Modify(ModifyKind::Metadata(MetadataKind::WriteTime)),
EventKind::Modify(ModifyKind::Name(RenameMode::From)),
EventKind::Modify(ModifyKind::Name(RenameMode::To)),
// The macOS FSEvents rename (no peer), and whole-event kinds the batch handles.
EventKind::Modify(ModifyKind::Name(RenameMode::Any)),
EventKind::Modify(ModifyKind::Name(RenameMode::Other)),
EventKind::Any,
EventKind::Other,
// A `Both` rename missing its second endpoint (some inotify backends).
EventKind::Modify(ModifyKind::Name(RenameMode::Both)),
];
// All four-event histories, with both present and absent final state.
// All three-event histories, with both present and absent final state.
for rel in ["source.rs", "file.ignored", "excluded/source.rs", ".git/HEAD"] {
let path = root.join(rel);
for exists in [false, true] {
if exists {
std::fs::write(&path, "x").unwrap();
}
for code in 0..kinds.len().pow(4) {
for code in 0..kinds.len().pow(3) {
let mut code = code;
let mut events = Vec::new();
let mut pending = PendingEvents::default();
for _ in 0..4 {
let filter = EventFilter::new(root.clone(), &excludes);
for _ in 0..3 {
let event = ev(kinds[code % kinds.len()], vec![path.clone()]);
code /= kinds.len();
// Each event is repeated to exercise compaction after transitions.
// Each event is repeated to exercise coalescing after transitions.
for _ in 0..2 {
events.push(event.clone());
pending.push(event.clone(), Instant::now());
push_event(&mut pending, &filter, &event);
}
}
let plain = EventFilter::new(root.clone(), &excludes).batch(&events);
let compact = EventFilter::new(root.clone(), &excludes).batch(&pending.events);
let compact = EventFilter::new(root.clone(), &excludes).batch(&pending.into_events());
assert_same_batch(&plain, &compact);
}
}
@@ -1053,13 +1220,13 @@ mod tests {
std::fs::write(root.join("new.rs"), "x").unwrap();
let mut pending = PendingEvents::default();
for event in &events {
pending.push(event.clone(), Instant::now());
push_event(&mut pending, &plain, event);
}
let expected = plain.batch(&events);
assert_eq!(expected.ignore_rules, vec![root.clone()]);
assert_eq!(expected.ignored, vec![root.join("file.ignored")]);
assert!(!expected.modified.contains(&root.join("file.ignored")));
assert_same_batch(&expected, &compact.batch(&pending.events));
assert_same_batch(&expected, &compact.batch(&pending.into_events()));
}
}
@@ -1330,6 +1497,43 @@ mod tests {
assert_eq!(g(".git/objects"), Some(false));
}
#[test]
fn git_metadata_directory_touches_do_not_refresh_vcs() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let filter = EventFilter::new(root.clone(), &[]);
let modify = EventKind::Modify(ModifyKind::Any);
for (dir, lock) in
[(".git", "index.lock"), (".git/refs/heads", "main.lock"), (".git/worktrees/wt", "index.lock")]
{
let dir = root.join(dir);
std::fs::create_dir_all(&dir).unwrap();
let lock = dir.join(lock);
let batch = filter.batch(&[
ev(EventKind::Create(CreateKind::File), vec![lock.clone()]),
ev(EventKind::Remove(RemoveKind::File), vec![lock]),
ev(modify, vec![dir.clone()]),
]);
assert!(batch.is_empty(), "{}: {batch:?}", dir.display());
for kind in [EventKind::Create(CreateKind::Folder), EventKind::Remove(RemoveKind::Folder)] {
let batch = filter.batch(&[ev(kind, vec![dir.clone()])]);
assert_eq!(batch.vcs, vec![dir.clone()]);
}
}
let gitfile = root.join("wt/.git");
std::fs::create_dir_all(root.join("wt")).unwrap();
std::fs::write(&gitfile, "gitdir: ../.git/worktrees/wt\n").unwrap();
let index = root.join(".git/index");
let head = root.join(".git/refs/heads/main");
std::fs::write(&index, b"index data").unwrap();
std::fs::write(&head, b"commit id").unwrap();
for path in [gitfile, index, head] {
let batch = filter.batch(&[ev(modify, vec![path.clone()])]);
assert_eq!(batch.vcs, vec![path]);
}
}
#[test]
fn nested_gitignore_and_rule_changes_in_one_batch() {
let tmp = tempfile::tempdir().unwrap();
@@ -1941,8 +2145,7 @@ mod tests {
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(&file, "x").unwrap();
let created = Event::new(EventKind::Create(notify::event::CreateKind::Folder)).add_path(root.join("new"));
inner.state.queue.lock().push(created, Instant::now());
inner.state.wake.notify_all();
inner.state.enqueue(created);
// Written before polling took over, so the poller never reports it.
assert!(wait_for(&batches, |b| all_paths(b).contains(&file)), "{:?}", batches.lock());
// root, a, c, new, new/inner
Loaded 100 of 575 files, more files were not shown because too many files have changed in this diff. Show more