Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 3ddd1ea9b8 fix(vcs): show why checkout was blocked 2026-12-02 19:04:39 +08:00
l0ng-ai 471bce2bb1 test: make the Windows Rust job pass again (#7516)
git_workflows: the 700 overlong paths of the two command-line batching tests exceeded Windows' 260-char MAX_PATH (Git for Windows enforces it without core.longpaths), so git add failed; on Windows they use shorter names that still overflow its 32,000-char command line. xcode_index: the test formatted a path into buildServer.json, and a Windows path's backslashes made the JSON invalid; it is built with serde_json now.
2026-12-02 18:46:03 +08:00
Qslia b630dfad55 fix(notebook): keep source lines whole when typing in a cell (#7502)
Rewriting a cell's source kept every old source element that still prefixed or suffixed the new text, including partial lines, so code typed character by character was saved one character per element and showed one character per line in VS Code and Cursor. Only whole lines (an element ending in a newline, starting at a line start) are reused now; the line being edited is written as one element, the notebook's own JSON layout and string-valued sources stay as they were, and a source already split into characters is joined into lines where it is edited.

Co-authored-by: qslia <[email protected]>
2026-12-02 18:41:09 +08:00
LU XIANGRUIтаwildcatDownstairs 74b50f7592 test(new-project): make apple_app_trees pass on Windows (#7507)
A Windows checkout gives the generator templates CRLF line endings; the test normalizes them before comparing the generated Swift file's first lines. Generated projects are unchanged.

Closes #7506

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:37:42 +08:00
l0ng-ai 95bc3622ab feat(vue): pick the managed Vue language server version per project (#7513)
Vue 2 projects (detected from package.json, or the installed vue for alias/workspace specs) use vue-language-server 3.0.x, which still supports Vue 2; other projects use latest. Each release installs in its own directory with its paired TypeScript. A version setting overrides detection.

Fixes #7357
2026-12-02 18:36:19 +08:00
l0ng-ai b911366115 fix(java): give project-wide Java usages time instead of falling back to a wider search (#7511)
Find Usages in large projects went through the Java usages extension with the default 30 s timeout and, when it ran out, fell back to jdtls' wider textDocument/references, so the user waited for both. A project-wide usages request now gets 300 s (still cancellable), and an extension timeout is returned as a timeout instead of starting the fallback; other extension failures still fall back.

Fixes #7376
2026-12-02 18:31:05 +08:00
l0ng-ai b2a9d105e2 feat(search): Endpoints tab in Search Everywhere and a Go to Endpoint action (#7510)
The request mappings the IDE indexes were only a section of Search Everywhere's All tab. They now have their own Endpoints tab, as in IDEA Ultimate (also /endpoints), and Navigate > Go to Endpoint... opens it with the editor selection as the query. No default shortcut; bindable in Settings > Keymap.
2026-12-02 18:29:03 +08:00
l0ng-ai b83c2cf11a docs(readme): refresh the WeChat group QR code 2026-12-02 18:26:46 +08:00
l0ng-ai 6648f502f1 feat(services): list Spring Boot configurations by default and show their address (#7508)
Projects without a saved Services list show Spring Boot run configurations by default; a saved list stays authoritative. Running Spring Boot nodes show the port and announced context path for runs and debug sessions.

Fixes #7346
2026-12-02 18:25:48 +08:00
LU XIANGRUIтаwildcatDownstairs 115003f0b6 feat(nuget): central package management awareness and one-click update (#7434)
The NuGet Packages window reads Directory.Packages.props: each package shows where its version is defined or pinned and any VersionOverride, and Check NuGet Package Updates offers an update to the newest version.

Metadata and update checks are scoped to the selected project, configuration and framework and run independently; one-click updates are withheld when compatibility across target frameworks is not verified.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:23:33 +08:00
nako-ruruтаnako-ruru 02d912d72a feat(keymap): add NetBeans keymap presets for Windows/Linux and macOS (#7481)
Adds NetBeans presets beside IntelliJ, Eclipse and VS Code, taken from JetBrains' NetBeans keymap (keymaps/NetBeans 6.5.xml) on top of the IntelliJ defaults; actions without an OpenIDEA counterpart keep the IntelliJ binding. IDEA's EditorDeleteLine now maps to code.deleteLine for imported keymaps.

Co-authored-by: nako-ruru <[email protected]>
2026-12-02 18:21:59 +08:00
LU XIANGRUIтаwildcatDownstairs 70fe0e6653 feat(nuget): manage NuGet package sources (#7424)
A Package sources panel lists NuGet sources and adds, enables, disables or removes them through dotnet nuget, writing to a chosen NuGet.Config under the workspace or the user-wide file.

Edits go only to the config file that defines a source, stale work is cancelled when the project or selection changes, and URL credentials are redacted from errors. CI installs SDK 10 and 11 for the real-CLI tests.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:21:34 +08:00
LU XIANGRUIтаwildcatDownstairs 950bf986d6 fix(libraries): tell same-named library roots apart in External Libraries (#7463)
A uv venv reports its own .venv/Lib beside the base interpreter's Lib, so External Libraries showed two rows called Lib. Roots sharing a name in one SDK group now show their parent folder after "library root". A root inside a sibling root (.venv/Lib/site-packages under .venv/Lib) also got the same tree key as its row in the sibling's listing, so the virtual list drew two rows on top of each other; nested roots now get their own key namespace.

Refs #7444

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:21:02 +08:00
LU XIANGRUIтаwildcatDownstairs 310d923480 feat(dotnet): show solution folders and solution items in the Project view (#7435)
Solution folders from .sln and .slnx files appear as nested nodes under the solution, holding their projects and solution items; projects outside every folder follow.

Parent folders an SLNX file only implies are created, literal slashes in legacy folder names are kept, and uppercase .SLNX extensions are accepted.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:19:58 +08:00
l0ng-ai 0c506fa479 style: format the Razor scanner and use spacing tokens in SVN working copies (#7505)
Fixes pnpm format:check and the spacing-scale test on main: two for headers in the Razor scanner are formatted as oxfmt expects, and the SVN Working Copies panel uses --space-* tokens for its gaps (same values, no visible change).
2026-12-02 18:18:43 +08:00
LU XIANGRUIтаwildcatDownstairs bc86836492 feat(dotnet): Dependencies node under each project in the Project view (#7430)
Each .NET project lists its packages, project references, framework references and analyzers under a Dependencies node.

Expandable .csproj rows keep their file behaviour (open, rename, context menu), same-named references and analyzers stay distinct, and the evaluated target framework is labelled.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:16:53 +08:00
l0ng-ai dead55af21 feat(windows): open project windows on the display last worked on (#7123)
On Windows, the display of the last focused or moved project window is saved to last-display.json. A project window opened without a position of its own is centred on that display and sized to its work area while the display is still connected and unchanged; otherwise it opens on the primary display. Cascaded windows keep their place, and macOS and Linux are unchanged.

Fixes #7031
2026-12-02 18:16:48 +08:00
langxpтаkradme c7a4201ce9 fix(agents): support context menu and stable selection (#7490)
Right-clicking the agent composer offered no editing menu. It now has Cut, Copy and Paste; menu paste goes through the same copied-code, link, project-path and long-text handling as a keyboard paste, and falls back to a clipboard image. A deferred multi-click selection handler no longer moves a selection that already left its conversation row back to it, which scrolled the conversation.

Co-authored-by: kradme <[email protected]>
2026-12-02 18:16:31 +08:00
l0ng-ai 91cf66e72e refactor(agents): simplify the automations dashboard and editor (#7491)
The Agents sidebar has a single clock button for Automations, with a dot for unread runs or runs waiting for input. The dashboard puts search and tabs on one row and moves import and pause-all into an Options menu. The automation dialog keeps provider tools with the prompt, moves permissions, continuity and run limits under Advanced, and expands Advanced when an edited schedule uses non-default settings.
2026-12-02 18:16:25 +08:00
l0ng-ai 4a87022e58 fix(agents): retry Cursor capacity errors and show attempt counts (#7500)
Cursor ACP can end a turn successfully while streaming a resource_exhausted error. Such turns now continue in the same conversation after 5, 15 and 30 seconds, with the countdown and attempt number in the working row and each continuation numbered in the history. Stop cancels the wait and Send Now replaces it; after three failed retries the task pauses with a manual Retry button.
2026-12-02 18:15:55 +08:00
l0ng-ai c92bd0999b fix(agents): render ANSI styles in tool output (#7495)
Agent tool cards now render ANSI colours and emphasis in command output with the shared console parser, instead of showing raw escape codes. Plain output keeps its text rendering path.
2026-12-02 18:15:39 +08:00
l0ng-ai 880835f0ac fix(agents): clean up plugin settings layout (#7497)
Plugin rows show the name and version with secondary metadata on its own line, keeping enable toggles and review buttons clear of the text. Manifest formats and marketplace move into the expandable details, and the list adapts to narrow Settings panes.
2026-12-02 18:15:12 +08:00
l0ng-ai ce938df81b fix(welcome): flatten recent project lists across hosts (#7504) 2026-12-02 18:05:39 +08:00
LU XIANGRUIтаwildcatDownstairs 9abe3d7e3c fix(editor): show a followed plugin theme's colours and font styles in Color Scheme (#7474)
With a plugin theme active and the scheme on Theme default, Settings > Editor > Color Scheme resolved attributes and the preview against the built-in scheme instead of the plugin theme's tokens the editor paints with, so an italic comment showed unchecked and clearing it saved nothing. resolvedSchemeTokens / resolvedAttribute now take the followed theme's tokens under the user's overrides, the page shows the plugin theme's name, and Markdown comments follow the comment style variable.

Closes #7453

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:05:29 +08:00
LU XIANGRUIтаwildcatDownstairs 4e5ae49aa9 feat(dotnet): edit solutions and project references from the Project view (#7426)
Add Existing Project, Add/Remove Project Reference and Remove from Solution on .NET solution and project nodes, running dotnet sln/reference one at a time.

Queued edits are cancelled when the workspace changes, the tree refreshes after a partially failed CLI edit, and solution paths are normalized before comparing them.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:05:25 +08:00
l0ng-ai 9443517d1c docs: restore AGENTS.md and add PR evidence rules with a pr skill (#7498)
Restore AGENTS.md (CLAUDE.md links to it) and the verify skill, and add a pr skill covering scope, checks to run, the evidence each kind of change needs and a UX consistency review against DESIGN.md and PRODUCT.md.

The PR template lists evidence by change type, and the PR check also asks for screenshots or a recording when a PR changes UI files under src/, unless the description says "No visible change".
2026-12-02 17:50:30 +08:00
l0ng-ai 29f6131f9d fix(plugins): keep plugin gutter markers while their file is reindexed (#7499)
An edit invalidated the file's indexed markers and the host has none for the new version until it is indexed again, so the gutter icon area emptied, collapsed and shifted the code sideways after every Enter or line copy. Markers now stay, mapped through the edits, until the reindex settles; editors no longer re-place a kept entry at its old lines; plugin line markers likewise stay until the new ones arrive.

Fixes #7422
2026-12-02 17:50:27 +08:00
Isaac Gallartтаigallart 4027b8341f fix(run): keep configuration fields aligned when resizing on Linux (#7470)
Fixes #7469. On Linux, WebKitGTK shifts the tracks of the scrolling options subgrid as the Run/Debug Configurations dialog resizes, moving fields away from the Name column. There the header and the options now share a fixed 150px label column instead of a subgrid; macOS and Windows keep the subgrid whose label column fits the longest label, and narrow panes keep the stacked layout.

Co-authored-by: igallart <[email protected]>
2026-12-02 17:41:13 +08:00
l0ng-ai ddc483fd2a feat(java): end a completed break or continue with a semicolon (#7493)
Fixes #7358. Completing break or continue in Java inserted the bare keyword. As in IDEA's keyword completion, it now ends with a semicolon, or with a space inside a labeled statement where the keyword can name the label; nothing is added when the line already continues. return is left alone.
2026-12-02 17:36:08 +08:00
l0ng-ai 23d81a2b3d feat(tools): show language server updates in the status bar (#7492)
Fixes #7365. Newer versions of the IDE-installed language servers were only visible in Settings > Language Servers. features/tools now looks for updates a minute after startup, at most once a day (the last result is stored and shown meanwhile in every window, and installing drops it), and publishes them through workbench/contributions. The status bar's Language Servers widget marks that an update exists and gives the server's popup row an Update button.
2026-12-02 17:34:26 +08:00
l0ng-ai 74f61a3540 fix(macos): avoid flashing when switching grouped project tabs (#7209)
Switching to an occluded or detached tab in a native window tab group now syncs its frame, re-attaches its web view and waits for one presentation commit (at most 80 ms) with occlusion detection off before swapping windows, so the incoming tab paints complete on its first visible frame. Rapid switches cancel a superseded wait and restore its web view. Tab switches and hiding AppKit's tab bar run without implicit animation, the tab bar is hidden before the window is ordered front, and a mouse click blurs the clicked project tab so the outgoing window does not keep its hover controls.
2026-12-02 17:19:13 +08:00
Muuтаmuutot c287ce0ee3 fix(python): indent @property inside the class body in the color scheme sample (#7460)
The Python sample in Editor > Color Scheme > Python showed @property at column 0 while the def alias it decorates was indented inside class Foo. The decorator line now has the same four-space indent.

Co-authored-by: muutot <[email protected]>
2026-12-02 17:18:57 +08:00
wangfeiтаhapput 607e4e095d fix(editor): show navigation link for bound click modifiers on hover (#7446)
Cmd+Alt-click (Ctrl+Alt elsewhere) is bound to Go to Implementation in the IntelliJ keymap, but the hover affordance only recognised Cmd/Ctrl alone, so the symbol kept plain text and the I-beam cursor. The navigation modifier tracker now also holds for any modifiers the active keymap binds to a navigation left-click (declaration, implementation, type declaration, super method); the LSP link hover and the plain hover popups follow it, and rebinding or removing the mouse binding removes the affordance.

Co-authored-by: happut <[email protected]>
2026-12-02 17:18:31 +08:00
LU XIANGRUIтаwildcatDownstairs e7da5e0937 fix(lsp): keep escaped brackets in hover docs from rendering as math (#7455)
Fixes #7454. basedpyright escapes literal brackets in hover Markdown (str(bytes_or_buffer\[, encoding\[, errors\]\]) -> str), which the \[...\] rule read as display math. mathExtension gets a strictBrackets option, used only by the LSP hover parser: there a single-line \[...\] is math only when padded with whitespace and not nested. Agents chat, Markdown files and notebooks keep rendering unpadded \[x^2\].

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 17:16:44 +08:00
audichuang ae4a90b23a fix(app): keep a window waiting for its peers to close from taking edits it would lose (#7428)
When Quit or closing several project tabs closes windows in parallel, a window with nothing to ask about waits at windowReadyToClose for the others; while a peer showed its Unsaved Changes prompt, the waiting window still took input, and an edit made there closed unasked. The waiting window now blurs its focused element, goes inert and suspends keyboard dispatch while it waits; it is given back with focus restored when the close is cancelled or the wait fails.

Co-authored-by: audichuang <[email protected]>
2026-12-02 17:12:10 +08:00
l0ng-ai 04006f2ea7 fix(agents): close open session view when archiving a task (#7440)
Archiving a task closes its session and Changes tabs, returns a docked Agents tool window to the task list, and clears lastTask / lastComposer so Send to Agent and layout switches do not target the read-only task. Closing a detached window of an archived task keeps its draft without reopening it. Reopening an already archived task from the Archived group still shows it.
2026-12-02 17:06:27 +08:00
l0ng-ai 7f20fc0c54 ci(smoke): run every language when lineNumberOptions.ts changes (#7484)
src/editor/api.ts now imports src/editor/core/cm/lineNumberOptions.ts, which the frontend smoke loads, so add it to the Language smoke paths and the Changes step pattern.
2026-12-02 17:06:20 +08:00
LU XIANGRUIтаwildcatDownstairs a8db175c25 feat(svn): shelf, working copy information, menu name and stripe position (#7478)
Subversion requests from #7433:

- Shelve, Shelve Silently, Unshelve and the Shelf tab work in Subversion working copies. Shelve saves `svn diff --git --show-copies-as-adds` of the selection and rolls the files back, refusing when the files changed since the patch was taken; Unshelve applies it with `svn patch` and reports rejected or skipped files as conflicts. Unversioned or conflicted files, binary files an older svn cannot put in a patch, non-UTF-8 text and selections across working copies are refused before anything is reverted. Stash stays Git-only.
- A Subversion Working Copies Information tab lists every working copy with its URL, repository root, revision, depth and format, with Show Log, Update Project, Cleanup and Relocate for each.
- The version control menu is named SVN for a Subversion project and VCS for a project with several systems.
- The version control tool window button is last in the bottom stripe group.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 16:57:05 +08:00
LU XIANGRUIтаwildcatDownstairs 8aacedf5ad fix(svn): bugs reported in #7433 (#7464)
Fixes five Subversion bugs from #7433:

- Revision details, changed files and annotation summaries ask the working copy's own URL first and the repository root only for revisions it does not list, so a server that authorizes by path no longer refuses them (E170013 / E175013). The branch list asks trunk, branches and tags one by one when the project folder cannot be listed.
- Shelving around Update Project is limited to Git repositories, so updating Subversion working copies no longer reports "not a git repository of the project".
- A double click on a working copy's tree or property conflict keeps it selected in the Conflicts dialog instead of opening the merge editor.
- The diff of a working copy's folder compares its properties instead of failing with W195007.
- The Log's User filter and author tooltip show an author without an email by name alone.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 16:44:42 +08:00
LU XIANGRUIтаwildcatDownstairs 1425bfe8ae feat(xcode): build in the background for code insight before the first build (#7339)
Opening an Xcode project with no build log builds its first scheme once in the background, so xcode-build-server has compiler arguments and sourcekit-lsp gives cross-target insight before the first Run. The build is cancellable, waits for Xcode's own build database, restarts sourcekit-lsp when it ends, and foreground builds cancel and reap it first. Xcode process execution lives in ide-run.

Closes #7337

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 16:32:55 +08:00
Glitched Polygons GmbH 75ec6c51a3 feat(csharp): Razor / cshtml / ASP.NET Core MVC support (#7256)
Razor (.cshtml/.razor) gets syntax highlighting, Roslyn's built-in Razor support with the HTML parts projected to the HTML language server (ordered open/close, a reserved projection URI, scoped capability registrations), and MVC navigation between controller actions and their views, including explicit View("...") names, subfolders and areas.

Closes #615

Co-authored-by: GlitchedPolygons <[email protected]>
2026-12-02 16:32:46 +08:00
l0ng-ai b20e7c0817 feat(agents): place image attachments inline in prompts (#7477)
Pasting, dropping or choosing an image in the agent composer inserts an [Image #n] label at the caret with a hover preview; deleting the label removes the attachment (undo restores it), and the prompt is sent as text and image blocks in label order (Copilot gets numbered references plus attachments).

Fixes #7336
2026-12-02 16:31:38 +08:00
LU XIANGRUIтаwildcatDownstairs adf5701e16 fix(svn): data loss and mixed-project Git fixes from a second review of #7131 (#7266)
Fixes from a second review of the built-in Subversion support: rollback keeps moved and needs-lock files intact, a failed commit staging step undoes only the schedules it made, mixed Git/SVN Commit All no longer pulls in unstaged Git edits, status refreshes keep failed roots' rows without resurrecting cleaned ones, BASE image sizes follow copy history, logins say whether the user asked, Windows passwords are sent in the console code page, and background Log refreshes share one SVN branch lookup so a cancelled login is not re-prompted.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 15:48:23 +08:00
Yohann CATHERINEтаyohannlog 5debc5297b feat(cmake): CLion-style profiles, presets and toolchains (#7262)
CMake gets CLion-style profiles (build type, generator, build directory, CMake options, environment), CMake presets as profiles, and toolchains (compilers, build tool, debugger, environment script). Only the active profile is detected; target ids have their own namespace, configurations from the older per-profile ids are migrated with their suppressions and before-launch references, the toolchain's build program is passed only to a compatible generator, and a profile switch refreshes the derived executable and build arguments while keeping user edits.

Co-authored-by: yohannlog <[email protected]>
2026-12-02 15:35:21 +08:00
l0ng-ai 5db70297cb fix(i18n): translate the Search Everywhere category actions (#7457)
#7405 added the Search Everywhere: {title} action title without zh / zh-TW text, which failed the source-text catalog test.
2026-12-02 15:34:13 +08:00
LU XIANGRUIтаwildcatDownstairs 0f78b845e6 docs(csharp): document Project view .NET entry points and Unity Editor attach (#7414)
Documents the .NET solution and project entry points in the Project view and attaching to the Unity Editor.

Closes #7410

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 14:51:15 +08:00
王斌 c319656529 feat(search): give every plugin search category its own action (#7405)
Each plugin-contributed Search Everywhere category gets a Navigate action (Search Everywhere: <category>) that opens that tab, so a keymap can bind it directly. The actions follow the categories as plugins are enabled or disabled; no default shortcuts.

Closes #7369

Co-authored-by: kitter960324 <[email protected]>
2026-12-02 14:51:05 +08:00
王斌 4ebc769042 feat(vcs): expand and collapse all in the Branches panel (#7407)
The Git Log Branches panel gets Expand All / Collapse All buttons and the ⌘+ / ⌘- (Ctrl+= / Ctrl+-) shortcuts while the tree has focus. Collapse All keeps the selected rows' ancestors open; the tree's identity (repository, grouping, reload) restores the default expansion.

Closes #7335

Co-authored-by: kitter960324 <[email protected]>
2026-12-02 14:50:54 +08:00
LU XIANGRUIтаwildcatDownstairs 300424658a fix(vcs): keep a deleted new file deleted after Pull, checkout, merge (#7343)
A new file staged and then deleted came back after Pull, checkout or merge: preserving local changes stashed and restored it. The deletions are now recorded and reapplied after the restore, across every batch of Git path queries; pre-existing empty folders are recreated, and a restore Git blocks keeps its marker and deletion record for the retry.

Closes #7333

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 14:47:00 +08:00
Onur Ugur 44ccaaef26 fix(editor): keep column 0 on paste after clearing auto-indent in YAML (#7415)
Fixes #7388. pasteReindentFilter fell back to the previous line's indent whenever the caret was at column 0 and the language had no indent opinion, so a line whose auto-indent the user had just deleted was treated like a clicked blank line (#4474). A state field now records a blank line whose indentation the user removed (kept across Enter from it, cleared when the caret leaves or the line gets text), and the paste keeps column 0 there. In YAML, an explicit indent is also kept when the language computes 0 because a root key follows.

Co-authored-by: OnurrUgur <[email protected]>
2026-12-02 14:39:45 +08:00
王斌 befb4792ce fix(editor): colour a module's top-level bindings as variables, not globals (#7409)
Fixes #7047. tsserver marks only function- and block-scoped bindings local, so every top-level const, let, function and import of a JS/TS file got cm-sem-global. A file with an import or export statement is an ES module, whose top-level bindings WebStorm colours as variables; only a script's top-level bindings keep the global classes. The module check is cached per syntax tree.

Co-authored-by: kitter960324 <[email protected]>
2026-12-02 14:37:53 +08:00
zhzhsxтаzhzhsx 34741f56c4 fix(diff): align the deleted lines with the new ones in the unified view (#7404)
In the unified diff viewer a deleted block started 3.5px right of the added lines: @codemirror/merge insets .cm-deletedChunk by 6px while the viewer's lines use LINE_INSET (2.5px). The block now uses LINE_INSET, which also fixes the base lines on the merge editor's sides.

Co-authored-by: zhzhsx <[email protected]>
2026-12-02 14:37:23 +08:00
Kim Myeong Su 2907832e37 fix(editor): keep a Space the Korean IME commits as a composition (#7411)
Fixes #7386. macOS Korean 2-Set commits a Space typed after Hangul as a one-character composition, and typedImeCommit (#6608) removed it as a Pinyin syllable space, in the editor and the terminal. Only spaces between non-space characters now count as syllable separators, so ni hao still becomes nihao and a lone Space is kept.

Co-authored-by: kmsdoit <[email protected]>
2026-12-02 14:33:17 +08:00
薛纪克таxuejike ff4e916561 fix(agents): retry opening a session while the agent finishes starting (#7350)
Opening a saved session while the agent was still starting failed with an internal error. The session open is now retried while the agent reports warming up, within a 30 s window that also bounds each attempt; a timeout or warm-up failure keeps the saved session id so Try again reopens the same conversation, and an auth request during any attempt runs the advertised authentication once.

Closes #7348

Co-authored-by: xuejike <[email protected]>
2026-12-02 14:32:35 +08:00
LU XIANGRUIтаwildcatDownstairs 2f799aede9 fix(editor): match WebStorm's JS/TS inlay hint defaults and cut long hints (#7338)
JS/TS inlay hints default as in WebStorm: inferred types for variables and fields, enum values, and parameter names for literal and anonymous-function arguments. The Editor toggle now reaches the typescript-language-server fallback too. Long hints are cut with the full label in the tooltip, which also refreshes when the server changes it.

Closes #7326

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 14:32:27 +08:00
l0ng-ai f853ccf544 fix(i18n): translate Bundle Identifier in the Xcode project wizard (#7425)
The Xcode project wizard (#7394) added zh entries equal to their English source, failing src/platform/i18n.test.ts on main. Bundle Identifier is translated; iOS and macOS join the kept-as-written list.
2026-12-02 14:32:11 +08:00
王斌 8b4de98664 fix(search): keep the arrows in the File Structure filter for text editing (#7416)
Fixes #4174. The filter field's keydown handler treated ←/→ as tree navigation even with a query, so the caret never moved and the selected symbol collapsed. With a query the arrows now move the caret; with an empty query they still expand and collapse the tree, as IDEA's speed search does until something is typed. The tree keeps its own ←/→ handling when it has focus.

Co-authored-by: kitter960324 <[email protected]>
2026-12-02 14:29:12 +08:00
l0ng-ai a36516d463 refactor(database): take plugin table menu entries from a workbench registry (#7423)
The Database tree imported pluginDatabaseTableMenuItems from features/plugins directly (from #7372). The table context type and a provider registry now live in workbench/contributions; features/plugins registers its provider.
2026-12-02 14:28:15 +08:00
葛俊таgejun123456 b7c2d4eacb feat(plugins): expose database table menus and read-only schema (#7372)
Plugin API 1.20 adds wit/database.wit with describe-table behind the database.schema capability: a read-only view of a connected source's table (columns, keys, indexes) through DbManager::connected_table_details. Plugins can contribute database.table.context menu entries (needs_api 20) that receive the non-secret table identity and the when keys databaseDriver, databaseObjectKind, databaseSchema, databaseTable and databaseSelectionCount.

Co-authored-by: gejun123456 <[email protected]>
2026-12-02 14:25:35 +08:00
LU XIANGRUIтаwildcatDownstairs abc5b2b2c6 feat(new-project): Xcode project templates for iOS, macOS and multiplatform apps (#7394)
File > New Project could only create SwiftPM packages. A new Xcode Project entry (Swift group; also found by iOS, macOS, App, SwiftUI or Xcode) opens a chooser modelled on Xcode's template sheet: platform tabs (Multiplatform, iOS, macOS), a filter and template tiles under Application and Framework & Library, then an options page (Product Name, Team, Organization Identifier, read-only Bundle Identifier preview, Interface, Language, Testing System). The App and Framework templates are generator definitions that write a minimal Xcode 16 project with synchronized folders and a shared scheme, so no XcodeGen or Tuist is needed and the existing scheme, simulator, run and test support takes over when it opens. The entry shows the installed Xcode's own icon, rendered at runtime, or a bundled glyph without Xcode.

Scaffold gains {{#if field=value}} blocks, c99 / bundle filters, generator platforms / section / name-pattern and readonly / remember fields. Template tree tests skip the generator's tool requirements so they run without Xcode.

Closes #7393

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 14:05:01 +08:00
l0ng-ai cb10ba7207 fix(build): copy Maven resources whose content changed without a newer mtime (#7413)
The resources step ran maven-resources-plugin, which copies a file only when it is newer than the copy, then recorded the source stamps as processed, so content replaced without a newer mtime stayed stale for good. It now passes -Dmaven.resources.overwrite=true.

Fixes #7340
2026-12-02 13:59:52 +08:00
l0ng-ai 0fe39535d6 test(trust): check SDK lookups against the restricted project window (#7412)
#7389 lets SDK commands run without a project window, so the assertion that a missing window is refused no longer held. Assert that the restricted project's own window still refuses them.
2026-12-02 13:58:59 +08:00
LU XIANGRUIтаwildcatDownstairs 0c9ffe1e41 fix(settings): let the Maven home path be typed or pasted (#7385)
Settings > Build Tools > Maven > Maven home path was a plain dropdown of detected installations plus Browse. It is now an editable combo box, as in IntelliJ IDEA: a typed or pasted path is saved on Enter, blur or paste (trimmed; empty means Auto), Escape undoes an unsaved edit, the arrow, Up and Down open the list of Auto and the detected homes. The saved path is checked the way maven_command resolves it (the home, its bin folder or mvn itself; ~/ from the home directory; relative paths from the project root) and a problem shows under the field. Other SDK combos keep the plain dropdown.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 13:52:19 +08:00
Qslia cda99d5495 fix(notebook): open an empty .ipynb file as an empty notebook (#7395)
New File named x.ipynb (or touch, or an agent) creates an empty file, which the notebook editor refused with 'Invalid notebook JSON: EOF while parsing a value'. It now reads as an empty nbformat 4 notebook, as in PyCharm; saving it unchanged leaves the file alone and an edit writes a real notebook. This covers every way an empty notebook file can appear, so New File needs no template of its own.

Co-authored-by: qslia <[email protected]>
2026-12-02 13:48:51 +08:00
王斌 d979e102f9 fix(editor): paste a clipboard's CRLF as single line breaks (#7399)
Paste with an empty selection in an editor (Vim Insert mode's Ctrl+V, Edit > Paste) went through document.execCommand('insertText'), which turns a Windows clipboard's CRLF into two line breaks: 1,000 pasted lines became 1,999, and a 5,000-line paste froze the window while the text was inserted line by line. A paste into a focused editor now always goes through one input.paste transaction, and the clipboard's line ends are normalized to LF; other focused elements still use insertText.

Closes #7387

Co-authored-by: kitter960324 <[email protected]>
2026-12-02 13:46:09 +08:00
aconeshanaтаaconeshana 67d68f7f4e fix(run): open the context path the embedded web server announces (#7384)
Open in Browser for a running Spring Boot app opened http://localhost:8080/ and dropped server.servlet.context-path, so an app under /api showed a 404. The embedded server's startup line (Tomcat started on port 8080 (http) with context path '/api') was parsed for the port only. It is now parsed into the port and the normalized context path, kept on run sessions (including reattached remote runs) and published for debug sessions, and both Open in Browser paths append it.

Closes #7383

Co-authored-by: aconeshana <[email protected]>
2026-12-02 13:43:53 +08:00
l0ng-ai 2b73ef73f1 perf(index): space snapshot refreshes by how long the last one took (#7401)
Any index write drops the startup snapshot, and it was written again at most every 10 s, also inline after every subtree scan. In a project of 160 000 files a write takes up to 11 s and holds the disk, so a build writing into the project kept it rewriting for minutes after startup.

The gap after a write is now 30 times what it took, between 10 s and 5 min; a subtree scan within the gap leaves the write to the scheduled refresh. Full scans still write at once. The snapshot only speeds up the next startup: one that is missing falls back to a scan.

Refs #7363
2026-12-02 13:41:25 +08:00
l0ng-ai de41651a5e fix(agents): ask AskUserQuestion forms one question at a time (#7396)
claude-agent-acp now sends AskUserQuestion as an ACP form (a choice field per question, each followed by a text field for a typed answer), and OMP's ask tool sends the same shape. They were shown as a plain form with every question stacked above the composer, at up to half the window, which in a short Agents panel left the conversation no room to scroll.

Such forms are now shown as the question card in the conversation, one question at a time with Previous/Next, option descriptions and previews; the answers are turned back into the form's values (picked options as the choice, typed text in its companion field; Skip declines). Other forms stay forms, and a long one waiting above the composer now leaves the conversation a share of the panel and scrolls within itself.

Fixes #7359
2026-12-02 13:36:43 +08:00
l0ng-ai 6bd2d5f843 fix(run): keep a log line with a stray NUL byte out of UTF-16 decoding (#7390)
On Windows the console decoder took any read containing a NUL byte for UTF-16LE output (wsl.exe, cmd /u). A Spring Boot app logging a payload that ends in a NUL turned the whole read into CJK-looking garbage. A read is now UTF-16LE only when NUL bytes are dense (one byte in eight or more, as every ASCII character in UTF-16 has one) or one follows a line feed (every UTF-16 line end has one).

Fixes #7362
2026-12-02 13:30:02 +08:00
l0ng-ai 93c15547ef fix(sdk): add a JDK from disk in Settings opened from the Welcome screen (#7389)
sdk_jdk_at was a trusted command, which needs an open trusted project, so Add JDK from Disk on the Welcome screen always failed and the error was shown as 'not a valid home for JDK'. SDKs are IDE-wide: sdk_jdk_at, sdk_flutter_at, sdk_locate_tools and sdk_php_xdebug now run outside Restricted Mode like sdk_detect (a restricted project still refuses them). A failed check now shows its error instead of calling the folder invalid.

Fixes #7361
2026-12-02 13:28:49 +08:00
Ivan 90d98f3edd feat(editor): gutter icons between Rust traits and their impls (#7253)
Rust files get RustRover's line markers between traits and implementations: an impl block and its methods get ↑ to the trait (or the trait's method, required vs default from the trait file's outline), a trait and its methods get ↓ to their implementations. The trait and the self type come from the tree-sitter impl header (outline items carry implements / self_type ranges, merged into rust-analyzer's outline), so multi-line generic headers, where clauses and const generic arguments label correctly. Lookups are asked only near the viewport, per-kind provider availability is cached, and every request of a pass is guarded by the document and pass generation, so an edit cancels a running pass and stale markers are refreshed.

Covered by lineMarkers.test.ts, ide-language syntax tests and the ide-lsp mock server.

Co-authored-by: Pecnikas <[email protected]>
2026-12-02 13:17:39 +08:00
Kamal ElFadlтаelfadl b7ef68df71 feat(debugger): make the expanded value tree popup resizable (#7374)
Expanding an object in the debugger's editor value tooltip fixed the tree at 460x260 px inside the hint's 480 px cap, truncating nested fields and package paths. The expanded tree now resizes from all eight edges and corners up to the viewport (minimum 280x120 px) and remembers its size (openidea.debugger.valueTreeSize.v1). hint.ts forwards resize/positioned from built hint content to CodeMirror's TooltipView so the tooltip keeps the dragged size and position.

Covered by valueHint.test.ts.

Co-authored-by: elfadl <[email protected]>
2026-12-02 13:08:52 +08:00
Kamal ElFadlтаelfadl fdc4df4752 feat(search): make Search Everywhere resizable from all edges and corners (#7373)
Search Everywhere opened at a fixed 700 px width with its height capped at 600 px, clipping long paths, containers and previews on wide monitors. Dialog's resizable="both" now resizes from all eight edges and corners (the opposite edge stays put), not only the bottom-right grip, and Search Everywhere uses it with a remembered size (openidea.search.everywhereSize.v1, clamped to its minimum). The other resizable dialogs get the edge handles too.

Covered by Dialog and Search Everywhere tests.

Co-authored-by: elfadl <[email protected]>
2026-12-02 13:04:52 +08:00
l0ng-ai 54ce048ec9 fix(vim): let af / if work on the right-hand side of a noremap (#7382)
A noremap runs its keys against codemirror-vim's built-in keymap only, and the function text objects were added after every mapclear as user mappings, so nnoremap X daf deleted nothing (same cause as <C-g>u in #7364). af / if are now part of the built-in keymap through the existing vim-core patch, with a placeholder motion the host overrides, and are no longer re-mapped after mapclear.
2026-12-02 12:58:43 +08:00
l0ng-ai a372385788 feat(vim): apply number and relativenumber from the rc file to the line numbers (#7381)
set relativenumber in ~/.ideavimrc was reported as an unsupported option and the gutter kept absolute numbers. As in IdeaVim, number (nu) and relativenumber (rnu) now set every editor's line numbers over Settings › Editor › General › Appearance › Show line numbers: both on is hybrid, relativenumber alone shows 0 on the caret line, both off hides them. An option the rc file leaves alone reads and follows Settings, nothing is written back, and turning Vim mode off or reloading an rc file without them returns to Settings. The options live in an editor-core store that lineNumbersExtension reads; the controller re-applies settings when it changes, as for Distraction Free Mode.

Fixes #7341
2026-12-02 12:53:37 +08:00
nako-ruruтаnako-ruru 7ff8d472f7 feat(chooser): mark interface targets in the implementation chooser (#7328)
Go to Implementation can list an interface declaration among the implementations (gopls answers both ways), and every row carried the same file icon. A target that is an interface or trait, or a method declared in one, now shows the editor's interface badge in place of the file icon, as GoLand does. LSP implementation answers carry no symbol kind, so the target file's outline supplies it; with targets in more than eight files the chooser opens with the kinds the index already knows instead of opening every file in the language server.

Covered by navigationInterfaceMark.test.ts.

Co-authored-by: nako-ruru <[email protected]>
2026-12-02 12:48:35 +08:00
GuoYuтаguoyucode 4de01a91c5 fix(mcp): list_directory_tree's maxDepth counts the levels below the directory (#7375)
list_directory_tree with maxDepth 1 listed nothing: the directory's own line took the first level, so 1 returned only that line with total 0, and the default 5 listed four levels. maxDepth now counts the levels below the directory (0: the directory alone, 1: its entries, …) and the parameter description says so. Paging, markers and the output format are unchanged.

Covered by max_depth_counts_the_levels_below_the_directory.

Co-authored-by: guoyucode <[email protected]>
2026-12-02 12:45:26 +08:00
LU XIANGRUIтаwildcatDownstairs 657d49e30a fix(debug): bind Xcode breakpoints for projects under /private/tmp (#7368)
Debugging an Xcode app whose project lives under /private/tmp never stopped at a breakpoint: the IDE sends breakpoints on the canonical /private/tmp/… path, while Xcode writes the files into the debug info as /tmp/…. The simulator attach now passes lldb-dap a sourceMap (/tmp, /var, /etc → /private/…). The map is Xcode-only: clang, swift build and cargo record /private/tmp/…, and LLDB uses only the first matching entry.

lldb-dap and CodeLLDB give no reason for a breakpoint they cannot bind; such breakpoints now carry one (code not loaded yet, or debug info under another path), shown translated on hover in the gutter and in the Breakpoints dialog, and dropped once the breakpoint binds.

Fixes #7367

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 12:40:05 +08:00
LU XIANGRUIтаwildcatDownstairs 2a7975a077 fix(xcode): select the root scheme and the backend's default simulator in Xcode projects (#7366)
An Xcode project with an npm package in a subfolder opened with that package's dev script selected, and the simulator chooser showed an iPad when nothing was booted.

- defaultSelection scored a root Xcode scheme the same as any run/dev script, so list order decided. A root scheme (kind xcode, no cwd) now scores like a Spring Boot application; schemes in subfolders and other project types keep their order, and a saved selection still wins.
- currentIosSimulator fell back to the first listed simulator, while the backend's pick_simulator takes a booted simulator, then the newest iPhone. The toolbar now applies the same rule, and pick_simulator ranks over simulator::parse_list so both sides agree on ties.

Fixes #7354

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 12:35:54 +08:00
tongkangwangтаchiyanking 71d88d0b55 fix(code-insight): allow dragging the Show Usages popup by its title bar (#7370)
The Show Usages popup could be resized but not moved: its header had no move handler, so it could not be dragged off the code it covers. Popup gains an opt-in `draggable` mode that moves it by descendants marked `data-popup-drag` (the same pattern Dialog uses with `data-dialog-drag`), skipping interactive controls; once moved the popup is positioned at its new place without flipping back to the anchor and stays 6 px inside the viewport. Show Usages marks its header as the drag handle.

Covered by e2e/usagesPopupLayout.spec.ts.

Co-authored-by: chiyanking <[email protected]>
2026-12-02 12:32:30 +08:00
angelf015таangelf015 c6faf280db fix(vim): support <C-g>u undo breaks in Insert mode (#7364)
An Insert-mode mapping such as `inoremap . .<C-g>u` typed the literal text ".<C-g>u": codemirror-vim has no <C-g>u command and writes unknown <...> keys of a mapping's right-hand side into the document. inoremap only searches the engine's built-in keymap, so the key is added there through a patch to @replit/codemirror-vim-core, bound to an action that isolates the next history event so the text after it starts a new undo group.

Covered by a Vim engine unit test and e2e/vimUndoBreak.spec.ts.

Co-authored-by: angelf015 <[email protected]>
2026-12-02 12:29:12 +08:00
王斌 fba7705acf feat(docker): run containers detached and open their log in Services (#7345)
Dockerfile and Docker Image runs start the container detached by default. The Run console keeps the build output; once the command line returns, a new exited hook on the run type reveals the container in the Services tool window with its Log tab (or a log editor tab for the CLI's default daemon). Closing the Run window or the IDE leaves the container running; an attached run still stops it with docker stop.

Co-authored-by: kitter960324 <[email protected]>
2026-12-02 11:48:52 +08:00
Alexanderтаstalexxx f87fb35be5 fix(libraries): don't list in-project Cargo path dependencies as External Libraries (#7316)
cargo metadata in a sub-crate's own workspace reported the project root (a path dependency such as vpn-core = { path = ".." }) as an external package, so the whole project became a read-only library root. Cargo library roots now drop path dependencies inside the open project, reusing is_project_source as Go modules do, so vendor copies stay libraries.

Co-authored-by: stalexxx <[email protected]>
2026-12-02 11:46:56 +08:00
Mansur Akhmadiтаmansur-akhmadi f4236a0ea1 feat(problems): Expand All / Collapse All in the Problems tool window toolbar (#7325)
The Problems toolbar gets Expand All and Collapse All; they touch only the files the current tab shows.

Closes #7324

Co-authored-by: mansur-akhmadi <[email protected]>
2026-12-02 11:20:51 +08:00
LU XIANGRUIтаwildcatDownstairs 1eece0ae51 fix(editor): scale gutter icons with the editor font zoom (#7352)
Gutter icons kept a fixed 14px while the editor font zoomed. They now follow the font size through --openidea-gutter-icon-size (14px at the default size, within 10-32px), applied to the icon area, the http/GraphQL/database run gutters and the feature icon wrappers.

Closes #7332

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 11:20:42 +08:00
LU XIANGRUIтаwildcatDownstairs 7361707b63 fix(astro): keep tag expressions with quoted strings as one attribute (#7331)
Quoted strings inside an Astro tag expression split the expression into several attributes. The tokenizer now skips string literals inside braces.

Closes #7330

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 11:20:30 +08:00
audichuang 8e56d3b73e fix(lsp): keep a newer Parameter Info reply when an older one arrives late (#7322)
fetchSignature applied every reply as it arrived, so a late reply for a call the caret had left replaced the newer signature. A reply is now skipped while a newer request's tooltip is still shown for the current document and caret.

Co-authored-by: audichuang <[email protected]>
2026-12-02 11:20:22 +08:00
audichuang e5453a8a97 fix(search): keep pinned Find results when the tab limit drops one (#7323)
Over the tab limit the Find tool window always dropped the first tab, even when pinned. With a pinned first tab it now drops the earliest unpinned search instead (the selected one only when it is the last unpinned).

Co-authored-by: audichuang <[email protected]>
2026-12-02 11:20:13 +08:00
audichuang 27689f09d3 fix(project): close the window on File → Close Project when another project is open (#7320)
File → Close Project always switched the window to Welcome. Like the native close button, it now closes the emptied window when another project window is open, and shows Welcome only for the last one.

Closes #7312

Co-authored-by: audichuang <[email protected]>
2026-12-02 11:20:06 +08:00
audichuang 9b468b0873 fix(vcs): keep the Git Log commit list a single Tab stop (#7321)
Every actionable graph edge and node had tabIndex 0, so Tab from the Commits list stopped on each graph segment of every row. They now use tabIndex -1 and stay clickable; the keyboard route is Collapse/Expand Linear Branches.

Closes #7311

Co-authored-by: audichuang <[email protected]>
2026-12-02 11:19:58 +08:00
audichuang cb887dad80 fix(search): report Replace All files left unsaved by a disk conflict (#7309)
Replace in Files saves clean open tabs through Documents::autosave, which keeps an external change and returns false when the file changed on disk first. That result was dropped, so the notification claimed every file was written. ReplaceHost::edit_file now also returns whether the edits were left unsaved, ReplaceSummary gains an unsaved count, and the summary reports it as a warning.

Closes #7273

Co-authored-by: audichuang <[email protected]>
2026-12-02 10:35:56 +08:00
audichuang 3cfbf80e26 fix(todo): drop the previous project's scan results after switching projects (#7318)
A scan of the old project still running after a project switch kept writing its files into the new project's TODO index. On a project change the index now bumps the scan counters (plus a new projectGen for file rescans), drops refreshes queued for the old project and resets the spinners.

Co-authored-by: audichuang <[email protected]>
2026-12-02 10:35:47 +08:00
audichuang 97add1f448 fix(coverage): show whole percentages like 29/100 as 29%, not 28% (#7317)
percent() divided before multiplying, so (29 / 100) * 100 was 28.999999999999996 and the whole-percent floor showed 28%. It now multiplies first, which is exact for integer counts.

Co-authored-by: audichuang <[email protected]>
2026-12-02 10:35:37 +08:00
Deng Liuтаdengliu 35a6bec1c2 feat(agents): implement unified Agent Plugins Hub across harnesses (#6877)
Adds a Plugins page under Settings > Agents for the plugin bundles each agent harness installs natively (Claude Code, GitHub Copilot, Codex, Gemini CLI).

- Rows are grouped by harness and scope with counts and paths. Toggles change only the harness's own enablement record, and row ids are stable and owner-qualified, so a toggle never reaches another project's row.
- Enabled plugins project their skills, MCP servers and memory files into Skills, MCP Connections and Memory; a workspace override decides what a globally enabled plugin projects in that workspace.
- Marketplaces can be browsed, previewed and installed from, with pinned git installs. Installs are written into each harness's native store without following symlinks, including at the store root.
- Plugins that run local MCP processes or lifecycle hooks need capability consent. Previews and installed folders resolve capabilities the same way, and consent is tied to the capability hash the user was shown: an install or enable whose capabilities differ is refused.

Closes #6872

Co-authored-by: dengliu <[email protected]>
2026-12-02 09:32:33 +08:00
Deng Liuтаdengliu f8ba067e1d feat(agents): add host-owned local and remote agent automations (#7084)
Adds agent automations owned by the host rather than a window: scheduled, one-shot and manual automations, in-session /loop and Send Later, and .automation.md import/export.

- Schedules run while OpenIDEA or openidea-server --daemon is running. An optional login service (LaunchAgent, systemd --user unit or Windows Startup entry), off by default, keeps them running when OpenIDEA is closed; a schedule that came due while nothing was running follows the missed-run policy.
- Every automated turn is capped at the interactive approval setting. A run fails and its schedule pauses unless the provider confirms the required ceiling, including for turns that waited in the queue.
- Scheduled turns re-check project and repository trust at dispatch; Restricted Mode pauses them.
- Worktree runs use new agent/* branches, keep the working directory confined to the worktree, and cleanup never deletes branches. Imported .automation.md files only create disabled copies.
- Automation state is shared across processes with one lock order, and in-memory claims roll back when persisting fails. Windows and peers can only act on tasks of projects they own.

Closes #6942

Co-authored-by: dengliu <[email protected]>
2026-12-02 09:19:54 +08:00
Deng Liuтаdengliu 85cbc6bacd feat(mdx): add side-by-side MDX preview with opt-in sandboxed JSX execution (#6881)
Adds Editor Only / Editor and Preview / Preview Only layouts for .mdx files.

- Safe Static Mode on open: frontmatter, GFM, math, Mermaid, MDX comments and documentation tags (Steps, CardGroup, Note, Tabs, Accordion) render through the sanitized Markdown pipeline with scroll sync and no script execution.
- Run JSX (or Trust Project in Restricted Mode) lazy-loads @mdx-js/mdx and sucrase and evaluates JSX, workspace/tsconfig/node_modules imports, .mdx transclusions, stylesheets, assets and custom layouts inside an opaque-origin sandboxed iframe with its own CSP, no network and no IPC.
- The host-guest bridge is a per-document MessagePort; image, media, module and link resolution stay inside the window's project roots, checked lexically and after canonicalization (new fs_canonicalize command, which rejects parent traversal).
- Execution requires a current, affirmative trust result for the file's owning project, including attached workspace members, whose trust changes now emit ProjectTrustChanged.
- External links open only from a real click on an anchor in the frame and always go through a confirmation dialog showing the parsed destination.
- Settings > Languages & Frameworks > Markdown adds MDX component execution (Ask before running / Run automatically in trusted projects / Disabled), a user-only setting that project settings cannot enable.

Closes #6876

Co-authored-by: dengliu <[email protected]>
2026-12-02 08:39:22 +08:00
l0ng-ai 3f490684d6 feat(run): expanded editor for program arguments in every run configuration (#7319)
Program, script and application argument fields of the other run configuration types use the arguments control added for Python: a one-line field with an editor showing one argument per line. A test keeps argument fields on that control.
2026-12-02 07:32:31 +08:00
Isaac Gallartтаigallart 8f6200c3fa feat(run): add an expanded editor for Python arguments (#7307)
The Python run configuration's Arguments field becomes a one-line field with an expand button that opens the editor with one argument per line. Accepting joins them into one command line with single spaces, keeping quotes and escapes (new splitArgsText in platform/commandLine).

Closes #7306

Co-authored-by: igallart <[email protected]>
2026-12-02 07:27:18 +08:00
Mansur Akhmadiтаmansur-akhmadi 0aa64c2c6e feat(todo): Expand All / Collapse All in the TODO tool window toolbar (#7314)
The TODO toolbar gets Expand All and Collapse All for the file groups, on the scope tabs and on commit TODO review tabs. A review tab's collapsed groups move from component state to its tab entry in useTodoView, so the toolbar and the tree share them; the scope tabs touch only the groups shown.

Closes #7313

Co-authored-by: mansur-akhmadi <[email protected]>
2026-12-02 07:27:10 +08:00
KaKi87таKaKi87 8d4e016cb0 fix(terminal): keep bash integration working with a trailing ";" in PROMPT_COMMAND and with ble.sh (#7310)
The bash integration appended ";__openidea_prompt_end" to PROMPT_COMMAND, so a user value ending in "; " became "; ;", a syntax error at every prompt that also lost the prompt-end mark. Trailing semicolons and spaces are now stripped first.

ble.sh decodes CSI sequences itself, so the readline bind of the line-clearing key never fired and vi_nmap warned about kill-whole-line. With ble.sh the sequence is mapped to F20 and bound in its emacs, vi_imap and vi_nmap keymaps.

Co-authored-by: KaKi87 <[email protected]>
2026-12-02 07:04:59 +08:00
l0ng-ai a1ef8ca749 fix(projects): keep remote open-project actions on one row (#7133)
The Open Project prompt was sized for its four actions only for the local Attach variant, so the remote variant wrapped its buttons. It is now sized for all four actions when New Tab is available, keeping responsive wrapping in narrow windows and the existing button order and default.
2026-12-02 05:33:43 +08:00
tongkangwangтаchiyanking 669462c4de fix(debugger): keep selected tab when stopping a root debug session (#7223)
When the active debug session terminated, the debugger selected the first live session in tab order, so with several independent root sessions (e.g. several Spring Boot apps) stopping one jumped to the leftmost tab and the console switched with it. A stopped root session now keeps its tab selected as finished; a finished child still hands selection back to its live parent.

Co-authored-by: chiyanking <[email protected]>
2026-12-02 05:33:31 +08:00
l0ng-ai 90eb6bac1b fix(run): save a before launch task's project directory (#7305)
Run Maven Goal / Run Gradle Task before launch steps (#7294) keep their project in projectDir, but the run configuration file never wrote it, so after a reload the step had no project and could not run (and ide-run's config round-trip test failed on main). The file now writes project-dir and reads it back.
2026-12-02 05:30:21 +08:00
l0ng-ai 674e925c9a fix(vcs): show only the branch on the toolbar branch widget (#7304)
With several repositories on different branches, the toolbar branch widget put the current repository's name before the branch, capped at 120px and ellipsized, so repositories sharing a name prefix looked the same. The button now shows only the branch and the tooltip names the repository.

Refs #7288
2026-12-02 05:23:42 +08:00
Mansur Akhmadiтаmansur-akhmadi ddd27a6e50 feat(debugger): Compare Value with Clipboard in the Variables view's context menu (#7296)
Adds Compare Value with Clipboard to the Variables view's context menu: it reads the clipboard on the click, gets the variable's full value the way Copy Value does, and opens a diff with the clipboard on the left and the value on the right.

Closes #7295

Co-authored-by: mansur-akhmadi <[email protected]>
2026-12-02 05:18:52 +08:00
Mansur Akhmadiтаmansur-akhmadi d4791ea0c2 feat(editor): Reopen Closed Tab in the editor tab context menu (#7298)
Adds Reopen Closed Tab to the editor tab context menu, in its own group after Configure Editor Tabs…; it is disabled when there is no closed tab to reopen.

Closes #7297

Co-authored-by: mansur-akhmadi <[email protected]>
2026-12-02 05:18:44 +08:00
l0ng-ai baea2733f8 test(editor): give the layout test's controller mock ensureSlot (#7303)
The Markdown preview now asks the editor controller for the tab's document slot (#7299); the layout actions test mocked the controller without ensureSlot, so 7 tests failed on main.
2026-12-02 05:17:38 +08:00
faysouтаfaysou 0d2401705e fix(preview): render Markdown and reStructuredText through symlinks (#7299)
When a file was opened under a second name (a symlink), the editor shared one document across both paths, but the preview waited for live text under the second tab's path and never rendered. The Markdown and reStructuredText previews now read the shared document's path from the editor slot and keep the tab's own path for relative links and images.

Co-authored-by: faysou <[email protected]>
2026-12-02 05:10:15 +08:00
l0ng-ai 6c96b79538 feat(agents): open the file a tool title names with a click (#7301)
A tool entry whose title already names its file ("Read src/index.ts") suppressed the separate file link, so the file could not be opened from the row. The file word in the title is now itself a link that opens the file in the editor; files the title doesn't name keep their links next to it.

Fixes #7285
2026-12-02 05:08:04 +08:00
Ivan 878e86e10c perf(vcs): read only the clicked file's change for the annotate gutter's Show Diff (#7257)
Show Diff in the annotate gutter listed every change of the blamed commit, with rename detection, only to learn how one file changed; on a commit touching thousands of files that was the whole wait. A new vcs_commit_file_change reads the file off the commit's and first parent's trees, and only runs the rename search for an added file, against the commit's deletions. Backend::commit_file_change defaults to filtering commit_files, so other backends (SVN) stay correct.

Fixes #7169

Co-authored-by: Pecnikas <[email protected]>
2026-12-02 05:02:36 +08:00
l0ng-ai 6c36723a7d fix(agents): drop the project folder from Windows paths in tool titles (#7300)
shortTitle stripped the task folder followed by '/' literally, so on Windows tool titles kept the full absolute path (backslashes, another drive-letter case). For Windows paths the task folder now matches with either separator and any letter case; commandTitle's cd check uses the same comparison.

Fixes #7286
2026-12-02 04:58:51 +08:00
Mansur Akhmadiтаmansur-akhmadi ed58f1aba0 feat(editor): Maximize Editor / Normalize Splits (#7275)
Adds Maximize Editor / Normalize Splits (IDEA's MaximizeEditorInSplit) to Window › Editor Tabs and the tab context menu of a split: it grows the current group in every split around it, and while that group stays maximized the same item gives all editor splits equal sizes. The tab menu label names what a click will do.

Closes #7274

Co-authored-by: mansur-akhmadi <[email protected]>
2026-12-02 04:56:12 +08:00
Mansur Akhmadiтаmansur-akhmadi adda2cbb93 feat(editor): File Properties › Line Separators (#7290)
File › File Properties gains a Line Separators submenu (CRLF / LF / CR) that converts the active file's line separators, like the status bar widget; it marks the file modified, does nothing when the file already uses that separator, and is disabled for read-only files and notebook cells. Mapped to IDEA's ConvertTo…LineSeparators action ids.

Closes #7289

Co-authored-by: mansur-akhmadi <[email protected]>
2026-12-02 04:56:03 +08:00
Vadim LazukтаInf1mum 132259242a fix(app): skip the exit confirmation when only the Welcome screen is open (#7284)
With Confirm application exit on, closing or quitting from the Welcome screen still asked, though no project would be lost. The confirmation now guards only a project or LightEdit session: a lone Welcome window closes and quits without it, while quitting from Welcome with other project windows open still asks.

Closes #7267

Co-authored-by: Inf1mum <[email protected]>
2026-12-02 04:29:12 +08:00
Vadim LazukтаInf1mum 1a400d3405 fix(editor): clamp horizontal scroll-hold spacer to scrollWidth (#7276)
The editor could scroll horizontally past the end of the longest line without end, because the scroll-hold spacer kept growing. It is now clamped to the content's scroll width.

Closes #7270

Co-authored-by: Inf1mum <[email protected]>
2026-12-02 04:26:59 +08:00
audichuang aa1711194c fix(tools): keep another program's tsconfig.json change when enabling CSS Modules Kit (#7281)
Enabling CSS Modules Kit saved tsconfig.json unconditionally, overwriting a change another program made on disk after the editor read it. The save is now guarded like an autosave; when refused, nothing is installed, the editor keeps the buffer and the user is told.

Co-authored-by: audichuang <[email protected]>
2026-12-02 04:26:52 +08:00
audichuang 83dcdc8eca fix(vcs): follow a branch rename only in Log tabs of that repository (#7283)
Renaming a branch renamed the Branch filter and Log tabs of every repository that had a branch of the same name. The rename now applies only to views scoped to the renamed repository (and its linked worktrees, which share its branches).

Co-authored-by: audichuang <[email protected]>
2026-12-02 04:26:44 +08:00
Vadim LazukтаInf1mum 783daaa041 fix(vcs): show mailmap-mapped authors in the Git Log (#7287)
The Git Log showed the raw author stored in each commit and ignored the repository's .mailmap, so one person with several name variants appeared as different authors. The log index now maps authors through .mailmap on read (reloaded when the file changes), and the User filter lists mailmap-mapped identities. Uses gix's mailmap feature.

Closes #7277

Co-authored-by: Inf1mum <[email protected]>
2026-12-02 04:26:37 +08:00
l0ng-ai dc74595bca feat(run): Tomcat before launch task list with Maven goal and Gradle task steps (#7294)
The Tomcat Server form's Before launch section only toggled one Build item. It now uses the same task list as other run configurations (BeforeLaunchTasks), with Tomcat's artifact Build as a removable, reorderable entry that existing configurations keep. Before launch also gains Run Maven Goal and Run Gradle Task steps that run through the build tools' existing execution and abort the launch on failure; BeforeLaunchTask gets an optional projectDir.

Fixes #7200
2026-12-02 04:19:59 +08:00
l0ng-ai aa596f1125 fix(vcs): put Select… and me first in the Git Log User filter (#7272)
With many authors the Git Log User menu was taller than the window, and Select..., the only way to filter by several users, came last and out of view.

The menu now starts with Select... and me, then the recent filters under a Recent header (several users apply in one click), then up to 30 known authors. A click on an author still sets the filter to that author alone.

Fixes #7254
2026-12-02 00:25:00 +08:00
l0ng-ai 6927b787b2 fix(vcs): move on to the next file from the changes diff preview (#7271)
The diff preview embedded in the Commit tool window and the Git window's Local Changes tab built a diff for the selected file without its sibling files, so F7 / the down arrow past the last difference did nothing there.

The changes tree now publishes its files in tree order (unversioned included, amend entries left out) and the preview uses them as the diff's chain. Past the last (first) difference the diff hints, then shows the next (previous) file in the preview itself and asks the tree to select it; the tree reveals it the same way it follows the active diff tab.

Fixes #7149
2026-12-02 00:15:32 +08:00
arookieofcтаarookieofc e1e9ede2d6 fix(agents): resolve agent CLIs on the shared tool search path (#7269)
Agent CLI detection looked only at the process PATH, and the registry, CLI update, native launch and spawn paths each used their own lookup (which::which, host PATH, login-shell PATH). When the app is launched from the desktop, CLIs installed in ~/.local/bin, ~/.npm-global/bin, ~/.bun/bin, nvm or Homebrew were reported as not installed or failed to start.

All of them now fall back to ide_core::tool_path::search_path(), which merges the host PATH, the login shell's PATH, the Windows user PATH, common home bin folders and version manager shims. A provider's own PATH from its env is checked first. MCP server launches and replayed agent sessions go through ide_jsonrpc::resolve_spawn_program as well instead of their own copies, and ide-agent no longer depends on which.

Fixes #7246

Co-authored-by: arookieofc <[email protected]>
2026-12-02 00:09:51 +08:00
LU XIANGRUIтаwildcatDownstairs 839292fb30 fix(run): keep the xcodebuild log out of an Xcode run's console (#7265)
Running an Xcode scheme printed the whole xcodebuild log in the Run console ahead of the app's output, so on a large project the console trimmed away or buried what the app printed.

The host now wraps an Xcode run's console (after Problems has read the output) with RunOutputSplit: everything up to xcodebuild's BUILD SUCCEEDED / FAILED / INTERRUPTED line goes to a per-configuration build log in the temporary folder, and the console shows the result and a link to the log. A failed build still shows its error lines (or the log's last lines when it printed none) and the failed commands. The app console leaves out simctl's '<bundle id>: <pid>' lines, keeping the first one while a debugger waits for it, and the runtime's 'Class ... is implemented in both' warnings. A build that ends without a result line is finished on the process's exit line.

Fixes #7264

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 00:07:01 +08:00
LU XIANGRUIтаwildcatDownstairs 2a4bf1f848 fix(run): skip SourcePackages, Pods, Carthage and DerivedData when discovering run configurations (#7263)
Run configuration discovery walks three levels deep and its shared skip list only knew node_modules, target, build and a few others, so an iOS project with resolved Swift packages in SourcePackages/checkouts listed every dependency's Rakefiles, CMake targets, Makefiles, Swift packages and Xcode schemes (252 configurations on a real Tuist app, 218 of them from dependencies).

project_roots now exposes the skip list as is_skipped_dir and adds SourcePackages, Pods, Carthage and DerivedData. Xcode's project_stamp uses the same list (plus Tuist) instead of its own copy, so build discovery, run discovery and the settings stamp agree on one list.

Fixes #7261

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 00:04:22 +08:00
l0ng-aiтаCursor 3e41c93a95 fix(ci): skip RPM bundles in nightly builds (#7258)
Co-authored-by: Cursor <[email protected]>
2026-12-02 00:00:57 +08:00
l0ng-ai b85027dc47 fix(database): colour quoted identifiers as names in DuckDB and Snowflake consoles (#7260)
The DuckDB and Snowflake console dialects are built from lang-sql directly, which tags QuotedIdentifier like a string, so "schema"."table" was still painted in the string colour there after #7255 fixed the plain SQL mode. Both dialects now restyle QuotedIdentifier as a name.
2026-12-01 23:08:39 +08:00
Alexanderтаformiat 63c2ced086 fix(vcs): focus the diff's text when the modal diff window opens (#7252)
Under the modal commit interface the diff window gave initial focus to its toolbar's first button, so F7 / Shift+F7 did nothing until a click in the text. The dialog body is now the autofocus target and an editor focus host, handing focus to the diff's text.

Closes #7250

Co-authored-by: formiat <[email protected]>
2026-12-01 23:06:34 +08:00
faysouтаfaysou d73b8d8ec1 fix(markdown): render equations in HTML table cells (#7249)
Marked passes raw HTML tables through untouched, so TeX delimiters stayed visible in their cells. Inline equations in sanitized cell text are now marked and sent through the existing preview typesetter; code and attributes stay literal.

Co-authored-by: faysou <[email protected]>
2026-12-01 23:06:15 +08:00
Ivan 74b90a114a fix(sql): colour quoted identifiers as names, not strings (#7255)
lang-sql tags QuotedIdentifier as special(string), so "schema"."table" and quoted column lists were painted in the string colour. The SQL mode now restyles QuotedIdentifier as a name.

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 23:06:02 +08:00
koeriaтаkoeria e70b516ca0 fix(lsp): do not swallow } when inline completion is unsupported (#7251)
Call Inline Completion is Alt+\, which on some macOS layouts types a character such as }. When no language server or plugin supports inline completion, the shortcut consumed the key and showed a hint. The action now re-inserts the typed character in that case, and once the provider is known to be unavailable the key is left to the editor.

Closes #7247

Co-authored-by: koeria <[email protected]>
2026-12-01 23:05:50 +08:00
LU XIANGRUIтаwildcatDownstairs 7d15681313 feat(svn): built-in Subversion support (#7131)
Adds an ide-svn backend on top of the generic VCS layer (#7065): SVN working copies are detected and routed through the shared Backend/BackendProvider, reusing the existing VCS UI for status, diff, commit, history, annotate, update and revert. CI installs Subversion on Linux and macOS; on Windows the SVN integration tests skip when svn is missing.

Closes #178

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 22:57:35 +08:00
l0ng-ai 2ecaefe859 fix(java): normalize Maven system-scope jar paths on Windows (#7248)
${pom.basedir}/src/main/... resolved to a path mixing \\ and / on Windows, so the launch classpath carried it in an odd spelling and the #7226 test failed on the Windows runner. The resolved path is rebuilt from its components.
2026-12-01 22:17:51 +08:00
Mykhailo Smolinskyiтаnntndfrk 895e5bd56e fix(editor): bump @codemirror/view to 6.44.2 for the Safari tooltip fix (#570)
@codemirror/view 6.44 contains the upstream fix for tooltip positioning in Safari/WebKit; bump to ^6.44.2 and rebase the local patch onto it.

Co-authored-by: nntndfrk <[email protected]>
2026-12-01 21:56:40 +08:00
solhovoy 2dc577614b fix(vcs): keep find in modal diff (#7198)
⌘F in the modal diff opened Find in the editor tab behind it. The diff dialog now claims the Find keys while it has focus, so Find opens in the modal; Replace works there on an editable side as in any diff.

Co-authored-by: solhovoy <[email protected]>
2026-12-01 21:47:09 +08:00
LU XIANGRUIтаLU XIANGRUI a9e92d0665 fix(python): load package description images only when asked (#6616)
* fix(python): load package description images only when asked, and list the PyPI link once

* fix(python): hold back image inputs and backgrounds too, and match the PyPI page by name

---------

Co-authored-by: LU XIANGRUI <[email protected]>
2026-12-01 21:22:13 +08:00
LU XIANGRUIтаwildcatDownstairs fa0be07436 perf(xcode): read a run's build settings once and say so in the console (#7244)
▶ on an Xcode scheme ran xcodebuild -showBuildSettings twice before building (8–13 s each on a large Tuist workspace) with an empty console. One read now also decides whether the app runs on the Mac, settings are cached until project.pbxproj, the workspace, a scheme, an xcconfig or Package.resolved changes, and the console reports the read and its duration.

Fixes #7236
Fixes #7237

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 21:19:28 +08:00
l0ng-ai fea27f5608 fix(format): reformat a directory without opening an editor for each file (#7245)
Reformat Code and Code Cleanup on a directory opened every file in a focused tab. As in IDEA, files that aren't open are formatted on their shared document and saved without a tab; open files are changed in place, keeping the active tab and focus, one undo step each.

Fixes #7221
2026-12-01 21:04:59 +08:00
LU XIANGRUIтаwildcatDownstairs a4d172ac83 fix(xcode): end the app when an iOS Simulator debug session stops (#7241)
Stopping an Xcode debug session on the iOS Simulator left simctl and the app running. Stopping now terminates the launched app on the simulator and ends the launcher.

Fixes #7240

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 20:52:43 +08:00
LU XIANGRUIтаwildcatDownstairs c40d06c702 fix(xcode): give xcode-build-server the build folder of the project's scheme (#7233)
Generating buildServer.json failed on a Tuist workspace whose first scheme is a Swift package: xcode-build-server read that scheme's build settings, which have no build folder. The IDE reads the DerivedData folder from the first project scheme and passes it as --build_root, with an absolute container path.

Fixes #7232

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 20:52:36 +08:00
Alexanderтаformiat 619ae7f727 fix(vcs): keep the end of a diff line clear of the overview lane (#7229)
At full horizontal scroll the end of a diff's longest line stayed under the change overview lane. The diff editors reserve the lane's width at the end of the content, in split and unified modes.

Fixes #7228

Co-authored-by: formiat <[email protected]>
2026-12-01 20:52:29 +08:00
l0ng-ai c725b1629d fix(vim): replace a Visual selection when Ctrl+V is given to the IDE (#7242)
With Ctrl+V's handler set to the IDE, pasting over a Visual selection inserted after it because the browser paste ran after Vim collapsed the selection. In Visual mode an IDE-handled paste stroke runs Paste, replacing the selection in one transaction; with the default handler Ctrl+V still starts a Visual block, as in IdeaVim.

Fixes #7192
2026-12-01 20:47:41 +08:00
l0ng-ai b0033a869d test(vcs): give the unavailable-root fixtures their VCS kind (#7238)
#7065 made VcsRoot.kind required; the fixtures #7161 added on main lacked it, so tsc failed on main.
2026-12-01 20:44:00 +08:00
l0ng-ai 4ed4ced5b1 fix(plugins): warn once about a duplicate plugin directory (#7235)
A plugin found both at an older location and a linked one logged "ignored: already loaded from" on every rescan, tens of thousands of times a session. The warning is given once per plugin directory.

Refs #7207
2026-12-01 20:29:57 +08:00
l0ng-ai 7668e4a5ba fix(java): open library classes through java-analyzer when it is the Java server (#7234)
Opening a class from a jar in Project › External Libraries always went through jdtls, so with java-analyzer as the Java server it failed with "no Java language server (jdtls) is configured". When the server advertises java-analyzer/classFile, the class is resolved there and opens like go to definition (attached sources, else decompiled); jdtls stays first when configured.

Fixes #7212
2026-12-01 20:27:04 +08:00
l0ng-ai 4a6e0dfac1 fix(i18n): translate "Couldn't retry the message" (#7231)
#7204 added the agent retry failure title without zh and zh-TW entries, so the text catalog test failed on main.
2026-12-01 20:16:21 +08:00
LU XIANGRUIтаwildcatDownstairs 11e8f8a101 feat(vcs): route non-Git backends through ide-host (#7065)
A generic layer for version control systems other than Git: ide_vcs::Backend gains kind, head label, update, branches/switch, the system's own changelists and open-for-edit, and BackendProvider finds working copies (asked only for trusted projects, with an optional marker such as .svn for nested roots). ide-host routes the vcs_* commands, status and the Changes view by root, so the existing Git UI serves other systems; Git's behaviour is unchanged. No provider is registered here.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 20:10:16 +08:00
LU XIANGRUIтаwildcatDownstairs 7a27f285e6 fix(xcode): set up code insight for Xcode projects without asking (#7219)
Opening a trusted Xcode project with xcode-build-server on PATH and no buildServer.json/.bsp now writes the config on open (added to .git/info/exclude unless tracked or ignored); an existing config is never touched. Runs build into Xcode's DerivedData, where the config reads build logs, so new files resolve after ▶ without restarting sourcekit-lsp; a workspace next to the project is built even without schemes or a Podfile (Tuist, SwiftPM).

Fixes #7213

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 19:45:16 +08:00
l0ng-ai f21ae03bdd fix(java): put Maven system-scope jars on the run and build classpath (#7226)
The POM reader dropped <systemPath>, so a system-scope jar that Maven's runtime classpath or the Java language server left out never reached the run classpath. Existing system-scope jars are added to the owning module's javac and Run/Debug classpaths, as IntelliJ IDEA does, with basedir and POM properties resolved.

Fixes #7194
2026-12-01 19:44:45 +08:00
l0ng-ai 5dacbcd0cd test(e2e): wait for the fetched user list in the Git Log User filter test (#7224)
The User menu opens with the authors known so far and fetches the full list in the background, so the stubbed users only appear when the menu is opened again; the test clicked one on the first open and timed out on main (E2E 3/4).
2026-12-01 19:32:34 +08:00
Ivan 281c2ff1e5 fix(logging): shrink the log writer queue from 128000 to 16384 lines (#7211)
tracing-appender's default non-blocking queue holds 128 000 lines and is allocated up front (about 4 MB) for a backlog the writer thread never builds. The log writer uses a 16 384-line queue.

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 19:22:17 +08:00
langxpтаkradme 4276250056 fix(agents): keep Codex forks writable (#7204)
A Codex fork could fail on its first message with "already has an active writer" because the original task's app-server owned the new thread. The fork is created on its own task's connection, and a session held by another writer offers Retry or Fork while keeping the submitted draft.

Co-authored-by: kradme <[email protected]>
2026-12-01 19:21:51 +08:00
koeriaтаkoeria ba04491ace fix(index): skip rewriting index.snapshot when a scan has no changes (#7214)
A reconcile scan that found nothing new still rewrote the whole index snapshot (30 MB, 1.3–19 s on a large Flutter project). The snapshot is now written only when the scan changed the index or the snapshot is missing; tests pin root-anchored .gitignore / info/exclude handling for build output.

Fixes #7208

Co-authored-by: koeria <[email protected]>
2026-12-01 19:21:43 +08:00
Ivan 660a311f21 fix(host): free a closed project's documents and language registry (#7210)
The language manager's apply-edit hook held the project's documents strongly while the documents kept the manager alive through their observers, so every closed project's documents, language registry and language manager leaked. The hook now holds a weak reference.

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 19:21:30 +08:00
koeriaтаkoeria 92bf9354fe fix(lsp): skip Dart Code Vision references for inherited Flutter lifecycle methods (#7216)
Code Vision asked the Dart server for references of every @override Flutter lifecycle method (build, initState, dispose…), which on a large app floods the single-isolate server and stalls completions. Usages counts are no longer requested for those inherited overrides.

Fixes #7206

Co-authored-by: koeria <[email protected]>
2026-12-01 18:57:07 +08:00
audichuang 54da9c2c12 fix(editor): overwrite a whole emoji instead of leaving half a surrogate pair (#7220)
In overwrite mode, typing over an emoji replaced only its high surrogate and left a broken low half. A replaced range that ends inside a surrogate pair now takes the whole pair.

Co-authored-by: audichuang <[email protected]>
2026-12-01 18:57:01 +08:00
audichuang 9ba3150998 fix(editor): unescape \/ when copying from a JavaScript string (#7218)
Copying from inside a JavaScript/TypeScript string literal unescapes its escapes, as IDEA does, but left \/ as is. It is now unescaped in JavaScript strings, and kept in strings of languages embedded in template literals.

Co-authored-by: audichuang <[email protected]>
2026-12-01 18:56:52 +08:00
l0ng-ai 190e5639f1 feat(docker): run Dockerfile and Docker Image containers in the background (#7215)
Dockerfile (when it runs the built image) and Docker Image run configurations get Run in the background (-d), as Docker Compose has: the container starts detached (a previous one of the same name is removed first) and the Run window follows docker logs; Stop ends only the log follower. Unchecked, command lines are unchanged.

Fixes #7180
2026-12-01 18:06:09 +08:00
l0ng-ai 5f782e9c5d feat(debugger): choose the GDB and lldb-dap executables for C/C++ debugging (#7205)
Settings › Build, Execution, Deployment › Debugger › C/C++ gets GDB executable and LLDB DAP executable (empty: find them on PATH as before; relative paths resolve against the project), as CLion lets a toolchain use a custom GDB. The GDB version check reads the chosen binary and names it when it is older than 14.

Fixes #7174
2026-12-01 17:33:45 +08:00
koeriaтаkoeria 10fe5d21af fix(editor): resolve lazy organize-imports before applying on the fly (#7202)
Java Optimize imports on the fly never removed unused imports: java-analyzer returns a lazy source.organizeImports action (data, no edit), and the on-the-fly path required an edit. It now resolves such an action first, as the command-palette and on-save paths already did.

Fixes #7197

Co-authored-by: koeria <[email protected]>
2026-12-01 17:01:28 +08:00
l0ng-ai 16c30e819c fix(database): include identity, generated, partition and unlogged clauses in PostgreSQL DDL (#7201)
Go to DDL on PostgreSQL dropped identity columns, stored generated columns, partition by on partitioned tables, the partition of … for values form of partitions, and unlogged. They are now rendered; a partition lists only its local overrides, constraints, indexes and triggers. Ordinary tables' DDL is unchanged (compared byte for byte on PostgreSQL 17).
2026-12-01 16:58:23 +08:00
l0ng-ai 43c8699beb feat(project-tree): show Java classes in source roots without the .java extension (#7199)
As IDEA shows class nodes, a .java file inside a source or test root whose name is a valid Java identifier is listed by its class name; files elsewhere, package-info.java and non-identifier names keep the extension. Only the label changes; speed search matches the shown name.

Fixes #7167
2026-12-01 16:45:26 +08:00
audichuang 071fbf7639 test: pin per-region diff results only when the diff ran within its time budget (#7175)
Document::diff returns one coarser (still correct) change once its 50 ms budget runs out, so tests pinning one change per region failed on loaded machines. The ide-text tests use diff_until with a far deadline; the formatter and workspace tests that reach the budgeted diff through production code check exact regions only when the call returned within DIFF_BUDGET (now pub), and always check the resulting text and that edits stay between the first and last changed line.

Co-authored-by: audichuang <[email protected]>
2026-12-01 16:36:34 +08:00
l0ng-ai bde1e5f7a0 fix(vcs): open the annotate gutter's Show Diff at the clicked line's change (#7196)
Show Diff from the blame gutter always opened at the commit's first change. git blame's porcelain header already names each line's number in the attributed commit; it is kept as BlameLine.originLine, and Show Diff opens the diff at that line of the commit's version.

Refs #7169
2026-12-01 16:33:43 +08:00
l0ng-ai c1e8864138 fix(i18n): translate the updated Import Module from Existing Sources description (#7195)
#7185 extended the action's description without updating the zh and zh-TW entries, so the text catalog test failed on main.
2026-12-01 16:30:33 +08:00
l0ng-ai 5966d193c4 fix(project-tree): name a file dropped from Windows by its file name (#7193)
Tauri reports dropped files on Windows with backslashes, and the import named the copy from /-separated paths, so a file dropped into an SSH remote project was uploaded as E:\dir\file. Dropped paths are normalized to the UI's / form first; the welcome screen's open-on-drop and the agent composer's dropped attachments do the same.

Fixes #7171
2026-12-01 16:19:15 +08:00
l0ng-ai 6d38521498 fix(vcs): read objects in a repository another user owns with more than 32 packs (#7191)
Repo::discover kept the handle from ThreadSafeRepository::discover, which picks gitoxide's options by the folder owner's trust; for a repository another user owns (reduced trust) they cap the object database at 32 pack indices, so with more packs no object could be read and HEAD failed to resolve in the Git log. The discovered repository is now opened the way gix() reopens it, with slots sized by the pack directory.

Fixes #7138
2026-12-01 16:09:37 +08:00
Waiting-Night 52e6a0f84b feat(database): honor selected cells in SQL extractor copy (#7177)
Plain Copy in database result grids uses the active SQL data extractor instead of TSV, as DataGrip does. The Where Clause extractor builds the clause from the selected cells (one value: a = v; several in one column: IN (…); several columns: AND; several rows: OR of ANDs; NULL as IS NULL); the Insert/Update/Delete extractors keep working on the selected rows.

Co-authored-by: wangyuewen-china <[email protected]>
2026-12-01 15:56:16 +08:00
Sameh Elhawaryтаsamehelhawary 72873981aa fix(plugins): keep a tree row's label whole in a narrow plugin view (#7184)
In a narrow plugin view a tree row's label shrank together with its detail, so "GET /posts" became "G…". Plugin views set --tree-detail-flex-shrink, as the Git log's branch tree does, so the detail gives way first.

Co-authored-by: samehelhawary <[email protected]>
2026-12-01 15:53:59 +08:00
Sameh Elhawaryтаsamehelhawary d44a104ff8 fix(terminal): keep the tab of a program a plugin runs when it ends (#7182)
A program a plugin runs in a terminal (views.open-terminal) that prints and exits closed its tab immediately because of "Close session when it ends", taking its output and exit code with it. terminal.runCommand accepts keepOpen, and plugin-launched programs use it: the tab stays with the completion line and exit code.

Co-authored-by: samehelhawary <[email protected]>
2026-12-01 15:53:51 +08:00
koeriaтаkoeria 23ea9cf07d fix(run): forward run-config env to Gradle-delegated JavaExec (#7183)
A Gradle-delegated Application / Spring Boot run merged the run configuration's env into the Gradle client environment only; a reused daemon keeps the environment it started with, so the variables never reached the forked application JVM. The env map is now passed like args and jvmArgs (-Dopenidea.run.env) and applied with JavaExec.environment on the openideaRun task.

Fixes #7179

Co-authored-by: koeria <[email protected]>
2026-12-01 15:53:42 +08:00
Anka Tamaтаxirf cea3f4ac9c feat(vcs): handle unavailable repositories and project roots gracefully (#7161)
When an external drive, network share or mapped directory becomes unreachable, the Project view emptied the root and VCS views kept reading it or offered active Git controls. VCS roots now report unavailable (Repo::check_valid) and skip gitoxide reads, distinct from Untrusted / Safe Mode; MCP get_repositories reports it and git_status skips such roots. The Project view keeps the cached entries greyed out with an unavailable mark and guards mutating actions and opening files; Commit, Git Log, Stashes, Branches and Git signing settings show an unavailable state with Retry and Directory Mappings, and recovery is retried on window focus or refresh.

Co-authored-by: xirf <[email protected]>
2026-12-01 15:52:08 +08:00
Alexanderтаformiat aee715f797 fix(vcs): drop check marks from the Git Log User filter menu (#6290)
The Git Log User filter menu showed check marks next to users, reading like a multi-select, while a click sets the filter to that user alone (IDEA's behaviour; several users go through Select…). The rows no longer carry check marks.

Refs #6289

Co-authored-by: formiat <[email protected]>
2026-12-01 15:43:13 +08:00
l0ng-ai 711349c6c1 fix(completion): complete a keyword rather than a declaration snippet of the same name (#7186)
jdtls lists both the keyword interface and a snippet interface that inserts a whole declaration named after the file; picking the snippet while changing class to interface duplicated the declaration. A server snippet whose label matches a keyword in the same list is dropped, as IDEA completes only the keyword.

Fixes #7151
2026-12-01 15:39:01 +08:00
l0ng-ai 9b2d783322 fix(project): keep Import Module from Existing Sources available after attaching a project (#7185)
Attaching a second project turns the window into a multi-project one, and Import Module from Existing Sources was limited to single-project windows, so it greyed out after the first import. In a multi-project window there is no single build to link into, so the chosen directory is attached as another project, as Attach Project does; a directory already inside a project is reported as such.

Fixes #7148
2026-12-01 15:37:34 +08:00
Waiting-Night 72ae354d29 feat(database): polish data source and table workflows (#7150)
- Introspected tree folder labels (tables, views, routines, keys, …) are localized.
- Database/schema introspection pickers get Select all filtered.
- New › Data Source lists recently added data source types in a Recent section first, seeded from existing sources on first use.
- New PostgreSQL data sources default to the postgres database.
- Modify Table is resizable, its content following the window size.

Co-authored-by: wangyuewen-china <[email protected]>
2026-12-01 15:33:08 +08:00
JunChang Peng dd8de05013 perf(database): read a table's catalog metadata concurrently and reload a generated DDL (#6985)
Go to DDL on PostgreSQL ran six catalog queries one after another although five only need the relation oid; on a remote server that is several seconds. The oid is read first and the column, constraint, grant, index and trigger queries then run together (two round trips instead of six); opening a table likewise reads indexes, foreign keys, triggers and properties together, and PostgreSQL's table comment comes with the properties row. The generated script is unchanged (checked byte-for-byte against main on PostgreSQL 17 with varchar(n), numeric(p,s), arrays, enums, comments, indexes, triggers, grants and partitions; a zero-column table still renders). A generated DDL file gets a Reload button that regenerates it in place.

Fixes #6911

Co-authored-by: junchangpeng <[email protected]>
2026-12-01 15:30:59 +08:00
Deng Liuтаdengliu a547c8cdee fix(agents): read VS Code titles through SQLx and fork Copilot sessions another app has open (#7126)
VS Code Agent Host titles (agent-host.db) are read with the workspace's SQLx SQLite driver over a read-only connection (no journal_mode or other write pragma), replacing the raw libsqlite3-sys FFI and its unsafe blocks and dropping that workspace dependency. Copilot sessions whose inuse.<pid>.lock names a live process are marked In use in Import Sessions and the history popup; with one selected, Fork becomes the default action so OpenIDEA and VS Code don't both append to the same events.jsonl. Stale locks are ignored.

Co-authored-by: dengliu <[email protected]>
2026-12-01 15:23:04 +08:00
Deng Liuтаdengliu a74d5b5dbb fix(agents): keep chat history visible and scrollable when rows collapse (#7172)
Collapsing a tall row near the end of an agent chat (submitting an inline question form, folding a live thought whose header had scrolled above the view) could push every row above the viewport, leaving only the Thinking… row over blank slack, and lock upward scrolling. Clicks on controls inside a row no longer count as a scroll drag; holdShownRow checks the pre-trim max scroll before trimSlack, and a row that collapsed past the top is anchored at the top padding within the content; sending a message or reaching the end clears the slack.

Fixes #7170

Co-authored-by: dengliu <[email protected]>
2026-12-01 15:21:05 +08:00
Qslia b895093f6b fix(notebook): apply comment style in notebook editor (#7160)
Notebook code cells ignored the Python line comment code style (add a space / at first column): the regular editor provides the lineCommentStyle facet through prefsFor, the standalone CellEditor didn't, so Comment with Line Comment fell back to defaults. Cells now get the Python comment style and reconfigure it in place when editor settings change.

Co-authored-by: qslia <[email protected]>
2026-12-01 15:15:42 +08:00
koeriaтаkoeria cbb9079577 fix(project-tree): keep a folder icon and a language badge on attached roots (#7164)
In a multi-project window an attached Python root used the 16px Python file logo as its whole glyph. File-type logos from the project-type registry (file-python, file-go, Node…) are now an 8px corner badge on the module folder icon; dedicated project glyphs (Maven, Gradle, Flutter, Vite) still replace the folder.

Fixes #7156

Co-authored-by: koeria <[email protected]>
2026-12-01 15:14:53 +08:00
koeriaтаkoeria 44418411b8 fix(project-tree): keep the horizontal scrollbar still while dragging out of the tree (#7165)
Dragging from a narrow Project tree toward the terminal made the horizontal overlay thumb jump: WebKit autoscrolled the pressed scroller sideways and keep() snapped scrollLeft back every frame. During a file drag the tree now sets overflow-x: hidden (restoring scrollLeft around it) so WebKit doesn't autoscroll that axis, and the horizontal overlay applies scroll updates on the next animation frame.

Fixes #7155

Co-authored-by: koeria <[email protected]>
2026-12-01 15:14:45 +08:00
aconeshanaтаaconeshana 5e23076766 fix(project-tree): drag a project root to drop targets outside the tree (#7162)
Dragging a project root from the Project view to the terminal inserted nothing and the tree scrolled toward the pointer: the pointerdown handler returned for root rows before any drag session existed, so the press stayed a text selection with WebKit autoscroll. A root is now a drag source for targets outside the tree (payload carries the folder with its trailing slash, the label names it, the scroll guard runs); it is still not moved inside the tree nor handed to an OS drag.

Fixes #7154

Co-authored-by: aconeshana <[email protected]>
2026-12-01 15:14:38 +08:00
koeriaтаkoeria 689d3fd877 fix(java): do not fail Debug on MDEP-187 reactor packaging errors (#7159)
In a multi-module Maven project, Debug of a main class failed in the pre-launch build when maven-dependency-plugin:copy-dependencies is bound to package, while Run succeeded. Debug uses jdtls' java/buildWorkspace (for HotSwap), and m2e runs package-phase mojos there; reactor jars aren't packaged yet, so the plugin leaves an MDEP-187 (copy) / MDEP-98 (unpack) error marker on the POM and the launch counted it as a compile error. Those packaging-reactor markers are now ignored when collecting launch errors; real compile errors and other mojo failures still block.

Fixes #7152

Co-authored-by: koeria <[email protected]>
2026-12-01 15:12:57 +08:00
koeriaтаkoeria 608ab44fca fix(completion): list same-name imports from different packages (#7147)
Typing @RequestBod in a Spring project listed only one RequestBody although JDT.LS returned it from two packages. CodeMirror merges options that share label, detail and apply; JDT.LS puts the package in labelDetails.description (our type column, not CodeMirror's detail) and often defers the import edit until resolve, so the existing distinct-apply conditions didn't fire. An item with a labelDescription, detail or labelDetail now gets its own apply; identical items are still dropped by withoutDuplicates.

Fixes #7144

Co-authored-by: koeria <[email protected]>
2026-12-01 15:11:48 +08:00
l0ng-ai 41545d38e5 feat(terminal): let programs set the clipboard with OSC 52 (#7181)
Programs that can't reach the local clipboard (tmux with set-clipboard on, Neovim over SSH, TUI multiplexers) emit OSC 52 and expect the terminal to write it; the sequence was discarded, so copying inside them never reached the system clipboard, notably in SSH remote projects. The terminal now decodes OSC 52 writes (clipboard/primary/select, UTF-8) and writes the system clipboard; read requests are never answered, cut-buffer-only, invalid and over-1-MiB payloads are ignored. Settings › Tools › Terminal: "Let programs copy to the clipboard (OSC 52)", on by default.

Fixes #7143
2026-12-01 15:10:49 +08:00
Waiting-Night 4f86211dd6 fix(editor): make Recent Files movable, resizable and size-persistent (#7139)
Recent Files could only be dragged by its title text and could not be resized. The whole title bar now drags the popup (except the search field and the edited-only checkbox), a corner grip resizes it, and the size is remembered across opens. Rows show the file name, plus the directory only when another listed file has the same name, so long names are no longer truncated by a repeated path; the footer keeps the selected file's full path.

Co-authored-by: wangyuewen-china <[email protected]>
2026-12-01 15:06:34 +08:00
l0ng-ai 203e4fbcb2 fix(java): avoid duplicate class templates from java-analyzer (#7145)
New Java classes got two package and two class declarations: OpenIDEA fills its template after opening the empty file while java-analyzer sent its own skeleton through workspace/applyEdit. java-analyzer's newFileTemplate initialization option is now off, so file creation stays with OpenIDEA's templates. Regression test on the language registry setting.
2026-12-01 15:02:36 +08:00
l0ng-ai 869e52f837 fix(agents): make Copy Agent Reference available to the keymap and Find Action (#7158)
The action was hidden and copied only the targets a context menu passed, so Settings > Keymap couldn't list it. Run without targets (a shortcut, Find Action), it now copies the focused Project view's selection (folders with a trailing slash), or else the active editor's file with the selected lines, or the caret's line, as the editor's menu does.

Fixes #7136
2026-12-01 11:58:46 +08:00
l0ng-ai 02e4c9c7a2 fix(project-tree): keep git-ignored files visible when excluded files are hidden (#7157)
Show Excluded Files hid every entry matched by .gitignore as well as the excluded ones, so turning it off also removed git-ignored files from the Project view. The option now hides only excluded entries (exclude settings, Project Structure); git-ignored files stay visible and dimmed. Select Opened File's explanation of a hidden path follows the same rule.

Fixes #7137
2026-12-01 11:58:35 +08:00
l0ng-ai 61be657209 docs: update Discord invitation link 2026-12-01 11:42:31 +08:00
l0ng-ai 52294c51c2 feat(csharp): use the Roslyn language server when installed, csharp-ls otherwise (#7153)
Roslyn completes types from namespaces a file doesn't import and adds the using directive on accept; csharp-ls 0.14+ no longer lists such types.

- languages/csharp.toml: roslyn-language-server first (--stdio --autoLoadProjects, unimported-namespace completion on), csharp-ls as its fallback.
- ide-tools: DotnetTool gains prerelease and min_sdk. Roslyn ships only prerelease, platform-specific tool packages, so it installs with --prerelease and needs the .NET 10 SDK; an older SDK gets an error that names the SDK and suggests csharp-ls.
- Docs: C#, Unity and the support matrix describe both servers.

Fixes #7124
2026-12-01 11:37:32 +08:00
l0ng-ai 222d0b5ee3 fix(ci): wait for the MCP listener before restarting on its port (#7141) 2026-12-01 11:06:22 +08:00
l0ng-ai cd8f29ea63 fix(ci): restore Windows clippy and Mermaid preview tests (#7132) 2026-12-01 09:14:14 +08:00
l0ng-ai ba94abcb8b fix(editor): draw CJK text next to a zero-width joiner on its own (#7128)
Text copied from web pages can carry U+200C (or U+200D) between CJK characters and punctuation. WebKitGTK looks up a glyph for the character and the joiner together and draws a box when its fallback font lacks the joiner.

A joiner next to CJK text, where it joins nothing, is now split off as an empty zero-width widget so the character is drawn on its own; the text is unchanged. Between ASCII characters or at a line edge it is shown like other invisible characters; next to other non-ASCII text (Arabic, Indic scripts, emoji sequences) it is left as it is.

Fixes #7019
2026-12-01 08:06:34 +08:00
l0ng-ai 937eb0c3a0 fix(python): leave detected package folders off PYTHONPATH (#7127)
0.1.56 put the project's source and test roots on PYTHONPATH in Docker and Compose containers. Root detection marks every folder with its own pyproject.toml / setup.py / requirements.txt plus its tests folder, so an Odoo project with OCA repositories got thousands of roots, and the joined value passed Linux's 128 KB limit for one environment string: the run failed with "Argument list too long (os error 7)". A local run hit the same limit.

A detected Source or Test root that is itself a package (holds __init__.py) is no longer an import root; folders the user marked still count. Runs, debug sessions, consoles and the module search for navigation and pytest fixtures share this list.

Fixes #7083
2026-12-01 08:02:01 +08:00
1182 змінених файлів з 97891 додано та 4923 видалено

No files matched your search

+129
Переглянути файл
@@ -0,0 +1,129 @@
---
name: pr
description: Prepare and open an OpenIDEA pull request that a maintainer can accept from its description — scope check, the checks CI runs, evidence chosen by the kind of change, UX consistency review, and a filled-in template. Use before opening or updating a PR ("提 pr", "open a PR", "写 PR 描述", "准备验收证据").
---
# Open a pull request with evidence
A reviewer should be able to accept the PR from its description: what changed, why, and proof
that it works and didn't break its neighbours. Evidence is the part people skip; it is required.
## 1. Scope
- One problem per PR. If the description needs more than 2–4 sentences, split it.
- `Closes #<n>` when it resolves an issue. Read the issue's comments first: a maintainer may
already have decided how it should behave.
- The diff contains only what the problem needs: no drive-by refactors, formatting of untouched
files, generated files you didn't need to regenerate, or local IDE state (`.openidea/`).
- A product decision you can't make (layout or navigation restructure, a changed default, an
unclear expected behaviour) → ask in the issue, label `needs-decision`, stop.
- Title in Conventional Commits, written as the commit you want on `main`:
`fix(editor): keep the caret visible after folding`. It describes the change, not the
process; no references to screenshots, other products or "parity".
## 2. Checks
Run what CI runs for the parts you touched (`AGENTS.md` § Before opening a PR). Run long checks
one at a time. Paste the command and its result line (`test result: ok. 412 passed`,
`Tests 87 passed`), not "tests pass".
Easy to miss:
| You touched | Also run |
| --------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| Any `.ts`/`.tsx`, including tests | `pnpm typecheck` |
| A feature's UI | every spec under `e2e/` whose name contains the feature |
| New regex in frontend code | `pnpm vitest run src/platform/webkitCompatibility.test.ts` |
| Text catalog keys | `pnpm vitest run src/platform/locales/textCatalog.test.ts src/platform/i18n.test.ts` |
| `tokens.css` | `pnpm gen:theme-docs`, then the full `pnpm test` |
| Moved or removed exports | `pnpm knip` |
| A `pub fn` signature | `cargo test -p <crate>` (all targets), or workspace clippy |
| A new crate dependency, or imports in files the smoke runs load | `pnpm vitest run scripts/smoke-paths.test.ts` |
| IPC types | `pnpm gen:bindings`, commit `src/bindings.ts` |
| `wit/` or the plugin SDK | `plugins/build.sh`, commit the rebuilt `dist/` |
## 3. Evidence
Pick every row that applies. Evidence must come from the final commit of the branch; re-take it
after review changes that affect it.
| Change | Evidence |
| ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Bug fix | A test that fails on `main` and passes on the branch (name it), or exact steps from a fresh start with the before/after result |
| Visible UI | `before.png` / `after.png` at the same state and window size. Every theme the change touches (at least Islands Light and Islands Dark when colours, borders or icons change). The narrow case when width matters |
| Interaction: multi-step, drag and drop, keyboard, focus, animation | A short recording (GIF/MP4), or numbered screenshots of each step |
| Keyboard shortcut or action | Where it appears (Find Action, menu, keymap settings) and that it doesn't clash in the default keymaps |
| Code intelligence / language support | Which `fixtures/` project, `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` output; for Java, `pnpm eval --only <id>` numbers before/after |
| Run / debug | `pnpm smoke smoke/run.test.ts -t <language>` or `smoke/debug.test.ts`, plus a screenshot of the Run/Debug tool window |
| Performance | Before/after numbers on the same machine and build type (`pnpm perf`, `pnpm perf:rust`, or the exact measurement), and evidence the results are identical: a fast path must return the same results or fall back |
| Windows / Linux only | The platform's CI job, and a screenshot or log from a real machine. Say plainly if you couldn't run it on that platform |
| Backend / IPC | Test output; logs for behaviour tests can't reach |
| Remote development / containers / WSL | The flow against a real `openidea-server` host or container, with a screenshot or log |
| Plugin API / `wit/` | A sample plugin exercising the change, and the rebuilt `dist/` |
| Settings / persisted data / migrations | Start from data written by the previous release and show it still loads and behaves the same |
| Security fix | A test for the attack case. Describe the class of problem only; follow `SECURITY.md` for anything not yet public |
| Copy, docs, pure refactor | The commands run, and "No visible change" / "no behaviour change" stated |
Also state what else the change could affect (other languages, platforms, entry points such as
menu / context menu / shortcut, other themes) and how you checked each.
How to capture:
- Use the `verify` skill to drive the app and take screenshots. Before: on `main` (or with the
fix reverted). After: on the branch, same state and window size.
- Crop to the relevant area when the window is large, but keep enough context to locate it.
- Drag screenshots and recordings into the PR description on GitHub. Never commit them.
- No real credentials, tokens, private repository names or personal paths in screenshots or logs.
## 4. UX consistency
For any change users can see, review it against `DESIGN.md`, `PRODUCT.md` and
`docs/en/contribute/guidelines/ui.mdx` before taking the "after" screenshots:
- Tokens only; spacing on the `--space-*` scale; icons from `src/ui/icons.tsx`; no emoji.
- Built from `src/ui/` primitives and workbench contributions; it looks like its neighbours
(same row height, font size, padding, hover/selection, empty state) rather than new.
- Same action, same name, place and shortcut as elsewhere in the IDE.
- Keyboard reachable, visible focus, focus returns sensibly; `aria-label` on icon buttons.
- Every new string in `en.json` and `zh.json`; long translations don't break the layout.
- Light and dark, default and narrow widths all look right.
- The Impeccable design skills can help critique and polish; they read `DESIGN.md`,
`PRODUCT.md` and `.impeccable/`.
A layout or navigation restructure needs a maintainer decision first (§ 1).
## 5. Description
Fill in `.github/pull_request_template.md`; keep it short and plain:
```markdown
Closes #123
## What and why
<The change a user notices, and the root cause. 2–4 sentences.>
## How it was verified
- [x] Bug fix: `pnpm vitest run src/features/editor/folding.test.ts` — the new
`keeps caret visible after fold` fails on main, passes here (12 passed)
- [x] Visible UI: before / after (Islands Light, Islands Dark)
<screenshots>
- `pnpm typecheck`, `pnpm lint`, `pnpm e2e e2e/editor-folding.spec.ts` — all pass
- Also affected: folding from the gutter and from ⌘- — both checked in the app
## Review focus
<Optional.>
```
The `PR check` workflow labels the PR `needs-info` when **How it was verified** is empty, or when
the PR changes UI files and the section has no screenshot or recording and doesn't say
"No visible change".
## 6. Before you push
- Re-read the diff as the reviewer: anything unrelated, debug output, commented-out code,
leftover TODOs?
- Rebased on current `main`; checks re-run if the rebase changed anything they cover.
- Open as draft while evidence is missing; mark ready once it's in.
+59
Переглянути файл
@@ -0,0 +1,59 @@
---
name: verify
description: Build, launch and drive the OpenIDEA desktop app through the Tauri MCP bridge to verify a change at runtime.
---
# Verify OpenIDEA in the running app
## Launch
- Run the app from the worktree that holds the change: `pnpm tauri dev` in the background, logging
into your task's scratch subdirectory. Use `pnpm dev:app` instead when your checks call
`window.__TAURI__` from `execute_js`. The wrapper gives each worktree its own app identity, data,
settings and Vite port, so other worktrees and the installed app don't interfere. If it reports a
session already running for this worktree, reuse that one.
- Once the app is up, `pnpm dev:status` lists this worktree's MCP bridges. Pass the reported
`appIdentifier` (the port) on every `mcp__tauri__*` call. The MCP server is shared between
sessions: never `driver_session stop` without an `appIdentifier`, and re-check `document.title` /
`location.href` before acting if anything looks off.
- Make sure the binary contains the change: a session already running for this worktree may be an
older build. Restart it after Rust changes; frontend changes reload through Vite.
- After the app restarts, `driver_session start` again for your port (a stale session says "Already connected").
- If the `pnpm tauri dev` process exits while the app window stays open, Vite is gone and any webview
reload shows an empty `#root`. Stop that app and start the session again.
- Stop everything you started when done and nothing else; never use process-name kills.
## Driving
- `manage_window focus` before screenshots / timing-sensitive steps: a background window throttles timers
(debounced LSP / VCS refreshes stall, `setTimeout` promises in `execute_js` time out) and native
screenshots come back black.
- Settings is a separate native window `settings-main`; pass `windowId`, focus it before screenshotting.
- CodeMirror / xterm ignore MCP `type`. Focus the element, then `document.execCommand('insertText', false, text)`.
For xterm Enter, dispatch a `keydown` (`key: 'Enter', keyCode: 13`) on `.xterm-helper-textarea`.
- MCP clicks arrive with `event.detail === 0`; CodeMirror treats them as line-select clicks. Set the caret
through the view instead: `document.querySelector('.cm-content').cmTile.view`.
- MCP `text` strategy can resolve to a hidden node; prefer coordinates (CSS px = image px × 0.9) or CSS selectors.
- CSS-module edits often trigger a full page reload in dev: dialogs close, Run sessions and terminal
scrollback reset, and each reload spawns a fresh shell. Re-open what you were testing.
## Evidence
- For UI or interaction changes, capture `before.png` (on `main` or with the fix reverted) and
`after.png` at the same state and window size, into your task's scratch subdirectory. Multi-step
flows: a numbered series (`after-1.png`, `after-2.png`, ...). When colours, borders or icons
change, take each in Islands Light and Islands Dark. The `pr` skill lists what evidence each
kind of change needs.
- Report the absolute paths; they go into the PR's **How it was verified** section and the triage
acceptance entry. Never commit screenshots to the feature branch.
## Fixture
`fixtures/` has sample projects (go-app, rust-app, ts-app, kotlin-gradle, polyglot). Copy one into
your scratch directory before editing it, and don't commit the IDE state it creates (`.openidea/`).
## Flows worth driving
⌘⇧O Goto File · ⌘⇧F Find in Files (preview scroll + highlight) · ⌘⇧A Find Action · editor edit/undo/autosave ·
Terminal (Unicode, venv) · Commit view at the default narrow width · Problems · Run → Stop · Project view
New / Delete (nested `a/b.txt` names) · ⌘, Settings search (+ Keymap filter) · Git Log on a repo without commits.
+1
Переглянути файл
@@ -0,0 +1 @@
../../.agents/skills/pr
+1
Переглянути файл
@@ -0,0 +1 @@
../../.agents/skills/verify
+7
Переглянути файл
@@ -11,3 +11,10 @@ package(=ide-clipboard) & (
)
'''
test-group = "windows-clipboard"
# The Subversion tests run svn against throwaway servers: none should take minutes. A test
# that hangs (a server left stopped) is ended after 5 minutes instead of waiting for svn's own
# timeout.
[[profile.default.overrides]]
filter = 'package(=ide-svn) | (package(=ide-host) & (binary(=svn) | binary(=ij_svn_roots)))'
slow-timeout = { period = "60s", terminate-after = 5 }
Бінарний файл не відображається.

До

Ширина:  |  Висота:  |  Розмір: 169 KiB

Після

Ширина:  |  Висота:  |  Розмір: 192 KiB

+14 -5
Переглянути файл
@@ -7,11 +7,20 @@
## How it was verified
<!-- Required. Commands you actually ran and their results; what else this could
affect and how you checked it still works.
Visible UI changes: before/after screenshots (not for removed UI or copy-only
changes). Multi-step interactions: a recording.
Backend changes: logs or command output. -->
<!-- Required, from the final version of this branch. Commands you actually ran and
their results; what else this could affect and how you checked it still works.
Then the evidence for each kind of change this PR makes (AGENTS.md § Issues & PRs):
- Bug fix: a test that fails on main and passes here, or exact repro steps
- Visible UI: before/after screenshots, same state and size; each theme touched
- Interaction (multi-step, drag, keyboard, focus): a recording
- Code intelligence / run / debug: language_smoke or smoke output on a fixture
- Performance: before/after numbers on the same machine, and the results unchanged
- Windows/Linux only: CI job plus a screenshot or log from a real machine
- Settings / persisted data: starting from the previous version's data
- Copy, docs, refactor, no UI change: write "No visible change"
Drag screenshots and recordings in here; don't commit them. -->
## Review focus
+17 -1
Переглянути файл
@@ -150,8 +150,18 @@ jobs:
- name: Linux deps
if: runner.os == 'Linux'
run: |
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf)
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf subversion sqlite3)
dpkg -s "${pkgs[@]}" >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y "${pkgs[@]}"; }
# The Subversion tests run the real svn, svnadmin and svnserve (and sqlite3, to write a
# working copy's database); with CI set they fail instead of skipping when these are
# missing. Linux gets them with the deps above; macOS has sqlite3. Windows runners skip them.
- name: Subversion (macOS)
if: runner.os == 'macOS'
run: command -v svnadmin >/dev/null || brew install subversion
- name: Subversion version
if: runner.os != 'Windows'
shell: bash
run: svn --version --quiet && svnadmin --version --quiet && svnserve --version --quiet && sqlite3 --version
# tauri-build checks that frontendDist exists.
- run: pnpm install --frozen-lockfile && mkdir -p dist
shell: bash
@@ -360,6 +370,12 @@ jobs:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
# src/features/dotnet/edit.test.ts and *.cli.test.ts run the real `dotnet` CLI; with CI set they fail, not skip, when it is missing.
- uses: actions/setup-dotnet@v5
with:
dotnet-version: |
10.0.x
11.0.x
- run: pnpm install --frozen-lockfile
- run: pnpm typecheck
- run: pnpm lint
+2 -1
Переглянути файл
@@ -36,6 +36,7 @@ on:
- "src/editor/core/cm/iconArea.ts"
- "src/editor/core/cm/inlineBg.ts"
- "src/editor/core/cm/localAppearance.ts"
- "src/editor/core/cm/lineNumberOptions.ts"
- "src/editor/lsp/availability.ts"
- "src/editor/lsp/diagnostics.ts"
- "src/editor/lsp/files.ts"
@@ -110,7 +111,7 @@ jobs:
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|lineNumberOptions|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
+20 -2
Переглянути файл
@@ -1,9 +1,9 @@
name: PR check
on:
# pull_request_target so the check can label PRs from forks. It never checks out
# or runs PR code: it only reads the PR title and description.
# or runs PR code: it only reads the PR title, description and changed file names.
pull_request_target:
types: [opened, edited, reopened, ready_for_review]
types: [opened, edited, reopened, ready_for_review, synchronize]
permissions:
issues: write
@@ -34,6 +34,24 @@ jobs:
const { owner, repo } = context.repo;
const issue_number = pr.number;
if (verified && verified[1].trim()) {
const section = verified[1];
const hasMedia =
/!\[[^\]]*\]\(|<img\b|<video\b|github\.com\/user-attachments\/|https?:\/\/\S+\.(png|jpe?g|gif|webp|mp4|mov|webm)\b/i.test(section);
const optedOut = /no visible change/i.test(section);
if (!hasMedia && !optedOut) {
const files = await github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number: issue_number, per_page: 100 });
const ui = files
.filter(f => f.status !== 'removed')
.map(f => f.filename)
.filter(name => /^src\/.*\.(tsx|css)$/.test(name) && !/\.(test|spec)\.tsx$/.test(name));
if (ui.length) {
const shown = ui.slice(0, 3).map(n => `\`${n}\``).join(', ') + (ui.length > 3 ? ', …' : '');
problems.push(`This PR changes UI files (${shown}). Add before/after screenshots, or a recording for interactions, to **How it was verified**; if nothing users see changed, write "No visible change" and say what you checked.`);
}
}
}
const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number });
const existing = comments.find(c => c.user.type === 'Bot' && c.body.includes(MARKER));
const labeled = pr.labels.some(l => l.name === LABEL);
+4 -2
Переглянути файл
@@ -284,6 +284,8 @@ jobs:
return;
}
// Bundle suffix → updater platform keys, as tauri-action names them.
// Nightly builds skip RPM because RPM rejects `-` in SemVer prerelease versions.
const nightly = tag.includes("-nightly.");
const windows = (arch, msi, nsis) => [
[msi, [`windows-${arch}`, `windows-${arch}-msi`]],
[nsis, [`windows-${arch}-nsis`]],
@@ -291,10 +293,10 @@ jobs:
const kinds = [
[/_aarch64\.AppImage$/, ["linux-aarch64", "linux-aarch64-appimage"]],
[/_arm64\.deb$/, ["linux-aarch64-deb"]],
[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]],
...(nightly ? [] : [[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]]]),
[/_amd64\.AppImage$/, ["linux-x86_64", "linux-x86_64-appimage"]],
[/_amd64\.deb$/, ["linux-x86_64-deb"]],
[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]],
...(nightly ? [] : [[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]]]),
[/_aarch64\.app\.tar\.gz$/, ["darwin-aarch64", "darwin-aarch64-app"]],
[/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]],
...windows("aarch64", /_arm64_en-US\.msi$/, /_arm64-setup\.exe$/),
+6 -5
Переглянути файл
@@ -33,12 +33,13 @@ target/
test-results/
playwright-report/
# Local AI agent files
AGENTS.md
CLAUDE.md
# Local AI agent files. Shared skills live in .agents/skills; .claude/skills links to them.
CLAUDE.local.md
.agents/
.claude/
.claude/*
!.claude/skills/
.claude/skills/*
!.claude/skills/pr
!.claude/skills/verify
# Local reference screenshots
pycharm-screenshots/
+197
Переглянути файл
@@ -0,0 +1,197 @@
# OpenIDEA — contributor guide
Rust + Tauri 2 desktop IDE with full-featured, multi-language code intelligence.
Visual style: rounded content islands on a grey frame, low-contrast greys, one cool accent;
Islands Light is the default theme. `src/styles/tokens.css` is the source of truth for colours
and metrics; `DESIGN.md` and `PRODUCT.md` describe the design system and who the product is for.
## Layout
- `crates/ide-*` — backend crates; one domain each. Depend on `ide-core` for shared
types; never reach into another crate's internals.
- `src-tauri/` — glue only: `state.rs` (AppState / Project), `commands/<domain>.rs`
(desktop-only commands; the adapters of `ide-host` commands are derived), `events.rs`.
No domain logic here.
- `src/bindings.ts` — generated by tauri-specta (`pnpm gen:bindings`). Never edit.
- `src/platform/` — ipc (`call`, `onIdeEvent`, `nextRequestId`), actions registry,
keymap + dispatcher, context keys / `when` clauses, project store.
- `src/workbench/contributions.ts` — extension points (tool windows, status items,
overlays, editor kinds) and cross-feature services (editor, tool windows, notifications).
- `src/ui/` — design-system primitives. `src/features/<name>/` — one feature each,
exporting `activate()` registered in `src/features/index.ts`.
- `languages/<id>.toml` — language definitions (detection, comments, LSP, DAP).
- `crates/ide-host` — the `openidea-server` binary for remote development and the
`openidea-plugin` CLI (plugin starter templates live in its `templates.rs`).
- `wit/` — plugin interface definitions; `plugins/` — sample and bundled plugins.
Plugin docs: `plugins/README.md`, `plugins/themes.md`.
- `java/` — JDT LS extension bundles (`java-usages`, `kotlin-bridge`) and the patched
Lombok agent, embedded into the app by `ide-sdk` / `ide-tools`.
- `e2e/` — Playwright UI tests (`pnpm e2e`). `evals/` — code-intelligence evals (`pnpm eval`).
`fixtures/` — sample projects per language for manual and automated testing.
- `docs/` — the Mintlify documentation site (`docs.json` navigation, `en/` and `zh/` pages);
preview with `npx mint dev` in `docs/`.
## Rules
- IPC coordinates: 0-based lines, **UTF-16** columns/offsets everywhere (`ide-core::text`).
- Every command returns `IdeResult<T>`; convert internal errors at the crate edge.
- Declare a command once, on its implementation: `#[command(trust = …)]` in `ide-host::ops`
plus its module's `domain!` list (Tauri adapter, server handler and bindings are derived);
desktop-only commands use `#[desktop_command(trust = …)]` and `desktop_domain!`.
- Streaming → `tauri::ipc::Channel<T>`; cancellable → UI-allocated `RequestId` +
`cancel_request`. Backend → UI notifications → `IdeEvent` via `EventSink`.
- Long work never blocks the UI thread or a Tauri command thread: use
`spawn_blocking`/rayon, honour `CancellationToken`.
- Frontend features never import each other; communicate via actions, contributions
and services. All user-invocable behaviour is an action with a stable id; default
shortcuts live in `src/platform/keymaps/`.
- Styling: CSS Modules + tokens only (no hex literals in components). Inline SVG
icons from `src/ui/icons.tsx`, never emoji. Real `<button>`/`<input>`; `aria-label` on icon buttons.
`gap` uses the `--space-*` scale (`src/styles/tokens.css`, 4px grid) where a value is on it.
- User-visible text goes through the text catalog: add every new string to both
`src/platform/locales/text/en.json` and `zh.json` (`textCatalog.test.ts` enforces it).
Other locales may lack entries; their UI shows the English text until a translator adds it.
- Keep comments sparse and purposeful; match surrounding style.
- New regular expressions in frontend code must run on WebKit (no lookbehind):
`src/platform/webkitCompatibility.test.ts` checks them.
- For GUI verification, prefer Tauri MCP; use Computer Use only when Tauri MCP is
unavailable or cannot cover the required checks.
## UX changes
A change to what users see or how they interact must look and behave like the rest of the IDE.
- `DESIGN.md` (colours, type, layout, components, Do's and Don'ts) and `PRODUCT.md`
(users, principles, accessibility) are the reference; `docs/en/contribute/guidelines/ui.mdx`
has the code-level rules. Build from `src/ui/` primitives and workbench contributions;
don't create a one-off control, colour or spacing when an existing one fits.
- Check every theme the change touches (at least Islands Light and Islands Dark) and narrow
sizes (e.g. the Commit tool window at its default width, a small window). Long translated
strings must not break the layout.
- Everything works from the keyboard; focus is visible and lands somewhere sensible when a
popup or dialog closes. Icon-only buttons have an `aria-label` and a tooltip.
- Follow the conventions users of this kind of IDE already know: the same action keeps the
same name, place and shortcut across views. Don't invent a new pattern for an existing one.
- Agent and MCP features follow good agent-tool practice: restrained, predictable, reversible.
- Restructuring a page layout or navigation, or changing a default behaviour, needs a
maintainer's decision first: ask in the issue and label it `needs-decision`.
- The Impeccable design skills may be used for design critique and polish; they read
`DESIGN.md`, `PRODUCT.md` and `.impeccable/`. A detector exception goes in
`.impeccable/config.json` with a reason.
## Issues & PRs
Follow `CONTRIBUTING.md` and `.github/pull_request_template.md`: one problem per PR
(`Closes #<n>` when it resolves an issue), reproduce first, keep the diff focused, short plain
description. Unclear product decisions → `needs-decision` and stop.
Every PR carries evidence a reviewer can accept without re-running everything, in
**How it was verified**. It must come from the final version of the branch:
| Change | Evidence |
| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| Bug fix | A test that fails before the fix and passes after, or exact reproduction steps with before/after result |
| Visible UI | Before/after screenshots at the same state and window size; each theme the change touches |
| Interaction (multi-step, drag, keyboard, focus) | A short recording or numbered screenshots |
| Code intelligence / language support | The fixture used and `language_smoke` output; `pnpm eval` numbers for Java |
| Run / debug | `pnpm smoke smoke/run.test.ts` / `smoke/debug.test.ts -t <language>` output |
| Performance | Before/after numbers on the same machine (`pnpm perf`, `pnpm perf:rust` or a stated measurement), plus proof the results are unchanged |
| Windows / Linux only | The platform's CI job, and a screenshot or log from a real machine |
| Backend / IPC | Test output; regenerated `src/bindings.ts` when types changed |
| Remote development | The flow against a real `openidea-server` host |
| Plugin API / `wit/` | `plugins/build.sh` run and `dist/` committed; a sample plugin using the change |
| Settings / persisted data | Behaviour when starting from data written by the previous version |
| Copy, docs, refactor | The commands run; "No visible change" when nothing users see changed |
Attach screenshots and recordings to the PR description; never commit them. The `pr` skill
has the full checklist.
## Skills
Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
`pr` prepares a pull request — checks to run, evidence for the kind of change, description;
`verify` drives the running app through Tauri MCP and captures screenshot evidence.
## Commands
- Optional: `mise install` provisions the contributor toolchain; `mise tasks` lists the task aliases.
See [Development setup](docs/en/contribute/setup.mdx). The direct commands below still work without mise.
- `pnpm tauri dev` — run the app with worktree isolation. Use Node 22.22.2 or later on the 22.x line.
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
this worktree's running MCP bridges and actual ports.
- `pnpm build` — typecheck + bundle frontend.
- `pnpm dogfood:local [--build-only]` (or `mise run dogfood:local`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
- `pnpm dogfood:all <remote_name> [--restart | --no-restart]` (or `mise run dogfood:all <remote_name>`) — run `dogfood:local` and `dogfood:remote <remote_name>` in parallel.
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
- `pnpm smoke smoke/run.test.ts -t <language>` — run and test that language's fixture through the
run store and a real `openidea-server` (build it first: `cargo build -p ide-host --bin openidea-server`).
- `pnpm smoke smoke/debug.test.ts -t <language>` — debug that fixture's entry point the same way, with
the debugger the IDE installs (on macOS, CodeLLDB and Delve may need Developer Mode:
`sudo DevToolsSecurity -enable`).
- `pnpm test`, `pnpm e2e`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm typecheck`,
`pnpm gen:bindings`.
- `pnpm perf` (UI interaction latency / frames / leaks), `pnpm perf:rust` (criterion
benches vs budgets). Budgets: `perf/budgets.json`.
- `pnpm eval [--only <id>] [--runs n] [--save-baseline]` — Java code intelligence (navigation,
usages, gutter markers) in the production workbench against a release `openidea-server` and
jdtls: time to feedback / first result / complete, results vs `evals/<language>/golden/`.
Report: `target/eval/report.json`. Goldens and `evals/budgets.json` are changed by people only.
Tool versions: `.github/tool-versions.env` (shared with Language smoke).
- `pnpm release:prepare <version>` — the release commit's changes: app version everywhere,
`Cargo.lock`, and the plugin API snapshot when `wit/` moved to a new version.
## Before opening a PR
Run what CI runs for the parts you touched:
- Rust: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,
`cargo nextest run --workspace`. After changing IPC types, run `pnpm gen:bindings` and
commit `src/bindings.ts`; CI fails if it differs.
- Frontend: `pnpm typecheck` (vitest does not type-check), `pnpm lint`, `pnpm format:check`,
`pnpm knip`, `pnpm test`, `pnpm build`, and every `e2e/` spec of the feature you touched.
- New text keys: `src/platform/locales/textCatalog.test.ts` and `src/platform/i18n.test.ts`.
New or renamed tokens: `pnpm gen:theme-docs`.
- Changed a `pub fn` signature in a crate: run that crate's whole `cargo test`, not one test.
- UI or runtime behaviour: verify in the running app (`.agents/skills/verify`) and collect
the evidence above (`.agents/skills/pr`).
## Pitfalls
- Run a subset of frontend tests with `pnpm vitest run <path>`. `pnpm test -- <path>` ignores
the filter and runs the whole suite, which takes several minutes.
- Don't run clippy while iterating: `pnpm tauri dev` compiles anyway. Run
`cargo fmt --all` + `cargo clippy -p <crate> --all-targets -- -D warnings` once, right
before committing. A cold build cache can take around 5 minutes. Run long checks one at
a time, not chained in one shell call that may hit the 10-minute tool timeout.
- `pnpm tauri dev` does a full debug build. Clippy only checks the code, so a passing clippy
doesn't make the first launch fast.
## Parallel worktrees
Several worktrees can be developed and run side by side.
- Create one per task: `git worktree add ../<name> -b <branch> origin/main`, then
`pnpm install` in it.
- Launch with `pnpm tauri dev` / `pnpm dev:app`, not the raw `pnpm exec tauri dev` CLI. The
wrapper starts Vite on a worktree-derived port (advancing if occupied), passes its actual
URL to Tauri, and reports an existing launcher instead of starting another for the same
worktree. HMR uses the Vite port.
- Debug app identity, data, settings, logs and single-instance scope follow the canonical
worktree path captured at build time, independent of launch cwd. Launching the same debug
binary again focuses its existing instance and forwards its path argument. Different
worktrees and the installed release can coexist. `--release` uses normal release identity
and bypasses the development wrapper.
- MCP bridge ports are dynamic (9223–9322). Use `pnpm dev:status`, connect to the reported
port, verify identifier/cwd, and pass `appIdentifier: <port>` explicitly. Do not assume the
default MCP session belongs to this worktree.
- Keep each worktree's Cargo output directory separate; do not point `CARGO_TARGET_DIR` or
`target` symlinks at a shared directory.
- Each worktree's first build is cold (several minutes) and `cargo build` output takes
around 9 GB; tests, clippy and incremental builds add more. Avoid running several heavy builds on one machine at the same time.
- Stop only processes started for the current worktree/session. Never use broad
process-name kills such as `pkill openidea`.
- When done: stop that worktree's app and dev session, delete its build output, then
`git worktree remove ../<name>`.
Symlink
+1
Переглянути файл
@@ -0,0 +1 @@
AGENTS.md
+8 -2
Переглянути файл
@@ -1,6 +1,7 @@
# Contributing to OpenIDEA
These rules apply to everyone, and to any coding agent working on their behalf.
Project layout, coding rules, commands, checks and the evidence a PR needs are in [AGENTS.md](AGENTS.md).
## Issues
@@ -26,7 +27,12 @@ These rules apply to everyone, and to any coding agent working on their behalf.
- **How it was verified** is required: the commands you ran and their results,
and what else the change could affect. Changes to what users see need before/after
screenshots; multi-step interactions need a recording. UI that goes away with a removed
feature, copy-only and non-visual changes don't; say what you checked instead.
feature, copy-only and non-visual changes don't; write "No visible change" and say what
you checked instead. [AGENTS.md](AGENTS.md#issues--prs) lists the evidence for each kind of
change (tests, smoke output, perf numbers, real-machine logs…).
- Changes to what users see follow [DESIGN.md](DESIGN.md) and the existing UI: tokens,
`src/ui/` primitives, both themes, keyboard access. Restructuring a layout or navigation
needs a maintainer's decision first.
- If a change needs a product decision you can't make, ask in the issue and stop
rather than guessing.
@@ -35,4 +41,4 @@ and the plugin API. Community plugins live in their authors' repositories and
are listed through [l0ng-ai/openidea-plugins](https://github.com/l0ng-ai/openidea-plugins);
see [`plugins/README.md`](plugins/README.md) § 8.1.
A check on each PR adds `needs-info` when the verification section is missing, and removes it once it's filled in.
A check on each PR adds `needs-info` when the verification section is missing, or when the PR changes UI files and the section has neither a screenshot nor a recording nor "No visible change". It removes the label once that's fixed.
Створено
+33 -2
Переглянути файл
@@ -2766,6 +2766,7 @@ dependencies = [
"gix-ignore",
"gix-index",
"gix-lock",
"gix-mailmap",
"gix-note",
"gix-object",
"gix-odb",
@@ -3132,6 +3133,18 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "gix-mailmap"
version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a30866257cc7f0af5b85f98a9e87dc73e46de8cb1838ee18c9dbe08a2461717e"
dependencies = [
"bstr",
"gix-actor",
"gix-date",
"gix-error",
]
[[package]]
name = "gix-note"
version = "0.3.1"
@@ -4166,7 +4179,7 @@ dependencies = [
"ide-tools",
"ide-vcs",
"ide-vfs",
"libsqlite3-sys",
"jiff",
"parking_lot 0.12.5",
"rustix",
"semver",
@@ -4174,12 +4187,13 @@ dependencies = [
"serde_json",
"sha1 0.10.7",
"specta",
"sqlx",
"tempfile",
"tokio",
"toml 0.9.12+spec-1.1.0",
"toml_edit 0.25.17+spec-1.1.0",
"tracing",
"uuid",
"which",
]
[[package]]
@@ -4514,6 +4528,7 @@ dependencies = [
"ide-spell",
"ide-ssh",
"ide-streams",
"ide-svn",
"ide-syntax",
"ide-terminal",
"ide-text",
@@ -4847,6 +4862,7 @@ dependencies = [
"parking_lot 0.12.5",
"portable-pty",
"quick-xml 0.42.0",
"regex",
"serde",
"serde_json",
"specta",
@@ -4972,6 +4988,21 @@ dependencies = [
"tree-sitter",
]
[[package]]
name = "ide-svn"
version = "0.1.56"
dependencies = [
"dunce",
"encoding_rs",
"ide-core",
"ide-vcs",
"parking_lot 0.12.5",
"quick-xml 0.42.0",
"tempfile",
"which",
"windows-sys 0.61.2",
]
[[package]]
name = "ide-syntax"
version = "0.1.56"
+3 -1
Переглянути файл
@@ -24,6 +24,7 @@ ide-jsonrpc = { path = "crates/ide-jsonrpc" }
ide-lsp = { path = "crates/ide-lsp" }
ide-dap = { path = "crates/ide-dap" }
ide-vcs = { path = "crates/ide-vcs" }
ide-svn = { path = "crates/ide-svn" }
ide-github = { path = "crates/ide-github" }
ide-terminal = { path = "crates/ide-terminal" }
ide-run = { path = "crates/ide-run" }
@@ -90,6 +91,7 @@ trash = "5"
blake3 = "1"
dunce = "1"
dirs = "6"
jiff = "0.2"
memmap2 = "0.9"
zip = { version = "9.2.3", default-features = false, features = ["deflate"] }
flate2 = "1"
@@ -99,6 +101,7 @@ tar = "0.4"
grep-searcher = "0.1"
grep-regex = "0.1"
regex-syntax = "0.8"
regex = "1"
grep-matcher = "0.1"
nucleo-matcher = "0.3"
redb = "4"
@@ -115,7 +118,6 @@ reqwest = { version = "0.13", default-features = false, features = ["rustls-no-p
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
rustls-platform-verifier = "0.7"
# Until SQLx releases its libsqlite3-sys 0.39 update (RUSTSEC-2026-0459).
libsqlite3-sys = { version = "0.39", features = ["bundled"] }
sqlx = { version = "0.9", git = "https://github.com/l0ng-ai/sqlx", rev = "9894985a1babc7e6bc0437da4fd43e3143184073", default-features = false, features = ["runtime-tokio", "tls-rustls-ring-webpki", "sqlite", "postgres", "mysql"] }
tiberius = { version = "0.13", default-features = false, features = ["tds73", "rustls", "sql-browser-tokio"] }
# Pure-Rust thin Oracle driver; pinned to the beta until it stabilizes.
+5
Переглянути файл
@@ -6,6 +6,11 @@ contributors as part of the IntelliJ Platform (https://github.com/JetBrains/inte
https://github.com/JetBrains/intellij-plugins), licensed under the Apache License 2.0.
Copyright 2000-2026 JetBrains s.r.o. and contributors.
The Subversion tests (crates/ide-svn/tests/matrix.rs) take the tree-conflict scenarios,
their names and file contents from IntelliJ's svn4idea TreeConflictData
(plugins/svn4idea/testSource/org/jetbrains/idea/svn/), Apache License 2.0, Copyright
2000-2026 JetBrains s.r.o. and contributors.
Some Simplified Chinese UI terms follow the Visual Studio Code Simplified Chinese
language pack (https://github.com/microsoft/vscode-loc), Copyright (c) Microsoft
Corporation, licensed under the MIT License.
+1 -1
Переглянути файл
@@ -71,7 +71,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
## Community
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
- [Discord](https://discord.gg/AsZqMgxZm) — questions, feedback and release news.
- WeChat group — scan to join:
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
+1 -1
Переглянути файл
@@ -71,7 +71,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
## Topluluk
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
- [Discord](https://discord.gg/AsZqMgxZm): sorular, geri bildirim ve sürüm haberleri.
- WeChat grubu, katılmak için kodu okut:
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
+1 -1
Переглянути файл
@@ -69,7 +69,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
## 社区
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
- [Discord](https://discord.gg/AsZqMgxZm):提问、反馈和版本发布消息。
- 微信群,扫码加入:
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
+1 -1
Переглянути файл
@@ -4,7 +4,7 @@
`src/ui/brands/*.svg` use the unmodified logo paths from
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
## DuckDB symbol
+3 -2
Переглянути файл
@@ -15,18 +15,19 @@ ide-mcp.workspace = true
ide-jsonrpc.workspace = true
ide-vcs.workspace = true
ide-tools = { path = "../ide-tools" }
libsqlite3-sys.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
sqlx.workspace = true
tokio.workspace = true
toml.workspace = true
toml_edit.workspace = true
tracing.workspace = true
parking_lot.workspace = true
dunce.workspace = true
jiff.workspace = true
uuid.workspace = true
tempfile.workspace = true
which = "8"
semver = "1"
sha1 = "0.10"
+18
Переглянути файл
@@ -53,6 +53,24 @@ pub(crate) fn auth_required(code: i64, message: &str) -> bool {
.any(|w| w == ["logged", "out"] || w == ["sign", "in"] || w == ["log", "in"] || w == ["login", "required"])
}
/// Whether a failed request only means the agent hasn't finished starting up: OpenCode
/// rejects session opens until the location's plugins and MCP servers finish activating
/// (`ServiceUnavailableError`, "Location plugins did not finish activating") and reports
/// an unavailable server as `ServerUnavailable`. Both arrive as internal errors naming
/// the cause in `data.errorName`; retrying them once activation completes succeeds.
pub(crate) fn service_warming_up(error: &RpcError) -> bool {
let RpcError::Server { code: codes::INTERNAL_ERROR, message, data } = error else {
return false;
};
if let Some(name) = data.as_ref().and_then(|d| d.get("errorName")).and_then(Value::as_str)
&& matches!(name, "ServiceUnavailableError" | "ServerUnavailable")
{
return true;
}
let lower = message.to_lowercase();
lower.contains("did not finish activating") || lower.contains("opencode server is unavailable")
}
/// The capabilities this client offers, in v1 form.
fn client_capabilities() -> Value {
json!({
+34
Переглянути файл
@@ -52,6 +52,40 @@ fn auth_required_matches_authentication_words_and_sign_in_phrases() {
}
}
#[test]
fn service_warming_up_matches_opencode_startup_races_only() {
for (code, message, data, expected) in [
(
codes::INTERNAL_ERROR,
"Internal error: Internal service failure",
Some(json!({"errorName": "ServiceUnavailableError"})),
true,
),
(
codes::INTERNAL_ERROR,
"Internal error: OpenCode server is unavailable",
Some(json!({"errorName": "ServerUnavailable"})),
true,
),
(codes::INTERNAL_ERROR, "Location plugins did not finish activating", None, true),
(
codes::INTERNAL_ERROR,
"Internal error: Internal service failure",
Some(json!({"errorName": "SQLiteError"})),
false,
),
(codes::INTERNAL_ERROR, "Internal error: Internal service failure", None, false),
(codes::INTERNAL_ERROR, "boom", None, false),
(AUTH_REQUIRED, "Authentication required", None, false),
] {
assert_eq!(
service_warming_up(&RpcError::Server { code, message: message.into(), data: data.clone() }),
expected,
"code={code}, message={message:?}, data={data:?}"
);
}
}
/// The messages of a fixture going `dir` (`in` or `out`).
pub(crate) fn frames(fixture: &str, dir: &str) -> Vec<Value> {
fixture
File diff suppressed because it is too large. Load diff
+3 -1
Переглянути файл
@@ -58,7 +58,9 @@ impl AgentManager {
if spec.source != AgentSource::Builtin {
return Ok(AgentCliUpdateResult::Unmanaged);
}
let Ok(npm) = which::which("npm") else { return Ok(AgentCliUpdateResult::Unmanaged) };
let Some(npm) = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path()) else {
return Ok(AgentCliUpdateResult::Unmanaged);
};
let program = spec.resolve_for_launch(&self.shared.paths.project_root).command;
match maintain(&npm, Path::new(&program), &builtin.command, pkg, offer, cancel) {
Err(e) if e.kind == ErrorKind::Unavailable => Ok(AgentCliUpdateResult::Error { code: e.message }),
+338 -1
Переглянути файл
@@ -131,7 +131,263 @@ fn is_bypass_mode(mode: &str) -> bool {
let lower = mode.to_lowercase();
let m: String =
lower.rsplit(['#', '/']).next().unwrap_or_default().chars().filter(char::is_ascii_lowercase).collect();
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous"
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous" || m == "autopilot"
}
fn upsert_choice(wanted: &mut Vec<crate::model::AgentConfigChoice>, id: &str, value: &str) {
if let Some(existing) = wanted.iter_mut().find(|c| c.id == id) {
existing.value = value.to_owned();
} else {
wanted.push(crate::model::AgentConfigChoice { id: id.to_owned(), value: value.to_owned() });
}
}
pub(crate) fn is_approval_option(opt: &AgentConfigOption) -> bool {
opt.id == CURSOR_APPROVAL || matches!(opt.category.as_deref(), Some("mode" | "permissions" | "approval"))
}
fn wanted_val(wanted: &[crate::model::AgentConfigChoice], id: &str) -> Option<String> {
wanted.iter().find(|c| c.id == id).map(|c| c.value.clone())
}
/// Applies an automation's permission policy (`mode`) to `config` and `wanted`, enforcing the
/// user's interactive approval setting (`interactive`) as a strict ceiling. When `mode` is `None`
/// (an in-session `/loop` or `Send Later` turn), clamps any bypass options down when `interactive`
/// is [`ide_core::settings::NewTaskApprovals::Ask`].
pub(crate) fn clamp_automation_permissions(
provider: &str,
mode: Option<crate::automation::AutomationPermissionMode>,
interactive: ide_core::settings::NewTaskApprovals,
config: &mut [AgentConfigOption],
wanted: &mut Vec<crate::model::AgentConfigChoice>,
) {
use crate::automation::AutomationPermissionMode;
use ide_core::settings::NewTaskApprovals;
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
return;
}
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
if !allow_bypass {
// Strip any explicit bypass choices from `wanted` first so they cannot re-elevate later.
wanted.retain(|c| match c.id.as_str() {
"mode" => !is_bypass_mode(&c.value),
"allow_all" | "permissions" => !matches!(c.value.to_ascii_lowercase().as_str(), "on" | "true"),
"approval" | CURSOR_APPROVAL => !c.value.eq_ignore_ascii_case("bypass"),
"approval_policy" => !c.value.eq_ignore_ascii_case("never"),
_ => true,
});
ask_for_approvals(config);
}
match provider {
"claude" | "claude-acp" => {
let cur_wanted = wanted_val(wanted, "mode");
let target = if allow_bypass {
match cur_wanted.as_deref() {
Some("default" | "plan" | "acceptEdits") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "bypassPermissions".to_owned(),
}
} else if interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::Assisted) {
match cur_wanted.as_deref() {
Some("default" | "plan") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "acceptEdits".to_owned(),
}
} else {
// Either Default mode or interactive policy is Ask (where interactive Claude starts in `default`).
match cur_wanted.as_deref() {
Some("plan") => "plan".to_owned(),
_ => "default".to_owned(),
}
};
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
&& opt.values.iter().any(|v| v.value == target)
{
let id = opt.id.clone();
opt.current = Some(target.clone());
upsert_choice(wanted, &id, &target);
} else if mode.is_some() || cur_wanted.is_some() {
upsert_choice(wanted, "mode", &target);
}
}
"codex" | "codex-acp" => {
let cur_wanted = wanted_val(wanted, "mode");
let target = if allow_bypass {
match cur_wanted.as_deref() {
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "full-access".to_owned(),
}
} else if mode == Some(AutomationPermissionMode::Default) {
"read-only".to_owned()
} else if mode.is_some() {
// Assisted, or AllowAll clamped by interactive Ask (`ask_for_approvals` maps full-access -> ask).
match cur_wanted.as_deref() {
Some("read-only") => "read-only".to_owned(),
_ => "ask".to_owned(),
}
} else {
// Scheduled /loop or Send Later under interactive Ask: never full-access.
match cur_wanted.as_deref() {
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "ask".to_owned(),
}
};
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
&& opt.values.iter().any(|v| v.value == target)
{
let id = opt.id.clone();
opt.current = Some(target.clone());
upsert_choice(wanted, &id, &target);
} else if mode.is_some() || cur_wanted.is_some() {
upsert_choice(wanted, "mode", &target);
}
}
"copilot" => {
if allow_bypass {
if !matches!(wanted_val(wanted, "allow_all").as_deref(), Some("off" | "false")) {
upsert_choice(wanted, "allow_all", "on");
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
opt.current = Some("on".into());
}
}
} else {
upsert_choice(wanted, "allow_all", "off");
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
opt.current = Some("off".into());
}
let non_auto = match wanted_val(wanted, "mode").as_deref() {
Some("plan") => "plan",
_ => "agent",
};
if mode.is_some() || config.iter().any(|o| o.id == "mode" && o.current.as_deref() == Some("autopilot"))
{
upsert_choice(wanted, "mode", non_auto);
}
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode")
&& (mode.is_some() || opt.current.as_deref() == Some("autopilot"))
&& opt.values.iter().any(|v| v.value == non_auto)
{
opt.current = Some(non_auto.into());
}
}
}
"cursor" => {
let target = if allow_bypass && wanted_val(wanted, CURSOR_APPROVAL).as_deref() != Some("ask") {
"bypass"
} else {
"ask"
};
upsert_choice(wanted, CURSOR_APPROVAL, target);
if let Some(opt) = config.iter_mut().find(|o| o.id == CURSOR_APPROVAL) {
opt.current = Some(target.into());
}
}
_ => {
if allow_bypass {
let user_chose_non_bypass = config.iter().any(|o| {
is_approval_option(o)
&& wanted.iter().any(|c| {
c.id == o.id && o.category.as_deref().and_then(bypass_value).is_some_and(|b| !b(&c.value))
})
});
if !user_chose_non_bypass {
apply_bypass_approvals(config);
}
}
}
}
// Ensure every approval-bearing option in `config` has its enforced value mirrored in `wanted`
// so `open_session` actively configures the live session even if the CLI's own config differs.
for opt in config.iter().filter(|o| is_approval_option(o)) {
if let Some(cur) = opt.current.as_deref() {
upsert_choice(wanted, &opt.id, cur);
}
}
}
/// Verifies that the session's reported `config` options do not exceed the required automation
/// permission ceiling (`min(mode, interactive)`). Returns `Err(reason)` if the provider remained
/// in a more permissive mode than allowed.
pub(crate) fn verify_automation_ceiling(
provider: &str,
mode: Option<crate::automation::AutomationPermissionMode>,
interactive: ide_core::settings::NewTaskApprovals,
config: &[AgentConfigOption],
) -> Result<(), String> {
use crate::automation::AutomationPermissionMode;
use ide_core::settings::NewTaskApprovals;
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
return Ok(());
}
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
if !allow_bypass && bypass_approvals(config) {
return Err("Agent did not confirm the required approval ceiling (session remained in bypass mode).".into());
}
let cur_of = |id: &str| config.iter().find(|o| o.id == id).and_then(|o| o.current.as_deref());
let mode_cur = config
.iter()
.find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
.and_then(|o| o.current.as_deref());
if !allow_bypass {
match provider {
"claude" | "claude-acp" => {
if let Some(cur) = mode_cur {
let allowed = if interactive == NewTaskApprovals::Bypass
&& mode == Some(AutomationPermissionMode::Assisted)
{
matches!(cur, "default" | "plan" | "acceptEdits")
} else {
matches!(cur, "default" | "plan")
};
if !allowed {
return Err(format!(
"Claude session remained in mode '{cur}', exceeding the required approval ceiling."
));
}
}
}
"codex" | "codex-acp" => {
if let Some(cur) = mode_cur {
let allowed = if mode == Some(AutomationPermissionMode::Default) {
cur == "read-only"
} else if mode.is_some() {
matches!(cur, "read-only" | "ask")
} else {
matches!(cur, "read-only" | "ask" | "auto")
};
if !allowed {
return Err(format!(
"Codex session remained in mode '{cur}', exceeding the required approval ceiling."
));
}
}
}
"copilot" => {
if let Some(cur) = cur_of("allow_all")
&& matches!(cur.to_ascii_lowercase().as_str(), "on" | "true")
{
return Err("Copilot session kept allow_all enabled above the approval ceiling.".into());
}
if let Some(cur) = mode_cur
&& cur.eq_ignore_ascii_case("autopilot")
{
return Err("Copilot session remained in autopilot mode above the approval ceiling.".into());
}
}
"cursor" if cur_of(CURSOR_APPROVAL).is_some_and(|cur| cur.eq_ignore_ascii_case("bypass")) => {
return Err("Cursor session remained in bypass mode above the approval ceiling.".into());
}
_ => {}
}
}
Ok(())
}
/// The settings in a `session/new` or `session/load` result: its select `configOptions`,
@@ -669,6 +925,87 @@ mod tests {
);
}
#[test]
fn automation_permissions_respect_interactive_approval_ceiling() {
use crate::automation::AutomationPermissionMode;
use crate::model::AgentConfigChoice;
use ide_core::settings::NewTaskApprovals;
let claude_opts = || {
options_of(&json!({"configOptions": [{
"id": "mode", "category": "mode", "type": "select", "currentValue": "bypassPermissions",
"defaultValue": "default",
"options": [
{"value": "default"}, {"value": "acceptEdits"}, {"value": "plan"}, {"value": "bypassPermissions"}
]
}]}))
};
// Claude Assisted under interactive Bypass -> acceptEdits; under interactive Ask -> default!
let mut c = claude_opts();
let mut wanted = Vec::new();
clamp_automation_permissions(
"claude",
Some(AutomationPermissionMode::Assisted),
NewTaskApprovals::Bypass,
&mut c,
&mut wanted,
);
assert_eq!(c[0].current.as_deref(), Some("acceptEdits"));
assert!(wanted.iter().any(|w| w.id == "mode" && w.value == "acceptEdits"));
let mut c_ask = claude_opts();
let mut wanted_ask = vec![AgentConfigChoice { id: "mode".into(), value: "bypassPermissions".into() }];
clamp_automation_permissions(
"claude",
Some(AutomationPermissionMode::AllowAll),
NewTaskApprovals::Ask,
&mut c_ask,
&mut wanted_ask,
);
assert_eq!(c_ask[0].current.as_deref(), Some("default"));
assert_eq!(wanted_ask, vec![AgentConfigChoice { id: "mode".into(), value: "default".into() }]);
// Copilot AllowAll under interactive Ask clamps allow_all -> off and autopilot -> agent.
let mut copilot = options_of(&json!({"configOptions": [
{"id": "mode", "category": "mode", "type": "select", "currentValue": "autopilot",
"options": [{"value": "agent"}, {"value": "plan"}, {"value": "autopilot"}]},
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "on",
"options": [{"value": "off"}, {"value": "on"}]}
]}));
let mut copilot_wanted = vec![AgentConfigChoice { id: "allow_all".into(), value: "on".into() }];
clamp_automation_permissions(
"copilot",
Some(AutomationPermissionMode::AllowAll),
NewTaskApprovals::Ask,
&mut copilot,
&mut copilot_wanted,
);
assert_eq!(ids(&copilot), [("mode", Some("agent")), ("allow_all", Some("off"))]);
assert!(!bypass_approvals(&copilot));
// Codex Default -> read-only, Assisted -> ask, AllowAll + Ask -> ask, AllowAll + Bypass -> full-access.
let codex_opts = || {
options_of(&json!({"configOptions": [{
"id": "mode", "category": "mode", "type": "select", "currentValue": "full-access",
"defaultValue": "ask",
"options": [{"value": "read-only"}, {"value": "ask"}, {"value": "auto"}, {"value": "full-access"}]
}]}))
};
for (perm, interactive, expected) in [
(AutomationPermissionMode::Default, NewTaskApprovals::Bypass, "read-only"),
(AutomationPermissionMode::Assisted, NewTaskApprovals::Bypass, "ask"),
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Ask, "ask"),
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Bypass, "full-access"),
] {
let mut opts = codex_opts();
let mut w = Vec::new();
clamp_automation_permissions("codex", Some(perm), interactive, &mut opts, &mut w);
assert_eq!(opts[0].current.as_deref(), Some(expected), "{perm:?} + {interactive:?}");
assert!(w.iter().any(|c| c.id == "mode" && c.value == expected));
}
}
#[test]
fn command_sources_in_updates_and_stored_tasks() {
let update = json!({"availableCommands": [
+182 -1
Переглянути файл
@@ -1,7 +1,10 @@
//! ACP elicitation in form mode: the agent's restricted JSON Schema as form fields, and the
//! user's answer as the `elicitation/create` response.
use crate::model::{AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption};
use crate::model::{
AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption, AgentQuestion,
AgentQuestionOption,
};
use serde::Deserialize;
use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
use serde_json::{Map, Value, json};
@@ -10,6 +13,9 @@ use serde_json::{Map, Value, json};
/// anything else cancels it.
const DECLINE: &str = "decline";
/// What the question card sends for Skip.
const SKIP: &str = "reject";
/// The form `elicitation/create` asks for; `Err` when it asks for something else.
pub(crate) fn form_of(params: &Value) -> Result<AgentForm, String> {
if params.get("mode").and_then(Value::as_str) != Some("form") {
@@ -148,6 +154,97 @@ fn scalar(value: &Value) -> Option<String> {
}
}
/// The questions a form asks when it is an agent's question tool in form shape: every field
/// a choice, each followed by its own text field for a typed answer, named after it
/// (`question_0` + `question_0_custom` from claude-agent-acp's `AskUserQuestion`, `q0` +
/// `q0__other` from OMP's `ask`). They are shown and answered as the agent's questions, one
/// at a time like a native `AskUserQuestion` (#7359); [`answer_questions`] turns the answers
/// back into the form's values. `None` for any other form.
pub(crate) fn questions_of(form: &AgentForm, params: &Value, message: &str) -> Option<Vec<AgentQuestion>> {
let choices = form.fields.len() / 2;
if choices == 0 || form.fields.len() % 2 == 1 {
return None;
}
let properties = params.pointer("/requestedSchema/properties");
form.fields
.chunks(2)
.map(|pair| {
let [choice, text] = pair else { return None };
let asks = matches!(choice.kind, AgentFormFieldKind::Choice | AgentFormFieldKind::Choices)
&& !choice.options.is_empty()
&& text.kind == AgentFormFieldKind::Text
&& text.name.len() > choice.name.len()
&& text.name.starts_with(&choice.name);
if !asks {
return None;
}
let (title, description) = (choice.title.trim(), choice.description.trim());
let (header, question) = if choices == 1 && !message.is_empty() {
(if title == message || title == choice.name { "" } else { title }, message)
} else if description.is_empty() {
("", title)
} else {
(if title == choice.name { "" } else { title }, description)
};
let schema = properties.and_then(|p| p.get(&choice.name));
let options = choice
.options
.iter()
.map(|option| AgentQuestionOption {
label: option.label.clone(),
description: option.description.clone(),
preview: schema.and_then(|s| option_preview(s, &option.value)),
})
.collect();
Some(AgentQuestion {
answer_key: Some(choice.name.clone()),
header: header.to_owned(),
question: question.to_owned(),
multi_select: choice.kind == AgentFormFieldKind::Choices,
options,
})
})
.collect()
}
/// The preview claude-agent-acp forwards beside an option (`_meta["_claude/askUserQuestionOption"]`).
fn option_preview(schema: &Value, value: &str) -> Option<String> {
let listed = schema.get("oneOf").or_else(|| schema.get("anyOf")).or_else(|| schema.pointer("/items/anyOf"));
listed?
.as_array()?
.iter()
.find(|o| o.get("const").and_then(Value::as_str) == Some(value))?
.pointer("/_meta/_claude~1askUserQuestionOption/preview")?
.as_str()
.map(str::to_owned)
}
/// The form reply to the answers of [`questions_of`]'s questions (question key to the picked
/// labels and the typed text): picked options as the choice's values, the text in the field
/// beside it. The question card's Skip declines the form; nothing passes through.
pub(crate) fn answer_questions(form: &AgentForm, reply: Option<&str>) -> Option<String> {
let reply = reply?;
if reply == SKIP {
return Some(DECLINE.to_owned());
}
let Ok(answers) = serde_json::from_str::<Map<String, Value>>(reply) else { return Some(reply.to_owned()) };
let mut values = Map::new();
for pair in form.fields.chunks(2) {
let [choice, text] = pair else { continue };
let items = answers.get(&choice.name).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str);
let (mut picked, mut typed) = (Vec::new(), Vec::new());
for item in items {
match choice.options.iter().find(|o| o.label == item) {
Some(option) => picked.push(json!(option.value)),
None => typed.push(item),
}
}
values.insert(choice.name.clone(), Value::Array(picked));
values.insert(text.name.clone(), json!([typed.join("\n")]));
}
Some(Value::Object(values).to_string())
}
/// A form is submitted from its own card; this option only names a declined form.
pub(crate) fn options() -> Vec<AgentPermissionOption> {
vec![AgentPermissionOption { id: DECLINE.to_owned(), name: "Decline".to_owned(), kind: "reject_once".to_owned() }]
@@ -295,6 +392,90 @@ mod tests {
assert_eq!(chosen, "count: 3; ok: no; size: Small; tags: a, b");
}
/// What claude-agent-acp sends for `AskUserQuestion` with two questions.
fn claude_questions() -> Value {
json!({
"sessionId": "s", "mode": "form", "message": "Please answer the following questions.",
"requestedSchema": { "type": "object", "properties": {
"question_0": { "type": "string", "title": "Delivery", "description": "How should it ship?",
"oneOf": [{ "const": "Util + table (Recommended)", "title": "Util + table (Recommended)",
"description": "Tracks tasks",
"_meta": { "_claude/askUserQuestionOption": { "preview": "```\nUtil\n```" } } },
{ "const": "Util only", "title": "Util only" }] },
"question_0_custom": { "type": "string", "title": "Other" },
"question_1": { "type": "array", "title": "Targets", "description": "Who receives it?",
"items": { "anyOf": [{ "const": "Members", "title": "Members" },
{ "const": "Tags", "title": "Tags" }] } },
"question_1_custom": { "type": "string", "title": "Other" }
} }
})
}
fn in_order(params: &Value, names: &[&str]) -> AgentForm {
let mut form = form_of(params).unwrap();
form.fields.sort_by_key(|f| names.iter().position(|n| *n == f.name));
form
}
#[test]
fn a_question_tool_form_is_asked_as_questions() {
let params = claude_questions();
let form = in_order(&params, &["question_0", "question_0_custom", "question_1", "question_1_custom"]);
let questions = questions_of(&form, &params, "Please answer the following questions.").unwrap();
let [delivery, targets] = questions.as_slice() else { panic!("{questions:?}") };
assert_eq!(
(
delivery.answer_key.as_deref(),
delivery.header.as_str(),
delivery.question.as_str(),
delivery.multi_select
),
(Some("question_0"), "Delivery", "How should it ship?", false)
);
assert_eq!(delivery.options[0].description, "Tracks tasks");
assert_eq!(delivery.options[0].preview.as_deref(), Some("```\nUtil\n```"));
assert_eq!(delivery.options[1].preview, None);
assert_eq!((targets.question.as_str(), targets.multi_select), ("Who receives it?", true));
let reply = json!({ "question_0": ["Util only", "keep it small"], "question_1": ["Members", "Tags"] });
let reply = answer_questions(&form, Some(&reply.to_string()));
let (response, chosen) = answer(&form, reply.as_deref());
assert_eq!(
response,
json!({ "action": "accept", "content": {
"question_0": "Util only", "question_0_custom": "keep it small", "question_1": ["Members", "Tags"]
} })
);
assert_eq!(chosen, "Delivery: Util only; Other: keep it small; Targets: Members, Tags");
assert_eq!(answer_questions(&form, Some(SKIP)).as_deref(), Some(DECLINE));
assert_eq!(answer_questions(&form, None), None);
}
#[test]
fn a_single_question_reads_from_the_message() {
let params = ask();
let form = in_order(&params, &["q0", "q0__other"]);
let questions = questions_of(&form, &params, "Which database?").unwrap();
assert_eq!((questions[0].header.as_str(), questions[0].question.as_str()), ("", "Which database?"));
assert_eq!(questions[0].options[0].label, "Postgres");
let reply = answer_questions(&form, Some(&json!({ "q0": ["SQLite"] }).to_string()));
assert_eq!(answer(&form, reply.as_deref()).0, json!({ "action": "accept", "content": { "q0": "sqlite" } }));
}
#[test]
fn other_forms_stay_forms() {
let only_choices = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
"size": { "type": "string", "enum": ["s", "l"] }, "env": { "type": "string", "enum": ["dev"] }
} } }))
.unwrap();
assert_eq!(questions_of(&only_choices, &json!({}), "Pick"), None);
let unrelated_text = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
"size": { "type": "string", "enum": ["s", "l"] }, "note": { "type": "string" }
} } }))
.unwrap();
assert_eq!(questions_of(&unrelated_text, &json!({}), "Pick"), None);
}
#[test]
fn declining_and_dismissing_send_no_content() {
let form = form_of(&ask()).unwrap();
+106 -128
Переглянути файл
@@ -27,6 +27,9 @@ pub struct ExternalSession {
pub cwd: Option<String>,
/// File modification time, ms since the epoch.
pub updated_ms: f64,
/// Another live process (VS Code, a terminal Copilot CLI) has it open: importing would let two
/// apps write the same session, so forking a copy is the safe choice.
pub in_use: bool,
}
/// Modification time of `path` in ms, else 0.
@@ -124,6 +127,7 @@ pub fn claude_sessions(config_dir: &Path, root: &Path) -> Vec<ExternalSession> {
title,
cwd,
updated_ms: mtime(&path),
in_use: false,
});
}
}
@@ -194,6 +198,7 @@ fn codex_file(path: &Path) -> Option<ExternalSession> {
session_id,
cwd,
updated_ms: mtime(path),
in_use: false,
})
}
@@ -332,80 +337,6 @@ fn copilot_prompt(path: &Path) -> Option<String> {
})
}
struct SqliteDb(*mut libsqlite3_sys::sqlite3);
impl SqliteDb {
fn open_readonly(path: &Path) -> Option<Self> {
if !path.is_file() {
return None;
}
let c_path = std::ffi::CString::new(path.to_str()?).ok()?;
let mut raw: *mut libsqlite3_sys::sqlite3 = std::ptr::null_mut();
let flags = libsqlite3_sys::SQLITE_OPEN_READONLY | libsqlite3_sys::SQLITE_OPEN_NOMUTEX;
let rc = unsafe { libsqlite3_sys::sqlite3_open_v2(c_path.as_ptr(), &mut raw, flags, std::ptr::null()) };
let guard = Self(raw);
if rc != libsqlite3_sys::SQLITE_OK || raw.is_null() {
return None;
}
unsafe {
libsqlite3_sys::sqlite3_busy_timeout(raw, 200);
}
Some(guard)
}
fn prepare(&self, sql: &str) -> Option<SqliteStmt> {
let c_sql = std::ffi::CString::new(sql).ok()?;
let mut stmt: *mut libsqlite3_sys::sqlite3_stmt = std::ptr::null_mut();
let rc =
unsafe { libsqlite3_sys::sqlite3_prepare_v2(self.0, c_sql.as_ptr(), -1, &mut stmt, std::ptr::null_mut()) };
let guard = SqliteStmt(stmt);
(rc == libsqlite3_sys::SQLITE_OK && !stmt.is_null()).then_some(guard)
}
}
impl Drop for SqliteDb {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe {
libsqlite3_sys::sqlite3_close(self.0);
}
}
}
}
struct SqliteStmt(*mut libsqlite3_sys::sqlite3_stmt);
impl SqliteStmt {
fn step(&self) -> bool {
unsafe { libsqlite3_sys::sqlite3_step(self.0) == libsqlite3_sys::SQLITE_ROW }
}
fn text(&self, col: std::ffi::c_int) -> Option<String> {
unsafe {
let ptr = libsqlite3_sys::sqlite3_column_text(self.0, col);
if ptr.is_null() {
return None;
}
let len = libsqlite3_sys::sqlite3_column_bytes(self.0, col);
if len <= 0 {
return None;
}
let bytes = std::slice::from_raw_parts(ptr, len as usize);
std::str::from_utf8(bytes).ok().map(str::to_owned)
}
}
}
impl Drop for SqliteStmt {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe {
libsqlite3_sys::sqlite3_finalize(self.0);
}
}
}
}
/// Candidate VS Code Agent Host SQLite databases (`<user>/globalStorage/agent-host.db`),
/// ordered oldest-first so a newer database wins when two editions share a session.
fn vscode_agent_host_dbs(home: &Path) -> Vec<PathBuf> {
@@ -462,9 +393,11 @@ fn pick_vscode_chat_title(
None
}
/// Session titles VS Code's Agent Host (`vscode-agent-host`) assigns to backing Copilot CLI
/// sessions (`sdkSessionId` → summary or user rename), read from `agent-host.db` without writing.
fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
/// The rows of one `agent-host.db` that map a backing Copilot session (`sdkSessionId`) to its
/// title. Read through a read-only connection that sets no `journal_mode` or other write pragma,
/// so VS Code's database is never changed. An unknown schema (a newer VS Code) reads nothing.
async fn read_vscode_chat_rows(path: &Path) -> Vec<[Option<String>; 5]> {
use sqlx::{Connection, Row};
const FULL_QUERY: &str = "\
SELECT c.provider_data, scs.title, scs.title_source, c.metadata, s.payload \
FROM chats_v2 c \
@@ -474,40 +407,85 @@ fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
ON s.session_uri = c.owner_session_uri \
WHERE c.tombstoned = 0 \
ORDER BY COALESCE(s.modified_time, 0) ASC, COALESCE(c.chat_order, 0) ASC";
const FALLBACK_QUERY: &str = "\
SELECT provider_data, NULL, NULL, metadata, NULL \
FROM chats_v2 \
WHERE tombstoned = 0";
const FALLBACK_QUERY: &str = "SELECT provider_data, NULL, NULL, metadata, NULL FROM chats_v2 WHERE tombstoned = 0";
let options = sqlx::sqlite::SqliteConnectOptions::new()
.filename(path)
.read_only(true)
.create_if_missing(false)
.busy_timeout(std::time::Duration::from_millis(200));
let Ok(mut conn) = sqlx::SqliteConnection::connect_with(&options).await else { return Vec::new() };
let rows = match sqlx::query(FULL_QUERY).fetch_all(&mut conn).await {
Ok(rows) => rows,
Err(_) => sqlx::query(FALLBACK_QUERY).fetch_all(&mut conn).await.unwrap_or_default(),
};
let _ = conn.close().await;
rows.iter().map(|row| std::array::from_fn(|i| row.try_get::<Option<String>, _>(i).ok().flatten())).collect()
}
/// Session titles VS Code's Agent Host (`vscode-agent-host`) assigns to backing Copilot CLI
/// sessions (`sdkSessionId` → summary or user rename). VS Code keeps these in its own
/// `agent-host.db` rather than in Copilot's `workspace.yaml`, so without them a renamed chat
/// would be listed under its first prompt. Best-effort: any failure leaves the CLI titles.
fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
let Some(home) = home else { return HashMap::new() };
let dbs = vscode_agent_host_dbs(home);
if dbs.is_empty() {
return HashMap::new();
}
// Callers are sync and may run on a runtime thread or none: a private runtime on its own
// thread works from either without blocking a runtime worker.
let rows: Vec<[Option<String>; 5]> = std::thread::scope(|scope| {
scope
.spawn(|| {
let Ok(rt) = tokio::runtime::Builder::new_current_thread().enable_all().build() else {
return Vec::new();
};
rt.block_on(async {
let mut all = Vec::new();
for path in &dbs {
all.extend(read_vscode_chat_rows(path).await);
}
all
})
})
.join()
.unwrap_or_default()
});
let mut titles = HashMap::new();
for path in vscode_agent_host_dbs(home) {
let Some(db) = SqliteDb::open_readonly(&path) else { continue };
let Some(stmt) = db.prepare(FULL_QUERY).or_else(|| db.prepare(FALLBACK_QUERY)) else { continue };
while stmt.step() {
let Some(pdata) = stmt.text(0) else { continue };
let Ok(pv) = serde_json::from_str::<serde_json::Value>(&pdata) else { continue };
let Some(sdk_id) = pv.get("sdkSessionId").and_then(serde_json::Value::as_str).filter(|s| !s.is_empty())
else {
continue;
};
let scs_title = stmt.text(1);
let scs_source = stmt.text(2);
let metadata = stmt.text(3);
let payload = stmt.text(4);
if let Some(title) = pick_vscode_chat_title(
scs_title.as_deref(),
scs_source.as_deref(),
metadata.as_deref(),
payload.as_deref(),
) {
titles.insert(sdk_id.to_owned(), title);
}
for [pdata, scs_title, scs_source, metadata, payload] in rows {
let Some(pdata) = pdata else { continue };
let Ok(pv) = serde_json::from_str::<serde_json::Value>(&pdata) else { continue };
let Some(sdk_id) = pv.get("sdkSessionId").and_then(serde_json::Value::as_str).filter(|s| !s.is_empty()) else {
continue;
};
if let Some(title) =
pick_vscode_chat_title(scs_title.as_deref(), scs_source.as_deref(), metadata.as_deref(), payload.as_deref())
{
titles.insert(sdk_id.to_owned(), title);
}
}
titles
}
/// Whether a live process holds the Copilot session in `dir`. Copilot writes `inuse.<pid>.lock`
/// while a CLI or SDK host (such as VS Code) has the session open; a crash leaves a stale one,
/// so only a lock whose process still runs counts.
fn copilot_session_in_use(dir: &Path) -> bool {
std::fs::read_dir(dir).into_iter().flatten().flatten().any(|entry| {
let name = entry.file_name();
let Some(pid) = name
.to_str()
.and_then(|n| n.strip_prefix("inuse."))
.and_then(|n| n.strip_suffix(".lock"))
.and_then(|n| n.parse::<u32>().ok())
else {
return false;
};
ide_core::process::process_alive(pid)
})
}
/// Copilot sessions of the project at `root`: `<config>/session-state/<id>`, titled by VS Code's
/// Agent Host summary/rename (when started from VS Code), their recorded CLI name, or first prompt.
/// Directories without an event log are unfinished sessions and are not listed.
@@ -535,10 +513,15 @@ pub fn copilot_sessions(copilot_home: &Path, home: Option<&Path>, root: &Path) -
.map(short)
.or_else(|| copilot_prompt(&events))
.unwrap_or_else(|| format!("Copilot session {}", &session_id[..session_id.len().min(8)]));
Some((
ExternalSession { provider: "copilot".to_owned(), session_id, title, cwd, updated_ms: mtime(&events) },
cli_user_named,
))
let session = ExternalSession {
provider: "copilot".to_owned(),
session_id,
title,
cwd,
updated_ms: mtime(&events),
in_use: copilot_session_in_use(&dir),
};
Some((session, cli_user_named))
})
.collect();
if !pending.is_empty() {
@@ -653,27 +636,16 @@ mod tests {
assert!(copilot_sessions(&tmp.path().join("nope"), None, Path::new("/work")).is_empty());
}
fn exec_sqlite(path: &Path, sql: &str) {
fn exec_sqlite(path: &Path, sql: &'static str) {
use sqlx::Connection;
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let c_path = std::ffi::CString::new(path.to_str().unwrap()).unwrap();
let c_sql = std::ffi::CString::new(sql).unwrap();
unsafe {
let mut db: *mut libsqlite3_sys::sqlite3 = std::ptr::null_mut();
assert_eq!(
libsqlite3_sys::sqlite3_open_v2(
c_path.as_ptr(),
&mut db,
libsqlite3_sys::SQLITE_OPEN_READWRITE | libsqlite3_sys::SQLITE_OPEN_CREATE,
std::ptr::null(),
),
libsqlite3_sys::SQLITE_OK
);
assert_eq!(
libsqlite3_sys::sqlite3_exec(db, c_sql.as_ptr(), None, std::ptr::null_mut(), std::ptr::null_mut()),
libsqlite3_sys::SQLITE_OK
);
libsqlite3_sys::sqlite3_close(db);
}
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
rt.block_on(async {
let options = sqlx::sqlite::SqliteConnectOptions::new().filename(path).create_if_missing(true);
let mut conn = sqlx::SqliteConnection::connect_with(&options).await.unwrap();
sqlx::raw_sql(sql).execute(&mut conn).await.unwrap();
conn.close().await.unwrap();
});
}
#[test]
@@ -727,6 +699,9 @@ mod tests {
&[json!({"type": "user.message", "data": {"content": "add a regression test"}})],
);
std::fs::write(unnamed.join("workspace.yaml"), "id: copilot-2\ncwd: /work/app\n").unwrap();
// A live holder marks the session in use; a lock left by a process that exited does not.
std::fs::write(session.join(format!("inuse.{}.lock", std::process::id())), "").unwrap();
std::fs::write(unnamed.join("inuse.2147483646.lock"), "").unwrap();
let empty = copilot_home.join("session-state/copilot-empty");
std::fs::create_dir_all(&empty).unwrap();
@@ -756,10 +731,13 @@ mod tests {
let named = by_id.remove("copilot-1").unwrap();
assert_eq!((named.provider.as_str(), named.title.as_str()), ("copilot", "Fix parser and tests"));
assert_eq!(named.cwd.as_deref(), Some("/work/app/api"));
assert!(named.in_use);
assert_eq!(by_id.remove("copilot-block").unwrap().title, "check why excalidraw font is not displayed");
assert_eq!(by_id.remove("copilot-vscode").unwrap().title, "Session");
assert_eq!(by_id.remove("copilot-placeholder").unwrap().title, "Greeting exchange");
assert_eq!(by_id.remove("copilot-2").unwrap().title, "add a regression test");
let unnamed = by_id.remove("copilot-2").unwrap();
assert_eq!(unnamed.title, "add a regression test");
assert!(!unnamed.in_use);
}
#[test]
+9 -2
Переглянути файл
@@ -16,14 +16,19 @@ pub(crate) fn from_content(content: &Value) -> Option<AgentImage> {
if let (Some(data), Some(mime)) = (str_of(content, "data"), str_of(content, "mimeType"))
&& mime.starts_with("image/")
{
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None, inline_number: None });
}
from_uri(str_of(content, "uri")?)
}
"resource" => {
let resource = content.get("resource")?;
let (data, mime) = (str_of(resource, "blob")?, str_of(resource, "mimeType")?);
mime.starts_with("image/").then(|| AgentImage { mime_type: mime.into(), data: data.into(), name: None })
mime.starts_with("image/").then(|| AgentImage {
mime_type: mime.into(),
data: data.into(),
name: None,
inline_number: None,
})
}
"resource_link" => {
let uri = str_of(content, "uri")?;
@@ -51,6 +56,7 @@ pub(crate) fn from_uri(uri: &str) -> Option<AgentImage> {
mime_type: mime.into(),
data: data.into(),
name: None,
inline_number: None,
});
}
uri.starts_with("file://").then(|| from_file(Path::new(&uri_path(uri))))?
@@ -67,6 +73,7 @@ pub(crate) fn from_file(path: &Path) -> Option<AgentImage> {
mime_type: mime.into(),
data: base64::engine::general_purpose::STANDARD.encode(bytes),
name: path.file_name().and_then(|n| n.to_str()).map(str::to_owned),
inline_number: None,
})
}
File diff suppressed because it is too large. Load diff
+29 -16
Переглянути файл
@@ -68,9 +68,25 @@ fn to_mcp_server(scope: McpScope, name: &str, cfg: &AgentMcpServer) -> McpServer
headers: cfg.headers.iter().map(|(k, v)| McpKeyValue { name: k.clone(), value: v.clone() }).collect(),
agents: cfg.agents.clone(),
unapproved: false,
plugin_id: None,
plugin_name: None,
}
}
/// Merges `projected` MCP servers from enabled agent plugins behind `configured` User and
/// Workspace servers so standalone settings entries always take precedence on name clashes.
pub fn merge_projected_servers(mut configured: Vec<McpServer>, projected: Vec<McpServer>) -> Vec<McpServer> {
let existing: HashSet<String> = configured.iter().map(|s| s.name.clone()).collect();
// Same-named servers from different bundles are distinct rows (ids are `plugin:<bundle>:<server>`).
let mut seen_projected: HashSet<String> = HashSet::new();
for srv in projected {
if !existing.contains(&srv.name) && seen_projected.insert(srv.id.clone()) {
configured.push(srv);
}
}
configured
}
fn normalize_provider(id: &str) -> &str {
id.strip_suffix("-acp").unwrap_or(id)
}
@@ -399,13 +415,8 @@ pub fn apply_save_json(
Ok(saved_names)
}
const COPILOT_PLUGIN_MANIFESTS: &[&str] = &[
".github/plugin/plugin.json",
".plugin/plugin.json",
".claude-plugin/plugin.json",
".cursor-plugin/plugin.json",
"plugin.json",
];
const COPILOT_PLUGIN_MANIFESTS: &[&str] =
&[".github/plugin/plugin.json", ".plugin/plugin.json", ".claude-plugin/plugin.json", "plugin.json"];
#[derive(Clone, PartialEq, Eq)]
enum SourceFormat {
@@ -1051,6 +1062,14 @@ fn extract_servers_from_root(root: &Value, fallback_name: Option<&str>) -> BTree
out
}
pub(crate) fn read_external_mcp_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
read_external_file(path)
}
pub(crate) fn parse_mcp_value(root: &Value) -> Result<BTreeMap<String, AgentMcpServer>, String> {
Ok(extract_servers_from_root(root, None))
}
fn read_external_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
let Ok(text) = std::fs::read_to_string(path) else {
return BTreeMap::new();
@@ -1088,15 +1107,7 @@ pub async fn probe_stdio_server(server: &AgentMcpServer, cwd: &Path) -> McpProbe
env.push((k.clone(), v.clone()));
}
}
let search_path = env
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
.map(|(_, v)| std::ffi::OsString::from(v))
.or_else(|| ide_core::process::host_var_os("PATH"))
.unwrap_or_default();
let program = ide_core::process::find_executable(raw_cmd, &search_path)
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|| raw_cmd.to_owned());
let program = ide_jsonrpc::resolve_spawn_program(raw_cmd, &env).to_string_lossy().into_owned();
let stderr_lines = std::sync::Arc::new(parking_lot::Mutex::new(Vec::<String>::new()));
let stderr_capture = stderr_lines.clone();
@@ -1259,6 +1270,8 @@ mod tests {
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
plugin_id: None,
plugin_name: None,
}
}
+24
Переглянути файл
@@ -453,6 +453,26 @@ pub fn discover_memories(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Age
out
}
/// Discovers all standalone memory entries across `workspaces` and `home`, then appends
/// projected rule/context entries from enabled agent plugins (deduplicated by canonical path).
pub fn discover_memories_with_plugins(
workspaces: &[PathBuf],
home: Option<&Path>,
projected: Vec<AgentMemoryEntry>,
) -> Vec<AgentMemoryEntry> {
let mut out = discover_memories(workspaces, home);
let mut seen: HashSet<PathBuf> =
out.iter().map(|e| dunce::canonicalize(&e.path.0).unwrap_or_else(|_| e.path.0.clone())).collect();
for mut entry in projected {
let canon = dunce::canonicalize(&entry.path.0).unwrap_or_else(|_| entry.path.0.clone());
entry.path = canon.clone().into();
if seen.insert(canon) {
out.push(entry);
}
}
out
}
/// Resolves the full [`AgentMemoryCatalog`] (entries + per-provider auto-memory statuses)
/// against `policy` and optional per-session `session_overrides`.
pub fn resolve_catalog(
@@ -1412,6 +1432,8 @@ fn parse_cursor_mdc(path: &Path, rel: &str) -> Option<AgentMemoryEntry> {
writable: false,
valid: true,
warnings,
plugin_id: None,
plugin_name: None,
})
}
@@ -1482,6 +1504,8 @@ fn parse_entry(
writable,
valid: true,
warnings,
plugin_id: None,
plugin_name: None,
})
}
+421 -3
Переглянути файл
@@ -71,6 +71,7 @@ pub enum InterruptionReason {
BackendStop,
UnexpectedExit,
NetworkTimeout,
CursorCapacity,
}
impl From<AgentShutdownReason> for InterruptionReason {
@@ -199,6 +200,10 @@ pub struct AgentTask {
/// Per-session recovery / network auto-retry window override in minutes (`0` = Off; `None` = inherit global).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recovery_window_mins: Option<u32>,
/// Provenance metadata when this task was created or continued by an [`crate::automation::AgentAutomation`].
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub automation: Option<Box<crate::automation::AgentTaskAutomation>>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
@@ -427,6 +432,9 @@ pub struct AgentImage {
/// Base64, without a `data:` prefix.
pub data: String,
pub name: Option<String>,
/// The `[Image #n]` label in the prompt text for an inline attachment.
#[specta(optional)]
pub inline_number: Option<u32>,
}
impl AgentImage {
@@ -454,11 +462,29 @@ pub struct AgentPrompt {
pub images: Vec<AgentImage>,
}
/// Provenance carried with a scheduled turn (`SameTask`, `Send Later`, or `/loop`), including
/// while queued behind a busy turn, so trust and approval ceilings are re-checked at dispatch.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduledTurnMeta {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub permissions: Option<crate::automation::AutomationPermissionMode>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub extra_choices: Vec<AgentConfigChoice>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub automation_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_schedule_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentQueued {
pub id: String,
pub prompt: AgentPrompt,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(skip)]
pub scheduled: Option<ScheduledTurnMeta>,
}
/// A setting chosen for a new task, by [`AgentConfigOption::id`].
@@ -616,6 +642,9 @@ pub enum AgentEntry {
/// Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn.
#[serde(default)]
recovery: Option<InterruptionReason>,
/// One-based automatic retry number for this continuation.
#[serde(default)]
retry_attempt: Option<u32>,
},
Agent {
text: String,
@@ -920,7 +949,7 @@ pub struct AgentModelCatalog {
}
/// Streamed to the window that subscribed (`AgentManager::subscribe_as`).
#[derive(Clone, Debug, Serialize, Type)]
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum AgentEvent {
/// A task was created or its metadata changed.
@@ -1018,6 +1047,14 @@ pub struct McpServer {
/// True when this Workspace server was added outside OpenIDEA and has not been approved yet.
#[serde(default)]
pub unapproved: bool,
/// Parent agent plugin ID when this server is live-projected from an enabled agent plugin bundle.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_id: Option<String>,
/// Display name of the parent agent plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_name: Option<String>,
}
/// Payload for creating or updating a user or workspace MCP server.
@@ -1051,8 +1088,8 @@ fn default_true() -> bool {
}
pub use ide_core::settings::{
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentProviderMemoryPolicy, AgentSkillMode,
AgentSkillPolicy, AutoMemoryMode,
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings,
AgentProviderMemoryPolicy, AgentSkillMode, AgentSkillPolicy, AutoMemoryMode,
};
/// Kind of discovered agent memory entry.
@@ -1165,6 +1202,14 @@ pub struct AgentMemoryEntry {
pub valid: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
/// Parent agent plugin ID when this rule/instruction is live-projected from an enabled agent plugin bundle.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_id: Option<String>,
/// Display name of the parent agent plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_name: Option<String>,
}
/// A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin.
@@ -1337,6 +1382,14 @@ pub struct AgentSkill {
pub valid: bool,
/// What validation found (`name` mismatch, missing or over-long description…).
pub warnings: Vec<String>,
/// Parent agent plugin ID when this skill comes from an agent plugin bundle.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_id: Option<String>,
/// Display name of the parent agent plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_name: Option<String>,
}
/// A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
@@ -1398,6 +1451,371 @@ pub struct McpDiscoveredServer {
pub header_keys: Vec<String>,
}
/// Which workspace, user, or CLI store an agent plugin bundle was discovered in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginSource {
/// `~/.copilot/installed-plugins/{<marketplace>,_direct}/*`.
#[default]
CopilotUser,
/// `~/.claude/plugins/installed_plugins.json` & `~/.claude/plugins/cache/*`.
ClaudeUser,
/// `~/.codex/plugins/cache/*`.
CodexUser,
/// `~/.gemini/extensions/*`.
GeminiUser,
}
/// Manifest format(s) recognized inside an agent plugin directory.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginFormat {
/// Vendor-neutral Agent Plugins 1.0 / 1.1 (`plugin.json` with `$schema`).
#[default]
AgentPluginsV1,
/// `.openidea/plugin.json`.
OpenIdea,
/// `.claude-plugin/plugin.json`.
Claude,
/// `.plugin/plugin.json`, `.github/plugin/plugin.json`, or legacy root `plugin.json`.
Copilot,
/// `.codex-plugin/plugin.json`.
Codex,
/// `gemini-extension.json`.
GeminiExtension,
}
/// Which policy layer decided an [`AgentPluginState::enabled`] status.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginOrigin {
/// Native harness configuration owns the enabled state.
#[default]
None,
/// Locked `Off` because the workspace is untrusted.
Trust,
/// Locked `Off` until executable capabilities (stdio MCP / lifecycle hooks) are approved.
Consent,
}
/// Data type of a plugin `userConfig` / `variables` / `settings` option.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginConfigFieldKind {
#[default]
String,
Number,
Boolean,
Secret,
}
/// One configurable option declared by an agent plugin (`userConfig`, `variables`, or Gemini `settings`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginConfigField {
pub key: String,
pub title: String,
#[serde(default)]
pub description: String,
pub kind: AgentPluginConfigFieldKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub default_value: Option<String>,
#[serde(default)]
pub required: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub env_var: Option<String>,
/// Current non-sensitive value (always empty when `kind == Secret`).
#[serde(default)]
pub value: String,
/// True when a secret is stored in OS Keychain for this field.
#[serde(default)]
pub has_secret: bool,
}
/// Summary of components and executable capabilities bundled inside an agent plugin.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginCapabilities {
pub skill_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub skill_names: Vec<String>,
pub mcp_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub mcp_names: Vec<String>,
pub rule_count: u32,
pub subagent_count: u32,
pub command_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub hook_files: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub stdio_commands: Vec<String>,
#[serde(default)]
pub has_lsp: bool,
#[serde(default)]
pub has_canvas_or_app: bool,
/// Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub native_harnesses: Vec<String>,
/// Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands` + `hook_files` contents).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub capability_hash: Option<String>,
#[serde(default)]
pub requires_consent: bool,
}
/// One discovered agent plugin bundle on disk (or built-in).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPlugin {
pub id: String,
pub name: String,
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub version: Option<String>,
pub description: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub author: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub homepage: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub repository: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub license: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace: Option<String>,
pub source: AgentPluginSource,
/// Scope this bundle is installed in. Native plugin folders and enablement config are
/// resolved relative to this scope.
pub scope: McpScope,
/// Workspace whose native configuration owns this row's enablement (workspace scope only).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub workspace_root: Option<IpcPath>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub also_in: Vec<AgentPluginSource>,
pub formats: Vec<AgentPluginFormat>,
pub root_path: IpcPath,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub manifest_path: Option<IpcPath>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub readme_path: Option<IpcPath>,
pub default_enabled: bool,
pub approx_tokens: u32,
pub capabilities: AgentPluginCapabilities,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub config_fields: Vec<AgentPluginConfigField>,
pub valid: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
}
/// Resolved agent plugin state paired with its policy origin and consent status.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginState {
pub plugin: AgentPlugin,
pub enabled: bool,
pub origin: AgentPluginOrigin,
/// True when executable stdio MCP / hook capabilities require user approval before enabling.
pub consent_required: bool,
}
/// Summary of a configured or repository-discovered plugin marketplace.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMarketplaceInfo {
pub id: String,
pub name: String,
pub source: String,
pub scope: McpScope,
/// True when discovered from a harness-native marketplace/configuration file.
pub discovered: bool,
}
/// Full catalog returned to Settings › Agents › Plugins.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginCatalog {
pub plugins: Vec<AgentPluginState>,
pub marketplaces: Vec<AgentMarketplaceInfo>,
pub projected_skills: u32,
pub projected_mcp_servers: u32,
pub projected_rules: u32,
}
/// One installable plugin entry listed inside a marketplace or repository.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMarketplaceCandidate {
pub name: String,
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub version: Option<String>,
pub description: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub author: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace: Option<String>,
/// Source spec to pass to preview (`"owner/repo[/subpath][@ref]"` or local directory path).
pub source_spec: String,
pub subpath: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub keywords: Vec<String>,
pub already_installed_user: bool,
pub already_installed_workspace: bool,
}
/// Result of browsing a marketplace (`owner/repo`, local marketplace path, or direct plugin repo).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMarketplaceBrowseResult {
pub source: String,
pub marketplace_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub owner: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub repo: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub git_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub tree_sha: Option<String>,
pub candidates: Vec<AgentMarketplaceCandidate>,
}
/// Whether a previewed plugin can be installed for one harness, and where it is already installed.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginInstallTarget {
pub harness: String,
pub supported: bool,
/// Why the harness cannot install this plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub reason: Option<String>,
/// Whether this harness can enable the plugin for just one workspace.
pub workspace_supported: bool,
/// This harness already records the plugin for the user / for the current workspace.
pub installed_user: bool,
pub installed_workspace: bool,
/// The harness store already holds this plugin version's folder, so installing replaces it.
pub overwrite_required: bool,
}
/// Security and capability preview of an agent plugin bundle before installation.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginPreview {
/// `"github"` or `"local"`.
pub source_kind: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub owner: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub repo: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub git_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub tree_sha: Option<String>,
/// Pinned commit SHA from preview when `source_kind == "github"`.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub commit_sha: Option<String>,
#[serde(default)]
pub subpath: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub local_path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace_source: Option<String>,
pub name: String,
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub version: Option<String>,
pub description: String,
pub formats: Vec<AgentPluginFormat>,
pub capabilities: AgentPluginCapabilities,
pub files: Vec<crate::skill_installer::RemoteSkillFile>,
pub scan_warnings: Vec<crate::skill_installer::SkillScanWarning>,
/// Per-harness install eligibility and existing installs for this plugin and marketplace.
pub targets: Vec<AgentPluginInstallTarget>,
}
/// Request payload to install a previewed agent plugin into a selected harness's native plugin directory.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct InstallAgentPluginRequest {
/// `"github"` or `"local"`.
pub source_kind: String,
#[serde(default)]
#[specta(optional)]
pub owner: Option<String>,
#[serde(default)]
#[specta(optional)]
pub repo: Option<String>,
#[serde(default)]
#[specta(optional)]
pub git_ref: Option<String>,
/// Pinned root tree SHA from preview when `source_kind == "github"`.
#[serde(default)]
#[specta(optional)]
pub tree_sha: Option<String>,
/// Pinned commit SHA from preview when `source_kind == "github"`.
#[serde(default)]
#[specta(optional)]
pub commit_sha: Option<String>,
#[serde(default)]
pub subpath: String,
#[serde(default)]
#[specta(optional)]
pub local_path: Option<String>,
#[serde(default)]
#[specta(optional)]
pub marketplace: Option<String>,
#[serde(default)]
#[specta(optional)]
pub marketplace_source: Option<String>,
pub scope: McpScope,
/// Native harness the plugin is installed for (`claude`, `copilot`, `codex`, or `gemini`).
pub harness: String,
#[serde(default)]
pub approve_capabilities: bool,
/// The preview's `capabilityHash` the user approved; the install is refused if the installed
/// folder resolves to different executable capabilities.
#[serde(default)]
#[specta(optional)]
pub approved_capability_hash: Option<String>,
#[serde(default)]
pub confirm_warnings: bool,
#[serde(default)]
pub overwrite: bool,
}
/// Selection of one server from an external MCP configuration source to import.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+31
Переглянути файл
@@ -1484,3 +1484,34 @@ async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env()
"claude-md-and-agents-md"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn session_merges_memory_settings_without_plugin_dir_or_plugin_config_injection() {
let cli = replay_cli(load_fixture("simple"));
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
let h =
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
let params = json!({
"cwd": h.cwd,
"mcpServers": [],
"_meta": {
"openidea": {
"memory": {
"claudeInstructionFiles": "claude-md-and-agents-md"
},
"plugins": { "activePlugins": ["azure", "linear@mkt"] }
}
}
});
h.request("session/new", params).await.unwrap();
let args = cli.launched.lock()[0].clone();
assert!(!args.iter().any(|a| a == "--plugin-dir"), "{args:?}");
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
assert_eq!(
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
"claude-md-and-agents-md"
);
assert!(parsed["pluginConfigs"]["azure"].is_null());
}
+6 -1
Переглянути файл
@@ -553,7 +553,12 @@ fn image_content(image: &crate::model::AgentImage) -> Value {
/// A generated image: inline (base64 PNG) or, when codex saved it, the file.
fn generated_image(item: &Value) -> Option<crate::model::AgentImage> {
if let Some(data) = item.get("result").and_then(Value::as_str).filter(|d| !d.is_empty()) {
let image = crate::model::AgentImage { mime_type: "image/png".into(), data: data.into(), name: None };
let image = crate::model::AgentImage {
mime_type: "image/png".into(),
data: data.into(),
name: None,
inline_number: None,
};
return Some(crate::model::AgentImage { mime_type: image.media_type().into(), ..image });
}
crate::images::from_file(std::path::Path::new(item.get("savedPath")?.as_str()?))
+4
Переглянути файл
@@ -1372,6 +1372,10 @@ fn build_prompt_payload(session_id: &str, blocks: &[Value]) -> (String, Vec<Valu
{
let path_str = saved.to_string_lossy().into_owned();
let name = saved.file_name().and_then(|n| n.to_str()).unwrap_or("image").to_owned();
// Copilot takes one text prompt and a separate attachments array.
if let Some(number) = block.pointer("/_meta/openideaImageNumber").and_then(Value::as_u64) {
text_parts.push(format!("[Image #{number}: {name}]"));
}
attachments.push(json!({ "type": "file", "path": path_str, "displayName": name }));
temp_files.push(saved);
}
+1 -5
Переглянути файл
@@ -25,11 +25,7 @@ use std::sync::Arc;
/// A path, or a name not found on `PATH`, is used as it is; a single match returns its
/// resolved path so Windows `PATHEXT` shims (`claude.cmd`, `codex.cmd`) start.
pub(crate) fn newest_install(command: &str) -> String {
let path = ide_core::process::host_var_os("PATH")
.or_else(|| ide_core::process::shell_env().find(|(k, _)| *k == "PATH").map(|(_, v)| v.to_owned()))
.unwrap_or_default();
// Windows: read afresh, so a tool the user installed since the IDE started is found too.
newest_install_in(command, &ide_core::process::with_user_path(&path))
newest_install_in(command, &ide_core::tool_path::search_path())
}
fn newest_install_in(command: &str, search: &std::ffi::OsStr) -> String {
File diff suppressed because it is too large. Load diff
+31 -11
Переглянути файл
@@ -114,7 +114,7 @@ impl ProviderSpec {
if !program.is_absolute() {
return self.login_hint.clone();
}
let search = ide_core::process::host_var_os("PATH").unwrap_or_default();
let search = ide_core::tool_path::search_path();
let builtin = builtin_spec(&self.id);
let on_path = builtin.as_ref().and_then(|b| ide_core::process::find_executable(&b.command, &search));
render_login_hint(self, program, on_path.as_deref(), cfg!(windows))
@@ -623,7 +623,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
command_overridden: builtin.as_ref().is_some_and(|b| b.command != spec.command),
command_editable: reason.is_none(),
command_read_only_reason: reason,
installed: installed(&spec.command),
installed: installed_with_env(&spec.command, &spec.env),
can_sign_in: spec.can_sign_in(Path::new("."), None),
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
env: spec.env.iter().cloned().collect(),
@@ -1057,19 +1057,23 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
specs
}
/// Whether `command` resolves to an executable (a path, or a name on `PATH`).
/// Whether `command` resolves to an executable (a path, or a name on [`ide_core::tool_path::search_path`]).
#[cfg(test)]
pub(crate) fn installed(command: &str) -> bool {
installed_with_env(command, &[])
}
pub(crate) fn installed_with_env(command: &str, env: &[(String, String)]) -> bool {
let p = Path::new(command);
if p.components().count() > 1 {
if p.components().count() > 1 || p.is_absolute() {
return is_executable(p);
}
let exts: &[&str] = if cfg!(windows) { &["exe", "cmd", "bat"] } else { &[] };
std::env::var_os("PATH").is_some_and(|path| {
std::env::split_paths(&path).any(|dir| {
let c = dir.join(command);
is_executable(&c) || exts.iter().any(|e| is_executable(&c.with_extension(e)))
})
})
if let Some((_, path)) = env.iter().find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
&& ide_core::process::find_executable(command, std::ffi::OsStr::new(path)).is_some()
{
return true;
}
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
}
fn is_executable(p: &Path) -> bool {
@@ -1326,6 +1330,22 @@ mod tests {
assert!(installed("sh"));
}
#[test]
fn installed_with_env_resolves_executables_on_provider_path() {
let dir = tempfile::tempdir().unwrap();
let name = if cfg!(windows) { "fake-agent.cmd" } else { "fake-agent" };
let exe = dir.path().join(name);
std::fs::write(&exe, "").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
}
assert!(!installed("fake-agent"));
let env = vec![("PATH".to_owned(), dir.path().to_string_lossy().into_owned())];
assert!(installed_with_env("fake-agent", &env));
}
#[test]
fn set_builtin_env_writes_and_clears_the_environment() {
let dir = tempfile::tempdir().unwrap();
+5 -3
Переглянути файл
@@ -320,7 +320,7 @@ fn is_builtin(id: &str) -> bool {
}
fn on_path(command: &str) -> bool {
which::which(command).is_ok()
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
}
/// `1.10.0` > `1.9.2`; a release is newer than its pre-releases.
@@ -708,7 +708,8 @@ fn install_npm(
emit: Emit,
) -> IdeResult<PathBuf> {
let (name, _) = split_npm_spec(&p.package);
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
let npm = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path())
.ok_or_else(|| IdeError::unavailable(format!("npm is required to install {name}")))?;
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
}
@@ -789,7 +790,8 @@ fn install_uv(
_ => format!("{name}=={}", entry.version),
};
check_spec(&spec)?;
let uv = which::which("uv").map_err(|_| IdeError::unavailable(format!("uv is required to install {name}")))?;
let uv = ide_core::process::find_executable("uv", &ide_core::tool_path::search_path())
.ok_or_else(|| IdeError::unavailable(format!("uv is required to install {name}")))?;
let bin = dir.join("bin");
let mut cmd = Command::new(uv);
cmd.args(["tool", "install", "--force"])
+1 -16
Переглянути файл
@@ -185,22 +185,7 @@ pub(crate) fn recorder(out: PathBuf) -> Connector {
let file = Arc::new(Mutex::new(String::new()));
let connections = Arc::new(Mutex::new(0u32));
Arc::new(move |spec, cwd, client, on_stderr| {
let program = {
let path = Path::new(&spec.command);
if path.components().count() > 1 || path.is_absolute() {
path.to_path_buf()
} else {
let search = spec
.env
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
.map(|(_, v)| std::ffi::OsString::from(v))
.or_else(|| ide_core::process::shell_env().find(|(k, _)| k == "PATH").map(|(_, v)| v))
.or_else(|| ide_core::process::host_var_os("PATH"))
.unwrap_or_default();
ide_core::process::find_executable(&spec.command, &search).unwrap_or_else(|| path.to_path_buf())
}
};
let program = ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env);
let mut cmd = tokio::process::Command::new(&program);
ide_core::process::prepare(cmd.as_std_mut());
let mut child = cmd
+517 -47
Переглянути файл
@@ -163,6 +163,15 @@ pub struct RepoRef<'a> {
pub trait SkillSourceFetcher: Send + Sync {
fn default_branch(&self, owner: &str, repo: &str, cancel: &CancellationToken) -> IdeResult<String>;
fn git_commit_sha(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<String>;
/// The root tree SHA recorded in commit `commit_sha`.
fn git_commit_tree_sha(
&self,
owner: &str,
repo: &str,
commit_sha: &str,
cancel: &CancellationToken,
) -> IdeResult<String>;
fn git_tree(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<GitTree>;
fn read_blob(
&self,
@@ -238,6 +247,63 @@ impl SkillSourceFetcher for GitHubHttpFetcher {
.map_err(|e| IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{git_ref}: invalid Git tree: {e}")))
}
fn git_commit_sha(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<String> {
#[derive(Deserialize)]
struct CommitMeta {
sha: String,
}
let RepoRef { owner, repo, git_ref } = target;
validate_repo_coord(owner, "owner")?;
validate_repo_coord(repo, "repository")?;
validate_git_ref(git_ref)?;
let encoded_ref = encode_url_segment(git_ref);
let url = format!("https://api.github.com/repos/{owner}/{repo}/commits/{encoded_ref}");
let body = self.get_github_json(&url, MAX_REPO_META_BYTES, cancel)?;
let meta: CommitMeta = serde_json::from_str(&body).map_err(|e| {
IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{git_ref}: invalid GitHub commit: {e}"))
})?;
if !is_git_object_id(&meta.sha) {
return Err(IdeError::new(
ErrorKind::Protocol,
format!("{owner}/{repo}@{git_ref}: invalid GitHub commit SHA"),
));
}
Ok(meta.sha)
}
fn git_commit_tree_sha(
&self,
owner: &str,
repo: &str,
commit_sha: &str,
cancel: &CancellationToken,
) -> IdeResult<String> {
#[derive(Deserialize)]
struct TreeRef {
sha: String,
}
#[derive(Deserialize)]
struct GitCommit {
tree: TreeRef,
}
validate_repo_coord(owner, "owner")?;
validate_repo_coord(repo, "repository")?;
if !is_git_object_id(commit_sha) {
return Err(IdeError::invalid("Invalid commit SHA"));
}
let url = format!("https://api.github.com/repos/{owner}/{repo}/git/commits/{commit_sha}");
let body = self.get_github_json(&url, MAX_REPO_META_BYTES, cancel)?;
let commit: GitCommit = serde_json::from_str(&body).map_err(|e| {
IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{commit_sha}: invalid Git commit: {e}"))
})?;
if !is_git_object_id(&commit.tree.sha) {
return Err(IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{commit_sha}: invalid tree SHA")));
}
Ok(commit.tree.sha)
}
fn read_blob(
&self,
target: RepoRef<'_>,
@@ -616,6 +682,17 @@ fn sanitize_repo_as_skill_name(repo: &str) -> String {
out.trim_matches('-').to_owned()
}
pub(crate) struct FetchedSubtree {
pub tree_sha: String,
pub normalized_subpath: String,
pub files: Vec<RemoteSkillFile>,
pub scan_warnings: Vec<SkillScanWarning>,
/// `(relative_path, bytes, executable)` for safe non-symlink files to write on disk.
pub regular_files: Vec<(PathBuf, Vec<u8>, bool)>,
/// `(relative_path, relative_target)` for safe internal symlinks.
pub in_root_symlinks: Vec<(PathBuf, PathBuf)>,
}
struct PreparedSkillBundle {
tree_sha: String,
skill_name: String,
@@ -629,14 +706,19 @@ struct PreparedSkillBundle {
in_root_symlinks: Vec<(PathBuf, PathBuf)>,
}
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
fn fetch_and_scan_bundle(
/// Fetches `target`'s tree (or exactly `pinned_tree_sha` when set) and scans `subpath` with hardened
/// symlink-graph, executable-script, and hidden-Unicode checks.
#[allow(clippy::too_many_arguments)]
pub(crate) fn fetch_and_scan_subtree(
fetcher: &dyn SkillSourceFetcher,
target: RepoRef<'_>,
subpath: &str,
pinned_tree_sha: Option<&str>,
max_files: usize,
max_subtree_bytes: u64,
noun: &str,
cancel: &CancellationToken,
) -> IdeResult<PreparedSkillBundle> {
) -> IdeResult<FetchedSubtree> {
let RepoRef { owner, repo, git_ref } = target;
validate_repo_coord(owner, "owner")?;
validate_repo_coord(repo, "repository")?;
@@ -646,9 +728,8 @@ fn fetch_and_scan_bundle(
let tree = match pinned_tree_sha {
Some(sha) => {
if !is_git_object_id(sha) {
return Err(IdeError::invalid("Preview the skill again before installing it"));
return Err(IdeError::invalid(format!("Preview the {noun} again before installing it")));
}
// The Git trees API accepts a tree SHA in place of a ref.
let tree = fetcher.git_tree(RepoRef { owner, repo, git_ref: sha }, cancel)?;
if !tree.sha.eq_ignore_ascii_case(sha) {
return Err(IdeError::new(
@@ -660,6 +741,14 @@ fn fetch_and_scan_bundle(
}
None => fetcher.git_tree(target, cancel)?,
};
if tree.truncated {
return Err(IdeError::new(
ErrorKind::Protocol,
format!(
"{owner}/{repo}@{git_ref}: GitHub returned a truncated file listing; the {noun} cannot be verified"
),
));
}
let prefix = if normalized_subpath.is_empty() { String::new() } else { format!("{normalized_subpath}/") };
let subtree_entries: Vec<&GitTreeEntry> = tree
@@ -672,27 +761,32 @@ fn fetch_and_scan_bundle(
if subtree_entries.is_empty() {
return Err(IdeError::not_found(format!(
"Skill path {:?} was not found in {owner}/{repo}@{git_ref}",
"{} path {:?} was not found in {owner}/{repo}@{git_ref}",
capitalize(noun),
normalized_subpath
)));
}
if subtree_entries.len() > MAX_SKILL_FILES {
if subtree_entries.len() > max_files {
return Err(IdeError::invalid(format!(
"Skill exceeds maximum of {MAX_SKILL_FILES} files ({} found)",
"{} exceeds maximum of {max_files} files ({} found)",
capitalize(noun),
subtree_entries.len()
)));
}
let declared_total: u64 = subtree_entries.iter().map(|e| e.size.unwrap_or(0)).sum();
if declared_total > MAX_SKILL_SUBTREE_BYTES {
return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20)));
if declared_total > max_subtree_bytes {
return Err(IdeError::invalid(format!(
"{} exceeds {} MiB size cap",
capitalize(noun),
max_subtree_bytes >> 20
)));
}
let mut files = Vec::with_capacity(subtree_entries.len());
let mut scan_warnings = Vec::new();
let mut regular_files = Vec::new();
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
let mut skill_markdown: Option<String> = None;
let mut actual_total = 0u64;
for entry in subtree_entries {
@@ -709,12 +803,16 @@ fn fetch_and_scan_bundle(
target,
&entry.path,
&entry.sha,
MAX_SINGLE_BLOB_BYTES.min(MAX_SKILL_SUBTREE_BYTES - actual_total),
MAX_SINGLE_BLOB_BYTES.min(max_subtree_bytes - actual_total),
cancel,
)?;
actual_total = actual_total.saturating_add(bytes.len() as u64);
if actual_total > MAX_SKILL_SUBTREE_BYTES {
return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20)));
if actual_total > max_subtree_bytes {
return Err(IdeError::invalid(format!(
"{} exceeds {} MiB size cap",
capitalize(noun),
max_subtree_bytes >> 20
)));
}
if is_symlink {
@@ -748,11 +846,15 @@ fn fetch_and_scan_bundle(
if let Ok(text) = std::str::from_utf8(&bytes) {
scan_hidden_unicode(rel_str, text, &mut scan_warnings);
if rel_str == "SKILL.md" {
skill_markdown = Some(text.to_owned());
if rel_str == "SKILL.md" || rel_str.ends_with("/SKILL.md") {
for tool in frontmatter_shell_tools(text) {
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::AllowedToolsShell,
file: rel_str.to_owned(),
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
});
}
}
} else if rel_str == "SKILL.md" {
return Err(IdeError::invalid("SKILL.md is not valid UTF-8 text"));
}
files.push(RemoteSkillFile {
@@ -767,13 +869,12 @@ fn fetch_and_scan_bundle(
files.sort_by(|a, b| a.path.cmp(&b.path));
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
// Symlinks are judged together: one link may point through another, and an entry placed beneath
// a symlink would be written wherever that link points.
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
if let Some(link) = graph.symlink_ancestor(path) {
return Err(IdeError::invalid(format!(
"Skill entry {:?} is inside symlink {link:?}; the repository tree is malformed",
"{} entry {:?} is inside symlink {link:?}; the repository tree is malformed",
capitalize(noun),
path.display().to_string()
)));
}
@@ -786,26 +887,65 @@ fn fetch_and_scan_bundle(
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::OutOfRootSymlink,
file: rel_str,
message: format!("Symlink target {target_raw:?} leaves the skill folder (omitted on install)"),
message: format!("Symlink target {target_raw:?} leaves the {noun} folder (omitted on install)"),
});
}
}
in_root_symlinks.sort();
let Some(skill_markdown) = skill_markdown else {
return Err(IdeError::invalid("Selected folder does not contain a regular SKILL.md file"));
};
Ok(FetchedSubtree { tree_sha: tree.sha, normalized_subpath, files, scan_warnings, regular_files, in_root_symlinks })
}
let folder_hint = normalized_subpath
fn capitalize(s: &str) -> String {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
}
}
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
fn fetch_and_scan_bundle(
fetcher: &dyn SkillSourceFetcher,
target: RepoRef<'_>,
subpath: &str,
pinned_tree_sha: Option<&str>,
cancel: &CancellationToken,
) -> IdeResult<PreparedSkillBundle> {
let RepoRef { repo, .. } = target;
let mut sub = fetch_and_scan_subtree(
fetcher,
target,
subpath,
pinned_tree_sha,
MAX_SKILL_FILES,
MAX_SKILL_SUBTREE_BYTES,
"skill",
cancel,
)?;
let skill_bytes = sub
.regular_files
.iter()
.find(|(p, _, _)| p == Path::new("SKILL.md"))
.map(|(_, b, _)| b.as_slice())
.ok_or_else(|| IdeError::invalid("Selected folder does not contain a regular SKILL.md file"))?;
let skill_markdown =
std::str::from_utf8(skill_bytes).map_err(|_| IdeError::invalid("SKILL.md is not valid UTF-8 text"))?.to_owned();
let folder_hint = sub
.normalized_subpath
.rsplit('/')
.next()
.filter(|s| !s.is_empty())
.map(str::to_owned)
.unwrap_or_else(|| sanitize_repo_as_skill_name(repo));
// Strip any `SKILL.md` shell-tool warnings already collected so `parse_skill_markdown_metadata` emits them in order.
sub.scan_warnings.retain(|w| !(w.kind == SkillScanWarningKind::AllowedToolsShell && w.file == "SKILL.md"));
let parsed_meta = parse_skill_markdown_metadata(&folder_hint, &skill_markdown)?;
for tool in &parsed_meta.shell_tools {
scan_warnings.push(SkillScanWarning {
sub.scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::AllowedToolsShell,
file: "SKILL.md".into(),
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
@@ -813,14 +953,14 @@ fn fetch_and_scan_bundle(
}
Ok(PreparedSkillBundle {
tree_sha: tree.sha,
tree_sha: sub.tree_sha,
skill_name: parsed_meta.name,
description: parsed_meta.description,
skill_markdown,
files,
scan_warnings,
regular_files,
in_root_symlinks,
files: sub.files,
scan_warnings: sub.scan_warnings,
regular_files: sub.regular_files,
in_root_symlinks: sub.in_root_symlinks,
})
}
@@ -1140,6 +1280,33 @@ fn create_parent_dirs_no_follow(root: &Path, rel: &Path) -> IdeResult<()> {
Ok(())
}
/// Creates `target` below the existing `anchor` (the home or project folder) without following a
/// symlink in any directory between them, the harness store root included.
fn create_dirs_below_anchor(anchor: &Path, target: &Path) -> IdeResult<()> {
if !anchor.is_dir() {
return Err(IdeError::not_found(format!("{} does not exist", anchor.display())));
}
let rel = target
.strip_prefix(anchor)
.map_err(|_| IdeError::invalid(format!("{} is outside {}", target.display(), anchor.display())))?;
let mut dir = anchor.to_path_buf();
for component in rel.components() {
if !matches!(component, Component::Normal(_)) {
return Err(IdeError::invalid(format!("{} is not a plain path below the store", target.display())));
}
dir.push(component);
match std::fs::symlink_metadata(&dir) {
Ok(meta) if meta.is_dir() => {}
Ok(_) => {
return Err(IdeError::invalid(format!("{} passes through a symlink or file", dir.display())));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => std::fs::create_dir(&dir)?,
Err(e) => return Err(e.into()),
}
}
Ok(())
}
/// Whether the symlink at `link` resolves strictly inside `root` (canonical), following links on disk.
/// Components that do not exist are resolved lexically.
#[cfg(unix)]
@@ -1220,15 +1387,16 @@ pub fn install_skill(
workspace_root: Option<&Path>,
cancel: &CancellationToken,
) -> IdeResult<PathBuf> {
let target_root = match req.scope {
// Anchored at the home or project folder: nothing below it may be a symlink, store included.
let (anchor, target_root) = match req.scope {
McpScope::User => {
let home = user_home.ok_or_else(|| IdeError::unavailable("Cannot locate user home directory"))?;
home.join(".agents").join("skills")
(home.to_path_buf(), home.join(".agents").join("skills"))
}
McpScope::Workspace => {
let ws = workspace_root
.ok_or_else(|| IdeError::invalid("Open a trusted project to install workspace skills"))?;
ws.join(".agents").join("skills")
(ws.to_path_buf(), ws.join(".agents").join("skills"))
}
};
@@ -1245,20 +1413,60 @@ pub fn install_skill(
));
}
std::fs::create_dir_all(&target_root)?;
let final_dir = target_root.join(&bundle.skill_name);
if final_dir.exists() && !req.overwrite {
write_staged_subtree(
&anchor,
&target_root,
&bundle.skill_name,
req.overwrite,
"Skill",
&bundle.regular_files,
&bundle.in_root_symlinks,
&[],
)
}
/// Atomically writes `regular_files`, `in_root_symlinks`, and `extra_files` into a staging folder
/// under `target_root`, verifies created symlinks stay inside the folder, and swaps into `<target_root>/<folder_name>`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn write_staged_subtree(
anchor: &Path,
target_root: &Path,
folder_name: &str,
overwrite: bool,
noun_cap: &str,
regular_files: &[(PathBuf, Vec<u8>, bool)],
in_root_symlinks: &[(PathBuf, PathBuf)],
extra_files: &[(&str, &[u8])],
) -> IdeResult<PathBuf> {
create_dirs_below_anchor(anchor, target_root)?;
if folder_name.is_empty() || !Path::new(folder_name).components().all(|c| matches!(c, Component::Normal(_))) {
return Err(IdeError::invalid(format!("Invalid {} folder name", noun_cap.to_ascii_lowercase())));
}
let final_dir = target_root.join(folder_name);
let existing = match std::fs::symlink_metadata(&final_dir) {
Ok(meta) if meta.is_dir() => true,
Ok(_) => {
return Err(IdeError::invalid(format!(
"{} is a symlink or file, not a {} folder",
final_dir.display(),
noun_cap.to_ascii_lowercase()
)));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
Err(e) => return Err(e.into()),
};
if existing && !overwrite {
return Err(IdeError::new(
ErrorKind::AlreadyExists,
format!("Skill `{}` is already installed in {}", bundle.skill_name, target_root.display()),
format!("{noun_cap} `{folder_name}` is already installed in {}", target_root.display()),
));
}
let nonce = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();
let staging = target_root.join(format!(".staging-{}-{nonce}-{}", bundle.skill_name, std::process::id()));
let staging = target_root.join(format!(".staging-{folder_name}-{nonce}-{}", std::process::id()));
let write_res = (|| -> IdeResult<()> {
std::fs::create_dir_all(&staging)?;
for (rel_path, bytes, is_exec) in &bundle.regular_files {
for (rel_path, bytes, is_exec) in regular_files {
create_parent_dirs_no_follow(&staging, rel_path)?;
let dest = staging.join(rel_path);
std::fs::write(&dest, bytes)?;
@@ -1270,7 +1478,12 @@ pub fn install_skill(
#[cfg(not(unix))]
let _ = is_exec;
}
for (rel_link, target) in &bundle.in_root_symlinks {
for (rel_str, bytes) in extra_files {
let rel_path = validate_rel_skill_file(rel_str)?;
create_parent_dirs_no_follow(&staging, &rel_path)?;
std::fs::write(staging.join(&rel_path), bytes)?;
}
for (rel_link, target) in in_root_symlinks {
create_parent_dirs_no_follow(&staging, rel_link)?;
let dest = staging.join(rel_link);
#[cfg(unix)]
@@ -1288,17 +1501,18 @@ pub fn install_skill(
#[cfg(unix)]
{
let root = std::fs::canonicalize(&staging)?;
for (rel_link, _) in &bundle.in_root_symlinks {
for (rel_link, _) in in_root_symlinks {
if !link_resolves_inside(&root, &staging.join(rel_link)) {
return Err(IdeError::invalid(format!(
"Symlink {:?} leaves the skill folder",
rel_link.display().to_string()
"Symlink {:?} leaves the {} folder",
rel_link.display().to_string(),
noun_cap.to_ascii_lowercase()
)));
}
}
}
let backup = if final_dir.exists() {
let bak = target_root.join(format!(".old-{}-{nonce}", bundle.skill_name));
let backup = if existing {
let bak = target_root.join(format!(".old-{folder_name}-{nonce}"));
std::fs::rename(&final_dir, &bak)?;
Some(bak)
} else {
@@ -1323,6 +1537,179 @@ pub fn install_skill(
Ok(final_dir)
}
/// Scans a local directory on disk with the same symlink-graph, executable-script, and hidden-Unicode
/// checks used for remote GitHub subtrees.
/// Content digest of a scanned local folder, used to pin a local preview to its install.
fn local_subtree_digest(regular_files: &[(PathBuf, Vec<u8>, bool)], symlinks: &[(PathBuf, PathBuf)]) -> String {
let mut hasher = blake3::Hasher::new();
hasher.update(b"openidea-local-subtree-v1\0");
for (path, bytes, executable) in regular_files {
hasher.update(b"f\0");
hasher.update(path.to_string_lossy().replace('\\', "/").as_bytes());
hasher.update(&[0, u8::from(*executable)]);
hasher.update(&(bytes.len() as u64).to_le_bytes());
hasher.update(bytes);
}
for (path, target) in symlinks {
hasher.update(b"l\0");
hasher.update(path.to_string_lossy().replace('\\', "/").as_bytes());
hasher.update(b"\0");
hasher.update(target.to_string_lossy().replace('\\', "/").as_bytes());
hasher.update(b"\0");
}
format!("local-blake3:{}", hasher.finalize().to_hex())
}
pub(crate) fn scan_local_subtree(
dir: &Path,
max_files: usize,
max_subtree_bytes: u64,
noun: &str,
) -> IdeResult<FetchedSubtree> {
if !dir.is_dir() {
return Err(IdeError::not_found(format!("Directory {} does not exist", dir.display())));
}
let mut files = Vec::new();
let mut scan_warnings = Vec::new();
let mut regular_files = Vec::new();
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
let mut actual_total = 0u64;
let mut stack = vec![(dir.to_path_buf(), String::new())];
while let Some((cur_dir, rel_prefix)) = stack.pop() {
let mut entries: Vec<_> = std::fs::read_dir(&cur_dir)?.filter_map(Result::ok).collect();
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let name = entry.file_name();
let Some(name_str) = name.to_str() else {
return Err(IdeError::invalid(format!(
"{} contains a file name that is not valid UTF-8: {}",
capitalize(noun),
entry.path().display()
)));
};
if name_str == ".git" || name_str == "node_modules" || name_str == "target" {
continue;
}
let rel_str = if rel_prefix.is_empty() { name_str.to_owned() } else { format!("{rel_prefix}/{name_str}") };
let rel_path = validate_rel_skill_file(&rel_str)?;
let full = entry.path();
let meta = std::fs::symlink_metadata(&full)?;
if (meta.file_type().is_symlink() || meta.file_type().is_file())
&& regular_files.len() + symlinks.len() >= max_files
{
return Err(IdeError::invalid(format!("{} exceeds maximum of {max_files} files", capitalize(noun))));
}
if meta.file_type().is_symlink() {
let target_raw = std::fs::read_link(&full)?.to_string_lossy().replace('\\', "/");
symlinks.push((rel_path, rel_str.clone(), target_raw));
files.push(RemoteSkillFile { path: rel_str, size: 0, executable: false, symlink: true });
continue;
}
if meta.file_type().is_dir() {
stack.push((full, rel_str));
continue;
}
if !meta.file_type().is_file() {
continue;
}
if meta.len() > MAX_SINGLE_BLOB_BYTES {
return Err(IdeError::invalid(format!(
"File {rel_str:?} exceeds {} MiB size cap",
MAX_SINGLE_BLOB_BYTES >> 20
)));
}
let bytes = std::fs::read(&full)?;
actual_total = actual_total.saturating_add(bytes.len() as u64);
if actual_total > max_subtree_bytes {
return Err(IdeError::invalid(format!(
"{} exceeds {} MiB size cap",
capitalize(noun),
max_subtree_bytes >> 20
)));
}
#[cfg(unix)]
let is_exec_mode = {
use std::os::unix::fs::PermissionsExt;
meta.permissions().mode() & 0o111 != 0
};
#[cfg(not(unix))]
let is_exec_mode = false;
let has_shebang = bytes.starts_with(b"#!");
let is_script_path = is_executable_or_script_path(&rel_path);
if is_exec_mode || has_shebang || is_script_path {
let reason = if is_exec_mode {
"executable file mode"
} else if has_shebang {
"script with `#!` interpreter header"
} else {
"bundled script or native binary"
};
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::ExecutableScript,
file: rel_str.clone(),
message: format!("Contains {reason}"),
});
}
if let Ok(text) = std::str::from_utf8(&bytes) {
scan_hidden_unicode(&rel_str, text, &mut scan_warnings);
if rel_str == "SKILL.md" || rel_str.ends_with("/SKILL.md") {
for tool in frontmatter_shell_tools(text) {
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::AllowedToolsShell,
file: rel_str.clone(),
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
});
}
}
}
files.push(RemoteSkillFile {
path: rel_str,
size: bytes.len() as u64,
executable: is_exec_mode || has_shebang,
symlink: false,
});
regular_files.push((rel_path, bytes, is_exec_mode));
}
}
files.sort_by(|a, b| a.path.cmp(&b.path));
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
if let Some(link) = graph.symlink_ancestor(path) {
return Err(IdeError::invalid(format!(
"{} entry {:?} is inside symlink {link:?}",
capitalize(noun),
path.display().to_string()
)));
}
}
let mut in_root_symlinks = Vec::new();
for (rel_path, rel_str, target_raw) in symlinks {
if graph.stays_inside(&rel_path, &target_raw) {
in_root_symlinks.push((rel_path, PathBuf::from(target_raw)));
} else {
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::OutOfRootSymlink,
file: rel_str,
message: format!("Symlink target {target_raw:?} leaves the {noun} folder (omitted on install)"),
});
}
}
in_root_symlinks.sort();
Ok(FetchedSubtree {
tree_sha: local_subtree_digest(&regular_files, &in_root_symlinks),
normalized_subpath: String::new(),
files,
scan_warnings,
regular_files,
in_root_symlinks,
})
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1374,6 +1761,25 @@ mod tests {
.cloned()
.ok_or_else(|| IdeError::not_found(format!("unknown ref {}", target.git_ref)))
}
fn git_commit_sha(&self, target: RepoRef<'_>, _cancel: &CancellationToken) -> IdeResult<String> {
self.trees
.get(target.git_ref)
.map(|_| git_blob_id(format!("commit:{}", target.git_ref).as_bytes()))
.ok_or_else(|| IdeError::not_found(format!("unknown ref {}", target.git_ref)))
}
fn git_commit_tree_sha(
&self,
_owner: &str,
_repo: &str,
commit_sha: &str,
_cancel: &CancellationToken,
) -> IdeResult<String> {
self.trees
.iter()
.find(|(git_ref, _)| git_blob_id(format!("commit:{git_ref}").as_bytes()) == commit_sha)
.map(|(_, tree)| tree.sha.clone())
.ok_or_else(|| IdeError::not_found(format!("unknown commit {commit_sha}")))
}
fn read_blob(
&self,
@@ -1440,7 +1846,9 @@ mod tests {
let cancel = CancellationToken::new();
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
std::fs::create_dir_all(&home).unwrap();
let ws = tmp.path().join("ws");
std::fs::create_dir_all(&ws).unwrap();
// Bare `owner/repo` lists both skills; `owner/repo@clean-skill` falls back from ref lookup to skill filter!
let all = browse_skills(&fetcher, "acme/skills", &cancel).unwrap();
@@ -1796,4 +2204,66 @@ mod tests {
.unwrap();
assert!(dest.join("SKILL.md").is_file());
}
#[cfg(unix)]
#[test]
fn local_scan_counts_symlinks_toward_the_file_cap() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("SKILL.md"), "x").unwrap();
for i in 0..3 {
std::os::unix::fs::symlink("SKILL.md", tmp.path().join(format!("link-{i}"))).unwrap();
}
let Err(err) = scan_local_subtree(tmp.path(), 3, 1 << 20, "plugin") else { panic!("symlinks must count") };
assert!(err.to_string().contains("maximum of 3 files"), "{err}");
}
#[test]
fn truncated_tree_listings_are_rejected() {
let mut fetcher = FakeFetcher::new();
fetcher.add_tree("main", vec![("skills/a/SKILL.md", "100644", b"---\nname: a\ndescription: a\n---\n")]);
fetcher.trees.get_mut("main").unwrap().truncated = true;
let cancel = CancellationToken::new();
let target = RepoRef { owner: "o", repo: "r", git_ref: "main" };
let Err(err) = fetch_and_scan_subtree(&fetcher, target, "skills/a", None, 10, 1 << 20, "skill", &cancel) else {
panic!("a truncated listing cannot be verified")
};
assert!(err.to_string().contains("truncated"), "{err}");
}
#[cfg(unix)]
#[test]
fn staged_installs_do_not_follow_symlinks_below_the_store() {
let tmp = tempfile::tempdir().unwrap();
let store = tmp.path().join("store");
let outside = tmp.path().join("outside");
std::fs::create_dir_all(&store).unwrap();
std::fs::create_dir_all(&outside).unwrap();
std::os::unix::fs::symlink(&outside, store.join("mkt")).unwrap();
let files = vec![(PathBuf::from("plugin.json"), b"{}".to_vec(), false)];
let Err(err) = write_staged_subtree(&store, &store.join("mkt"), "plugin", false, "Plugin", &files, &[], &[])
else {
panic!("a symlinked marketplace folder must not be written through")
};
assert!(err.to_string().contains("symlink"), "{err}");
assert!(std::fs::read_dir(&outside).unwrap().next().is_none(), "nothing was written outside the store");
// The store root itself (`<home>/.claude/plugins` → elsewhere) is checked as well.
let home = tmp.path().join("home");
std::fs::create_dir_all(home.join(".claude")).unwrap();
std::os::unix::fs::symlink(&outside, home.join(".claude/plugins")).unwrap();
let store_root = home.join(".claude/plugins/cache/mkt");
let Err(err) = write_staged_subtree(&home, &store_root, "plugin", false, "Plugin", &files, &[], &[]) else {
panic!("a symlinked store root must not be written through")
};
assert!(err.to_string().contains("symlink"), "{err}");
assert!(std::fs::read_dir(&outside).unwrap().next().is_none());
std::fs::create_dir_all(store.join("real")).unwrap();
std::os::unix::fs::symlink(&outside, store.join("real/plugin")).unwrap();
let Err(err) = write_staged_subtree(&store, &store.join("real"), "plugin", true, "Plugin", &files, &[], &[])
else {
panic!("an existing symlinked plugin folder must not be replaced through")
};
assert!(err.to_string().contains("symlink"), "{err}");
}
}
+34 -82
Переглянути файл
@@ -275,12 +275,27 @@ pub fn discover_skills_in(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Ag
}
/// [`discover_skills_in`] plus the `<dir>` skill folders contributed by enabled OpenIDEA
/// plugins (`[[contributes.skills]]`). Workspace and user skills take precedence on a name
/// clash; a plugin skill is never silently renamed.
/// plugins (`[[contributes.skills]]`) and unified agent plugin bundles (`plugins.rs`).
/// Workspace and user skills take precedence on a name clash; a plugin skill is never silently renamed.
pub fn discover_skills_with_plugins(
workspaces: &[PathBuf],
home: Option<&Path>,
plugin_skill_dirs: &[PathBuf],
) -> Vec<AgentSkill> {
let default_policy = crate::plugins::PluginsPolicy { workspace_roots: workspaces.to_vec(), ..Default::default() };
let states =
crate::plugins::resolve_plugins(crate::plugins::discover_plugins(workspaces, home), &default_policy, None);
let projected = crate::plugins::projected_skill_roots(&states, None);
discover_skills_with_agent_plugins(workspaces, home, plugin_skill_dirs, &projected)
}
/// Discovers skills across `workspaces`, `home`, OpenIDEA IDE-plugin skill folders (`plugin_skill_dirs`),
/// and resolved agent plugin bundle roots (`agent_plugin_roots`).
pub fn discover_skills_with_agent_plugins(
workspaces: &[PathBuf],
home: Option<&Path>,
plugin_skill_dirs: &[PathBuf],
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
) -> Vec<AgentSkill> {
let mut out: Vec<AgentSkill> = Vec::new();
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
@@ -338,9 +353,19 @@ pub fn discover_skills_with_plugins(
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
push_skill(parse_skill_file(dir, &folder, &text, AgentSkillSource::Plugin));
}
if let Some(home) = home {
for (root, source) in copilot_installed_plugin_roots(&home.join(".copilot")) {
for skill in skills_of(&root, source) {
for proj in agent_plugin_roots {
if proj.dir.join("SKILL.md").is_file() && proj.dir.file_name().and_then(|s| s.to_str()) != Some("skills") {
let Some(folder) = file_name(&proj.dir) else { continue };
if let Ok(text) = std::fs::read_to_string(proj.dir.join("SKILL.md")) {
let mut skill = parse_skill_file(&proj.dir, &folder, &text, proj.source);
skill.plugin_id = Some(proj.plugin_id.clone());
skill.plugin_name = Some(proj.plugin_name.clone());
push_skill(skill);
}
} else {
for mut skill in skills_of(&proj.dir, proj.source) {
skill.plugin_id = Some(proj.plugin_id.clone());
skill.plugin_name = Some(proj.plugin_name.clone());
push_skill(skill);
}
}
@@ -388,83 +413,6 @@ fn monorepo_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
out
}
/// Discovers skill roots inside `~/.copilot/installed-plugins`, supporting both Copilot CLI's
/// 2-level `<marketplace-or-_direct>/<plugin>` layout (and `config.json` `installedPlugins`
/// enablement) and flat 1-level `<plugin>` folders.
fn copilot_installed_plugin_roots(copilot_dir: &Path) -> Vec<(PathBuf, AgentSkillSource)> {
let mut disabled_paths: HashSet<PathBuf> = HashSet::new();
let mut plugin_dirs: Vec<PathBuf> = Vec::new();
let mut seen_dirs: HashSet<PathBuf> = HashSet::new();
let mut push_plugin = |dir: PathBuf, disabled: &HashSet<PathBuf>| {
if !dir.is_dir() {
return;
}
let canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
if disabled.contains(&canon) || !seen_dirs.insert(canon) {
return;
}
plugin_dirs.push(dir);
};
if let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json"))
&& let Ok(root) = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text))
&& let Some(installed) = root.get("installedPlugins").and_then(serde_json::Value::as_array)
{
for entry in installed {
let Some(raw_cache) = entry.get("cache_path").and_then(serde_json::Value::as_str).map(str::trim) else {
continue;
};
if raw_cache.is_empty() {
continue;
}
let dir =
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
if entry.get("enabled").and_then(serde_json::Value::as_bool) == Some(false) {
disabled_paths.insert(dunce::canonicalize(&dir).unwrap_or(dir));
} else {
push_plugin(dir, &disabled_paths);
}
}
}
let plugins_root = copilot_dir.join("installed-plugins");
for entry in sorted(&plugins_root) {
if !entry.is_dir() {
continue;
}
if looks_like_plugin_dir(&entry) {
push_plugin(entry, &disabled_paths);
} else {
// 2-level `<marketplace>/<plugin>` or `_direct/<plugin>`.
for sub in sorted(&entry) {
if sub.is_dir() {
push_plugin(sub, &disabled_paths);
}
}
}
}
let mut roots = Vec::new();
for plugin in plugin_dirs {
let skills_sub = plugin.join("skills");
if skills_sub.is_dir() {
roots.push((skills_sub, AgentSkillSource::CopilotUser));
} else {
roots.push((plugin, AgentSkillSource::CopilotUser));
}
}
roots
}
fn looks_like_plugin_dir(dir: &Path) -> bool {
dir.join("skills").is_dir()
|| dir.join("plugin.json").is_file()
|| dir.join(".plugin").is_dir()
|| dir.join(".claude-plugin").is_dir()
|| dir.join(".cursor-plugin").is_dir()
|| dir.join("SKILL.md").is_file()
}
/// The skills of one root: `<name>/SKILL.md` folders and `<category>/<name>/SKILL.md`
/// category folders, validated.
fn skills_of(root: &Path, source: AgentSkillSource) -> Vec<AgentSkill> {
@@ -544,6 +492,8 @@ fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSour
paths,
valid: warnings.is_empty(),
warnings,
plugin_id: None,
plugin_name: None,
}
}
@@ -1070,6 +1020,8 @@ mod tests {
paths: Vec::new(),
valid: true,
warnings: Vec::new(),
plugin_id: None,
plugin_name: None,
}
}
+417 -3
Переглянути файл
@@ -69,6 +69,10 @@ struct FakeAgent {
prompts: Mutex<Vec<Value>>,
/// Queued errors returned on the next `session/prompt` calls before succeeding.
prompt_errors: Mutex<VecDeque<(i64, String)>>,
/// Number of prompts that stream Cursor's capacity diagnostic before returning end_turn.
capacity_errors: Mutex<u32>,
/// Queued errors returned on the next session-open calls before succeeding.
open_errors: Mutex<VecDeque<(i64, String, Option<Value>)>>,
/// Recorded `(method, _meta.openidea.memory)` payloads across `session/new`, `session/load`, and `session/fork`.
memory_calls: Mutex<Vec<(String, Option<Value>)>>,
}
@@ -150,6 +154,12 @@ impl Handler for FakeAgent {
let data = json!({"openidea": {"usageLimit": {"resetsAtMs": 1234.0}}});
return Err((codes::INTERNAL_ERROR, "You've hit your usage limit".into(), Some(data)));
}
if matches!(method, "session/new" | "session/load" | "session/fork")
&& let Some(err) = self.open_errors.lock().pop_front()
{
self.calls.lock().push(method.to_owned());
return Err(err);
}
self.on_request(method, params).map_err(|(code, message)| (code, message, None))
}
@@ -289,6 +299,22 @@ impl Handler for FakeAgent {
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
{
let mut remaining = self.capacity_errors.lock();
if *remaining > 0 {
*remaining -= 1;
if text == "edit once" {
self.update(
&session,
json!({"sessionUpdate": "tool_call", "toolCallId": "edit",
"title": "Edit file", "kind": "edit", "status": "completed"}),
);
}
self.say(&session, "\n\nError: RetriableError: ");
self.say(&session, "[resource_exhausted] Error");
return Ok(json!({"stopReason": "end_turn"}));
}
}
if text.starts_with("The previous turn was interrupted because ") {
self.say(&session, "resumed cleanly");
return Ok(json!({"stopReason": "end_turn"}));
@@ -426,6 +452,28 @@ impl Handler for FakeAgent {
self.say(&session, &format!("form {answer}"));
return Ok(json!({ "stopReason": "end_turn" }));
}
if text == "question form" {
// claude-agent-acp's `AskUserQuestion`, sent as a form.
let peer = self.latest();
let answer: Value = tokio::runtime::Handle::current()
.block_on(peer.request(
"elicitation/create",
json!({"sessionId": session, "mode": "form",
"message": "Please answer the following questions.",
"requestedSchema": {"type": "object", "properties": {
"question_0": {"type": "string", "title": "Layout", "description": "Which layout?",
"oneOf": [{"const": "List", "title": "List"}, {"const": "Grid", "title": "Grid"}]},
"question_0_custom": {"type": "string", "title": "Other"},
"question_1": {"type": "array", "title": "Checks", "description": "Which checks?",
"items": {"anyOf": [{"const": "Disk", "title": "Disk"},
{"const": "GPU", "title": "GPU"}]}},
"question_1_custom": {"type": "string", "title": "Other"}}}}),
None,
))
.unwrap();
self.say(&session, &format!("form {answer}"));
return Ok(json!({ "stopReason": "end_turn" }));
}
if text == "ask" {
let peer = self.latest();
let answer: Value = tokio::runtime::Handle::current()
@@ -2191,6 +2239,210 @@ async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_ag
assert_eq!(calls(&agent), ["session/load", "session/new", "session/prompt"]);
}
/// A locked Codex recording can be forked without resuming it or moving its writer between tasks.
#[tokio::test(flavor = "multi_thread")]
async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
let tmp = tempfile::tempdir().unwrap();
let task = {
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "codex".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.shutdown();
task
};
let agent = Arc::new(FakeAgent {
load_error: Some((codes::INVALID_PARAMS, "thread s1 already has an active writer".into())),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
for _ in 0..2 {
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
}
assert!(!agent.calls.lock().iter().any(|c| c == "session/new"));
let copy = mgr.fork(&task.id, None).await.unwrap();
assert_eq!(agent.forks.lock().last().unwrap()["sessionId"], "s1");
let copy_handle = mgr.task(&copy.id).unwrap();
assert_eq!(copy_handle.live.lock().as_ref().unwrap().session, "s2");
let loads = agent.calls.lock().iter().filter(|c| *c == "session/load").count();
mgr.prompt(&copy.id, text("again"), false).await.unwrap();
wait_for(&mgr, &copy.id, AgentStatus::Ready).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/load").count(), loads);
mgr.shutdown();
}
fn warming_up_error() -> (i64, String, Option<Value>) {
(
codes::INTERNAL_ERROR,
"Internal error: Internal service failure".to_owned(),
Some(json!({"errorName": "ServiceUnavailableError"})),
)
}
#[tokio::test(flavor = "multi_thread")]
async fn session_open_retries_while_the_agent_finishes_starting_up() {
// OpenCode rejects session opens until its plugins and MCP servers finish activating.
let tmp = tempfile::tempdir().unwrap();
let agent =
Arc::new(FakeAgent { open_errors: Mutex::new(VecDeque::from([warming_up_error()])), ..Default::default() });
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/new").count(), 2, "retried the startup race");
let saved = mgr.task(&task.id).unwrap().state.lock().session_id.clone().expect("a session");
mgr.shutdown();
// The same race when reopening a saved session.
let agent =
Arc::new(FakeAgent { open_errors: Mutex::new(VecDeque::from([warming_up_error()])), ..Default::default() });
let mgr = manager(tmp.path(), agent.clone());
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/load").count(), 2, "retried the startup race");
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some(saved.as_str()));
mgr.shutdown();
}
async fn wait_for_session_open_attempts(agent: &FakeAgent, method: &str, attempts: usize) {
tokio::time::timeout(Duration::from_secs(5), async {
while agent.calls.lock().iter().filter(|call| call.as_str() == method).count() < attempts {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("agent received the session-open requests");
}
#[tokio::test]
async fn retry_after_warmup_expires_loads_the_saved_session_again() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let saved = mgr.task(&task.id).unwrap().state.lock().session_id.clone().unwrap();
mgr.shutdown();
let agent = Arc::new(FakeAgent {
open_errors: Mutex::new(std::iter::repeat_with(warming_up_error).take(16).collect()),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for_session_open_attempts(&agent, "session/load", 2).await;
tokio::time::pause();
tokio::time::advance(WARMUP_WINDOW - WARMUP_DELAY * 2).await;
tokio::time::resume();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
assert!(mgr.entries(&task.id, None).unwrap().iter().any(|entry| matches!(
entry, AgentEntry::Error { message } if message.contains("Try again") && !message.contains("new session")
)));
agent.open_errors.lock().clear();
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert!(!agent.calls.lock().iter().any(|call| call == "session/new"));
let handle = mgr.task(&task.id).unwrap();
assert_eq!(handle.live.lock().as_ref().unwrap().session, saved);
mgr.shutdown();
}
#[tokio::test]
async fn a_stalled_warmup_retry_times_out_and_closes_the_connection() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent {
open_errors: Mutex::new(VecDeque::from([warming_up_error()])),
hold_session_new: AtomicBool::new(true),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for_session_open_attempts(&agent, "session/new", 2).await;
tokio::time::pause();
tokio::time::advance(WARMUP_WINDOW).await;
tokio::time::resume();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
assert!(mgr.entries(&task.id, None).unwrap().iter().any(|entry| matches!(
entry, AgentEntry::Error { message } if message.contains("timed out")
)));
tokio::time::timeout(Duration::from_secs(5), agent.latest().closed())
.await
.expect("the timed-out connection closes");
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn session_open_authenticates_after_a_warmup_reply() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent {
open_errors: Mutex::new(VecDeque::from([warming_up_error()])),
auth_on_new: true,
authenticate_method: Some("agent_login".into()),
auth_methods: vec![json!({"id": "agent_login", "name": "Sign in"})],
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let calls = agent.calls.lock();
let setup: Vec<_> = calls
.iter()
.map(String::as_str)
.filter(|call| call.starts_with("session/") || call.starts_with("authenticate"))
.collect();
assert_eq!(
setup,
["session/new", "session/new", "authenticate", "authenticate agent_login", "session/new", "session/prompt"]
);
drop(calls);
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn session_open_does_not_retry_unrelated_internal_errors() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent {
open_errors: Mutex::new(VecDeque::from([(
codes::INTERNAL_ERROR,
"Internal error: Internal service failure".into(),
Some(json!({"errorName": "SQLiteError"})),
)])),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/new").count(), 1, "no retry on a real failure");
mgr.shutdown();
}
fn text(t: &str) -> AgentPrompt {
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
}
@@ -2571,7 +2823,12 @@ async fn subagents_get_their_own_conversation() {
#[test]
fn image_blocks_declare_the_type_of_their_bytes() {
let image = |mime: &str, data: &str| AgentImage { mime_type: mime.into(), data: data.into(), name: None };
let image = |mime: &str, data: &str| AgentImage {
mime_type: mime.into(),
data: data.into(),
name: None,
inline_number: None,
};
let cases = [
// A browser's JPEG pasted as PNG.
(image("image/png", "/9j/4AAQSkZJRgABAQ"), "image/jpeg"),
@@ -2593,7 +2850,7 @@ fn prompts_become_acp_content_blocks() {
let p = AgentPrompt {
text: "look".into(),
files: vec![IpcPath(PathBuf::from("/p/my file.rs"))],
images: vec![AgentImage { mime_type: "image/png".into(), data: "AAA".into(), name: None }],
images: vec![AgentImage { mime_type: "image/png".into(), data: "AAA".into(), name: None, inline_number: None }],
};
assert_eq!(
blocks(&p, &[]),
@@ -2625,6 +2882,32 @@ fn prompts_become_acp_content_blocks() {
assert!(clean(text(" ")).is_none());
}
#[test]
fn inline_images_are_distinct_content_blocks_in_text_order() {
let older: AgentImage = serde_json::from_value(json!({"mimeType":"image/png", "data":"AAA", "name":null})).unwrap();
assert!(older.inline_number.is_none());
let image = |number, data: &str| AgentImage {
mime_type: "image/png".into(),
data: data.into(),
name: None,
inline_number: Some(number),
};
let prompt = AgentPrompt {
text: "😀 [Image #2] then [Image #1] and [Image #99]".into(),
images: vec![image(1, "AAA"), image(2, "BBB"), image(3, "CCC")],
..Default::default()
};
let content = blocks(&prompt, &[]);
assert_eq!(content.len(), 5);
assert_eq!(content[0], json!({"type": "text", "text": "😀 "}));
assert_eq!(content[1]["type"], "image");
assert_eq!(content[1]["data"], "BBB");
assert_eq!(content[2], json!({"type": "text", "text": " then "}));
assert_eq!(content[3]["type"], "image");
assert_eq!(content[3]["data"], "AAA");
assert_eq!(content[4], json!({"type": "text", "text": " and [Image #99]"}));
}
#[tokio::test(flavor = "multi_thread")]
async fn claude_questions_keep_the_answer_object_as_the_option_id() {
let tmp = tempfile::tempdir().unwrap();
@@ -3895,6 +4178,54 @@ async fn an_agent_form_is_answered_declined_or_cancelled_even_when_approvals_are
}
}
/// claude-agent-acp asks `AskUserQuestion` as a form: it is shown as the question card, one
/// question at a time, and the card's answers fill the form (#7359).
#[tokio::test(flavor = "multi_thread")]
async fn a_question_tool_form_is_asked_as_questions() {
let answers = json!({"question_0": ["Grid", "with thumbnails"], "question_1": ["Disk", "GPU"]}).to_string();
for (reply, said) in [
(
answers.as_str(),
r#"form {"action":"accept","content":{"question_0":"Grid","question_0_custom":"with thumbnails","question_1":["Disk","GPU"]}}"#,
),
("reject", r#"form {"action":"decline"}"#),
] {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("question form"),
provider: "cursor".into(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
let (id, questions) = mgr
.entries(&task.id, None)
.unwrap()
.into_iter()
.find_map(|entry| match entry {
AgentEntry::Permission { id, questions, form: None, chosen: None, .. } if !questions.is_empty() => {
Some((id, questions))
}
_ => None,
})
.unwrap();
let asked: Vec<_> =
questions.iter().map(|q| (q.answer_key.as_deref(), q.question.as_str(), q.multi_select)).collect();
assert_eq!(asked, [(Some("question_0"), "Which layout?", false), (Some("question_1"), "Which checks?", true)]);
mgr.respond(&task.id, id, Some(reply.to_owned())).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let entries = mgr.entries(&task.id, None).unwrap();
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == said)), "{entries:?}");
mgr.shutdown();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_approval_choice_applies_before_first_prompt() {
let tmp = tempfile::tempdir().unwrap();
@@ -4847,7 +5178,7 @@ fn a_running_tools_output_is_sent_as_appends() {
// An image the tool returned is not part of the appended text: it goes with the whole entry.
let mut shown = titled.clone();
if let AgentEntry::Tool { images, output, .. } = &mut shown {
images.push(AgentImage { mime_type: "image/png".into(), data: "AAAA".into(), name: None });
images.push(AgentImage { mime_type: "image/png".into(), data: "AAAA".into(), name: None, inline_number: None });
output.as_mut().unwrap().push('!');
}
let imaged = event(&mut streamed, None, 2, &shown).unwrap();
@@ -6021,6 +6352,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
plugin_id: None,
plugin_name: None,
},
McpServer {
id: "user::slack".into(),
@@ -6035,6 +6368,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
plugin_id: None,
plugin_name: None,
},
]
}));
@@ -6946,6 +7281,85 @@ async fn transient_network_outage_probes_with_zero_prompts_and_auto_resumes_when
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_capacity_retry_pauses_after_three_continuations_and_resumes_on_request() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.capacity_errors.lock() = 4;
let mgr = manager(tmp.path(), agent.clone());
let _down = ShutDown(&mgr);
let task = mgr
.create(NewAgentTask { provider: "cursor".into(), prompt: text("edit once"), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let handle = mgr.task(&task.id).unwrap();
let snap = handle.state.lock().snapshot();
assert_eq!(snap.interrupted.unwrap().reason, InterruptionReason::CursorCapacity);
assert!(snap.retry.is_none());
let entries = mgr.entries(&task.id, None).unwrap();
let attempts: Vec<_> = entries
.iter()
.filter_map(|e| match e {
AgentEntry::User { retry_attempt, .. } => *retry_attempt,
_ => None,
})
.collect();
assert_eq!(attempts, [1, 2, 3]);
assert_eq!(entries.iter().filter(|e| matches!(e, AgentEntry::Tool { .. })).count(), 1);
assert_eq!(agent.prompts.lock().len(), 4);
mgr.resume(&task.id).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert!(handle.state.lock().task.interrupted.is_none());
assert_eq!(agent.prompts.lock().len(), 5);
assert!(
agent
.prompts
.lock()
.iter()
.skip(1)
.all(|p| p[0]["text"].as_str().unwrap().contains("Inspect the current workspace"))
);
assert!(
matches!(mgr.entries(&task.id, None).unwrap().last(), Some(AgentEntry::Agent { text }) if text == "resumed cleanly")
);
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_capacity_retry_can_be_stopped_or_replaced_during_backoff() {
for send_now in [false, true] {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.capacity_errors.lock() = 1;
let mgr = manager(tmp.path(), agent.clone());
let _down = ShutDown(&mgr);
let task = mgr
.create(NewAgentTask { provider: "cursor".into(), prompt: text("edit once"), ..Default::default() })
.await
.unwrap();
let handle = mgr.task(&task.id).unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
while handle.state.lock().task.retry.is_none() {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.unwrap();
let retry = handle.state.lock().task.retry.clone().unwrap();
assert_eq!((retry.attempt, retry.max_retries, retry.deadline_ms), (1, Some(3), None));
if !send_now {
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.prompts.lock().len(), 1);
assert!(handle.state.lock().task.retry.is_none());
}
mgr.prompt(&task.id, text("again"), send_now).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.prompts.lock().len(), 2);
assert_eq!(agent.prompts.lock()[1][0]["text"], "again");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn network_outage_window_off_or_expired_degrades_to_interrupted_and_auth_errors_fail_fast() {
use ide_core::settings::{NetworkRetryWindow, ResumeInterruptedPolicy};
+3 -1
Переглянути файл
@@ -523,7 +523,7 @@ mod tests {
t.apply(&update);
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "status": "completed"}));
let AgentEntry::Tool { images, output, status, .. } = &t.entries[0] else { panic!() };
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None }]);
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None, inline_number: None }]);
assert!(output.as_ref().unwrap().len() < MAX_OUTPUT + 100);
assert_eq!(*status, AgentToolStatus::Completed);
let saved = serde_json::to_string(&t.entries[0]).unwrap();
@@ -646,6 +646,7 @@ mod tests {
done_ms: None,
steered: false,
recovery: None,
retry_attempt: None,
};
let mut t = Timeline::default();
t.push(user(1.0));
@@ -668,6 +669,7 @@ mod tests {
done_ms: None,
steered,
recovery: None,
retry_attempt: None,
};
let mut t = Timeline::default();
t.push(user(1.0, false));
+377 -7
Переглянути файл
@@ -9,12 +9,34 @@ use std::path::{Path, PathBuf};
use std::time::{Duration, UNIX_EPOCH};
pub(crate) struct Created {
#[cfg_attr(not(test), allow(dead_code))]
pub path: PathBuf,
pub cwd: PathBuf,
pub branch: String,
pub base: String,
pub base_commit: String,
}
const OWNERSHIP_MARKER: &str = "openidea-worktree.json";
const OWNERSHIP_TAG: &str = "openidea-agent";
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct WorktreeOwnership {
owner: String,
task_id: String,
worktree_root: PathBuf,
repo_root: PathBuf,
}
/// Returns the canonical root of the Git repository containing `project_root`, if any.
pub fn canonical_repo_root(project_root: &Path) -> IdeResult<Option<PathBuf>> {
match Repo::discover(project_root)? {
Some(repo) => Ok(Some(dunce::canonicalize(repo.root())?)),
None => Ok(None),
}
}
/// The repository of `path`, free to execute: the host runs every agent command that
/// reaches a repository only in a trusted project.
fn discover(path: &Path) -> IdeResult<Option<Repo>> {
@@ -157,9 +179,38 @@ pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
}
}
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
#[cfg(test)]
pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, base: Option<&str>) -> IdeResult<Created> {
create_for_task(project_root, worktrees_dir, "", title, base)
}
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
/// Records an ownership marker in the linked worktree's private `git_dir` and preserves any
/// project-relative subdirectory inside `project_root` when `project_root` is below `repo.root()`.
pub(crate) fn create_for_task(
project_root: &Path,
worktrees_dir: &Path,
task_id: &str,
title: &str,
base: Option<&str>,
) -> IdeResult<Created> {
let repo = repo_at(project_root)?;
let canon_repo = dunce::canonicalize(repo.root())?;
let canon_proj = dunce::canonicalize(project_root)?;
let rel_subdir = if canon_proj != canon_repo {
canon_proj
.strip_prefix(&canon_repo)
.map_err(|_| {
IdeError::invalid(format!(
"{} is outside git repository {}",
canon_proj.display(),
canon_repo.display()
))
})?
.to_path_buf()
} else {
PathBuf::new()
};
let (base, base_commit) = match base.map(str::trim).filter(|b| !b.is_empty()) {
Some(b) => {
let commit =
@@ -177,7 +228,125 @@ pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, bas
let path = worktrees_dir.join(&slug);
let branch = format!("agent/{slug}");
repo.add_worktree(&path, &base_commit, Some(&branch))?;
Ok(Created { path, branch, base, base_commit })
let canon_wt = match dunce::canonicalize(&path) {
Ok(p) => p,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e.into());
}
};
let wt_repo = match repo_at(&canon_wt) {
Ok(r) => r,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
};
let [git_dir, common_dir] = match wt_repo.metadata_dirs() {
Ok(dirs) => dirs,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
};
if dunce::canonicalize(&git_dir).ok() == dunce::canonicalize(&common_dir).ok() {
let _ = repo.remove_worktree(&path, false);
return Err(IdeError::internal("linked worktree did not receive a separate git metadata directory"));
}
let marker = WorktreeOwnership {
owner: OWNERSHIP_TAG.to_owned(),
task_id: task_id.to_owned(),
worktree_root: canon_wt.clone(),
repo_root: canon_repo,
};
if let Err(e) = serde_json::to_vec_pretty(&marker)
.map_err(|e| IdeError::internal(e.to_string()))
.and_then(|bytes| ide_vfs::write_atomic(&git_dir.join(OWNERSHIP_MARKER), &bytes))
{
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
let raw_cwd = if rel_subdir.as_os_str().is_empty() { canon_wt.clone() } else { canon_wt.join(&rel_subdir) };
if !raw_cwd.is_dir() {
let _ = repo.remove_worktree(&path, false);
return Err(IdeError::invalid(format!(
"project folder {} does not exist in base revision {}",
rel_subdir.display(),
base
)));
}
let canon_cwd = match verify_confined_worktree_subdir(&canon_wt, &raw_cwd) {
Ok(c) => c,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
};
Ok(Created { path, cwd: canon_cwd, branch, base, base_commit })
}
fn verify_confined_worktree_subdir(canon_wt_root: &Path, target_cwd: &Path) -> IdeResult<PathBuf> {
let canon_cwd = dunce::canonicalize(target_cwd)?;
let real_wt = ide_core::real_path::resolve_real(canon_wt_root);
let real_cwd = ide_core::real_path::resolve_real(target_cwd);
if !canon_cwd.starts_with(canon_wt_root)
|| !real_cwd.starts_with(&real_wt)
|| ide_core::real_path::reaches_git_dir(&real_wt, &real_cwd)
{
return Err(IdeError::invalid(format!(
"worktree working directory {} resolves outside worktree {}",
target_cwd.display(),
canon_wt_root.display()
)));
}
Ok(canon_cwd)
}
/// Canonicalizes `cwd` of an existing `Isolation::Worktree` task and verifies that it still
/// resolves strictly inside its own worktree checkout root under `worktrees_dir` (preventing
/// symlink escapes on reused sessions/turns).
pub(crate) fn verify_confined_worktree_cwd(worktrees_dir: &Path, cwd: &Path) -> IdeResult<PathBuf> {
let (wt_root, wt_base) = worktree_checkout_root(worktrees_dir, cwd);
if !wt_root.starts_with(&wt_base) || wt_root == wt_base {
return Err(IdeError::invalid(format!(
"worktree working directory {} is outside managed worktrees directory {}",
cwd.display(),
worktrees_dir.display()
)));
}
let canon_wt_root = dunce::canonicalize(&wt_root)?;
let canon_wt_dir = dunce::canonicalize(worktrees_dir)?;
if !canon_wt_root.starts_with(&canon_wt_dir)
|| canon_wt_root == canon_wt_dir
|| canon_wt_root.parent() != Some(canon_wt_dir.as_path())
{
return Err(IdeError::invalid("worktree checkout root escaped managed worktrees directory"));
}
verify_confined_worktree_subdir(&canon_wt_root, cwd)
}
fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) {
if let Ok(rel) = path.strip_prefix(worktrees_dir)
&& let Some(first) = rel.components().next()
{
return (worktrees_dir.join(first), worktrees_dir.to_path_buf());
}
if let Ok(canon_wt_dir) = dunce::canonicalize(worktrees_dir) {
if let Ok(rel) = path.strip_prefix(&canon_wt_dir)
&& let Some(first) = rel.components().next()
{
return (canon_wt_dir.join(first), canon_wt_dir);
}
if let Ok(canon_path) = dunce::canonicalize(path)
&& let Ok(rel) = canon_path.strip_prefix(&canon_wt_dir)
&& let Some(first) = rel.components().next()
{
return (canon_wt_dir.join(first), canon_wt_dir);
}
}
(path.to_path_buf(), worktrees_dir.to_path_buf())
}
/// `git worktree remove --force -- <path>`. When git no longer recognizes the
@@ -186,19 +355,94 @@ pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, bas
/// ours, so it is removed directly to keep the task deletable (a stale
/// registration prunes later); anything else keeps git's error.
pub(crate) fn remove(project_root: &Path, worktrees_dir: &Path, path: &Path) -> IdeResult<()> {
let (target, wt_base) = worktree_checkout_root(worktrees_dir, path);
let repo = repo_at(project_root)?;
let err = match repo.remove_worktree(path, true) {
let err = match repo.remove_worktree(&target, true) {
Ok(()) => return Ok(()),
Err(e) => e,
};
if !path.exists() {
if !target.exists() {
return Ok(());
}
if !path.starts_with(worktrees_dir) || path == worktrees_dir {
if !target.starts_with(&wt_base) || target == wt_base {
return Err(err);
}
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(path))
.map_err(|e| IdeError::internal(format!("{}: {e}", path.display())))
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(&target))
.map_err(|e| IdeError::internal(format!("{}: {e}", target.display())))
}
/// Safely removes an automation worktree ONLY after verifying its private `git_dir` ownership
/// marker (`openidea-worktree.json`) matches `task_id` and `worktrees_dir`.
///
/// - When `require_clean` is `true` (zero-diff GC): verifies `HEAD == base_commit` and both the
/// Git index (staged) and working tree (unstaged + untracked) are completely clean right before
/// running **non-forced** `git worktree remove` (`force = false`). Returns `Ok(false)` without
/// modifying disk if the worktree has any commits, staged changes, unstaged edits, or untracked
/// files.
/// - Never falls back to `remove_dir_all` on any ownership or Git error: any error keeps the
/// checkout intact.
pub(crate) fn remove_owned_automation_worktree(
project_root: &Path,
worktrees_dir: &Path,
cwd: &Path,
task_id: &str,
base_commit: Option<&str>,
require_clean: bool,
) -> IdeResult<bool> {
if !cwd.exists() || !worktrees_dir.exists() {
return Ok(false);
}
let canon_worktrees = dunce::canonicalize(worktrees_dir)?;
let canon_cwd = dunce::canonicalize(cwd)?;
if !canon_cwd.starts_with(&canon_worktrees) || canon_cwd == canon_worktrees {
return Err(IdeError::invalid("refusing to clean worktree outside managed worktrees directory"));
}
let main_repo = repo_at(project_root)?;
let wt_repo = repo_at(&canon_cwd)?;
let canon_wt_root = dunce::canonicalize(wt_repo.root())?;
if !canon_wt_root.starts_with(&canon_worktrees)
|| canon_wt_root == canon_worktrees
|| canon_wt_root.parent() != Some(canon_worktrees.as_path())
{
return Err(IdeError::invalid("worktree root does not match managed worktrees directory"));
}
let [git_dir, wt_common] = wt_repo.metadata_dirs()?;
let [_, main_common] = main_repo.metadata_dirs()?;
let canon_git_dir = dunce::canonicalize(&git_dir)?;
let canon_wt_common = dunce::canonicalize(&wt_common)?;
let canon_main_common = dunce::canonicalize(&main_common)?;
if canon_git_dir == canon_wt_common || canon_wt_common != canon_main_common {
return Err(IdeError::invalid("target checkout is not a linked worktree of this repository"));
}
let marker_bytes = std::fs::read(canon_git_dir.join(OWNERSHIP_MARKER))
.map_err(|_| IdeError::invalid("refusing to remove worktree without OpenIDEA ownership marker"))?;
let marker: WorktreeOwnership = serde_json::from_slice(&marker_bytes)
.map_err(|_| IdeError::invalid("corrupt OpenIDEA worktree ownership marker"))?;
let marker_root = dunce::canonicalize(&marker.worktree_root).unwrap_or(marker.worktree_root);
if marker.owner != OWNERSHIP_TAG || marker.task_id != task_id || marker_root != canon_wt_root {
return Err(IdeError::invalid("worktree ownership marker does not match task"));
}
if require_clean {
let Some(base) = base_commit else {
return Ok(false);
};
if wt_repo.head()?.1.as_deref() != Some(base) {
return Ok(false);
}
// `status()` checks BOTH HEAD↔index (staged) and index↔worktree (unstaged + untracked).
if !wt_repo.status()?.is_empty() {
return Ok(false);
}
if !wt_repo.diff_with_worktree(base)?.is_empty() {
return Ok(false);
}
main_repo.remove_worktree(&canon_wt_root, false)?;
return Ok(true);
}
main_repo.remove_worktree(&canon_wt_root, true)?;
Ok(true)
}
/// On Windows a folder can't be deleted while a process still has a file in it open
@@ -1944,4 +2188,130 @@ mod tests {
changed.sort();
assert_eq!(changed, ["edited", "new", "reverted"]);
}
#[test]
fn owned_worktree_cleanup_preserves_subproject_cwd_catches_staged_changes_and_verifies_ownership() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
let sub = repo.join("packages").join("subapp");
std::fs::create_dir_all(&sub).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
git(&repo, &["config", "core.autocrlf", "false"]);
std::fs::write(repo.join("root.txt"), "root\n").unwrap();
std::fs::write(sub.join("index.ts"), "export const x = 1;\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
let wt_dir = tmp.path().join("wt");
let created = create_for_task(&sub, &wt_dir, "task-1", "Sub Audit", None).unwrap();
assert_eq!(
dunce::canonicalize(&created.cwd).unwrap(),
dunce::canonicalize(&created.path).unwrap().join("packages").join("subapp"),
"project-relative cwd inside parent repo must be preserved inside worktree"
);
// Wrong task_id is refused and keeps the checkout untouched.
assert!(
remove_owned_automation_worktree(
&sub,
&wt_dir,
&created.cwd,
"wrong-task",
Some(&created.base_commit),
true,
)
.is_err()
);
assert!(created.path.exists());
// Staged-only change (index differs from HEAD while working tree matches HEAD!) is NOT clean!
std::fs::write(created.cwd.join("index.ts"), "export const x = 2;\n").unwrap();
git(&created.path, &["add", "packages/subapp/index.ts"]);
std::fs::write(created.cwd.join("index.ts"), "export const x = 1;\n").unwrap();
let removed_staged =
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
.unwrap();
assert!(!removed_staged, "staged-only index change must prevent zero-diff worktree GC");
assert!(created.path.exists());
// Reset index back to HEAD -> zero-diff GC removes the worktree via non-forced `git worktree remove`.
git(&created.path, &["reset", "-q", "HEAD", "--", "packages/subapp/index.ts"]);
let removed_clean =
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
.unwrap();
assert!(removed_clean);
assert!(!created.path.exists());
// Foreign / manually created git worktree inside `wt_dir` without ownership marker is NEVER deleted.
let manual_wt = wt_dir.join("foreign");
git(&repo, &["worktree", "add", "-q", "-b", "manual-branch", manual_wt.to_str().unwrap(), "HEAD"]);
assert!(
remove_owned_automation_worktree(&repo, &wt_dir, &manual_wt, "task-2", Some(&created.base_commit), false,)
.is_err()
);
assert!(manual_wt.exists(), "worktree without OpenIDEA ownership marker must never be deleted");
}
#[cfg(unix)]
#[test]
fn symlinked_subproject_cwd_escaping_worktree_is_rejected_on_create_and_reuse() {
let tmp = tempfile::tempdir().unwrap();
let outside = tmp.path().join("outside");
std::fs::create_dir_all(&outside).unwrap();
std::fs::write(outside.join("secret.txt"), "nope\n").unwrap();
let repo = tmp.path().join("repo");
let packages = repo.join("packages");
std::fs::create_dir_all(&packages).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
git(&repo, &["config", "core.autocrlf", "false"]);
// 1a. Direct symlink pointing outside git is rejected immediately.
let escape_link = packages.join("escape");
std::os::unix::fs::symlink(&outside, &escape_link).unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "symlink escape"]);
let wt_dir = tmp.path().join("wt");
assert!(create_for_task(&escape_link, &wt_dir, "task-escape-direct", "Escape", None).is_err());
// 1b. Committed symlink in `HEAD` (`packages/tricky -> ../../outside`) while the main
// checkout temporarily has a real directory at `packages/tricky`: `git worktree add`
// checks out `HEAD`'s symlink inside the worktree, and `verify_confined_worktree_subdir`
// must catch the escape and clean up the worktree!
let tricky = packages.join("tricky");
std::os::unix::fs::symlink(&outside, &tricky).unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "committed tricky symlink"]);
std::fs::remove_file(&tricky).unwrap();
std::fs::create_dir_all(&tricky).unwrap();
let Err(err) = create_for_task(&tricky, &wt_dir, "task-escape-head", "Tricky", None) else {
panic!("expected committed symlink escaping worktree root to be rejected");
};
assert!(
err.to_string().contains("outside worktree") || err.to_string().contains("escapes worktree root"),
"unexpected error for committed symlink cwd: {err}"
);
// 2. Normal directory at creation time, later replaced with an escaping symlink before reuse,
// must be rejected by `verify_confined_worktree_cwd`!
let legit_sub = packages.join("legit");
std::fs::create_dir_all(&legit_sub).unwrap();
std::fs::write(legit_sub.join("ok.txt"), "ok\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "legit sub"]);
let created = create_for_task(&legit_sub, &wt_dir, "task-reuse", "Legit", None).unwrap();
let verified = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap();
assert!(verified.starts_with(dunce::canonicalize(&created.path).unwrap()));
std::fs::remove_dir_all(&created.cwd).unwrap();
std::os::unix::fs::symlink(&outside, &created.cwd).unwrap();
let reuse_err = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap_err();
assert!(
reuse_err.to_string().contains("outside worktree") || reuse_err.to_string().contains("escapes"),
"symlink swap on worktree reuse must be rejected: {reuse_err}"
);
}
}
+24
Переглянути файл
@@ -0,0 +1,24 @@
{
"version": 2,
"plugins": {
"evidence-plugin@evidence-mkt": [
{
"scope": "user",
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
"version": "1.2.3",
"installedAt": "2026-11-30T21:50:25.665Z",
"lastUpdated": "2026-11-30T21:50:25.665Z",
"gitCommitSha": "1111111111111111111111111111111111111111"
},
{
"scope": "project",
"projectPath": "$WORKSPACE",
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
"version": "1.2.3",
"installedAt": "2026-11-30T21:50:25.665Z",
"lastUpdated": "2026-11-30T21:50:25.665Z",
"gitCommitSha": "1111111111111111111111111111111111111111"
}
]
}
}
+6
Переглянути файл
@@ -0,0 +1,6 @@
[marketplaces.evidence-mkt]
source_type = "local"
source = "$HOME/.codex/.tmp/marketplaces/evidence-mkt"
[plugins."evidence-plugin@evidence-mkt"]
enabled = false
+19
Переглянути файл
@@ -0,0 +1,19 @@
// This file is managed automatically.
{
"installedPlugins": [
{
"name": "evidence-plugin",
"marketplace": "evidence-mkt",
"installed_at": "2026-11-30T21:50:25.665Z",
"enabled": true,
"version": "1.2.3",
"cache_path": "$HOME/.copilot/installed-plugins/evidence-mkt/evidence-plugin",
"source": {
"source": "github",
"repo": "acme/plugins",
"sha": "1111111111111111111111111111111111111111",
"path": "plugins/evidence-plugin"
}
}
]
}
+8
Переглянути файл
@@ -0,0 +1,8 @@
{
"evidence-extension": {
"overrides": [
"$HOME/*",
"!$WORKSPACE/*"
]
}
}
+79 -11
Переглянути файл
@@ -17,8 +17,8 @@ pub use launch_resources::process_launch_resources;
pub use modules::record_module_build;
pub use single::{
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
has_gradle_file_target, javac_step, module_classpath, module_classpath_without_build, module_classpaths,
single_file_classpath, single_file_target,
has_gradle_file_target, javac_step, maven_system_classpath, module_classpath, module_classpath_without_build,
module_classpaths, single_file_classpath, single_file_target,
};
pub use structure::{
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
@@ -421,13 +421,14 @@ fn cargo_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
}
/// CLion's Build Project for a CMake project: configures the build directory when it has no
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild), one job per
/// `CMakeCache.txt` or no File API reply yet, then `cmake --build` (`--clean-first` to rebuild), one job per
/// logical CPU unless the profile's build arguments choose a count. The directory and
/// options come from the CMake profile; without one, a configured directory of the project
/// (the first by name), else `build`, as the generated run configurations use.
fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> Vec<BuildStep> {
let build_dir = match profile {
Some(p) if !p.build_dir.trim().is_empty() => p.build_dir.trim().to_owned(),
Some(p) if p.build_type.is_empty() => "cmake-build-default".into(),
Some(p) => format!("cmake-build-{}", p.build_type.to_lowercase()),
None => {
let mut configured: Vec<String> = std::fs::read_dir(dir)
@@ -444,18 +445,49 @@ fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> V
let build_type = profile.map_or("Debug", |p| p.build_type.as_str());
let env = profile.map(|p| p.env.clone()).unwrap_or_default();
let mut steps = Vec::new();
if !dir.join(&build_dir).join("CMakeCache.txt").is_file() {
let mut configure = BuildStep::new("cmake", &["-S", ".", "-B", &build_dir], dir, Format::Gcc);
if let Some(p) = profile.filter(|p| !p.generator.trim().is_empty()) {
configure.args.extend(["-G".into(), p.generator.clone()]);
}
configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}"));
let preset = profile.and_then(|p| p.preset.as_ref());
// The profile's toolchain may bring its own cmake.
let cmake = profile.and_then(|p| p.cmake_program.as_ref()).map_or("cmake".into(), |c| c.to_string_lossy());
let cmake = cmake.as_ref();
let build_path = dir.join(&build_dir);
// Configured without the File API queries (by another tool, or before they were written):
// configure again so the targets, and their run configurations, become known.
let fresh = !build_path.join("CMakeCache.txt").is_file();
if fresh || !build_path.join(ide_core::cmake_file_api::REPLY).is_dir() {
// Best effort: without the queries the build still runs, only the targets stay unknown.
let _ = ide_core::cmake_file_api::write_queries(&build_path);
let mut configure = match preset {
// The preset sets the generator and cache variables.
Some(preset) => BuildStep::new(cmake, &["--preset", &preset.configure], dir, Format::Gcc),
None => {
let mut configure = BuildStep::new(cmake, &["-S", ".", "-B", &build_dir], dir, Format::Gcc);
// A configured directory keeps its generator (CMake refuses another one) and,
// without a profile, its build type.
if let Some(p) = profile.filter(|p| fresh && !p.generator.trim().is_empty()) {
configure.args.extend(["-G".into(), p.generator.clone()]);
}
if fresh || profile.is_some() {
configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}"));
}
configure
}
};
configure.args.push("-DCMAKE_EXPORT_COMPILE_COMMANDS=ON".into());
configure.args.extend(profile.map(|p| p.cmake_args.clone()).unwrap_or_default());
configure.env = env.clone();
steps.push(configure);
}
let mut build = BuildStep::new("cmake", &["--build", &build_dir, "--config", build_type], dir, Format::Gcc);
let mut build = match preset.and_then(|p| p.build.as_deref()) {
Some(build) => BuildStep::new(cmake, &["--build", "--preset", build], dir, Format::Gcc),
None => {
let mut build = BuildStep::new(cmake, &["--build", &build_dir], dir, Format::Gcc);
// CLion's "Default" build type: no configuration at all.
if !build_type.is_empty() {
build.args.extend(["--config".into(), build_type.into()]);
}
build
}
};
if kind == BuildKind::Rebuild {
build.args.push("--clean-first".into());
}
@@ -986,7 +1018,7 @@ fn maven_launch_projects<'a>(
}
projects.push(p);
for dep in &p.dependencies {
if !dep.resolved() || (dep.scope == "test" && (!test || p.pom != start.pom)) {
if !dep.resolved() || dep.scope == "system" || (dep.scope == "test" && (!test || p.pom != start.pom)) {
continue;
}
if let Some(upstream) = reactor.iter().find(|u| {
@@ -1659,6 +1691,15 @@ mod tests {
"an unconfigured project is configured first"
);
write(&cm, "cmake-build-release/CMakeCache.txt", "");
let p =
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(
p.steps[0].args,
["-S", ".", "-B", "cmake-build-release", "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"],
"configured again, as it was, when it has no File API reply"
);
assert!(cm.join("cmake-build-release/.cmake/api/v1/query/client-openidea/codemodel-v2").is_file());
std::fs::create_dir_all(cm.join("cmake-build-release").join(ide_core::cmake_file_api::REPLY)).unwrap();
let p =
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(
@@ -1694,6 +1735,33 @@ mod tests {
)
.unwrap();
assert_eq!(p.steps[0].args[..4], ["-S", ".", "-B", "cmake-build-debug"]);
let preset = CMakeProfile {
build_dir: "out/dev".into(),
preset: Some(ide_core::settings::CMakePresetRef {
configure: "dev".into(),
build: Some("dev-build".into()),
..Default::default()
}),
..CMakeProfile::default()
};
let p = plan(
&cm,
&BuildModel::default(),
BuildKind::Build,
None,
Some(std::slice::from_ref(&preset)),
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(
args(&p),
[
"--preset dev -DCMAKE_EXPORT_COMPILE_COMMANDS=ON".to_owned(),
format!("--build --preset dev-build {jobs}")
],
"a preset profile configures and builds with its presets"
);
let siblings = tmp.path().join("siblings");
write(&siblings, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
+87 -4
Переглянути файл
@@ -180,6 +180,30 @@ pub fn find_javac(env: &BTreeMap<String, String>) -> String {
exe.to_owned()
}
/// Existing system-scope dependencies of this module. Maven resolves these from
/// their local files and does not pass them transitively to reactor dependents.
pub fn maven_system_classpath(root: &Path, model: &BuildModel, module: &Path) -> Vec<PathBuf> {
let Some(maven) = &model.maven else { return Vec::new() };
let module = root.join(module);
maven
.projects
.iter()
.find(|p| root.join(&p.dir) == module)
.into_iter()
.flat_map(|p| &p.system_paths)
.filter(|p| p.is_file())
.cloned()
.collect()
}
fn with_system_classpath(root: &Path, model: &BuildModel, module: &Path, classpath: String) -> String {
let system = maven_system_classpath(root, model, module);
if system.is_empty() {
return classpath;
}
join_classpath(std::env::split_paths(&classpath).chain(system).map(|p| p.to_string_lossy().into_owned()))
}
/// Dependency classpath of the module: existing reactor class directories plus
/// `mvn dependency:build-classpath` (which resolves without compiling anything,
/// so `-am` stays cheap). Entries are platform-separated (`;` on Windows).
@@ -233,7 +257,7 @@ pub fn module_classpath_without_build(
&& cached.version == CLASSPATH_CACHE_VERSION
&& classpath_entries_exist(root, &cached.classpath)
{
return Ok(cached.classpath);
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
}
classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel)
}
@@ -270,7 +294,7 @@ pub fn module_classpaths(
&& classpath_entries_exist(root, &cached.classpath)
{
if i == 0 {
return Ok(cached.classpath);
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
}
continue;
}
@@ -298,7 +322,7 @@ pub fn module_classpaths(
}
}
}
Ok(classpaths.into_iter().next().unwrap())
Ok(with_system_classpath(root, model, &modules[0], classpaths.into_iter().next().unwrap()))
}
/// A module whose classpath the Maven probe resolves, with its cache key and file.
@@ -346,7 +370,8 @@ fn classpath(
compile_first: bool,
cancel: &CancellationToken,
) -> IdeResult<String> {
Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
let classpath = classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap();
Ok(with_system_classpath(root, model, &target.module, classpath))
}
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
@@ -912,6 +937,64 @@ mod tests {
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
}
#[cfg(unix)]
#[test]
fn system_jars_augment_maven_javac_and_launch_classpaths() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
write(
&root,
"pom.xml",
r#"<project><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version>
<packaging>pom</packaging><modules><module>app</module></modules>
<properties><lib.dir>src/main/resources/lib</lib.dir></properties></project>"#,
);
write(
&root,
"app/pom.xml",
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
<artifactId>app</artifactId>
<properties><lib.file>${lib.dir}/offline.jar</lib.file></properties>
<dependencies>
<dependency><groupId>local</groupId><artifactId>offline</artifactId><version>1</version>
<scope>system</scope><systemPath>${pom.basedir}/${lib.file}</systemPath></dependency>
<dependency><groupId>local</groupId><artifactId>late</artifactId><version>1</version>
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}/late.jar</systemPath></dependency>
<dependency><groupId>local</groupId><artifactId>directory</artifactId><version>1</version>
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}</systemPath></dependency>
</dependencies></project>"#,
);
let jars = "app/src/main/resources/lib";
write(&root, &format!("{jars}/offline.jar"), "");
write(&root, "app/src/main/java/demo/Main.java", "class Main {}");
// The scope-filtered Maven classpath can contain no dependencies.
write(&root, "mvnw", "#!/bin/sh\nmkdir -p app/target\n: > app/target/ide-compile-cp.txt\n");
fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap();
let cache = root.join("cache");
let model = crate::load(&root, &cache, None);
let module = root.join("app");
let file = module.join("src/main/java/demo/Main.java");
let jar = root.join(jars).join("offline.jar");
let plan = compile_file_plan(&root, &model, &file).unwrap();
assert!(plan.steps[0].args.windows(2).any(|arg| arg[0] == "-cp" && Path::new(&arg[1]) == jar));
let cancel = CancellationToken::new();
let cp = module_classpath(&root, &model, &module, false, None, &cache, &cancel).unwrap();
let paths: Vec<_> = std::env::split_paths(&cp).collect();
assert_eq!(paths, [module.join("target/classes"), jar.clone()]);
assert!(maven_system_classpath(&root, &model, &root).is_empty());
// Adding a previously absent jar or deleting an old one updates a no-build launch.
fs::remove_file(jar).unwrap();
write(&root, &format!("{jars}/late.jar"), "");
fs::remove_file(root.join("mvnw")).unwrap();
let cp = module_classpath_without_build(&root, &model, &module, false, &cache, &cancel).unwrap();
let paths: Vec<_> = std::env::split_paths(&cp).collect();
assert_eq!(paths, [module.join("target/classes"), root.join(jars).join("late.jar")]);
}
/// Modules launched together resolve their classpaths in one Maven probe and leave
/// the others' cached; a probe another module breaks still resolves the first one.
#[cfg(unix)]
+19 -4
Переглянути файл
@@ -234,9 +234,7 @@ fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Ve
Some(out)
}
/// Parses a class file; `None` when it isn't a well-formed one.
pub fn parse(data: &[u8]) -> Option<ClassFile> {
let mut r = Bytes { data, pos: 0 };
fn read_pool(r: &mut Bytes<'_>) -> Option<Pool> {
if r.u4()? != 0xCAFE_BABE {
return None;
}
@@ -283,11 +281,28 @@ pub fn parse(data: &[u8]) -> Option<ClassFile> {
entries.push(entry);
i += 1;
if wide {
if i == count {
return None;
}
entries.push(Entry::Empty);
i += 1;
}
}
let pool = Pool(entries);
Some(Pool(entries))
}
/// Reads the internal class name (e.g. `com/acme/Order$Line`) from `this_class`.
pub fn class_file_name(data: &[u8]) -> Option<String> {
let mut r = Bytes { data, pos: 0 };
let pool = read_pool(&mut r)?;
r.u2()?; // access_flags
Some(pool.class(r.u2()?)?.to_owned())
}
/// Parses a class file; `None` when it isn't a well-formed one.
pub fn parse(data: &[u8]) -> Option<ClassFile> {
let mut r = Bytes { data, pos: 0 };
let pool = read_pool(&mut r)?;
let mut refs = BTreeSet::new();
for entry in &pool.0 {
match entry {
+6 -2
Переглянути файл
@@ -22,7 +22,7 @@ mod incremental;
mod javac;
mod model;
pub use classfile::ClassFile;
pub use classfile::{ClassFile, class_file_name};
pub use javac::{JavacPool, Reply, ServerKey};
use incremental::{ClassRecord, SetStamp, SetState};
@@ -702,7 +702,11 @@ impl JavaBuild<'_> {
let step = match top {
Reactor::Maven(top) => {
let selection = maven_project_selection(changed.iter().map(|(p, _, _)| *p));
let mut extra = vec!["-q".to_owned(), "-pl".to_owned(), selection];
// The resources plugin copies a file only when it is newer than the copy; content
// replaced without moving the mtime (a sync tool, PowerShell `Copy-Item`) would stay
// stale while its stamp is recorded as processed.
let mut extra =
vec!["-q".to_owned(), "-pl".to_owned(), selection, "-Dmaven.resources.overwrite=true".to_owned()];
extra.push("resources:resources".into());
if changed.iter().any(|(_, test, _)| *test) {
extra.push("resources:testResources".into());
+2
Переглянути файл
@@ -258,6 +258,8 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl t:app"), "{steps:?}");
// #7340: content replaced without a newer mtime is copied too.
assert!(steps[0].contains("-Dmaven.resources.overwrite=true"), "{steps:?}");
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nmore=1\n");
// A deleted source leaves no class behind.
+29 -2
Переглянути файл
@@ -69,6 +69,9 @@ pub struct MavenProject {
pub aggregated: bool,
pub plugins: Vec<MavenPlugin>,
pub dependencies: Vec<MavenDependency>,
/// Local classpath entries from the POM. The synced dependency tree has coordinates only.
#[serde(skip)]
pub system_paths: Vec<PathBuf>,
/// Profile ids declared in this POM.
pub profiles: Vec<String>,
/// Java feature version the project compiles for (`maven.compiler.release`, `java.version`…).
@@ -176,6 +179,7 @@ struct RawDep {
kind: Option<String>,
classifier: Option<String>,
scope: Option<String>,
system_path: Option<String>,
optional: bool,
}
@@ -248,6 +252,7 @@ fn read_dep(e: &Element) -> Option<RawDep> {
kind: e.text_of("type"),
classifier: e.text_of("classifier"),
scope: e.text_of("scope"),
system_path: e.text_of("systemPath"),
optional: e.text_of("optional").is_some_and(|o| o == "true"),
})
}
@@ -1519,7 +1524,13 @@ pub fn load_with_linked_jdk(
let packaging = i(pom.packaging.as_deref().unwrap_or("jar"));
let managed: HashMap<String, &RawDep> = ctx.managed.iter().map(|m| (m.key(), m)).collect();
let managed_version = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.version.clone());
let managed_scope = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.scope.clone());
let scope = |d: &RawDep| {
d.scope
.as_deref()
.or_else(|| managed.get(&d.key()).and_then(|m| m.scope.as_deref()))
.map(i)
.unwrap_or_else(|| "compile".into())
};
let dependencies = ctx
.deps
.iter()
@@ -1529,11 +1540,26 @@ pub fn load_with_linked_jdk(
version: d.version.clone().or_else(|| managed_version(d)).map(|v| i(&v)),
kind: d.kind.clone().unwrap_or_else(|| "jar".into()),
classifier: d.classifier.clone(),
scope: d.scope.clone().or_else(|| managed_scope(d)).unwrap_or_else(|| "compile".into()),
scope: scope(d),
optional: d.optional,
..MavenDependency::default()
})
.collect();
let system_paths = ctx
.deps
.iter()
.filter(|d| scope(d) == "system")
.filter_map(|d| {
let path = d
.system_path
.as_deref()
.or_else(|| managed.get(&d.key()).and_then(|m| m.system_path.as_deref()))?;
let path = i(path);
// Rebuilt from its components: `${pom.basedir}/lib/x.jar` on Windows mixes `\\` and `/`.
(!path.contains("${") && Path::new(&path).is_absolute())
.then(|| Path::new(&path).components().collect::<PathBuf>())
})
.collect();
let mut plugins: Vec<RawPlugin> = ctx.plugins.clone();
for a in lifecycle_plugins(&packaging) {
@@ -1592,6 +1618,7 @@ pub fn load_with_linked_jdk(
aggregated,
plugins,
dependencies,
system_paths,
profiles: ctx.profiles.iter().map(|(id, _)| id.clone()).collect(),
java_version: jv,
command: wrapper(&canonical_root, &dir_canon),
+20
Переглянути файл
@@ -0,0 +1,20 @@
//! The CMake File API queries the IDE writes into a build directory, shared by the run
//! configurations (which read the replies) and Build Project (which configures).
use std::path::Path;
/// The objects asked for: targets, cache, toolchains and the CMake files.
pub const QUERIES: [&str; 4] = ["codemodel-v2", "cache-v2", "toolchains-v1", "cmakeFiles-v1"];
const QUERY: &str = ".cmake/api/v1/query/client-openidea";
/// Where CMake writes its replies, relative to the build directory.
pub const REPLY: &str = ".cmake/api/v1/reply";
/// Asks CMake to answer [`QUERIES`] on the next configure of `build`.
pub fn write_queries(build: &Path) -> std::io::Result<()> {
let query = build.join(QUERY);
std::fs::create_dir_all(&query)?;
for name in QUERIES {
std::fs::write(query.join(name), "")?;
}
Ok(())
}
+16
Переглянути файл
@@ -401,6 +401,8 @@ impl Default for CodeEditingSettings {
#[serde(default, rename_all = "camelCase")]
pub struct InlayHintsSettings {
pub types: bool,
/// Inferred variable and field types from the JavaScript and TypeScript servers (on, as in WebStorm).
pub js_ts_types: bool,
pub parameters: bool,
/// Hints of other kinds (chaining, closing labels…).
pub other: bool,
@@ -436,6 +438,7 @@ impl Default for InlayHintsSettings {
fn default() -> Self {
Self {
types: true,
js_ts_types: true,
parameters: true,
other: true,
closing_labels: true,
@@ -710,6 +713,19 @@ mod folding_tests {
}
}
#[cfg(test)]
mod inlay_hints_tests {
use super::InlayHintsSettings;
#[test]
fn existing_settings_enable_js_ts_type_hints_by_default() {
let settings: InlayHintsSettings = serde_json::from_str(r#"{"parameters":false}"#).unwrap();
assert!(settings.types);
assert!(settings.js_ts_types);
assert!(!settings.parameters);
}
}
#[cfg(test)]
mod sticky_lines_tests {
use super::CodeEditingSettings;
+2
Переглянути файл
@@ -99,6 +99,8 @@ pub enum IdeEvent {
WindowGroupsChanged,
/// A project was loaded or unloaded for the MCP server without a window of its own.
McpBackgroundProjectsChanged,
/// Agent automations, run history, or session schedules changed on the host.
AutomationsChanged,
/// A window entered or left full screen, itself or as a member of a full-screen window group.
WindowFullscreenChanged,
/// This remote window's connection ended or another window took over the session.
+1
Переглянути файл
@@ -6,6 +6,7 @@
pub mod build_jobs;
pub mod cli_process;
pub mod cmake_file_api;
pub mod editor_settings;
pub mod error;
pub mod event;
+40
Переглянути файл
@@ -83,6 +83,24 @@ pub fn own_group(cmd: &mut Command) -> &mut Command {
cmd
}
/// Starts the child as the leader of a session of its own on Unix. Like [`own_group`] it leads
/// its process group, so [`kill_tree`] and [`terminate_tree`] reach what it starts; unlike it,
/// the child has no controlling terminal, so a tool that would ask on `/dev/tty` (and be
/// stopped there as a background job when the app was started from a shell) falls back to
/// its pipes. Use it in place of `own_group`: a group leader cannot start a session. A no-op
/// elsewhere.
pub fn own_session(cmd: &mut Command) -> &mut Command {
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// SAFETY: `setsid` is async-signal-safe and touches none of the parent's memory.
unsafe {
cmd.pre_exec(|| if libc::setsid() == -1 { Err(std::io::Error::last_os_error()) } else { Ok(()) });
}
}
cmd
}
/// Kills the child and everything it started, then reaps it.
///
/// - Unix: `SIGKILL` to its process group, so spawn it with [`own_group`].
@@ -970,6 +988,28 @@ fn append_path_entries(path: &OsStr, extra: &OsStr) -> OsString {
mod tests {
use super::*;
#[cfg(unix)]
#[test]
fn own_session_leaves_the_controlling_terminal_behind() {
// `ps` prints `?` (Linux) or `??` (macOS) for a process without a controlling terminal.
let mut cmd = Command::new("sh");
cmd.args(["-c", "ps -o tty= -p $$"]);
let out = own_session(&mut cmd).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert!(String::from_utf8_lossy(&out.stdout).trim().chars().all(|c| c == '?'), "{:?}", out.stdout);
// Without a terminal (CI) the line above holds anyway: the child must lead a session
// of its own, which only `setsid` makes it.
let mut cmd = Command::new("sleep");
cmd.arg("5");
let mut child = own_session(&mut cmd).spawn().unwrap();
let pid = libc::pid_t::try_from(child.id()).unwrap();
// SAFETY: plain syscall on a child not reaped yet.
let session = unsafe { libc::getsid(pid) };
let _ = child.kill();
let _ = child.wait();
assert_eq!(session, pid, "the child leads its own session");
}
#[test]
fn process_alive_tells_live_from_dead_pids() {
assert!(process_alive(std::process::id()));
+24 -7
Переглянути файл
@@ -5,6 +5,29 @@ use std::path::{Component, Path, PathBuf};
pub const SEARCH_DEPTH: usize = 3;
/// Folders that hold dependencies or build output rather than the project's own builds: hidden
/// folders (`.build`, `.git`), package checkouts (`node_modules`, `SourcePackages`, `Pods`,
/// `Carthage`) and build products (`target`, `build`, `DerivedData`, …).
pub fn is_skipped_dir(name: &str) -> bool {
name.starts_with('.')
|| matches!(
name,
"node_modules"
| "target"
| "build"
| "dist"
| "vendor"
| "out"
| "bin"
| "obj"
| "venv"
| "SourcePackages"
| "Pods"
| "Carthage"
| "DerivedData"
)
}
pub fn children(dir: &Path) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
let mut dirs: Vec<_> = entries
@@ -13,13 +36,7 @@ pub fn children(dir: &Path) -> Vec<PathBuf> {
if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
return false;
}
let name = entry.file_name();
let name = name.to_string_lossy();
!name.starts_with('.')
&& !matches!(
name.as_ref(),
"node_modules" | "target" | "build" | "dist" | "vendor" | "out" | "bin" | "obj" | "venv"
)
!is_skipped_dir(&entry.file_name().to_string_lossy())
})
.map(|entry| entry.path())
.collect();
+204 -1
Переглянути файл
@@ -68,6 +68,8 @@ pub struct Settings {
/// Build, Execution, Deployment › Run Targets.
pub run_targets: Vec<RunTarget>,
pub cmake: CMakeSettings,
/// Build, Execution, Deployment › Toolchains; the first is the default.
pub toolchains: Vec<Toolchain>,
/// Settings › Agents.
pub agents: AgentSettings,
/// Agents › MCP Server (global only).
@@ -170,6 +172,15 @@ pub struct AgentSettings {
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentMemorySettings)]
pub memory: AgentMemorySettings,
/// Agent plugin bundle policies (`[agents.plugins]`): registered marketplaces and non-sensitive
/// config. Enablement lives in each harness's native config; capability consent is stored per machine.
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentPluginSettings)]
pub plugins: AgentPluginSettings,
/// Scheduled agent automations and headless scheduler host policies (`[agents.automations]`).
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentAutomationSettings)]
pub automations: AgentAutomationSettings,
}
impl Default for AgentSettings {
@@ -202,6 +213,8 @@ impl Default for AgentSettings {
mcp_servers: BTreeMap::new(),
skills: BTreeMap::new(),
memory: AgentMemorySettings::default(),
plugins: AgentPluginSettings::default(),
automations: AgentAutomationSettings::default(),
}
}
}
@@ -358,6 +371,96 @@ pub struct AgentMemorySettings {
pub entries: BTreeMap<String, AgentMemoryEntryPolicy>,
}
/// One agent plugin bundle's policy in Settings › Agents › Plugins
/// (`[agents.plugins.entries."<harness>:<plugin>@<marketplace>"]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentPluginEntryPolicy {
/// Non-sensitive `userConfig` / `variables` key-value pairs; sensitive values live in OS Keychain.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub config: BTreeMap<String, String>,
}
/// Agent plugin bundle settings (`[agents.plugins]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentPluginSettings {
/// Registered plugin marketplaces (`owner/repo[#ref]`, GitHub URL, or local directory/manifest path).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub marketplaces: Vec<String>,
/// Per-plugin non-sensitive native option hints, keyed by `<harness>:<plugin>@<marketplace>`.
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
#[specta(type = BTreeMap<String, AgentPluginEntryPolicy>)]
pub entries: BTreeMap<String, AgentPluginEntryPolicy>,
}
/// When OpenIDEA holds an OS idle-sleep assertion during active automation turns.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AutomationPreventSleep {
/// Prevent idle sleep while plugged into AC power.
#[default]
Ac,
/// Prevent idle sleep whenever an automated turn is running.
Always,
/// Never hold an idle-sleep assertion.
Never,
}
/// What the scheduler does when one or more scheduled occurrences fell due while asleep or offline.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AutomationMisfirePolicy {
/// Coalesce all missed occurrences into at most one catch-up run once awake and online.
#[default]
RunOnce,
/// Skip missed occurrences and advance to the next future slot.
Skip,
}
/// Agent automation and headless scheduler settings (`[agents.automations]`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentAutomationSettings {
/// Automatically register the headless login/boot scheduler service while at least one
/// automation is enabled, and unregister it when none remain enabled.
pub auto_start_service: bool,
/// Keep the local OpenIDEA host alive in the background when windows close while local
/// automations are enabled.
pub keep_alive_in_background: bool,
/// Prevent system idle sleep while an automated turn is running.
#[serde(deserialize_with = "or_default")]
#[specta(type = AutomationPreventSleep)]
pub prevent_sleep: AutomationPreventSleep,
/// Default policy for scheduled occurrences missed during sleep, offline downtime, or reboot.
#[serde(deserialize_with = "or_default")]
#[specta(type = AutomationMisfirePolicy)]
pub misfire_policy: AutomationMisfirePolicy,
/// Keep `openidea-server --daemon` alive across disconnects while the remote host has
/// enabled scheduled automations.
pub keep_remote_daemon_alive: bool,
/// Automatically remove temporary automation worktrees when a run finishes with zero diff
/// and zero commits.
pub auto_clean_worktrees: bool,
/// Maximum retained non-clean automation worktrees per automation before pruning oldest
/// finished ones.
pub max_dirty_worktrees: u32,
}
impl Default for AgentAutomationSettings {
fn default() -> Self {
Self {
auto_start_service: false,
keep_alive_in_background: true,
prevent_sleep: AutomationPreventSleep::Ac,
misfire_policy: AutomationMisfirePolicy::RunOnce,
keep_remote_daemon_alive: true,
auto_clean_worktrees: true,
max_dirty_worktrees: 5,
}
}
}
/// 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>
@@ -602,6 +705,8 @@ pub struct ToolDownloadSettings {
/// Maven Central, dependency version completion from Maven Central, npm, PyPI and
/// crates.io). Off by default.
pub configured_registries_only: bool,
/// The managed Vue Language Server release. Empty selects it from the project's Vue dependency.
pub vue_language_server_version: String,
}
/// Settings › Settings Sync: the Git repository the IDE settings sync through, and what syncs.
@@ -649,9 +754,42 @@ impl Default for SettingsSyncSettings {
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CMakeSettings {
#[serde(skip_serializing_if = "Option::is_none")]
/// Serialized as `null` when absent, so `cmake.profiles` stays a known settings key.
#[specta(optional)]
pub profiles: Option<Vec<CMakeProfile>>,
/// `true` ignores `CMakePresets.json` / `CMakeUserPresets.json`; otherwise every visible
/// configure preset whose condition holds is listed after the explicit profiles.
pub ignore_presets: bool,
/// Configure presets (by name) enabled as profiles. As in CLion, a preset is listed but
/// disabled until enabled here.
pub enabled_presets: Vec<String>,
/// The profile (by name) that build, run and debug use, as CLion's toolbar switcher;
/// empty or unknown = the first enabled one.
pub active_profile: String,
}
/// The presets a profile made from `CMakePresets.json` runs with.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CMakePresetRef {
pub configure: String,
/// The first build preset of `configure`, used by `cmake --build --preset`.
#[serde(skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub build: Option<String>,
/// The first test preset of `configure`, used by `ctest --preset`.
#[serde(skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub test: Option<String>,
/// Cache variables the resolved preset sets itself, read when presets are loaded (never
/// saved): a toolchain does not override them.
#[serde(skip)]
#[specta(skip)]
pub cache_variables: Vec<String>,
/// The preset names a toolchain file, which picks the compilers.
#[serde(skip)]
#[specta(skip)]
pub toolchain_file: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -665,6 +803,23 @@ pub struct CMakeProfile {
pub build_dir: String,
pub build_args: Vec<String>,
pub env: BTreeMap<String, String>,
/// `false` keeps the profile listed but unused (CLion's "Enable profile").
pub enabled: bool,
/// Toolchain name (Settings › Toolchains); empty = the default (first) toolchain.
pub toolchain: String,
/// Set only on the profiles made from presets: configure with `cmake --preset`, and the
/// generator and cache variables come from the preset.
#[serde(skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub preset: Option<CMakePresetRef>,
/// Resolved from the toolchain when profiles are put to use (never saved): the `cmake`
/// to run (`ctest` next to it) and the debugger to prefer.
#[serde(skip)]
#[specta(skip)]
pub cmake_program: Option<std::path::PathBuf>,
#[serde(skip)]
#[specta(skip)]
pub debugger: Option<std::path::PathBuf>,
}
impl Default for CMakeProfile {
@@ -677,10 +832,44 @@ impl Default for CMakeProfile {
build_dir: String::new(),
build_args: Vec::new(),
env: BTreeMap::new(),
enabled: true,
toolchain: String::new(),
preset: None,
cmake_program: None,
debugger: None,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum ToolchainKind {
/// Tools from the chosen paths, else from `PATH`.
#[default]
System,
/// A MinGW / MSYS2 directory: its `bin` goes first on `PATH`, with gcc, g++,
/// mingw32-make and gdb from there.
#[serde(rename = "mingw")]
MinGw,
}
/// Build, Execution, Deployment › Toolchains (IDE-wide, as in CLion). Empty fields are
/// detected: from the MinGW directory, else from `PATH`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct Toolchain {
pub name: String,
pub kind: ToolchainKind,
/// The MinGW directory (the one holding `bin`).
pub path: String,
pub cmake: String,
/// `CMAKE_MAKE_PROGRAM`: make, mingw32-make or ninja.
pub build_tool: String,
pub c_compiler: String,
pub cxx_compiler: String,
pub debugger: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ToolSettings {
@@ -792,6 +981,7 @@ impl Default for Settings {
deployment: DeploymentSettings::default(),
run_targets: Vec::new(),
cmake: CMakeSettings::default(),
toolchains: Vec::new(),
agents: AgentSettings::default(),
mcp_server: McpServerSettings::default(),
agent_security: AgentSecuritySettings::default(),
@@ -1509,6 +1699,9 @@ pub struct MarkdownSettings {
pub preview_layout: MarkdownPreviewLayout,
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
pub preview_font_size: Option<u32>,
/// Whether `.mdx` previews ask before running JSX components/imports, run automatically in
/// trusted projects, or stay in static safe mode.
pub mdx_execution: MdxExecutionPolicy,
/// "Detect commands that can be run right from Markdown files": gutter run icons on
/// shell code blocks and on command lines in code blocks.
pub run_commands: bool,
@@ -1521,12 +1714,22 @@ impl Default for MarkdownSettings {
Self {
preview_layout: MarkdownPreviewLayout::default(),
preview_font_size: None,
mdx_execution: MdxExecutionPolicy::default(),
run_commands: true,
command_directory: None,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MdxExecutionPolicy {
#[default]
Ask,
Trusted,
Off,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MarkdownPreviewLayout {
+8
Переглянути файл
@@ -296,6 +296,14 @@ pub struct OutlineItem {
#[serde(default)]
#[specta(optional)]
pub visibility: Option<Visibility>,
/// Rust `impl Trait for Type`: the trait's name in the header (its last path segment, where go-to-definition lands), from the syntax tree.
#[serde(default)]
#[specta(optional)]
pub implements: Option<Range>,
/// Rust `impl [Trait for] Type`: the implementing type's name (its last path segment), from the syntax tree.
#[serde(default)]
#[specta(optional)]
pub self_type: Option<Range>,
}
/// Fuzzy-match highlight: indices (in chars of the displayed string) that matched.
+60 -1
Переглянути файл
@@ -27,6 +27,35 @@ pub struct VcsSettings {
pub mappings: VcsMappings,
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
pub github: GithubSettings,
/// Settings › Version Control › Subversion.
pub svn: SvnSettings,
}
/// Settings › Version Control › Subversion (`vcs.svn`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct SvnSettings {
/// Path to the svn executable; empty = auto-detect.
pub executable: String,
/// Run svn as if in a terminal: its password, passphrase and certificate prompts open
/// dialogs. Off, svn runs with `--non-interactive` and a rejected login asks once.
pub interactive: bool,
/// Pass `--config-dir config_dir` to every svn command.
pub use_custom_config_dir: bool,
pub config_dir: String,
}
impl Default for SvnSettings {
/// Interactive except on Windows: svn there asks on the console, which an IDE's child
/// process has hidden, so a prompt could not be answered (not verified on Windows yet).
fn default() -> Self {
Self {
executable: String::new(),
interactive: !cfg!(windows),
use_custom_config_dir: false,
config_dir: String::new(),
}
}
}
/// Settings › Version Control › GitHub (`vcs.github`).
@@ -80,6 +109,7 @@ impl Default for VcsSettings {
issue_navigation: Vec::new(),
mappings: VcsMappings::default(),
github: GithubSettings::default(),
svn: SvnSettings::default(),
}
}
}
@@ -447,12 +477,15 @@ pub struct BuildSettings {
pub open_tool_window: String,
/// When to focus the Build tool window: `always` | `onError` | `never`.
pub focus_tool_window: String,
/// Build an Xcode project in the background when xcode-build-server has no build log to read
/// yet, so cross-file code insight works before the first Run.
pub xcode_index_build: bool,
}
impl Default for BuildSettings {
fn default() -> Self {
// Builds open the tool window without taking focus.
Self { open_tool_window: "always".into(), focus_tool_window: "never".into() }
Self { open_tool_window: "always".into(), focus_tool_window: "never".into(), xcode_index_build: true }
}
}
@@ -530,6 +563,7 @@ pub struct DebuggerSettings {
/// Java: whether to reload changed classes into running debug sessions after compilation.
pub hot_swap_after_compile: HotSwapPolicy,
pub python: PythonDebuggerSettings,
pub cpp: CppDebuggerSettings,
}
impl Default for DebuggerSettings {
@@ -552,6 +586,7 @@ impl Default for DebuggerSettings {
flutter_hot_reload_on_save: true,
hot_swap_after_compile: HotSwapPolicy::Ask,
python: PythonDebuggerSettings::default(),
cpp: CppDebuggerSettings::default(),
}
}
}
@@ -570,6 +605,14 @@ impl Default for PythonDebuggerSettings {
}
}
/// C/C++ debugger executables. Empty paths use automatic discovery.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CppDebuggerSettings {
pub gdb_executable: String,
pub lldb_dap_executable: String,
}
/// Run/Debug configuration behaviour.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -616,6 +659,8 @@ pub struct TerminalSettings {
pub close_on_exit: bool,
pub mouse_reporting: bool,
pub copy_on_selection: bool,
/// Programs may set the clipboard with OSC 52 (tmux, Neovim, TUIs over SSH); never read it.
pub osc52_clipboard: bool,
pub paste_on_middle_click: bool,
/// Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it).
pub right_click_paste: bool,
@@ -656,6 +701,7 @@ impl Default for TerminalSettings {
close_on_exit: true,
mouse_reporting: true,
copy_on_selection: false,
osc52_clipboard: true,
paste_on_middle_click: true,
right_click_paste: false,
override_ide_shortcuts: true,
@@ -800,4 +846,17 @@ mod tests {
assert_eq!(serialized["hotSwapAfterCompile"], raw);
}
}
#[test]
fn cpp_debugger_paths_default_to_empty_and_roundtrip() {
let missing: DebuggerSettings = serde_json::from_str("{}").unwrap();
assert!(missing.cpp.gdb_executable.is_empty());
assert!(missing.cpp.lldb_dap_executable.is_empty());
let cpp = serde_json::json!({"gdbExecutable": "tools/gdb-16", "lldbDapExecutable": "/opt/llvm/bin/lldb-dap"});
let settings: DebuggerSettings = serde_json::from_value(serde_json::json!({"cpp": cpp})).unwrap();
assert_eq!(settings.cpp.gdb_executable, "tools/gdb-16");
assert_eq!(settings.cpp.lldb_dap_executable, "/opt/llvm/bin/lldb-dap");
assert_eq!(serde_json::to_value(&settings).unwrap()["cpp"], cpp);
}
}
+23 -2
Переглянути файл
@@ -585,8 +585,9 @@ async fn prepare_gdb(spec: &AdapterSpec, binary: &Path) -> IdeResult<bool> {
return Ok(major == 15);
}
let mut msg = format!(
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor}): \
this one has no DAP interpreter (`gdb -i dap`)"
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor} at {}): \
this one has no DAP interpreter (`gdb -i dap`)",
binary.display(),
);
if let Some(hint) = &spec.install_hint {
msg.push_str(". ");
@@ -1068,6 +1069,26 @@ mod tests {
assert!(builtin("nope").is_none());
}
#[cfg(unix)]
#[tokio::test]
async fn gdb_version_check_probes_the_adapter_command() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let binary = dir.path().join("custom gdb");
std::fs::write(&binary, "#!/bin/sh\n[ \"$1\" = --version ] && echo 'GNU gdb (GDB) 13.2'\n").unwrap();
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut spec = resolve(&builtin("gdb").unwrap(), dir.path().to_path_buf());
spec.command = binary.to_str().unwrap().to_owned();
let Err(error) = ProcessLauncher.launch(spec, None).await else {
panic!("GDB 13 was started as a DAP adapter");
};
assert_eq!(error.kind, ide_core::error::ErrorKind::Unavailable);
assert!(error.message.contains("needs GDB 14 or newer (found 13.2 at "), "{}", error.message);
assert!(error.message.contains(binary.to_str().unwrap()), "{}", error.message);
}
/// Debian/Ubuntu's versioned lldb-dap (and lldb-vscode before LLVM 18): the newest LLVM wins.
#[cfg(unix)]
#[test]
+22 -2
Переглянути файл
@@ -508,6 +508,11 @@ fn child_name(configuration: &Value, parent: &str) -> String {
}
}
/// LLDB-based adapters, which debug native programs (and Swift on Apple platforms).
fn is_native(adapter: &str) -> bool {
matches!(adapter, "lldb-dap" | "codelldb")
}
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
/// adapter.
pub const RUN_LINK: &str = "__openideaRun";
@@ -1050,6 +1055,15 @@ impl DebugManager {
if let Some(command) = custom_command(&spec.command) {
spec.command = command;
}
// The debugger of the run configuration's toolchain (a MinGW gdb), over every other choice.
if let Some(command) = arguments
.as_object_mut()
.and_then(|o| o.remove(native::ADAPTER_COMMAND))
.and_then(|v| v.as_str().map(str::to_owned))
{
spec.command = command;
spec.pinned = None;
}
// debugpy: run the adapter with the debuggee's interpreter (venvs carry their own debugpy),
// or with the launcher's when the debuggee runs through a manager (`uv run python`).
if config.adapter == "debugpy" {
@@ -1638,11 +1652,16 @@ impl DebugManager {
let _ = s.conn.request_timeout("terminate", json!({ "restart": false }), SHUTDOWN_TIMEOUT).await;
}
if !graceful && (!own_terminate || killed) {
// A native attach to a program a run started for the debugger (an Xcode app launched
// with `simctl launch --wait-for-debugger`) ends it too: detached, the app can be
// left stopped with the SIGTERM the run's Stop sent while it was traced, and the
// simulator then holds its launch (and the next one) forever.
let ends_debuggee = s.request == "launch" || (terminate && s.run.is_some() && is_native(&s.adapter));
let _ = s
.conn
.request_timeout(
"disconnect",
json!({ "restart": false, "terminateDebuggee": s.request == "launch" }),
json!({ "restart": false, "terminateDebuggee": ends_debuggee }),
SHUTDOWN_TIMEOUT,
)
.await;
@@ -1786,7 +1805,8 @@ impl DebugManager {
let mut states = self.states.lock();
let Some(slot) = states.get_mut(path).and_then(|v| v.get_mut(index)) else { return false };
let next = session::state_from(bp, slot.line);
let next = BreakpointState { message: next.message.or_else(|| slot.message.clone()), ..next };
let kept = slot.message.clone().filter(|m| !(next.verified && m == session::UNBOUND_NATIVE));
let next = BreakpointState { message: next.message.or(kept), ..next };
let changed = *slot != next;
*slot = next;
changed
+36 -8
Переглянути файл
@@ -6,7 +6,11 @@ use crate::LaunchConfig;
use crate::adapter::{GDB_MIN_MAJOR, probe_gdb_version};
use ide_core::{IdeError, IdeResult};
use serde_json::{Map, Value, json};
use std::path::PathBuf;
use std::path::{Path, PathBuf};
/// Launch argument naming the debugger to run (a toolchain's gdb or lldb-dap), which replaces
/// the search: lldb-dap if its name says so, else GDB.
pub const ADAPTER_COMMAND: &str = "__adapterCommand";
/// Prefix of the error when none of them is there; the UI offers to install CodeLLDB on it.
pub const NO_NATIVE_DEBUGGER: &str = "No C/C++ debugger found";
@@ -20,7 +24,16 @@ pub async fn choose(
if config.adapter != "lldb-dap" || config.request != "launch" {
return Ok(config);
}
let chosen = config
.extra_json
.as_deref()
.and_then(|e| serde_json::from_str::<Value>(e).ok())
.and_then(|e| e[ADAPTER_COMMAND].as_str().map(PathBuf::from));
let found = tokio::task::spawn_blocking(move || {
if let Some(chosen) = chosen {
let name = chosen.file_stem().map(|s| s.to_string_lossy().to_lowercase()).unwrap_or_default();
return if name.contains("lldb-dap") { Found::LldbDap } else { Found::Gdb(chosen) };
}
if lookup("lldb-dap").is_some() {
return Found::LldbDap;
}
@@ -36,7 +49,7 @@ pub async fn choose(
Found::LldbDap => {}
Found::CodeLldb => convert(&mut config, "codelldb")?,
Found::Gdb(gdb) => match probe_gdb_version(&gdb, &cwd, &[]).await {
Some((major, minor)) if major < GDB_MIN_MAJOR => return Err(missing(Some((major, minor)))),
Some((major, minor)) if major < GDB_MIN_MAJOR => return Err(missing(Some((&gdb, major, minor)))),
// Unknown versions are left to GDB itself, as a GDB launch does.
_ => convert(&mut config, "gdb")?,
},
@@ -52,11 +65,12 @@ enum Found {
Nothing,
}
fn missing(gdb: Option<(u32, u32)>) -> IdeError {
fn missing(gdb: Option<(&Path, u32, u32)>) -> IdeError {
let found = match gdb {
Some((major, minor)) => format!(
"lldb-dap and CodeLLDB are not installed, and GDB {major}.{minor} cannot debug through DAP \
(it needs GDB {GDB_MIN_MAJOR} or newer)"
Some((path, major, minor)) => format!(
"lldb-dap and CodeLLDB are not installed, and GDB {major}.{minor} at {} cannot debug through DAP \
(it needs GDB {GDB_MIN_MAJOR} or newer)",
path.display(),
),
None => "lldb-dap, CodeLLDB and GDB are not installed".to_owned(),
};
@@ -103,7 +117,6 @@ fn convert(config: &mut LaunchConfig, to: &str) -> IdeResult<()> {
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::path::Path;
fn cmake_launch() -> LaunchConfig {
LaunchConfig {
@@ -154,6 +167,19 @@ mod tests {
assert_eq!(extra(&config)["swiftpm"]["product"], "app");
}
#[tokio::test]
async fn a_toolchain_debugger_replaces_the_search() {
let mut launch = cmake_launch();
launch.extra_json = Some(json!({"env": ["A=1"], ADAPTER_COMMAND: "/opt/mingw/bin/gdb.exe"}).to_string());
// lldb-dap is there, but the toolchain names its GDB (an unknown version is left to GDB).
let config = choose(launch, only(&["lldb-dap"])).await.unwrap();
assert_eq!(config.adapter, "gdb");
assert_eq!(extra(&config)[ADAPTER_COMMAND], "/opt/mingw/bin/gdb.exe", "kept for the adapter launch");
let mut launch = cmake_launch();
launch.extra_json = Some(json!({ADAPTER_COMMAND: "/opt/llvm/bin/lldb-dap"}).to_string());
assert_eq!(choose(launch, only(&[])).await.unwrap().adapter, "lldb-dap");
}
#[tokio::test]
async fn without_any_debugger_says_what_to_install() {
let e = choose(cmake_launch(), only(&[])).await.unwrap_err();
@@ -187,9 +213,11 @@ mod tests {
async fn an_old_gdb_is_named_in_the_error() {
let dir = tempfile::tempdir().unwrap();
let gdb = fake_gdb(dir.path(), "GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1");
let e = choose(cmake_launch(), move |c| (c == "gdb").then(|| gdb.clone())).await.unwrap_err();
let path = gdb.clone();
let e = choose(cmake_launch(), move |c| (c == "gdb").then(|| path.clone())).await.unwrap_err();
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
assert!(e.message.contains("GDB 12.1"), "{}", e.message);
assert!(e.message.contains(gdb.to_str().unwrap()), "{}", e.message);
}
#[cfg(unix)]
+8
Переглянути файл
@@ -293,6 +293,11 @@ impl Suspension {
/// symlinked path (`/tmp/game` while the editor has `/private/tmp/game`).
const RESOLVES_PATHS: &[&str] = &["godot"];
/// LLDB answers a breakpoint it can't bind yet with no reason: the code may simply not be loaded.
const NATIVE_ADAPTERS: &[&str] = &["lldb-dap", "codelldb"];
/// One literal: the UI looks it up in the text catalogs to translate it.
pub(crate) const UNBOUND_NATIVE: &str = "No loaded code at this line yet. If it stays unbound after its module loads, the debug info may record this file under another path (through a symlink, or /tmp for /private/tmp): set a source map from that path to this one";
impl Session {
#[allow(clippy::too_many_arguments)]
pub fn new(
@@ -514,6 +519,9 @@ impl Session {
ids.insert(id, (path.to_path_buf(), i));
}
states[i] = state_from(r, breakpoints[i].line);
if !states[i].verified && states[i].message.is_none() && NATIVE_ADAPTERS.contains(&self.adapter.as_str()) {
states[i].message = Some(UNBOUND_NATIVE.to_owned());
}
}
Ok(states)
}
+48 -1
Переглянути файл
@@ -138,6 +138,8 @@ struct Script {
output_after_terminate: bool,
/// Advertise `supportsTerminateRequest` (java-debug does not, so Stop signals the program).
supports_terminate: bool,
/// Answer `setBreakpoints` with unverified breakpoints and no reason (LLDB before the code loads).
unbound_breakpoints: bool,
/// Answer `setBreakpoints` only once this many are waiting (a client that waits for each never gets one).
hold_set_breakpoints: usize,
/// Send a `continued` event right after the first `stopped` one.
@@ -220,6 +222,7 @@ impl Default for Script {
fn default() -> Self {
Self {
run_in_terminal: None,
unbound_breakpoints: false,
start_debugging: false,
child_request: None,
ignore_configuration_done: false,
@@ -414,7 +417,7 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
.unwrap()
.iter()
.enumerate()
.map(|(i, b)| json!({"id": i + 1, "verified": true, "line": b["line"]}))
.map(|(i, b)| json!({"id": i + 1, "verified": !script.unbound_breakpoints, "line": b["line"]}))
.collect();
ok!(msg, json!({"breakpoints": bps}));
}
@@ -4019,6 +4022,50 @@ async fn stop_detaches_from_an_attached_program() {
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
}
/// Xcode Debug: lldb-dap attaches to the app a run launched suspended. Stop ends the app through
/// the debugger; detaching would leave it stopped with the run's SIGTERM, holding the simulator.
#[tokio::test]
async fn stop_ends_a_native_program_a_run_started_for_the_debugger() {
let h = harness(Script::default());
let linked = |adapter: &str| LaunchConfig {
adapter: adapter.into(),
request: "attach".into(),
extra_json: Some(json!({ RUN_LINK: 7, "pid": 4242 }).to_string()),
..config()
};
let id = h.start(linked("lldb-dap")).await.unwrap();
h.manager.stop(id).await.unwrap();
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], true);
// Another adapter's attach to a run (a Gradle test worker JVM) still only detaches.
let h = harness(Script::default());
let id = h.start(linked("debugpy")).await.unwrap();
h.manager.stop(id).await.unwrap();
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
}
/// LLDB leaves a breakpoint it can't bind unverified without a reason: say what may be wrong
/// (#6665 E1b: Xcode's debug info had `/tmp/…` for a project under `/private/tmp`).
#[tokio::test]
async fn an_unbound_native_breakpoint_says_why() {
for (adapter, hint) in [("lldb-dap", true), ("codelldb", true), ("debugpy", false)] {
let h = harness(Script { unbound_breakpoints: true, ..Script::default() });
h.start(LaunchConfig { adapter: adapter.into(), ..config() }).await.unwrap();
let path = PathBuf::from("/private/tmp/app/Counter.swift");
let states = h.manager.set_breakpoints(&h.owner.key, path, vec![bp(6)]).await.unwrap();
assert!(!states[0].verified);
assert_eq!(states[0].message.as_deref() == Some(crate::session::UNBOUND_NATIVE), hint, "{adapter}");
}
// Bound once the module loads (lldb-dap's `breakpoint` event has no message): the hint goes.
let path = PathBuf::from("/private/tmp/app/Counter.swift");
let h = harness(Script { unbound_breakpoints: true, ..Script::default() });
h.start(LaunchConfig { adapter: "lldb-dap".into(), ..config() }).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(6)]).await.unwrap();
assert!(h.manager.update_breakpoint_state(&path, 0, &json!({"id": 1, "verified": true, "line": 7})));
assert_eq!(h.manager.breakpoint_states(&path)[0].message, None);
}
#[tokio::test]
async fn cell_breakpoints_go_only_to_their_notebooks_kernel_session() {
use crate::jvm_memory::test_support::bare_session_of;
+153 -62
Переглянути файл
@@ -447,6 +447,15 @@ fn read_table_properties(details: &mut TableDetails, row: Vec<Option<String>>) {
);
details.partitioning = next();
details.persistence = next().as_deref().and_then(DbPersistence::from_catalog);
// PostgreSQL's `table_properties` carries the comment as its last column, so reading it here
// saves the separate query `table_comment` would make on the same `pg_class` row.
if let Some(comment) = next() {
// `table_comment` this replaces yielded `NULL` or empty for no comment, so an empty
// comment must not become `Some("")` — the DDL would emit an empty `COMMENT ON`.
if !comment.is_empty() {
details.comment = Some(comment);
}
}
}
fn flag(v: &Option<String>) -> bool {
@@ -1346,6 +1355,25 @@ impl DbManager {
Self::table_details_on(&pool, Some(catalog), schema, table).await
}
/// Read metadata using an existing connection only. A concurrent disconnect must not
/// cause a read-only extension request to reopen a source or prompt for credentials.
pub async fn connected_table_details(
&self,
id: &str,
catalog: Option<&str>,
schema: &str,
table: &str,
) -> IdeResult<TableDetails> {
if catalog.is_some() {
let source = self.source(id)?;
if id != source.id || source.driver != DbDriver::Jdbc || source.vendor != "duckdb" {
return Err(IdeError::invalid("Catalog browsing requires a DuckDB data source"));
}
}
let pool = self.connected_pool(id)?;
Self::table_details_on(&pool, catalog, schema, table).await
}
pub async fn table_details(&self, id: &str, schema: &str, table: &str) -> IdeResult<TableDetails> {
let pool = self.pool(id).await?;
Self::table_details_on(&pool, None, schema, table).await
@@ -1384,8 +1412,61 @@ impl DbManager {
if driver == DbDriver::Jdbc {
return Ok(TableDetails { columns, ..Default::default() });
}
// Everything below describes the same table and none of it feeds the next, so it goes
// out together. Serialised, this is four round trips on the path that opens a table
// (`table_page_on` calls this for the primary key), which is what makes opening a table
// feel slow on a remote server. Five queries against a pool of four (`conn.rs`'s `MAX`),
// so one waits — still one round trip rather than five.
type Rows = Vec<Vec<Option<String>>>;
let keys = !matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake);
let (index_q, fk_q, trigger_q) = (
sql::indexes(driver, schema, table),
sql::table_foreign_keys(driver, schema, table),
sql::triggers(driver, schema, table),
);
let (index_rows, fk_rows, trigger_rows, comment_rows, property_rows) = futures::join!(
pool.rows(&index_q, MAX_META_ROWS),
async {
if !keys {
return Ok::<Rows, IdeError>(Vec::new());
}
match pool.rows(&fk_q, MAX_META_ROWS).await {
Ok(rows) => Ok(rows),
Err(e) => {
tracing::warn!("foreign keys: {}", e.message);
Ok(Vec::new())
}
}
},
async {
if !keys {
return Ok::<Rows, IdeError>(Vec::new());
}
match pool.rows(&trigger_q, MAX_META_ROWS).await {
Ok(rows) => Ok(rows),
Err(e) => {
tracing::warn!("triggers: {}", e.message);
Ok(Vec::new())
}
}
},
async {
// PostgreSQL reads it with the properties above; the engines without a
// `table_properties` query ask for it here.
match sql::table_comment(driver, schema, table) {
Some(q) if sql::table_properties(driver, schema, table).is_none() => pool.rows(&q, 1).await,
_ => Ok::<Rows, IdeError>(Vec::new()),
}
},
async {
match sql::table_properties(driver, schema, table) {
Some(q) => catalog_rows(pool, &q).await,
None => Ok::<Rows, IdeError>(Vec::new()),
}
},
);
let mut indexes: Vec<IndexInfo> = Vec::new();
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
for r in index_rows? {
let mut it = r.into_iter();
let (Some(name), unique, Some(col)) = (it.next().flatten(), it.next().flatten(), it.next().flatten())
else {
@@ -1401,11 +1482,7 @@ impl DbManager {
}),
}
}
let fk_rows = if matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake) {
Vec::new()
} else {
pool.rows(&sql::table_foreign_keys(driver, schema, table), MAX_META_ROWS).await.unwrap_or_default()
};
let fk_rows = fk_rows?;
let mut foreign_keys = group_foreign_keys(fk_rows, &[]);
// SQLite keys that reference the primary key implicitly: look it up.
for k in foreign_keys.iter_mut().filter(|k| k.ref_columns.is_empty()) {
@@ -1418,15 +1495,7 @@ impl DbManager {
.collect();
}
foreign_keys.retain(|k| k.columns.len() == k.ref_columns.len());
let trigger_rows = if matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake) {
Vec::new()
} else {
pool.rows(&sql::triggers(driver, schema, table), MAX_META_ROWS).await.unwrap_or_else(|e| {
tracing::warn!("triggers: {}", e.message);
Vec::new()
})
};
let triggers = trigger_rows
let triggers = trigger_rows?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
@@ -1439,26 +1508,21 @@ impl DbManager {
Some(TriggerInfo { name, timing, events })
})
.collect();
let comment = match sql::table_comment(driver, schema, table) {
Some(q) => pool.rows(&q, 1).await.map_or_else(
|e| {
tracing::warn!("table comment: {}", e.message);
None
},
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
),
None => None,
};
let comment = comment_rows.map_or_else(
|e| {
tracing::warn!("table comment: {}", e.message);
None
},
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
);
let mut details = TableDetails { comment, columns, indexes, foreign_keys, triggers, ..Default::default() };
if let Some(q) = sql::table_properties(driver, schema, table) {
match catalog_rows(pool, &q).await {
Ok(rows) => {
if let Some(row) = rows.into_iter().next() {
read_table_properties(&mut details, row);
}
match property_rows {
Ok(rows) => {
if let Some(row) = rows.into_iter().next() {
read_table_properties(&mut details, row);
}
Err(e) => tracing::warn!("table properties: {}", e.message),
}
Err(e) => tracing::warn!("table properties: {}", e.message),
}
Ok(details)
}
@@ -1669,16 +1733,16 @@ impl DbManager {
ddl.map(|d| format!("{};\n", d.trim_end().trim_end_matches(';'))).ok_or_else(missing)
}
DbDriver::Postgres => {
let rel = pool.rows(&sql::postgres_relation(schema, name), 1).await?.into_iter().next();
let (oid, kind, owner, comment) = match rel.as_deref() {
Some([Some(oid), Some(kind), owner, comment]) => (
oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?,
kind.clone(),
owner.clone(),
comment.clone(),
),
_ => return Err(missing()),
// Everything the script needs depends on the relation oid, so read that first and
// then the rest at once — five queries in flight against a pool of four, so one
// waits, but that is still two round trips instead of six.
let rel = catalog_rows(&pool, &sql::postgres_relation(schema, name)).await?.into_iter().next();
let Some([Some(oid), Some(kind), owner, comment, persistence, partition_key, parent @ ..]) =
rel.as_deref()
else {
return Err(missing());
};
let oid = oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?;
if kind == "v" || kind == "m" {
let def = cells(pool.rows(&format!("SELECT pg_get_viewdef({oid}, true)"), 1).await?, 0);
let what = if kind == "m" { "materialized view" } else { "view" };
@@ -1686,43 +1750,70 @@ impl DbManager {
let target = sql::qualified(driver, schema, name);
return Ok(format!("create {what} {target} as\n{};\n", body.trim_end().trim_end_matches(';')));
}
let columns = pool
.rows(&sql::postgres_ddl_columns(oid), MAX_META_ROWS)
.await?
let partition = match parent {
[Some(parent_schema), Some(parent_table), Some(bound)] => Some(sql::DdlPartition {
parent_schema: parent_schema.clone(),
parent_table: parent_table.clone(),
bound: bound.clone(),
}),
_ => None,
};
let is_partition = partition.is_some();
let (cols_q, keys_q, grants_q, index_q, trigger_q) = (
sql::postgres_ddl_columns(oid, is_partition),
sql::postgres_ddl_constraints(oid, is_partition),
sql::postgres_ddl_grants(oid),
sql::postgres_ddl_indexes(oid, is_partition),
sql::postgres_ddl_triggers(oid, is_partition),
);
let (col_rows, key_rows, grant_rows, index_rows, trigger_rows) = futures::join!(
catalog_rows(&pool, &cols_q),
pool.rows(&keys_q, MAX_META_ROWS),
pool.rows(&grants_q, MAX_META_ROWS),
pool.rows(&index_q, MAX_META_ROWS),
catalog_rows(&pool, &trigger_q),
);
let columns = col_rows?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
Some(sql::DdlColumn {
name: it.next().flatten()?,
data_type: it.next().flatten().unwrap_or_default(),
not_null: flag(&it.next().flatten()),
default: it.next().flatten(),
comment: it.next().flatten(),
})
let name = it.next().flatten()?;
let data_type = it.next().flatten()?;
let not_null = flag(&it.next().flatten());
let expression = it.next().flatten();
let comment = it.next().flatten().filter(|c| !c.is_empty());
let identity = it.next().flatten();
let generated = it.next().flatten();
let value =
sql::DdlColumnValue::from_catalog(identity.as_deref(), generated.as_deref(), expression);
Some(sql::DdlColumn { name, data_type, not_null, value, comment })
})
.collect::<Vec<_>>();
let constraints = pool
.rows(&sql::postgres_ddl_constraints(oid), MAX_META_ROWS)
.await?
let constraints = key_rows?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
Some((it.next().flatten()?, it.next().flatten()?))
})
.collect::<Vec<_>>();
let indexes = cells(pool.rows(&sql::postgres_ddl_indexes(oid), MAX_META_ROWS).await?, 0);
let grants = pool
.rows(&sql::postgres_ddl_grants(oid), MAX_META_ROWS)
.await?
let indexes =
index_rows?.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect::<Vec<_>>();
let grants = grant_rows?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
Some((it.next().flatten()?, it.next().flatten()?, flag(&it.next().flatten())))
})
.collect();
let triggers = cells(pool.rows(&sql::postgres_ddl_triggers(oid), MAX_META_ROWS).await?, 0);
let extras = sql::DdlExtras { comment, owner, grants, triggers };
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &extras))
.collect::<Vec<_>>();
let triggers =
trigger_rows?.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect::<Vec<_>>();
let options = sql::DdlTableOptions {
unlogged: persistence.as_deref() == Some("u"),
partition_key: partition_key.clone(),
partition,
};
let extras = sql::DdlExtras { comment: comment.clone(), owner: owner.clone(), grants, triggers };
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &options, &extras))
}
}
}
+11
Переглянути файл
@@ -165,6 +165,17 @@ impl DbManager {
.collect()
}
/// Snapshot an existing connection without allocating a slot or opening a route.
pub(super) fn connected_pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
self.pools
.lock()
.get(id)
.and_then(|slot| slot.value.get())
.filter(|connection| !connection.is_closed())
.map(|connection| connection.pool.clone())
.ok_or_else(|| IdeError::invalid("Connect the data source in the Database tool window first"))
}
pub async fn pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
Ok(self.connection(id).await?.pool)
}
+224 -24
Переглянути файл
@@ -249,7 +249,7 @@ pub fn table_properties(driver: DbDriver, schema: &str, table: &str) -> Option<S
JOIN pg_tablespace dt ON dt.oid = d.dattablespace WHERE d.datname = current_database())), \
am.amname, array_to_string(array_cat(c.reloptions, \
(SELECT array_agg('toast.' || o) FROM unnest(tc.reloptions) o)), chr(10)), \
pg_get_partkeydef(c.oid), c.relpersistence \
pg_get_partkeydef(c.oid), c.relpersistence, obj_description(c.oid, 'pg_class') \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
LEFT JOIN pg_class tc ON tc.oid = c.reltoastrelid \
LEFT JOIN pg_tablespace ts ON ts.oid = c.reltablespace LEFT JOIN pg_am am ON am.oid = c.relam \
@@ -697,40 +697,70 @@ pub fn sqlite_ddl(schema: &str, name: &str) -> String {
)
}
/// Rows: `oid, relkind, owner, comment` of a PostgreSQL relation.
/// Rows: `oid, relkind, owner, comment, persistence, partition key, parent schema, parent name, bound`.
pub fn postgres_relation(schema: &str, name: &str) -> String {
format!(
"SELECT c.oid::text, c.relkind::text, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class') \
"SELECT c.oid::text, c.relkind::text, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class'), \
c.relpersistence::text, pg_get_partkeydef(c.oid), pn.nspname, p.relname, pg_get_expr(c.relpartbound, c.oid) \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
LEFT JOIN pg_inherits i ON i.inhrelid = c.oid AND c.relispartition \
LEFT JOIN pg_class p ON p.oid = i.inhparent LEFT JOIN pg_namespace pn ON pn.oid = p.relnamespace \
WHERE n.nspname = {} AND c.relname = {}",
quote_literal(DbDriver::Postgres, schema),
quote_literal(DbDriver::Postgres, name)
)
}
/// Rows: `name, type, not null (0/1), default, comment` of relation `oid`.
pub fn postgres_ddl_columns(oid: u32) -> String {
/// Rows: `name, type, not null (0/1), expression, comment, identity, generated` of relation `oid`.
/// On a partition, the not-null flag and expression describe overrides of the parent column.
///
/// Read from `pg_attribute` with `format_type` rather than from `information_schema.columns`:
/// that view reports `character varying` without the length, `numeric` without the precision,
/// `ARRAY` for every array and `USER-DEFINED` for an enum, so a script built from it would not
/// recreate the table. It also lists only the columns the current role holds privileges on.
pub fn postgres_ddl_columns(oid: u32, partition: bool) -> String {
// Generated clauses add their own parentheses. Keep the original deparser style for defaults.
let pretty = "(a.attgenerated::text = 's') IS TRUE";
let expression = format!("pg_get_expr(d.adbin, d.adrelid, {pretty})");
let (not_null, expression, identity, parent_join) = if partition {
let parent_expression = format!("pg_get_expr(pd.adbin, pd.adrelid, {pretty})");
(
"a.attnotnull AND NOT pa.attnotnull",
format!(
"CASE WHEN {expression} IS DISTINCT FROM {parent_expression} THEN COALESCE({expression}, 'NULL') END"
),
"NULL",
"JOIN pg_inherits i ON i.inhrelid = a.attrelid \
JOIN pg_attribute pa ON pa.attrelid = i.inhparent AND pa.attname = a.attname AND NOT pa.attisdropped \
LEFT JOIN pg_attrdef pd ON pd.adrelid = pa.attrelid AND pd.adnum = pa.attnum",
)
} else {
("a.attnotnull", expression, "a.attidentity::text", "")
};
format!(
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 1 ELSE 0 END, \
pg_get_expr(d.adbin, d.adrelid), col_description(a.attrelid, a.attnum) FROM pg_attribute a \
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum \
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN {not_null} THEN 1 ELSE 0 END, \
{expression}, col_description(a.attrelid, a.attnum), {identity}, a.attgenerated::text FROM pg_attribute a \
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum {parent_join} \
WHERE a.attrelid = {oid} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum"
)
}
/// Rows: `name, definition` of the constraints of relation `oid` (primary key first).
pub fn postgres_ddl_constraints(oid: u32) -> String {
pub fn postgres_ddl_constraints(oid: u32, partition: bool) -> String {
let local = if partition { " AND conislocal AND coninhcount = 0" } else { "" };
format!(
"SELECT conname, pg_get_constraintdef(oid, true) FROM pg_constraint WHERE conrelid = {oid} \
"SELECT conname, pg_get_constraintdef(oid, true) FROM pg_constraint WHERE conrelid = {oid}{local} \
ORDER BY CASE contype WHEN 'p' THEN 0 WHEN 'u' THEN 1 WHEN 'c' THEN 2 WHEN 'f' THEN 3 ELSE 4 END, conname"
)
}
/// Rows: `CREATE INDEX …` of relation `oid`, except the indexes behind constraints.
pub fn postgres_ddl_indexes(oid: u32) -> String {
pub fn postgres_ddl_indexes(oid: u32, partition: bool) -> String {
let local =
if partition { " AND NOT EXISTS (SELECT 1 FROM pg_inherits WHERE inhrelid = i.indexrelid)" } else { "" };
format!(
"SELECT pg_get_indexdef(i.indexrelid) FROM pg_index i WHERE i.indrelid = {oid} \
AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = i.indexrelid AND c.conrelid = i.indrelid) \
AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = i.indexrelid AND c.conrelid = i.indrelid){local} \
ORDER BY 1"
)
}
@@ -749,9 +779,10 @@ pub fn postgres_ddl_grants(oid: u32) -> String {
}
/// Rows: `CREATE TRIGGER …` of the user triggers of relation `oid`.
pub fn postgres_ddl_triggers(oid: u32) -> String {
pub fn postgres_ddl_triggers(oid: u32, partition: bool) -> String {
let local = if partition { " AND tgparentid = 0" } else { "" };
format!(
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = {oid} AND NOT tgisinternal \
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger t WHERE tgrelid = {oid} AND NOT tgisinternal{local} \
ORDER BY tgname"
)
}
@@ -840,6 +871,12 @@ pub fn postgres_legacy(sql: &str) -> Option<String> {
.replace(" LEFT JOIN pg_am am ON am.oid = c.relam", "")
.replace("am.amname", "NULL")
.replace("pg_get_partkeydef(c.oid)", "NULL")
.replace("c.relispartition", "false")
.replace("pg_get_expr(c.relpartbound, c.oid)", "NULL")
// These flags entered the catalog in different releases. Keep whichever ones exist.
.replace("a.attidentity::text", "to_jsonb(a)->>'attidentity'")
.replace("a.attgenerated::text", "to_jsonb(a)->>'attgenerated'")
.replace("tgparentid = 0", "COALESCE(to_jsonb(t)->>'tgparentid', '0') = '0'")
.replace("c.relkind IN ('r', 'p')", "c.relkind = 'r'");
(legacy != sql).then_some(legacy)
}
@@ -999,10 +1036,42 @@ pub struct DdlColumn {
pub name: String,
pub data_type: String,
pub not_null: bool,
pub default: Option<String>,
pub value: Option<DdlColumnValue>,
pub comment: Option<String>,
}
pub enum DdlColumnValue {
Default(String),
IdentityByDefault,
IdentityAlways,
GeneratedStored(String),
}
impl DdlColumnValue {
pub fn from_catalog(identity: Option<&str>, generated: Option<&str>, expression: Option<String>) -> Option<Self> {
match (identity, generated) {
(Some("d"), _) => Some(Self::IdentityByDefault),
(Some("a"), _) => Some(Self::IdentityAlways),
(_, Some("s")) => expression.map(Self::GeneratedStored),
(_, None | Some("")) => expression.map(Self::Default),
_ => None,
}
}
}
#[derive(Default)]
pub struct DdlTableOptions {
pub unlogged: bool,
pub partition_key: Option<String>,
pub partition: Option<DdlPartition>,
}
pub struct DdlPartition {
pub parent_schema: String,
pub parent_table: String,
pub bound: String,
}
/// What [`postgres_table_ddl`] adds after `create table` so the script rebuilds the table.
#[derive(Default)]
pub struct DdlExtras {
@@ -1021,17 +1090,30 @@ pub fn postgres_table_ddl(
columns: &[DdlColumn],
constraints: &[(String, String)],
indexes: &[String],
options: &DdlTableOptions,
extras: &DdlExtras,
) -> String {
let d = DbDriver::Postgres;
let partition = options.partition.as_ref();
let mut items: Vec<String> = columns
.iter()
.filter(|c| partition.is_none() || c.not_null || c.value.is_some())
.map(|c| {
let mut s = format!(" {} {}", quote_ident(d, &c.name), c.data_type);
if let Some(v) = &c.default {
s.push_str(&format!(" default {v}"));
let mut s = format!(" {}", quote_ident(d, &c.name));
if partition.is_none() {
s.push(' ');
s.push_str(&c.data_type);
}
if c.not_null {
match &c.value {
Some(DdlColumnValue::Default(v)) => s.push_str(&format!(" default {v}")),
Some(DdlColumnValue::IdentityByDefault) => s.push_str(" generated by default as identity"),
Some(DdlColumnValue::IdentityAlways) => s.push_str(" generated always as identity"),
Some(DdlColumnValue::GeneratedStored(v)) => s.push_str(&format!(" generated always as ({v}) stored")),
None => {}
}
if c.not_null
&& !matches!(c.value, Some(DdlColumnValue::IdentityByDefault | DdlColumnValue::IdentityAlways))
{
s.push_str(" not null");
}
s
@@ -1039,7 +1121,35 @@ pub fn postgres_table_ddl(
.collect();
items.extend(constraints.iter().map(|(name, def)| format!(" constraint {} {def}", quote_ident(d, name))));
let target = qualified(d, schema, table);
let mut out = format!("create table {target}\n(\n{}\n);\n", items.join(",\n"));
let persistence = if options.unlogged { "unlogged " } else { "" };
let mut out = format!("create {persistence}table {target}");
if let Some(partition) = partition {
let parent = qualified(d, &partition.parent_schema, &partition.parent_table);
out.push_str(&format!(" partition of {parent}"));
}
if partition.is_none() || !items.is_empty() {
out.push_str(&format!("\n(\n{}\n)", items.join(",\n")));
}
if let Some(partition) = partition {
out.push_str("\n ");
// pg_get_expr deparses bounds as keywords and constants. Preserve quoted constants,
// including doubled quotes, while matching the casing of the generated DDL.
for (i, part) in partition.bound.split('\'').enumerate() {
if i != 0 {
out.push('\'');
}
if i % 2 == 0 {
out.push_str(&part.to_ascii_lowercase());
} else {
out.push_str(part);
}
}
}
if let Some(key) = &options.partition_key {
let (method, expression) = key.split_at(key.find(' ').unwrap_or(key.len()));
out.push_str(&format!("\n partition by {}{expression}", method.to_ascii_lowercase()));
}
out.push_str(";\n");
// The order a script runs in: comments, owner and privileges, then indexes and triggers.
if let Some(comment) = &extras.comment {
out.push_str(&format!("\ncomment on table {target} is {};\n", quote_literal(d, comment)));
@@ -1416,15 +1526,31 @@ mod tests {
assert_eq!(use_schema(DbDriver::Clickhouse, "default"), None);
}
#[test]
fn postgres_ddl_columns_reads_pg_attribute_not_information_schema() {
// `information_schema.columns.data_type` loses what a script needs to recreate the table:
// `character varying` without the length, `numeric` without the precision, `ARRAY` for
// every array and `USER-DEFINED` for an enum. It also lists only the columns the current
// role holds privileges on. The DDL must therefore read `pg_attribute` with
// `format_type(atttypid, atttypmod)`, which is what makes `varchar(255)`, `numeric(10,2)`,
// `text[]` and an enum name come out as written.
let q = postgres_ddl_columns(42, false);
assert!(q.contains("format_type(a.atttypid, a.atttypmod)"), "{q}");
assert!(q.contains("FROM pg_attribute a"), "{q}");
assert!(q.contains("left join pg_attrdef") || q.contains("LEFT JOIN pg_attrdef"), "{q}");
assert!(q.contains("attrelid = 42"), "{q}");
assert!(!q.contains("information_schema"), "{q}");
}
#[test]
fn postgres_ddl() {
let cols = [
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, value: None, comment: None },
DdlColumn {
name: "name".into(),
data_type: "character varying(40)".into(),
not_null: false,
default: Some("'x'::character varying".into()),
value: Some(DdlColumnValue::Default("'x'::character varying".into())),
comment: None,
},
];
@@ -1435,21 +1561,94 @@ mod tests {
&cols,
&[("t_pkey".into(), "PRIMARY KEY (id)".into())],
&["CREATE INDEX t_name ON public.t USING btree (name)".into()],
&DdlTableOptions::default(),
&DdlExtras::default(),
),
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"name\" character varying(40) default 'x'::character varying,\n constraint \"t_pkey\" PRIMARY KEY (id)\n);\n\nCREATE INDEX t_name ON public.t USING btree (name);\n"
);
}
#[test]
fn postgres_ddl_renders_identity_and_stored_columns() {
let columns = [
("id_default", "bigint", true, "d", "", Some("ignored()")),
("id_always", "bigint", true, "a", "", None),
("total", "integer", true, "", "s", Some("qty * price")),
]
.map(|(name, data_type, not_null, identity, generated, expression)| DdlColumn {
name: name.into(),
data_type: data_type.into(),
not_null,
value: DdlColumnValue::from_catalog(Some(identity), Some(generated), expression.map(Into::into)),
comment: None,
});
let ddl =
postgres_table_ddl("public", "t", &columns, &[], &[], &DdlTableOptions::default(), &DdlExtras::default());
assert_eq!(
ddl,
concat!(
"create table \"public\".\"t\"\n(\n",
" \"id_default\" bigint generated by default as identity,\n",
" \"id_always\" bigint generated always as identity,\n",
" \"total\" integer generated always as (qty * price) stored not null\n",
");\n",
)
);
}
#[test]
fn postgres_ddl_renders_unlogged_partitioned_parent() {
let columns =
[DdlColumn { name: "Day".into(), data_type: "date".into(), not_null: true, value: None, comment: None }];
let options =
DdlTableOptions { unlogged: true, partition_key: Some("RANGE (\"Day\")".into()), partition: None };
assert_eq!(
postgres_table_ddl("public", "events", &columns, &[], &[], &options, &DdlExtras::default()),
"create unlogged table \"public\".\"events\"\n(\n \"Day\" date not null\n)\n partition by range (\"Day\");\n"
);
}
#[test]
fn postgres_ddl_renders_partitions_and_preserves_bound_literals() {
let columns = [DdlColumn {
name: "region".into(),
data_type: "text".into(),
not_null: false,
value: None,
comment: None,
}];
for (bound, rendered) in [
("FOR VALUES FROM (MINVALUE) TO ('A) TO (B')", "for values from (minvalue) to ('A) TO (B')"),
("FOR VALUES IN ('East''s', 'SOUTH', NULL)", "for values in ('East''s', 'SOUTH', null)"),
("FOR VALUES WITH (modulus 2, remainder 0)", "for values with (modulus 2, remainder 0)"),
("DEFAULT", "default"),
] {
let options = DdlTableOptions {
partition: Some(DdlPartition {
parent_schema: "other".into(),
parent_table: "Parent\"Table".into(),
bound: bound.into(),
}),
..Default::default()
};
assert_eq!(
postgres_table_ddl("public", "child", &columns, &[], &[], &options, &DdlExtras::default()),
format!(
"create table \"public\".\"child\" partition of \"other\".\"Parent\"\"Table\"\n {rendered};\n"
)
);
}
}
#[test]
fn postgres_ddl_rebuilds_comments_owner_grants_and_triggers() {
let cols = [
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, value: None, comment: None },
DdlColumn {
name: "note".into(),
data_type: "text".into(),
not_null: false,
default: None,
value: None,
comment: Some("what's this".into()),
},
];
@@ -1468,6 +1667,7 @@ mod tests {
&cols,
&[],
&["CREATE INDEX t_note ON public.t USING btree (note)".into()],
&DdlTableOptions::default(),
&extras
),
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"note\" text\n);\n\
+23
Переглянути файл
@@ -24,6 +24,8 @@ pub enum Capability {
IdeCommands,
/// Manage only its own project database sources and write their credentials.
DatabaseSources,
/// Read table metadata of connected project sources; never rows or credentials.
DatabaseSchema,
VcsRead,
VcsWrite,
/// The Maven / Gradle dependency graph the IDE resolved.
@@ -93,6 +95,7 @@ impl Capability {
}
Self::EditorWrite
| Self::DatabaseSources
| Self::DatabaseSchema
| Self::VcsWrite
| Self::Net(_)
| Self::NetAsk
@@ -130,6 +133,7 @@ impl Capability {
Self::EditorWrite => "Change text in the editor".into(),
Self::ProjectWrite => "Create and change files in the open project".into(),
Self::DatabaseSources => "Manage its own database sources and store their passwords in trusted projects".into(),
Self::DatabaseSchema => "Read table structures of connected database sources in trusted projects, without rows or passwords".into(),
Self::IdeCommands => "Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing".into(),
Self::VcsRead => "Read version control state".into(),
Self::VcsWrite => "Change version control state (commit, fetch, checkout)".into(),
@@ -289,6 +293,7 @@ impl fmt::Display for Capability {
Self::ProjectWrite => f.write_str("project.write"),
Self::IdeCommands => f.write_str("ide.commands"),
Self::DatabaseSources => f.write_str("database.sources"),
Self::DatabaseSchema => f.write_str("database.schema"),
Self::VcsRead => f.write_str("vcs.read"),
Self::VcsWrite => f.write_str("vcs.write"),
Self::BuildRead => f.write_str("build.read"),
@@ -383,6 +388,7 @@ impl FromStr for Capability {
"project.write" => Self::ProjectWrite,
"ide.commands" => Self::IdeCommands,
"database.sources" => Self::DatabaseSources,
"database.schema" => Self::DatabaseSchema,
"vcs.read" => Self::VcsRead,
"vcs.write" => Self::VcsWrite,
"build.read" => Self::BuildRead,
@@ -677,6 +683,23 @@ mod net_setting_tests {
mod database_tests {
use super::*;
#[test]
fn database_schema_is_a_separate_medium_risk_grant_requiring_api20() {
let cap: Capability = "database.schema".parse().unwrap();
assert_eq!(cap, Capability::DatabaseSchema);
assert_eq!(cap.to_string(), "database.schema");
assert_eq!(cap.risk(), Risk::Medium);
assert!(!cap.auto_migrates());
for other in [Capability::ProjectRead, Capability::DatabaseSources] {
assert!(!other.covers(&cap));
}
for (api, valid) in [("^1.19", false), ("^1.20", true)] {
let text = format!(
"id='schema'\nname='Schema'\nversion='1.0.0'\nengines.openidea='{api}'\n[capabilities]\nrequired=['database.schema']"
);
assert_eq!(crate::Manifest::parse(&text).is_ok(), valid);
}
}
#[test]
fn database_sources_is_a_medium_risk_exact_grant_requiring_api4() {
let cap: Capability = "database.sources".parse().unwrap();
assert_eq!(cap, Capability::DatabaseSources);
+4 -1
Переглянути файл
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
pub const MANIFEST_FILE: &str = "plugin.toml";
/// The plugin API (engine) version this host implements.
pub const ENGINE_VERSION: &str = "1.19.0";
pub const ENGINE_VERSION: &str = "1.20.0";
/// The longest `[capabilities.reasons]` entry, in characters: a sentence or two.
pub const MAX_CAPABILITY_REASON: usize = 500;
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
@@ -426,6 +426,9 @@ impl Manifest {
if matches!(cap, Capability::ClipboardRead) {
self.needs_api(&format!("capability `{cap}`"), 11)?;
}
if matches!(cap, Capability::DatabaseSchema) {
self.needs_api(&format!("capability `{cap}`"), 20)?;
}
if matches!(cap, Capability::Agents) {
self.needs_api(&format!("capability `{cap}`"), 18)?;
}
+1
Переглянути файл
@@ -28,6 +28,7 @@ ide-syntax.workspace = true
ide-search.workspace = true
ide-lsp.workspace = true
ide-vcs.workspace = true
ide-svn.workspace = true
ide-github.workspace = true
ide-dap.workspace = true
ide-heap.workspace = true
+18
Переглянути файл
@@ -111,6 +111,24 @@ impl AgentSecrets {
}
}
impl ide_agent::EnvSecrets for AgentSecrets {
fn get(&self, key: &str) -> Option<String> {
AgentSecrets::get(self, key)
}
fn set(&self, key: &str, value: &str) -> IdeResult<()> {
AgentSecrets::set(self, key, value).map(|_| ())
}
fn delete(&self, key: &str) {
AgentSecrets::delete(self, key);
}
fn keys(&self, prefix: &str) -> Vec<String> {
AgentSecrets::keys(self, prefix)
}
}
#[cfg(test)]
mod tests {
use super::*;
+775
Переглянути файл
@@ -0,0 +1,775 @@
//! Per-user OS login / boot service registration for `openidea-server --scheduler`
//! (or `<desktop-exe> --scheduler`).
//!
//! Off by default (`agents.automations.autoStartService = false`). When the user enables it
//! and at least one scheduled automation is active, registers the user login service; when
//! disabled or when zero scheduled automations remain (after any in-flight claimed runs finish),
//! stops and unregisters the service.
use ide_core::{IdeError, IdeResult, IpcPath};
use parking_lot::{Mutex, RwLock};
use std::path::{Path, PathBuf};
use std::sync::Arc;
pub const SERVICE_LABEL: &str = "ai.l0ng.openidea.scheduler";
pub const SYSTEMD_UNIT_NAME: &str = "openidea-scheduler.service";
const WINDOWS_SCRIPT_NAME: &str = "openidea-scheduler.cmd";
const OVERRIDE_ENV: &str = "OPENIDEA_BOOT_SERVICE_DIR";
const DISABLE_OS_CALLS_ENV: &str = "OPENIDEA_DISABLE_OS_SERVICE_CALLS";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ServicePlatform {
Macos,
Linux,
Windows,
Other,
}
impl ServicePlatform {
pub fn host() -> Self {
if cfg!(target_os = "macos") {
Self::Macos
} else if cfg!(target_os = "linux") {
Self::Linux
} else if cfg!(target_os = "windows") {
Self::Windows
} else {
Self::Other
}
}
}
pub type CommandRunner = Arc<dyn Fn(&str, &[&str]) -> std::io::Result<(i32, String, String)> + Send + Sync>;
#[derive(Default)]
pub struct BootServiceManager {
sync_lock: Mutex<()>,
override_dir: RwLock<Option<PathBuf>>,
executable_override: RwLock<Option<PathBuf>>,
platform_override: RwLock<Option<ServicePlatform>>,
command_runner: RwLock<Option<CommandRunner>>,
last_error: Mutex<Option<String>>,
}
#[derive(Clone, Debug)]
pub struct BootServiceState {
pub kind: String,
pub registered: bool,
pub path: Option<IpcPath>,
pub error: Option<String>,
pub linux_linger_enabled: Option<bool>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum OsServicePresence {
RegisteredAndActive,
RegisteredIdle,
ActiveUnregistered,
Absent,
}
impl OsServicePresence {
fn is_registered(self) -> bool {
matches!(self, Self::RegisteredAndActive | Self::RegisteredIdle)
}
fn is_loaded_or_active(self) -> bool {
!matches!(self, Self::Absent)
}
}
impl BootServiceManager {
pub fn with_override_dir(dir: Option<PathBuf>) -> Self {
Self {
sync_lock: Mutex::new(()),
override_dir: RwLock::new(dir),
executable_override: RwLock::new(None),
platform_override: RwLock::new(None),
command_runner: RwLock::new(None),
last_error: Mutex::new(None),
}
}
pub fn set_override_dir(&self, dir: Option<PathBuf>) {
*self.override_dir.write() = dir;
}
pub fn set_executable_override(&self, exe: Option<PathBuf>) {
*self.executable_override.write() = exe;
}
pub fn set_command_runner_for_test(&self, platform: ServicePlatform, runner: Option<CommandRunner>) {
*self.platform_override.write() = runner.as_ref().map(|_| platform);
*self.command_runner.write() = runner;
}
fn effective_platform(&self) -> ServicePlatform {
self.platform_override.read().unwrap_or_else(ServicePlatform::host)
}
fn effective_override_dir(&self) -> Option<PathBuf> {
self.override_dir
.read()
.clone()
.or_else(|| std::env::var_os(OVERRIDE_ENV).filter(|v| !v.is_empty()).map(PathBuf::from))
}
fn uses_os_commands(&self) -> bool {
if self.command_runner.read().is_some() {
return true;
}
self.effective_override_dir().is_none() && std::env::var_os(DISABLE_OS_CALLS_ENV).is_none_or(|v| v != "1")
}
fn run_command(&self, program: &str, args: &[&str]) -> IdeResult<(i32, String, String)> {
if let Some(runner) = self.command_runner.read().clone() {
return runner(program, args).map_err(|e| IdeError::internal(format!("{program} failed to spawn: {e}")));
}
let out = std::process::Command::new(program)
.args(args)
.output()
.map_err(|e| IdeError::internal(format!("{program} failed to spawn: {e}")))?;
let code = out.status.code().unwrap_or(-1);
let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
Ok((code, stdout, stderr))
}
fn run_checked(&self, program: &str, args: &[&str]) -> IdeResult<String> {
let (code, stdout, stderr) = self.run_command(program, args)?;
if code == 0 {
return Ok(stdout);
}
let detail = stderr.trim();
let msg = if detail.is_empty() { stdout.trim() } else { detail };
Err(IdeError::internal(format!("{program} {} exited with {code}: {msg}", args.join(" "))))
}
fn scheduler_executable(&self) -> Option<PathBuf> {
self.executable_override.read().clone().or_else(|| std::env::current_exe().ok())
}
pub fn service_kind_for(platform: ServicePlatform, remote: bool) -> &'static str {
if remote && platform == ServicePlatform::Linux {
"systemdUser"
} else {
match platform {
ServicePlatform::Macos => "launchAgent",
ServicePlatform::Linux => "systemdUser",
ServicePlatform::Windows => "windowsStartup",
ServicePlatform::Other => "backgroundHost",
}
}
}
pub fn service_kind(remote: bool) -> &'static str {
Self::service_kind_for(ServicePlatform::host(), remote)
}
pub fn service_file_path(&self, home_dir: Option<&Path>) -> Option<PathBuf> {
let platform = self.effective_platform();
if let Some(dir) = self.effective_override_dir() {
let filename = match platform {
ServicePlatform::Macos => format!("{SERVICE_LABEL}.plist"),
ServicePlatform::Windows => WINDOWS_SCRIPT_NAME.to_owned(),
ServicePlatform::Linux | ServicePlatform::Other => SYSTEMD_UNIT_NAME.to_owned(),
};
return Some(dir.join(filename));
}
let home = home_dir?;
match platform {
ServicePlatform::Macos => {
Some(home.join("Library").join("LaunchAgents").join(format!("{SERVICE_LABEL}.plist")))
}
ServicePlatform::Linux => Some(home.join(".config").join("systemd").join("user").join(SYSTEMD_UNIT_NAME)),
ServicePlatform::Windows => {
let appdata = std::env::var_os("APPDATA")
.map(PathBuf::from)
.unwrap_or_else(|| home.join("AppData").join("Roaming"));
Some(
appdata
.join("Microsoft")
.join("Windows")
.join("Start Menu")
.join("Programs")
.join("Startup")
.join(WINDOWS_SCRIPT_NAME),
)
}
ServicePlatform::Other => None,
}
}
fn macos_domain() -> String {
#[cfg(target_os = "macos")]
{
format!("gui/{}", rustix::process::getuid().as_raw())
}
#[cfg(not(target_os = "macos"))]
{
"gui/501".to_owned()
}
}
/// Queries the OS service manager, distinguishing confirmed `Absent` from `Err(...)` (unknown
/// status, e.g. D-Bus / launchd unreachable) so `sync(..., false)` never deletes the service
/// file when status cannot be determined.
fn query_os_presence(&self, platform: ServicePlatform) -> IdeResult<OsServicePresence> {
if !self.uses_os_commands() {
return Ok(OsServicePresence::Absent);
}
match platform {
ServicePlatform::Macos => {
let job = format!("{}/{SERVICE_LABEL}", Self::macos_domain());
let (code, stdout, stderr) = self.run_command("launchctl", &["print", &job])?;
if code == 0 {
return Ok(OsServicePresence::RegisteredAndActive);
}
let combined = format!("{stdout}\n{stderr}");
if code == 113 || combined.contains("Could not find service") {
return Ok(OsServicePresence::Absent);
}
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
Err(IdeError::internal(format!("launchctl print {job} returned unknown status {code}: {detail}")))
}
ServicePlatform::Linux => {
let (en_code, en_out, en_err) =
self.run_command("systemctl", &["--user", "is-enabled", SYSTEMD_UNIT_NAME])?;
let en_state = en_out.trim();
let enabled = if en_code == 0 && matches!(en_state, "enabled" | "enabled-runtime") {
true
} else if matches!(
en_state,
"disabled" | "not-found" | "static" | "indirect" | "masked" | "linked" | "generated"
) {
false
} else {
let detail = if en_err.trim().is_empty() { en_state } else { en_err.trim() };
return Err(IdeError::internal(format!(
"systemctl --user is-enabled {SYSTEMD_UNIT_NAME} returned unknown status {en_code}: {detail}"
)));
};
let (ac_code, ac_out, ac_err) =
self.run_command("systemctl", &["--user", "is-active", SYSTEMD_UNIT_NAME])?;
let ac_state = ac_out.trim();
let active = if ac_code == 0 && matches!(ac_state, "active" | "activating" | "reloading") {
true
} else if matches!(ac_state, "inactive" | "failed" | "deactivating") {
false
} else {
let detail = if ac_err.trim().is_empty() { ac_state } else { ac_err.trim() };
return Err(IdeError::internal(format!(
"systemctl --user is-active {SYSTEMD_UNIT_NAME} returned unknown status {ac_code}: {detail}"
)));
};
Ok(match (enabled, active) {
(true, true) => OsServicePresence::RegisteredAndActive,
(true, false) => OsServicePresence::RegisteredIdle,
(false, true) => OsServicePresence::ActiveUnregistered,
(false, false) => OsServicePresence::Absent,
})
}
ServicePlatform::Windows | ServicePlatform::Other => Ok(OsServicePresence::Absent),
}
}
fn is_os_registered(&self, platform: ServicePlatform, path: &Path) -> bool {
if !path.is_file() {
return false;
}
if !self.uses_os_commands() {
return true;
}
match platform {
ServicePlatform::Macos | ServicePlatform::Linux => {
self.query_os_presence(platform).is_ok_and(OsServicePresence::is_registered)
}
ServicePlatform::Windows => std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() > 0),
ServicePlatform::Other => false,
}
}
pub fn status(&self, home_dir: Option<&Path>, remote: bool) -> BootServiceState {
let platform = self.effective_platform();
let path = self.service_file_path(home_dir);
let registered = path.as_ref().is_some_and(|p| self.is_os_registered(platform, p));
let linux_linger_enabled = if platform == ServicePlatform::Linux { Some(check_linux_linger()) } else { None };
BootServiceState {
kind: Self::service_kind_for(platform, remote).to_owned(),
registered,
path: path.map(IpcPath),
error: self.last_error.lock().clone(),
linux_linger_enabled,
}
}
/// Synchronizes the OS user service file and service manager state to match
/// `(should_register, base_dir)`. Checks command results, retries activation even when the
/// unit/plist file on disk is unchanged, and stops + unloads the worker BEFORE deleting the
/// unit/plist file (keeping the file when status is unknown) so failed unregistrations retry.
pub fn sync(&self, home_dir: Option<&Path>, base_dir: &Path, should_register: bool) -> IdeResult<BootServiceState> {
let _guard = self.sync_lock.lock();
let result = self.sync_locked(home_dir, base_dir, should_register);
match &result {
Ok(_) => *self.last_error.lock() = None,
Err(err) => *self.last_error.lock() = Some(err.to_string()),
}
result
}
fn sync_locked(
&self,
home_dir: Option<&Path>,
base_dir: &Path,
should_register: bool,
) -> IdeResult<BootServiceState> {
let platform = self.effective_platform();
let Some(target) = self.service_file_path(home_dir) else {
return Ok(self.status(home_dir, false));
};
let use_os = self.uses_os_commands();
if should_register {
let exe = self
.scheduler_executable()
.ok_or_else(|| IdeError::unavailable("cannot locate OpenIDEA executable for --scheduler"))?;
let content = render_service_file_for(platform, &exe, base_dir)?;
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent)?;
}
let file_changed = std::fs::read_to_string(&target).ok().as_deref() != Some(content.as_str());
if file_changed {
ide_vfs::write_atomic(&target, content.as_bytes())?;
}
if use_os {
let already_registered = self.is_os_registered(platform, &target);
if file_changed || !already_registered {
self.activate_os_service(platform, &target)?;
}
}
} else {
if use_os {
// Propagate unknown status BEFORE touching `target` so the file stays for retry!
let presence = self.query_os_presence(platform)?;
if presence.is_loaded_or_active() || target.exists() {
self.deactivate_os_service(platform, presence)?;
}
}
if target.exists() {
match std::fs::remove_file(&target) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
}
}
Ok(BootServiceState {
kind: Self::service_kind_for(platform, false).to_owned(),
registered: self.is_os_registered(platform, &target),
path: Some(IpcPath(target)),
error: None,
linux_linger_enabled: if platform == ServicePlatform::Linux { Some(check_linux_linger()) } else { None },
})
}
fn activate_os_service(&self, platform: ServicePlatform, path: &Path) -> IdeResult<()> {
let path_str = path
.to_str()
.ok_or_else(|| IdeError::invalid(format!("service file path is not valid UTF-8: {}", path.display())))?;
match platform {
ServicePlatform::Macos => {
let domain = Self::macos_domain();
let job = format!("{domain}/{SERVICE_LABEL}");
if self.query_os_presence(platform).is_ok_and(OsServicePresence::is_loaded_or_active) {
let _ = self.run_command("launchctl", &["bootout", &job]);
}
self.run_checked("launchctl", &["bootstrap", &domain, path_str])?;
Ok(())
}
ServicePlatform::Linux => {
self.run_checked("systemctl", &["--user", "daemon-reload"])?;
self.run_checked("systemctl", &["--user", "enable", SYSTEMD_UNIT_NAME])?;
Ok(())
}
ServicePlatform::Windows | ServicePlatform::Other => Ok(()),
}
}
fn deactivate_os_service(&self, platform: ServicePlatform, presence: OsServicePresence) -> IdeResult<()> {
match platform {
ServicePlatform::Macos => {
let domain = Self::macos_domain();
let job = format!("{domain}/{SERVICE_LABEL}");
if presence.is_loaded_or_active() {
let (code, stdout, stderr) = self.run_command("launchctl", &["bootout", &job])?;
let after = self.query_os_presence(platform)?;
if code != 0 && after.is_loaded_or_active() {
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
return Err(IdeError::internal(format!(
"launchctl bootout {job} exited with {code}: {detail}"
)));
}
}
Ok(())
}
ServicePlatform::Linux => {
match presence {
OsServicePresence::RegisteredAndActive | OsServicePresence::RegisteredIdle => {
self.run_checked("systemctl", &["--user", "disable", "--now", SYSTEMD_UNIT_NAME])?;
}
OsServicePresence::ActiveUnregistered => {
self.run_checked("systemctl", &["--user", "stop", SYSTEMD_UNIT_NAME])?;
}
OsServicePresence::Absent => {}
}
self.run_checked("systemctl", &["--user", "daemon-reload"])?;
Ok(())
}
ServicePlatform::Windows | ServicePlatform::Other => Ok(()),
}
}
}
pub fn render_service_file(exe: &Path, base_dir: &Path) -> IdeResult<String> {
render_service_file_for(ServicePlatform::host(), exe, base_dir)
}
pub fn render_service_file_for(platform: ServicePlatform, exe: &Path, base_dir: &Path) -> IdeResult<String> {
match platform {
ServicePlatform::Macos => render_macos_plist(exe, base_dir),
ServicePlatform::Windows => render_windows_cmd(exe, base_dir),
ServicePlatform::Linux | ServicePlatform::Other => render_systemd_unit(exe, base_dir),
}
}
fn validate_roundtrip_path<'a>(path: &'a Path, label: &str) -> IdeResult<&'a str> {
let s = path.to_str().ok_or_else(|| IdeError::invalid(format!("{label} path is not valid UTF-8")))?;
if s.is_empty() {
return Err(IdeError::invalid(format!("{label} path cannot be empty")));
}
let has_root = path.is_absolute() || s.starts_with('/') || (s.len() >= 3 && s.as_bytes()[1] == b':');
if !has_root {
return Err(IdeError::invalid(format!("{label} path must be absolute: {s}")));
}
if s.chars().any(char::is_control) {
return Err(IdeError::invalid(format!(
"{label} path contains control characters or line breaks that cannot round-trip in a service file"
)));
}
Ok(s)
}
pub fn render_macos_plist(exe: &Path, base_dir: &Path) -> IdeResult<String> {
let exe_str = validate_roundtrip_path(exe, "scheduler executable")?;
let home_str = validate_roundtrip_path(base_dir, "scheduler data")?;
let log_path = base_dir.join("logs").join("scheduler.log");
let log_str = validate_roundtrip_path(&log_path, "scheduler log")?;
let exe_esc = xml_escape(exe_str);
let home_esc = xml_escape(home_str);
let log_esc = xml_escape(log_str);
Ok(format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>{SERVICE_LABEL}</string>
<key>AssociatedBundleIdentifiers</key>
<array>
<string>ai.l0ng.openidea</string>
</array>
<key>LimitLoadToSessionType</key>
<string>Aqua</string>
<key>ProgramArguments</key>
<array>
<string>{exe_esc}</string>
<string>--scheduler</string>
</array>
<key>EnvironmentVariables</key>
<dict>
<key>OPENIDEA_SERVER_HOME</key>
<string>{home_esc}</string>
</dict>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>{log_esc}</string>
</dict>
</plist>
"#
))
}
pub fn render_systemd_unit(exe: &Path, base_dir: &Path) -> IdeResult<String> {
let exe_raw = validate_roundtrip_path(exe, "scheduler executable")?;
let home_raw = validate_roundtrip_path(base_dir, "scheduler data")?;
// Both `Environment=` and the executable path (`argv[0]`) of `ExecStart=` are resolved before
// `$` variable expansion (`systemd.exec(5)`, `systemd.service(5)`), so `$` stays literal!
let exe_str = systemd_escape_literal_quoted(exe_raw);
let home_str = systemd_escape_literal_quoted(home_raw);
Ok(format!(
"[Unit]\n\
Description=OpenIDEA Headless Agent Automation Scheduler\n\
After=network-online.target\n\
\n\
[Service]\n\
Type=simple\n\
Environment=\"OPENIDEA_SERVER_HOME={home_str}\"\n\
ExecStart=\"{exe_str}\" --scheduler\n\
Restart=on-failure\n\
RestartSec=10\n\
\n\
[Install]\n\
WantedBy=default.target\n"
))
}
pub fn render_windows_cmd(exe: &Path, base_dir: &Path) -> IdeResult<String> {
let exe_raw = validate_roundtrip_path(exe, "scheduler executable")?;
let home_raw = validate_roundtrip_path(base_dir, "scheduler data")?;
if exe_raw.contains('"') || home_raw.contains('"') {
return Err(IdeError::invalid("Windows Startup script path cannot contain '\"'"));
}
let home_esc = cmd_escape(home_raw);
let exe_esc = cmd_escape(exe_raw);
Ok(format!("@echo off\r\nset \"OPENIDEA_SERVER_HOME={home_esc}\"\r\nstart \"\" /B \"{exe_esc}\" --scheduler\r\n"))
}
/// Escapes a double-quoted systemd value where `$` is literal (`Environment="KEY=VALUE"` and
/// `ExecStart="EXECUTABLE"` `argv[0]`): specifiers (`%` -> `%%`) and C escapes (`\` -> `\\`,
/// `"` -> `\"`) are interpreted, while `$` must remain literal.
fn systemd_escape_literal_quoted(s: &str) -> String {
s.replace('\\', "\\\\").replace('"', "\\\"").replace('%', "%%")
}
fn cmd_escape(s: &str) -> String {
s.replace('%', "%%")
}
fn xml_escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;").replace('\'', "&apos;")
}
fn check_linux_linger() -> bool {
if let Ok(user) = std::env::var("USER").or_else(|_| std::env::var("LOGNAME"))
&& !user.is_empty()
&& Path::new("/var/lib/systemd/linger").join(user).exists()
{
return true;
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
fn unescape_systemd_quoted(s: &str, expand_dollars: bool) -> String {
let after_specifiers = s.replace("%%", "%");
let after_dollars = if expand_dollars { after_specifiers.replace("$$", "$") } else { after_specifiers };
let mut out = String::new();
let mut chars = after_dollars.chars();
while let Some(c) = chars.next() {
if c == '\\' {
if let Some(next) = chars.next() {
out.push(next);
}
} else {
out.push(c);
}
}
out
}
#[test]
fn systemd_unit_encodes_environment_and_exec_start_with_distinct_rules_and_rejects_bad_paths() {
let exe = Path::new("/opt/openidea$bin/with \"quotes\"\\slash/open%idea");
let home = Path::new("/home/dev&co/100%data$dir/\"sub\"\\path");
let plist = render_macos_plist(exe, home).unwrap();
assert!(plist.contains("dev&amp;co"));
let unit = render_systemd_unit(exe, home).unwrap();
let env_line = unit.lines().find(|l| l.starts_with("Environment=")).unwrap();
let exec_line = unit.lines().find(|l| l.starts_with("ExecStart=")).unwrap();
// Both Environment= and ExecStart= argv[0] keep `$` literal while escaping `\`, `"`, and `%`.
assert!(env_line.contains("100%%data$dir"));
assert!(!env_line.contains("data$$dir"));
let env_inner =
env_line.strip_prefix("Environment=\"OPENIDEA_SERVER_HOME=").unwrap().strip_suffix('"').unwrap();
assert_eq!(unescape_systemd_quoted(env_inner, false), home.to_str().unwrap());
assert!(exec_line.contains("openidea$bin"));
assert!(!exec_line.contains("openidea$$bin"));
assert!(exec_line.contains("open%%idea"));
let exec_inner = exec_line.strip_prefix("ExecStart=\"").unwrap().strip_suffix("\" --scheduler").unwrap();
assert_eq!(unescape_systemd_quoted(exec_inner, false), exe.to_str().unwrap());
// Windows .cmd rejects embedded quotes and round-trips `%` and `$`.
assert!(render_windows_cmd(exe, home).is_err());
let win_ok = render_windows_cmd(
Path::new(r"C:\Program Files\OpenIDEA\open%idea$1.exe"),
Path::new(r"C:\Users\dev&co\100%data$dir"),
)
.unwrap();
assert!(win_ok.contains("100%%data$dir"));
assert!(win_ok.contains("open%%idea$1.exe"));
// Line breaks, NULs, and relative paths are rejected across all platforms.
assert!(render_systemd_unit(Path::new("/opt/openidea\nExecStart=/bin/sh"), home).is_err());
assert!(render_systemd_unit(exe, Path::new("/home/user\r\nBad=1")).is_err());
assert!(render_systemd_unit(Path::new("relative/openidea"), home).is_err());
assert!(render_macos_plist(Path::new("/Applications/OpenIDEA\nBad"), home).is_err());
}
#[cfg(unix)]
#[test]
fn systemd_unit_rejects_non_utf8_paths() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let bad = Path::new(OsStr::from_bytes(b"/tmp/openidea-\xff"));
assert!(render_systemd_unit(bad, Path::new("/tmp/home")).is_err());
}
#[test]
fn boot_service_checks_real_registration_retries_unchanged_file_and_stops_on_disable() {
let tmp = tempfile::tempdir().unwrap();
let mgr = BootServiceManager::with_override_dir(Some(tmp.path().join("units")));
mgr.set_executable_override(Some(PathBuf::from("/usr/local/bin/openidea-server")));
let enabled = Arc::new(AtomicBool::new(false));
let active = Arc::new(AtomicBool::new(false));
let fail_next_enable = Arc::new(AtomicBool::new(true));
let fail_next_disable = Arc::new(AtomicBool::new(true));
let disable_now_calls = Arc::new(AtomicUsize::new(0));
let enabled_c = enabled.clone();
let active_c = active.clone();
let fail_en_c = fail_next_enable.clone();
let fail_dis_c = fail_next_disable.clone();
let dis_calls_c = disable_now_calls.clone();
mgr.set_command_runner_for_test(
ServicePlatform::Linux,
Some(Arc::new(move |prog, args| {
assert_eq!(prog, "systemctl");
match args {
["--user", "is-enabled", u] if *u == SYSTEMD_UNIT_NAME => {
if enabled_c.load(Ordering::Acquire) {
Ok((0, "enabled\n".into(), String::new()))
} else {
Ok((1, "disabled\n".into(), String::new()))
}
}
["--user", "is-active", u] if *u == SYSTEMD_UNIT_NAME => {
if active_c.load(Ordering::Acquire) {
Ok((0, "active\n".into(), String::new()))
} else {
Ok((3, "inactive\n".into(), String::new()))
}
}
["--user", "daemon-reload"] => Ok((0, String::new(), String::new())),
["--user", "enable", u] if *u == SYSTEMD_UNIT_NAME => {
if fail_en_c.swap(false, Ordering::AcqRel) {
Ok((1, String::new(), "dbus unavailable".into()))
} else {
enabled_c.store(true, Ordering::Release);
active_c.store(true, Ordering::Release);
Ok((0, String::new(), String::new()))
}
}
["--user", "disable", "--now", u] if *u == SYSTEMD_UNIT_NAME => {
dis_calls_c.fetch_add(1, Ordering::AcqRel);
if fail_dis_c.swap(false, Ordering::AcqRel) {
Ok((1, String::new(), "unit busy".into()))
} else {
enabled_c.store(false, Ordering::Release);
active_c.store(false, Ordering::Release);
Ok((0, String::new(), String::new()))
}
}
other => panic!("unexpected systemctl args: {other:?}"),
}
})),
);
let home = tmp.path();
let data = tmp.path().join("data");
std::fs::create_dir_all(&data).unwrap();
// 1. First sync writes the unit file, `systemctl enable` fails -> returns Err and status is NOT registered
// even though the unit file already exists on disk!
assert!(mgr.sync(Some(home), &data, true).is_err());
let st_failed = mgr.status(Some(home), true);
assert!(!st_failed.registered, "file exists alone must not report registered when systemctl failed");
assert!(st_failed.error.as_deref().unwrap_or_default().contains("dbus unavailable"));
// 2. Second sync with identical parameters (unchanged file on disk!) retries `systemctl enable` and succeeds.
let st_ok = mgr.sync(Some(home), &data, true).unwrap();
assert!(st_ok.registered);
assert!(st_ok.error.is_none());
// 3. Disabling when `systemctl disable --now` fails preserves the unit file and retryability.
assert!(mgr.sync(Some(home), &data, false).is_err());
assert!(mgr.service_file_path(Some(home)).unwrap().is_file(), "unit file kept so unregister can retry");
assert!(mgr.status(Some(home), true).registered);
// 4. Retrying disable runs `systemctl --user disable --now` (stopping the worker), removes the file, and clears status.
let st_off = mgr.sync(Some(home), &data, false).unwrap();
assert!(!st_off.registered);
assert!(!active.load(Ordering::Acquire), "running worker stopped on disable");
assert_eq!(disable_now_calls.load(Ordering::Acquire), 2);
assert!(!mgr.service_file_path(Some(home)).unwrap().exists());
// 5. Unknown OS query status (e.g. D-Bus unreachable) MUST NOT treat worker as absent or delete unit file!
let status_unknown = Arc::new(AtomicBool::new(false));
let status_unknown_c = status_unknown.clone();
let macos_loaded = Arc::new(AtomicBool::new(false));
let macos_loaded_c = macos_loaded.clone();
mgr.set_command_runner_for_test(
ServicePlatform::Macos,
Some(Arc::new(move |prog, args| {
assert_eq!(prog, "launchctl");
match args {
["print", _] => {
if status_unknown_c.load(Ordering::Acquire) {
Ok((1, String::new(), "IPC transport error".into()))
} else if macos_loaded_c.load(Ordering::Acquire) {
Ok((0, "state = running\n".into(), String::new()))
} else {
Ok((113, String::new(), "Could not find service\n".into()))
}
}
["bootstrap", _, _] => {
macos_loaded_c.store(true, Ordering::Release);
Ok((0, String::new(), String::new()))
}
["bootout", _] => {
macos_loaded_c.store(false, Ordering::Release);
Ok((0, String::new(), String::new()))
}
other => panic!("unexpected launchctl args: {other:?}"),
}
})),
);
mgr.sync(Some(home), &data, true).unwrap();
let plist_path = mgr.service_file_path(Some(home)).unwrap();
assert!(plist_path.is_file());
// Simulate transient launchd query failure on disable -> keeps plist file on disk for retry!
status_unknown.store(true, Ordering::Release);
assert!(mgr.sync(Some(home), &data, false).is_err());
assert!(plist_path.is_file(), "plist must be preserved when OS status is unknown");
assert!(macos_loaded.load(Ordering::Acquire));
// Restore launchd query -> retry succeeds, unloads worker, and deletes plist!
status_unknown.store(false, Ordering::Release);
mgr.sync(Some(home), &data, false).unwrap();
assert!(!macos_loaded.load(Ordering::Acquire));
assert!(!plist_path.exists());
}
}
File diff suppressed because it is too large. Load diff
+577
Переглянути файл
@@ -0,0 +1,577 @@
//! Cross-process owner locks, abandonment detection, and authenticated loopback RPC bridge
//! so live runs owned by `openidea --scheduler` (or `ChatOnly` / headless `AgentManager`s)
//! stream `AgentEvent`s to open windows and accept permission approvals (`agent_respond`,
//! `agent_answer_question`, `agent_cancel`, `agent_entries`, etc.).
use ide_agent::{AgentEntry, AgentEvent, AgentManager, AgentPrompt, AgentTask};
use ide_core::{CancellationToken, IdeError, IdeResult};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::broadcast;
const OWNERS_DIR: &str = "owners";
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OwnerEndpoint {
pub instance_id: String,
pub pid: u32,
pub addr: String,
pub token: String,
}
#[derive(Clone, Debug)]
pub struct RoutedAgentEvent {
pub project_root: Option<PathBuf>,
pub event: AgentEvent,
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "camelCase", rename_all_fields = "camelCase")]
enum PeerRequest {
Subscribe { token: String, allowed_roots: Vec<PathBuf>, include_chat_only: bool },
Entries { token: String, task: String, subagent: Option<String> },
Respond { token: String, task: String, permission: u32, option: Option<String> },
AnswerQuestion { token: String, task: String, question: String, answer: Option<String> },
Cancel { token: String, task: String, subagent: Option<String> },
StopBackground { token: String, task: String, background: String },
Prompt { token: String, task: String, prompt: AgentPrompt, now: bool },
StopIdleWorker { token: String },
}
pub type ResolveManagerFn = Arc<dyn Fn(&str) -> Option<Arc<AgentManager>> + Send + Sync>;
pub type ListLiveTasksFn = Arc<dyn Fn(&[PathBuf], bool) -> Vec<AgentTask> + Send + Sync>;
#[derive(Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
enum PeerStreamItem {
Snapshot { tasks: Vec<AgentTask> },
Event { event: Box<AgentEvent> },
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "camelCase")]
enum PeerReply<T> {
Ok { value: T },
Err { error: String },
}
pub fn owners_dir(automations_dir: &Path) -> PathBuf {
automations_dir.join(OWNERS_DIR)
}
/// Checks whether `owner_id` holds an active OS lock in `automations_dir/owners/`.
/// If the lock can be acquired immediately, that process has exited/crashed and its stale
/// lock/endpoint files are cleaned up.
pub fn is_owner_alive(automations_dir: &Path, self_instance_id: &str, owner_id: &str) -> bool {
if owner_id.is_empty() {
return false;
}
if owner_id == self_instance_id {
return true;
}
let dir = owners_dir(automations_dir);
let lock_path = dir.join(format!("{owner_id}.lock"));
let Ok(file) = std::fs::OpenOptions::new().read(true).write(true).open(&lock_path) else {
return false;
};
if file.try_lock().is_ok() {
let _ = file.unlock();
drop(file);
let _ = std::fs::remove_file(&lock_path);
let _ = std::fs::remove_file(dir.join(format!("{owner_id}.json")));
false
} else {
true
}
}
pub fn read_live_endpoint(automations_dir: &Path, self_instance_id: &str, owner_id: &str) -> Option<OwnerEndpoint> {
if !is_owner_alive(automations_dir, self_instance_id, owner_id) {
return None;
}
let path = owners_dir(automations_dir).join(format!("{owner_id}.json"));
let bytes = std::fs::read(path).ok()?;
serde_json::from_slice(&bytes).ok()
}
pub fn list_live_peer_endpoints(automations_dir: &Path, self_instance_id: &str) -> Vec<OwnerEndpoint> {
let dir = owners_dir(automations_dir);
let Ok(entries) = std::fs::read_dir(&dir) else {
return Vec::new();
};
let mut out = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
if path.extension().is_none_or(|e| e != "json") {
continue;
}
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
continue;
};
if stem == self_instance_id {
continue;
}
if let Some(ep) = read_live_endpoint(automations_dir, self_instance_id, stem) {
out.push(ep);
}
}
out
}
pub struct OwnerNode {
pub instance_id: String,
lock_file: Mutex<Option<std::fs::File>>,
endpoint_path: Mutex<Option<PathBuf>>,
pub events_tx: broadcast::Sender<RoutedAgentEvent>,
worker_stop_requested: std::sync::atomic::AtomicBool,
subscriptions: Mutex<HashMap<String, CancellationToken>>,
}
impl OwnerNode {
pub fn new(instance_id: String) -> Self {
let (events_tx, _) = broadcast::channel(512);
Self {
instance_id,
lock_file: Mutex::new(None),
endpoint_path: Mutex::new(None),
events_tx,
worker_stop_requested: std::sync::atomic::AtomicBool::new(false),
subscriptions: Mutex::new(HashMap::new()),
}
}
pub fn worker_stop_requested(&self) -> bool {
self.worker_stop_requested.load(std::sync::atomic::Ordering::Acquire)
}
/// Acquires `owners/<instance_id>.lock` (idempotent) so any peer can tell this process is alive.
pub fn ensure_lock(&self, automations_dir: &Path) -> IdeResult<()> {
let mut guard = self.lock_file.lock();
if guard.is_some() {
return Ok(());
}
let dir = owners_dir(automations_dir);
std::fs::create_dir_all(&dir)?;
let lock_path = dir.join(format!("{}.lock", self.instance_id));
let file = std::fs::OpenOptions::new().create(true).read(true).write(true).truncate(false).open(&lock_path)?;
file.try_lock()
.map_err(|e| IdeError::internal(format!("cannot acquire owner lock {}: {e}", lock_path.display())))?;
*guard = Some(file);
Ok(())
}
/// Starts the authenticated loopback RPC server for live run events and approvals.
pub fn start_server(
&self,
automations_dir: &Path,
runtime: &tokio::runtime::Handle,
shutdown: CancellationToken,
resolve_mgr: ResolveManagerFn,
list_live_tasks: ListLiveTasksFn,
node_ref: Arc<OwnerNode>,
) {
if self.ensure_lock(automations_dir).is_err() {
return;
}
if self.endpoint_path.lock().is_some() {
return;
}
let dir = owners_dir(automations_dir);
let token = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
let Ok(std_listener) = std::net::TcpListener::bind("127.0.0.1:0") else {
return;
};
if std_listener.set_nonblocking(true).is_err() {
return;
}
let Ok(local_addr) = std_listener.local_addr() else {
return;
};
let instance_id = self.instance_id.clone();
let json_path = dir.join(format!("{instance_id}.json"));
let ep = OwnerEndpoint {
instance_id: instance_id.clone(),
pid: std::process::id(),
addr: local_addr.to_string(),
token: token.clone(),
};
if let Ok(bytes) = serde_json::to_vec_pretty(&ep) {
let _ = write_private_file(&json_path, &bytes);
}
*self.endpoint_path.lock() = Some(json_path.clone());
runtime.spawn(async move {
let Ok(listener) = TcpListener::from_std(std_listener) else {
let _ = std::fs::remove_file(&json_path);
return;
};
loop {
tokio::select! {
_ = shutdown.cancelled() => break,
accepted = listener.accept() => {
let Ok((stream, _)) = accepted else { continue };
let token_c = token.clone();
let resolve_c = resolve_mgr.clone();
let list_c = list_live_tasks.clone();
let shutdown_c = shutdown.clone();
let node_c = node_ref.clone();
tokio::spawn(async move {
handle_peer_conn(stream, token_c, resolve_c, list_c, shutdown_c, node_c).await;
});
}
}
}
let _ = std::fs::remove_file(&json_path);
});
}
pub fn stop(&self, automations_dir: &Path) {
for (_, cancel) in self.subscriptions.lock().drain() {
cancel.cancel();
}
if let Some(ep_path) = self.endpoint_path.lock().take() {
let _ = std::fs::remove_file(ep_path);
}
if let Some(file) = self.lock_file.lock().take() {
let _ = file.unlock();
}
let _ = std::fs::remove_file(owners_dir(automations_dir).join(format!("{}.lock", self.instance_id)));
}
pub fn replace_subscriber(&self, subscriber: &str) -> CancellationToken {
let token = CancellationToken::new();
if let Some(prev) = self.subscriptions.lock().insert(subscriber.to_owned(), token.clone()) {
prev.cancel();
}
token
}
pub fn unsubscribe(&self, subscriber: &str) {
if let Some(prev) = self.subscriptions.lock().remove(subscriber) {
prev.cancel();
}
}
}
fn write_private_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
#[cfg(unix)]
{
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
let mut f = std::fs::OpenOptions::new().create(true).write(true).truncate(true).mode(0o600).open(path)?;
f.write_all(bytes)?;
f.sync_all()
}
#[cfg(not(unix))]
{
std::fs::write(path, bytes)
}
}
async fn handle_peer_conn(
stream: TcpStream,
expected_token: String,
resolve_mgr: ResolveManagerFn,
list_live_tasks: ListLiveTasksFn,
shutdown: CancellationToken,
node: Arc<OwnerNode>,
) {
let (reader, mut writer) = stream.into_split();
let mut lines = BufReader::new(reader).lines();
let Ok(Some(first_line)) = lines.next_line().await else {
return;
};
let Ok(req) = serde_json::from_str::<PeerRequest>(&first_line) else {
return;
};
let req_token = match &req {
PeerRequest::Subscribe { token, .. }
| PeerRequest::Entries { token, .. }
| PeerRequest::Respond { token, .. }
| PeerRequest::AnswerQuestion { token, .. }
| PeerRequest::Cancel { token, .. }
| PeerRequest::StopBackground { token, .. }
| PeerRequest::Prompt { token, .. }
| PeerRequest::StopIdleWorker { token } => token,
};
if req_token != &expected_token {
let _ = write_json_line(&mut writer, &PeerReply::<()>::err("unauthorized")).await;
return;
}
match req {
PeerRequest::Subscribe { allowed_roots, include_chat_only, .. } => {
let mut rx = node.events_tx.subscribe();
let canon_allowed: Vec<PathBuf> =
allowed_roots.into_iter().map(|p| dunce::canonicalize(&p).unwrap_or(p)).collect();
let initial = list_live_tasks(&canon_allowed, include_chat_only);
if write_json_line(&mut writer, &PeerStreamItem::Snapshot { tasks: initial }).await.is_err() {
return;
}
loop {
tokio::select! {
_ = shutdown.cancelled() => break,
recv = rx.recv() => {
match recv {
Ok(routed) => {
let matches = match &routed.project_root {
None => include_chat_only,
Some(actual) => {
let cand = dunce::canonicalize(actual).unwrap_or_else(|_| actual.clone());
canon_allowed.iter().any(|w| w == &cand)
}
};
if matches
&& write_json_line(
&mut writer,
&PeerStreamItem::Event { event: Box::new(routed.event) },
)
.await
.is_err()
{
break;
}
}
Err(broadcast::error::RecvError::Lagged(_)) => continue,
Err(broadcast::error::RecvError::Closed) => break,
}
}
}
}
}
PeerRequest::Entries { task, subagent, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => tokio::task::spawn_blocking(move || mgr.entries(&task, subagent))
.await
.map_err(|e| IdeError::internal(e.to_string()))
.and_then(|r| r),
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::Respond { task, permission, option, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.respond(&task, permission, option),
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::AnswerQuestion { task, question, answer, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.answer_question(&task, &question, answer).await,
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::Cancel { task, subagent, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.cancel(&task, subagent),
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::StopBackground { task, background, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.stop_background(&task, &background).await,
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::Prompt { task, prompt, now, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.prompt(&task, prompt, now).await,
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::StopIdleWorker { .. } => {
node.worker_stop_requested.store(true, std::sync::atomic::Ordering::Release);
let _ = write_json_line(&mut writer, &PeerReply::from_res(Ok(()))).await;
}
}
}
impl<T> PeerReply<T> {
fn from_res(res: IdeResult<T>) -> Self {
match res {
Ok(value) => Self::Ok { value },
Err(e) => Self::Err { error: e.to_string() },
}
}
fn err(msg: &str) -> Self {
Self::Err { error: msg.to_owned() }
}
}
async fn write_json_line<W: AsyncWriteExt + Unpin, T: Serialize>(writer: &mut W, msg: &T) -> std::io::Result<()> {
let mut line = serde_json::to_vec(msg).map_err(std::io::Error::other)?;
line.push(b'\n');
writer.write_all(&line).await?;
writer.flush().await
}
async fn call_peer<T: for<'de> Deserialize<'de>>(ep: &OwnerEndpoint, req: &PeerRequest) -> IdeResult<T> {
let mut stream = TcpStream::connect(&ep.addr)
.await
.map_err(|e| IdeError::unavailable(format!("cannot reach live automation worker at {}: {e}", ep.addr)))?;
write_json_line(&mut stream, req)
.await
.map_err(|e| IdeError::unavailable(format!("failed sending request to automation worker: {e}")))?;
let mut lines = BufReader::new(stream).lines();
let raw = lines
.next_line()
.await
.map_err(|e| IdeError::unavailable(format!("failed reading automation worker reply: {e}")))?
.ok_or_else(|| IdeError::unavailable("automation worker closed connection without replying"))?;
match serde_json::from_str::<PeerReply<T>>(&raw).map_err(|e| IdeError::internal(e.to_string()))? {
PeerReply::Ok { value } => Ok(value),
PeerReply::Err { error } => Err(IdeError::internal(error)),
}
}
fn call_peer_sync<T: for<'de> Deserialize<'de>>(ep: &OwnerEndpoint, req: &PeerRequest) -> IdeResult<T> {
use std::io::{BufRead, Write};
let addr: std::net::SocketAddr = ep
.addr
.parse()
.map_err(|e| IdeError::internal(format!("invalid automation worker address {}: {e}", ep.addr)))?;
let mut stream = std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_secs(3))
.map_err(|e| IdeError::unavailable(format!("cannot reach live automation worker at {}: {e}", ep.addr)))?;
let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(5)));
let _ = stream.set_write_timeout(Some(std::time::Duration::from_secs(5)));
let mut line = serde_json::to_vec(req).map_err(|e| IdeError::internal(e.to_string()))?;
line.push(b'\n');
stream
.write_all(&line)
.and_then(|()| stream.flush())
.map_err(|e| IdeError::unavailable(format!("failed sending request to automation worker: {e}")))?;
let mut reader = std::io::BufReader::new(stream);
let mut raw = String::new();
reader
.read_line(&mut raw)
.map_err(|e| IdeError::unavailable(format!("failed reading automation worker reply: {e}")))?;
if raw.trim().is_empty() {
return Err(IdeError::unavailable("automation worker closed connection without replying"));
}
match serde_json::from_str::<PeerReply<T>>(&raw).map_err(|e| IdeError::internal(e.to_string()))? {
PeerReply::Ok { value } => Ok(value),
PeerReply::Err { error } => Err(IdeError::internal(error)),
}
}
pub async fn peer_entries(ep: &OwnerEndpoint, task: String, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
call_peer(ep, &PeerRequest::Entries { token: ep.token.clone(), task, subagent }).await
}
pub fn peer_respond(
_runtime: &tokio::runtime::Handle,
ep: OwnerEndpoint,
task: String,
permission: u32,
option: Option<String>,
) -> IdeResult<()> {
let token = ep.token.clone();
call_peer_sync(&ep, &PeerRequest::Respond { token, task, permission, option })
}
pub async fn peer_answer_question(
ep: &OwnerEndpoint,
task: String,
question: String,
answer: Option<String>,
) -> IdeResult<()> {
call_peer(ep, &PeerRequest::AnswerQuestion { token: ep.token.clone(), task, question, answer }).await
}
pub fn peer_cancel(
_runtime: &tokio::runtime::Handle,
ep: OwnerEndpoint,
task: String,
subagent: Option<String>,
) -> IdeResult<()> {
let token = ep.token.clone();
call_peer_sync(&ep, &PeerRequest::Cancel { token, task, subagent })
}
pub async fn peer_stop_background(ep: &OwnerEndpoint, task: String, background: String) -> IdeResult<()> {
call_peer(ep, &PeerRequest::StopBackground { token: ep.token.clone(), task, background }).await
}
pub async fn peer_prompt(ep: &OwnerEndpoint, task: String, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
call_peer(ep, &PeerRequest::Prompt { token: ep.token.clone(), task, prompt, now }).await
}
pub fn notify_peers_stop_if_headless(runtime: &tokio::runtime::Handle, endpoints: Vec<OwnerEndpoint>) {
for ep in endpoints {
runtime.spawn(async move {
let token = ep.token.clone();
let _: IdeResult<()> = call_peer(&ep, &PeerRequest::StopIdleWorker { token }).await;
});
}
}
/// Connects to `ep`, fetches its initial live task snapshot synchronously (with a short timeout),
/// and spawns an async forwarder streaming subsequent `AgentEvent`s until `cancel` triggers.
pub fn attach_peer_stream(
runtime: &tokio::runtime::Handle,
ep: OwnerEndpoint,
allowed_roots: Vec<PathBuf>,
include_chat_only: bool,
cancel: CancellationToken,
on_event: Arc<dyn Fn(AgentEvent) + Send + Sync>,
) -> Vec<AgentTask> {
let (snap_tx, snap_rx) = std::sync::mpsc::channel();
runtime.spawn(async move {
let connect_fut = TcpStream::connect(&ep.addr);
let Ok(Ok(mut stream)) = tokio::time::timeout(std::time::Duration::from_secs(2), connect_fut).await else {
let _ = snap_tx.send(Vec::new());
return;
};
let req = PeerRequest::Subscribe { token: ep.token.clone(), allowed_roots, include_chat_only };
if write_json_line(&mut stream, &req).await.is_err() {
let _ = snap_tx.send(Vec::new());
return;
}
let mut lines = BufReader::new(stream).lines();
match tokio::time::timeout(std::time::Duration::from_secs(2), lines.next_line()).await {
Ok(Ok(Some(first))) => match serde_json::from_str::<PeerStreamItem>(&first) {
Ok(PeerStreamItem::Snapshot { tasks }) => {
let _ = snap_tx.send(tasks);
}
_ => {
let _ = snap_tx.send(Vec::new());
return;
}
},
_ => {
let _ = snap_tx.send(Vec::new());
return;
}
}
loop {
tokio::select! {
_ = cancel.cancelled() => break,
next = lines.next_line() => {
match next {
Ok(Some(line)) => {
if let Ok(PeerStreamItem::Event { event }) = serde_json::from_str::<PeerStreamItem>(&line) {
on_event(*event);
}
}
_ => break,
}
}
}
}
});
snap_rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap_or_default()
}
+86 -17
Переглянути файл
@@ -18,6 +18,7 @@ use std::sync::{Arc, OnceLock};
enum Mode {
Stdio,
Scheduler,
#[cfg(unix)]
Daemon(PathBuf, ide_host::daemon::BuildId),
}
@@ -29,6 +30,7 @@ usage:
openidea-server --web [options] [<project>]
openidea-server --stdio
openidea-server --attach <project-path>
openidea-server --scheduler
openidea-server --mcp-stdio [--project <path>]
openidea-server --connect <host> <port>
openidea-server --version
@@ -233,6 +235,7 @@ fn main() {
}
#[cfg(not(unix))]
[flag, _] if flag == "--attach" => Mode::Stdio,
_ if args.iter().any(|a| a == "--scheduler") => Mode::Scheduler,
_ if args.iter().any(|a| a == "--stdio") => Mode::Stdio,
_ => {
print_usage();
@@ -292,17 +295,21 @@ async fn run(base: PathBuf, mode: Mode) -> i32 {
let peer = Arc::new(OnceLock::new());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
let host = Arc::new(
Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
})
// The client answers no svn prompts here: svn runs non-interactively.
.with_subversion(false),
);
start_mcp(&host, &base);
let plugins = start_plugins(&plugins_data, &host, peer.clone());
inherit_trust(&host);
@@ -312,23 +319,85 @@ async fn run(base: PathBuf, mode: Mode) -> i32 {
shutdown_all(&host, plugins.as_ref()).await;
0
}
#[cfg(unix)]
Mode::Daemon(socket, build) => {
let peer = Arc::new(rpc::PeerSlot::default());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
Mode::Scheduler => {
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
start_mcp(&host, &base);
inherit_trust(&host);
host.automations.set_headless_worker_mode(true);
host.automations.start(&host);
tracing::info!("openidea-server {} headless scheduler started", env!("CARGO_PKG_VERSION"));
let mut idle_ticks = 0u32;
let mut check = tokio::time::interval(std::time::Duration::from_secs(5));
#[cfg(unix)]
let mut terminate =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).expect("SIGTERM listener");
loop {
#[cfg(unix)]
tokio::select! {
_ = tokio::signal::ctrl_c() => break,
_ = terminate.recv() => break,
_ = check.tick() => {}
}
#[cfg(not(unix))]
tokio::select! {
_ = tokio::signal::ctrl_c() => break,
_ = check.tick() => {}
}
let service_enabled = ide_workspace::SettingsStore::load(&host.config_dir, None)
.effective()
.agents
.automations
.auto_start_service;
let running = host.automations.has_running_runs();
if host.automations.worker_stop_requested() || !service_enabled {
if !running {
tracing::info!("headless scheduler login service disabled; exiting");
break;
}
} else if host.automations.has_enabled_schedules() || running {
idle_ticks = 0;
} else {
idle_ticks += 1;
if idle_ticks >= 3 {
tracing::info!("no enabled automations remain; headless scheduler exiting");
break;
}
}
}
shutdown_all(&host, None).await;
0
}
#[cfg(unix)]
Mode::Daemon(socket, build) => {
let peer = Arc::new(rpc::PeerSlot::default());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(
Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
})
// The client answers no svn prompts here: svn runs non-interactively.
.with_subversion(false),
);
start_mcp(&host, &base);
let plugins = start_plugins(&plugins_data, &host, peer.clone());
inherit_trust(&host);
tracing::info!("openidea-server {} daemon ready at {}", env!("CARGO_PKG_VERSION"), socket.display());
+2
Переглянути файл
@@ -398,6 +398,7 @@ pub async fn serve(
};
let shutdown = CancellationToken::new();
host.automations.start(&host);
let idle_policy = RemoteIdlePolicy { override_seconds: idle_override() };
let mut check = tokio::time::interval(Duration::from_secs(idle_policy.override_seconds.unwrap_or(5).min(5)));
let mut idle = None;
@@ -541,6 +542,7 @@ fn has_live_work(host: &Host) -> bool {
!host.terminals.list().is_empty()
|| host.processes.has_live_runs()
|| !host.debugger.sessions(None).is_empty()
|| host.automations.keeps_remote_daemon_alive(host)
|| host
.projects()
.iter()
+20 -8
Переглянути файл
@@ -1601,15 +1601,21 @@ mod tests {
let text = "a\n b\nc\nd\n e\n";
let formatted = "a\nb\nc\nd\ne\n";
let whole = vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(5, 0)), new_text: formatted.into() }];
let started = std::time::Instant::now();
let edits = minimal_edits(text, whole);
assert_eq!(
edits,
[
TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() },
TextEdit { range: Range::new(Pos::new(4, 0), Pos::new(4, 2)), new_text: String::new() },
]
);
// Past the diff budget (a loaded machine) the regions may merge, still correctly.
if started.elapsed() < ide_text::DIFF_BUDGET {
assert_eq!(
edits,
[
TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() },
TextEdit { range: Range::new(Pos::new(4, 0), Pos::new(4, 2)), new_text: String::new() },
]
);
}
assert_eq!(after(text, &edits), formatted);
// Merged or not, the edits stay between the first and the last changed line.
assert!(edits[0].range.start >= Pos::new(1, 0) && edits[edits.len() - 1].range.end <= Pos::new(4, 2));
// Single-line edits are already minimal and pass through.
let small = vec![TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() }];
assert_eq!(minimal_edits(text, small.clone()), small);
@@ -1660,11 +1666,17 @@ mod tests {
let text = "<?php\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n";
// PHP-CS-Fixer formats the whole file (here: adds a line at the top) whatever the selection.
let formatted = format!("<?php\n\ndeclare(strict_types=1);\n{}", &text["<?php\n".len()..]);
let started = std::time::Instant::now();
let edits = whole_file(text, &formatted);
// Lines 3..=6 select the array, up to the start of the line after it.
let range = Range::new(Pos::new(3, 0), Pos::new(7, 0));
let aligned = align_formatted(&syntax, &php, text, edits, Some(range), ALIGN).unwrap();
assert_eq!(aligned.len(), 2, "one edit per changed region: {aligned:?}");
// Past the diff budget (a loaded machine) the regions may merge, still correctly.
if started.elapsed() < ide_text::DIFF_BUDGET {
assert_eq!(aligned.len(), 2, "one edit per changed region: {aligned:?}");
}
// Merged or not, the edits leave the unchanged first and last lines alone.
assert!(aligned[0].range.start >= Pos::new(1, 0) && aligned[aligned.len() - 1].range.end <= Pos::new(6, 0));
assert_eq!(
after(text, &aligned),
"<?php\n\ndeclare(strict_types=1);\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n"
+39 -1
Переглянути файл
@@ -4,6 +4,7 @@
//! runs one on a remote machine and serves it over JSON-RPC ([`rpc`]).
pub mod agent_secrets;
pub mod automations;
pub mod catalogue;
#[cfg(unix)]
pub mod daemon;
@@ -27,6 +28,7 @@ pub mod relay;
mod requests;
pub mod rpc;
pub mod shell_env;
pub mod svn;
mod swiftlint;
pub mod trust;
mod ts_code_style;
@@ -90,6 +92,10 @@ impl HostConfig {
pub struct Host {
local_database_tunnels: bool,
/// Finders of non-Git working copies ([`Host::with_vcs_provider`]); Git is built in.
pub(crate) vcs_providers: Vec<Arc<dyn ide_vcs::BackendProvider>>,
/// Subversion is on ([`Host::with_subversion`]); `Some(true)` shows svn's prompts in dialogs.
pub(crate) subversion: Option<bool>,
pub(crate) mcp_executable: Arc<RwLock<Option<PathBuf>>>,
pub mcp: mcp::McpService,
plugin_host: RwLock<std::sync::Weak<plugins::PluginHost>>,
@@ -102,9 +108,12 @@ pub struct Host {
pub mcp_agent_runs: mcp::AgentRuns,
/// Projects the MCP server serves without a window.
pub mcp_background: mcp::BackgroundProjects,
/// Host-owned scheduled agent automations and in-session follow-up timers.
pub automations: Arc<automations::AutomationService>,
pub(crate) agent_catalogs: Arc<ide_agent::AgentCatalogs>,
pub trust: std::sync::Arc<trust::TrustStore>,
pub(crate) mcp_approvals: Arc<trust::McpServerApprovals>,
pub(crate) plugin_approvals: Arc<trust::PluginCapabilityApprovals>,
pub config_dir: PathBuf,
/// Persistent user state, including credentials and recovery history.
pub data_dir: PathBuf,
@@ -209,6 +218,21 @@ impl Host {
self
}
/// Adds a version control system besides Git: projects opened afterwards look for its
/// working copies (when trusted) and route the Changes view, status and log to them.
pub fn with_vcs_provider(mut self, provider: Arc<dyn ide_vcs::BackendProvider>) -> Self {
self.vcs_providers.push(provider);
self
}
/// Adds Subversion: every project gets its own svn settings ([`svn`]) and finds its
/// working copies. `prompts` routes svn's login and certificate prompts to the project's
/// window (the desktop app, which answers them with `ssh_askpass_answer`).
pub fn with_subversion(mut self, prompts: bool) -> Self {
self.subversion = Some(prompts);
self
}
/// User home directory used by agent memory discovery.
pub fn home_dir(&self) -> Option<PathBuf> {
self.home_dir.clone()
@@ -234,9 +258,13 @@ impl Host {
let migration = ssh.clone();
runtime.spawn_blocking(move || migration.start_password_migration());
ssh.set_configs(global_settings.effective().ssh.configs);
let boot_override = if cfg!(test) { Some(data_dir.join("boot-services-test")) } else { None };
let automations = automations::AutomationService::new(&data_dir, boot_override);
let host = Self {
plugin_host: RwLock::default(),
local_database_tunnels: false,
vcs_providers: Vec::new(),
subversion: None,
mcp_executable: Arc::default(),
mcp: Default::default(),
diagnostics,
@@ -244,9 +272,11 @@ impl Host {
mcp_requests: Default::default(),
mcp_agent_runs: Default::default(),
mcp_background: Default::default(),
automations,
agent_catalogs: Arc::default(),
trust: std::sync::Arc::new(trust::TrustStore::load(&config_dir, &data_dir)),
mcp_approvals: Arc::new(trust::McpServerApprovals::load(&data_dir)),
plugin_approvals: Arc::new(trust::PluginCapabilityApprovals::load(&data_dir)),
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
jupyter_tokens: ide_ssh::secrets::SecretFile::new(data_dir.join("jupyter-tokens.json")),
proxy_session_password: Mutex::default(),
@@ -482,13 +512,20 @@ impl Host {
let processes = self.processes.detach_project_kills(&project.root);
let terminals = self.terminals.detach_key(self.owner_window(window));
let root = (!project.light).then(|| project.root.clone());
let shutdown_agents = if !project.light
&& self.automations.retain_on_window_close(self, &project.root, &project.agents, agent_reason)
{
Vec::new()
} else {
vec![project.agents.clone()]
};
let handle = self.spawn_project_shutdown(ShutdownWork {
notebooks: vec![project.notebooks.clone()],
bridges: project.kotlin_bridge.iter().cloned().collect(),
lsp: Some(project.lsp.clone()),
// Debug sessions under the root belong to windows: a project served without one starts none.
debug: Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
agents: vec![project.agents.clone()],
agents: shutdown_agents,
agent_reason,
terminals: Some(terminals),
processes: Some(processes),
@@ -617,6 +654,7 @@ impl Host {
}
pub fn shutdown_notebooks_on_exit_with(&self, agent_reason: ide_agent::AgentShutdownReason) {
self.automations.stop();
let projects = self.projects();
let mut pending: Vec<_> = self.closing.lock().drain(..).map(|entry| entry.handle).collect();
if !projects.is_empty() {
+1 -1
Переглянути файл
@@ -444,7 +444,7 @@ impl BackgroundProjects {
impl Host {
/// The window, and its project, that has `root` open as a project (not in LightEdit).
fn window_project(&self, root: &Path) -> Option<(String, Arc<Project>)> {
pub(crate) fn window_project(&self, root: &Path) -> Option<(String, Arc<Project>)> {
let projects = self.projects.read();
let windows = projects.iter().filter(|(w, p)| !BackgroundProjects::is_key(w) && !p.light && p.root == root);
windows.min_by_key(|(w, _)| w.as_str()).map(|(w, p)| (w.clone(), p.clone()))
+40 -3
Переглянути файл
@@ -242,7 +242,11 @@ marked directory are not marked again.",
},
)
.param(Param::required("directoryPath", ParamType::String, RELATIVE_PATH_IN_PROJECT_DESCRIPTION))
.param(Param::optional("maxDepth", ParamType::Integer, "Maximum recursion depth"))
.param(Param::optional(
"maxDepth",
ParamType::Integer,
"Levels to list below the directory: 1 lists its entries, 2 their entries too, and so on (default 5)",
))
.param(Param::optional("limit", ParamType::Integer, "Entries to return at most (default 100)"))
.param(Param::optional("offset", ParamType::Integer, OFFSET))
.param(Param::optional("timeout", ParamType::Integer, TIMEOUT_MILLISECONDS_DESCRIPTION))
@@ -306,6 +310,7 @@ fn marker(git_ignored: bool, ide_excluded: bool) -> &'static str {
}
impl TreeRender {
/// `max_depth`: the levels to list below the entry (0 lists the entry alone);
/// `mark`: the entry's marker; `marked`: it or a directory above it is marked.
#[allow(clippy::too_many_arguments)]
fn render(
@@ -318,7 +323,7 @@ impl TreeRender {
mark: &str,
marked: bool,
) {
if max_depth <= 0 || self.timed_out || self.cancel.is_cancelled() {
if self.timed_out || self.cancel.is_cancelled() {
return;
}
if Instant::now() >= self.deadline {
@@ -343,7 +348,7 @@ impl TreeRender {
} else {
self.entry(&line)
};
if !is_dir {
if !is_dir || max_depth <= 0 {
return;
}
// Without exclusions, `ignored` is what `.gitignore` says.
@@ -482,6 +487,38 @@ mod tests {
assert_eq!(render(0, 100).0, " ├── a/\n │ ├── x.txt\n │ └── y.txt\n └── b.txt\n");
}
#[test]
fn max_depth_counts_the_levels_below_the_directory() {
let tmp = tempfile::tempdir().unwrap();
for file in ["a/b/c.txt", "d.txt"] {
let path = tmp.path().join(file);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "").unwrap();
}
let render = |max_depth| {
let mut tree = TreeRender {
out: String::new(),
errors: Vec::new(),
timed_out: false,
deadline: Instant::now() + Duration::from_secs(10),
cancel: CancellationToken::new(),
page: Page { offset: 0, limit: 100 },
seen: 0,
above: Vec::new(),
marks: Marks { root: tmp.path().to_path_buf(), excludes: None },
};
tree.render(tmp.path(), "", true, max_depth, true, "", false);
let root = format!("{}/\n", tmp.path().display());
(tree.out.strip_prefix(&root).unwrap().to_owned(), tree.seen)
};
assert_eq!(render(0), (String::new(), 0), "0 lists the directory alone");
assert_eq!(render(1), (" ├── a/\n └── d.txt\n".to_owned(), 2), "1 lists its entries");
assert_eq!(render(2), (" ├── a/\n │ └── b/\n └── d.txt\n".to_owned(), 3));
let full = " ├── a/\n │ └── b/\n │ └── c.txt\n └── d.txt\n".to_owned();
assert_eq!(render(3), (full.clone(), 4));
assert_eq!(render(5), (full, 4), "a depth beyond the tree lists all of it");
}
#[test]
fn what_the_project_leaves_out_is_marked_once() {
let tmp = tempfile::tempdir().unwrap();
+2
Переглянути файл
@@ -668,6 +668,8 @@ mod tests {
selection_range: Range::new(range.start, range.start),
children,
visibility: None,
implements: None,
self_type: None,
};
let method = outline(
"total",
+21 -5
Переглянути файл
@@ -99,8 +99,8 @@ fn get_repositories() -> Tool {
"get_repositories",
"Retrieves the list of VCS roots in the project.
This is useful to detect all repositories in a multi-repository project.
In OpenIDEA each root also tells its current `branch` (absent when HEAD is detached), `headCommit` and a merge, \
rebase or cherry-pick in progress (`operationInProgress`).",
In OpenIDEA each root also tells its current `branch` (absent when HEAD is detached or the repository is unavailable), \
`headCommit`, a merge, rebase or cherry-pick in progress (`operationInProgress`), and `unavailable` (`true` when the repository directory cannot be reached).",
|call| async move {
let roots = crate::ops::vcs::vcs_roots(&call.host(), &call.window).await?;
let list: Vec<Value> = roots
@@ -117,6 +117,9 @@ rebase or cherry-pick in progress (`operationInProgress`).",
if let Some(op) = r.operation {
v["operationInProgress"] = op.into();
}
if r.unavailable {
v["unavailable"] = true.into();
}
v
})
.collect();
@@ -256,10 +259,10 @@ By default all Git repositories are returned.",
let include_ignored = call.flag("includeIgnored", false)?;
let page = Page::of(&call, STATUS_DEFAULT_LIMIT)?;
let host = call.host();
let repos: Vec<(PathBuf, Option<String>)> = crate::ops::vcs::vcs_roots(&host, &call.window)
let repos: Vec<(PathBuf, (Option<String>, bool))> = crate::ops::vcs::vcs_roots(&host, &call.window)
.await?
.into_iter()
.map(|r| (r.root.into_path_buf(), r.head))
.map(|r| (r.root.into_path_buf(), (r.head, r.unavailable)))
.collect();
let wanted = call.opt_str("repositoryPathRelativeToProject")?;
let paths = super::search::PathScope::of(&call)?;
@@ -271,12 +274,25 @@ By default all Git repositories are returned.",
};
let mut roots: Vec<(PathBuf, Option<String>)> = if targets.is_empty() {
repos
.into_iter()
.filter(|(_, (_, unavailable))| !unavailable)
.map(|(root, (head, _))| (root, head))
.collect()
} else {
let mut picked: Vec<(PathBuf, Option<String>)> = Vec::new();
for path in targets {
// The innermost repository containing the path.
let repo = match innermost_repo(repos.clone(), &path) {
Some(repo) => repo,
Some((root, (_, true))) => {
if wanted.is_some() {
return Err(IdeError::unavailable(format!(
"Git repository '{}' is currently unavailable",
relative_to_project(&call, &root)
)));
}
continue;
}
Some((root, (head, false))) => (root, head),
None => match find_git_root(call.root(), &path) {
Some(root) => {
// JetBrains reads the branch of any repository it reports.
+29 -1
Переглянути файл
@@ -264,7 +264,22 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("file.save", "Save All"),
act("templates.saveFileAsTemplate", "Save File as Template…"),
act("file.reloadAllFromDisk", "Reload All from Disk"),
sub("fileProperties", "File Properties", vec![act("file.toggleReadOnly", "Make File Read-only / Writable")]),
sub(
"fileProperties",
"File Properties",
vec![
sub(
"lineSeparators",
"Line Separators",
vec![
act("file.lineSeparators.crLf", "CRLF - Windows (\\r\\n)"),
act("file.lineSeparators.lf", "LF - Unix and macOS (\\n)"),
act("file.lineSeparators.cr", "CR - Classic Mac OS (\\r)"),
],
),
act("file.toggleReadOnly", "Make File Read-only / Writable"),
],
),
SEP,
act("file.projectStructure", "Project Structure…"),
SEP,
@@ -735,6 +750,18 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("vcs.syncSubmodules", "Sync Submodule URLs"),
],
),
// What only a Subversion working copy has; disabled for a Git repository.
sub(
"subversion",
"Subversion",
vec![
act("svn.cleanup", "Cleanup"),
act("svn.lock", "Lock…"),
act("svn.unlock", "Unlock"),
act("svn.relocate", "Relocate…"),
act("svn.properties", "Properties…"),
],
),
SEP,
act("vcs.showLog", "Show Git Log"),
sub(
@@ -903,6 +930,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("editor.moveToOppositeGroup", "Move to Opposite Group"),
act("editor.openInOppositeGroup", "Open in Opposite Group"),
act("editor.changeSplitOrientation", "Change Splitter Orientation"),
act("editor.maximizeInSplit", "Maximize Editor / Normalize Splits"),
act("editor.unsplitAll", "Unsplit All"),
act("editor.nextSplitter", "Go to Next Splitter"),
act("editor.prevSplitter", "Go to Previous Splitter"),
+774 -69
Переглянути файл
@@ -5,14 +5,17 @@ use crate::Host;
use crate::agent_secrets::{AgentSecrets, Kept};
use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentMemoryCatalog,
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemoryOverrides, AgentMemorySettings, AgentModelCatalog, AgentProbe,
AcpImportOutcome, AgentAcceptOutcome, AgentAutomation, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent,
AgentMarketplaceBrowseResult, AgentMemoryCatalog, AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemoryOverrides,
AgentMemorySettings, AgentModelCatalog, AgentPluginCatalog, AgentPluginPreview, AgentPluginSettings, AgentProbe,
AgentPrompt, AgentProvider, AgentProviderMemoryPolicy, AgentQueued, AgentRecoveryReport, AgentSkillMode,
AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode, CopilotAuthStatus, CreateAgentMemoryInput,
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource, McpImportSelection,
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput,
RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode, AutomationRun, AutomationRunsPage,
AutomationSnapshot, AutomationTrigger, AutomationWorkspace, CopilotAuthStatus, CreateAgentMemoryInput,
CreateSessionScheduleInput, CustomAgentInput, ExternalSession, InstallAgentPluginRequest,
InstallRemoteSkillRequest, Isolation, LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult, McpScope,
McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput, RemoteSkillBrowseResult,
RemoteSkillPreview, SaveAutomationInput, SessionSchedule, SkillsPolicy,
};
use ide_command::command;
use ide_core::error::ErrorKind;
@@ -30,18 +33,47 @@ pub fn agent_subscribe(
on_event: Channel<AgentEvent>,
subscriber: String,
) -> IdeResult<Vec<AgentTask>> {
Ok(host.project(window)?.agents.subscribe_as(
&subscriber,
std::sync::Arc::new(move |e| {
let _ = on_event.send(e);
}),
))
let sink: ide_agent::AgentSink = std::sync::Arc::new(move |e| {
let _ = on_event.send(e);
});
let scope = crate::automations::AutomationTaskScope::for_window(host, window);
let mut by_id: std::collections::HashMap<String, AgentTask> = std::collections::HashMap::new();
match host.project(window) {
Ok(proj) => {
for t in proj.agents.subscribe_as(&subscriber, sink.clone()) {
by_id.insert(t.id.clone(), t);
}
}
Err(e) => {
// Without an open project, `scope.allowed_roots` is empty (no wildcard!) so ONLY
// `ChatOnly` tasks may be subscribed if any exist.
let extras = host.automations.subscribe_window_extras(host, &scope, &subscriber, sink);
if extras.is_empty() {
return Err(e);
}
for t in extras {
by_id.insert(t.id.clone(), t);
}
let mut list: Vec<AgentTask> = by_id.into_values().collect();
list.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
return Ok(list);
}
}
for extra in host.automations.subscribe_window_extras(host, &scope, &subscriber, sink) {
by_id.insert(extra.id.clone(), extra);
}
let mut list: Vec<AgentTask> = by_id.into_values().collect();
list.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
Ok(list)
}
/// Stops the events of a window that closed.
#[command(trust = always)]
pub fn agent_unsubscribe(host: &Host, window: &str, subscriber: String) -> IdeResult<()> {
host.project(window)?.agents.unsubscribe(&subscriber);
host.automations.unsubscribe_window_extras(&subscriber);
if let Ok(proj) = host.project(window) {
proj.agents.unsubscribe(&subscriber);
}
Ok(())
}
@@ -422,8 +454,7 @@ pub async fn agent_entries(
task: String,
subagent: Option<String>,
) -> IdeResult<Vec<AgentEntry>> {
let agents = host.project(window)?.agents.clone();
host.blocking(move || agents.entries(&task, subagent)).await
host.automations.route_entries(host, window, task, subagent).await
}
/// Sessions of the project on this machine that no task holds yet, newest first.
@@ -478,8 +509,8 @@ pub async fn agent_create(host: &Host, window: &str, request: NewAgentTask) -> I
/// Sends a message; while the agent works it is queued, or with `now` it interrupts the turn.
#[command(trust = trusted)]
pub async fn agent_prompt(host: &Host, window: &str, task: String, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.prompt(&task, prompt, now).await
host.require_trust_if_project(window)?;
host.automations.route_prompt(host, window, task, prompt, now).await
}
/// Runs a `!` line of the composer in the task's folder with the user's shell, without
@@ -509,8 +540,8 @@ pub async fn agent_answer_question(
question: String,
answer: Option<String>,
) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.answer_question(&task, &question, answer).await
host.require_trust_if_project(window)?;
host.automations.route_answer_question(host, window, task, question, answer).await
}
/// Drops a queued message and returns it (to edit it).
@@ -615,7 +646,7 @@ pub async fn agent_context_usage(host: &Host, window: &str, task: String) -> Ide
/// Stops the task's current turn, or with `subagent` only that subagent's work.
#[command(trust = always)]
pub fn agent_cancel(host: &Host, window: &str, task: String, subagent: Option<String>) -> IdeResult<()> {
host.project(window)?.agents.cancel(&task, subagent)
host.automations.route_cancel(host, window, task, subagent)
}
/// Resumes an interrupted task with a continuation turn (or immediately wakes a task waiting
@@ -645,7 +676,10 @@ pub async fn agent_dismiss_interrupted(host: &Host, window: &str, task: String)
/// Marks a task as read (`unread = false`) when viewed by the user.
#[command(trust = always)]
pub async fn agent_mark_read(host: &Host, window: &str, task: String) -> IdeResult<()> {
let agents = host.project(window)?.agents.clone();
let agents = match host.automations.authorized_local_manager(host, window, &task, false)? {
Some(mgr) => mgr,
None => host.project(window)?.agents.clone(),
};
host.blocking(move || agents.mark_read(&task)).await
}
@@ -689,7 +723,7 @@ pub async fn agent_reconcile_interrupted(host: &Host, window: &str) -> IdeResult
/// Stops one of the task's background tasks.
#[command(trust = always)]
pub async fn agent_stop_background(host: &Host, window: &str, task: String, background: String) -> IdeResult<()> {
host.project(window)?.agents.stop_background(&task, &background).await
host.automations.route_stop_background(host, window, task, background).await
}
/// Answers a permission request; `option: null` cancels it.
@@ -701,29 +735,48 @@ pub fn agent_respond(
permission: u32,
option: Option<String>,
) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.respond(&task, permission, option)
host.require_trust_if_project(window)?;
host.automations.route_respond(host, window, task, permission, option)
}
#[command(trust = always)]
pub fn agent_archive(host: &Host, window: &str, task: String) -> IdeResult<()> {
host.project(window)?.agents.archive(&task)
match host.automations.authorized_local_manager(host, window, &task, false)? {
Some(mgr) => mgr.archive(&task),
None => host.project(window)?.agents.archive(&task),
}
}
#[command(trust = always)]
pub fn agent_unarchive(host: &Host, window: &str, task: String) -> IdeResult<()> {
host.project(window)?.agents.unarchive(&task)
match host.automations.authorized_local_manager(host, window, &task, false)? {
Some(mgr) => mgr.unarchive(&task),
None => host.project(window)?.agents.unarchive(&task),
}
}
#[command(trust = trusted)]
pub fn agent_rename(host: &Host, window: &str, task: String, title: String) -> IdeResult<()> {
host.project(window)?.agents.rename(&task, &title)
host.require_trust_if_project(window)?;
match host.automations.authorized_local_manager(host, window, &task, true)? {
Some(mgr) => mgr.rename(&task, &title),
None => {
host.require_trust(window)?;
host.project(window)?.agents.rename(&task, &title)
}
}
}
#[command(trust = trusted)]
pub async fn agent_delete(host: &Host, window: &str, task: String, remove_worktree: bool) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.delete(&task, remove_worktree).await
host.require_trust_if_project(window)?;
match host.automations.authorized_local_manager(host, window, &task, true)? {
Some(mgr) => mgr.delete(&task, remove_worktree).await,
None => {
host.require_trust(window)?;
host.project(window)?.agents.delete(&task, remove_worktree).await
}
}
}
/// The task's changed files as `view` compares them (without: since it started).
@@ -956,7 +1009,20 @@ fn listed(
}
}
}
out
let plug_policy = host_plugins_policy(host, project.map(|p| p.as_ref()));
let home = host.home_dir();
let plug_states = ide_agent::plugins::resolve_plugins(
ide_agent::plugins::discover_plugins(&plug_policy.workspace_roots, home.as_deref()),
&plug_policy,
Some(&*host.agent_secrets),
);
let projected = ide_agent::plugins::projected_mcp_servers(
&plug_states,
&plug_policy,
home.as_deref(),
Some(&*host.agent_secrets),
);
ide_agent::mcp::merge_projected_servers(out, projected)
}
/// The MCP servers agent sessions of the project at `root` get: the user's, values filled in, and
@@ -1315,27 +1381,43 @@ pub fn agent_set_memory_overrides(
host.project(window)?.agents.set_memory_overrides(&task, overrides)
}
fn resolve_skills_with_host_plugins(
policy: &SkillsPolicy,
plug_policy: &ide_agent::plugins::PluginsPolicy,
home: Option<&std::path::Path>,
secrets: Option<&dyn ide_agent::EnvSecrets>,
) -> Vec<AgentSkillState> {
let plug_states = ide_agent::plugins::resolve_plugins(
ide_agent::plugins::discover_plugins(&policy.workspace_roots, home),
plug_policy,
secrets,
);
let projected = ide_agent::plugins::projected_skill_roots(&plug_states, None);
ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_agent_plugins(
&policy.workspace_roots,
home,
&policy.plugin_dirs,
&projected,
),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
)
}
/// Every skill discovered in the project, the user's folders and enabled plugins, with
/// the mode a session 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).ok().filter(|p| !p.light);
let policy = host_skills_policy(host, project.as_deref());
let home = dirs::home_dir();
blocking(move || {
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_plugins(
&policy.workspace_roots,
home.as_deref(),
&policy.plugin_dirs,
),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
let plug_policy = host_plugins_policy(host, project.as_deref());
let home = host.home_dir();
let secrets = host.agent_secrets.clone();
blocking(move || Ok(resolve_skills_with_host_plugins(&policy, &plug_policy, home.as_deref(), Some(&*secrets))))
.await
}
/// Sets how `name` may run in `scope`, in the settings file of that scope, and returns the
@@ -1380,14 +1462,9 @@ pub fn agent_skills_set_mode(
}
}
let policy = host_skills_policy(host, project.as_deref());
let home = dirs::home_dir();
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_plugins(&policy.workspace_roots, home.as_deref(), &policy.plugin_dirs),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
let plug_policy = host_plugins_policy(host, project.as_deref());
let home = host.home_dir();
Ok(resolve_skills_with_host_plugins(&policy, &plug_policy, home.as_deref(), Some(&*host.agent_secrets)))
}
/// Resolves a GitHub `owner/repo[/path][@ref]` source and lists the `SKILL.md` skills in it.
@@ -1478,20 +1555,10 @@ pub async fn agent_skills_install(
}
let policy = host_skills_policy(host, project.as_deref());
blocking(move || {
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_plugins(
&policy.workspace_roots,
home.as_deref(),
&policy.plugin_dirs,
),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
let plug_policy = host_plugins_policy(host, project.as_deref());
let secrets = host.agent_secrets.clone();
blocking(move || Ok(resolve_skills_with_host_plugins(&policy, &plug_policy, home.as_deref(), Some(&*secrets))))
.await
}
/// The user's and the workspace's skill policies (`[agents.skills.<name>]`).
@@ -1650,9 +1717,18 @@ fn persist_memory_settings(
async fn current_memory_catalog(host: &Host, project: Option<&crate::Project>) -> IdeResult<AgentMemoryCatalog> {
let policy = host_memory_policy(host, project);
let plug_policy = host_plugins_policy(host, project);
let home = host.home_dir();
let secrets = host.agent_secrets.clone();
blocking(move || {
let entries = ide_agent::memory::discover_memories(&policy.workspace_roots, home.as_deref());
let plug_states = ide_agent::plugins::resolve_plugins(
ide_agent::plugins::discover_plugins(&policy.workspace_roots, home.as_deref()),
&plug_policy,
Some(&*secrets),
);
let projected = ide_agent::plugins::projected_memory_entries(&plug_states);
let entries =
ide_agent::memory::discover_memories_with_plugins(&policy.workspace_roots, home.as_deref(), projected);
Ok(ide_agent::memory::resolve_catalog(entries, None, &policy, home.as_deref()))
})
.await
@@ -1852,6 +1928,307 @@ pub async fn agent_memory_reset_provider(host: &Host, window: &str, provider: St
current_memory_catalog(host, project.as_deref()).await
}
fn host_plugins_policy(host: &Host, project: Option<&crate::Project>) -> ide_agent::plugins::PluginsPolicy {
match project {
Some(project) => ide_agent::plugins::PluginsPolicy {
user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.plugins.clone(),
workspace: project.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.plugins.clone(),
workspace_trusted: project.trusted.load(std::sync::atomic::Ordering::Acquire),
workspace_roots: workspace_skill_roots(&project.root),
approved_capabilities: host.plugin_approvals.snapshot(),
},
None => ide_agent::plugins::PluginsPolicy {
user: host.global_settings.effective().agents.plugins.clone(),
workspace: Default::default(),
workspace_trusted: true,
workspace_roots: Vec::new(),
approved_capabilities: host.plugin_approvals.snapshot(),
},
}
}
fn plugins_settings_layers(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
) -> (AgentPluginSettings, Option<AgentPluginSettings>) {
let user = host.global_settings.effective().agents.plugins.clone();
let workspace =
project.map(|p| p.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.plugins.clone());
(user, workspace)
}
fn is_default_plugin_settings(s: &AgentPluginSettings) -> bool {
s.marketplaces.is_empty() && s.entries.is_empty()
}
fn persist_plugin_settings(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
scope: McpScope,
settings: &AgentPluginSettings,
) -> IdeResult<()> {
let value = if is_default_plugin_settings(settings) {
serde_json::Value::Null
} else {
serde_json::to_value(settings).map_err(|e| IdeError::invalid(e.to_string()))?
};
match scope {
McpScope::User => {
host.global_settings.set(ide_workspace::settings::SettingsScope::Global, "agents.plugins", value)?;
for p in host.projects() {
p.settings.reload();
p.agents.notify_mcp_servers_changed();
emit_plugin_projection_events(&p.sink);
}
}
McpScope::Workspace => {
let p = project.ok_or_else(|| IdeError::invalid("Open a project to configure workspace agent plugins"))?;
p.settings.set(ide_workspace::settings::SettingsScope::Project, "agents.plugins", value)?;
p.agents.notify_mcp_servers_changed();
emit_plugin_projection_events(&p.sink);
}
}
Ok(())
}
fn emit_plugin_projection_events(sink: &SharedSink) {
for key in ["agents.plugins", "agents.skills", "agents.mcpServers", "agents.memory"] {
sink.emit(IdeEvent::SettingsChanged { key: key.into() });
}
}
async fn current_plugins_catalog(host: &Host, project: Option<&crate::Project>) -> IdeResult<AgentPluginCatalog> {
let policy = host_plugins_policy(host, project);
let home = host.home_dir();
let secrets = host.agent_secrets.clone();
blocking(move || {
let discovered = ide_agent::plugins::discover_plugins(&policy.workspace_roots, home.as_deref());
Ok(ide_agent::plugins::resolve_catalog(discovered, &policy, home.as_deref(), Some(&*secrets)))
})
.await
}
/// Lists all discovered agent plugin bundles, registered/discovered marketplaces, and projection counts.
#[command(trust = always)]
pub async fn agent_plugins_list(host: &Host, window: &str) -> IdeResult<AgentPluginCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
current_plugins_catalog(host, project.as_deref()).await
}
/// Enables or disables an installed plugin in that harness's native configuration.
#[command(trust = always)]
pub async fn agent_plugins_set_enabled(
host: &Host,
window: &str,
id: String,
scope: McpScope,
enabled: bool,
approve_capabilities: bool,
capability_hash: Option<String>,
) -> IdeResult<AgentPluginCatalog> {
let id = id.trim().to_owned();
if id.is_empty() {
return Err(IdeError::invalid("Plugin ID is required"));
}
let project = host.project(window).ok().filter(|p| !p.light);
let project_root = project.as_ref().map(|p| p.root.clone());
let policy = host_plugins_policy(host, project.as_deref());
let home = host.home_dir();
let lookup_id = id.clone();
let home_for_discovery = home.clone();
let found_plugin = blocking(move || {
let discovered = ide_agent::plugins::discover_plugins(&policy.workspace_roots, home_for_discovery.as_deref());
// Ids are owner-qualified and stable, so only an exact match may be toggled.
Ok(discovered.into_iter().find(|p| p.scope == scope && p.id == lookup_id))
})
.await?;
let plugin = found_plugin.ok_or_else(|| IdeError::not_found(format!("Plugin `{id}` not found")))?;
if plugin.scope == McpScope::Workspace {
host.require_trust(window)?;
}
let approval_key = ide_agent::plugins::capability_approval_key(&plugin);
let already_approved = approval_key.as_ref().is_some_and(|key| host.plugin_approvals.snapshot().contains(key));
if enabled && plugin.capabilities.requires_consent && !approve_capabilities && !already_approved {
return Err(IdeError::invalid("Approve the plugin's executable capabilities before enabling it"));
}
if approve_capabilities && let Some(key) = approval_key {
// Approve only the capabilities the user was shown; re-inspection may have found others.
if capability_hash.as_deref() != plugin.capabilities.capability_hash.as_deref() {
return Err(IdeError::invalid(
"The plugin's executable capabilities changed since they were shown; review them again",
));
}
host.plugin_approvals.approve(key)?;
}
let plugin_for_write = plugin.clone();
let home_for_write = home.clone();
blocking(move || {
ide_agent::plugins::set_plugin_enabled(
&plugin_for_write,
enabled,
home_for_write.as_deref(),
project_root.as_deref(),
)
})
.await?;
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
emit_plugin_projection_events(&p.sink);
}
current_plugins_catalog(host, project.as_deref()).await
}
/// Registers a marketplace source (`owner/repo[#ref]`, GitHub URL, or local path) in `scope`.
#[command(trust = always)]
pub async fn agent_plugins_add_marketplace(
host: &Host,
window: &str,
scope: McpScope,
source: String,
) -> IdeResult<AgentPluginCatalog> {
let clean = source.trim().to_owned();
if clean.is_empty() {
return Err(IdeError::invalid("Enter a marketplace repository or local path"));
}
if scope == McpScope::Workspace {
host.require_trust(window)?;
}
let project = host.project(window).ok().filter(|p| !p.light);
let (mut user, mut workspace) = plugins_settings_layers(host, project.as_ref());
let target = match scope {
McpScope::User => &mut user,
McpScope::Workspace => {
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace marketplaces"))?
}
};
if !target.marketplaces.iter().any(|m| m == &clean) {
target.marketplaces.push(clean);
let to_save = target.clone();
persist_plugin_settings(host, project.as_ref(), scope, &to_save)?;
}
current_plugins_catalog(host, project.as_deref()).await
}
/// Removes a registered marketplace source from `scope`.
#[command(trust = always)]
pub async fn agent_plugins_remove_marketplace(
host: &Host,
window: &str,
scope: McpScope,
source: String,
) -> IdeResult<AgentPluginCatalog> {
let clean = source.trim();
if scope == McpScope::Workspace {
host.require_trust(window)?;
}
let project = host.project(window).ok().filter(|p| !p.light);
let (mut user, mut workspace) = plugins_settings_layers(host, project.as_ref());
let target = match scope {
McpScope::User => &mut user,
McpScope::Workspace => {
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace marketplaces"))?
}
};
let before = target.marketplaces.len();
target.marketplaces.retain(|m| m != clean);
if target.marketplaces.len() != before {
let to_save = target.clone();
persist_plugin_settings(host, project.as_ref(), scope, &to_save)?;
}
current_plugins_catalog(host, project.as_deref()).await
}
/// Browses installable plugins inside a marketplace (`owner/repo[#ref]`, GitHub URL, or local directory/manifest).
#[command(trust = always)]
pub async fn agent_plugins_browse_marketplace(
host: &Host,
window: &str,
source: String,
request: RequestId,
) -> IdeResult<AgentMarketplaceBrowseResult> {
let cancel = host.begin_request(request);
let ws_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
let home = host.home_dir();
let search_path = ide_core::tool_path::search_path();
let res = blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::plugins::browse_marketplace(&fetcher, &source, home.as_deref(), ws_root.as_deref(), &cancel)
})
.await;
host.end_request(request);
res
}
/// Previews an agent plugin bundle from GitHub or a local folder before installation, scanning files and capabilities.
#[command(trust = always)]
pub async fn agent_plugins_preview(
host: &Host,
window: &str,
source: String,
subpath: Option<String>,
marketplace: Option<String>,
request: RequestId,
) -> IdeResult<AgentPluginPreview> {
let cancel = host.begin_request(request);
let ws_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
let home = host.home_dir();
let search_path = ide_core::tool_path::search_path();
let res = blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::plugins::preview_plugin(
&fetcher,
&source,
subpath.as_deref(),
marketplace.as_deref(),
home.as_deref(),
ws_root.as_deref(),
&cancel,
)
})
.await;
host.end_request(request);
res
}
/// Atomically installs a previewed agent plugin into the selected harness's native plugin directory.
#[command(trust = always)]
pub async fn agent_plugins_install(
host: &Host,
window: &str,
input: InstallAgentPluginRequest,
request: RequestId,
) -> IdeResult<AgentPluginCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
if input.scope == McpScope::Workspace || input.source_kind == "local" {
host.require_trust(window)?;
}
let ws_root = project.as_ref().map(|p| p.root.clone());
let home = host.home_dir();
let cancel = host.begin_request(request);
let search_path = ide_core::tool_path::search_path();
let req_clone = input.clone();
let install_res = blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::plugins::install_plugin(&fetcher, &req_clone, home.as_deref(), ws_root.as_deref(), &cancel)
})
.await;
host.end_request(request);
let (_, approval_key) = install_res?;
if input.approve_capabilities
&& let Some(key) = approval_key
{
host.plugin_approvals.approve(key)?;
}
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
emit_plugin_projection_events(&p.sink);
}
current_plugins_catalog(host, project.as_deref()).await
}
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());
@@ -1869,6 +2246,312 @@ fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::P
Err(IdeError::invalid("Agent project must be the window project or a workspace member"))
}
// ---------------------------------------------------------------------------
// Agent Automations & In-Session Schedules
// ---------------------------------------------------------------------------
fn host_label_for(remote: bool) -> String {
std::env::var("HOSTNAME")
.ok()
.filter(|s| !s.trim().is_empty())
.unwrap_or_else(|| if remote { "Remote Server".into() } else { "Local Host".into() })
}
fn window_automation_scope(host: &Host, window: &str) -> (Option<Vec<std::path::PathBuf>>, bool) {
if let Some(p) = host.project(window).ok().filter(|p| !p.light) {
let trusted = host.trust.window_trusted(&p.root).unwrap_or(false);
let mut roots = vec![dunce::canonicalize(&p.root).unwrap_or_else(|_| p.root.clone())];
if let Ok(Some(ws)) = ide_workspace::workspace::Workspace::load(&p.root) {
for member in ws.projects {
let canon = dunce::canonicalize(&member).unwrap_or(member);
if !roots.contains(&canon) {
roots.push(canon);
}
}
}
(Some(roots), trusted)
} else {
(Some(Vec::new()), true)
}
}
fn require_window_trust_if_project(host: &Host, window: &str) -> IdeResult<()> {
if let Some(p) = host.project(window).ok().filter(|p| !p.light) {
p.require_trust()?;
}
Ok(())
}
fn ensure_window_owns_automation(host: &Host, window: &str, id: &str) -> IdeResult<AgentAutomation> {
require_window_trust_if_project(host, window)?;
let auto = host.automations.get(id).ok_or_else(|| IdeError::not_found(format!("unknown automation '{id}'")))?;
let (allowed_roots, include_chat_only) = window_automation_scope(host, window);
if let Some(roots) = allowed_roots {
match &auto.workspace {
AutomationWorkspace::ChatOnly if include_chat_only => {}
AutomationWorkspace::ChatOnly => {
return Err(IdeError::invalid("Trust the project before accessing automations"));
}
AutomationWorkspace::Project { root, .. } => {
let cand = dunce::canonicalize(&root.0).unwrap_or_else(|_| root.0.clone());
if !roots.contains(&cand) {
return Err(IdeError::invalid("Automation belongs to a different project"));
}
}
}
}
Ok(auto)
}
fn ensure_window_owns_session_schedule(host: &Host, window: &str, id: &str) -> IdeResult<()> {
host.require_trust(window)?;
let (allowed_roots, _) = window_automation_scope(host, window);
if let Some(roots) = allowed_roots {
let schedules = host.automations.list_session_schedules_scoped(Some(&roots), None);
if !schedules.iter().any(|s| s.id == id) {
return Err(IdeError::not_found(format!("unknown session schedule '{id}'")));
}
}
Ok(())
}
/// Returns the current project's automations, first page of run history, active session schedules,
/// and scheduler/boot-service status.
#[command(trust = always)]
pub async fn agent_automation_snapshot(
host: &std::sync::Arc<Host>,
window: &str,
remote: bool,
) -> IdeResult<AutomationSnapshot> {
let (allowed_roots, include_chat_only) = window_automation_scope(host, window);
let h = host.clone();
host.blocking(move || {
Ok(h.automations.snapshot_scoped(
&h,
allowed_roots.as_deref(),
include_chat_only,
remote,
host_label_for(remote),
))
})
.await
}
/// Creates or updates an [`AgentAutomation`]. Project-scoped automations require a trusted project.
#[command(trust = trusted)]
pub async fn agent_automation_save(
host: &std::sync::Arc<Host>,
window: &str,
mut input: SaveAutomationInput,
) -> IdeResult<AgentAutomation> {
require_window_trust_if_project(host, window)?;
if let Some(existing_id) = input.id.as_deref() {
let _ = ensure_window_owns_automation(host, window, existing_id)?;
}
if let AutomationWorkspace::Project { root, isolation, base, auto_clean_worktree } = input.workspace {
let project = host.project(window).ok().filter(|p| !p.light);
let validated = match &project {
Some(p) => {
p.require_trust()?;
validate_project_root(&p.root, Some(&root.0))?
}
None => {
if !host.trust.window_trusted(&root.0)? {
return Err(IdeError::invalid("Trust the project before creating an automation in it"));
}
dunce::canonicalize(&root.0)?
}
};
input.workspace =
AutomationWorkspace::Project { root: IpcPath(validated), isolation, base, auto_clean_worktree };
}
let h = host.clone();
host.blocking(move || h.automations.save(&h, input)).await
}
/// Enables or pauses an automation schedule.
#[command(trust = trusted)]
pub async fn agent_automation_set_enabled(
host: &std::sync::Arc<Host>,
window: &str,
id: String,
enabled: bool,
) -> IdeResult<AgentAutomation> {
let _ = ensure_window_owns_automation(host, window, &id)?;
let h = host.clone();
host.blocking(move || h.automations.set_enabled(&h, &id, enabled)).await
}
/// Pauses all enabled schedules (for the current window's project, or across all projects when `all_projects` is true).
#[command(trust = trusted)]
pub async fn agent_automation_pause_all(
host: &std::sync::Arc<Host>,
window: &str,
all_projects: bool,
) -> IdeResult<u32> {
require_window_trust_if_project(host, window)?;
let (allowed_roots, include_chat_only) =
if all_projects { (None, true) } else { window_automation_scope(host, window) };
let h = host.clone();
host.blocking(move || h.automations.pause_all_scoped(&h, allowed_roots.as_deref(), include_chat_only)).await
}
/// Deletes an automation and its run history entries.
#[command(trust = trusted)]
pub async fn agent_automation_delete(host: &std::sync::Arc<Host>, window: &str, id: String) -> IdeResult<()> {
let _ = ensure_window_owns_automation(host, window, &id)?;
let h = host.clone();
host.blocking(move || h.automations.delete(&h, &id)).await
}
/// Immediately triggers a manual run of automation `id`.
#[command(trust = trusted)]
pub async fn agent_automation_run_now(
host: &std::sync::Arc<Host>,
window: &str,
id: String,
) -> IdeResult<AutomationRun> {
let _ = ensure_window_owns_automation(host, window, &id)?;
host.automations.clone().run_now(host, &id).await
}
/// Lists paginated automation run history.
#[command(trust = always)]
pub async fn agent_automation_runs(
host: &std::sync::Arc<Host>,
window: &str,
automation_id: Option<String>,
cursor: Option<u32>,
limit: Option<u32>,
) -> IdeResult<AutomationRunsPage> {
let (allowed_roots, include_chat_only) = window_automation_scope(host, window);
let h = host.clone();
host.blocking(move || {
Ok(h.automations.runs_scoped(
allowed_roots.as_deref(),
include_chat_only,
automation_id.as_deref(),
cursor,
limit,
))
})
.await
}
/// Marks one run, one automation's runs, or all runs in the current window's scope as read.
#[command(trust = trusted)]
pub async fn agent_automation_mark_read(
host: &std::sync::Arc<Host>,
window: &str,
run_id: Option<String>,
automation_id: Option<String>,
) -> IdeResult<()> {
require_window_trust_if_project(host, window)?;
let (allowed_roots, include_chat_only) = window_automation_scope(host, window);
let h = host.clone();
host.blocking(move || {
h.automations.mark_read_scoped(
&h,
allowed_roots.as_deref(),
include_chat_only,
run_id.as_deref(),
automation_id.as_deref(),
)
})
.await
}
/// Previews the next `count` firing timestamps (epoch ms) for a schedule trigger.
#[command(trust = always)]
pub async fn agent_automation_preview_schedule(
host: &std::sync::Arc<Host>,
trigger: AutomationTrigger,
count: Option<u32>,
) -> IdeResult<Vec<f64>> {
let h = host.clone();
host.blocking(move || h.automations.preview_schedule(&trigger, count)).await
}
/// Exports automation `id` into portable `.automation.md` text.
#[command(trust = trusted)]
pub async fn agent_automation_export_markdown(
host: &std::sync::Arc<Host>,
window: &str,
id: String,
) -> IdeResult<String> {
let _ = ensure_window_owns_automation(host, window, &id)?;
let h = host.clone();
host.blocking(move || h.automations.export_markdown(&id)).await
}
/// Imports a `.automation.md` template into the current project (or as ChatOnly) with `enabled = false`.
#[command(trust = trusted)]
pub async fn agent_automation_import_markdown(
host: &std::sync::Arc<Host>,
window: &str,
markdown: String,
chat_only: bool,
provider: String,
) -> IdeResult<AgentAutomation> {
require_window_trust_if_project(host, window)?;
let workspace = if chat_only {
AutomationWorkspace::ChatOnly
} else {
host.require_trust(window)?;
let project = host.project(window)?;
AutomationWorkspace::Project {
root: IpcPath(project.root.clone()),
isolation: Isolation::Worktree,
base: None,
auto_clean_worktree: true,
}
};
let h = host.clone();
host.blocking(move || h.automations.import_markdown(&h, &markdown, workspace, provider)).await
}
/// Attaches a `Send Later` one-shot or `/loop` recurring schedule to an existing task session.
#[command(trust = trusted)]
pub async fn agent_session_schedule_create(
host: &std::sync::Arc<Host>,
window: &str,
input: CreateSessionScheduleInput,
) -> IdeResult<SessionSchedule> {
host.require_trust(window)?;
let project = host.project(window)?;
let root = project.root.clone();
let h = host.clone();
host.blocking(move || h.automations.create_session_schedule(&h, root, input)).await
}
/// Pauses or resumes an in-session `/loop` or `Send Later` schedule.
#[command(trust = trusted)]
pub async fn agent_session_schedule_set_paused(
host: &std::sync::Arc<Host>,
window: &str,
id: String,
paused: bool,
) -> IdeResult<SessionSchedule> {
ensure_window_owns_session_schedule(host, window, &id)?;
let h = host.clone();
host.blocking(move || h.automations.set_session_schedule_paused(&h, &id, paused)).await
}
/// Sends a queued `Send Later` prompt or fires a `/loop` iteration immediately.
#[command(trust = trusted)]
pub async fn agent_session_schedule_run_now(host: &std::sync::Arc<Host>, window: &str, id: String) -> IdeResult<()> {
ensure_window_owns_session_schedule(host, window, &id)?;
host.automations.clone().run_session_schedule_now(host, &id).await
}
/// Cancels and deletes an in-session `Send Later` or `/loop` schedule.
#[command(trust = trusted)]
pub async fn agent_session_schedule_delete(host: &std::sync::Arc<Host>, window: &str, id: String) -> IdeResult<()> {
ensure_window_owns_session_schedule(host, window, &id)?;
let h = host.clone();
host.blocking(move || h.automations.delete_session_schedule(&h, &id)).await
}
#[cfg(test)]
mod tests {
use super::*;
@@ -2111,6 +2794,17 @@ ide_command::domain!(
agent_context_usage,
agent_changes,
agent_cli_update,
agent_automation_delete,
agent_automation_export_markdown,
agent_automation_import_markdown,
agent_automation_mark_read,
agent_automation_pause_all,
agent_automation_preview_schedule,
agent_automation_run_now,
agent_automation_runs,
agent_automation_save,
agent_automation_set_enabled,
agent_automation_snapshot,
agent_cli_update_check,
agent_commands,
agent_copilot_auth_status,
@@ -2143,6 +2837,13 @@ ide_command::domain!(
agent_memory_reset_provider,
agent_memory_set_auto,
agent_memory_set_mode,
agent_plugins_add_marketplace,
agent_plugins_browse_marketplace,
agent_plugins_install,
agent_plugins_list,
agent_plugins_preview,
agent_plugins_remove_marketplace,
agent_plugins_set_enabled,
agent_poke_network,
agent_preview_copilot_models,
agent_probe,
@@ -2160,6 +2861,10 @@ ide_command::domain!(
agent_rollback,
agent_rollback_changes,
agent_send_queued_now,
agent_session_schedule_create,
agent_session_schedule_delete,
agent_session_schedule_run_now,
agent_session_schedule_set_paused,
agent_set_additional_args,
agent_set_auto_resume_once,
agent_set_command,
+149 -4
Переглянути файл
@@ -201,6 +201,143 @@ pub async fn build_model(host: &Host, window: &str) -> IdeResult<BuildModel> {
blocking(move || workspace::load_project(&project, &config)).await
}
/// Settings › CMake and the toolbar switcher: every profile, saved ones then presets (with
/// whether each is enabled), and why the presets file cannot be read, if it cannot.
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct CMakeProfileList {
pub profiles: Vec<ide_core::settings::CMakeProfile>,
pub presets_error: Option<String>,
}
/// Reading the profiles runs nothing, so an untrusted project lists them too.
#[command(trust = always)]
pub async fn cmake_profiles(host: &Host, window: &str) -> IdeResult<CMakeProfileList> {
let project = host.project(window)?;
let (root, settings) = (project.root.clone(), project.settings.effective());
blocking(move || {
let presets_error = if settings.cmake.ignore_presets { None } else { ide_run::cmake_presets(&root).err() };
Ok(CMakeProfileList { profiles: ide_run::cmake_listed_profiles(&root, &settings.cmake), presets_error })
})
.await
}
/// Settings › CMake › Cache variables: the `CMakeCache.txt` of `build_dir` (relative to the
/// project, or absolute), empty while that directory is not configured. Reading runs nothing.
#[command(trust = always)]
pub async fn cmake_cache(
host: &Host,
window: &str,
build_dir: String,
) -> IdeResult<Vec<ide_run::cmake_cache::CacheEntry>> {
let root = host.project(window)?.root.clone();
blocking(move || {
let cache = root.join(build_dir.trim()).join("CMakeCache.txt");
Ok(std::fs::read_to_string(cache).map(|text| ide_run::cmake_cache::parse(&text)).unwrap_or_default())
})
.await
}
/// One tool of a toolchain as Settings › Toolchains shows it: the executable used (chosen, from the
/// MinGW directory, else found on `PATH`) and its version, or why it cannot be used.
#[derive(Clone, Debug, Default, serde::Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct ToolCheck {
pub path: Option<String>,
pub version: Option<String>,
pub problem: Option<String>,
}
/// Each tool of a toolchain, keyed as the toolchain's fields (`cmake`, `buildTool`, `cCompiler`,
/// `cxxCompiler`, `debugger`).
pub type ToolchainCheck = std::collections::BTreeMap<String, ToolCheck>;
async fn check_tool(path: Option<std::path::PathBuf>) -> ToolCheck {
let Some(path) = path else {
return ToolCheck { problem: Some("Not found".into()), ..Default::default() };
};
let shown = Some(path.to_string_lossy().into_owned());
if !path.is_file() {
return ToolCheck { path: shown, problem: Some("Not found".into()), ..Default::default() };
}
let mut command = tokio::process::Command::new(&path);
command.arg("--version").stdin(std::process::Stdio::null()).kill_on_drop(true);
ide_core::process::prepare(command.as_std_mut());
match tokio::time::timeout(std::time::Duration::from_secs(5), command.output()).await {
Ok(Ok(output)) => {
let text = String::from_utf8_lossy(&output.stdout).into_owned() + &String::from_utf8_lossy(&output.stderr);
let version = text.lines().map(str::trim).find(|l| !l.is_empty()).map(String::from);
ToolCheck { path: shown, version, problem: None }
}
Ok(Err(e)) => ToolCheck { path: shown, problem: Some(e.to_string()), ..Default::default() },
Err(_) => ToolCheck { path: shown, problem: Some("No answer to --version".into()), ..Default::default() },
}
}
/// Settings › Toolchains: which executable each tool of `toolchain` resolves to, and its version.
/// Only `--version` runs; the settings are IDE-wide, so no project needs to be trusted.
#[command(trust = always)]
pub async fn toolchain_check(toolchain: ide_core::settings::Toolchain) -> IdeResult<ToolchainCheck> {
let tools = ide_run::cmake_toolchain::tools(&toolchain);
let chosen = |key: &str| -> Option<std::path::PathBuf> {
match key {
"cmake" => tools.cmake.clone(),
"buildTool" => tools.build_tool.clone().map(Into::into),
"cCompiler" => tools.c_compiler.clone().map(Into::into),
"cxxCompiler" => tools.cxx_compiler.clone().map(Into::into),
_ => tools.debugger.clone(),
}
};
let search = match &tools.path {
Some(bin) => std::env::join_paths(
std::iter::once(bin.clone()).chain(std::env::split_paths(&ide_core::tool_path::search_path())),
)
.unwrap_or_else(|_| ide_core::tool_path::search_path()),
None => ide_core::tool_path::search_path(),
};
let mut out = ToolchainCheck::new();
for (key, names) in ide_run::cmake_toolchain::FALLBACKS {
let path = chosen(key)
.map(|p| {
// A bare name ("clang++") is looked up like CMake would.
if p.components().count() == 1 {
ide_core::process::find_executable(&p.to_string_lossy(), &search).unwrap_or(p)
} else {
p
}
})
.or_else(|| names.iter().find_map(|n| ide_core::process::find_executable(n, &search)));
out.insert(key.into(), check_tool(path).await);
}
Ok(out)
}
/// Settings › Toolchains: a toolchain for each MinGW / MSYS2 install found (Windows).
#[command(trust = always)]
pub async fn toolchains_detect() -> IdeResult<Vec<ide_core::settings::Toolchain>> {
blocking(|| {
Ok(ide_run::cmake_toolchain::detect_mingw()
.into_iter()
.map(|dir| {
let name = match dir.parent().and_then(|p| p.file_name()) {
// MSYS2 environments: "MSYS2 ucrt64".
Some(parent) if parent.to_string_lossy().starts_with("msys") => {
format!("MSYS2 {}", dir.file_name().unwrap_or_default().to_string_lossy())
}
_ => format!("MinGW ({})", dir.display()),
};
ide_core::settings::Toolchain {
name,
kind: ide_core::settings::ToolchainKind::MinGw,
path: dir.to_string_lossy().into_owned(),
..Default::default()
}
})
.collect())
})
.await
}
fn linked_gradle_paths(
root: &Path,
settings: &ide_core::settings::GradleSettings,
@@ -1023,7 +1160,7 @@ pub async fn build_run(
&model,
kind,
file.as_deref(),
settings.cmake.profiles.as_deref(),
ide_run::cmake_profiles(&root, &settings.cmake, &settings.toolchains).as_deref(),
None,
&token,
)?,
@@ -1071,7 +1208,7 @@ pub async fn build_run(
&model,
kind,
file.as_deref(),
settings.cmake.profiles.as_deref(),
ide_run::cmake_profiles(member, &settings.cmake, &settings.toolchains).as_deref(),
None,
&token,
)?,
@@ -1094,7 +1231,7 @@ pub async fn build_run(
&model,
kind,
file.as_deref(),
settings.cmake.profiles.as_deref(),
ide_run::cmake_profiles(&root, &settings.cmake, &settings.toolchains).as_deref(),
Some(&cache),
&token,
) {
@@ -1314,7 +1451,11 @@ mod build_tool_settings_tests {
let configure = config("configure", &["-S", ".", "-B", "release", "-G", "Ninja"]);
let mut build =
config("target", &["--build", "release", "--target", "hello", "--config", "Release", "-j", "8"]);
build.extras.before_launch.push(ide_run::BeforeLaunchTask { kind: "build".into(), target: "configure".into() });
build.extras.before_launch.push(ide_run::BeforeLaunchTask {
kind: "build".into(),
target: "configure".into(),
..Default::default()
});
let configs = [configure, build];
for kind in [BuildKind::Build, BuildKind::Rebuild] {
let plan = cmake_plan(root.path(), kind, &configs, "target").unwrap();
@@ -1683,6 +1824,8 @@ ide_command::domain!(
build_model,
build_run,
build_sync,
cmake_cache,
cmake_profiles,
gradle_dependencies,
gradle_link_projects,
gradle_published_catalog,
@@ -1692,4 +1835,6 @@ ide_command::domain!(
maven_exclude_dependency,
maven_goto_declaration,
maven_managed_declarations,
toolchain_check,
toolchains_detect,
);
+22 -3
Переглянути файл
@@ -1,13 +1,15 @@
mod kotlin;
#[cfg(test)]
mod kotlin_tests;
#[cfg(test)]
mod native_tests;
mod output;
use crate::Host;
use ide_command::command;
use ide_core::{DebugSessionId, IdeResult};
use ide_dap::*;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
/// Starts a session owned by this window: its events (and those of child sessions) go here only.
#[command(trust = trusted)]
@@ -143,8 +145,10 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
// No lldb-dap on this host (most Linux hosts): CodeLLDB, else GDB 14+.
if config.adapter == "lldb-dap" {
let (root, settings) = (root.clone(), settings.clone());
let project_root = project.root.clone();
config = ide_dap::native::choose(config, move |command| {
ide_sdk::apply::tool_command(&root, &settings, command)
native_debugger_command(&project_root, &settings.debugger.cpp, command)
.or_else(|| ide_sdk::apply::tool_command(&root, &settings, command))
.or_else(|| ide_dap::adapter::resolve_binary(command, &root))
})
.await?;
@@ -161,11 +165,13 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
.await?;
}
let java_analyzer = java_analyzer_command(host, window, &config)?;
let native = native_debugger_command(&project.root, &settings.debugger.cpp, &config.adapter);
let custom = |command: &str| {
if let Some(binary) = java_analyzer {
return Some(binary.to_string_lossy().into_owned());
}
let path = ide_sdk::apply::tool_command(&root, &settings, command)
let path = native
.or_else(|| ide_sdk::apply::tool_command(&root, &settings, command))
.or_else(|| ruby_tools.into_iter().find(|(name, _)| *name == command).map(|(_, path)| path))?;
Some(path.to_string_lossy().into_owned())
};
@@ -197,6 +203,19 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
result
}
fn native_debugger_command(
root: &Path,
settings: &ide_core::settings::CppDebuggerSettings,
adapter: &str,
) -> Option<PathBuf> {
let path = match adapter {
"gdb" => &settings.gdb_executable,
"lldb-dap" => &settings.lldb_dap_executable,
_ => return None,
};
ide_sdk::apply::setting_path(root, path)
}
/// For java-analyzer's debugger, the executable of the java-analyzer serving the module
/// (`projectRoot`, else the working directory), so the session debugs with the server that
/// analyzes the code.
+63
Переглянути файл
@@ -0,0 +1,63 @@
use super::*;
use ide_core::IdeError;
use ide_dap::adapter::{AdapterLauncher, AdapterSpec, LaunchFuture};
use ide_workspace::SettingsScope;
use parking_lot::Mutex;
use std::sync::Arc;
#[derive(Default)]
struct CaptureAdapter(Mutex<Option<AdapterSpec>>);
impl AdapterLauncher for CaptureAdapter {
fn launch(&self, spec: AdapterSpec, _: Option<u16>) -> LaunchFuture {
*self.0.lock() = Some(spec);
Box::pin(async { Err(IdeError::cancelled()) })
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn cpp_debugger_paths_override_adapter_commands() {
let dir = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(dir.path()).unwrap();
let root = base.join("project");
let cwd = root.join("build");
std::fs::create_dir_all(&cwd).unwrap();
let capture = Arc::new(CaptureAdapter::default());
let mut host = Host::new(crate::HostConfig::for_test(&base));
host.debugger = DebugManager::with_launcher(host.languages.clone(), capture.clone());
host.open_project("main", &root).unwrap();
host.set_project_trust(&root, true, false).await.unwrap();
let project = host.project("main").unwrap();
for (adapter, key, configured) in [
("gdb", "gdbExecutable", root.join("custom gdb").to_str().unwrap().to_owned()),
("lldb-dap", "lldbDapExecutable", "tools/lldb-dap-custom".into()),
] {
let config = LaunchConfig {
name: "C++".into(),
adapter: adapter.into(),
request: "attach".into(),
program: None,
args: vec![],
cwd: Some(cwd.clone().into()),
env: Default::default(),
extra_json: Some(r#"{"pid":1}"#.into()),
};
let _ = debug_start(&host, "main", config.clone()).await.unwrap_err();
assert_eq!(capture.0.lock().take().unwrap().command, adapter);
project
.settings
.set(SettingsScope::Project, &format!("debugger.cpp.{key}"), serde_json::json!(configured))
.unwrap();
let mut config = config;
config.request = "launch".into();
config.program = Some(cwd.join("app").to_str().unwrap().to_owned());
config.extra_json = None;
let _ = debug_start(&host, "main", config).await.unwrap_err();
let spec = capture.0.lock().take().unwrap();
assert_eq!(spec.adapter, adapter);
assert_eq!(Path::new(&spec.command), root.join(configured));
assert_eq!(spec.cwd, cwd);
}
}
+1
Переглянути файл
@@ -160,6 +160,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
let syntax = syntax();
ide_language::merge_visibility(&mut items, &syntax);
ide_language::merge_kinds(&mut items, &syntax);
ide_language::merge_impl_traits(&mut items, &syntax);
}
items
}
+162 -7
Переглянути файл
@@ -15,6 +15,52 @@ pub async fn fs_entry_kind(host: &Host, path: PathBuf) -> IdeResult<ide_vfs::Ent
.await
}
/// Rejects relative paths and any `..` parent traversal without touching the filesystem.
fn reject_parent_traversal(path: &Path) -> Option<PathBuf> {
use std::path::Component;
if !path.is_absolute() {
return None;
}
let mut out = PathBuf::new();
for comp in path.components() {
match comp {
Component::Prefix(p) => out.push(p.as_os_str()),
Component::RootDir => out.push(comp.as_os_str()),
Component::CurDir => {}
Component::ParentDir => return None,
Component::Normal(c) => out.push(c),
}
}
Some(out)
}
/// Resolves symlinks for a path inside the window's project roots and returns its canonical path.
/// Rejects relative paths, `..` parent traversal, and paths outside those roots before touching
/// the filesystem, and rejects symlink targets that canonicalize outside those roots.
#[command(trust = always)]
pub async fn fs_canonicalize(host: &Host, window: &str, path: PathBuf) -> IdeResult<ide_core::IpcPath> {
let project = host.project(window)?;
host.blocking(move || {
let Some(clean) = reject_parent_traversal(&path) else {
return Err(IdeError::invalid(format!("{}: outside the project", path.display())));
};
let raw_roots: Vec<PathBuf> = std::iter::once(project.root.clone()).chain(project.content_roots()).collect();
let canonical_roots: Vec<PathBuf> = raw_roots.iter().filter_map(|r| dunce::canonicalize(r).ok()).collect();
let mut allowed_lexical: Vec<PathBuf> = raw_roots.iter().filter_map(|r| reject_parent_traversal(r)).collect();
allowed_lexical.extend(canonical_roots.iter().cloned());
if !inside_any_root(&clean, &allowed_lexical) {
return Err(IdeError::invalid(format!("{}: outside the project", path.display())));
}
let real = dunce::canonicalize(&clean)
.map_err(|_| IdeError::not_found(format!("{}: no such file", path.display())))?;
if !inside_any_root(&real, &canonical_roots) {
return Err(IdeError::invalid(format!("{}: outside the project", path.display())));
}
Ok(real.into())
})
.await
}
#[command(trust = always)]
pub async fn fs_compare_directories(
host: &Host,
@@ -243,12 +289,26 @@ pub fn fs_scratches_dir(host: &Host) -> IdeResult<ide_core::IpcPath> {
/// Toggle Read-only Attribute: sets the writable bit (and the open document's
/// state). Returns whether the file is read-only now.
/// Off the main thread: opening a file for edit can ask a server (`svn lock`, `p4 edit`) and
/// wait for a login.
#[command(trust = always)]
pub fn fs_set_writable(host: &Host, window: &str, path: PathBuf, writable: bool) -> IdeResult<bool> {
match host.project(window) {
Ok(p) => p.documents.set_writable(&path, writable),
Err(_) => ide_vfs::set_writable(&path, writable).map(|()| !writable),
}
pub async fn fs_set_writable(host: &Host, window: &str, path: PathBuf, writable: bool) -> IdeResult<bool> {
let project = host.project(window).ok();
host.blocking(move || match project {
Some(p) => {
// A checkout backend keeps files read-only until opened for edit (`p4 edit`), so
// its server learns about the change to come. `backend_of` is empty unless trusted.
if writable
&& let Some(backend) = p.backend_of(&path)
&& backend.open_for_edit(std::slice::from_ref(&path))?
{
p.vcs_changed();
}
p.documents.set_writable(&path, writable)
}
None => ide_vfs::set_writable(&path, writable).map(|()| !writable),
})
.await
}
/// Moving to the trash can take a while (large trees): kept off the main thread.
@@ -291,7 +351,47 @@ fn delete_recorded(project: Option<&Project>, path: &Path, undoable: bool) -> Id
#[command(trust = always)]
pub async fn fs_undo_delete(host: &Host, window: &str, undo: DeletionUndo) -> IdeResult<Vec<ide_core::IpcPath>> {
let project = host.project(window)?;
host.blocking(move || Ok(project.history.restore_deletion_undo(undo))).await
host.blocking(move || {
let wanted = undo.paths();
let skipped = project.history.restore_deletion_undo(undo);
// The Delete scheduled the files for deletion in a working copy (`files_deleted`): Undo
// takes that back, keeping the restored content. Git records deletions at commit time
// (a file it dropped from the index because it was only added comes back unversioned).
// One call per working copy: its first folder takes the tree below with it anyway.
let mut by_backend: Vec<(std::sync::Arc<dyn ide_vcs::Backend>, Vec<PathBuf>)> = Vec::new();
for path in wanted.iter().filter(|p| !skipped.iter().any(|s| s.0 == **p)) {
let Some(backend) = project.backend_of(path).filter(|b| b.kind() != ide_vcs::VcsKind::Git) else {
continue;
};
match by_backend.iter_mut().find(|(b, _)| b.root() == backend.root()) {
Some((_, paths)) => paths.push(path.clone()),
None => by_backend.push((backend, vec![path.clone()])),
}
}
for (backend, paths) in by_backend {
// The files are back either way; still scheduled for deletion, they would go at commit.
// Only the rows the Delete made deleted: an added or moved file it left as it was
// keeps its schedule (unstaging it would make it unversioned).
let deleted = backend.status_paths(&paths).map(|rows| {
rows.into_iter()
.filter(|f| f.unstaged == Some(ide_vcs::ChangeKind::Deleted) && f.path.0.exists())
.map(|f| f.path.0)
.collect::<Vec<_>>()
});
if let Err(e) =
deleted.and_then(|deleted| if deleted.is_empty() { Ok(()) } else { backend.unstage(&deleted) })
{
tracing::warn!("undo of delete in {}: {e}", backend.root().display());
project.sink.emit(ide_core::IdeEvent::Notify {
level: ide_core::event::NotifyLevel::Warning,
title: "The restored files are still scheduled for deletion".into(),
body: Some(e.message),
});
}
}
Ok(skipped)
})
.await
}
#[command(trust = always)]
@@ -367,7 +467,9 @@ pub(crate) fn inside_any_root(path: &Path, roots: &[PathBuf]) -> bool {
#[cfg(test)]
mod tests {
use super::inside_any_root;
use super::{fs_canonicalize, inside_any_root};
use crate::{Host, HostConfig};
use ide_core::error::ErrorKind;
use std::path::{Path, PathBuf};
#[test]
@@ -380,10 +482,63 @@ mod tests {
assert!(!inside_any_root(Path::new("/home/me/.ssh/id_rsa"), &roots));
assert!(!inside_any_root(Path::new("/work/spec.pdf"), &[]));
}
#[tokio::test]
async fn fs_canonicalize_enforces_window_project_roots() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let root = base.join("project");
let outside = base.join("outside");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&outside).unwrap();
let inside = root.join("guide.mdx");
std::fs::write(&inside, "# Guide").unwrap();
let secret = outside.join("secret.ts");
std::fs::write(&secret, "export const secret = 1;").unwrap();
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
host.open_project("main", &root).unwrap();
// Valid path inside the window's project root succeeds with its canonical path.
let resolved = fs_canonicalize(&host, "main", inside.clone()).await.unwrap();
assert_eq!(resolved.0, dunce::canonicalize(&inside).unwrap());
// Path outside the project (existing or nonexistent) is rejected with InvalidInput before touching disk.
let outside_existing = fs_canonicalize(&host, "main", secret.clone()).await.unwrap_err();
assert_eq!(outside_existing.kind, ErrorKind::InvalidInput);
let outside_missing = fs_canonicalize(&host, "main", outside.join("does-not-exist.ts")).await.unwrap_err();
assert_eq!(outside_missing.kind, ErrorKind::InvalidInput);
// Parent traversal (`..`) is rejected even when lexically inside the project root.
let traversal = fs_canonicalize(&host, "main", root.join("../outside/secret.ts")).await.unwrap_err();
assert_eq!(traversal.kind, ErrorKind::InvalidInput);
let in_root_parent = fs_canonicalize(&host, "main", root.join("sub/../guide.mdx")).await.unwrap_err();
assert_eq!(in_root_parent.kind, ErrorKind::InvalidInput);
// Symlink inside the project pointing outside (directly or via `..`) is rejected.
#[cfg(unix)]
{
let link = root.join("link.ts");
std::os::unix::fs::symlink(&secret, &link).unwrap();
let escaped = fs_canonicalize(&host, "main", link).await.unwrap_err();
assert_eq!(escaped.kind, ErrorKind::InvalidInput);
let dir_link = root.join("dir-link");
std::os::unix::fs::symlink(&outside, &dir_link).unwrap();
let symlink_parent =
fs_canonicalize(&host, "main", dir_link.join("../outside/secret.ts")).await.unwrap_err();
assert_eq!(symlink_parent.kind, ErrorKind::InvalidInput);
}
// Unknown window with no open project is rejected.
assert!(fs_canonicalize(&host, "other", inside).await.is_err());
}
}
ide_command::domain!(
fs:
fs_canonicalize,
fs_compare_directories,
fs_copy,
fs_copy_merge,
+41
Переглянути файл
@@ -246,6 +246,7 @@ pub(crate) async fn resolve_launch(
append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths));
}
info.class_paths = class_paths;
apply_maven_system_classpath(&mut info, root, &model, &module);
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
if build && !delegated {
match compile::process_launch_resources(root, &model, cache, &info.class_paths, &cancel) {
@@ -563,6 +564,9 @@ async fn resolve_launch_without_jdtls(
},
)?;
info.class_paths = class_paths;
if !by_service {
apply_maven_system_classpath(&mut info, root, &model, &module);
}
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
if cancel.is_cancelled() {
@@ -681,6 +685,15 @@ fn entry_key(path: &str, windows: bool) -> String {
if windows { key.to_lowercase() } else { key }
}
fn apply_maven_system_classpath(info: &mut JavaLaunchInfo, root: &Path, model: &BuildModel, module: &Path) {
for path in compile::maven_system_classpath(root, model, module) {
let path = path.to_string_lossy();
if !info.class_paths.iter().chain(&info.module_paths).any(|entry| same_entry(entry, &path, cfg!(windows))) {
info.class_paths.push(path.into_owned());
}
}
}
fn apply_library_classpath(
info: &mut JavaLaunchInfo,
root: &std::path::Path,
@@ -1275,6 +1288,34 @@ mod tests {
assert!(info.hints[0].contains("offline dependency"), "{:?}", info.hints);
}
#[test]
fn java_server_launch_classpath_includes_local_maven_system_jars() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let jar = ["src", "main", "resources", "lib", "offline.jar"].iter().fold(root.clone(), |p, c| p.join(c));
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
std::fs::write(&jar, "").unwrap();
std::fs::write(
root.join("pom.xml"),
r#"<project><groupId>demo</groupId><artifactId>app</artifactId><version>1</version>
<dependencies><dependency><groupId>local</groupId><artifactId>offline</artifactId><version>1</version>
<scope>system</scope><systemPath>${pom.basedir}/src/main/resources/lib/offline.jar</systemPath>
</dependency></dependencies></project>"#,
)
.unwrap();
let model = ide_build::load(&root, &root.join("cache"), None);
let jar = jar.to_string_lossy().into_owned();
let mut info = JavaLaunchInfo { class_paths: vec!["classes".into()], ..Default::default() };
apply_maven_system_classpath(&mut info, &root, &model, &root);
apply_maven_system_classpath(&mut info, &root, &model, &root);
assert_eq!(info.class_paths, ["classes", &jar]);
info.class_paths.pop();
info.module_paths.push(jar);
apply_maven_system_classpath(&mut info, &root, &model, &root);
assert_eq!(info.class_paths, ["classes"]);
}
/// Maven's launch classpath lists the module's and its reactor siblings' outputs, which
/// the launch already runs from a snapshot: listed twice, MyBatis loads each mapper XML
/// twice and fails with "XML fragments parsed from previous mappers already contains value".
+56 -9
Переглянути файл
@@ -722,16 +722,15 @@ pub async fn lsp_move_to_file_targets(
Ok(result?.into_iter().map(ide_core::IpcPath::from).collect())
}
/// Implementations of the symbols at `positions`, one list per position (the
/// editor's "is implemented / overridden" gutter markers). Cancel with
/// `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_implementations(
/// One `kind` of go-to request at each of `positions` (grouped by the document that answers
/// them), one list per position. Cancel with `cancel_request(request)`.
async fn goto_each(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
positions: Vec<Pos>,
kind: GotoKind,
positions: &[Pos],
) -> IdeResult<Vec<Vec<Location>>> {
let lsp = host.project(window)?.lsp.clone();
let (_, cancel) =
@@ -747,7 +746,7 @@ pub async fn lsp_implementations(
let (lsp, cancel) = (lsp.clone(), cancel.clone());
async move {
let positions: Vec<_> = entries.iter().map(|(_, p)| *p).collect();
(entries, lsp.implementations(target, &positions, cancel).await)
(entries, lsp.goto_each(kind, target, &positions, cancel).await)
}
}))
.await;
@@ -775,6 +774,21 @@ pub async fn lsp_implementations(
Err(error.expect("at least one request"))
};
host.end_request(request);
result
}
/// Implementations of the symbols at `positions`, one list per position (the
/// editor's "is implemented / overridden" gutter markers). Cancel with
/// `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_implementations(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
positions: Vec<Pos>,
) -> IdeResult<Vec<Vec<Location>>> {
let result = goto_each(host, window, request, doc, GotoKind::Implementation, &positions).await;
if let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Implementation) {
let count = positions.len();
let found = plugin_call(move || {
@@ -792,6 +806,21 @@ pub async fn lsp_implementations(
result
}
/// Go-to `kind` (declaration, definition) of the symbols at `positions`, one list per position:
/// the editor's "implements" gutter markers for languages without a type hierarchy (Rust).
/// Cancel with `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_gotos(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
kind: GotoKind,
positions: Vec<Pos>,
) -> IdeResult<Vec<Vec<Location>>> {
goto_each(host, window, request, doc, kind, &positions).await
}
/// Refines the implementations `targets` of the method at `pos` to their declarations (Java
/// dependencies' class files point at the start of the class). Cancel with
/// `cancel_request(request)`.
@@ -929,9 +958,14 @@ pub async fn lsp_library_sources(
#[command(trust = trusted)]
pub async fn lsp_resolve_class_file(host: &Host, window: &str, path: std::path::PathBuf) -> IdeResult<String> {
// Opens compiled classes through JDT as decompiled class documents.
let archive = ide_vfs::split_archive_path(&path);
host.project(window)?.lsp.java_class_file(&path, archive).await
host.project(window)?.lsp.java_class_file(&path, archive, read_internal_class_name(&path)).await
}
async fn read_internal_class_name(path: &Path) -> IdeResult<String> {
let bytes = tokio::fs::read(path).await?;
ide_build::jbuild::class_file_name(&bytes)
.ok_or_else(|| IdeError::not_found(format!("invalid class file: {}", path.display())))
}
/// References of the symbol at `pos`. `project_wide` also searches project files
@@ -2492,6 +2526,18 @@ pub fn plugin_formatters() -> IdeResult<Vec<crate::plugins::language_features::F
#[cfg(test)]
mod tests {
#[tokio::test]
async fn disk_class_name_comes_from_bytecode() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("moved.class");
// Class header, UTF-8 and Class constants, then access_flags and this_class.
let bytes = b"\xca\xfe\xba\xbe\0\0\0\x3d\0\x03\x01\0\x0d\x70/Outer$Inner\x07\0\x01\0\x21\0\x02";
std::fs::write(&path, bytes).unwrap();
assert_eq!(read_internal_class_name(&path).await.unwrap(), "p/Outer$Inner");
std::fs::write(&path, b"invalid").unwrap();
assert_eq!(read_internal_class_name(&path).await.unwrap_err().kind, ErrorKind::NotFound);
}
#[test]
fn a_plugin_offering_ghost_text_keeps_the_editor_asking() {
use super::*;
@@ -3385,6 +3431,7 @@ ide_command::domain!(
lsp_source_action_text,
lsp_goto,
lsp_goto_implementation,
lsp_gotos,
lsp_hierarchy_members,
lsp_hierarchy_refactor,
lsp_hover,
+2
Переглянути файл
@@ -45,6 +45,7 @@ pub mod settings_sync;
pub mod spell;
pub mod ssh;
pub mod stream_trace;
pub mod svn;
pub mod syntax;
pub mod term;
pub mod thread_dump;
@@ -133,6 +134,7 @@ ide_command::domains!(
search_commands: crate::ops::search::commands,
spell: crate::ops::spell,
ssh: crate::ops::ssh,
svn: crate::ops::svn,
stream_trace: crate::ops::stream_trace,
syntax: crate::ops::syntax,
term: crate::ops::term,
Loaded 100 of 1182 files, more files were not shown because too many files have changed in this diff. Show more