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

..
Автор 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
l0ng-ai b2d03ac5f0 fix(debugger): fall back to CodeLLDB or GDB when a C/C++ host has no lldb-dap (#7125)
CMake targets (and Swift packages) always launched lldb-dap. Most Linux hosts, remote ones included, have no lldb-dap on PATH, so Debug failed with a macOS-oriented install hint although GDB or an installable CodeLLDB would have worked.

- An lldb-dap launch uses lldb-dap when present (also Debian/Ubuntu's versioned lldb-dap-NN / lldb-vscode-NN and /usr/lib/llvm-NN/bin), else CodeLLDB, else GDB 14+, with the launch arguments rewritten for the chosen adapter.
- With none of them, the error says what was found (e.g. GDB 12.1 without DAP) and the notification offers Install CodeLLDB and Debug, which installs it on the project's host and debugs again.

Fixes #7001
2026-12-01 07:45:19 +08:00
l0ng-ai 4e735eadcb fix(java): recheck open files when Java sources change on disk (#7121)
When another tool rewrote an open Java file to call a class or method it added in another file, the open file kept a "cannot be resolved" error until it was reopened. jdtls rebuilds sources reported through workspace/didChangeWatchedFiles but does not re-reconcile the open working copies it already checked, so when the open file's reload reached it before the new class, the stale error stayed. After sending Java source changes to jdtls, the open documents are now sent again (resync_documents), so jdtls checks them against the new sources.

Fixes #6986
2026-12-01 07:03:06 +08:00
Deng Liuтаdengliu 50ba6b5c56 fix(agents): resolve VS Code Copilot session titles and search across all project sessions (#7118)
Copilot sessions started from VS Code got their titles from VS Code's Agent Host, which stores summaries and user renames in <user>/globalStorage/agent-host.db and does not write them back to workspace.yaml. The import list now reads that database read-only to resolve the titles, skipping unrenamed "New session" / "New Chat" placeholders. It also parses YAML block scalars (|, |-, >, >-) in workspace.yaml names instead of showing a literal "|-".

The backend now lists every session of the project. The Import Sessions dialog filters by title, folder or session ID before taking the 50 newest matches, so older sessions and sessions searched by ID can be found. The 50-session hint appears only when more sessions match.

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

Co-authored-by: dengliu <[email protected]>
2026-12-01 06:56:32 +08:00
l0ng-ai 36910712d1 fix(ci): run Language smoke when the inline background helper changes (#7120)
#7110 made src/editor/lsp/diagnostics.ts import src/editor/core/cm/inlineBg.ts. The frontend smoke loads diagnostics.ts, but the new import was missing from the workflow's trigger paths and from the Changes step's smoke pattern, so scripts/smoke-paths.test.ts failed on main. Add the file to both; only path filters change.
2026-12-01 06:55:29 +08:00
l0ng-ai 5b99b8b5ab fix(vcs): dim Git log metadata columns only for merge commits (#7119)
The User, Date and Hash cells in the Git log always used the muted color, while the subject is only dimmed for merge commits (Highlight > Merge Commits) and for commits outside the cherry-pick selection. The metadata cells now use the same condition, so a row is dimmed as a whole or not at all. My Commits still shows the author in bold.

Fixes #7112
2026-12-01 06:51:40 +08:00
koeriaтаkoeria f3874b9b2e fix(terminal): drop malformed env entries that break Windows PTY spawns (#7113)
Spawning a PTY on Windows failed when the inherited environment held malformed entries (names with '=' or empty names such as the per-drive '=C:' cwd variables), because the child block was rebuilt from them. The terminal, run processes and the debug adapter now rebuild the child environment after env_clear from spawnable_host_vars_in, which drops entries that cannot be passed to CreateProcess. On Unix this is equivalent to the previous behaviour.

Fixes #6806

Co-authored-by: koeria <[email protected]>
2026-12-01 06:31:32 +08:00
faysouтаfaysou 18b87b066b perf(markdown): update changed preview blocks (#7116)
Editing Markdown rebuilt the preview's whole DOM and restarted its viewport tracking. The preview now keeps unchanged blocks and graphics mounted and parses edits in a worker. When the Markdown context allows it, only the edited block is reparsed (a prose paragraph, a heading without slug collisions, or the body of a mermaid/math fence); anything else falls back to a full parse. Mermaid keeps the previous drawing while the source editor has focus. Hidden previews release their worker, and live state is dropped when the document closes.

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

Co-authored-by: faysou <[email protected]>
2026-12-01 06:29:58 +08:00
l0ng-ai 41a76ca0d7 fix(vcs): stop rescanning the file per hunk when opening large diffs (#7117)
Opening a working-tree diff from the commit panel computes a key for every hunk (hunkKeys). Each key called currentHunkText, which rebuilt the whole file's line-start table, so the cost was hunks x file size. A 9.4 MB JSON with 17,931 changes froze the window.

rollbackEdit and currentHunkText now take an optional precomputed lineStarts table, and hunkKeys builds it once. The same applies to every other per-hunk loop: line-level partial commits, the partial commit projection, the commit-check rollback fallback, and stage/unstage from the gutter.
2026-12-01 06:25:49 +08:00
l0ng-ai 1bf29ab3d7 test(typescript): wait for import style changes to reach vtsls in the smoke (#7115)
typescript_import_style failed intermittently on slower CI runners: with autoImportSpecifierExcludeRegexes set, third.ts kept offering alphaHelper for 120 s. settings_set reconfigures the servers in a background task, so the first completion in third.ts could run under the old preferences; tsserver caches that file's module specifiers under a key without autoImportSpecifierExcludeRegexes, and vtsls' per-file configure doesn't clear it, so every retry got the old answer. Each setting change in the test now awaits LspManager::reconfigure before the next completion.
2026-12-01 06:02:57 +08:00
Deng Liuтаdengliu 49b52a8bfa feat(agents): import and fork Copilot sessions (#7111)
Import Sessions now lists Copilot sessions of the project, read from <config>/session-state/<id>/workspace.yaml (COPILOT_HOME or ~/.copilot) and titled by their name or first prompt without reading the whole event log. Importing resumes the session and replays its history (session.getMessages) into the task, and the Copilot shim now supports session/fork through sessions.fork, so Copilot sessions can be forked without changing the source. Imported sessions of every provider load in the background so their history shows before the first message. The plugin docs list copilot among the native fork providers.

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

Co-authored-by: dengliu <[email protected]>
2026-12-01 05:58:56 +08:00
lleviathe 77342b8e71 feat(mcp): ask a background project's confirmations in a project window (#7114)
A tool call needing confirmation in a project served in the background (build_project, execute_run_configuration, http_run_request, destructive plugin tools) failed with "no project window is available" unless brave mode was on. It now asks in the trusted project window focused last, with the usual dialog naming the background project and its path. Requests queue there; the dialog keeps the keyboard focus where it is and answers no key typed outside it, and the Dock icon bounces when the app isn't active. When that window closes, switches project, reloads or loses trust, the request moves to the next trusted project window, within the same 180 s deadline. Tools whose result needs a window (run_command, open_file_in_editor, xdebug_start_debugger_session and the breakpoint tools) refuse in a background project before asking.

Closes #7035

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

Co-authored-by: lleviathe <[email protected]>
2026-12-01 05:57:12 +08:00
Vadim LazukтаInf1mum 369ff7cec8 fix(editor): fill warning, usage-match and link boxes to the full line height (#7110)
Three inline marks still painted only their font box: the warning lint fill (a flat background-color), the Usages preview match, and the Cmd/Ctrl-hover link, whose pointer cursor stopped at the font so the gap above and below the word showed the I-beam. They now use the inlineBg pattern: the mark grows to the row with padding-block and the fill is a 1lh-capped gradient centred in it; the link only needs the padding. An unnecessary warning still drops the fill, and the active warning keeps it. The usage contrast e2e check reads the fill from the gradient.

Closes #7105, closes #7106, closes #7107

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

Co-authored-by: Inf1mum <[email protected]>
2026-12-01 05:49:19 +08:00
solhovoy 4016c410db feat(bookmarks): add toolbar actions and embedded editor preview (#7102)
The Bookmarks tool window gets Rename, Select in Project View, Expand All, Collapse All and an Editor Preview toggle in its header. The preview shows the selected bookmark's or file's code with the bookmark gutter, below the tree when the window is docked at a side and beside it when docked at the bottom; the toggle is remembered. Remove All Bookmarks now asks first, and the bookmark and list rename dialogs get a labelled form with Create/Rename buttons.

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

Co-authored-by: solhovoy <[email protected]>
2026-12-01 05:44:33 +08:00
lleviathe 3c3d02d7be feat(mcp): list tools on a connection without a project of its own (#7103)
An MCP client started in a folder no project serves got -32001 for tools/list and registered no tools, so it couldn't reach the projects inside even with projectPath. Such a connection (and one naming no folder with zero or several windows open) now lists the tools a trusted project gets; each call still resolves its project, and a tool that writes or runs refuses an untrusted project with the Restricted Mode error before the project loads. initialize tells the agent to pass projectPath in every call.

The stdio bridge picks its IDE process with a new openidea/servesFolder method (falling back to the tools/list probe for older IDEs), keeps the process initialize picked, picks again when processes stop or start, and sends cancellations to every process. Plugin tools list projectPath in their schema and get the call without it when their own schema refuses it.

Closes #7039

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

Co-authored-by: lleviathe <[email protected]>
2026-12-01 03:53:20 +08:00
NK StudioтаNK-Studio 2f66eb0503 fix(editor): recognize C# using fixes in auto import and imports on paste (#7100)
Add unambiguous imports on the fly and Insert imports on paste pick the import quick fix by its title, but Roslyn (csharp-ls) titles it with the directive itself (using UnityEngine.SceneManagement;), so C# never got a missing using added. Both now also accept a whole using [static] directive title; fully-qualify and Remove unnecessary usings fixes stay ignored.

Co-authored-by: NK-Studio <[email protected]>

Co-authored-by: NK-Studio <[email protected]>
2026-12-01 03:48:45 +08:00
l0ng-ai 63db10a688 fix(vcs): reuse one diff tab with the preview tab turned off (#7108)
Diffs from the version control views reused one tab only through the preview tab, so turning off Opening Policy > Enable preview tab opened every diff in a new tab. Editor kinds can now have their previews granted regardless of that setting (reusesPreviewTab); the diff, combined diff and merge commit diff kinds do, so Commit / Local Changes, the Git Log, shelves and stashes keep one diff tab while project files still open as regular tabs. Pinned and kept diff tabs stay, and activeInput({ previewOnly }) uses the same check so the Git Log's selection-following preview works too.

Fixes #7096
2026-12-01 03:47:32 +08:00
l0ng-ai 1dd3d64781 feat(freemarker): HTML, script and style languages and completion in FreeMarker templates (#7104)
FreeMarker files were highlighted by a stream mode, so markup had no HTML completion and script/style content was plain text. A Lezer grammar now parses the template layer (directives, user-defined directive calls, interpolations, comments, noparse), the first directive fixing the angle or square syntax, and the text between them is mounted as one HTML document: markup nests across directives and <script>/<style> get JavaScript and CSS.

Block directives fold, indent, match their end tags and get their end tag when > is typed; completion offers directives after <#, the open blocks' end tags after </, and built-ins after ?. Comment Block uses <#-- --> ([#-- --] in the square syntax).

Fixes #6906
2026-12-01 03:44:08 +08:00
l0ng-ai 8ac194cf50 fix(plugins): let capabilities.reasons explain capabilities a contribution brings (#7101)
A plugin with [[contributes.javaAgents]] gets java.agent without listing it under [capabilities], so the manifest check rejected a reason for it and the install dialog and Permissions showed only the IDE's description. Manifest::derived_capabilities names the capabilities contributions bring (java.agent from javaAgents, project.read from documentIndexers) and reasons may use those keys too; docs updated.

Fixes #7088
2026-12-01 03:26:09 +08:00
Ivan 3b488a7824 fix(macos): let background project tabs give their web content memory back (#7060)
A background project tab of a native tab group detaches its WKWebView from the window 30 s after it leaves the front, so WebKit frees the hidden page's graphics and caches. The view comes back when the tab is selected through our tab bar, when its window becomes key (Window menu, Close Project) or when AppKit makes it visible by itself; an inactive app's full-screen group waits for activation (#6937).

Every macOS with_webview caller goes through macos::with_web_view, which hands the retained view to a detached tab instead of panicking in wry; titlebar::set_height uses the NSWindow directly. clippy.toml disallows the raw with_webview calls. Covered by BackgroundTabs unit tests and an AppKit test of the synchronous re-attach on the key notification (it no longer asks a never-loaded web view for its process ids, which WebKit asserts on).

Fixes #6938

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

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 03:20:08 +08:00
l0ng-ai b5e89aace0 feat(run): show each invocation of a parameterized test in the Run window (#7099)
The JUnit runner and the Gradle test init script report an invocation of a parameterized, repeated or dynamic test with its display name, and the JVM parser puts it under its method node with its own status, output and stack trace; the method shows the aggregate. Rerunning a failed invocation reruns its method.

Fixes #7046
2026-12-01 03:06:11 +08:00
Akbar Husain 81c95b2ab7 perf(lint): clear remaining non-e2e React perf violations (#7093)
Clears the remaining non-e2e React perf lint violations and turns the three rules on outside e2e/ so they can't come back: data-derived keys for diagram edges and deadlock cycles (index keys stay, with a documented suppression, where position is the identity), context values in tests hoisted to constants or memoized, and array/JSX default props replaced with module-level constants.

Co-authored-by: akbar1214 <[email protected]>
2026-12-01 02:59:24 +08:00
LU XIANGRUIтаwildcatDownstairs f7b5cc388c feat(run): debug Python on a WSL run target (#6777)
A Python run configuration on a WSL target can now be debugged: the program starts under the container debugger's bootstrap in the distribution, which waits for the IDE on the distribution's loopback (WSL forwards it), finding the IDE's debugpy and bootstrap through wslpath when the distro has none. Stop ends the debugged process in the distribution, with pkill or, where it is missing, a /proc scan. Other kinds say they can't be debugged in WSL.

Also carries the WSL run target review fixes that neither #6764 nor #6770 included: Maven options naming this machine's files are dropped from remote runs, a failed wsl.exe listing is reported in Run Targets and retried on focus, an unsafe distribution name is cleared and asked for again, a printed path whose .. climbs above its root is refused, and prepare_wsl is built only on Windows.

Verified by the contributor on Windows 11 with WSL 2 (Ubuntu 24.04): a breakpoint is hit and Stop leaves no debug process.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 02:54:14 +08:00
LU XIANGRUIтаwildcatDownstairs 277d0e9d1e feat(python): a Python in WSL as the project interpreter (#6770)
Python > Add Interpreter gets a WSL tab: pick a distribution and a Python in it (a bare python3 is looked up on the distribution's PATH; Windows paths are refused). The project interpreter then runs in the distribution: packages are listed from there, the project's virtualenv inside the distro is read, the language server resolves imports from the distro's site-packages through \\wsl.localhost, and runs go through the WSL run target. Verified by the contributor on Windows 11 with WSL 2 (Ubuntu 24.04).

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 02:38:34 +08:00
LU XIANGRUIтаwildcatDownstairs d6adb7aa40 feat(run): run configurations in a WSL distribution from a Windows project (#6764)
Settings > Run Targets gets a WSL target that lists the installed distributions. A run configuration on it starts locally as wsl.exe -d <distro> --cd <dir> --exec ..., with the project's Windows paths mapped to /mnt/<drive>/..., arguments passed unchanged, environment variables forwarded through WSLENV, and Stop ending the Linux process. Verified by the contributor on Windows 11 with WSL 2 (Ubuntu 24.04), including quoted arguments and Emulate terminal.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 02:21:28 +08:00
l0ng-ai 6e5e482410 test(memory): make the debounce test tolerate a loaded machine (#7098)
memory::tests::a_burst_of_calls_runs_once_after_the_delay failed on a loaded macOS runner: with a 100 ms delay and 20 ms gaps, oversleeping let the debounced call fire before the burst ended. The test now uses a 500 ms delay, checks "nothing ran yet" only when less than the delay has passed since the last call, waits for the run, and asserts exactly one run only when no gap in the burst reached the delay.
2026-12-01 02:20:22 +08:00
solhovoy cc02c2fe40 feat(vcs): show shelved files under their shelf with grouping and diff preview (#7090)
The Shelf tab now lists each shelf's files beneath it in one tree instead of a separate files pane. View Options groups the files by Directory or Module and toggles Show Diff Preview (a side-by-side diff of the selected file, hidden in non-modal commit mode); Expand All / Collapse All work on the groups. File paths show inline, Delete and Cmd+Backspace delete the selected shelf or file, and the Shelve button, already in Local Changes, is gone from this toolbar.

Co-authored-by: solhovoy <[email protected]>
2026-12-01 02:16:33 +08:00
Игорь Тихомиров 74a3f6470a feat(php): add PHPantom as a built-in language server (#7052)
PHPantom (MIT) joins the selectable PHP language servers, with a tools-registry entry for installing it.

textDocument/implementation now sends a client-created workDoneToken for any server; its progress shows as a cancellable task and is retired when the request ends (response, cancel or timeout). A server's TOML can list server-created progress-token prefixes to ignore (ignored-progress-token-prefixes); php.toml uses it for PHPantom 1.1.0, which can leave find_references/goto_implementation progress open after a cancel (PHPantom-dev/phpantom_lsp#603).

Co-authored-by: fenndooscar <[email protected]>
2026-12-01 02:04:13 +08:00
Ivan 4c8c078666 perf(lsp): bound the cache of virtual document text (#7082)
The window-wide cache of lspVirtualDocument results (decompiled classes, library sources, jdt:// documents) kept one entry per document ever shown, hover previews and go-to-definition included, for the window's lifetime. It now keeps the 32 most recently used; an evicted document is fetched again on next use, and a failed fetch is dropped only while it is still the cached one.

Refs #6938

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 02:00:34 +08:00
Ivan e672b14d52 fix(plugins,mcp): stop idle IPC loops in Restricted Mode windows (#7091)
Idle Restricted Mode windows called the backend over 100 times a second. PluginHost::restrict_project announced CommandsChanged even when the project had no plugins to restrict; every window answered with plugin_list, which restricted the untrusted root again. Separately, the MCP editor and problems reporters retried every 300 ms on commands Restricted Mode refuses.

restrict_project now announces only when it restricted something, and the reporters skip untrusted projects and report once trust is granted. Measured over 4 idle windows: invoke calls 115/s -> 0.7/s, CPU per idle minute 12.3 s -> 1.1 s.

Refs #6938

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 01:59:18 +08:00
audichuang c0300f8959 fix(vcs): find a worktree added below the project when its HEAD lands after the watcher's rescan (#7086)
git worktree add writes the worktree's .git file before its gitdir's commondir and HEAD, so a watcher rescan in between found no repository there, and the later .git/worktrees/<id>/HEAD write never triggered another rescan. That HEAD now rescans too while its worktree is unknown and is one a scan would find (Repos::searched, sharing discover's depth, hidden, vendor and skip rules, plus Directory Mappings exclusions).

Co-authored-by: audichuang <[email protected]>
2026-12-01 01:57:06 +08:00
l0ng-ai 11cf9864a1 fix(vcs): guide GitHub HTTPS failures to project account settings (#7061)
A Git Update, Fetch, Push or branch update that fails on an https://github.com remote with "repository not found" or "Authentication failed" now checks the GitHub CLI accounts. When several are signed in, the original Git error is kept and a hint says the effective account may lack access, with a GitHub Settings action that opens the project-scoped account selector. Nothing switches gh's global account, rewrites remotes or retries the operation; other hosts, SSH remotes and network errors are left as they were.
2026-12-01 01:52:43 +08:00
l0ng-ai 04a4d98d68 fix(vcs): open the Log User filter without waiting for every author (#7095)
The Log's User filter popup waited for git log --all to list every author before opening, which takes 8-10 s on a history of 500K+ commits, on every open.

The popup now opens at once with the authors already known (loaded commits plus each repository's last full list). The full list is fetched in the background, reusing a running fetch and a list younger than five minutes, and only Select..., which shows every author, waits for it.

Fixes #7064
2026-12-01 01:44:26 +08:00
l0ng-ai 9a984f64a3 fix(vcs): keep No Merges fast on long pull-request histories (#7094)
With No Merges on, a hidden commit's graph parents are projected onto its nearest shown ancestors. On a pull-request history (M_k = merge(M_k-1, F_k)) each hidden merge projected onto all older features, because the projection of M_k-1 was kept next to F_k although M_k-1 is F_k's own parent. The lists grew with every merge and the first page walked the whole history, so a 500K-commit repository never finished loading.

Before projecting through a hidden commit, parents that are ancestors of another of its parents are dropped (a bounded walk that keeps the parent when unsure). The graph builder and the filtered log view (path, date and author filters share the projection) both apply it.

Fixes #7063
2026-12-01 01:39:39 +08:00
l0ng-ai e35a607556 fix(welcome): expand JetBrains path variables without re-checking the base (#7092)
expand_jetbrains_path re-checked is_absolute after joining a path variable onto the home or IDE config folder. Those folders are already absolute; on Windows the unit test's /home/me home has no drive, so recent::tests::expands_jetbrains_path_variables failed on Rust (windows-latest) since #6979. Only a path without a variable is checked now.
2026-12-01 01:32:47 +08:00
Muuтаmuutot 3fa990fce2 feat(editor): add Render All Doc Comments (#7066)
Adds the Render All Doc Comments action (IDEA id ToggleRenderedDocPresentationForAll, no default shortcut). It flips Editor > Appearance > Render documentation comments globally and clears every open document's per-file rendered-docs override, so all editors follow the new default.

Co-authored-by: muutot <[email protected]>
2026-12-01 01:31:03 +08:00
RuyimgByCN 11e520dedb feat(project-tree): add "Add as Library…" for JARs and library directories (#7077)
Right-clicking a .jar or a folder of jars (such as WEB-INF/lib) in the Project view, or running it from Find Action, opens a Create Library dialog (name, scope, classes) that appends the library to projectStructure.libraries. Collapsed folders are probed briefly before the menu opens. Registered library folders get the library icon and an Open Library Settings entry instead of a duplicate add, External Libraries refreshes when jars inside them are added or removed, and manifest-free Java projects with libraries show the project JDK there.

Library class entries (jar globs, root-relative paths) are parsed once in platform/languageSettings for both the action and the refresh.

Closes #7051

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-01 01:24:16 +08:00
Chris-young42таChris-young42 a0c0b69b4a feat(project-structure): add search and batch folder marking (#7069)
Project Structure gets a search field: sections and module tabs are filtered by English or translated labels, the matching section or Sources/Paths tab opens, and staged edits are kept while searching.

The module folder tree now allows Shift and Ctrl/Cmd selection, and the Mark as buttons mark or unmark all selected folders at once (pressed only when every selected folder already has that role). Long paths in the marked folders pane wrap in narrow windows.

Co-authored-by: Chris-young42 <[email protected]>
2026-12-01 01:14:04 +08:00
RuyimgByCN b89128649f fix(project-structure): show full content root tooltips and enable custom test output path (#7076)
Long content root and library paths in Project Structure were truncated with only a native title attribute, which the tooltip host skips and WKWebView suppresses; they now use verbatim tooltips, and the module Sources tree scrolls horizontally.

Test output path was always disabled, although the builder already compiles tests into the module's testCompilerOutput. It is now editable for a root module not managed by Maven or Gradle. Browse dialogs for output paths resolve relative values against the project root.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-01 01:08:10 +08:00
RuyimgByCN 9973cad74c fix(java): expand JAR directories in Project Structure libraries (#7074)
A Project Structure library whose class root is a folder of jars (such as WebRoot/WEB-INF/lib) was passed through as a bare folder, so jdtls, javac, artifact layouts, External Libraries and the Java launch classpath all missed its jars.

Folder roots and dir/*.jar, dir/**/*.jar globs now expand consistently: jdtls gets a **/*.jar glob, javac gets <dir>/* per folder holding jars, and artifacts, External Libraries and launch classpaths get the individual jars. A folder without jars stays a class folder. The jar walk and glob parsing are shared from ide-core, and the class-root expansion from ide_sdk::libraries::library_class_paths.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-01 01:02:29 +08:00
RuyimgByCN 8cb7a2fe06 fix(tomcat): keep Project Structure WAR and exploded artifacts across prepare (#7073)
Launching Tomcat with a Project Structure artifact in a project without Maven or Gradle failed with 'The built WAR artifact does not exist': the WAR was written inside Tomcat's runtime directory, which tomcat::prepare deletes and recreates. Project Structure artifacts are now built to their configured output (compile::artifact_file), exploded artifacts are laid out directly without packing and unpacking a WAR, Tomcat deploys a recorded exploded directory as is, and the artifact list falls back to Project Structure web artifacts when there is no build tool. Refs #404.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-01 00:57:16 +08:00
faysouтаfaysou 5d867d7d2d fix(markdown): preview Git repository versions (#7067)
Open Repository Version opened Markdown in a read-only tab that skipped the Markdown wrapper, so a committed README had no preview. Editor wrappers can now match virtual documents (matchesVirtual), and the Markdown wrapper matches Git revisions of Markdown files: those tabs get Editor Only, Editor and Preview and Preview Only, with the preview rendering the committed text and the source staying read-only.

Co-authored-by: faysou <[email protected]>
2026-12-01 00:54:08 +08:00
Ivan 70f6678271 perf(memory): release freed heap pages after closing a project or tabs (#7072)
Closing a project or a batch of documents now calls release_free_pages once, 2 s after the last close, on a background thread. On macOS the freed pages are already reclaimable, so the footprint change is within noise; on Linux malloc_trim can return pages glibc would keep resident (not measured).

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 00:51:07 +08:00
lleviathe 530388a79d fix(mcp): pick the innermost project across windows and background projects (#7085)
A call naming a folder went to the innermost project open in a window, and the background policy was asked only for folders outside every open project. With a window on a parent folder, a call naming a nested trusted repository served in the background read the parent's files instead, so the answer depended on which windows were open. resolve_project now also asks the policy for a path below the innermost open root, passing that root so only folders strictly inside it are considered and nothing else is looked up on disk. A path at an open root, or one no nested folder serves, stays with the window and loads nothing; a remote window's root answers nothing locally. The MCP guide (English and Chinese) describes how the project is picked. Closes #7040.

Co-authored-by: lleviathe <[email protected]>
2026-12-01 00:49:59 +08:00
Bake Yam 98cb85003a fix(notebook): let commands find a cell document (#7071)
A notebook's cells are documents of the language servers only, never of the editor's document table, so commands that read that table failed on a cell: Reformat Code answered 'document is not open' and Alt+Enter offered no import for an installed package's name. Formatting and the Python import quick fix now fall back to the LSP manager's cell buffer (new LspManager::cell_text), and the formatter is given the notebook path with a .py extension so Ruff parses the cell as Python rather than notebook JSON. Part of #5846 (items 1 and 3).

Co-authored-by: Renjiankang <[email protected]>
2026-12-01 00:46:37 +08:00
l0ng-ai dfae46868c test(lsp): compare server roots without cloning into a slice (#7087)
The Xcode C-family test added in #7023 built a one-element array by cloning the root, which clippy's cloned_ref_to_slice_refs rejects under -D warnings, so the three Rust CI jobs failed to compile ide-lsp's mock_server test. It now compares against std::slice::from_ref.
2026-12-01 00:45:21 +08:00
faysouтаfaysou 635da15486 fix(markdown): follow explicit preview anchors (#7070)
A Markdown link such as #ref-1 can point to an explicit HTML id in the document, but the preview only looked for the generated heading id, so a citation link jumped to a heading with the same slug or nowhere. The preview now tries the exact id first and falls back to the generated heading id.

Co-authored-by: faysou <[email protected]>
2026-11-30 23:56:35 +08:00
lleviathe 249d0526f0 fix(settings): fill the row with the background folders list (#7078)
In Settings › Agents › IDE MCP Server › Background Projects the Folders list was 116 px wide while empty and grew with its longest path up to 480 px. The wrapper that turns it off in mode Off kept it from being the row's flex item; the wrapper now fills the row and the list passes fullWidth like the other stacked lists.

Co-authored-by: lleviathe <[email protected]>
2026-11-30 23:55:06 +08:00
Игорь Тихомиров 181bbdfdc2 fix(remote): clear background tasks when the backend changes (#7068)
After a remote backend disconnected or was replaced, its progress rows stayed in the window because the old connection could no longer deliver completion events. When the connection is lost or the session changes, the window now drops the backend's numeric task IDs, their pending delayed updates and the indexing row, and keeps client-side tasks.

Co-authored-by: fenndooscar <[email protected]>
2026-11-30 23:53:33 +08:00
l0ng-ai c7172184ad feat(editor): choose the styles Cycle Identifier Case goes through (#7081)
Cycle Identifier Case always went through all five styles. Settings › Editor › General › Smart Keys gets a Cycle Identifier Case group with one checkbox per style (snake_case, SCREAMING_SNAKE_CASE, kebab-case, camelCase, PascalCase), all on by default. The action skips the styles that are off and keeps starting from the style the name is written in, even when that one is off. Fixes #6972.
2026-11-30 23:50:27 +08:00
Muuтаmuutot 8380732e60 fix(vcs): split global and per-tab Git Log options (#6931)
All Git Log options were one store, so changing the sort or first-parent view in one log tab or File History tab changed every other tab, and switching tabs overwrote the global choices. Application-level properties (compact refs, tag names, labels on the left, commit date, author/date/hash/signature/checks columns and column order, diff preview and its location, changes from parents) are now saved globally and shared across tabs and windows. Graph options, long edges, highlighters, details and root visibility, text filters and column widths stay per tab and are restored with the log session. Tab switches and cross-window storage updates no longer overwrite the global set.

Co-authored-by: muutot <[email protected]>
2026-11-30 23:25:11 +08:00
Muuтаmuutot 42fcbb336a feat(settings): copy the selected Settings page path (#7037)
Adds Copy Settings Path (CopySettingsPath alias). It copies the current Settings page as 'Settings | Group | Page', built from the same translated page-tree breadcrumb the dialog header shows. The page tree's context menu offers it for the right-clicked page.

Co-authored-by: muutot <[email protected]>
2026-11-30 23:17:46 +08:00
Muuтаmuutot 93a450aa8c feat(editor): toggle breadcrumbs for the active editor (#7034)
Adds the Show Breadcrumbs toggle action (EditorToggleShowBreadcrumbs alias). It forces breadcrumbs on or off for the active editor tab only, ahead of the global setting and the per-language disabled list, without changing either. The override lives as long as the tab: it is dropped when the tab closes or the editor session stops, and split editors of one file keep their own.

Co-authored-by: muutot <[email protected]>
2026-11-30 23:12:21 +08:00
Muuтаmuutot 8e0a36fb1c feat(tree): center the focused selection like IDEA (#7025)
Adds Scroll Tree to Center for the focused tree, reachable from Find Action and the ScrollTreeToCenter IDEA action alias. It centers the selected lead row without changing the selection, does nothing with an empty selection, and is disabled once the tree loses focus. Every Tree registers for focused-action lookup, so it works in tool windows, Settings and tree dialogs alike.

Co-authored-by: muutot <[email protected]>
2026-11-30 23:07:15 +08:00
l0ng-ai 11da3ecce7 fix(welcome): flatten the project switcher list (#7009)
The title-bar project switcher keeps only Open Projects and Recent Projects, as one flat list ordered by recency, without host or custom group headings. Local and remote projects share one row layout; remote rows keep the avatar badge and show host:path on the path line. Section headings line up with the project badges. The Welcome screen and the standalone Recent Projects popup keep their grouping.
2026-11-30 23:02:06 +08:00
l0ng-ai 53d295d785 fix(agents): align task controls and questions with workbench styling (#7015)
The agent composer, recovery notices and question forms used one-off styles. Skills and agent Resume get dedicated monochrome icons that inherit the menu, toolbar or button colour, leaving the editor intention bulb and debugger Resume icons unchanged. Interrupted, network-retry and archived notices share one inset geometry with warning colours from the theme, and question forms use the standard control styles.
2026-11-30 23:00:32 +08:00
l0ng-ai 9f1380cf04 fix(agents): edit user messages in place without layout jump (#7007)
Clicking Edit on a user message replaced the bubble with a full-width, left-aligned textarea and dropped the timestamp and You label, so the text jumped. Editing now stays inside the user message container: the header is kept, the editor takes the measured bubble width (bounded by the bubble max-width) with the same padding, and the actions sit under it.
2026-11-30 22:54:56 +08:00
l0ng-ai 338e1a5b02 fix(agents): keep active and pinned task order stable (#7002)
Active status groups and active tasks in custom groups were ordered by updatedMs, so concurrent turns, status changes, renames and per-task MCP/skill/memory overrides kept reshuffling the list. They now sort by creation time, newest first, and Pinned keeps its pinned order including manual drag overrides. Renaming a task or changing its overrides no longer bumps updated_ms.
2026-11-30 22:52:26 +08:00
l0ng-ai 092cde1319 fix(agents): prevent native context menu on conversation images (#6995)
Right-clicking a conversation image thumbnail or its full-size preview showed the WebView's native image menu (Open Image in New Window, Download Image, Copy Image). Both contextmenu handlers stopped propagation without preventing the default action; they now call preventDefault as well.
2026-11-30 22:50:39 +08:00
LU XIANGRUIтаwildcatDownstairs fc1e1838ca feat(run): run Xcode apps on a connected iPhone or iPad (#7056)
The Xcode run destination chooser lists paired iPhones and iPads from devicectl under a Devices header, marking ones that are not connected or have Developer Mode off. Running on a device stops before building when the device is not ready or the app would be unsigned (CODE_SIGNING_ALLOWED = NO, or automatic signing without a team), and otherwise builds with -allowProvisioningUpdates, installs with devicectl and launches with --console so output shows in the Run console and Stop ends the app. Scheme environment goes through DEVICECTL_CHILD_*, and a failed launch adds an unlock hint after devicectl's error. Debugging on a device is not supported yet. Install and launch on real hardware were exercised with a stubbed xcrun only.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 22:45:00 +08:00
solhovoy 9a9a536525 feat(bookmarks): show a tooltip on gutter bookmarks, update the icon and add Rename Bookmark to context menu (#7057)
Hovering a bookmark in the editor gutter shows its description, or the line text when it has none, and the marker carries the same text as its accessible label. The plain marker uses the shared filled bookmark icon at 13px instead of a custom outline. The gutter context menu on a bookmarked line offers Rename Bookmark…, which opens the bookmark description editor, next to Delete Bookmark.

Co-authored-by: solhovoy <[email protected]>
2026-11-30 22:39:04 +08:00
LU XIANGRUIтаwildcatDownstairs 2d7928374e fix(ui): keep list and popup match highlights off the editor scheme's search colour (#7045)
Matched characters in Search Everywhere and every chooser built on HighlightedText used --bg-search-match, which editor colour schemes rewrite for their Search result attribute (Darcula: dark green), so the popup highlight turned dark green instead of the SearchMatch gold. Lists now read new --bg-list-match / --fg-list-match tokens set per theme (dark, light, high contrast, palette themes) and mapped from IntelliJ theme SearchMatch keys; they are not scheme variables, so applying a colour scheme leaves them alone. In-editor search marks and code previews still follow the scheme. The Harbor Night template and the theme token docs include the new tokens.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 22:18:41 +08:00
audichuang 58eb5ae667 fix(network): route plugin WebSockets and the MCP probe through the IDE proxy (#7062)
The plugin WebSocket API opened a direct socket and the MCP server probe built a bare reqwest client, so both ignored the IDE's proxy settings (Manual and the macOS PAC). Plugin WebSockets now open their TCP stream through ide_http::tunnel; loopback stays direct in every mode, and a proxy the tunnel cannot speak to (SOCKS, https://) keeps the previous direct connection. The tunnel's reason, such as a proxy that needs a login, is part of the failure message. The MCP probe uses the shared ide_http client builder and sets the MCP headers and 12 s limit per request, with protocol headers taking precedence over configured ones. The tunnel also no longer double-brackets IPv6 literals ([[::1]]:port), which broke the Jupyter kernel channels for IPv6 hosts.

Co-authored-by: audichuang <[email protected]>
2026-11-30 22:12:37 +08:00
Игорь Тихомиров 0698ebb9b0 fix(php): check Composer dependencies from the project owning vendor files (#7053)
A file inside an installed package under vendor/ (or a custom config.vendor-dir) has its own composer.json, so the dependency check treated the package as a separate Composer project and reported it as not installed. The check now walks from the content root inward and attributes a file to the outermost project whose vendor directory contains it; nested projects outside vendor still use their own manifest.

Co-authored-by: fenndooscar <[email protected]>
2026-11-30 22:09:31 +08:00
l0ng-ai 647e564127 fix(ui): align descriptive columns in option pickers (#7032)
Option descriptions in pickers such as Effort Level started at different horizontal positions because each virtualized row sized its own label. The shared select can now align descriptions in one column sized from the widest rendered label, capped for narrow menus and re-measured when fonts change; agent effort, model and configuration pickers, agent defaults, task isolation and Git fetch tag modes use it.
2026-11-30 22:06:17 +08:00
l0ng-ai edd2e90b9b feat(editor): colour Vue component tags apart from HTML elements (#7059)
Component tags in Vue templates (<Icon>, <el-input>) had the same colour as HTML elements. PascalCase or hyphenated tag names now use a new --syn-custom-tag token, the Custom tag name colour: #2fbaa3 in Islands Dark and #b21dbf in Islands Light, with values for high contrast, the palette themes and Harbor Night; other themes fall back to the tag colour.

Fixes #6894
2026-11-30 21:59:52 +08:00
nako-ruruтаnako-ruru 5bfefff5e1 feat(jni): navigate between Java native methods and C++ JNI implementations (#7020)
Go to Declaration on a Java native method opens its Java_<mangled name> implementation in C/C++ files, and on such a function goes back to the native declaration, with a chooser for several targets. Symbols come from the project index, with a text search as fallback; JNI names are mangled and unmangled per the JNI spec (escapes, nested classes, overload signatures). Contributed definition providers may now answer asynchronously.

Co-authored-by: nako-ruru <[email protected]>
2026-11-30 21:45:44 +08:00
LU XIANGRUIтаwildcatDownstairs 49097bf5c0 feat(swift): show SwiftLint findings as diagnostics (#7029)
Swift files below a .swiftlint.yml are linted with swiftlint lint --reporter json: an opened or saved file by its path (so excluded paths and nested configs apply), an edited buffer through stdin. Findings show in the editor and Problems with severity and rule id. SwiftLint joins the tool registry as an installable CLI under Swift; a missing swiftlint is reported once, and nothing runs in Restricted Mode.

Closes #7028

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 21:39:53 +08:00
LU XIANGRUIтаwildcatDownstairs 09a44bebbe feat(lsp): serve C-family files of Xcode projects through sourcekit-lsp (#7023)
In an Xcode project plain clangd finds no compile flags, so headers on the target's search paths and the generated <Module>-Swift.h were not found. C, C++, Objective-C and Objective-C++ now list sourcekit-lsp before clangd with require-root-marker on buildServer.json and replaces clangd: with an Xcode BSP config sourcekit-lsp serves them with the build server's flags; without one, or without sourcekit-lsp, clangd serves as before.

Closes #7022

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 21:32:00 +08:00
LU XIANGRUIтаwildcatDownstairs 7237a37104 feat(language): bundle the Objective-C tree-sitter grammar for outline, folding and symbols (#7027)
Bundles tree-sitter-objc (MIT) with an outline query for Objective-C and Objective-C++: @interface/@implementation/@protocol blocks, categories, methods named by selector, properties, instance variables, C declarations and #pragma mark labels, so the Structure view, folding and the symbol index work for .m and .mm files. The built-in syntax-error diagnostics skip both languages, since the grammar misreads Apple's macros and C++.

Closes #7026

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 21:29:33 +08:00
LU XIANGRUIтаwildcatDownstairs c864cec32f feat(languages): recognize Apple entitlements, privacy manifests, String Catalogs, xcconfig and .strings files (#7021)
.entitlements and .xcprivacy open as XML property lists and .xcstrings as JSON; .xcconfig and .strings get small language definitions that use the C mode for comments, #include and quoted strings. Each gets a matching file icon.

Closes #7018

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 21:25:40 +08:00
l0ng-ai f7f2efaace feat(debugger): evaluate the expression of an operator on hover and Quick Evaluate (#7055)
Hovering or Alt-clicking an operator while suspended evaluated nothing, because only identifiers, member chains and calls were taken. An operator now gives the expression it belongs to, from the syntax tree: && gives a > 1 && !flag, > gives a > 1, ! gives !flag. A hover leaves out expressions with calls, increments or assignments, which Quick Evaluate still evaluates; an identifier is still just the identifier.

Fixes #7000
2026-11-30 21:19:38 +08:00
l0ng-ai e8cb141d86 fix(plugins): activate plugins whose activation event fired before they loaded (#7054)
A remote project's server receives the desktop's plugin packages after the window has opened its files, so on-language:twig reached the server before the Twig plugin was installed there and was lost; the plugin stayed inactive and Twig files got no highlighting or completion. The same happened locally when a plugin was installed with a matching file already open. The host now remembers the language, file and view activation events fired so far (bounded) and activates a plugin that loads later if one matches, and the window reports on-language again when the active file's language changes.

Fixes #7014
2026-11-30 21:16:47 +08:00
l0ng-ai 3eb6933644 fix(find): keep the usages popup size loader private and fix a knip import (#7049)
#7048 exported the size loader only its own file uses, and its e2e test imported usages.ts from a literal path; knip reported both. Unexport the loader and import through a variable like the other spec in the file.
2026-11-30 21:06:50 +08:00
l0ng-ai 72669a04c2 fix(find): make the Show Usages popup resizable and remember its size (#7048)
The usages popup had a fixed width and a height derived from its row count, so it could not be enlarged on any platform. It now resizes from its right and bottom edges and corner, the list takes the added height, and the size is remembered for the next time it opens.

Fixes #6999
2026-11-30 21:05:36 +08:00
audichuang 0b9c675172 test(mcp): stop agent commands only once they run, not while the login shell reads its profile (#7041)
The agent-commands MCP test stopped and interrupted 'sleep 30' right after run_command returned with timeout 0, while the login shell could still be reading its profile; a profile command that handles SIGINT lets the shell go on to run the command, leaving the tab stopping past the 10 s wait. Both stops now wait for the command to print 'ready' and assert it is running first.

Co-authored-by: audichuang <[email protected]>
2026-11-30 20:58:49 +08:00
Chris-young42таChris-young42 5188a34e3d fix(java): hot swap Gradle applications without resources (#7044)
Gradle's processResources succeeds with NO-SOURCE when a project has no resources and never creates its output directory, so Update Application stopped before asking the debugger to reload classes. A missing output directory now counts as an empty resource set, and resources an earlier update copied are removed.

Refs #6977

Co-authored-by: Chris-young42 <[email protected]>
2026-11-30 20:56:38 +08:00
Qslia 8d26a9b483 fix(notebook): respect editor tab size (#7043)
Notebook cell editors used CodeMirror's default indent of 4 regardless of settings. Cells now take the Python (code cells) or Markdown Code Style, falling back to the editor tab size, through an indent compartment that is reconfigured in place when settings change, so the cell editor is not rebuilt.

Co-authored-by: qslia <[email protected]>
2026-11-30 20:55:53 +08:00
LU XIANGRUIтаwildcatDownstairs 267a61c581 feat(coverage): run Xcode tests with coverage (#6944)
Run with Coverage is offered for xcode-test configurations: it adds -enableCodeCoverage YES and names the run's result bundle, which xcode::prepare_test uses instead of its own, so there is still one test run and one bundle. Afterwards xcrun xccov view --report and --archive feed the shared coverage accumulator: files compiled only by .xctest targets, files outside the project and DerivedData/.build are left out, resolved paths map back to the project root, and lines with a missed subrange are partial.

Closes #6941

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 20:53:41 +08:00
LU XIANGRUIтаwildcatDownstairs 21dfa8dd10 feat(xcode): build CocoaPods projects through their workspace and run pod install/update (#6957)
In a project with a Podfile the app project's schemes are built and tested through the .xcworkspace that pod install writes (it has no schemes of its own), and Pods/ gets no run configurations. Pod Install and Pod Update run in the Run tool window from Find Action, Build > Xcode and a Podfile's context menu; afterwards configurations are detected again and an xcode-build-server buildServer.json is regenerated for the workspace. Opening a project whose Pods/Manifest.lock is missing or differs from Podfile.lock offers Pod Install.

Closes #6956

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 20:49:53 +08:00
LU XIANGRUIтаwildcatDownstairs 0cfabdbbbd feat(swift): choose the Xcode a project uses and pass it to its tools as DEVELOPER_DIR (#6964)
Settings > Languages > Swift gets an Xcode field (empty = the xcode-select one). For a trusted project the chosen Xcode.app or Contents/Developer becomes DEVELOPER_DIR in the project environment, so sourcekit-lsp, xcodebuild, xcrun, simulators, debug adapters and terminals use it; it overrides a DEVELOPER_DIR from .envrc and is not applied to untrusted projects or LightEdit.

Closes #6963

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 20:43:48 +08:00
l0ng-ai 485d7bf99d test(vim): count Select in Project View as a known action (#7042)
#7011 mapped IDEA's SelectInProjectView to navigate.selectInProjectView, a registered action with no default shortcut in any preset, so the rc.test.ts :action id check failed on main. List it with the other unbound actions.
2026-11-30 20:40:00 +08:00
Anka Tamaтаxirf 53a1e9255e fix(vcs): reopen the repository after its volume was remounted (#6949)
The cached gitoxide handle kept pack mappings from the old mount; after a remount with the same device, inodes and mtimes it was reused and reading it raised SIGBUS. The cache now detects the remount and reopens the repository. A volume lost in the middle of a git operation is not covered.

Refs #6948

Co-authored-by: xirf <[email protected]>
2026-11-30 20:27:43 +08:00
audichuang 40ab249cb8 fix(http): route WebSocket tunnels through the macOS PAC in Auto mode (#6939)
In Auto mode the TCP/CONNECT tunnel used for WebSockets resolved the proxy with the system matcher only, so a macOS PAC script was ignored. It now asks the PAC resolver first on a blocking thread and falls back to the matcher when there is no PAC or an env proxy is set.

Co-authored-by: audichuang <[email protected]>
2026-11-30 20:27:28 +08:00
LU XIANGRUIтаwildcatDownstairs 9da3d6d9b5 feat(typescript): Go to Source Definition, Project Configuration, Move to File and TS Server log through vtsls (#6935)
Five vtsls commands, run through workspace/executeCommand on a vtsls server that advertises them (other TypeScript servers report that vtsls is needed). Go to Source Definition opens the JavaScript implementation instead of the .d.ts; Go to Project Configuration opens the file's tsconfig.json or jsconfig.json; Move to File appears in Refactor > Move and the intention menu, offering tsserver's suggested target files and Choose File, and applies the move with its import updates as one workspace edit; Open TS Server Log offers to turn on logging through the new languages.typescript.tsserverLog setting, which restarts vtsls, and then opens the log.

Closes #6922

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 20:24:55 +08:00
l0ng-ai 0df7cb1da2 fix(keymap): list Select Opened File in the VS Code preset (#7038)
project.selectOpenedFile (#7011) was added to the IntelliJ presets only, so the keymap test that the VS Code preset covers every IntelliJ action id failed on main.
2026-11-30 20:23:48 +08:00
LU XIANGRUIтаwildcatDownstairs ee9b50179e feat(welcome): import recent projects and groups from a JetBrains IDE (#6979)
Import Recent Projects from JetBrains IDE (Welcome screen more menu, File > Manage IDE Settings) reads the IDE's options/recentProjects.xml and merges its recent projects and project groups into OpenIDEA's. Entries keep their custom or display name and the later of their open and activation times; hidden (LightEdit) entries are skipped, $USER_HOME$ and $APPLICATION_CONFIG_DIR$ are expanded, and projects whose folder is gone are skipped and counted. Existing entries and groups are kept, a taken group name gets a number, and importing twice adds nothing. Import Settings from JetBrains IDE lists the recent projects as a row of its confirmation and merges them too.

Closes #6970

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 20:15:11 +08:00
Muuтаmuutot baab92c804 feat(vcs): create patches from selected historical files (#6981)
Git Log and File History changed files get Create Patch and Copy as Patch to Clipboard, in the toolbar and the context menu. Only the selected repository-relative paths are exported, as path-filtered revision diffs with Git's empty tree on the missing side of additions and deletions and both names for renames. The existing patch dialog, base directory defaults, reverse option and clipboard flow are reused; empty, malformed, no-op, mixed-repository and external-repository selections are disabled.

Co-authored-by: muutot <[email protected]>
2026-11-30 20:08:11 +08:00
l0ng-ai 2b7a18ffd7 fix(search): start Find in Files from the selection in its preview (#7033)
Find in Files and Search Everywhere took the selection only from the active editor tab, so text selected in the Find in Files preview (or another focused editor, such as a diff pane) was ignored when the action ran again. The focused editor's selection now comes first, then the active editor's.

Fixes #6992
2026-11-30 20:04:14 +08:00
Muuтаmuutot f47a83828c feat(structure): temporarily enable filters to find matches (#6934)
With Narrow down on typing on, a File Structure query that matches nothing now turns on the unchecked filters (Show fields, Show non-public, Show inherited members) one at a time until a match appears. Filters enabled this way are restored as the query gets shorter and when the popup closes, and are never saved; a checkbox the user changes by hand keeps its new state, and the cascade stops right after a backspace restores a filter.

Co-authored-by: muutot <[email protected]>
2026-11-30 19:58:05 +08:00
薛纪克таxuejike 4d5ee2d01c feat(agents): drag and delete the whole task list selection (#6933)
In the Agents task list, dragging a row of a multi-selection moves every selected task (into a group, Pinned, a status group, or before or after a task, keeping their order), and Delete deletes the selection while the list has focus. Tree collapsed the selection to the pressed row on mouse down, before a drag could start; a press on a selected row now narrows the selection only on a release without movement. agents.deleteTasks gets a list-focus key binding like agents.archiveTasks, and a click or arrow key opens the session without taking focus from the list; Enter and double-click still focus it.

Closes #6932

Co-authored-by: xuejike <[email protected]>
2026-11-30 19:56:24 +08:00
l0ng-ai 2ecb44098a fix(debugger): drop lldb-dap pseudo paths on Windows too (#7030)
A referenced source's pseudo path such as /usr/lib/swift/libswiftCore.dylib`swift_willThrow was kept on Windows, where a path with a root but no drive is not absolute, so frames_drop_pseudo_paths_of_referenced_sources failed on Rust (windows-latest) since #6961. A rooted path now counts.
2026-11-30 19:48:37 +08:00
Mollo-i b1039bc175 feat(search): select Search Everywhere results in the Project view (#6955)
File, symbol and text results in Search Everywhere get Select in Project View, in the Alt+Enter menu and in a new right-click menu on the row: it closes the popup and selects the result in the Project tool window. This helps with files that open in another application, such as a .doc, where choosing the result leaves no trace of where the file lives. The item is offered only for paths inside the project. One item list now feeds both menus, and Open to the Side is disabled for folders.

Co-authored-by: Greenker <[email protected]>
2026-11-30 19:43:10 +08:00
薛纪克таxuejike 182c7c1dbb feat(editor): double-click the empty tab strip to maximize the editor (#6969)
A double click on the empty part of an editor tab strip (not on a tab, a button or trailing content) now maximizes the editor by hiding all tool windows, the same as a double click on a regular tab; doing it again restores them. Tabs gets an onBlankDoubleClick callback that fires only for the strip itself or its scroller.

Closes #6968

Co-authored-by: xuejike <[email protected]>
2026-11-30 19:42:00 +08:00
l0ng-ai c8dc613485 fix(projects): offer New Tab when opening a remote project or from a remote window (#7017)
The Open Project prompt gated Attach and New Tab on one flag that required a local project in a local window, so opening an SSH/WSL project, or any project from a remote window, offered only New Window and This Window, and "Open project in: tab" fell back to a new window. Attach still needs a local project in a local window, but a project tab is a window of its own joined to this window's group, so it now applies whenever this window has a project: a remote project opens in a new window that joins the group.

Fixes #6923
2026-11-30 18:36:46 +08:00
audichuang 88a6bbca14 perf(vcs): run Git outside the log index lock so commit details and one-commit queries do not wait for a history walk (#7006)
history::log held the log index lock for its whole run, so every Git subprocess it started (file history, path selection, range ids, rev-list, the --grep text filter) ran under the lock, and commit details plus the one-commit queries behind inline blame waited for the whole walk. The lock is now taken per phase: Git runs unlocked and only in-memory work holds the guard. update_head_reachable runs under the guard that builds the rows, and the shared nodes are used only when they were built for the query's shallow set, rebuilt otherwise, so a query stays on one snapshot while others run in between.

Co-authored-by: audichuang <[email protected]>
2026-11-30 18:32:37 +08:00
Ivan b9e555300f fix(macos): defer moving a full-screen tab out of its group until the app is active (#6997)
Close Project on a tab of a native full-screen group moves the tab into a window, and so a full-screen Space, of its own. While the app is inactive, AppKit's enter-full-screen transition for that Space crashes in SLSWindowServerClientSpaceAddWindowsAndRemoveFromSpaces as soon as the web view draws its next frame, taking every project window with it. Detaching such a tab is now deferred: the tab stays in its group (showing Welcome) and moves to its own Space when the app is next activated. Foreground closes and windowed groups detach immediately as before.

Fixes #6937

Co-authored-by: Pecnikas <[email protected]>
2026-11-30 18:30:57 +08:00
l0ng-ai 7ff223001b fix(fonts): keep Latin text monospaced when the chosen font isn't installed (#7013)
With a fallback font set and a primary family that isn't installed, every glyph came from the fallback. A CJK fallback such as PingFang SC has proportional Latin letters, and the terminal sized its cells for the widest of them, so text came out spread apart. Once the native font catalog shows the family is missing, the bundled JetBrains Mono now stands in for it ahead of the fallback, which still covers the glyphs it lacks. Applies to every monospace stack built from the editor or terminal font settings.

Fixes #6974
2026-11-30 18:25:17 +08:00
l0ng-ai cc9279a6d6 fix(editor): indent Slint element blocks by their braces (#7012)
Slint borrows the C mode for highlighting until slint-lsp's semantic tokens arrive, and Enter used that mode's statement indentation: after a child element's closing brace the next line went back to column 0, and nested blocks below it opened one level short. Slint now uses the brace-based fallback indentation even though a highlighting mode is loaded. No other language with a borrowed mode has this mismatch.

Fixes #6976
2026-11-30 18:22:26 +08:00
l0ng-ai 1cfbb24b31 fix(project-tree): add Select Opened File as a Project View action for the keymap (#7011)
The keymap listed "Select Opened File" only as the Database view action, so a shortcut assigned to it revealed the file in the Database view and did nothing in a project without data sources. Like IDEA's SelectOpenedFileInProjectView, the Project view now has its own Select Opened File action (the toolbar button runs it), and imported IDEA keymaps map SelectOpenedFileInProjectView and SelectInProjectView.

Fixes #6978
2026-11-30 18:18:33 +08:00
l0ng-ai a8a0cdb315 fix(plugins): load precompiled plugin components in the signed macOS app (#7010)
compile_cached loaded the cached .cwasm with Component::deserialize_file, which maps the file and makes its pages executable; the hardened runtime of the signed app refuses that, so every activation discarded the cache and compiled the plugin again. The file is now read into memory and deserialized from the bytes. A new test checks the cache is hit; signed with the app entitlements it fails with the old code.

Refs #6954
2026-11-30 18:16:20 +08:00
l0ng-ai 8ab776ada6 fix(keymap): import an Emacs-based IDEA keymap on top of $default, not macOS (#7008)
presetOf picked the macOS preset for any parent whose name contains "mac", including "Emacs", so a keymap derived from IDEA's Emacs keymap was imported as based on macOS. The match is now on the word (Mac OS X, macOS), and Emacs and its copies map to the $default preset they inherit in IDEA.

Refs #6896
2026-11-30 18:14:01 +08:00
LU XIANGRUIтаwildcatDownstairs 88b463d888 fix(debugger): let a tsx program behind a remote root run under Attach to Node.js (#6926)
On a loopback address js-debug makes the program require its child-process bootloader by a local path; behind a remote root (published container port, SSH tunnel) that path is missing, tsx's esbuild worker exits and the program waits for it forever. Attach to Node.js with a remote root, and Node.js debugging on SSH/Docker/Compose run targets, now pass autoAttachChildProcesses: false.

Closes #6925

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 18:11:42 +08:00
LU XIANGRUIтаwildcatDownstairs ac88059d0f fix(plugins): index the first 20,000 files of a large project instead of none (#6958)
Plugin navigation discovery refused the whole project above 20,000 matching files, counted out-of-scope and git-ignored files toward the cap, and showed the raw error text half translated. Discovery now keeps the first 20,000 in-scope, non-ignored files, reports total/truncated, and shows one warning naming the project and the counts.

Fixes #6940

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 18:11:27 +08:00
Waiting-Night a09c9aa9ad fix(java): navigate inherited method references to their declarations (#6953)
JDT's selection-based definition can answer the functional interface method (Function.apply) for a method reference whose method is inherited. Go to Definition on a Java method reference now asks the app-owned JDT command openidea.java.methodReferenceDefinition (java-usages 1.20.1) for the AST method binding; Lombok accessors without a source range fall back to their field or declaring type. The bundled jar is reproducible from source (SHA-256 a111a935...); tests/method-reference.py checks the command against a real JDT LS.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-30 18:06:54 +08:00
LU XIANGRUIтаwildcatDownstairs 7fef1e10a8 fix(ai-completion): say why no suggestions appear and let the model be chosen (#6936)
The plugin's optional net:localhost permission is not ticked by default, and a missing Ollama model answers 404; both only reached the IDE log. Failed requests now show one warning that says why and what to do, and a new AI Completion: Set Model command (Set Endpoint URL also asks for its value from the palette). The host answers an empty list instead of "no server supports inline completion" when a plugin offers ghost text, so the editor keeps asking while typing.

Fixes #6930

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 18:03:40 +08:00
l0ng-ai 1748c98ac8 test(agents): type the store import of the long agent form e2e (#7004)
The e2e from #7003 imported the store by a literal /src path, which pnpm typecheck rejects (TS2307); it now imports through a variable typed as the store module.
2026-11-30 17:59:41 +08:00
l0ng-ai 399ae25ab6 fix(agents): keep a long agent form scrollable above the composer (#7003)
An agent form (ACP elicitation, used by opencode for its questions) had no height limit, so a form with several fields pushed its last choices, its buttons and the composer out of view with nothing to scroll. FormCard now uses the pinned question card layout (at most half the window, scrolling within), and the pinned card shrinks when the session is shorter so the composer stays in view.

Fixes #6945
2026-11-30 17:58:47 +08:00
audichuang f28dd8125b fix(deps): update yanked async-executor 1.14.0 to 1.14.1 (#6971)
crates.io yanked async-executor 1.14.0 for a use-after-free when a Waker fires during Executor::drop (smol-rs/async-executor#164). Lock-only update to 1.14.1.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:51:51 +08:00
arookieofcтаarookieofc d5f7e0a99b fix(maven): delegate launch classpath to Maven without jdtls (#6984)
With delegateBuild on a Maven module, launches without jdtls (java-analyzer) used the language server classpath, which ignores child POM exclusions. They now merge the classpath Maven resolves, as the jdtls path does, and fall back to the server classpath when the probe fails.

Fixes #5586

Co-authored-by: arookieofc <[email protected]>
2026-11-30 17:50:57 +08:00
audichuang a66c9e6d05 fix(vcs): retry git status without rename detection when a partial clone cannot fetch a blob (#6987)
In a blobless partial clone rename detection needs a staged blob it cannot fetch (Restricted Mode sets GIT_NO_LAZY_FETCH, or the promisor is unreachable) and git status fails. Status retries once with --no-renames when git reports the promisor remote.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:50:44 +08:00
audichuang 59bcf7eac5 fix(refactor): keep external changes when a file move's reference edits are rejected (#6990)
FileMoves::perform restored its pre-edit snapshots when the reference edits were rejected, overwriting a change another program wrote after the snapshot. apply_edit is transactional and leaves nothing behind on error, so a rejected edit is now returned without a restore; a failed move still rolls back the applied edits.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:50:29 +08:00
LU XIANGRUIтаwildcatDownstairs fe21c67537 fix(debugger): do not open lldb-dap's disassembly pseudo paths as files (#6961)
lldb-dap reports frames without debug info with a sourceReference and a pseudo path such as libswiftCore.dylib`swift_willThrow, which opened as a missing file. An absolute path that does not exist on a referenced source is dropped, so the stop selects the first frame with source.

Closes #6960

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 17:50:10 +08:00
audichuang c085f52b59 fix(editor): paste an image from the Markdown editor's context menu without WebKit's Paste callout (#6994)
On macOS the context-menu Paste in a Markdown editor called execCommand(paste), which shows the WebKit Paste callout. Images and copied image files are read through the backend instead; text takes the native path.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:43:14 +08:00
Bin 0104ed63c1 fix(project-tree): open external files on double-click only (#6993)
Single-click in the project tree opened files associated with an external application. Those now open on double-click only.

Co-authored-by: ffgenius <[email protected]>
2026-11-30 17:42:57 +08:00
Chris-young42таChris-young42 a441b2a906 fix(java): remove extra spaces from annotation completions (#6989)
JDT LS appends a space to annotation completions; it is dropped when nothing follows that needs a separator, so no trailing whitespace after @Override or space before the parenthesis.

Co-authored-by: Chris-young42 <[email protected]>
2026-11-30 17:42:42 +08:00
audichuang c4f7fec86c fix(build): keep output the channel delivers after the build result (#6988)
Tauri delivers channel messages over 8 KiB through an async fetch and holds later ones back, so output can arrive after the command result. Output and step events of the latest build are still applied after it finished, until another build takes the window.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:42:28 +08:00
audichuang 37a8aae018 fix(vcs): keep focused and unsaved all-in-one diff blocks mounted while the view has no height (#6983)
With no height (a maximized tool window over the diff) the virtualizer rendered no range and unmounted the focused and unsaved blocks, saving an unsaved index edit. The view now reports at least 1 px and keeps the last measured block sizes while hidden.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:42:16 +08:00
LU XIANGRUIтаwildcatDownstairs acc48a4816 fix(run): clear a selected test's output with Clear All (#6982)
A selected test node shows the output captured on that node, which Clear All did not touch. Clear All now drops captured test output as well; statuses and the tree stay.

Closes #6975

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 17:42:00 +08:00
audichuang 8301326289 fix(ui): remeasure the custom scrollbar when its content grows without the scroller resizing (#6973)
The custom scrollbar observed only the scroller, whose size does not change when its content grows (a Markdown preview reflowing after a width change). It now also observes the scroller children, re-observing them when they are replaced.

Co-authored-by: audichuang <[email protected]>
2026-11-30 17:41:43 +08:00
sonnartliao 4c71299745 fix(editor): resolve C declarations without include metadata (#6959)
Without a compilation database clangd leaves nested includes unresolved or answers with the call site itself. For C-family files an empty or self-only answer falls back to syntax and the project index (including identifiers in macro bodies), Go to Implementation from a header finds the source definition, and member access is never guessed by bare name.

Co-authored-by: sonnartliao <[email protected]>
2026-11-30 17:41:27 +08:00
Jimmy Song 08249ca5fd fix(viewers): reload preview images when files change on disk (#6952)
Preview image data URLs were cached by path forever. The cache now drops entries on fsChanged and open Markdown and reStructuredText previews reload the affected images.

Co-authored-by: zhiai007 <[email protected]>
2026-11-30 17:41:09 +08:00
Waiting-Night edd6746439 fix(editor): stop type hierarchy searches from library gutter markers (#6951)
Library gutter markers asked jdtls for inheritors of every visible class, which on a JDK interface ran a full type hierarchy search and timed out. Library sources keep super-method markers but ask for no inheritors; Go to Implementation still answers.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-30 17:40:54 +08:00
LU XIANGRUIтаwildcatDownstairs 695424beb2 fix(editor): reopen restored library source tabs read-only (#6950)
The library-source mark lived only in memory, so a tab restored after a reload opened the same file editable. The editor session now saves the mark and restores it before the documents open.

Closes #6947

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 17:40:41 +08:00
LU XIANGRUIтаwildcatDownstairs 9943d71d02 fix(editor): show no diagnostics in library sources (#6946)
Language servers publish errors for files they generate or read outside the project (sourcekit-lsp parse errors in its .swiftinterface). Library sources open read-only, so their diagnostics are dropped from the editor and the Problems view.

Closes #6943

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 17:40:25 +08:00
l0ng-ai e03c5507f7 ci: publish a nightly prerelease of main every day (#6962)
nightly.yml builds main at 18:00 UTC, when it has moved since the last
nightly, as v<next patch>-nightly.<date>: a tag on a commit over main that
only sets the version (scripts/nightly-prepare.ts), built and published by
release.yml, which can now be called with `nightly: true` (notes from the
previous nightly; no official plugins, CNB mirror or Homebrew cask).

Nightly apps update from the rolling `nightly` release, which holds the
newest nightly's latest.json, and skip the CNB mirror, which carries only
stable releases. Stable apps keep reading releases/latest, never a
prerelease. The MSI gets a numeric version (last release + run number),
and the newest 14 nightlies are kept.
2026-11-30 15:55:50 +08:00
l0ng-ai 745099feaa chore: v0.1.56 2026-11-30 15:07:20 +08:00
l0ng-ai 6894d0a4e3 fix(web): declare the GTK dialog probe and hotkey probe as always allowed in the web shell (#6967)
file_dialog_needs_gtk and system_probe_hotkeys are trust = always on the desktop, but the web shell table still declared them Trusted, so commands::tests::web_shell_commands_match_the_desktop_declarations failed on every Rust job on main.
2026-11-30 15:06:25 +08:00
l0ng-ai f80be658ea fix(run-targets): apply a published ports edit that hasn't left the field (#6966)
Published ports and the other list fields of a run target were stored only on blur, so OK pressed with Enter, or applying the settings while the field still had focus, dropped the edit. The list is now staged on every change; the text stays as typed while the field has focus.
2026-11-30 15:01:45 +08:00
l0ng-ai 1c377b7f66 fix(run): show configuration types in the UI language in Add New Configuration (#6965)
The Add New Configuration type picker and the Edit Configurations Templates list showed each type's English label while the form showed the translation. Rows now carry the translated label, which the list also sorts and searches by.
2026-11-30 15:01:28 +08:00
LU XIANGRUIтаwildcatDownstairs 093cf6fdf8 feat(cpp): switch between a header and its source file (#6928)
A Switch Header/Source action (F10; Alt+O in the VS Code keymaps) opens the counterpart of the current C, C++, Objective-C or Objective-C++ file. It asks clangd with textDocument/switchSourceHeader (new lsp_switch_source_header, cancellable), so headers in include/ and sources in src/ are found; without clangd or an answer it opens a project file with the same stem and a counterpart extension, as Related Symbol does.

Closes #6927

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

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 12:00:32 +08:00
LU XIANGRUIтаwildcatDownstairs 9b578c2fad feat(run): debug Node.js on SSH, Docker and Compose run targets (#6919)
Debug on a Node.js configuration or a .js / .ts file run whose run target is SSH, Docker or Compose now debugs the program there, extending the Python flow. A js-debug configuration starts node with --inspect-brk on a free port (0.0.0.0 inside the container, published on this machine's loopback only; the host's loopback over the existing SSH forward). The run prints the project folder on the target as a system line, which the frontend reads to map sources before attaching js-debug. tsx is refused for now (it hangs once js-debug attaches); other programs get an error naming the fix.

Closes #6901

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

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 11:52:59 +08:00
LU XIANGRUIтаwildcatDownstairs f5bb97babd feat(js): CSS completion and diagnostics in styled-components and emotion templates (#6917)
Adds the managed tool typescript-styled-plugin (@styled/typescript-styled-plugin, pinned, hosted by vtsls). ide_sdk::apply::configure_styled adds it to vtsls' globalPlugins when it is installed and a package.json at, above or below the server root depends on styled-components or emotion; a tsconfig that declares the plugin keeps one copy. Opening a script that imports one of those libraries offers the install once per project and session. The bounded walk below the root is now shared with CSS Modules Kit.

Closes #6900

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

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 11:49:27 +08:00
l0ng-ai e23088d558 fix(vfs): don't cache ignore rules read before an invalidation (#6929)
GitignoreStack::matcher_for read a directory's ignore files outside the cache lock and stored the matcher afterwards, so a watcher-thread lookup racing a command that rewrote .gitignore and invalidated could leave the older rules cached; the next listing then missed the new entry. Invalidations now bump a generation counter under the cache lock and a lookup stores its matcher only when none happened since it started reading. This made rpc::serves_projects_files_documents_search_and_runs fail intermittently on Windows.
2026-11-30 11:48:07 +08:00
LU XIANGRUIтаwildcatDownstairs 7279f515db feat(xcode): run macOS app schemes on the Mac (#6918)
Xcode run configurations only ran iOS apps on the Simulator. The run now reads the scheme's build settings without a destination and, when its first application supports macOS but not the iOS Simulator (or the Simulator field is macos), builds with -destination platform=macOS and execs the app's executable, so its output reaches the Run console and Stop's SIGINT reaches it; NSUnbufferedIO=YES is set as Xcode does. The destination choice is shared by Clean Build Folder, which now cleans a macOS app's build for the Mac too.

Closes #6907

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

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 11:36:02 +08:00
LU XIANGRUIтаwildcatDownstairs 710d120689 feat(swift): debug SwiftPM executables from swift build's bin path (#6914)
Debug on a SwiftPM executable configuration launched lldb-dap on a hardcoded .build/debug/<product>, which misses -c release, --scratch-path / --build-path and the .build/out/Products layout of recent toolchains. The launch now carries a swiftpm key (product and the swift run build options), and ide-dap resolves program with swift build <options> --show-bin-path, like the cargo key. The Swift docs describe the SwiftPM run configurations and Debug.

Closes #6913

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

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 11:33:15 +08:00
JunChang Peng 38709947fe feat(database): give a table's tab its data source's colour (#6916)
A table's EditorInput has no path, so the path-keyed file decorations that tint console tabs never reached it. Editor kinds can now supply tabTint, read next to tabTrailing and refreshed by notifyTabTintsChanged when a source's colour changes; the table kind answers with its source's colour, and the data view's toolbar carries it too. A selected tinted tab now shows the colour at full strength instead of mixing it with the selection background, and inactive tinted tabs are dimmed.

Closes #6915

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

Co-authored-by: junchangpeng <[email protected]>
2026-11-30 11:31:00 +08:00
JunChang Peng d9fbb19787 feat(database): show a table's DDL from the data view (#6909)
The data view's toolbar gets a DDL button that opens the table's definition through the same openDdl the tree's Go to DDL uses, so checking an index or constraint no longer means leaving the rows. It is disabled while the DDL loads, for custom JDBC sources (no vendor DDL) and for catalog-qualified tables.

Closes #6910

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

Co-authored-by: junchangpeng <[email protected]>
2026-11-30 11:30:32 +08:00
LU XIANGRUIтаwildcatDownstairs 6aa613d4ec fix(editor): drop the unused gutter icon group re-exports that fail knip (#6920)
prefs.ts re-exported GUTTER_ICON_GROUPS and GutterIconGroup from ./localAppearance, but their users import localAppearance directly, so pnpm knip failed on main since #6912.

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

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 11:26:32 +08:00
LU XIANGRUIтаwildcatDownstairs 60ef498deb feat(run): add Clean Build Folder and Delete DerivedData for Xcode schemes (#6902)
Xcode projects had no way to clean a scheme's build or clear its DerivedData. Clean Build Folder runs xcodebuild clean in the Run tool window with the same flags as an xcode run. Delete DerivedData resolves the project's <Name>-<hash> folder from xcodebuild -showBuildSettings (never a guessed hash) plus the IDE's own run builds, asks, moves them to the Trash and restarts sourcekit-lsp. Both are in a new Build › Xcode submenu, Find Action and the .xcodeproj / .xcworkspace context menu; Flutter's and Xcode's build submenus now come from one dynamic_submenu table in both menu renderers.

Closes #6897

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

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 11:25:40 +08:00
LU XIANGRUIтаwildcatDownstairs 719b73ecd9 feat(xcode): flag new source files an Xcode project doesn't build (#6888)
xcodebuild compiles only the files a target lists, so a source file created or renamed in the IDE inside a classic .xcodeproj group was silently left out of the build. After file operations in the IDE (one check per burst), an XcodeGen or Tuist project gets an offer to regenerate it, and a classic project without synchronized folders gets a warning naming the files project.pbxproj doesn't list, with Open in Xcode. Regenerate Xcode Project is also in Find Action and in the context menus of project.yml / Project.swift. Names are matched as whole file names, and file operations without source files skip the check.

Closes #6887

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

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 11:20:17 +08:00
l0ng-ai 6c3284c300 fix(settings): change the local data directory without an open project (#6921)
The Caches settings commands were trusted-only, so the welcome window could neither show the current location nor apply a custom directory, though the directory is an app-wide setting. Reading it now runs everywhere and changing it runs outside Restricted Mode. The Linux GTK file chooser and the global hotkey probe had the same gate and are now always allowed.

Fixes #6886
2026-11-30 11:15:49 +08:00
Bert Verhelstтаbertyhell 69cec11761 ci: run the release jobs that read secrets in the release environment (#6873)
The signing keys and tokens are repository secrets, readable by any workflow on any branch, and secrets: inherit hands them all to the called release workflows. The jobs that read a secret other than GITHUB_TOKEN now name environment: release (plugins, plugin-keys, build, server-signatures, mirror, cask). secrets: inherit stays until the secrets move into the environment, so releases build and sign as before; the environment is created on first use with no rules. Refs #6701.

Co-authored-by: bertyhell <[email protected]>
2026-11-30 10:52:02 +08:00
l0ng-ai 6c76cfd316 fix(editor): keep the run gutter from loading the editor preferences (#6912)
runGutter, which the Language smoke loads, imported gutterIconsOn from cm/prefs, pulling about 40 editor modules into the smoke inputs and failing scripts/smoke-paths.test.ts on main. The gutter icon groups and the per-editor appearance override move to cm/localAppearance, which prefs re-exports; the gutter providers import it directly and language-smoke.yml lists the new file.
2026-11-30 10:51:33 +08:00
audichuang 66496221b9 fix(ci): run Language smoke for every language when ide-http changes (#6905)
Since #6893 ide-tools depends on ide-http on macOS, so ide-http is an input of the Language smoke, but the Changes step still listed it as unused and scripts/smoke-paths.test.ts failed on main. Removes ide-http from that list.

Co-authored-by: audichuang <[email protected]>
2026-11-30 10:49:13 +08:00
l0ng-ai e9f3aef5ae fix(markdown): keep the preview painted while scrolling (#6908)
Trackpad scrolling in the Markdown preview could leave a large part of it blank until the next scroll. The preview moves itself on each wheel event with scrollBy, and in WebKit a run of scrollBy calls can leave the compositor at an older, never-painted offset than the page's. Setting scrollTop/scrollLeft keeps them in step; the source editor's large wheel jumps and the diff divider's wheel did the same and now set offsets too.

A fenced code block overflowing by a pixel no longer counts as a vertical scroller, and a nested scroller keeps the wheel only while it can still move in that direction, so scrolling no longer stops over code blocks.
2026-11-30 10:31:45 +08:00
LU XIANGRUIтаwildcatDownstairs 4ca46032c4 feat(run): debug Xcode run configurations on the iOS Simulator (#6889)
Debug on an Xcode run configuration builds and installs the app as Run does, launches it suspended on the iOS Simulator (simctl launch --wait-for-debugger) and attaches lldb-dap to its pid, so breakpoints in the app's Swift sources hit while its output stays in the Run console; stopping the debug session stops the run. simctl holds back its <bundle id>: <pid> line when stdout is a pipe, so the launch script prints it once the suspended process under the installed bundle appears. Detected and new Xcode configurations get debugAdapter lldb-dap. Closes #6885.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 10:27:53 +08:00
Muuтаmuutot 8d8f66dfe5 feat(editor): add active-editor appearance toggles (#6891)
Show Line Numbers, Show Whitespaces, Show Gutter Icons and Show Indent Guides can be toggled for the active editor without changing the global setting. Overrides live in each CodeMirror EditorState, so split panes on one document can differ and untouched editors keep following the settings; line numbers, whitespace marks, indent guides and gutter providers reconfigure through one appearance path, and a local Gutter Icons override can enable providers even when the global setting is off. The toggles are in View > Active Editor, with IdeaVim aliases and unbound keymap entries.

Co-authored-by: muutot <[email protected]>
2026-11-30 10:26:06 +08:00
LU XIANGRUIтаwildcatDownstairs 5229e44a9c feat(swift): resolve and update Swift packages from the IDE (#6899)
Resolve Swift Packages and Update Swift Packages run swift package resolve / update in the Run tool window from the folder of Package.swift, like Go Mod Tidy, using the swiftpm run kind. They are in Find Action (category Swift) and on a single Package.swift in the Project view, editor and tab menus; when the run ends, run configurations and external libraries reload. sourcekit-lsp already reloads on Package.resolved changes through its file watcher, so no restart is added. Documented on the Swift page.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 10:17:00 +08:00
audichuang 7be55e4eec fix(tools): follow the macOS PAC script for tool downloads in Auto proxy mode (#6893)
Tool downloads run through the system curl, which in Auto proxy mode only got the manual macOS proxy from Matcher::from_system(), never the PAC script, so on a PAC-only network language-server installs went direct while the rest of the IDE followed the PAC.

Http::base now asks the same PacResolver the HTTP client uses (ide_http::system_pac_route, evaluated inline with the per-host cache) and passes its proxy to curl as --proxy; while the script loads or fails it answers with the manual proxy, as before. Linux and Windows build the same command as before.

Co-authored-by: audichuang <[email protected]>
2026-11-30 10:14:57 +08:00
l0ng-ai ce206f74af fix(deps): update curve25519-dalek to 5.1.0 (RUSTSEC-2026-0620) (#6903)
cargo deny failed on RUSTSEC-2026-0620: curve25519-dalek 5.0.0, pulled in by ed25519-dalek for extension signature checks in ide-extension, has an AVX-512 backend bug in scalar multiplication. Our builds do not enable that backend; lock-only update to the fixed 5.1.0.
2026-11-30 10:13:10 +08:00
Muuтаmuutot 3c6bc1b29f feat(editor): zoom Quick Documentation with the mouse wheel (#6883)
With Editor > General > Change font size with Ctrl/Command+Mouse Wheel enabled, Ctrl/Cmd+wheel over Quick Documentation changes the documentation font size. One persisted zoom (-6..36 px) is shared by the hover, the F1 popup and the Documentation tool window, and the focused Increase/Decrease/Reset Font Size actions go through the existing font-zoom surface registry. Only documentation typography scales; editor text, toolbar controls and popup scrolling are unchanged.

Co-authored-by: muutot <[email protected]>
2026-11-30 09:12:45 +08:00
audichuang f9a8ad3fa7 fix(editor): do not recreate a file deleted outside the IDE on autosave (#6884)
A dirty buffer whose file another program deleted (git switch, git stash -u, a build clean) was written back by the next autosave, because check_disk_conflict only ran when fs::metadata succeeded.

A missing file (NotFound) now goes through the existing disk-conflict path: autosave refuses and the buffer stays dirty. DocDiskConflict carries deleted, so the notice says the file was deleted and offers no Load Changes from Disk; an explicit save recreates the file and clears the conflict.

Co-authored-by: audichuang <[email protected]>
2026-11-30 09:10:13 +08:00
audichuang 3d3ed6e120 fix(editor): update the status bar when a file's encoding or line ending changes (#6882)
When another program rewrote a clean open file in a different encoding or line ending, Documents::reload_from_disk re-detected and stored the new values but nothing sent them to the editor's DocMeta, so the status bar kept the old encoding and line separator until the tab was reopened; Load Changes from Disk had the same gap for the BOM.

Adds IdeEvent::DocEncoding (modelled on DocLanguage): both reload paths emit it through one helper only when the encoding, BOM or line ending changed, and the DocumentManager updates the meta.

Co-authored-by: audichuang <[email protected]>
2026-11-30 08:00:08 +08:00
Deng Liuтаdengliu 61dbb2f863 docs(agents): add agent resources and lifecycle guide (#6875)
Adds an English and Chinese guide under Guide > AI explaining how plugins, memory, MCP, tools and skills interact across an agent task, and what enters the LLM context window: plugin mcpTools reach the model through the built-in server's tools/list while plugin code stays out of the prompt. Linked from the Agents guide. The walkthrough video was left out to keep large binaries out of the repository.

Co-authored-by: dengliu <[email protected]>
2026-11-30 07:51:43 +08:00
Deng Liuтаdengliu 79e5ddda3e feat(agents): inspect built-in openidea MCP tools in MCP Connections (#6878)
The built-in openidea card in Settings > Agents > MCP Connections is now expandable like the other servers: it shows the tool count, status, stdio command and HTTP endpoint, lists the core and enabled plugin-contributed tools, and the search box filters them.

A read-only mcp_server_tools host command (trust = always) lists them through the same tools_for helper as Registry::tools, so Restricted Mode filtering and plugin tools match what agents see, while external server probing stays trusted-only. Tool descriptions are clamped to two lines with the full text in a tooltip.

Co-authored-by: dengliu <[email protected]>
2026-11-30 07:50:28 +08:00
Elmir Abkerimov 53cc0059a4 perf(macos): unlock 120Hz scrolling in WKWebView (#6874)
WebKit enables PreferPageRenderingUpdatesNear60FPSEnabled by default, throttling rendering updates (requestAnimationFrame, scrolling, viewport updates) to about 60 Hz on ProMotion and other high-refresh displays. The webview configuration now disables it through the private feature API (_features, falling back to _experimentalFeatures on macOS 12.0-13.2), sharing one helper with the TextInputClientSelectionUpdatesEnabled workaround.

To keep frames within the shorter budget: the window-level wheel listener stays passive unless a wheel shortcut is bound (none by default), horizontalScrollHold skips unchanged writes, and the overview lane moves its thumb with a transform and folds the pass-through hit test into its measure pass.

Co-authored-by: w4terlaw <[email protected]>
2026-11-30 07:40:26 +08:00
audichuang 6c945c73ad fix(github): look the pull request up again when the review repository's upstream changes (#6880)
When the review repository is not the VCS store's branch root, connectedBranch() reports upstream: null, so a change of that branch's upstream under the same HEAD (git branch -u, git push -u) never triggered a new pull request lookup.

For such a root each VCS refresh re-reads branch.<head>.remote/.merge and looks the pull request up again only when they differ from the last lookup; the change is recorded when read so a later reset also supersedes a late answer. The single-repository path is unchanged and no GitHub request is sent while the config is unchanged.

Co-authored-by: audichuang <[email protected]>
2026-11-30 07:26:25 +08:00
audichuang 51b93d25bd fix(github): check out the Review Mode branch in the repository the sync check uses (#6879)
"Update Branch to Enable Review Mode..." ran gh pr checkout in connectedRoot() while the sync check and pull request lookup use reviewRoot() (#6622), so with a worktree or a second clone selected the update acted on another repository and could fail with "refusing to fetch into branch checked out at ...".

checkoutPullRequest takes an optional root (default connectedRoot(), so other callers keep theirs); updateReviewBranch captures reviewRoot() before the details reload so a selection change during the reload cannot move the checkout.

Co-authored-by: audichuang <[email protected]>
2026-11-30 07:25:46 +08:00
l0ng-ai c0b5789dd6 fix(run): rebuild the WAR before redeploying a copied Tomcat update (#6871)
Update classes while debugging copies the compiled outputs into the exploded
deployment, then HotSwaps. When HotSwap could not apply the change (a new
class or method) it fell back to a redeploy, which explodes the recorded WAR
into the deployment again; that WAR predates the change, so the old classes
came back and classes added since were removed while the IDE reported
"Application updated". The WAR is now rebuilt before that redeploy.

Refs #6603
2026-11-30 02:05:05 +08:00
l0ng-ai 016240ac1b fix(windows): open one Settings window when it is requested in a burst (#6870)
The auxiliary-window commands are async, so several requests for the same
window (Ctrl+Alt+S pressed quickly or held) could all pass the already-open
check before the first window registered; five parallel requests opened
five Settings windows for one project window. The window's creation is now
claimed before the check, and a request arriving during the build leaves
its launch for that window and returns.

Fixes #6630
2026-11-30 01:36:01 +08:00
l0ng-ai 97598641be fix(agents): keep the reader's place when streamed content reflows above or below (#6863)
Scrolled away from the end while a reply streams, the view jumped when rows
changed height (a reasoning folding once the next tool call arrives, a lone
call joining a folded run): WebKit has no scroll anchoring. Away from the
end, Stream now keeps the row at the top of the view in place after every
render, row resize and scroll; content that gets shorter below leaves blank
room (now an ::after spacer) instead of pulling the view down. Following
the end is unchanged.
2026-11-30 01:25:34 +08:00
l0ng-ai f220ceb117 feat(data-dirs): portable installs with an openidea.properties file (#6869)
An openidea.properties next to the executable (the AppImage file on Linux,
the folder holding OpenIDEA.app on macOS) sets the OPENIDEA_CONFIG_DIR,
OPENIDEA_DATA_DIR, OPENIDEA_LOCAL_DATA_DIR and OPENIDEA_LOG_DIR variables at
start, so a portable install needs no environment. Relative paths are taken
from the file's folder and the environment wins. Applied first thing in main
so every directory and child process sees the same locations.

Closes #6207
Closes #6437
2026-11-30 01:06:22 +08:00
l0ng-ai 263c95738e fix(test-runner): show the run's time when the runner reports no total (#6868)
The test status bar only showed a duration from the runner's summary line.
JUnit runs through the IDE's runner report each test's time but no total,
so the bar showed none. TestResults.totalDurationMs() now falls back to the
tests' summed time; the status bar and the export share it.
2026-11-30 00:55:13 +08:00
l0ng-ai 3a07f05a75 fix(endpoints): keep every Spring controller in large multi-project trees (#6867)
The Spring route source scan kept every Java/Kotlin file containing
"Mapping" (MapStruct mappers, DTOs, @Mapping) and stopped at 1024 files.
In a large multi-module backend those filled the budget and, with the
parallel walk, which controllers survived varied between runs.

Only files naming a request mapping annotation and a controller or Feign
client are kept now (what the endpoint index reads), the caps are raised
to 8192 files / 128 MB, and hitting a cap is logged.
2026-11-30 00:48:16 +08:00
Muuтаmuutot 81d0ada2f3 feat(vcs): maximize selected Git Log commit messages (#6864)
Adds Maximize Commit Message after Copy Revision Number in the Git Log and
File History commit menus and on the commit details toolbar. It opens a
resizable, scrollable dialog with the full message and metadata of every
selected commit (read-only commits included); disabled without a
selection.

Co-authored-by: muutot <[email protected]>
2026-11-30 00:45:16 +08:00
Muuтаmuutot 04bea8718e feat(vcs): refresh Git Log with the Refresh shortcut (#6862)
Adds the Git Log Refresh action (Vcs.Log.Refresh) for Git Log and File
History, bound to the Refresh shortcut (Ctrl+F5 on Windows/Linux, Cmd+R on
macOS) and scoped to the log so other bindings keep the key elsewhere. The
toolbar button and the action share one refresh path that keeps the current
log while reloading, invalidates commit-detail caches for the visible
repositories and is ignored while the log is already loading.

Co-authored-by: muutot <[email protected]>
2026-11-30 00:36:23 +08:00
l0ng-ai 7f32d04b19 feat(plugins): open files as text and contribute to Open In (API 1.19) (#6866)
Plugins can open a file in the built-in text editor even when a custom
editor claims it (workspace.editor open-as-text, SDK open_editor_as_text),
and commands can contribute to the Open In submenu (openIn menu location,
file as the argument, no submenus). Docs, versioning table and rebuilt
components included.

Fixes #6852
Fixes #6853
2026-11-30 00:32:41 +08:00
Muuтаmuutot 4a714b2eff feat(editor): speed-search navigation bar children (#6855)
Typing in a Navigation Bar child list (the floating Alt+Home bar and the status-bar breadcrumbs) filters its rows with fuzzy matching and highlights the matched characters; Backspace edits the query, Escape clears it before closing, and Enter opens the selected match. The query resets when the list moves to another folder or back to a parent.

The typed text shows in a row above the list, red when nothing matches, as in the project tree's speed search.

Co-authored-by: muutot <[email protected]>
2026-11-30 00:07:33 +08:00
l0ng-ai 83b273ec4c fix(editor): keep a horizontally scrolled view in place while line-end hints refresh (#6865)
Line-end hints (inline blame, line-end lenses, plugin messages) draw from a zero-width anchor: they widen the scroll range but not the content, and most leave on an edit and return a moment later. While one was away the range shrank and the browser clamped scrollLeft, so a horizontally scrolled editor jumped sideways on every keystroke.

A 1px spacer at the visible right edge, moved on every scroll and geometry change, keeps the range from shrinking under the view without adding scroll room. Covers every line-end hint, not only blame.

Fixes #6624
2026-11-30 00:02:14 +08:00
Muuтаmuutot 37e2e250e9 feat(vcs): focus Git Log text filter with Ctrl+L (#6861)
Adds Focus Text Filter (Vcs.Log.FocusTextFilter, Ctrl+L) to Git Log and File History: from the commit list it focuses the message filter, from inside the filters toolbar it returns to the commit list.

The action is ordered ahead of the Agents input (also Ctrl+L in the Windows keymap), which otherwise took the key whenever an agent task was on screen, and it leaves popups their own Ctrl+L. Eclipse keymaps share Go to Line's Ctrl+L with it; the title has a zh entry.

Co-authored-by: muutot <[email protected]>
2026-11-29 23:48:08 +08:00
l0ng-ai 16c2613cc0 fix(agents): harden the GitHub skill installer
- Resolve each symlink target through the other symlinks of the skill,
  folding case, and reject trees that place entries beneath a symlink.
  Installs create directories without following symlinks and re-check
  every created link on disk before the skill is moved into place.
- Scan every form of an `allowed-tools` value (block scalars, flow and
  block sequences, continuation lines, quoted keys, aliases, escapes)
  for shell grants instead of only inline values and `-` lists.
- Install exactly the tree the preview showed: the request carries the
  preview's tree SHA and the installer fetches that tree, so commits
  pushed to the ref after review are not installed. Downloaded blobs
  are checked against their Git object id.
2026-11-29 23:21:59 +08:00
arookieofcтаarookieofc e40a03c373 fix(run): shorten long Java debug launch command lines (#6802)
Run launches already shorten long Java command lines, but Debug through java-analyzer sent the full classPaths list, and the Kotlin debuggee was spawned with java -cp and the whole classpath, so large JDK 8 Spring Boot projects on Windows failed with os error 206. java-analyzer launches now pack an oversized classpath into a temporary manifest-only pathing jar (works on JDK 8 and later), the Kotlin debuggee goes through the same shortening as Run, and the session removes its temporary files when it stops.

Fixes #4733

Co-authored-by: arookieofc <[email protected]>
2026-11-29 22:54:43 +08:00
l0ng-ai cf6d8fa510 fix(remote): download the server from the update source and verify its signature (#6860)
Remote development fetched openidea-server from GitHub only, even when the app updates from the CNB mirror. The server now comes from the configured update source first, then the other host. Releases sign every server archive with the updater key in a dedicated server-signatures job, the only one given the key, and the app verifies the archive against the updater public key from tauri.conf.json, so a signed archive is trusted from either host. Releases without signatures keep the GitHub download checked against its .sha256. When a signature exists but no host serves a matching archive, the download fails instead of falling back to an unverified binary.

Fixes #6747
2026-11-29 22:54:25 +08:00
arookieofcтаarookieofc 73ee2117e9 fix(maven): run plugin prefix goals under the plugin's coordinates (#6807)
A goal typed or picked as prefix:goal (spring-javaformat:apply) reached mvn verbatim, and Maven only resolves prefixes of its default plugin groups when the plugin metadata is missing from the repositories, so plugins such as io.spring.javaformat failed with No plugin found for prefix. Goals whose prefix matches a plugin of the project's effective model (inherited plugins included) now run as groupId:artifactId[:version]:goal, keeping @execution; flags and their values, phases, full coordinates and unknown prefixes stay as typed. The configuration name keeps the prefix form.

Fixes #5570

Co-authored-by: arookieofc <[email protected]>
2026-11-29 22:52:46 +08:00
l0ng-ai 1ec634619c feat(plugins): read HTTP responses as they arrive with net.fetch-stream (#6859)
Plugin API 1.19 adds net.fetch-stream: it returns a response-stream once the headers arrive, and the body is read piece by piece with a timeout (read returns nothing with done=false when no bytes came in time). It applies the same grants, net:ask, secrets, body limit and redirect checks as fetch, which now shares the request builder; at most eight streams per plugin, closed on resource drop or plugin stop. The SDK adds host::fetch_stream, ResponseStream and an incremental text/event-stream parser (ResponseStream::events), with mock support; components are rebuilt for the new WIT.

Fixes #6844
2026-11-29 22:49:50 +08:00
l0ng-aiтаrohitdanda 18860f5f98 ci: give signing secrets only to the steps that sign, and pin actions by SHA (#6854)
The updater signing key and Apple credentials were exported job-wide through GITHUB_ENV, so every later step in the release build (dependency installs, third-party actions) could read them. They now reach only the steps that sign: a signed tauri-action build when the updater key is configured (an unsigned build otherwise, since an empty key still counts as set), DMG notarization, and the portable zip. All third-party actions across the workflows are pinned to commit SHAs with their release in a comment, and Dependabot keeps the github-actions ecosystem current with weekly grouped updates.

Refs #6142, #6701

Co-authored-by: rohitdanda <[email protected]>
2026-11-29 22:46:18 +08:00
l0ng-ai 8e9c02cae6 test(e2e): expect editable artifacts in a project without a build tool (#6857)
#6834 made Project Structure › Artifacts editable when the project has no Maven or Gradle build; the settings spec still expected a disabled JAR button. It now checks the button is enabled and the Maven/Gradle note is absent.
2026-11-29 22:45:25 +08:00
l0ng-ai 28b879c668 fix(run): show the iOS Simulator chooser only in confirmed Xcode projects (#6856)
The chooser appeared whenever listing simulators failed, so Restricted Mode windows, hosts without the command and the browser e2e harness showed "Simulators unavailable" in every project's toolbar (breaking the toolbar layout e2e specs on main). A failure is now shown only after a listing has confirmed an Xcode project; later refresh failures still appear in the chooser.
2026-11-29 22:44:10 +08:00
Deng Liuтаdengliu 19aef36354 feat(agents): add Agent Memory settings and a per-session memory picker (#6826)
Adds Settings › Agents › Memory and a Session Memory picker (/memory, /memories, the composer + menu and the context meter link). They list each agent's own instruction files, path-scoped rules and auto-memory notes: AGENTS.md, CLAUDE.md and .claude/rules, .github/copilot-instructions.md and .github/instructions, .cursor/rules, GEMINI.md, and the Claude Code, Codex and Hermes auto-memory folders.

Per-file modes (Auto / Always / Off) and the auto-memory policy (Inherit / Read & Write / Read Only / Off) are stored in settings.toml at user or workspace scope and never edit tracked files. Workspace entries load only in trusted projects. Each driver receives the policy natively: Claude Code through --settings and --add-dir, Codex through its memories config and /memories, GitHub Copilot through excludedTools and the system message, and Hermes through config.yaml. A file set to Always is staged into other agents' sessions. Auto-memory notes can be promoted into the workspace AGENTS.md, and an idle session restarts when a memory policy changes.

Groups of the same agent are titled by scope, for example Claude Code (User) and Claude Code (Auto Memory).

Closes #6810

Co-authored-by: dengliu <[email protected]>
2026-11-29 22:38:20 +08:00
Muuтаmuutot c8efb2917d feat(bookmarks): select and rename lists in the popup (#6849)
List headers in the Bookmarks popup are now selectable rows; F2 on one opens the list name dialog, while file section rows stay non-selectable and are skipped by the keyboard. The popup claims F2 while its list is focused so the global Rename File shortcut does not take it.

Co-authored-by: muutot <[email protected]>
2026-11-29 22:28:40 +08:00
Vladislav Kuzmin 94ddb1807d fix(ci): cache Maven launch classpath artifacts (#6565)
The Rust job's Maven cache only held what resources:resources and compiler:compile resolve,
so the Java launch and rebuild tests on GitHub-hosted runners missed artifacts (#6561).
The preparation step now also runs clean and fetches slf4j-api 1.7.36 with
maven-dependency-plugin 3.8.1 (both pinned, from Maven Central), and the cache key gets a
v2 prefix so the incomplete caches are not restored.

Co-authored-by: principalwater <[email protected]>
2026-11-29 22:15:32 +08:00
l0ng-ai 27447d21a7 ci: keep the Windows Rust cache warm and allow a cold build 75 minutes (#6850)
A Windows run on main that ended in a test failure skipped the Rust cache save, so the next PR
compiled every dependency again (about 19 minutes of Clippy plus 30 of test binaries) and ran out
of the 60-minute limit partway through the tests.

- rust-cache in the Rust job saves on failure too; still only on main, PRs and forks restore.
- The Windows Rust job gets 75 minutes; macOS and Linux stay at 60.

Refs #6496
2026-11-29 22:07:17 +08:00
l0ng-ai 3edbcc0dcd ci(smoke): run the TypeScript project-errors and import-style smokes (#6851)
The TypeScript job in Language smoke now also runs typescript_project_errors (Problems ›
TypeScript Project Errors against the global tsc the job installs) and typescript_import_style
(the import style settings through real vtsls). Both smokes came with #6097 and #6342 but were
not run in CI yet.
2026-11-29 22:06:27 +08:00
Akbar Husain 782a0a98e3 feat(mcp): add debugger tools (#6579)
The built-in MCP server gets xdebug_* tools: debugger status, start a session for a run configuration or run point, control it (resume, pause, step, wait for pause, stop), list/set/remove breakpoints, run to line, threads, stack, frame values, values by path, evaluate and set variable. Breakpoints go through the window's editor model, so they show in the gutter, persist and are the list the user sees; sessions start through the IDE's Debug action with its before-launch tasks. Mutating tools are marked write for the trust gate.

Co-authored-by: akbar1214 <[email protected]>
2026-11-29 21:59:42 +08:00
arookieofcтаarookieofc bd0455bda5 fix(vcs): stop retrying stale git worktrees (#6794)
A failed reopen of a repository never updated the cache stamp, so every gix() call reopened it again and logged a warning, and status fell back to running git in a worktree folder that no longer existed (os error 267 on Windows). The stamp is now updated on failure too, and a repository whose worktree or git directory is missing is skipped by status, ignored-files and path status, logged once, and picked up again when both directories are back.

Fixes #5514

Co-authored-by: arookieofc <[email protected]>
2026-11-29 21:56:58 +08:00
l0ng-ai 13cd8ba006 fix(updates): flush the received bytes before a broken download returns (#6407)
append_body returned on a body error before flushing the tokio File, whose writes run on a
background thread, so a resume could measure the partial file shorter than the bytes already
received (the Linux CI flake in a_broken_download_resumes_with_range). The error is now held
until the file is flushed; the success path and signature checks are unchanged.
2026-11-29 21:53:33 +08:00
Muuтаmuutot 9b413fde11 feat(search): share text match options with Search Everywhere (#6843)
Search Everywhere's Text tab gets Match Case, Words and Regex toggles (Alt+C / Alt+W / Alt+X). They use Find in Files' option store, so both entry points send the same search flags, and the choices are persisted across restarts.

Co-authored-by: muutot <[email protected]>
2026-11-29 21:42:37 +08:00
Muuтаmuutot 29e5571186 fix(editor): extend Select Line through the next line on each call (#6839)
Select Line at Caret dropped the line where a selection ended at column 0 and kept a backward selection's direction, so invoking it again selected the same lines. It now covers every line the selection touches, including the one it ends at the start of, and leaves the caret at the selection end, so repeated calls extend line by line. Folded lines and multiple carets work as before.

Co-authored-by: muutot <[email protected]>
2026-11-29 21:37:01 +08:00
audichuang 08eb9e3ff9 fix(editor): don't save stale text over a file replaced by binary content (#6840)
reload_from_disk treated a file that now loads as binary like a document opened as binary: it refreshed the disk stamp without a disk-change report, so autosave wrote the next edit over the binary file. A detected-encoding buffer now gets the disk conflict too. Reopening a file whose closed tab kept unsaved changes shows that buffer as text instead of a binary viewer that hid what Save would write. A clean buffer gets its own disk-change wording.

Co-authored-by: audichuang <[email protected]>
2026-11-29 21:34:53 +08:00
LU XIANGRUIтаwildcatDownstairs 3d6ad2e254 feat(run): show xcodebuild errors and warnings in Problems (#6848)
Xcode run and test configurations now publish the compiler and linker messages in their xcodebuild output to Problems and the editor as they arrive. A Format::Xcode on top of the GCC/Clang line parser folds in notes, project-level lines and Undefined symbols blocks; XcodebuildMessages resolves positions, maps symlinked paths back to the project, reports each message once across architectures and stops at the build result. A new run clears the files its previous run reported; messages without a location go on the project file.

Closes #6842

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 21:32:42 +08:00
LU XIANGRUIтаwildcatDownstairs 55b23c90b8 feat(lsp): open documents a language server asks to show (#6846)
Advertise window/showDocument support. An existing file: URI becomes an LspShowDocument event that the frontend opens through openCodeLocation with the requested selection and focus; external http/https/mailto links open in the browser. Anything else answers success: false. This makes sourcekit-lsp's Expand Macro and Inline Macro code actions work.

Closes #6845

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 21:27:53 +08:00
l0ng-ai 3fb58cf69b feat(lsp): stop a language server from the status bar popup (#6847)
Running, busy and starting servers get a Stop button next to Restart in the language server popup. LspManager::stop shuts the instance down and leaves it idle, so it starts again when a file it serves is opened; a notification says it will restart when needed. Adds the lsp_stop command.

Fixes #6835
2026-11-29 21:20:31 +08:00
l0ng-ai 3b6ee66b74 fix(debugger): keep the inlay Run to Cursor button while the pointer moves to it (#6841)
The button sits left of the line's first non-space character, over the indent or the gutter, but the hover area started at the text and ended four characters in: moving the pointer to the button left the area and hid it before it could be clicked. The area now includes the gutter, and while the button is shown it reaches the button's right edge on that line.

Fixes #6832
2026-11-29 20:37:05 +08:00
l0ng-ai 243b9ffa7a fix(editor): let other X11 apps keep the primary selection while the window is inactive (#6838)
Another application taking the primary selection makes WebKitGTK clear the page's selection. An editor in an inactive window is still the active element, so CodeMirror wrote its selection back and claimed the primary selection again: terminals and other X11 apps could not keep a selection while an OpenIDEA editor had one. On Linux the editor now accepts the cleared selection while its window is inactive, keeping its carets.

Fixes #6309
2026-11-29 20:03:46 +08:00
LU XIANGRUIтаwildcatDownstairs 86fabc7d1b feat(project-structure): add Project Structure and Open Module Settings entry points (#6834)
Adds Project Structure… to the title bar gear menu (before Settings) and Open Module Settings to the Project view context menu (below Compare With, above Mark Directory as). Open Module Settings is offered on the project folder, Maven / Gradle / Project Structure module folders and sources / resources roots; it opens Project Structure › Modules with the innermost module holding the path selected, and F4 / Cmd+Down on a module folder opens it too. The action uses a new project-structure icon.

Artifacts in Project Structure are now editable when the project has no build tool, since the IDE builds and deploys them itself; with Maven or Gradle the page stays read-only with a note. The Tomcat run configuration's "No artifacts configured" Fix opens Project Structure › Artifacts and the deployment list refreshes when artifacts change.

Refs #404

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 19:15:50 +08:00
l0ng-ai ae3405486f fix(debugger): skip Windows Store Python aliases when starting debugpy (#6831)
The built-in python.toml starts debugpy's adapter with a bare python3. On Windows that name (and often python) resolves to an App Execution Alias in %LOCALAPPDATA%\Microsoft\WindowsApps, which fails to start unless the Store's Python is installed, so a Python Debug Server reported failed to start ...\WindowsApps\python3.exe even with Python installed and on PATH.

The adapter now takes every match on PATH of the command, then python, then the py launcher, and uses the first that is no alias or one that runs, as the IDE already does when it installs Python tools.

Fixes #6818
2026-11-29 19:03:50 +08:00
l0ng-ai dfea6d2c1e feat(plugins): explain capabilities and open a plugin's own settings (API 1.19) (#6830)
[capabilities.reasons] lets a plugin say in one sentence why it asks for a declared capability. The permission dialog and the plugin's details in Settings › Plugins show it below the IDE's own description, marked as the plugin's words and never instead of it; it is translated through the plugin's locales/<tag>.json. Keys must be capabilities under required or optional; reasons are 1-500 characters.

settings.open(page) opens Settings at the plugin's node or one of its declared pages, and settings.open-permissions at its permissions in Settings › Plugins (plugins#permissions:<id>, so it also reaches a separate Settings window), letting a notice take the user straight there. Both work only from a command or event of a window; an undeclared page is not-found.

Plugin API 1.19.0: WIT package, engine, SDK wrappers and mock, rebuilt components; 1.18 is recorded as shipped with 0.1.54. The settings-pages fixture exercises both additions.

Refs #6745
2026-11-29 18:24:29 +08:00
l0ng-ai b9a25462ea fix(vfs): reload ignore rules after git init on Windows (#6829)
A watcher that started outside a repository caches, per directory, that no .git encloses it. After git init the explicit reload invalidated that cache from /, which is no ancestor of C:\ paths, so on Windows the .gitignore and .git/info/exclude entries written right after were not applied to listings until a file event arrived. It now invalidates from the watch root's topmost ancestor.

The Python library index test no longer opens a directory as a plain file to bump its mtime: Windows refuses that, and the bump is only needed for coarse Unix clocks.
2026-11-29 18:13:01 +08:00
l0ng-ai 04e68f6a12 fix(plugins): keep a plugin's settings pages in manifest order (#6828)
A plugin's settings sub-pages registered without an order, so the settings tree sorted them by title. They now keep the order the manifest lists them in, so no new manifest field is needed. Part of #6745.
2026-11-29 17:28:37 +08:00
Muuтаmuutot 4cfc794f60 feat(lsp): open trusted external documentation (#6819)
Documentation entries can carry a trusted externalUrl supplied by the language (never parsed from Markdown links), and the Quick Documentation window and popup menu offer External Documentation for the current page when it is an absolute http(s) URL. The built-in PHP empty/isset documentation is the first provider, pointing at its PHP manual page.

Co-authored-by: muutot <[email protected]>
2026-11-29 17:26:51 +08:00
LU XIANGRUIтаwildcatDownstairs 8105dfd41a feat(logcat): stream iOS Simulator logs in the Logcat tool window (#6822)
On macOS the Logcat device picker also lists booted iOS Simulators (simctl list devices booted). Selecting one follows simctl spawn <udid> log stream --style ndjson --level debug, mapping each log event to a Logcat line (timestamp, pid, thread, a process (subsystem:category) tag, message type to level), so simulator logs get the same level filter, colors, filter language, pause/follow and history as Android. The stream ends normally when the simulator shuts down, the list is empty off macOS or without Xcode, and a missing adb is only reported when there are no simulators either.

Closes #6801

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 17:24:11 +08:00
LU XIANGRUIтаwildcatDownstairs fca497d246 feat(run): choose the iOS simulator for Xcode projects in the toolbar (#6821)
Native Xcode projects get an iOS Simulator chooser next to the run widget on macOS, shown when the project root holds an .xcodeproj or .xcworkspace and no pubspec.yaml (Flutter lists simulators through its own daemon). ide_run::simulator lists available iOS simulators from simctl, booted first, then newest runtime, then name; the menu has Booted and Available sections with Boot / Shut Down per row and Open Simulator, refreshes on open and after each boot or shutdown, and the choice is kept per project root. Xcode run configurations without a pinned simulator launch on the chooser's selection.

Closes #6797

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 17:16:33 +08:00
l0ng-ai 5cb73c5fd1 fix(i18n): translate the Xcode run configuration type (#6827)
The Xcode App run configuration type (#6824) shipped without zh entries for its name, description and fields, so the source-text catalog test failed on main. Adds zh and zh-TW translations; the App.xcodeproj placeholder stays in English.
2026-11-29 17:14:19 +08:00
LU XIANGRUIтаwildcatDownstairs 2b435c8440 feat(run): run xcode schemes on the ios simulator (#6824)
Xcode projects get one run configuration per scheme (xcode:run:<container>:<scheme>), keeping the scheme's launch build configuration, arguments and environment; a workspace next to the projects is used as the container, and the iOS/macOS host app of a Flutter or React Native project is skipped. At launch the host resolves the simulator and the built .app and bundle id from xcodebuild -showBuildSettings -json, then runs a script that builds with xcodebuild into the project cache's DerivedData, boots the simulator, installs and launches the app with simctl --console-pty, with the environment passed as SIMCTL_CHILD_*. Stop turns the SIGINT into the SIGTERM simctl forwards to the app.

Closes #6795

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 17:07:59 +08:00
l0ng-ai db266643aa feat(terminal): add an optional Paste on right click (#6825)
Settings › Tools › Terminal gains Paste on right click (terminal.rightClickPaste, off by default). When on, a plain right-click in a terminal pane pastes the clipboard through the same path as Paste and middle-click paste, so bracketed paste and multiline handling are unchanged; Ctrl or Shift + right-click still opens the context menu, and focus stays in the pane.

Fixes #6634
2026-11-29 16:55:39 +08:00
l0ng-ai 4812d28614 fix(dotnet): show only top-level solutions above the Project view folder (#6820)
Since #6224 the Project view listed every discovered .NET solution and standalone project above the project folder, so a polyglot repository with many solutions in subfolders got dozens of root nodes ahead of its own folder. Only solution and project files directly in a content root (the project root, or each workspace member folder) now get a node there; nested ones stay in their folders, where they already showed.

Fixes #6803
2026-11-29 16:47:13 +08:00
Muuтаmuutot 7c9f343ca4 feat(vcs): open changed files at their repository revision (#6816)
Adds Open Repository Version to the Git Log changed-files menu: each selected file opens read-only at its revision after the change through the existing revision editor. Deleted files and directory symlinks are skipped in both enablement and execution, read-only working-tree files still qualify, and grouped directory selections contribute their files. Includes zh and zh-TW translations.

Co-authored-by: muutot <[email protected]>
2026-11-29 16:40:43 +08:00
Muuтаmuutot d815a8ef44 feat(editor): add Cut Line Backward action (#6815)
Adds Cut Line Backward, mapped from EditorCutLineBackward: it cuts from the start of the previous line to the primary caret (from the document start on the first line) and collects repeated cuts into one clipboard entry like the other kill-ring cuts, a backward cut going before the collected text. Includes zh and zh-TW translations.

Co-authored-by: muutot <[email protected]>
2026-11-29 16:36:01 +08:00
l0ng-ai d22c42e471 test(vim): count Disable Sticky Lines for Language as a known action (#6817)
EditorStickyLinesDisableForLang (#6814) maps to editor.disableStickyLinesForLanguage, which no keymap preset binds, so the :action id check in rc.test.ts failed on main. The action is now in its known list.
2026-11-29 16:32:41 +08:00
Muuтаmuutot a111b32e11 feat(editor): disable sticky lines for the current language (#6814)
Adds a View action, Disable Sticky Lines for Language, that appends the active document's language to the existing per-language disabled list without touching the global Sticky Lines setting. It is available when sticky lines are on and the active editor has a known language (never for a notebook cell), keeps other entries, skips redundant writes, and is mapped from the EditorStickyLinesDisableForLang action id. Includes zh and zh-TW translations.

Co-authored-by: muutot <[email protected]>
2026-11-29 16:22:20 +08:00
Muuтаmuutot f7141f6515 feat(search): inspect previewable results on single click (#6813)
With the preview shown, a single click on a previewable Search Everywhere result opened it and closed the popup, so results could not be browsed in the preview by mouse. A single click now only selects and previews such a row; a double click, Enter or Shift+Enter opens it. Action rows, rows without a preview and clicks with the preview hidden still open on a single click.

Co-authored-by: muutot <[email protected]>
2026-11-29 16:21:58 +08:00
Muuтаmuutot 2d14368d2c feat(structure): jump to filtered symbols with F4 (#6811)
F4 in the File Structure popup navigated only when the tree had focus. The filter input now handles F4 like Enter, opening the selected symbol with the same node resolution, so the empty-query preselection, both narrowing modes, explicit tree selection and unmatched filters behave the same for both keys.

Co-authored-by: muutot <[email protected]>
2026-11-29 16:21:40 +08:00
Vladislav Kuzmin 5cbc4134a1 feat(database): join tables across saved data sources in a query workspace (#6265)
Query Workspace, opened from the Database tree, runs a single SELECT joining two to eight tables from saved PostgreSQL, ClickHouse, SQLite and file-backed DuckDB sources. Typing # picks a saved source without connecting; table and key completion fetch that source's metadata, and optional aliases disambiguate duplicate names. The project host reads the projected columns and join keys on independent read-only connections, complete or failing, within per-input and total row/byte limits, and joins them in the installed DuckDB JDBC driver. Run executes the statement at the caret or the selected statements in order and Execute Script runs the editor; each statement keeps its timing, result tab and page, and Stop or the first error ends the batch.

Closes #6177

Co-authored-by: principalwater <[email protected]>
2026-11-29 16:14:39 +08:00
Vladislav Kuzmin 5a92145ad9 feat(database): open and create DuckLake catalogs (#6206)
A DuckDB data source can be a DuckLake catalog: an existing catalog file or named DuckDB secret is attached read-only, without migrating its metadata version, optionally with a relocated local data directory. Create New DuckLake is a separate, confirmed action that requires a new directory, so testing or reconnecting never initializes a catalog. The Rust side limits DuckLake sources to read-only jdbc:duckdb with no credentials, properties, tunnels or session overrides, and saving catalog settings goes through a dedicated approval command so an older remote host cannot drop them silently. The JDBC bridge JAR is rebuilt from the updated sources.

Part of #334

Co-authored-by: principalwater <[email protected]>
2026-11-29 16:13:52 +08:00
Bert Verhelstтаbertyhell 4354839584 feat(database): edit a PostgreSQL table's owner, tablespace, storage options and persistence (#6693)
Modify Table on a PostgreSQL table gets a Properties tab for owner, tablespace, storage options (including toast.*) and logged/unlogged persistence, with access method and partition key shown read-only. Each change adds one alter table statement to the preview; the owner change runs last, after a rename. The properties are read with one pg_class query, with a fallback for catalogs before PostgreSQL 12; engines that report none show no tab.

Part of #6306

Co-authored-by: bertyhell <[email protected]>
2026-11-29 15:56:23 +08:00
Bert Verhelstтаbertyhell e1a1becadd feat(python): offer imports of names from installed packages in Alt+Enter (#6676)
basedpyright offers import fixes only for project and standard-library symbols. A library symbol index now reads each public module of the interpreter's site-packages once (its __all__, otherwise public top-level definitions, preferring stubs), rebuilt when a folder changes, and Alt+Enter on an unresolved name lists Import rows from it when the server has no import fix for that name.

Closes #6521

Co-authored-by: bertyhell <[email protected]>
2026-11-29 15:55:16 +08:00
Bert Verhelstтаbertyhell ad685ea19e feat(debugger): Disassembly view and instruction stepping for native debugging (#6694)
Native debug sessions whose adapter supports disassemble get a Disassembly tab showing the selected frame's instructions with the program counter highlighted, following stepping and frame selection, including frames without source. Show Disassembly is on the Frames list; Step Over Instruction and Step Into Instruction send steps with instruction granularity and are disabled with a reason when the adapter lacks it. Frames keep instructionPointerReference; when the PC is not where the requested window expects it, the view reads again from the PC.

lldb-dap sends instruction bytes already spaced and pads mnemonics unevenly; the view strips the spacing before grouping the bytes and pads mnemonics to one width.

Part of #5922

Co-authored-by: bertyhell <[email protected]>
2026-11-29 15:54:29 +08:00
Bert Verhelstтаbertyhell 5fb8f21c60 feat(debugger): native Memory View for C/C++ debugging (#6674)
Native debug sessions whose adapter supports readMemory get a read-only Memory View tab: an address or expression field, address/hex/ASCII rows aligned to 16 bytes with the target byte marked, paging and a re-read after each stop. View Memory is offered on variables and watches that carry a memoryReference. The client now declares supportsMemoryReferences in initialize and keeps memoryReference on variables and evaluation results; adapter errors are shown without ending the session.

Closes #5921

Co-authored-by: bertyhell <[email protected]>
2026-11-29 15:52:32 +08:00
Bert Verhelstтаbertyhell 68abe345cc feat(run): read-only caret with keyboard navigation in the Run console (#6670)
The Run console's output gets a read-only caret: Home/End go to the line ends, PageUp/PageDown move a page, Ctrl/Cmd+Home/End go to the start or end of the output, the arrows move the caret and Shift extends the selection. The caret is the browser selection's focus, so mouse and keyboard share it; moves are computed over the virtualized rows, keyboard selections keep only their end rows mounted and copy from the console model. Leaving the end of the output stops following and Ctrl/Cmd+End resumes it; typing returns the caret to the input. Covers Run, Services, stack-trace and thread-dump consoles.

Closes #6295

Co-authored-by: bertyhell <[email protected]>
2026-11-29 15:52:02 +08:00
audichuang 32381cc740 test(agents): wait for the fake agent's connections to close after shutdown (#6809)
Tests that shut the manager down while the fake agent waits on a permission request could hang: returning before the fake's side read the end of the connection dropped the runtime, which then waited forever on the blocked thread. A shut_down helper now waits for each fake connection to close.

Co-authored-by: audichuang <[email protected]>
2026-11-29 15:51:42 +08:00
Bert Verhelstтаbertyhell d897236bd7 feat(vcs): add a global Enable Git integration switch (#6704)
Settings > Version Control > Git gets an Enable Git integration master toggle (global, on by default). While it is off the IDE discovers no repositories and runs no git: status, log, blame, fetch, clone, GitHub, the MCP git tools, plugin repository access and agent worktrees refuse to run, and the Git menu, Get from Version Control, the Git, Commit and GitHub Actions tool windows, Git actions and the branch widget are hidden. Turning it back on restores them without reopening the project. Settings pages gain a reusable master toggle that disables the page's sections, and MenuConfig gains a hidden list applied to the native and in-app menus.

Co-authored-by: bertyhell <[email protected]>
2026-11-29 15:45:38 +08:00
l0ng-ai 68e3adde99 chore(bindings): regenerate after project_roots moved off the IPC thread (#6812)
#6799 made project_roots a spawned desktop command and added a doc line without regenerating src/bindings.ts and the command snapshot, which CI's generated-files check compares.
2026-11-29 15:36:33 +08:00
LU XIANGRUIтаwildcatDownstairs b5aa21e791 perf: cut per-file round trips on network drives (#6799)
On network shares every stat is a round trip, and several paths did one per file or per ancestor. Directory listings take kind, size and mtime from the listing itself; Project view expansion lists through the project watcher and reuses its ignore rules and repository root; root detection probes Unity and virtual-env markers only when their names appear; the Gradle build walk is reused for 30 seconds on hot paths; project_roots runs off the IPC thread; index warm start checks files against one listing per folder, in parallel, and stops when the project closes; git status on network paths compares only mtime and size.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 15:19:27 +08:00
audichuang 652798bc53 feat(http): follow the macOS PAC script in Auto proxy mode (#6783)
reqwest's system proxy ignores macOS Automatic Proxy Configuration. In Auto mode, when a PAC URL is enabled and no *_PROXY variable is set, the script is fetched in the background (refreshed every 5 minutes, retried after failures) and evaluated per request with CFNetwork, caching routes per host. Until the script loads, or when it gives no proxy, requests use the manual system proxy as before. The cached shared client is rebuilt when the PAC URL changes.

Closes #6761

Co-authored-by: audichuang <[email protected]>
2026-11-29 15:17:21 +08:00
Muuтаmuutot 85e417001a feat(structure): prefer File Structure matches near the caret (#6782)
File Structure speed search preselected the globally best match even when the caret was inside another symbol. It now prefers a direct child of the caret symbol, then a sibling, then a descendant, before falling back to the best match, keeping scores, tree-order ties and up/down match cycling.

Co-authored-by: muutot <[email protected]>
2026-11-29 15:16:53 +08:00
Muuтаmuutot 8488eda54e feat(editor): add plain-text paste from history (#6780)
Paste from History gains a Paste as Plain Text choice that inserts the selected entries through input.pastePlain, skipping Reformat on Paste, without rereading the system clipboard. Normal paste, Enter, double-click, multi-selection order and line-wise entries keep their behavior.

Co-authored-by: muutot <[email protected]>
2026-11-29 15:16:33 +08:00
nako-ruruтаnako-ruru d02a3592b0 feat(usages): option to open Find Usages results in a new tab (#6772)
Find Usages reused the selected unpinned result tab, so a new search replaced the previous one. An Open Results in New Tab toggle in the tool window menu makes every search open its own tab; it is off by default and persists with the Preview preference.

Co-authored-by: nako-ruru <[email protected]>
2026-11-29 15:16:08 +08:00
Deng Liuтаdengliu 439b7940a8 feat(agents): recover and resume interrupted agent tasks (#6808)
Agent turns cut off by a window close, quit, restart, backend stop or crash are recorded as interrupted (without changing the task status) and can be resumed from the task view, a notification or automatically on reopen. Closing a window with running tasks asks whether to pause them or arm a one-time auto-resume. Transient network failures hold the turn in Waiting for network and continue once connectivity returns within a configurable window. Auto-resume is refused when the turn was waiting for tool approval, the approval policy changed, several local tasks share a checkout, or a crash loop is detected. Recovery settings are user-only so project settings cannot force auto-resume.

Closes #6758

Co-authored-by: dengliu <[email protected]>
2026-11-29 15:15:42 +08:00
LU XIANGRUIтаwildcatDownstairs de92f3b367 feat(run): run xcode scheme tests with results in the test tree (#6804)
Each Xcode scheme whose TestAction has tests gets a Test <scheme> configuration running xcodebuild test with a fresh result bundle. At launch a -destination is added unless one is configured (the booted iOS simulator, else the first iPhone of the newest runtime). After the run, the result bundle is read through a new run_xcode_test_results command and XCTest and Swift Testing results fill the test tree; reruns of single tests, suites or failed tests use -only-testing with the identifiers from the bundle.

Closes #6796

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 14:48:42 +08:00
LU XIANGRUIтаwildcatDownstairs 5b904f7896 feat(run): read xcode schemes from disk (#6790)
Adds ide_run::xcode::schemes(root), which reads the schemes of the .xcodeproj/.xcworkspace bundles at a project root from xcshareddata/xcschemes, falling back to the current user's xcuserdata (a shared scheme shadows a personal one of the same name). Each scheme carries its container, whether it is shared, the launch and test build configurations, enabled launch arguments and environment variables, and the buildable references.

Closes #6785

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 14:44:47 +08:00
LU XIANGRUIтаwildcatDownstairs 511d3f21bb feat(run): run swift test with results in the test tree and single tests from the gutter (#6798)
swift test runs now feed the test tree: XCTest results are read from its console lines (including failure locations), and Swift Testing results from its JSON event stream (ABI version 0), requested with --experimental-event-stream-output so suite-qualified ids and issues arrive while the run goes. Swift files under Tests/<target>/ that import XCTest or Testing get gutter run icons on XCTestCase test methods, @Test functions and the types holding them or marked @Suite, each running swift test --filter in the package directory; Rerun Failed and Run Selected build one --filter per test.

Adds fixtures/swiftpm-app with XCTest and Swift Testing tests; it declares macOS 10.15 so its Swift Testing tests also build with older toolchains (verified with Swift 6.1).

Closes #6788

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 14:44:13 +08:00
LU XIANGRUIтаwildcatDownstairs 972f18331e feat(swift): offer a BSP config for Xcode projects (#6793)
sourcekit-lsp needs a Build Server Protocol config to understand .xcodeproj/.xcworkspace projects. It now also starts at roots marked by .bsp, *.xcworkspace or *.xcodeproj, and a project root with an Xcode project but no BSP config gets a notification offering to generate one with xcode-build-server or sourcekit-xcode-bsp from PATH (workspace preferred), then restarts sourcekit-lsp; without either tool it explains how to install one. The root is typed as a Swift project in the Project view.

Closes #6787

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 14:43:12 +08:00
LU XIANGRUIтаwildcatDownstairs 77e669c189 feat(run): detect SwiftPM executable products as run configurations (#6792)
A Swift package now gets one run configuration per executable product, read from the manifest source without running it: declared .executable products plus executable targets no product builds (and legacy targets with main.swift). Each runs swift run --skip-build <product> after a swift build --product <product> before-launch task, and Debug launches .build/debug/<product> under lldb-dap with the configured arguments.

Closes #6786

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 14:39:13 +08:00
LU XIANGRUIтаwildcatDownstairs f2641b9697 docs(swift): add a Swift language page (#6791)
Adds a Swift language page (en, zh) covering toolchain setup, how the sourcekit-lsp workspace root is found, SwiftPM packages and Xcode projects through a BSP config, choosing an Xcode with DEVELOPER_DIR, formatting, single-file runs, debugging with lldb-dap, and current limitations.

Closes #6789

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 14:38:45 +08:00
LU XIANGRUIтаwildcatDownstairs 3811dfb512 feat(settings): sync the list of installed plugins (#6756)
Adds a Plugins category to Settings Sync. plugins.json maps each computer's random id to the plugins installed in its data directory; every computer writes only its own list, so lists never conflict and an uninstall only shortens one of them. After a sync, plugins other computers have and this one lacks are looked up in the marketplace and offered in a notification under the marketplace's names; ids that are not marketplace ids are dropped. Install... lets the user pick (each goes through the usual install and consent page) and Ignore These Plugins declines them; nothing is installed or uninstalled on its own. An unreadable plugins.json is left untouched.

The hidden plugins.installFromMarket action now accepts a single id (Import Settings) or a list of ids (Settings Sync).

Closes #6750

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 14:37:35 +08:00
LU XIANGRUIтаwildcatDownstairs 9e2da77162 feat(settings): sync settings automatically on startup and after changes (#6748)
Settings Sync gains Sync automatically (on by default once a repository is set): a sync on startup, shared across windows opened within a minute, and one 30 seconds after the last settings change. Before going to the network the automatic sync checks locally whether anything that syncs changed, so machine-only changes cause no fetch, and applying a sync does not trigger another.

Automatic syncs use saved credentials only and never prompt, stay quiet when nothing changed, report pulled and conflicting settings like Sync Now, show a warning with Sync Now on failure, and leave a notification instead of asking when the repository holds settings this computer never synced with. Frontend entries edited during a sync are kept for the next one, and a change arriving during a sync schedules one more.

Closes #6744

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 14:32:51 +08:00
LU XIANGRUIтаwildcatDownstairs 3a89b94624 feat(settings): sync IDE settings through a Git repository (#6733)
Adds Settings > Appearance & Behavior > System Settings > Settings Sync, which syncs settings through a Git repository the user chooses (a secret gist works too); Git runs with the user's own credentials. Categories can be toggled individually: appearance, editor, keymaps, templates, macros, tool window layouts and view options, and other settings.

Sync Now (also File > Manage IDE Settings) fetches, merges each setting three ways against the last synced commit, commits, pushes and applies the result, retrying the merge once if another machine pushed in between. When both sides changed a setting this machine wins and the notification names it. The first sync with a repository that already holds settings asks whether to merge, use the repository's or use this computer's. An unreadable category file stops the sync without changing anything; a deleted one is written again.

Credentials, environment/argument/command/path-like settings, path values, URLs with credentials, proxy, SSH, deployment, run targets, tools, language servers, the MCP server, agent permissions and machine-local state never sync in either direction. The repository holds one JSON file per category and is written through a bare clone with plumbing commands only, keeping every other file in the tree.

Closes #6713

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 14:27:46 +08:00
LU XIANGRUIтаwildcatDownstairs df40f0befe feat(run): debug Python on SSH run targets (#6696)
Debug on a Python configuration with an SSH run target now starts the program under the debugpy bootstrap listening on the host's loopback interface, forwards a local port through the SSH session and attaches with the project root mapped onto the target folder. When the host's interpreter has no debugpy, the IDE's copy is uploaded once to ~/.openidea/debug/<version> (written to a temporary folder and renamed into place so concurrent runs don't see partial files); without a local copy the error offers to install it. The check times out after 30 s, and the run fails if debugpy is not ready 120 s after start. The launch parameter containerDebug is renamed targetDebug.

Closes #6695

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 14:03:48 +08:00
LU XIANGRUIтаwildcatDownstairs f151498e07 feat(notebook): debug a cell with the kernel's own debugger (#6698)
Breakpoints can be set in notebook code cells, and Debug Cell (notebook toolbar, cell toolbar, Find Action) runs the cell under the kernel's debugger through the Jupyter debugger protocol: DAP requests go as debug_request on the control channel, replies and events come back as debug_reply/debug_event. This works for local ZeroMQ kernels and kernels on a Jupyter server alike.

The bridge dumps every code cell once the debugger starts, rewrites source paths between cell URIs and the kernel's compiled files, re-dumps edited cells before setBreakpoints, and sends disconnect (never terminate) when the session ends, so the kernel and its variables are kept. DebugManager::start_over attaches a session over an existing stream. Kernels without a debugger are refused at once with the reason, and Interrupt during a debug session disconnects first.

Closes #6681

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 14:02:26 +08:00
LU XIANGRUIтаwildcatDownstairs d959a2a583 feat(notebook): run notebooks on a remote Jupyter server (#6669)
Connect to Jupyter Server... in the notebook kernel drop-down and Find Action takes any URL a Jupyter server prints (lab/notebook/JupyterHub user URLs are reduced to the server base) and a token. The token is checked against /api/kernelspecs and stored in the OS credential store; only the base URL is written to disk. Saved servers are listed in the kernel drop-down with their kernel specs, remembered per notebook, and can be removed again.

A remote kernel is started with POST api/kernels, driven over its channels WebSocket (through the configured HTTP proxy via the new ide_http::tunnel), interrupted with POST .../interrupt and deleted on restart, close, failed or cancelled start. A dropped socket is reopened for the same kernel and session for about 15 s so buffered output is replayed. The kernel transport now has a Link with local (ZeroMQ) and remote variants, sharing execution, output routing and the Jupyter Variables window. Token-less servers get the _xsrf cookie and header.

Closes #6526

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 14:00:21 +08:00
LU XIANGRUIтаwildcatDownstairs 7ab456b1e7 feat(github): GitHub Actions tool window with job logs and re-runs (#6767)
Adds a GitHub Actions tool window listing the workflow runs of the current branch (including its pull request runs), with a toggle for every branch. Expanding a run lists its jobs; selecting a job shows its log with runner timestamps and group markers removed and error lines highlighted. The toolbar has Re-run Failed Jobs, Re-run All Jobs, Re-run Job, Open in Browser and Refresh, and the list refreshes every 15 seconds while anything runs.

gh 2.104 refuses to print responses containing terminal escape sequences unless --allow-escape-sequences is passed; ide_github::api retries a GET with the flag only when gh refused for that reason, so older gh versions keep working.

resetConnection now clears a GitHub check still running for the previous project, which left the connection stuck in "checking" after switching projects.

The tool window uses the github icon (the build tool window already uses toolwindow-build), and "GitHub Actions" is kept untranslated in zh.

Closes #6716

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 13:59:25 +08:00
LU XIANGRUIтаwildcatDownstairs f8a9b204c6 feat(github): share the project on GitHub (#6766)
Adds Git > GitHub > Share Project on GitHub. The dialog asks for the repository name, Private (on by default), the remote name and a description; a folder that is not a Git repository yet is initialized. A confirmation lists the commits to push, or the files and message of an initial commit. The repository is then created with gh api, added as the remote and the branch pushed with its upstream. A project that already has a remote on that GitHub server gets a notification linking to it instead.

vcs_init now detects the project's repositories before it returns, so a command right after it no longer fails with "project is not a git repository".

Closes #6715

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 13:58:40 +08:00
LU XIANGRUIтаwildcatDownstairs be7a0cfa5b feat(github): create gists from the selection or files (#6765)
Adds Git > GitHub > Create Gist... From the editor it posts the selection, or the whole file without one; from the Project view and editor tabs it posts the selected files (folders are skipped). The dialog asks for a file name (single file only) and a description, with Secret (on by default), Open in browser and Copy URL; the choices are remembered. The gist is created with gh api under the project's GitHub account and a notification links to it.

Closes #6714

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 13:57:17 +08:00
l0ng-ai f40b645c8e fix(bindings): regenerate after the localized plugin index fields (#6800)
The plugin index entry gained optional localized fields (#6776) that are skipped when empty, so specta now emits separate serialize and deserialize shapes for IndexEntry and MarketPlugin. The committed bindings still had the single shape; regenerated with the export_bindings test.
2026-11-29 13:37:41 +08:00
LU XIANGRUIтаwildcatDownstairs e4ec1978d8 feat(vcs): SSH commit signing in Configure GPG Signature (#6724)
Configure GPG Signature gets a signing format (OpenPGP / SSH), saved as gpg.format in the repository config. With SSH, the key list shows ssh-agent's keys (`ssh-add -L`, saved as key::<public key>) and ~/.ssh/*.pub files, agent keys first, with a hint to ssh-add a key that isn't in the agent. Changing the format without a new key removes the old key, which belongs to the other format.

Closes #6712

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 13:36:06 +08:00
LU XIANGRUIтаwildcatDownstairs 10242d2e58 feat(plugins): support Markdown and UI-locale localization for Overview and What's New (#6776)
Plugin Overview and What's New rendered as plain text and ignored the UI language. plugin.toml gains optional description-file and change-notes-file (API 1.18, Markdown inside the package, UTF-8, at most 256 KiB); a shared loader validates them and localized siblings (description.zh-CN.md) in check, pack, install and index. Descriptions and change notes resolve per locale from locales/<tag>.json and those siblings, with English fallback, for installed, local catalog and marketplace plugins.

Markdown is rendered with lazily loaded marked and an isolated DOMPurify that strips scripts, event handlers, javascript:/file: links, styles and external resources, keeping marked out of the Settings window's boot graph.

Closes #6773


Merged with main: the pending-uninstall placeholder plugin now gets docs from its manifest.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 13:31:13 +08:00
LU XIANGRUIтаwildcatDownstairs fad9135f7a feat(terminal): run recognised commands with the IDE (#6722)
The terminal now highlights a typed command the IDE recognises, and Cmd+Enter (Ctrl+Enter on Windows/Linux) runs it in the Run tool window instead of the shell; plain Enter still runs it in the shell, and unrecognised lines pass Cmd+Enter through. Settings > Tools > Terminal > Run commands using IDE, on by default.

The zsh, bash and fish integration scripts now send OSC 133 B after the prompt, report PATH, VIRTUAL_ENV and CONDA_PREFIX at each prompt, and bind a key that clears the command line in emacs and vi modes; nothing runs if the line isn't cleared. Recognised lines are those a Run Anything provider accepts for the terminal's folder: pytest / python -m / python file.py with the shell's active environment, package scripts, mvn/gradle in the containing module, npx / pnpm exec, and manage.py in its folder. Lines with shell syntax and run configuration names stay with the shell.

Closes #6719

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 13:29:57 +08:00
LU XIANGRUIтаwildcatDownstairs 703b19b526 feat(editor): live preview for reStructuredText files (#6689)
.rst files opened in the editor alone. They now get the Editor Only / Editor and Preview / Preview Only layouts with a preview that follows typing, rendered by docutils in the project's Python interpreter; without docutils or an interpreter the preview says what is missing.

Rendering runs only in trusted projects, off the UI thread, with a 15 s timeout, -E and an empty working directory; a render superseded by new text is cancelled and its interpreter stopped. include, raw, file and URL insertion and docutils.conf are off, and the HTML goes through the Markdown preview's sanitizer (MathML kept, remote images not loaded). The SVG preview's live-text store and the Markdown preview's image loader moved to shared modules unchanged.

Closes #6682

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 13:29:18 +08:00
LU XIANGRUIтаwildcatDownstairs c3de09be78 feat(json): settings page for custom JSON Schema mappings (#6707)
Adds Settings > Languages & Frameworks > JSON Schema Mappings: each mapping has a name, a schema (URL or project file) and the files it applies to (paths or globs, !pattern excludes). Mappings are saved to the project's .openidea/settings.toml by default, or globally, and are sent to vscode-json-language-server and yaml-language-server through workspace/didChangeConfiguration without a restart.

Patterns are sent as absolute paths because both servers prefix patterns with **/, built-in SchemaStore entries exclude the files a custom mapping takes so the custom schema replaces rather than adds to them, a project schema file is not validated against itself, and the page warns about patterns that take every JSON or YAML file.

Closes #6679

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 13:28:38 +08:00
LU XIANGRUIтаwildcatDownstairs 6b61b15f00 feat(http-client): index Flask and FastAPI routes as project endpoints (#6648)
Project endpoints (Search Everywhere's Endpoints tab, URL completion and navigation in .http files) came only from Spring and plugins. A built-in provider now reads Flask and FastAPI routes: app/blueprint/router decorators with methods, add_url_rule, blueprint and APIRouter prefixes including those given at registration, nested routers and mounted sub-apps, prefixes from module constants, imports and settings attributes. Only receivers resolved to Flask, Blueprint, FastAPI or APIRouter instances count, and routes whose path is only known at runtime are left out. Path parameters become {name}.

Route decorators get the Open in HTTP Client gutter icon. The project is scanned once and changed .py files are re-read individually (a large change set rescans); a new python_route_sources command lists candidate files using the Spring source scan, skipping site-packages.

Closes #6533

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 13:27:58 +08:00
LU XIANGRUIтаwildcatDownstairs 19948c1426 feat(run): add a Celery run configuration (#6651)
Adds a Celery run configuration type: Worker runs python -m celery -A <app> worker (with -B when Run Beat scheduler is on), and Enqueue task sends one task with celery call (module, task, JSON args and kwargs). Celery joins the shared Python kind check (ide_run::is_python_kind, now also used for the container PYTHONPATH of local Docker runs, which Flask and FastAPI missed), so it runs on the project interpreter with PYTHONPATH / PYTHONUNBUFFERED, in containers too, and debugs through debugpy with subprocess attach for pool processes.

Checkbox fields in run configuration forms now show their text once, on the checkbox, instead of also as a misaligned row label (Go, JVM, Tomcat, Docker types included). The Python docs cover -P solo and separate Beat on Windows, @shared_task needing the app, and one debug session per pool process.

Closes #6646

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 13:27:17 +08:00
LU XIANGRUIтаwildcatDownstairs e30ae3f6b8 feat(run): add Flask and FastAPI run configurations (#6647)
Flask and FastAPI apps could only run as ordinary scripts. Adds Flask server and FastAPI run configuration types: Flask runs python -m flask run with FLASK_APP / FLASK_DEBUG (read by every Flask version), host, port and extra options; FastAPI runs python -m uvicorn <module:app> with reload, host, port and options. Both use the Python interpreter choice and debug with debugpy; under the debugger Flask runs with --no-debugger, and without subprocess attach the reloader is turned off so breakpoints still stop.

A top-level (or src/) app.py, wsgi.py, main.py or app/main.py assigning Flask(...) or FastAPI(...) to a module-level name gets a detected configuration. The list of Python run kinds is now one function (ide_run::is_python_kind) instead of copies in the host, Docker, process and SDK code.

Closes #6532

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 13:25:10 +08:00
LU XIANGRUIтаwildcatDownstairs 9ee8f67e9f feat(languages): Jinja2 Template language for .jinja, .jinja2 and .j2 files (#6645)
.jinja, .jinja2 and .j2 files opened as Plain Text. They now open as Jinja2 templates, with the extension before them deciding the content between the tags: Jinja2 HTML (.html.j2, .html.jinja, .htm.*) gets the HTML language server, Emmet, tag closing and linked tags like Django templates; any other name (nginx.conf.j2, values.yaml.j2, base.jinja) is a Jinja2 Template over plain text without HTML tooling.

Both use @codemirror/lang-jinja (now a direct dependency, the same 6.0.1 already in the lockfile): highlighting, folding and indentation of block statements, completion of tags, filters and tests, and tag matching. The file icon follows the extension before .j2, and breakpoints in a file typed as a Jinja language turn on debugpy's jinja support.

Closes #6644

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 13:23:45 +08:00
LU XIANGRUIтаwildcatDownstairs 5b486f1588 feat(vcs): detect Git LFS pointer files and pull LFS objects (#6749)
A repository tracking files with Git LFS gave no sign of it, and when the LFS objects were not downloaded (git-lfs missing, or a clone with GIT_LFS_SKIP_SMUDGE) the files stayed pointer files without explanation.

Once per repository and session in a trusted project, the LFS-tracked files whose checkout is still a pointer are listed (git ls-files ':(attr:filter=lfs)'). A notification names them and offers Pull LFS Objects (git lfs pull, after git lfs install --local when no config sets up the filter; an existing hook is kept), or says Git LFS is not installed and links to git-lfs.com. Git > Pull LFS Objects runs the same pull as a remote operation with progress, console output and cancel; it shows for repositories whose root .gitattributes uses filter=lfs.

Merged with the submodule actions from #6738: both repository flags, operations and notices are kept side by side.

Closes #6743

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 13:00:49 +08:00
LU XIANGRUIтаwildcatDownstairs 6f8e8501c6 feat(settings): offer the OpenIDEA counterparts of JetBrains plugins (#6734)
Importing JetBrains settings now reads installed.txt and disabled_plugins.txt instead of listing plugins as not imported. Plugins with a known OpenIDEA counterpart are looked up in the marketplace while the confirmation is open and offered for install afterwards; IdeaVim turns on the built-in Vim emulation; disabled and unmapped plugins are listed.

Closes #6732

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 12:51:51 +08:00
LU XIANGRUIтаwildcatDownstairs 27c7323c0b feat(python): inherit base interpreter packages when creating a virtualenv (#6668)
Add Python Interpreter › Virtualenv / uv Environment gets "Inherit packages from base interpreter" (off by default, as in PyCharm), creating the environment with --system-site-packages for venv and uv. A virtualenv picked as the base is refused with the option on, since venv and uv build on the Python it came from.

Closes #6664

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 12:49:48 +08:00
LU XIANGRUIтаwildcatDownstairs 41cb8f993e feat(settings): import JetBrains inspection profiles (#6725)
Importing JetBrains settings now carries over inspection profiles (inspection/*.xml): Default merges into OpenIDEA's Default profile and other profiles become IDE-level profiles of the same name. Inspections with a counterpart keep their state and level, PEP 8 codes PyCharm ignores are turned off for Ruff and pylsp, and the confirmation lists what has no equivalent.

Closes #6723

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 12:48:26 +08:00
LU XIANGRUIтаwildcatDownstairs 6e37a1a977 feat(python): run and debug conda interpreters with their environment activated (#6702)
Python runs, tests and debug sessions started a conda interpreter without activating its environment, so on Windows packages whose DLLs live in Library\bin failed to import and the environment's tools weren't on PATH. When the launch's interpreter belongs to a conda environment, the launch gets what `conda activate` sets: CONDA_PREFIX, CONDA_DEFAULT_ENV (base, the envs/ name, or the path) and the environment's folders in front of PATH (Windows' Library\* folders included); values the configuration sets itself are kept.

Closes #6690

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 12:48:16 +08:00
LU XIANGRUIтаwildcatDownstairs e99fcb0c49 feat(python): manage packages of conda environments with conda (#6688)
In a conda environment every package change used pip, including for packages conda installed. Packages a conda-meta record owns (matched by their .dist-info / .egg-info, so torch → pytorch is found) are now upgraded, changed and removed with conda (`conda update`, `conda install pkg<constraint>`, `conda remove --force`); everything else, and requirements only pip reads, keep using pip. Outdated checks skip conda's packages, whose PyPI versions may not be on conda's channels yet.

Closes #6687

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 12:48:06 +08:00
LU XIANGRUIтаwildcatDownstairs 2f31544d04 feat(python): create conda environments with any Python version (#6678)
Add Python Interpreter › Conda Environment only listed the Python versions of local interpreters, so an environment with another version (or any, with no local Python) couldn't be created although conda downloads it. The version list now also offers Python 3.10–3.15; a version without a local interpreter is passed as is (`conda create … python=3.12`). The newest local version stays the default, 3.13 without one. conda's own error (the …Error: block, without the channel hints) is shown when create fails.

Closes #6672

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 12:47:56 +08:00
LU XIANGRUIтаwildcatDownstairs cbcd84f1d2 feat(vcs): initialize and sync Git submodules (#6738)
A project cloned without --recurse-submodules had empty submodule folders and no sign of it. Repositories now report submodules whose checkout was never initialized (skipping update=none and active=false ones); a notification lists them with Initialize, and Git › Submodules gets Initialize Submodules (`git submodule update --init --recursive -- <uninitialized paths>`, so checked-out submodules aren't detached) and Sync Submodule URLs (`git submodule sync --recursive`). Both need a trusted project.

Closes #6726

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 12:47:05 +08:00
LU XIANGRUIтаwildcatDownstairs a3a56ab10d feat(run): reach development servers run in Docker and Compose containers (#6740)
Development servers on a Docker or Compose run target listened on 127.0.0.1 in the container, and `docker compose run` published none of the service's ports, so the host couldn't reach them.

container_config now recognizes Django runserver (manage.py, django-admin, python -m django), flask run, uvicorn and fastapi dev/run, and when nothing chooses an address makes them listen on all interfaces in the container: runserver gets 0.0.0.0:<port>, flask/uvicorn get FLASK_RUN_HOST / UVICORN_HOST=0.0.0.0 unless the command, env files, the Compose service's environment or .env/.flaskenv set one, fastapi dev gets --host 0.0.0.0. When the target has no ports of its own, the server's port is published on the host's loopback only (through the service's own mapping when it has one). Other commands and shell lines are unchanged.

Closes #6737

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 12:46:51 +08:00
Muuтаmuutot 3961f38f46 feat(templates): save the active file as a template (#6638)
Adds File › Save File as Template… (also in Find Action). The dialog prefills the active file's name, extension and current buffer, unsaved edits included, lets the user edit them and saves the template to the global Default file-template scheme without switching the selected scheme.

Co-authored-by: muutot <[email protected]>
2026-11-29 12:37:37 +08:00
Deng Liuтаdengliu 4c5f4fa1e1 feat(github): add in-IDE GitHub account sign-in in Settings, Pull Requests, and Clone (#6642)
Settings › Version Control › GitHub only listed accounts already signed in with gh, Clone Repository › GitHub told signed-out users to run gh auth login in a terminal, and Pull Requests opened a raw terminal tab.

The PTY sign-in dialog and OAuth device-code parser move from features/agents to src/workbench/CliSignInDialog.tsx and src/platform/deviceCode.ts, so agents and GitHub share them without a cross-feature import. GitHub settings get Sign In… / Add account… (selecting a newly added second account for the project) and Install GitHub CLI when gh is missing; the Pull Requests tool window signs in in-IDE and reconnects, with Add account… in its error state, repository selector and account menu; Clone › GitHub gets Sign In… and Add account…. The merge with main carries the dialog's terminal-reply filtering and FIFO input over to the moved file.

Co-authored-by: dengliu <[email protected]>
2026-11-29 12:29:38 +08:00
Deng Liuтаdengliu 90734775b9 feat(welcome): group recent projects by Local and remote host (#6763)
When the recent list holds remote projects, Welcome › Projects, the Recent Projects popup, the title-bar Project Widget's Recent Projects and File › Open Recent group them under Local and each remote target (SSH · host, WSL · distro, Dev Container · folder), most recently used first, with collapsible groups and the per-row host pill dropped inside a host group; search flattens the groups again. Local-only lists are unchanged. Recent list rows now take their natural height, so two- and three-line remote rows no longer overlap in the popup's virtualized list.

Co-authored-by: dengliu <[email protected]>
2026-11-29 12:28:47 +08:00
Deng Liuтаdengliu b53915e4b6 feat(toolwindows): add setting to hide open tool windows on shortcut (#6781)
Tool window shortcuts focus an open but unfocused tool window on the first press and hide it on the second, as in IntelliJ IDEA. Appearance › Tool Windows gets an opt-in "Hide open tool windows on shortcut" (appearance.toggleToolWindowsOnShortcut, default off): when on, the shortcut hides such a window in one press and focus stays where it was.

Co-authored-by: dengliu <[email protected]>
2026-11-29 12:28:33 +08:00
audichuang d361d7239a fix(editor): fit a hidden tab's kept view instead of drawing a whole reloaded file (#6779)
A background tab keeps its CodeMirror view detached. Measured detached it is out of view, so CodeMirror maps its viewport through changes instead of fitting it, and a reload replacing most of the file (a checkout) made the hidden view draw every new line (30k DOM lines, ~5 s to show the tab again).

onTransactions now maps a detached view's viewport through the composed batch and, only when that exceeds 1,000 lines, runs that one update with the private viewState.inView set (guarded: only when it is a boolean, restored in finally) so CodeMirror fits the viewport. Small hidden edits keep mapping as before.

Closes #6762

Co-authored-by: audichuang <[email protected]>
2026-11-29 12:27:54 +08:00
Deng Liuтаdengliu 77a03ac197 fix(plugins): prevent lock-order deadlock and main-thread stalls during event dispatch (#6784)
PluginHost could deadlock: ensure_active held plugin.runtime across Wasm instantiation and activate(), where plugins call subscribe* (shared.subscriptions), while flush_events_at took queues -> plugins -> subscriptions -> runtime. post_window_events then blocked behind queues on the WebKit main thread, freezing the app (Not Responding).

- A per-plugin `activating` mutex serializes start/stop; `runtime` is now a leaf lock that never spans activation or host callbacks. stop() marks the plugin Disabled under it so a concurrent event can't reactivate it mid-stop.
- flush_events_at, queue_watched_changes, post_events_from and remote_languages snapshot plugins/subscriptions before taking queues instead of nesting the locks.
- plugin_post_events and plugin_set_active_file run off the main thread (async + spawn_blocking); the frontend keeps their order with a FIFO chain, snapshotting the editor context at call time.

Closes #6774

Co-authored-by: dengliu <[email protected]>
2026-11-29 12:27:43 +08:00
Muuтаmuutot f28a11d043 feat(editor): add advanced line copy and paste options (#6708)
Settings > Editor > Smart Keys gets the Line Copy and Paste options: Copy/Cut with no selection act on each caret's line (can be turned off), Copy can select the copied lines, and a linewise paste goes above the caret line, at the caret, or trimmed mid-line. Native, context-menu and Paste from History pastes share the same linewise metadata.

Co-authored-by: muutot <[email protected]>
2026-11-29 11:08:19 +08:00
Muuтаmuutot cdb4f9ab15 feat(python): insert docstring stubs from an intention (#6659)
Python functions and classes without a docstring offer Insert a documentation string stub in Show Context Actions, generating PyCharm's default reStructuredText stub with :param: lines for the parameters (self/cls skipped) and :return:.

Co-authored-by: muutot <[email protected]>
2026-11-29 10:35:35 +08:00
Muuтаmuutot c709844c04 feat(editor): add Save As for existing files (#6534)
File > Save As opens the existing Copy dialog for the active file with Open copy in editor forced on. A single-file copy of an open editor uses the new doc_copy_as, which writes the current buffer with its encoding, BOM and line endings and refuses a target that is open in another editor.

Co-authored-by: muutot <[email protected]>
2026-11-29 10:35:25 +08:00
Muuтаmuutot 2cce84ad2c feat(docs): search the Documentation tool window (#6627)
The Documentation tool window gets a find bar (Cmd/Ctrl+F and a toolbar button) with match highlighting, a match count and previous/next navigation; the query is matched as plain text, and re-rendered documentation keeps the active match without scrolling.

Co-authored-by: muutot <[email protected]>
2026-11-29 10:35:14 +08:00
Muuтаmuutot 91dcd1b7eb feat(project-tree): preview a selected file with Space (#6641)
Quick Preview in the Project tool window: with one file selected, Space opens a read-only, highlighted preview popup without opening an editor tab (an open buffer's text when there is one). Escape, a selection change, focus loss or unmount close it. Bound in the IntelliJ macOS/Windows and VS Code macOS keymaps.

Co-authored-by: muutot <[email protected]>
2026-11-29 10:35:05 +08:00
JunChang Peng 3d275d5a3d feat(vcs): one tint strength for the annotate backgrounds (#6636)
Annotate backgrounds alternated between 18% and 24% tint once a file had more commits than palette colours, so neighbouring commits differed in weight as well as hue, and at 18% some hues were nearly grey. Commit and author colouring now share one tinted() helper at 40%.

Co-authored-by: junchangpeng <[email protected]>
2026-11-29 10:34:51 +08:00
Muuтаmuutot cc49827793 feat(scratch): create a scratch file from the selection (#6635)
A non-empty selection offers Create new scratch file from selection in Show Context Actions. The selection is copied verbatim into a new numbered scratch file (no language template), whose language is detected from the fragment, else the source file's language or extension.

Co-authored-by: muutot <[email protected]>
2026-11-29 10:34:41 +08:00
Muuтаmuutot 7b3813f9e2 feat(templates): duplicate live templates from settings (#6615)
Settings > Live Templates gets Duplicate Template: it creates an editable user copy in the same group with the body, variables, contexts and options, and resets the abbreviation to ABBREVIATION as IDEA does. Plugin templates stay read-only but can be duplicated; the copy drops the plugin origin.

Co-authored-by: muutot <[email protected]>
2026-11-29 10:34:29 +08:00
Muuтаmuutot ebc6dc86f1 feat(project-tree): show file size and modification details (#6613)
Project view Options > Appearance > File Details shows each file's modification date and time and its size beside its name, as IDEA's File Details does. Off by default, persisted with the other view options; a missing modification time shows only the size.

Co-authored-by: muutot <[email protected]>
2026-11-29 10:34:17 +08:00
audichuang 0ae1628678 perf(vcs): load selection history diffs lazily and read deep rows from their commits (#6754)
Show History for Selection ran one git log -L with patches and sent every commit's before/after block in one reply; selecting all of a 5,000-line file with 2,000 commits produced an 849 MB reply. The single git log -L is now read line by line: the first records keep their diffs (at least four, then as many as fit in 512 KiB), the rest keep only the commit header and the +++ path and hunk ranges. A row without its diff is read from its own commit when selected (git log -L <range> -n1 <commit>), and the tab prefetches in the direction of travel. New commands vcs_block_history_summary / _revisions / _revisions_at; the tab falls back to vcs_block_history on older servers. The reader pins --src-prefix/--dst-prefix and applies the lone-CR normalisation from #6757 to the summary path.

Co-authored-by: audichuang <[email protected]>
2026-11-29 10:34:07 +08:00
faysouтаfaysou dc8c45c77c fix(project-tree): hide the horizontal scrollbar between scrolls (#6760)
The Project view's horizontal scrollbar stayed visible at rest. It is now a DOM overlay (the shared Scrollbar gains a horizontal mode) that shows while the content scrolls sideways and fades about a second after scrolling stops, taking no row space either way; its thumb can still be dragged while visible. With the overlay the tree follows the dominant wheel axis over the last 200 ms, so small sideways deltas in a vertical trackpad gesture no longer shift the tree or reveal the bar. Other trees keep the native horizontal scrollbar.

Co-authored-by: faysou <[email protected]>
2026-11-29 10:08:17 +08:00
Deng Liuтаdengliu e5f93b8526 fix(agents): keep OSC 11 color replies from breaking interactive CLI sign-in (#6755)
Signing in to GitHub CLI in the Sign In dialog could abort with "unexpected escape sequence from terminal": gh probes the background color with OSC 11 before prompting, and xterm's reply could be dropped before the PTY id resolved or reordered across concurrent term_write calls, so a late reply reached gh's prompter. gh auth login PTYs (local and remote) now get GLAMOUR_STYLE=notty when unset, which skips the probe; the dialog drops OSC 10/11/12 color replies, buffers input until the PTY exists and writes it in FIFO order, and no longer counts automated cursor/device replies as user input when deciding on the auto-Enter for the device code.

Co-authored-by: dengliu <[email protected]>
2026-11-29 10:06:49 +08:00
audichuang 73ba36381c fix(vcs): don't list Local Changes in History for Selection for clean lone-CR files (#6757)
Show History for Selection on a clean file with lone-CR line endings listed a Local Changes row: HEAD's block was sliced from the raw blob with str::lines(), which keeps lone CRs, so it never equalled the LF-normalised editor block. HEAD's text now goes through diff::normalize_eol before slicing, as line_hunks already does.

Co-authored-by: audichuang <[email protected]>
2026-11-29 10:04:38 +08:00
LU XIANGRUIтаwildcatDownstairs 3bc75e1de0 fix(github): read a choice saved without a host as github.com's (#6753)
Follow-up to #6746. A repository choice saved as owner/name comes from a release that knew only github.com, so it now means github.com's repository of that name, and the Enterprise one only when github.com has none; #6746 had read it as the origin remote's, which reconnected some projects to the Enterprise server. The probe that picks where to ask gh follows the same rule and finds an Enterprise repository by its remote's path.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 10:03:56 +08:00
Albince Paliakkara 633bef2e69 fix(vcs): show the focused view's diff for Show Diff and Show Diff in New Window (#6752)
With a key bound to Show Diff in New Window, the Compare tool window opened an empty diff: the diff actions could not ask the focused view what it shows, so they diffed the Project view's or the editor's file against HEAD, and the shelf, stash, patch and review trees only claimed Show Diff's own key. Views now register a diff source on their element (diffSource.ts) and both diff actions ask the one around the focused element first, whatever runs them (shortcut, menu, Find Action). Covered: Compare trees (tool window, comparison window, Push, rebase plan), shelf checklist and panel, Stash view and Unstash dialog, Apply Patch list, Local Changes review dialog and the Git Log's changed files. A guessed file without local changes now shows "No local changes in X" instead of an empty diff.

Fixes #6751

Co-authored-by: albince-mi <[email protected]>
2026-11-28 23:10:17 +08:00
LU XIANGRUIтаwildcatDownstairs 9aa0718cf9 fix(github): keep a new pull request's head on the base repository's host (#6746)
Follow-up to #6742. The new pull request form's head repository picker keyed its options by owner/name, so same-named repositories on an Enterprise server and on github.com could not both be picked, and it offered remotes on another host. It now lists only remotes on the base repository's host, keyed by host/owner/name, and the default head ignores a tracked remote on another host. A selection saved before #6742 (no host) now resolves to the origin remote's repository when that is one of the matches, instead of depending on remote order.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 23:04:41 +08:00
LU XIANGRUIтаwildcatDownstairs 836a4405d6 fix(github): keep GitHub Enterprise and github.com repositories apart (#6742)
Follow-up to #6729. Repositories now compare by host as well, so acme/app on an Enterprise server and on github.com stay two remotes; the selector shows the host when remotes span hosts, and the saved choice is host/owner/name (an older owner/name still loads). connect passes the target's host and root to its own requests and switches the shared API host only after they succeed, so a failed switch no longer redirects the existing connection's requests. Remotes match an Enterprise host whatever its port, keeping gh's host:port for --hostname. Docs note that gh checks the server certificate against the system trust store.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 21:48:48 +08:00
l0ng-ai 952bd0b24b fix(editor): highlight versioned script types such as text/ecmascript-6 as JavaScript (#6736)
@codemirror/lang-html only nests JavaScript into <script> blocks whose type is exactly text/javascript, text/ecmascript and the like, so type="text/ecmascript-6" (old Vue CLI templates) and HTML's legacy text/javascript1.x stayed plain text. HTML, Vue, JSP, Django, Angular and Thymeleaf templates now parse these types as JavaScript.

Fixes #6683
2026-11-28 21:15:16 +08:00
audichuang ac5e4b7259 perf(editor): keep long lines rendered when a selection scrolls into view (#6677)
Extending a selection with Shift+Down over long unwrapped lines got slower with every selected line: while scrolling the head into view, CodeMirror placed each long line's rendered part by the target's fraction of that line (1 above the target, negative below it), so every long line above the caret was redrawn from its end and back. The @codemirror/view patch now centres every unwrapped line's line gaps on the target's x, taken from the target's own line; wrapped lines are unchanged.

Adds selectLongLinesSql/Txt perf scenarios, SQL to the in-memory backend's languages, and a jsdom test for the line gaps.

Refs #4658

Co-authored-by: audichuang <[email protected]>
2026-11-28 21:11:32 +08:00
LU XIANGRUIтаwildcatDownstairs 2ea7d6c41b feat(github): support GitHub Enterprise Server hosts in pull requests (#6729)
gh api does not take the host from the remote as gh pr does, so requests for an Enterprise repository went to github.com. GhApiRequest now carries an optional host passed as gh api --hostname (validated as host[:port]); the GitHub tool window sends the connected repository's host, availability reads the login on that host, and remotes on the host gh resolved count as GitHub remotes. Commit checks in the Git log keep github.com.

Fixes #6717

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 21:00:14 +08:00
LU XIANGRUIтаwildcatDownstairs 16e5cb5763 fix(run): open container paths in tracebacks as project files and copied library sources (#6711)
Tracebacks of runs on Docker and Compose run targets print container paths: a site-packages frame showed File not found and a project frame fell back to a search by file name. The Run console, test tree and Debug Console now know the container a run is in, and an absolute path from such a run resolves through run_container_path: a file under a folder the project interpreter's snapshot copied opens that read-only copy, otherwise the bind mount whose container folder is the longest prefix maps it to the folder here (Compose mounts from docker compose config, cached until a Compose file changes). Paths that map to nothing show File not found; local runs resolve as before.

Closes #6710.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 20:54:55 +08:00
LU XIANGRUIтаwildcatDownstairs 611440f77f fix(python): run the Python Console in a Docker or Compose interpreter's container (#6686)
With a Docker or Compose run target as the project interpreter, the Python Console reported "No Python interpreter" because it only asked for a local interpreter. When there is none but a run target interpreter is set, the console now starts its driver as a python run, which Run already routes into the target's container (project mounted, the target's interpreter, docker stop on Stop). The driver exits on SIGTERM itself, since as a container's PID 1 it would otherwise ignore Stop until docker's SIGKILL.

Closes #6685.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 20:49:10 +08:00
Vladislav Kuzmin 482143769f test(agents): wait for the permission entry before archiving (#6632)
The archive regression waited on NeedsInput, which the permission handler records before it queues the initial permission entry. When the test took the delivery lock first, the handler could not publish the entry and the test then waited for settlement while holding that lock, so the macOS job hung until cancelled. The test now waits for the published permission entry before taking the lock, and uses the shutdown guard to stop the fake agent on failure.

Closes #6631.

Co-authored-by: principalwater <[email protected]>
2026-11-28 20:47:42 +08:00
l0ng-ai 176859987b fix(vcs): list a merge's own changes above its parents' in Git Log (#6731)
With Show Changes from Parents on, a merge commit's changes listed only one group per parent, and the flat view did not show the groups at all. The merge's own changes (files changed against every parent) now come first, followed by a "Changes to <hash> <subject>" node per parent in both the flat and the directory view; a merge with no changes of its own shows "No merge conflicts". The parent filter keeps the merge's own changes and the chosen parent's node.

Fixes #6691
2026-11-28 20:45:36 +08:00
iGinkтаiGink 6cdd52d31a fix(workbench): collapse the merged main menu slot instead of leaving a blank gap (#6721)
With the main menu merged into the toolbar, a window too narrow for the menu titles collapsed them to the hamburger but the hidden measuring copy stayed in flow and held the slot at the full menu width, leaving a blank gap. The measuring copy is now absolutely positioned so the visible presentation sizes the slot, and the fit check counts the bar's free flex space, so the titles return when the window widens.

Co-authored-by: iGink <[email protected]>
2026-11-28 20:37:14 +08:00
LU XIANGRUIтаwildcatDownstairs 90a0fd9901 fix(run): put the source roots on PYTHONPATH in Docker and Compose containers (#6728)
Python runs on Docker and Compose run targets got no source roots on PYTHONPATH, so a src layout failed with ModuleNotFoundError in the container while it worked locally. For Python configurations on a container target, the project's source roots inside the project folder now go on PYTHONPATH (joined with ':' before the configuration's own value), and container::prepare maps them to the container folder. Roots outside the project are not mounted and are skipped.

Closes #6727.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 20:36:55 +08:00
LU XIANGRUIтаwildcatDownstairs 9d92f47f94 fix(python): address the review of the Django PRs #6542-#6545 (#6656)
Follow-up fixes to the Django support:
- manage.py tasks: manage.py is looked up on each use and only a successful command list is cached; lines run while help loads go to manage.py; a failed help is reported; the active file's project picks the manage.py in a monorepo (shared via platform/django.ts); py/python3.x/Windows forms count as manage.py lines.
- Django console: keeps the project root as working directory with manage.py's folder on sys.path, reads setdefault and os.environ[...] settings forms, and shows auto-imported names once reassigned.
- URL names: re-reading names clears navigation's cache, names nest under include namespaces, and only path/re_path/url name= counts (small Python scanner).
- Field lookups: models keyed per app, multi-table inheritance reverse names fixed, related_query_name/related_name/%(class)s rules, relation lookups and <fk>_id, completion in Q(...) and after F(...).

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 20:31:33 +08:00
Deng Liuтаdengliu 68abd00a7f fix(remote-dev): fix vertical text wrapping and clipping in resource tooltip (#6618)
A truncated element with a long data-tooltip put that text in the tooltip's shortcut slot (nowrap, keys font), which overflowed the bubble and crushed the main text to one character per line, as on the Remote Host Resources status item. The tooltip now shows such text as a wrapping note separate from the shortcut and honours data-no-tooltip up to the tooltip owner. The remote status items opt out of the redundant ellipsis tooltip and ellipsize their labels, and the breadcrumbs yield space first in the status bar.

Co-authored-by: dengliu <[email protected]>
2026-11-28 20:29:29 +08:00
audichuang 4c01ce4443 fix(console): scroll the current Find match into view sideways (#6640)
Find in the Run and Debug consoles only scrolled vertically to the current match's row, so a match near the end of a line wider than the console stayed out of sight. Once the virtualized row renders, the consoles now scroll the current match mark into view with block and inline 'nearest', as the HTTP response view does. The reveal runs when Find moves or the query or options change, not on appended output, and its sideways scroll does not re-enable Scroll to End.

Co-authored-by: audichuang <[email protected]>
2026-11-28 20:29:14 +08:00
audichuang 9da53322bc fix(vcs): keep favorite branches per repository (#6709)
Favorite branches were one list per project, so in a multi-repository project starring a branch in one repository starred it in all of them. Each repository now has its own list, and every place that shows or toggles a star (Git Branches popup and submenus, the Git Log Branches pane and branch filter, commit and Tracked Branch submenus) reads and edits the list of the branch's repository. A single-repository project keeps the stars saved before.

Co-authored-by: audichuang <[email protected]>
2026-11-28 20:23:57 +08:00
audichuang 720b18861c fix(github): act on the connected repository in multi-repo projects (#6622)
Jump to Source, Review Mode and the details' checked-out state used the repository selected in the VCS widgets even when the connected pull requests belong to another repository. They now use the review repository: the selected one when it has the connected GitHub repository as a remote, else the connection's root. The branch widget offers the pull request entries only while the selected repository is the review repository.

Co-authored-by: audichuang <[email protected]>
2026-11-28 20:21:22 +08:00
audichuang 802d9d26e2 fix(vcs): keep recent branches per repository (#6705)
Recent branches were stored once per project, so in a multi-repository project a branch checked out in one repository showed up under another's Recent Branches. They are now stored per repository root: checkout, New Branch, Rename, Checkout and Rebase and the multi-repository operations record each repository they ran in, and the popups read that repository's list. A single-repository project still reads the list saved before.

Co-authored-by: audichuang <[email protected]>
2026-11-28 20:21:01 +08:00
audichuang fb97cdac03 fix(vcs): remember "Don't warn about this target" per project and (remote, branch) (#6662)
The Force Push confirmation's "Don't warn about this target" list was one app-wide entry of joined remote/branch strings, so silencing a target silenced it in every project and confused origin + team/feature with origin/team + feature. The list is now kept per project, under the key scheme Push tags already uses, as (remote, branch) pairs; the multi-repository Push dialog confirms such targets separately.

Co-authored-by: audichuang <[email protected]>
2026-11-28 20:20:46 +08:00
audichuang caf909cab3 fix(vcs): let a wheel over a pane at its end scroll the other side-by-side pane (#6628)
In the unaligned side-by-side diff with synchronized scrolling, a file ending in a long deletion or addition left one pane at its end while the other still had content below, and a wheel over the finished pane or the divider moved nothing. A synchronized vertical wheel that the pane under the pointer cannot follow now scrolls the other pane; the pointer's pane keeps leading, and wheeling back closes the overshoot over a few notches instead of snapping.

Co-authored-by: audichuang <[email protected]>
2026-11-28 20:20:28 +08:00
audichuang c88a4f403f fix(vcs): keep the Commit preview's diff across a status refresh (#6611)
The Commit tool window builds a new, equal DiffData on every Git status refresh, and the two-pane diff rebuilt its views whenever the request objects changed identity, losing the caret, selection and current find match. The view-building effect now depends on the sides and annotations by content, so only a request with other sides or notes rebuilds the panes.

Co-authored-by: audichuang <[email protected]>
2026-11-28 20:20:09 +08:00
Deng Liuтаdengliu 98f163da75 fix(agents): open SKILL.md from Settings window in parent editor (#6639)
Open SKILL.md in Settings > Agents > Skills did nothing in the native Settings window, which hosts no editor service. The Settings window now forwards editor opens to its parent window over openidea://settings/open-file; the parent opens the file in its project or LightEdit editor (or through file.openPaths from the Welcome screen), raises itself and reports failures. In the in-page Settings dialog, a clean dialog closes so the opened tab is visible, and trailing slashes on skill paths are normalized.

Co-authored-by: dengliu <[email protected]>
2026-11-28 20:10:49 +08:00
LU XIANGRUIтаwildcatDownstairs 5952e36d8b fix(i18n): translate the rename preview's occurrence count (#6667)
The refactoring preview's count line and per-file counts were built from plain English strings. They now go through tx with singular and plural forms, as do the create/delete operation labels, with Chinese translations added.

Closes #6666.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 20:10:27 +08:00
zhzhsxтаzhzhsx ad56613901 fix(vim): let one Escape close popups and exit Insert mode (#6673)
In Insert mode the editor's Escape bindings closed an open popup and stopped the key before Vim saw it, so leaving Insert mode took a second press. In Insert mode the bindings still close popups but no longer stop the key; Normal and Visual mode are unchanged.

Co-authored-by: zhzhsx <[email protected]>
2026-11-28 20:10:06 +08:00
Deng Liuтаdengliu 3fae4c0417 fix(terminal): keep a line height below 1 from blocking live settings (#6660)
xterm.js throws when a line height below 1 is set on a live terminal. With Settings > Tools > Terminal > Line height below 1, the throw inside the settings listener kept later listeners (Appearance and others) from applying until the window was reopened. terminalFont() now hands xterm at least 1, the height a new terminal already renders.

Co-authored-by: dengliu <[email protected]>
2026-11-28 20:09:50 +08:00
zhzhsxтаzhzhsx 99fdea5c9a fix(lsp): request semantic highlighting when a file opens (#6706)
The first semantic-tokens request waited for the 600 ms edit debounce, so a newly opened file showed only syntax colours and then changed colour. The view now requests tokens as soon as it opens; edits still refresh through the debounce.

Co-authored-by: zhzhsx <[email protected]>
2026-11-28 20:09:32 +08:00
zhzhsxтаzhzhsx 8aeac949b5 fix(editor): map t.namespace to Package reference, not Class name (#6684)
Syntax highlighting coloured t.namespace with Class name while semantic highlighting used Package reference, so namespace identifiers changed colour once the language server's tokens arrived. t.namespace now uses the namespace scheme attribute and falls back to Class name when a scheme leaves it unset.

Co-authored-by: zhzhsx <[email protected]>
2026-11-28 20:09:09 +08:00
LU XIANGRUIтаwildcatDownstairs fa625d8cc7 fix(profiler): run cProfile through a launcher that keeps the exit code (#6654)
Profiling a Python run with cProfile replaced the program's exit code with the profiler's, and Stop could end the run before the profile was written. A bundled launcher now runs the target under cProfile, keeps its exit code, and saves the profile once when the run ends or when Stop connects to a named pipe (a FIFO on Unix); the watcher blocks in C so it stays out of the profile. The Windows pipe is created in byte mode with PIPE_WAIT alone, since _winapi doesn't export PIPE_TYPE_BYTE.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 19:13:48 +08:00
Vladislav Kuzmin b7b5bd5c50 fix(run): ignore unchanged JUnit reports from earlier runs (#6700)
Rerun Failed Tests read every JUnit XML written in the two seconds before the run started, so reports Maven left untouched for skipped classes showed up as passes. The host now snapshots recent reports (mtime and blake3 digest) before a local JVM test process starts and, when it exits, reads only reports that are new or whose contents changed. Remote runs and older hosts keep the timestamp window. The Java smoke adds a second passing class to cover the rerun.

Closes #6699.

Co-authored-by: principalwater <[email protected]>
2026-11-28 18:30:28 +08:00
audichuang 2174a7278a fix(editor): don't load a file replaced by binary content as text (#6675)
Reloads under a chosen or remembered encoding decode with ide_vfs::load_text_as, which never reports binary content, so a text file replaced by binary bytes was loaded as text and a later save corrupted it. The reload now probes the file head; when the file turned binary the document keeps its text and reports the change on disk, so autosave leaves the file alone and the user picks Load Changes from Disk or an explicit save. UTF-16 text and buffers already opened as text despite NUL bytes reload as before.

Co-authored-by: audichuang <[email protected]>
2026-11-28 18:25:44 +08:00
Deng Liuтаdengliu 7bbc12382e fix(macos): suppress Siri Writing Tools affordance on macOS 27 (#6614)
macOS 27 shows the Writing Tools affordance over any editable WKWebView selection, covering the editor. The main, project and Settings windows now opt their WryWebView out of Writing Tools; the change is gated on macOS and leaves IME and selection untouched.

Co-authored-by: dengliu <[email protected]>
2026-11-28 18:24:07 +08:00
rolicon 4fb1cae917 fix(java): stop legacy launch records from forcing Maven builds after delegation is off (#6556)
A Maven launch record served both as a reusable snapshot and as the signal to keep delegating to Maven. A failed build left a null record that could not be reused but, because the file existed, kept overriding delegateBuild=false. The need to clean mixed-language output is now persisted on its own (java-launch/delegation): a plain Java build failure or an unpublished snapshot no longer forces later launches through Maven, while a pending cleanup survives failures and restarts and is cleared after a successful Maven clean build. Legacy null and old snapshot records migrate conservatively (no output directory: no cleanup needed). Normal launches and shared Maven builds use the same check, and main launches ignore records kept only for test output.

Closes #5538

Co-authored-by: rolicon <[email protected]>
2026-11-28 14:58:51 +08:00
LU XIANGRUIтаwildcatDownstairs 23bbed8bfe fix(notebook): keep the Jupyter Variables read cheap and out of the way of runs (#6643)
Follow-up to #6517. The Variables read shortens bytes, bytearray and str subclasses without building the full repr, and is interrupted after 5 seconds instead of dropped, so a run waiting behind it gets a drained kernel; a read interrupted for its time limit keeps the kernel. Interrupt, restart and close reach an in-flight read, and several reads can be in flight while a run waits for them.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 14:58:28 +08:00
LU XIANGRUIтаwildcatDownstairs 1880ac541c fix(python): fixture usages and rename follow pytest's files and Python's names (#6655)
Follow-up to #6520. Find Usages, Go to Declaration and Rename of a pytest fixture now search where pytest would look: the defining test module, the test files below a conftest.py, or the project's test files for a plugin or pytest_plugins module, with test files taken from python_files in the configuration file pytest reads. A fixture imported into a conftest or test module is that module's own. Rename merges the language server's rename of the fixture function, refuses names that clash with a parameter or body name, an override or another fixture in scope, and invalid identifiers, and reads of a parameter skip nested scopes that rebind it.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 14:58:10 +08:00
LU XIANGRUIтаwildcatDownstairs d698b50361 fix(python): respect inherited MPLBACKEND and tidy plot files (#6653)
Follow-up to #6529. A run that inherits the IDE's environment now keeps an MPLBACKEND set in the login shell or the project's .envrc instead of replacing it with the Plots backend; debug launches get the backend too, unless their own environment names one. Figures dropped from the Plots tool window are deleted from the project's plots folder (plots_delete, limited to finished figures in that folder, compared canonicalized), and the watcher reports a figure once it is renamed into place.

Refs #6514

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 14:57:42 +08:00
LU XIANGRUIтаwildcatDownstairs d5ba63e333 fix(python): accept direct references and bzr+lp URLs, report a missing path, and keep editable cleared after an archive (#6650)
Follow-up to #6617. The version control dialog now accepts pip's direct references (name @ git+https://..., with extras) and bzr+lp:project. Installing from a local path that does not exist fails before pip runs, with the path in the message; a trailing [extras] is not part of the path, and a folder whose name has brackets is still a folder. Typing an archive path clears the editable choice, so a directory typed after it starts unticked.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 14:57:21 +08:00
l0ng-ai 8108b440a6 fix(dotnet): detect Microsoft.Testing.Platform test projects without the test SDK (#6671)
Run configuration detection treated a .NET project as a test project only when it referenced Microsoft.NET.Test.Sdk, so an xUnit v3 project on Microsoft.Testing.Platform (OutputType Exe, no test SDK) got only a .NET Project configuration and the gutter found nothing to run for its tests. parse_project now uses the evaluated project model's rules: IsTestProject true; a Testing Platform property on (IsTestingPlatformApplication, TestingPlatformDotnetTestSupport, EnableMSTestRunner, UseMicrosoftTestingPlatformRunner) or an xunit.v3.mtp-* package; or, unless IsTestProject is false, MSTest.Sdk or a test framework package (Microsoft.NET.Test.Sdk, MSTest, NUnit, xunit, xunit.v3, TUnit).

Fixes #6602
2026-11-28 14:49:16 +08:00
audichuang 4401ed3119 fix(clipboard): allow clipboard_text in Restricted Mode, like the other clipboard reads (#6658)
clipboard_text was the only clipboard command declared trusted, so in Restricted Mode the native read was refused and readClipboardPlainText() fell back to the WebView's own read: WebKit's Paste callout on macOS (and WebView2's prompt on Windows) appeared for the editor's right-click Paste. Reading the clipboard runs nothing from the project, and clipboard_image, clipboard_file_list and clipboard_has_* are already always. clipboard_text is now always too, as is the web shell's stub; a test pins all clipboard reads to always. Plugins still read through plugin_answer_clipboard, which stays trusted.

Co-authored-by: audichuang <[email protected]>
2026-11-28 14:46:43 +08:00
Deng Liuтаdengliu dbbdc4a085 fix(github): route gh commands through ide-host for remote projects (#6649)
The Pull Requests tool window failed in SSH, WSL and dev-container windows with "no project is open in this window": the gh_* commands were desktop commands in src-tauri and ran on the desktop, while the project lives on the remote host. The 11 gh_* commands move to crates/ide-host/src/ops/github.rs as project_host commands, so remote windows route them to openidea-server, where the repository, gh CLI and project-scoped GH_TOKEN are. gh_account_repos becomes outside_restricted so Clone Repository > GitHub keeps working without an open project, and the streaming gh_pr_* output channels are cleaned up as finite channels when the remote reply completes.

Co-authored-by: dengliu <[email protected]>
2026-11-28 14:44:06 +08:00
LU XIANGRUIтаwildcatDownstairs 85456e6930 fix(python): find conda outside PATH when creating environments (#6661)
Creating a conda environment failed with "conda is not installed" whenever conda was not on PATH (the Windows installers' default), even though the IDE listed that installation's environments. conda is now resolved from the base interpreter's own installation, then PATH, CONDA_EXE, the default install folders (including %ProgramData%) and the installations behind ~/.conda/environments.txt. On Windows it runs with the installation's DLL folders on PATH, as activation would. Discovery and terminal activation use the same lookup.

Closes #6652

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 14:36:59 +08:00
HandsomeXi b4d2859277 fix(build): give cmake --build one job per logical CPU (#6629)
Build Project, Build <target>, Rebuild and the generated CMake Build run configurations ran `cmake --build` without a job count, so the default Makefile generator compiled one file at a time. Every cmake build step now gets `-j <logical CPUs>` before a `--` separator; a count the profile's build arguments already set (-j, -jN, --parallel, --jobs) is left alone. CTest steps are unchanged.

Co-authored-by: HandsomeXi <[email protected]>
2026-11-28 14:36:10 +08:00
l0ng-ai ba880dac06 chore: v0.1.55 2026-11-28 11:10:37 +08:00
LU XIANGRUIтаwildcatDownstairs 0b1a675fab fix(python): install from disk never falls back to PyPI, editable only for a local directory (#6617)
Install from Disk resolved only paths starting with '.', and pip runs in a temporary folder, so a bare name like 'mylib' installed the PyPI package of that name. A typed relative path is now sent as './...' (resolved against the project) and '~/' expands to the home folder, so pip always gets an absolute path. Editable installs are offered and accepted only for a local directory: an editable clone of a repository would land in pip's temporary folder. The version control dialog accepts only vcs+scheme:// URLs, and an archive disables editable.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 11:09:48 +08:00
Vladislav Kuzmin 0b06d3313f test(ssh): send POSIX shell test scripts through stdin (#6620)
The POSIX command round-trip test passed the script to the local sh as an argument; on windows-latest that is Git for Windows' sh, whose argument handling dropped the a\b sample. The test now feeds the program to sh -s through stdin on every platform, still checking all samples and the exact stdout bytes, and reports the exit status and stderr when sh fails.

Fixes #6619

Co-authored-by: principalwater <[email protected]>
2026-11-28 11:09:33 +08:00
l0ng-ai ddaee1f5ce fix(host): keep a command's last output lines after it exits (#6625)
run_command stopped reading a finished command's output after 100 ms without a line, so on a busy machine the last lines (often the error a failed worktree setup script printed) were lost. It now reads until the pipes close, for at most a second. Sibling output loops already wait for the pipes to close.
2026-11-28 11:03:31 +08:00
Vladislav Kuzmin 623f1fa4e7 fix(ci): run language smoke for refactor providers (#6552)
src/editor/api.ts imports src/editor/refactorProviders.ts since #6520, so the frontend smoke loads it. Add it to the Language smoke push/pull_request paths and to the Changes step's smoke pattern so a change to it runs every language.

Co-authored-by: principalwater <[email protected]>
2026-11-28 11:01:33 +08:00
l0ng-ai 79f6476d52 fix: unique menu row keys, backend-only plugin points, Debug Server host hint (#6623)
Menu rows of one action repeated with object args (Run with Coverage, Profile... via run.withExecutor) shared a React key; repeated keys now get a suffix. The client defines the backend-only runConfigurations and locales plugin points so plugins contributing them no longer log 'has no client projection'. The Python Debug Server host hint now says loopback hosts listen on loopback only, matching how the listener binds.
2026-11-28 10:55:14 +08:00
Vladislav Kuzmin bd396485c2 feat(database): support DuckDB SQL and browse attached catalogs (#6254)
DuckDB sources get DuckDB's SQL dialect (highlighting, completion, formatting and resolution) and the database tree lists attached catalogs with their schemas, tables and columns. The JDBC bridge gains a catalogs command and catalog-scoped schema and table metadata, matched by exact catalog and schema names; tables in another catalog open and page through the source session. DDL that attaches, detaches or changes a catalog refreshes the tree.

Co-authored-by: principalwater <[email protected]>
2026-11-28 09:07:53 +08:00
Vladislav Kuzmin c04d9381be feat(database): add a Database Output tool window for SQL consoles (#6243)
SQL consoles and files get a Database Output bottom tool window. It follows the active editor, keeps result tabs and errors scoped to each console, and has a client selector (file name with its data source) for looking at another run, plus a button to open that client in its editor. Run and Explain reveal the current client's results while keeping editor focus; background completions and late Explain responses leave the selected client in view. Switching clients or destinations never re-runs SQL. Settings > Tools > Database can send results to Services instead.

Closes #6176

Co-authored-by: principalwater <[email protected]>
2026-11-28 08:56:19 +08:00
Vladislav Kuzmin 45f6366b92 feat(database): explain queries on named DuckDB sources (#6244)
Explain Plan now works for DuckDB data sources connected through JDBC. The statement runs as EXPLAIN (FORMAT JSON) in the console's session (so temporary tables resolve), and the physical plan is shown, falling back to the optimized or logical plan when explain_output asks for those; operator details become node properties. A script with several statements is checked with json_serialize_plan first and refused. Other custom JDBC sources still have no Explain Plan.

Co-authored-by: principalwater <[email protected]>
2026-11-28 08:49:45 +08:00
l0ng-ai fb0b2d6a5f fix(ssh): run remote commands with sh whatever the login shell (#6612)
sshd runs every exec request through the account's login shell. The commands the IDE sends (server probe and install, connection test, run targets, command tunnels) are POSIX shell, so with fish as the login shell they failed with stderr only and opening a remote project never got past the probe.

Exec requests now send sh -c '<script>', a plain command to every shell, quoted so that fish reads the same text as a POSIX shell (quotes and backslashes written outside the single quotes). The login shell still starts first, so its environment is inherited; interactive terminals keep the login shell itself.

Fixes #6200
2026-11-28 08:44:47 +08:00
LU XIANGRUIтаwildcatDownstairs ddea7e5ec5 feat(python): install packages from version control or a local directory (#6601)
A + button in the Python Packages tool window offers Install from Version Control… and Install from Disk… (with Browse), both with Install as editable (-e). A plain https://, ssh://, git:// or git@host:path URL gets pip's git+ form; git+… and other vcs+ URLs pass as they are. sdk_python_pip takes an editable flag that adds -e (pip and uv pip); text starting with - is still refused, so no other pip option can be passed.

Closes #6531

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 08:37:01 +08:00
LU XIANGRUIтаwildcatDownstairs 3747a8a63f feat(python): show package documentation in the Python Packages tool window (#6600)
When the pane has a package's PyPI details (a search result, or an installed package after Show PyPI Details), it also shows the project's links (its PyPI page, home_page and project_urls; http(s) only, duplicates dropped) and its long description: rendered Markdown (sanitized, as in hover docs) when description_content_type is Markdown, plain text otherwise. Links open in the browser. Everything comes from the JSON API response the pane already loads.

Closes #6530

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 08:31:32 +08:00
l0ng-ai 0a8fea1876 fix(agents): take one lock at a time when checking for pending input (#6610)
emit_attention_if_input_pending held the permissions guard, a temporary living to the end of the statement, while taking the task state lock. approve_pending takes them the other way round, so a permission request and a bypass-approvals config change on another thread could deadlock. The check now releases the permissions lock before reading the status.
2026-11-28 08:29:23 +08:00
Deng Liuтаdengliu ccc0eb1f54 fix(agents): settle in-flight turns cleanly on manager shutdown (#6606)
Closing a project or quitting while an agent turn was in flight left the task Failed with "The agent process exited.": shutdown killed the peer, and the still-running turn then woke up, failed the task and overwrote what shutdown had saved. Restart only normalizes Running/NeedsInput/Starting, so the Failed state stuck.

A shutdown epoch on the manager now marks work started before a shutdown (turns, session opens, permission and form requests, notifications, delayed saves); that work exits quietly instead of failing the task or rewriting its file. A peer still mid-handshake is tracked and killed by shutdown, and interrupted tasks settle to Ready. The manager stays usable after a shutdown (trust revoked and granted again).

Co-authored-by: dengliu <[email protected]>
2026-11-28 08:28:11 +08:00
l0ng-ai 54dadc4605 fix(vcs): keep a diff tab's scroll position across tab switches (#6609)
Switching away from a Show Diff tab unmounted the diff viewer, so switching back rebuilt it at the top. The single-file and combined diff kinds are now kept alive like other recently used tabs, so they come back where they were left (scroll, caret, expanded lines) without reloading the revisions.

Fixes #6394
2026-11-28 08:25:26 +08:00
l0ng-ai 6fba4671e6 fix(editor): drop Pinyin syllable spaces when the input source switches mid-composition (#6608)
Switching macOS Pinyin to English while composing commits the composition as displayed, with the spaces the IME shows between syllables, so typing nihao left "ni hao" in the editor. When the commit is exactly the ASCII composition text, the editor now rewrites it to the letters typed, at every cursor that took it, in the same undo step. Candidate commits are unchanged. The commit rule moves to platform/ime so the terminal and the editor share it.

Fixes #6393
2026-11-28 08:16:39 +08:00
l0ng-ai d5058b930b fix(macos): stop restoring full screen from saved window state (#6607)
Window state is kept per label, and project-N labels are reused by other projects. A full-screen flag saved once came back on every later project window, each claiming its own Space, some while still hidden and blank. macOS no longer saves or restores the full-screen flag; a window that was full screen comes back maximized. Windows and Linux are unchanged.

Fixes #6430
2026-11-28 08:14:13 +08:00
l0ng-ai 44aab11296 fix(java): open output-directory class files decompiled (#6605)
Opening a .class under target/classes or build/classes jumped to the project .java it was built from. The resolver now returns the class document itself, so the compiled class opens read-only as decompiled text. Library classes in archives are unchanged.

Fixes #6410
2026-11-28 08:11:48 +08:00
l0ng-ai fcd24885c1 fix(build): select Maven projects by coordinates when processing launch resources (#6604)
The launch resources step selected changed modules by their Maven basedir relative to the reactor root. On Windows the basedir need not share a spelling with the opened folder, so the absolute path reached -pl and Maven could not find the project in the reactor. It now selects them by groupId:artifactId.

Fixes #6409
2026-11-28 08:08:24 +08:00
Vladislav Kuzmin 4b3717618f fix(database): isolate JDBC console sessions (#6553)
Two SQL consoles on one JDBC data source waited on the same connection, so a long query, cancellation or close in one blocked the other. The JDBC bridge now multiplexes one connection per console inside the existing bridge JVM (capped at 32, with bounded reply buffers), and result reads, cancel and close are routed to the originating console's connection. DuckDB console connections share the database and its attachments with separate temporary tables and session settings; anonymous SQLite and H2 databases keep one shared connection so their contents stay visible.

Fixes #6484

Co-authored-by: principalwater <[email protected]>
2026-11-28 08:05:59 +08:00
Vladislav Kuzmin 8fd5ee382d fix(database): isolate PostgreSQL manual transactions by SQL console (#6482)
Two PostgreSQL consoles on the same data source shared one manual transaction, so one console could see and commit the other's pending work. Each console now owns its manual transaction: Commit, Roll Back, Stop, result reads and close act on the originating console, retained results keep their transaction until the last reference closes, and a statement for a lost transaction fails before executing. The pool reserves capacity for ordinary work; up to two manual transactions can hold a connection per target, and a third gets a message on how to free a slot. Auto-commit and the transaction-pooler read-only path are unchanged.

Fixes #6445

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:57:17 +08:00
Vladislav Kuzmin 3a3b2e424a perf(remote): reuse the verified release archive for SSH installs (#6288)
The first SSH install recompressed the unpacked server with fast gzip before uploading it. The release download now keeps its gzip next to the cached binary, and the SSH install sends that archive when it decodes to exactly the selected binary (size and BLAKE3 hash); custom binaries and missing or mismatched archives fall back to the existing upload. Container and WSL installs are unchanged. For the Linux arm64 payload this sends about 51 MB instead of 66 MB.

Fixes #6283

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:44:18 +08:00
Vladislav Kuzmin b9d0e28f7a fix(database): bound idle waits for ClickHouse HTTP responses (#6456)
A ClickHouse HTTP response that stalled (a relay holding the reply, a dropped connection) left the console showing Running forever. The built-in driver now stops waiting after 600 seconds without response data and reports that the outcome is unknown, with the query_id; it does not replay or cancel the statement. Reading another chunk restarts the timer, and the Advanced property http_read_timeout (seconds) changes the interval.

Fixes #6435

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:39:50 +08:00
Vladislav Kuzmin 53627ea2e9 fix(database): reject session SET on stateless ClickHouse HTTP (#6442)
ClickHouse accepts a standalone SET over HTTP, but without a session the setting is gone before the next request, so a console script silently ran its later statements with other settings. With use_http_session=false the driver now refuses a session-scoped SET before sending it and says to use a session or query-level SETTINGS; named sessions, SETTINGS clauses and SET DEFAULT ROLE are unchanged. The ClickHouse splitter now also treats # line comments and nested block comments as comments.

Fixes #6432

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:38:29 +08:00
Vladislav Kuzmin 55366a2a31 test(build): report Gradle output when fixture preparation fails (#6564)
When the Gradle model fixture could not be prepared, the test panicked with only the unsupported reason and hid the build error. It now appends the last 150 lines of the build output from both streams, with a unit test for the tail.

Fixes #6555

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:37:09 +08:00
Deng Liuтаdengliu 0b9610fe69 feat(appearance): add a project color strength setting (#6592)
Settings › Appearance › Use project colors in main toolbar gains a Project color strength slider (10–70%) that scales the header's project colour wash. The default stays at today's 22%, so nothing changes unless the slider is moved.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:34:23 +08:00
l0ng-ai 43e3575eb2 test(settings): expect the Thymeleaf inspection group (#6599)
#6598 added the Thymeleaf inspection group; the inspections tree test still listed the old groups.
2026-11-28 07:33:01 +08:00
Deng Liuтаdengliu bc4a422424 feat(remote-dev): show the remote host in grouped project window tabs (#6577)
Window group tabs of remote development windows now show a flat 'SSH · host' (WSL, Dev Container) label after the project name, with the full host and remote path in the tab's tooltip, and take their name from the remote project's display name instead of the window title. WindowTab carries the connection's host, and remote connections keep the project's display name.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:26:55 +08:00
Deng Liuтаdengliu 7ccaa10496 feat(remote-dev): distinguish remote windows and project switcher entries (#6557)
Remote projects in the project switcher and the welcome screen's recent list now carry a server badge on their avatar and an 'SSH · host' (WSL, Dev Container) label above the remote path, with search highlights split between host and path. The Remote Host status bar item gains the remote icon, and shows its disconnected state as a warning-coloured label.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:21:32 +08:00
Deng Liuтаdengliu b5e45ca98b feat(agents): consolidate session stats into a Session Info popover (#6563)
The agent status strip showed context usage, last-turn tokens, every usage-limit window and session cost inline. It now shows the context ring and percentage, plus any usage limit at 80% or more in its warning tone; everything else moves into one Session Info popover with a Context Window bar (reserved-for-response segment, System and User Context breakdown with token counts on hover), the last turn's tokens, usage limits and cost. Free space and deferred categories are skipped by name for Claude Code.

GitHub Copilot sessions now report a context breakdown through _openidea/context_usage (session.metadata.getContextAttribution, with contextInfo and usage_info fallbacks), accumulate AI-credit spend across turns and subagents, keep session cost across usage updates without cost, map /compact to session.history.compact, and label quota windows Chat, Completions and Premium requests.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:19:50 +08:00
Deng Liuтаdengliu 6faff1b1a8 feat(agents): autocomplete slash command arguments and show inline hints (#6567)
Typing a slash command and a space (/skills, /sandbox, /remote, Codex's /goal) now offers its subcommands with descriptions, chains /skills info and /skills remove into the session's active skills, and shows a muted inline argument hint after /command until an argument is typed. AgentCommand keeps structured choices from Copilot's commands.list, Codex builtins and ACP available_commands_update, with a fallback that parses literal [a|b|c] hints. Enter on /skills and /mcp still opens the session pickers; Tab or a trailing space enters subcommands.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:14:43 +08:00
Vladislav Kuzmin 1edfa9180b test(profiler): wait for profiled loop work before stopping (#6588)
a_stopped_run_still_writes_its_profile sent SIGINT right after the fixture printed done, which could land before the loop ran, so the profile held only the initial fib(22) calls and the 'the loop ran' assertion failed. The fixture now prints looped after its first fib(18), and the test stops the run only after reading it, then checks for both completed passes.

Fixes #6585

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:09:47 +08:00
Vladislav Kuzmin b15c56cdb0 test(project): wait for the updated attached-root index (#6587)
attached_projects_keep_their_own_excluded_folders waited for the attached project's exclusion settings to change, then for the index to go idle. The settings become visible before the background refresh queues the rescan, so the index could be idle with its previous results. The test now waits for the newly included file to appear in the index.

Fixes #6584

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:09:15 +08:00
audichuang 91ff5c8a15 feat(thymeleaf): warn on fragment expressions naming a missing template or fragment (#6598)
Templates under src/main/resources/templates get a warning (underline and Problems) on a fragment expression whose template does not exist or does not define the fragment, as the inspection Thymeleaf > Unresolved template and fragment references. A fragment counts as defined by th:fragment, th:ref, an element of that name, or an id. It stays silent where names cannot be resolved as Spring Boot's defaults do: spring.thymeleaf.prefix or suffix set in application.properties / .yml, missing templates outside the project folder's own templates directory, ~{_}, ?: fallbacks, expression names, relative names and comments. Template names get .html unless they end in an extension Thymeleaf recognizes, which also fixes Go to Declaration on names with a dot.

Part of #2889

Co-authored-by: audichuang <[email protected]>
2026-11-28 07:07:06 +08:00
Vladislav Kuzmin 929b6837f9 fix(agents): keep archived tasks from resuming on a permission reply (#6586)
Archiving a task cancels its pending permission request. The reply handler checked whether to resume the task, released the state lock, then reacquired it to write Running; an archive finishing in between left running on disk, so the task came back outside the archive after a restart. The handler now records the answer and resumes the task under the same state lock, so a later archive still takes effect. A regression test overlaps settlement with archiving and checks the persisted Archived status and the recorded answer.

Fixes #6583

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:05:44 +08:00
Deng Liuтаdengliu d1af5f656a fix(windows): include remote development windows in Merge All Project Windows (#6593)
Merge All Project Windows only collected windows with a local project, so remote development windows were left out. Candidates now include every local or remote project window (welcome and LightEdit windows stay out), selected by a unit-tested merge_candidates helper in ide-workspace. A member that shares a native tab group or frame with a window outside the merge is split from it first, so that window is neither pulled in nor left hidden.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:02:55 +08:00
audichuang 604e9348f2 fix(vcs): offer New Changelist and Move under Group By Staging State (#6596)
With the staging area off and the Commit tool window grouped by Staging State, the Staged / Unstaged nodes carry no changelist, so Move to Another Changelist… was hidden and New Changelist… (only on changelist headers) was unreachable. Their nodes and files now offer Move to Another Changelist… in the first group and New Changelist… next to Create Patch and Shelve. Nothing changes with the staging area on.

Fixes #6422

Co-authored-by: audichuang <[email protected]>
2026-11-28 07:01:37 +08:00
audichuang 9592b9ee1b fix(vcs): Jump to Source in the comparison window opens the file in the project window (#6595)
Jump to Source from a diff in the Compare with Branch window went to the comparison window's own editor area, which stays hidden until Show Diff, so nothing appeared. The comparison window now hands openFile to the project window's editor, as the diff window does, for files in any folder of the project (workspace projects included); files outside the project still open in the comparison window.

Fixes #6405

Co-authored-by: audichuang <[email protected]>
2026-11-28 06:59:28 +08:00
Paweł SzymańskiтаPawelSzymanski89 c658b3eb88 fix(notifications): stop leaking a thread per macOS system toast (#6597)
With an action handler registered, tauri-plugin-notification shows every macOS toast on a thread of its own that waits for a click. Toasts that are never clicked keep their thread and NSUserNotificationCenter work alive, so the app slowly gets laggy.

macOS now skips the action handler, so toasts are delivered without tracking; clicking one activates the app instead of focusing the exact window that raised it. Windows and Linux keep per-window focus.

Co-authored-by: PawelSzymanski89 <[email protected]>
2026-11-28 06:57:19 +08:00
audichuang cc5d9d95e4 feat(vcs): bold the current revision's lines in the annotate gutter (#6594)
Lines last changed by the file's current revision are drawn bold in a last-commit colour in the Annotate gutter. The current revision is the last commit to the file at HEAD, or at the annotated revision for Annotate Revision and the diff/merge panes; it is read with vcs_log after the gutter paints and again when HEAD moves. The colour is a new token, --git-annotations-last-commit, listed under Color Scheme > Git > Annotations > Last commit and imported/exported as ANNOTATIONS_LAST_COMMIT_COLOR.

Refs #6397

Co-authored-by: audichuang <[email protected]>
2026-11-28 05:55:03 +08:00
Vladislav Kuzmin 75a15b7eed fix(database): isolate ClickHouse console sessions (#6455)
The built-in ClickHouse HTTP driver gives each SQL console its own named session: a second console finishes while the first one runs, and repeated statements in one console keep their SET values and temporary tables. Result paging, Explain and Stop use the same console identity, and closing the console's last editor or result releases it. Requests without a console stay stateless and can run concurrently. The PR also carries the TODO layout and bookmarks fixture fixes from #6507/#6458.

Closes #6433

Co-authored-by: principalwater <[email protected]>
2026-11-28 05:50:23 +08:00
audichuang b2998cb37a fix(project-tree): scroll the inline name field into view when it starts (#6590)
In a folder scrolled so its top was out of view, New > File / Directory / Package showed no name field and keystrokes went to the tree's speed search: the tree is virtualized and the placeholder row was never mounted. Starting an inline edit (new item or rename) now scrolls its row into view through a new TreeHandle.scrollIntoView, leaving the viewport alone when the row is already visible.

Closes #6461

Co-authored-by: audichuang <[email protected]>
2026-11-28 05:43:05 +08:00
audichuang 5c131edb7e feat(http-client): go to the Spring endpoint from a RestTemplate or WebClient URL (#6581)
Go to Declaration on a literal URL in a RestTemplate, WebClient or RestClient call (the *For* methods, put, delete, exchange with HttpMethod.X, and the fluent .get()/.method(HttpMethod.X).uri(...)) in Java and Kotlin now opens the matching controller method, reusing the Feign controller index, path matching and service filtering. A bare host narrows the targets to that spring.application.name, and falls back to every matching endpoint when no module has that name. With no match, Cmd-click still opens the URL.

Refs #3882

Co-authored-by: audichuang <[email protected]>
2026-11-28 05:41:20 +08:00
audichuang bb8906edb8 feat(vcs): Colors submenu in the Annotate Options menu (#6582)
The Annotate gutter's Options menu gets a Colors submenu with Author, Order (the default, tint by commit order) and Hide. Author gives the authors, sorted by name, the palette colours in turn. The choice is kept in localStorage and applies to every annotated editor, like the column and Names options.

Refs #6397

Co-authored-by: audichuang <[email protected]>
2026-11-28 05:40:40 +08:00
Deng Liuтаdengliu 2e3b087db7 fix(remote-dev): apply custom project color on remote windows and tabs (#6576)
Change Project Color… did nothing in a remote development window: the window group's tab had no root, because it only looked up local projects. Remote windows now report their remote location (ssh://host/path) as the tab root, and the workbench reads the custom colour under the same key the project popup, Welcome and the window tabs store it, so the tab, title bar avatar and frame tint update. Window tabs refresh when a remote session connects or disconnects.

Co-authored-by: dengliu <[email protected]>
2026-11-28 05:38:40 +08:00
l0ng-ai 0c5f1ffabf fix(ci): rebuild the execution-output plugin component after formatting its source (#6591)
#6572 rustfmt-formatted the fixture's source, which changes its source fingerprint, so plugins/build.sh --check reported dist/plugin.wasm as stale. Rebuilt with plugins/build.sh.

Refs #6569
2026-11-28 05:35:34 +08:00
Vladislav Kuzmin 0a9055b40d test(clipboard): serialize Windows clipboard fixtures in Nextest (#6574)
Nextest runs each test in its own process, so the per-process SERIAL mutex of the three Windows clipboard tests from #6549 did not keep them from writing the system clipboard at the same time. A Nextest test group with one slot runs them in turn while other tests stay parallel.

Closes #6571

Co-authored-by: principalwater <[email protected]>
2026-11-28 05:32:15 +08:00
Bert Verhelstтаbertyhell 8776bf536f feat(database): add and drop keys and indexes from Modify Table (#6578)
Modify Table can change an existing table's primary key, add and drop unique keys, and create and drop indexes, each statement shown in the Preview. The index catalog query now marks the indexes that enforce a primary or unique key (DbIndexInfo.key), so they are listed under Keys and dropped with their constraint instead of a drop index the server rejects. Engines that cannot express a change don't offer it (SQLite: indexes only; Snowflake: primary key only). Existing keys and indexes are kept or dropped, not edited. The tree's Drop of a SQL Server index now emits drop index ix on schema.table.

Part of #6307

Co-authored-by: bertyhell <[email protected]>
2026-11-28 04:19:28 +08:00
Vladislav Kuzmin 9cc781717d fix(coverage): align headers while the tree scrolls (#6506)
#6468 increased the Tree's end inset while its scrollbar is visible, so in a narrow Coverage dock the percentage cells shifted 2 px from their headings. The Coverage header now uses the matching inset.

Closes #6499

Co-authored-by: principalwater <[email protected]>
2026-11-28 04:14:12 +08:00
Vladislav Kuzmin 8f1e95e5a2 test(diff): align navigation fixtures with the initial difference (#6505)
#6471 opens a diff at its first change when the caller gives no line, so the cross-file navigation test clicked Next once too often before checking the boundary hint. The tests that navigate from the top now pass an explicit starting line.

Closes #6500

Co-authored-by: principalwater <[email protected]>
2026-11-28 04:14:03 +08:00
l0ng-ai e49c634064 fix(ci): expect commit fixOnCommit in default settings and format the execution-output fixture (#6572)
#6540 added vcs.commit.fixOnCommit, so the defaults JSON shape test now lists it. #5131 left the execution-output plugin fixture unformatted, which failed the plugin crates' cargo fmt --check.
2026-11-28 03:38:37 +08:00
Vadim LazukтаInf1mum 4e82599c49 feat(dotnet): show solution tree discovery states (#6566)
While the .NET workspace scan runs, or after it failed, the Project view showed nothing where the solutions would appear. One placeholder .NET root now carries the state as grey detail text (Scanning… / Scan failed); idle and empty still registers no root, and a failed scan still retries on next use.

Refs #5635

Co-authored-by: Inf1mum <[email protected]>
2026-11-28 03:26:26 +08:00
Akbar Husain e08de6771d feat(mcp): add optimize_imports tool (#6562)
reformat_file's description pointed agents at an optimize_imports tool for import-only cleanup, but none was registered. optimize_imports runs the existing organize-imports path (including the Ruff fallback for Python) on the given files without reformatting and returns the same capped unified diff as reformat_file. Documented in the English and Chinese MCP guides.

Co-authored-by: akbar1214 <[email protected]>
2026-11-28 02:24:34 +08:00
Bert Verhelstтаbertyhell d31a22b5dd perf(editor): let Alt+Enter and refactorings go before Code Vision usage counts (#6560)
Code Vision usage counts run project-wide searches on the same language server and only gave way to Go to Declaration, so Alt+Enter, Refactor menu actions, Refactor This, code actions by kind and Apply Quick Fix queued behind them on a busy server (jdtls on a large project).

The foreground mark now covers every request the user waits for: those requests mark themselves while they ask the server, and the usage counts and implementation gutter markers cancel in-flight work and resume afterwards. Refactor menu actions show a pending hint while the server is busy.

Refs #6381

Co-authored-by: bertyhell <[email protected]>
2026-11-28 02:20:06 +08:00
Bert Verhelstтаbertyhell cead5f08f7 fix(terminal): expand ~ to the remote home in remote windows (#6559)
In a remote window (WSL, SSH, dev container), a ~/ path in the terminal never became a Ctrl+hover link, and a ~/...:12 link opened only through the project-wide basename search, so it could open a same-named file in the project. Terminal links took ~ from the desktop's home only, and had no home at all in a remote window. Both now use the home of the machine the shell runs on: the desktop's home in a local window, and $HOME (else %USERPROFILE%) of the project host in a remote window, read through run_system_env, which runs on that host.

Closes #6246

Co-authored-by: bertyhell <[email protected]>
2026-11-28 02:13:02 +08:00
l0ng-ai 1fc9a9f5d5 feat(vcs): settings to hide the change markers in the gutter and on the scrollbar (#6558)
Editor > General gets a Gutter section with "Highlight modified lines in the gutter" and, under it, "Highlight modified lines in error stripe on the scrollbar". Both are on by default; turning off the first hides the scrollbar marks too, and the change applies to open editors right away through a changeMarkerDisplay facet set from the prefs compartment.

Fixes #6539
2026-11-28 02:01:47 +08:00
Deng Liuтаdengliu 11a8152988 feat(remote-dev): show used and total disk space in resources dashboard (#6554)
The Disk card in Remote Host Resources replaced total capacity with live read/write throughput once disk I/O counters arrived, leaving only the free space in its header. The header now shows used / total like the Memory card, and the subtitle and status bar tooltip keep the free space beside the read/write rates (or the used percentage when I/O counters are unavailable).

Co-authored-by: dengliu <[email protected]>
2026-11-28 01:53:16 +08:00
LU XIANGRUIтаwildcatDownstairs 10b459268e feat(python): set Django up in the Python Console of a Django project (#6543)
In a Django project the Python Console started a plain interpreter, so importing models failed with ImproperlyConfigured. When the project's manage.py sets DJANGO_SETTINGS_MODULE, the console now starts in manage.py's directory and its driver calls django.setup() with that settings module (one already in the environment wins, as for manage.py). On Django 5.2+ it also defines what manage.py shell imports automatically (the models, settings, timezone, ...) and keeps those names out of the Variables pane. The header shows the Django version; if setup fails, the traceback is printed and the console works as before.

Closes #6536

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 01:51:13 +08:00
LU XIANGRUIтаwildcatDownstairs 382c22cfc3 feat(python): complete Django field lookups and offer django-types for model typing (#6545)
In Model.objects.filter( (and exclude, get, get_or_create, update_or_create, also after other queryset calls) the keyword completes the model's fields: pk, fields inherited from project base models, and reverse relations by related_name or the lowercase model name. __ follows a relation, and after a plain field come its lookups, with date and time transforms for date fields. Models are read from the project's models.py files and read again when one changes.

When the project's interpreter has Django but neither django-types nor django-stubs, a banner on Python files offers to install django-types (pip as a background task, then the type checker restarts), so basedpyright types managers and model fields.

The stubs check and the manage.py, URL-name and model lookups run again once indexing ends, since on a fresh open they can run before the index has the project's files.

Closes #6541

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 01:50:02 +08:00
LU XIANGRUIтаwildcatDownstairs 7bb69e353d feat(python): complete and navigate Django URL names in reverse() calls (#6544)
In Python files, the first string argument of reverse(, reverse_lazy(, redirect( and resolve_url( completes URL names, and Go to Declaration on it opens the path(..., name=...) entry. Names come from the project's urls.py files under their module's app_name (shop:product), with the file shown beside each, and are read again when a urls.py changes. They rank above the parameter names the language server suggests in the string.

Closes #6537

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 01:48:54 +08:00
LU XIANGRUIтаwildcatDownstairs 988f93be46 feat(python): run manage.py tasks from Run Anything with command completion (#6542)
Adds Run manage.py Task… (django.runManageTask), which opens Run Anything with manage.py typed. A Run Anything provider recognises manage.py lines (also ./manage.py and python manage.py), completes the command word from manage.py help (read once per project, shown with the app that defines each command), and runs the line with the project interpreter in manage.py's directory in a terminal-emulating Run tab, so createsuperuser and shell can prompt. runAnything.show now takes an optional initial line.

Closes #6535

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 01:48:00 +08:00
Muuтаmuutot 494dd61193 feat(settings): import JetBrains live templates (#6546)
Import Settings now reads templates/*.xml from a JetBrains settings archive or settings folder and, after confirmation, merges the templates (group, abbreviation, description, body, variables and defaults, contexts, deactivated state) into the custom live templates under stable jetbrains.* ids, so importing again updates rather than duplicates. Built-in and unrelated custom templates are kept.

Contexts are read as IDEA writes them: the full context id first (JAVA_SCRIPT, SHELL_SCRIPT), then its shorter prefixes down to the language (JAVA_STATEMENT, Python_Class, JS_STATEMENT, KOTLIN_TOPLEVEL), OTHER as everywhere, and comment or string contexts expand outside code. Templates whose contexts don't map to a language are listed as not imported, never made global; expressions OpenIDEA can't evaluate are listed and kept as text.

Co-authored-by: muutot <[email protected]>
2026-11-28 01:39:19 +08:00
audichuang cbabb5e9b5 fix(debug): cancel pending debug builds and launches when closing a project (#6282)
Closing a project while a debug launch was still starting (a Cargo build before CodeLLDB, or the adapter spawning and connecting) didn't stop it, so the adapter started for the closed project once the build finished: nothing between debug_start and session registration was tied to the project's lifetime.

Project now has a closed token that debug_start passes down. Closing the project cancels the Cargo build (killing its process tree, through a Job object on Windows) and the adapter launch.

Co-authored-by: audichuang <[email protected]>
2026-11-28 01:35:15 +08:00
GuoYuтаguoyucode 75997ae0ee fix(clipboard): read and write the Windows clipboard one call at a time (#6549)
Concurrent clipboard reads from the project tree raced on the Windows clipboard, which only one caller can open at a time, so a paste could fail with an access error. All Windows clipboard functions now hold a process-wide lock, and the project tree joins an OS clipboard refresh that is still running instead of starting another read.

Fixes #6388

Co-authored-by: guoyucode <[email protected]>
2026-11-28 01:25:36 +08:00
Muuтаmuutot 81df8f2649 feat(python): apply Ruff safe fixes on save and commit (#6540)
Adds a "Fix safe lint issues on save" Ruff setting that runs ruff check --fix-only on Python files when saving, and a commit check that applies the same safe fixes before committing. Safe fixes run separately from formatting and Format on save.

Also translates the new "No safe lint fixes to apply" message and drops the replaced on-save hint from the ko/ru/tr catalogs.

Co-authored-by: muutot <[email protected]>
2026-11-28 01:23:52 +08:00
l0ng-ai 26992ec4ce fix(syntax): comments between a start tag's attributes are not XML syntax errors (#6551)
Without an XML language server, the built-in parser's syntax check flagged a comment inside a start tag, which is read as whitespace. For the XML grammar the check now runs on the text with such comments blanked (lines and UTF-16 columns kept); an unclosed comment or an unterminated tag still reports.
2026-11-28 01:03:23 +08:00
Akbar Husain 2c22574be0 fix(lsp): drop LemMinX's comment-in-start-tag error in XML (#6548)
XML files can keep attributes commented out inside a start tag (JGroups' configs do). Such a comment is accepted as whitespace, but LemMinX (Xerces) stops at <!-- and reports the whole tag as ElementUnterminated. That diagnostic is now dropped only when the reported tag is well-formed with its comments removed; real parser and schema errors stay.

Co-authored-by: akbar1214 <[email protected]>
2026-11-28 01:00:09 +08:00
LU XIANGRUIтаwildcatDownstairs 93368d4379 feat(profiler): profile Python runs with cProfile (#6512)
Profile on a Python configuration runs it under cProfile from the standard library when py-spy can't sample without root (always on macOS), or when Settings > Python > Profiler chooses cProfile. Scripts, modules and pytest configurations run with their own interpreter; stopping the run still writes the snapshot, which opens in the profiler view.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 00:54:42 +08:00
l0ng-ai 14741101bd perf(agents): don't keep the slash command list of archived tasks (#6528)
Each saved task kept the slash commands its agent last offered (up to ~200 entries) in memory and in the task list, archived ones included. Archiving now drops the list and tasks loaded archived start without it; completion for a task without a list uses what its agent last offered in the project.
2026-11-28 00:47:38 +08:00
l0ng-ai db60deede5 perf(agents): read a task's conversation from disk when it is first needed (#6527)
Opening a project parsed every saved agent task in full and kept every conversation in memory for the whole session, archived ones included. Startup now decodes only each task's own fields; the conversation and turn checkouts are read from the task file on first use. A conversation that cannot be read shows empty and is never saved over. agent_entries runs on the blocking pool since its first call parses the file.
2026-11-28 00:46:31 +08:00
l0ng-ai ab2a7767c7 feat(plugins): plugin commands can run a configuration through the plugin's executor (#6547)
The Run/Debug with <title> actions of a plugin executor took only an object argument, while a plugin command passes text, so a plugin's own entry could start a configuration only as a plain run without the executor's Java agent. They now take a configuration id, or a services.context / services.toolbar command's argument as it came (the first selected service's configuration).

Fixes #6516
2026-11-28 00:20:48 +08:00
LU XIANGRUIтаwildcatDownstairs 49c917880d feat(python): find usages and rename for pytest fixtures (#6520)
Find Usages and Rename on a pytest fixture (its definition or a test parameter that requests it) now cover every test and fixture that requests it by parameter name, including conftest.py fixtures used across the directory tree, overrides and usefixtures markers.

Closes #6513

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 00:15:16 +08:00
l0ng-ai f0db09aca5 fix(java): remove jdtls temporary files left in the workspace by earlier versions (#6538)
A workspace whose path has a space (every workspace on macOS) keeps jdtls' temporary files in the system temp folder, but the old <workspace>/.tmp was never read again, and a workspace in use is never removed as unused. Each jdtls start now removes that folder when the temporary files live elsewhere.

Fixes #6515
2026-11-27 23:54:53 +08:00
LU XIANGRUIтаwildcatDownstairs 979cce1175 feat(python): show matplotlib figures in a Plots tool window (#6529)
Python runs, debug sessions and the Python Console get MPLBACKEND pointing at a small bundled Agg backend (unless the run or the environment already sets it). plt.show() saves each open figure as a PNG in the project's cache folder; a watcher sends PlotAdded and the Plots tool window lists the figures with thumbnails, the image viewer, save, copy and delete. Settings > Python > Plots turns it off.

Closes #6514

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 23:53:40 +08:00
Muuтаmuutot faa7571038 feat(scratch): add New Scratch Buffer (#6525)
New Scratch Buffer (NewScratchBuffer, no default shortcut) cycles through buffer1.txt to buffer5.txt in the scratches folder: an existing buffer is opened with its contents (matched case-insensitively), a missing one is created empty. Listed in the keymap presets and the scratch guide.

Co-authored-by: muutot <[email protected]>
2026-11-27 23:40:52 +08:00
Deng Liuтаdengliu 264bf6969f feat(remote-dev): add remote host resource indicator and dashboard (#6425)
A remote window (SSH, WSL, Dev Container) shows a compact CPU and memory indicator beside the connection status; network and disk badges appear only when saturated. Clicking it, or Show Remote Host Resources, opens a dashboard with 60-second sparklines for CPU (cores, load), memory, network (with RPC round-trip latency) and disk (I/O and free space), the OpenIDEA processes on the host grouped by kind, and the top other host processes.

End Process asks for confirmation naming the process and PID, and ends only processes in the backend's own tree. Linux /proc and cgroup v2 limits are read for containers.

Co-authored-by: dengliu <[email protected]>
2026-11-27 23:34:21 +08:00
Vadim LazukтаInf1mum 66e17df216 feat(dotnet): show discovered solutions and projects as project-view tree nodes (#6224)
The Project view lists the discovered .NET workspace above the project folder: a Solution '<name>' group per solution with a leaf per project, and standalone projects as roots of their own. Each leaf is the real project file, so run/debug, build, selection and Select In work on it, and the same file still shows in its own folder.

The shared workspace scan starts only when the file index holds .sln, .slnx or project files; the check retries once the index settles, so a fresh open still gets the nodes, and a workspace without .NET is never scanned at open. Project view roots gain an optional file leaf for this.

Co-authored-by: Inf1mum <[email protected]>
2026-11-27 23:17:00 +08:00
LU XIANGRUIтаwildcatDownstairs 4ff5739854 feat(notebook): show the running kernel's variables in a Jupyter Variables tool window (#6517)
A Jupyter Variables tool window (bottom, under the stripe's overflow until first opened; also in Find Action) lists the variables of the last active notebook's kernel: name, type and a truncated repr, hiding private names, modules and IPython's own names. It refreshes after a run, a kernel restart and a switch of notebook, and never starts a kernel.

The variables are read with a silent execute_request carrying a user expression (no output, history, execution count or busy/idle status), only while the kernel is idle; a run started meanwhile waits for it, bounded to 10 seconds. A notebook tab restored at startup picks up its session once it opens.

Closes #6508

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 23:02:19 +08:00
Muuтаmuutot a0c03447a0 feat(editor): add Transpose action (#6524)
Transpose (EditorTranspose, no default shortcut) swaps the code points before and after each caret and moves the caret past them; at a line end it swaps the line's last two code points. With several selections it rotates their texts (the rightmost moves to the leftmost) and keeps each replacement selected; mixed carets and selections do nothing. Listed in the IntelliJ and VS Code keymap presets and documented in the editor guide.

Co-authored-by: muutot <[email protected]>
2026-11-27 22:51:50 +08:00
Vladislav Kuzmin c4e0900485 test: keep the stale Replace All buffer outside the project watcher and fix Windows path tests (#6498)
The Replace All fixture wrote its external change inside the watched project, so the watcher sometimes refreshed the clean buffer before the stale-buffer path ran. The stale file now lives just outside the project and is reached through a directory search scope; the test also checks the unsaved replacement text.

Includes the Windows fixes from #6459/#6460: Cobertura keeps rooted (drive-less) paths instead of joining them onto the checkout's drive, and the tsconfig plugin shim test compares the decoded path.

Closes #6494

Co-authored-by: principalwater <[email protected]>
2026-11-27 22:36:22 +08:00
Dimas Avrian Fachriza a42f13edc2 fix(editor): keep color swatches while typing so the gutter doesn't shift (#6519)
Language server and plugin color fields were cleared on every document change, so the color gutter collapsed on each keystroke until the debounced documentColor request answered, shifting the code left and right. Existing colors are now mapped through the change; only a color whose text the edit touches is dropped until the provider answers again.

Closes #6518

Co-authored-by: FForFachriza <[email protected]>
2026-11-27 22:33:39 +08:00
l0ng-ai 18d6041f2f fix(ci): run language smoke when LSP snippet conversion changes (#6523)
The breakpoint condition completion (#6509) imports src/editor/lsp/snippet.ts from the debugger code the frontend smoke loads, so scripts/smoke-paths.test.ts failed on main. The file is now in the workflow's paths and the Changes step's smoke pattern.
2026-11-27 22:31:46 +08:00
l0ng-ai 15c5e921df feat(agents): show links in the composer as chips and reference pasted GitHub file links (#6470)
Bare https URLs and [label](url) links show as chips in the agent composer and in sent messages: issues and pull requests as repo#12 (GitLab repo!3, Linear ENG-42), commits as repo@abc1234, other pages as host and path. A click opens the page; the text sent to the agent is unchanged. A link stays text while the caret is at its end, and a URL ends at CJK text and full-width punctuation.

Pasting a URL over selected text on one line makes [text](url). A pasted GitHub blob or tree link into this repository (matched against the git remotes, refs with / resolved) becomes an @path:lines or @dir/ reference when the file exists; other links paste as the URL.
2026-11-27 22:30:09 +08:00
LU XIANGRUIтаwildcatDownstairs bc64188c38 feat(python): go to definition and completion for pytest fixtures (#6510)
A fixture parameter of a test or fixture now resolves to the fixture that pytest would inject: the nearest definition in the same class or module, then the conftest.py chain up to the root, pytest_plugins modules, pytest11 entry points and the _pytest builtins. Go to Declaration opens it, and completion in a test's parameter list offers the fixtures in scope with their source file. Named fixtures (name=...) and usefixtures("...") strings are covered; the fixture layers are cached by file mtime.

Closes #6490

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 22:12:59 +08:00
LU XIANGRUIтаwildcatDownstairs a3c819e064 feat(debugger): complete breakpoint conditions from the language server (#6509)
The Condition field and the {...} parts of the log message in breakpoint properties offer code completion without a debug session. The expression is spliced on its own line before the breakpoint's line, indented like it, and a new lsp_snapshot_completion command asks the language server on a transient snapshot of the file, so locals in scope, fields and members after . are offered while the open document and its diagnostics stay untouched. The popup and keys are those of Evaluate; the field claims Ctrl+Space so the non-modal popover doesn't also run the editor's completion.

Fixes #6403

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 22:05:41 +08:00
audichuang 1f2e92b433 feat(project-tree): copy a Java class's fully qualified name from Copy Path/Reference… (#6503)
The Project view's Copy Path/Reference… chooser gains a Reference row, backed by a project.copyReference action: com.example.App for App.java and the package name for a folder under a JVM source or test root. The name comes from the path below the source root, so no file is read. The row is left out where there is no valid name: other files, package-info.java / module-info.java, folders that aren't Java identifiers, the source root itself, non-JVM roots, library files and selections that are only partly Java.

Closes #6495

Co-authored-by: audichuang <[email protected]>
2026-11-27 21:58:36 +08:00
LU XIANGRUIтаwildcatDownstairs 8dfca955a5 fix(profiler): harden the pstats reader (#6511)
A pstats file can point many functions at one stats tuple by marshal reference, so a few kilobytes could unfold into millions of caller edges; the reader now refuses a file whose callers tables add up to more edges than it has bytes. The format is decided by content first, so a V8 profile saved as cpu.prof opens as V8 instead of a broken cProfile snapshot. A function recorded under two names of one file is now one method row with its stats and edges added up. Open Snapshot also offers .pstat and All files.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 21:53:52 +08:00
l0ng-ai 91aba61c97 fix(agents): keep the caret in the composer after Quote (#6419)
Choosing Quote on a conversation selection focused the composer, but when the context menu closed it put the conversation's text selection back (a WebKit workaround), after the chosen row had moved focus into the composer, so the caret was lost. The context menu now leaves the selection alone when focus has moved into an editable element.
2026-11-27 20:57:12 +08:00
l0ng-ai 1fb4135b5b fix(ui): keep context menu labels whole when the menu meets the window edge (#6497)
A context menu a few pixels taller than the room below its point was capped and scrolled, and in WebKit the scrollbar that appeared took its width from the popup's content, so labels were cut. A popup opened at a point now moves up to fit the window before it is capped, and a capped popup always shows its scrollbar so the popup widens instead of cutting its labels.
2026-11-27 20:49:21 +08:00
LU XIANGRUIтаwildcatDownstairs 24598e0dae feat(notebook): convert a notebook to a Python script and back (#6491)
Adds Convert to Python File to the Project view context menu of a .ipynb and Convert to Jupyter Notebook to that of a .py file, both also in Find Action for the active editor.

The script uses # %% cell markers; Markdown and raw cells become commented # %% [markdown] / # %% [raw] cells, and IPython-only lines (%magic, !shell) and whole %%cell-magic cells are commented out so the script runs with plain python. The result is written next to the source without overwriting (<name>-1.py, ...) and opened; an open notebook or script is converted as shown, unsaved edits included. Back to a notebook gives nbformat 4.5 with a Python 3 kernelspec, where # %% / #%% lines start cells and a script without markers becomes one code cell. A notebook that is not nbformat 4 reports an error and writes nothing.

Closes #6372

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:42:23 +08:00
Bake Yam 2436ad6fe9 fix(notebook): give a cell the intentions menu a text editor has (#6492)
Alt+Enter in a notebook code cell offered only the server's code actions and the inspection controls: cellLspExtensions never included intentionsExtension, so a language's own intentions and quick fixes (Python's create function / class) were missing in cells. Cells now get the same intention providers as a text editor, looked up by the cell document's language; each cell is its own document, so the edits stay in the cell.

Part of #5846

Co-authored-by: Renjiankang <[email protected]>
2026-11-27 20:41:53 +08:00
LU XIANGRUIтаwildcatDownstairs c2c6931f0e feat(database): open .csv / .tsv files as a table (#6493)
.csv and .tsv files now open with Text / Data tabs under the editor. Data shows the file as a read-only table in the result grid, with header sort, the local column filter and search. The delimiter (comma, semicolon, tab or pipe) is guessed from the first 64 KB (.tsv is always tab), and the header row is guessed with a First row is header override. Quoted fields, line breaks inside quotes and a UTF-8 BOM are handled; ragged rows are padded, unnamed columns numbered and repeated names suffixed. Parsing runs in a Web Worker and the table re-reads the editor text (debounced) only while Data is shown; Text stays mounted so undo history and unsaved edits are kept.

visibleRows also computes each row's sort key once instead of per comparison, which speeds up local sorting of query results too.

Closes #6368

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:38:44 +08:00
Dimas Avrian Fachriza 2e0c8dd527 perf(editor): prune huge completion lists before mapping (#6477)
Tailwind answers every completion request with its full utility list (about 26k items), and each item was mapped to a CodeMirror option and re-filtered on every keystroke, which showed as input lag.

Lists above 2000 items now keep only the items whose filter text contains the typed token as a subsequence, before mapping. That is a superset of what CodeMirror's fuzzy matcher can show for text that grows from the token, so typing forward loses nothing; the pruned list stays valid only while the text still starts with that token, so backspacing asks the server again.

Co-authored-by: FForFachriza <[email protected]>
2026-11-27 20:33:39 +08:00
faysouтаfaysou f4be752dda fix(markdown): keep reading position when toggling Structure (#6483)
Showing or hiding a docked Structure pane changes the Markdown editor's width. CodeMirror could keep an old pixel offset within a wrapped line, and the preview measured its position after some blocks had already reflowed, so both jumped. The source view now anchors the first visible character across a side-dock change and restores it in the resize frame; the preview remembers its line and offset on scroll, pauses following the source while blocks reflow, and restores the position once the width settles. A navigation made while paused is applied on resume. Works in all three Markdown modes.

Co-authored-by: faysou <[email protected]>
2026-11-27 20:32:41 +08:00
LU XIANGRUIтаwildcatDownstairs a52a639b8e fix(coverage): import coverage.py data below fail_under and in monorepo members (#6478)
coverage xml (import) and coverage lcov (Run with Coverage) exit 2 when the data misses a [report] fail_under, which failed the import and lost the run's report; both now get --fail-under=0.

coverage.py now runs in the nearest folder above the data file with a coverage.py configuration (.coveragerc, setup.cfg, tox.ini, pyproject.toml), else the project root, so a monorepo member's [paths] and relative_files apply. Files without source come from the combined data's measured_files() instead of parsing warnings, and Python runs with -W ignore, so disable_warnings and PYTHONWARNINGS=error no longer drop files or fail the import. coverage.py runs with a 10-minute timeout, and coverage.py 4 data or a coverage.py older than 6.3 get clear errors.

Closes #6474

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:30:50 +08:00
LU XIANGRUIтаwildcatDownstairs 1b0bf4d741 fix(python): fix edge cases of import updates on module moves (#6479)
Fixes for the Python import updates on module and package moves:

- Nested attribute chains got overlapping edits and the move failed; each expression now gets one edit, on its longest moved prefix.
- Cancelling ends the request after the import scan and returns cancelled instead of partial edits.
- In monorepos, module names come only from Python roots (detected from a Python project file or marked by the user), a moved folder counts only when it holds .py/.pyi files, and an import is left alone when the importing file's own root has a module of that name.
- Files are read through the documents layer, so a BOM or another encoding no longer shifts the edits.
- Moving a .pyi stub without its .py changes no imports.
- Rewriting import pkg.models keeps pkg bound when the file still uses pkg.helper().
- Statements sharing a line stay valid, and moved names are removed line by line, keeping the remaining names' layout and comments.

Closes #6475

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:29:48 +08:00
LU XIANGRUIтаwildcatDownstairs 13597e40a1 fix(debugger): keep Python's debugpy config and pick Django or Jinja templates by language (#6476)
django-html declared a debugpy [debugger], and find_config takes the first language declaring an adapter, so a user's languages/python.toml debugger override no longer applied. The block is gone; breakpoint placement accepts Django Templates by language instead.

django: true came only from manage.py / -m django / django-admin, so template breakpoints never stopped under uvicorn, gunicorn, daphne or pytest-django, and the templates/*.html rule sent jinja: true for them. At debug start each file with an enabled breakpoint (other than .py) is asked for its language with the editor's detection: a Django Template turns on django, other templates turn on jinja. Disabled breakpoints no longer turn either on, and templates/*.txt and *.xml accept breakpoints.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:26:34 +08:00
LU XIANGRUIтаwildcatDownstairs aa1aa91b0d fix(debugger): keep Python Debug Server loopback hosts on loopback (#6487)
The port check retried every bind error for 5 s; it now retries only AddrInUse (the previous adapter still shutting down) and reports any other bind error at once.

Every loopback form of the host (127.1, LOCALHOST, 0:0:0:0:0:0:0:1, ::ffff:127.0.0.1) is normalised with the URL parser and stays on loopback: localhost and IPv6 loopback listen on 127.0.0.1, since debugpy's adapter before 1.8 listens on IPv4 only, and the connect line and waiting note say 127.0.0.1 then. Another 127.x address listens on itself. Docs explain that an imported VS Code listen.host of 0.0.0.0 becomes localhost and how to reach the IDE from a container.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:25:27 +08:00
LU XIANGRUIтаwildcatDownstairs 032a3b0453 fix(python): correct doctest results, module imports and docstring detection (#6489)
Skipped examples, examples after a first failure under REPORT_ONLY_FIRST_FAILURE, and examples after a FAIL_FAST stop were all reported as passed: the reporter only kept failures and marked every other example passed. It now records each example that ran (and reports skipped ones as skipped), applying REPORT_ONLY_FIRST_FAILURE itself so later examples still reach it.

Modules are imported by their dotted name from the deepest sys.path root that holds them (working directory, PYTHONPATH, source roots), falling back to loading the file when the import fails or resolves to another module. Docstring detection now skips lines inside triple-quoted strings and no longer gives a one-line def the next object's docstring; -v is passed through to the runner.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:24:03 +08:00
LU XIANGRUIтаwildcatDownstairs 07750ad984 fix(python): Create Test keeps imports, indentation and module paths valid (#6488)
Create Test wrote invalid Python in several cases: a new import glued to a last import without a final newline; the first import above a shebang, coding line or module docstring; methods added to a tab- or differently-indented Test class in the editor's indent unit; repeated definitions (@overload, conditional) tested several times; import paths not relative to the innermost source root; and an import of a module no import can name (my-tool.py). Each is fixed: the new import gets its own line below the header, methods use the class's indentation, a name is offered once, the module path is relative to its source root (no import when it has no valid name), and an uneditable test file shows a hint.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:21:22 +08:00
Muuтаmuutot ba38f070d9 feat(analysis): manage a producer's suppressed rules from the problem menus (#6472)
The submenu of a problem's inspection (Alt+Enter on a fix, Problems, Inspection Results) lists the codes the inspection profile in effect turns off for that producer, each checked (unchecking removes the rule), plus Add rule… to suppress a code before it has ever reported (for example Ruff's UP045). Rules are plain profile entries, so the editor, Problems and Inspect Code hide those codes. The rows show only for inspections split by code (language servers, code-split built-ins); the input dialog is provided by the workbench.

Co-authored-by: muutot <[email protected]>
2026-11-27 20:20:12 +08:00
l0ng-ai c77f4db777 fix(usages): show what the server found in its scope before the widened search (#6485)
A project-wide usages search asks the server, then opens the other files that mention the name and asks again. Only Java's library search streamed an early answer, so for Python (pyright) and the other servers the popup waited for the second pass. The first answer is now shown while the other files are searched, for a single answering server (not the CSS server, whose answer is filtered afterwards) and for Java's sources.

Fixes #6441
2026-11-27 20:05:53 +08:00
l0ng-ai d3067c8d3a feat(database): rebuild a PostgreSQL table's comments, owner, grants and triggers in its DDL (#6481)
Go to DDL on a PostgreSQL table gave the table, its constraints and indexes only. It now also gives the table and column comments, the owner, the privileges granted beyond the owner's (none while the ACL was never changed) and the user triggers, in the order a script runs them. Views keep their single statement.

Fixes #6439
2026-11-27 20:01:33 +08:00
l0ng-ai 7bf2702565 fix(kotlin): show the Kotlin bridge build as a background task (#6480)
The Maven build that compiles a project's Kotlin for JDT (on opening the project and after saved Kotlin or POM changes) ran with no sign in the UI, for about a minute on a large project, while Java code using the Kotlin API stayed red. It now shows in the status bar as Compiling Kotlin for Java with Maven's reactor progress, and can be stopped there; the next saved change builds again.

Fixes #6434
2026-11-27 19:56:49 +08:00
Dimas Avrian Fachriza 65c45ffe05 fix(editor): complete hyphenated tokens such as Tailwind classes (#6463)
Typing a hyphenated token such as items-c never offered items-center: the server's replace range covers the whole class, but the client filtered on the last word segment (c), and CodeMirror matches a one-character pattern only at a label's start. Typing - also closed the popup and re-queried. The completion now starts where the servers' single-token replace ranges start when they reach back over hyphens (the most common start wins), and the list stays valid across - while an option still starts with the typed text. Other punctuation, and lists with no option continuing the hyphen, re-query as before. CSS properties (background-c → background-color) benefit too.

Closes #6462

Co-authored-by: FForFachriza <[email protected]>
2026-11-27 19:51:26 +08:00
LU XIANGRUIтаwildcatDownstairs 84b528f0cd feat(profiler): open cProfile snapshots (.pstats / .prof) (#6466)
Open Snapshot… and Open in Profiler accept pstats files written by cProfile / profile (and yappi's pstat export), told apart from a V8 .cpuprofile by content. The marshal'd pstats dict is read in Rust without a Python interpreter. The method list shows exact own time, total time and call counts (total/primitive for recursion); selecting a method lists its callers and callees, exact for cProfile and summed from the call tree for sampled profiles. The flame graph and call tree are rebuilt from the caller/callee totals, sharing each function's time among its callers in proportion, with a notice that they are estimated; recursion is not unfolded, roots are the strongly connected components of the call graph, and the tree is bounded in share and node count. Recorded files resolve against the project root, then the snapshot's folder, each file looked up once.

Closes #6367

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 19:48:03 +08:00
LU XIANGRUIтаwildcatDownstairs 8621764813 feat(python): Create Test generates pytest tests for the chosen functions and methods (#6465)
On a Python module, Create New Test… (and the new Create Test… action) opens a chooser of the module's functions and its classes' methods, preselecting the one at the caret or every method of the class there. OK writes pytest stubs (test_<name> / class Test<Class> with test_<method>, body assert False) into the module's test file, or a new test_<module>.py in the mirrored package under the test root, importing only names the file doesn't import yet. Existing tests are kept, methods go into an existing Test<Class>, and the edit is one undo step. Imports spanning several lines (parenthesized or backslash-continued) are read too, so their names are not imported again and a new import goes after them. Other languages keep the template flow.

Closes #6387

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 19:40:40 +08:00
rolicon 22e1c4b927 fix(run): import JetBrains Dockerfile run configurations (#6469)
JetBrains docker-deploy configurations with a dockerfile deployment were skipped as UnsupportedType. The importer now keeps the Dockerfile path, image tag, container name and server name; the Dockerfile run type completes the import through a new prepareImport hook, resolving the server name to this machine's connection (the default daemon when none is saved and the name is Docker) and generating the run and stop commands. A missing or ambiguous server is left for the user to choose and reported as unmapped; running such a configuration asks for a server instead of using the default daemon. Other deployment types are still skipped.

Co-authored-by: rolicon <[email protected]>
2026-11-27 19:30:15 +08:00
Ernstjan FreriksтаEjaYF e2817656e8 fix(ui): end tree rows at the scrollbar track (#6468)
While a tree's vertical scrollbar thumb is shown, Scrollbar sets data-scrollbar-shown on its scroller and Tree reserves 8px on the right (the 10px track minus the thumb's 2px border), clipping its rows there. Rows wider than the panel no longer show their text, selection or hover background through the translucent thumb. Trees without a vertical scrollbar keep their 6px inset.

Co-authored-by: EjaYF <[email protected]>
2026-11-27 19:26:04 +08:00
LU XIANGRUIтаwildcatDownstairs 306c71290c fix(debugger): address review of the Python Debug Server (#6464)
Follow-up to #6421. A waiting Python Debug Server no longer lends its run configuration to other debug starts: each start's configuration is kept by name and taken by its own started event. Listening again retries the port for up to 5 s while the previous adapter shuts down instead of failing with Address already in use. An IDE host of ::1 listens on ::1 (other IPv6 hosts on ::) and the connect line strips the brackets. A VS Code listen host of 0.0.0.0 imports as localhost.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 19:21:53 +08:00
l0ng-ai 51ccb68b72 fix(diff): open a diff at its first difference (#6471)
A diff opened without a line to show (double-click in the Commit tool window, Show Diff) started at the top of the file. The two-pane and staging-area diffs now open at their first difference unless a line or a remembered caret is given. The all-in-one diff opens at the first difference of the file it was opened for, once, repeating the scroll until the change is drawn since lines below the drawn ones have estimated heights.

Fixes #6427
2026-11-27 19:19:02 +08:00
l0ng-ai 2e965810e9 feat(color-scheme): Java interface, abstract class, enum and type parameter colours (#6467)
The Java colour page gets Interface name, Abstract class name, Enum name and Type parameter under Classes. jdtls's interface, enum and typeParameter tokens, and class tokens with the abstract modifier, carry their own classes, which keep the class name colour until set. INTERFACE_NAME_ATTRIBUTES, ABSTRACT_CLASS_NAME_ATTRIBUTES, ENUM_NAME_ATTRIBUTES and TYPE_PARAMETER_NAME_ATTRIBUTES in an imported .icls land on them, and the default Interface name colours Java's interface until its own key does.

Fixes #6415
2026-11-27 19:09:20 +08:00
Vladislav Kuzmin 31b70cf0ac test(e2e): use the configured shortcuts for editor zoom and aggregate copy (#6457) 2026-11-27 19:00:02 +08:00
Muuтаmuutot d0989e2a4b fix(plugins): keep line-end annotations on their line when Enter splits it (#6454)
A plugin line-end annotation is a side: 1 point widget at the end of its line, and CodeMirror maps such a widget across an insertion at its position, so Enter at the end of an annotated line carried the label into the new line and down with every further Enter. The decorations field now re-places its items on every edit: marks and hover data map with the text, while an after label re-anchors at the end of the line its range's end maps onto. An empty range stays a point before text typed at it, so its label is kept.

Co-authored-by: muutot <[email protected]>
2026-11-27 18:59:15 +08:00
LU XIANGRUIтаwildcatDownstairs d96ed8d154 feat(python): run doctests from the gutter and the context menu (#6451)
Modules, classes and functions whose docstrings have >>> examples get a gutter run icon, and a module with examples and no if __name__ == "__main__": runs its doctests from the project tree and editor context menus ("Doctests in …"). A new Python doctest run configuration takes files or file.py::Class.method targets and doctest's -o options; PyCharm Doctests configurations import as it. Runs go through a stdlib-only reporter built on DocTestFinder / DocTestRunner that reports each example as a test under its object, so gutter icons show results, failures open Expected / Got in the comparison view, and Rerun Failed Tests reruns the failed objects.

Closes #6389

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:56:35 +08:00
l0ng-ai 6b41870368 fix(agents): keep the conversation painted when sending from far up (#6446)
Sending a message while scrolled up jumps the conversation to its end. The rows there had
skipped rendering (content-visibility: auto); WebKit turned them visible but didn't repaint
them, so the view stayed blank until the reply changed the conversation. A row whose
remembered height went stale the same way also kept the end of a streaming reply out of reach.

Rows within a viewport of the view are now tracked with an IntersectionObserver (data-near)
and always render, and a programmatic jump marks the rows around its target before moving.
2026-11-27 18:54:58 +08:00
LU XIANGRUIтаwildcatDownstairs 660becbaa4 feat(coverage): import coverage.py data files (.coverage) (#6450)
Import a Coverage Report now reads coverage.py's .coverage data file; choosing one .coverage.* file of a parallel run imports all of them. The data only records executed lines and arcs, so coverage.py in the project's interpreter combines it into a scratch file (combine --keep, the user's files untouched) and writes Cobertura XML (xml -i) for the existing importer, run in the project directory so [paths] and excluded lines apply. Running the interpreter needs a trusted project; without trust, an interpreter or coverage.py the error says so and points to coverage xml output. Files without source in the project are listed without lines and the notification says to map them with [paths].

Closes #6392

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:50:40 +08:00
LU XIANGRUIтаwildcatDownstairs a0afc478c1 fix(debugger): stop at breakpoints in Jinja2 and Flask templates (#6453)
debugpy reads a breakpoint in a non-.py file as a template breakpoint only when the launch has jinja: true, which was never set. A Python debug launch now gets it when it starts Flask (flask, -m flask) or when a breakpoint is already in a Jinja2 template (.jinja / .jinja2 / .j2, or markup or text in a templates folder). Django launches keep django: true alone, since debugpy reads one or the other. .jinja / .jinja2 / .j2 files now accept breakpoints.

Closes #6371

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:47:37 +08:00
LU XIANGRUIтаwildcatDownstairs 07a88c6fa4 fix(debugger): accept breakpoints in Django templates without the any-file setting (#6452)
Only languages with a debugger accept new breakpoints, and the Django Template language (files in a Django project's templates folders) had none, so breakpoints there needed "Allow placing breakpoints in any file". It now declares debugpy. debugpy also gets django: true for python -m django and django-admin launches, not only manage.py, and django-admin now runs as python -m django instead of a module that doesn't exist.

Closes #6370

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:46:23 +08:00
Bake Yam 46bd6fad3c fix(notebook): refresh cell documents when the backend changes their DocId (#6440)
The backend hands a notebook cell a new DocId when its servers open the notebook again (a restarted language server, a reopened notebook) while the cell ids stay the same. The session refetched cell documents only when the set of code cells changed, so it kept a spent DocId and editor shortcuts in a cell answered "DocId#N is not open". The lookup now runs on every snapshot, ordered by a sequence number, and publishes only when a cell's document or uri moved.

Part of #5846

Co-authored-by: Renjiankang <[email protected]>
2026-11-27 18:44:46 +08:00
薛纪克таxuejike f64dbe65b4 feat(agents): show the command a tool call ran in the session UI (#6429)
A command tool call showed only the agent's own title ("Run command"). The timeline now keeps the command from the call's structured input (rawInput.command / rawInput.cmd, a string or an argv array, <shell> -c <script> unwrapped), and the session UI uses it as the row title, its tooltip and the $ line of the expanded terminal block, falling back to the output's $ line and then the title. Saved sessions without the field still load.

Closes #6428

Co-authored-by: xuejike <[email protected]>
2026-11-27 18:42:02 +08:00
l0ng-ai e2a5a5db81 fix(debugger): flash only the stopped project's window on a breakpoint (#6449)
A breakpoint hit while the app was in the background requested attention for every webview window, so on Windows the taskbar button of another open project flashed too. Only the window of the project whose session stopped asks now; an event without a window still reaches every window. No other place requests attention for all windows.

Fixes #6404
2026-11-27 18:35:01 +08:00
LU XIANGRUIтаwildcatDownstairs 6eb7abff9f feat(debugger): add Python Debug Server configurations (#6421)
Python Debug Server run configuration (Debug only): the IDE's debugpy adapter listens (attach with listen) and the program connects with debugpy.connect. The form shows the line to add; a loopback host listens on 127.0.0.1 only, any other host on all interfaces (with a warning, since debugpy's listen mode has no authentication); local/remote roots map paths and redirectOutput sends the program's output to the console. While waiting, the session is Starting and the console shows the address and the line; Stop cancels the wait. When the connected program ends by itself, the configuration listens again in the same tab, keeping the output. A port in use fails the start up front (debugpy's adapter would otherwise wait forever), and on the first stop the program's debugpy version is compared with the IDE's, with a warning when they differ. VS Code attach configurations with listen import as Python Debug Server.

Closes #6369

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:30:11 +08:00
Waiting-Night b46112fe0b feat(database): organize data sources into folders (#6423)
Project-local data source folders in the Database tree: New › Folder…, rename and delete (members move back to the root), Move to Folder (also for several selected sources, including a new folder) and drag-and-drop onto a folder. Folders live in .openidea/data-source-folders.toml, written atomically and validated (one folder per source, known parents, no cycles), and are reloaded when the file changes on disk; removing data sources drops them from their folders.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-27 18:20:04 +08:00
Waiting-Night 4507dc172d feat(database): support batch actions on selected data sources (#6420)
Several selected data sources in the Database tree share Refresh, Deactivate and Remove: the context menu shows only those, with the number of affected sources. Refresh runs every selected source and reports failures once; Deactivate disconnects only the connected ones; Remove asks once (listing the names), disconnects, saves the project once and keeps the rest of the selection. The toolbar's Deactivate and Properties follow the multi-selection.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-27 18:08:08 +08:00
LU XIANGRUIтаwildcatDownstairs 8442c0c339 feat(typescript): CSS Modules navigation through CSS Modules Kit (#6345)
Go to Declaration, completion, Find Usages and Rename for CSS Module class names between TS/JSX and *.module.css, through the CSS Modules Kit tsserver plugin on vtsls. The plugin is an IDE-managed tool pinned to @css-modules-kit/[email protected]; a project turns it on with "cmkOptions": { "enabled": true } in tsconfig.json (also inherited through a local extends), which the editor offers to add, installing the plugin if needed. CSS files reach vtsls only once the plugin is installed; references from a selector drop the CSS server's own rule, and rename takes vtsls' edit so the selector keeps its dot.

CSS Modules Kit loads before the Vue tsserver plugin outside a Vue project: both are Volar plugins sharing one @volar/typescript, which decorates a project once, so with the Vue language server installed the Vue plugin had claimed every vtsls and CSS Modules Kit did nothing.

Closes #6071

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:00:08 +08:00
l0ng-ai 8ffe3bd230 fix(i18n): translate the Run tool window's agent configuration action (#6436)
The hidden run.mcpStart action added in #6431 had no Chinese title and description, which the locale catalog tests require.
2026-11-27 17:41:48 +08:00
l0ng-ai 1babff55fc feat(mcp): run execute_run_configuration's runs in the Run tool window (#6431)
A run configuration started through execute_run_configuration ran out of sight, with no Run tool window tab, console or Stop. The tool now asks the project window to start the prepared configuration (before launch tasks already done), tagged with mcp.configRun; run_start recognises the tag on the first start, tees the output into the call's output file and reports the run it started, so exitCode, runId, stop_run and fullOutputPath keep working. A project loaded for MCP alone (no window, brave mode) still runs it directly.

Fixes #6330
2026-11-27 17:30:39 +08:00
l0ng-ai 2ad95150eb fix(refactoring): undo an extract refactoring with its rename and reformatting in one step (#6424)
The history group around a server refactoring kept every transaction out of the undo history, including the workspace refactoring's history marker, so Cmd+Z reverted only the current file's text locally and the notification's Undo failed with "Undo newer editor changes".

The marker now stays in the history. Local edits after the server's within the group (reformatting, the in-place rename) are recorded as the refactoring's follow-up edits: undoing the refactoring reverts them before the backend restores the files, redoing applies them again, and a refused restore puts them back. The notification's Undo first finishes an open in-place rename. Quick fixes group the server's edit with its reformatting the same way, so their reformatting no longer sits above the marker as a separate step.

Fixes #6327
2026-11-27 17:19:13 +08:00
Waiting-Night fe3e647abb feat(database): list query consoles under a Database Consoles root (#6408)
Query consoles stay in <dataDir>/consoles/db; the database feature registers that folder as a Database Consoles root in the Project view's Scratches and Consoles scope, re-registered when a remote session starts or ends. Console folders show the data source's name and icon ("Orders", "Orders: sales") through new display-only label/icon file decorations, which also order siblings when sorting by name. Consoles announce their creation so the tree refreshes, deleted console files close their editors, and a console's data source is recovered from its path when the binding is missing.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-27 17:06:51 +08:00
Waiting-Night 62cc6768fe feat(search): show data source names for recent query consoles (#6411)
Recent Files listed every query console as console.sql, so consoles of different data sources looked the same. Rows for files without an open editor now use the file decoration's tab title and icon, so a console shows as console [Orders] with its data source icon; match highlighting is dropped when the shown title differs from the file name.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-27 16:49:38 +08:00
Waiting-Night 2e93422270 feat(database): show table comments in the database tree (#6416)
Tables and views in the Database tree now show their comment in grey after the name, with the full comment as the row tooltip. Built-in drivers read it in the same catalog query that lists relations (PostgreSQL, MySQL, Oracle, ClickHouse, Snowflake, SQL Server extended properties) and JDBC sources from REMARKS. The new Show Table Comments view option is on by default and toggles from the Database window options; TableInfo.comment is optional on the wire.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-27 16:48:31 +08:00
audichuang 3a1353cc0e feat(vcs): show a file's diff from the Rollback, Shelve and Create Patch file lists (#6417)
In the Rollback Changes dialog, double-click and Enter only toggled a file's checkbox and Show Diff did nothing. The file checklist shared by Rollback, Shelve and Create Patch now opens the file's diff in a front dialog on double-click, Enter and Show Diff, with the listed files as the next/previous chain; Space toggles the selected rows and clicking a box still toggles it. Rollback Unstaged Changes shows the index against the working copy. Closes #5295.

Co-authored-by: audichuang <[email protected]>
2026-11-27 16:44:28 +08:00
audichuang c5eab0a4a3 fix(editor): show color swatches for Java new Color(0x...) literals (#6413)
The hex rule required a leading #, so java.awt.Color int literals never matched. In Java files, a 0x literal that is the whole argument of new Color(...) or new ColorUIResource(...) (unqualified or qualified as java.awt / javax.swing.plaf) is now a color, read as Color(int) reads it (the low 24 bits); picking a color writes it back as 0x hex in the literal's case. Other overloads, suffixed literals, other Color classes and Kotlin stay without a swatch. Closes #5529 together with #6412.

Co-authored-by: audichuang <[email protected]>
2026-11-27 16:42:28 +08:00
audichuang 581c8cf025 fix(editor): show color swatches for HTML style attributes and embedded scripts (#6412)
Named colors only counted in style sheet languages, and in markup only matches inside style nodes were kept, so embedded script code was dropped. Named colors now count in markup (still limited to <style> and style attributes by the syntax tree), and a match inside a Script node is kept when a standalone script file would accept it: quoted hex and color functions, never names. The property-colon check now looks only after the last colon, so long markup lines no longer cost quadratic time. Refs #5529.

Co-authored-by: audichuang <[email protected]>
2026-11-27 16:41:56 +08:00
l0ng-ai 807c447792 feat(database): Revert Selected and Copy Aggregation Result in the data grid (#6418)
Revert Selected drops the pending edits, deletes and added rows of the selected rows only, from the row menu of the table editor and editable results; it takes Cmd+Alt+Z / Ctrl+Alt+Z while the selection has changes, and Revert keeps the shortcut otherwise. Copy Aggregation Result copies one aggregate of the selected cells as the Aggregates panel shows it: Cmd+Shift+C / Ctrl+Shift+C copies the Sum of numbers or the Count otherwise, and the grid context menu lists every aggregate the selection has. Fixes #6308.
2026-11-27 16:40:46 +08:00
l0ng-ai 217693a56f test: make three Rust tests pass on Windows (#6386)
Three tests failed on the Windows Rust job after Clippy: the tsc solution test built expected paths with mixed separators, the gutter plugin test compared a path argument as a string although the plugin sees /-separated Windows paths, and the run configuration completion fixture approved /bin/echo, which is not executable on Windows. Expectations use chained joins, the gutter test compares paths, and the fixture approves the test binary itself.
2026-11-27 16:21:12 +08:00
Deng Liuтаdengliu 557295b1df feat(agents): surface OAuth device-code banner in Sign In dialog (#6399)
The agent Sign In dialog parses OAuth device-authorization URLs and one-time codes from the sign-in PTY output and shows them above the terminal with Copy and Copy Code & Open Browser, using the desktop clipboard and browser. On openidea-server, sign-in PTYs are marked as a remote session (REMOTE_CONTAINERS=1 when no SSH or Codespaces marker exists, GH_BROWSER=true for gh without a browser override), so CLIs pick device-code sign-in instead of a remote-only loopback callback.

Co-authored-by: dengliu <[email protected]>
2026-11-27 16:20:24 +08:00
Deng Liuтаdengliu 7c674e70e5 fix(agents): pick Linux Copilot archive from host dynamic linker (#6398)
openidea-server on Linux is a static musl binary, so choosing the Copilot archive with cfg!(target_env = "musl") installed the linuxmusl build on glibc hosts, where execve fails with ENOENT. The archive variant now comes from the host's runtime dynamic linker: linuxmusl only when ld-musl is present and glibc's loader is absent or symlinked to musl.

Co-authored-by: dengliu <[email protected]>
2026-11-27 16:17:35 +08:00
Deng Liuтаdengliu 1602a5d010 fix(services): route Docker Services to the remote host daemon (#6379)
Docker commands moved from the desktop crate into the ide-host project_host domain, so a remote window reaches the Docker daemon on the remote host through openidea-server instead of the local one. The SSH tunnel reuses the existing resolve logic, docker_executable only caches a found path, and the Services store drops event streams, timers and in-flight requests when the host changes.

Co-authored-by: dengliu <[email protected]>
2026-11-27 16:16:20 +08:00
wangfeiтаhapput a6d135d66f feat(agents): add separate chat and code font settings (#6395)
Settings > Agents > Chat gets Font and Code Font groups like Terminal's: chat text and code each take a family, a fallback and a size. Defaults follow the interface font and the built-in code font, so nothing changes until a choice is made. Chat zoom steps on top of the chosen size, and a chosen code size also applies to fenced code blocks while inline code stays with the chat text.

Co-authored-by: happut <[email protected]>
2026-11-27 16:07:51 +08:00
LU XIANGRUIтаwildcatDownstairs 924bf6d3b9 feat(coverage): import Cobertura XML reports (#6390)
Import a Coverage Report now reads Cobertura XML (coverage.py's coverage xml and many other tools): line hits, partial branches from condition-coverage, relative file names resolved against <sources>, foreign paths mapped by suffix as for the other formats, and <methods> lines not counted twice. The import notification says how many files of a report are not in the project. Missing directories are now looked up once, which makes reports with CI paths under macOS's autofs /home import in under a second instead of tens of seconds.

Closes #6359

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 16:03:41 +08:00
l0ng-ai 318c227b0c fix(database): show column comments in the SQL table and column hover (#6402)
The completion metadata the SQL console hover reads carried no column comments, though Modify Table and the Database view already read them. completion_columns now returns the comment on PostgreSQL, MySQL, Oracle, ClickHouse and Snowflake (NULL on SQL Server and SQLite), Snowflake's SHOW COLUMNS path and the JDBC bridge's schemaColumns (REMARKS, jar rebuilt) carry it too, and the hover shows a comment column in the table card and the comment under a single column.

Fixes #6374
2026-11-27 16:01:45 +08:00
l0ng-ai 2ce7621abb fix(terminal): write shell integration scripts atomically into a content-keyed folder (#6400)
The shell integration scripts went to a temp folder named by version only and were rewritten in place, so a shell starting while another process rewrote them could source a truncated file, and two builds of the same version with different scripts (a dev build next to a release, two checkouts' tests on one runner) overwrote each other; zsh_restores_zdotdir_and_histfile_for_login_shells failed on macOS CI that way. The folder name now carries a hash of the scripts, and each file is written to a unique temporary name and renamed into place.
2026-11-27 15:54:12 +08:00
2461 змінених файлів з 234403 додано та 14091 видалено

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
+20
Переглянути файл
@@ -0,0 +1,20 @@
# Nextest runs tests in separate processes. These three tests write the same Windows clipboard.
[test-groups.windows-clipboard]
max-threads = 1
[[profile.default.overrides]]
filter = '''
package(=ide-clipboard) & (
test(=tests::text_reads_on_one_thread_do_not_corrupt_the_heap)
| test(=tests::text_reads_taking_turns_do_not_corrupt_the_heap)
| test(=tests::concurrent_text_reads_do_not_corrupt_the_heap)
)
'''
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

+9
Переглянути файл
@@ -0,0 +1,9 @@
# Keeps the commit SHAs the workflows pin their actions to current (the trailing comment names
# the release each SHA comes from).
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule: { interval: weekly }
groups:
actions: { patterns: ["*"] }
+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
+1 -1
Переглянути файл
@@ -12,7 +12,7 @@ jobs:
cancel:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v8
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
script: |
// A merged or closed PR's remaining CI only holds runners other PRs wait for.
+59 -35
Переглянути файл
@@ -106,7 +106,8 @@ jobs:
if: needs.changes.outputs.rust == 'true'
permissions:
contents: read
timeout-minutes: 60
# A Windows build that misses the Rust cache spends ~50 minutes compiling before the tests run.
timeout-minutes: ${{ matrix.os == 'windows-latest' && 75 || 60 }}
strategy:
fail-fast: false
matrix:
@@ -115,22 +116,24 @@ jobs:
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { components: "clippy, rustfmt" }
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
# (only main saves it because saving takes minutes on Windows; PRs restore main's).
- uses: Swatinem/rust-cache@v2
# A failing test run on main still saves it, so the next PR doesn't compile from scratch.
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: runner.environment != 'self-hosted'
with:
save-if: ${{ github.ref == 'refs/heads/main' }}
cache-on-failure: true
# The persistent target dir makes incremental builds pay off; cap its size so it can't fill the disk.
- name: Persistent Cargo target dir
if: runner.environment == 'self-hosted'
@@ -142,12 +145,23 @@ jobs:
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
rm -rf "$CARGO_TARGET_DIR"
fi
- uses: taiki-e/install-action@nextest
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
with: { tool: nextest }
- 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
@@ -159,10 +173,10 @@ jobs:
- name: Restore Maven artifacts for Java build tests
id: jbuild-maven-cache
if: runner.environment == 'github-hosted'
uses: actions/cache/restore@v5
uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: jbuild-maven-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
key: jbuild-maven-v2-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
- name: Prepare Maven artifacts for Java build tests
id: jbuild-maven
if: runner.environment == 'github-hosted'
@@ -179,10 +193,13 @@ jobs:
if [[ "$CACHE_HIT" == true ]]; then
exit 0
fi
# The IDE also reads the compiler plugin descriptor when it builds the Maven model.
# The Java tests read the compiler descriptor and run Maven launch and rebuild.
for delay in 0 10 30; do
sleep "$delay"
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml resources:resources compiler:compile; then
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml \
clean resources:resources compiler:compile \
org.apache.maven.plugins:maven-dependency-plugin:3.8.1:get \
-Dartifact=org.slf4j:slf4j-api:1.7.36; then
echo "prepared=true" >> "$GITHUB_OUTPUT"
exit 0
fi
@@ -190,7 +207,7 @@ jobs:
exit 1
- name: Save Maven artifacts for Java build tests
if: steps.jbuild-maven.outputs.prepared == 'true'
uses: actions/cache/save@v5
uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
@@ -235,10 +252,10 @@ jobs:
timeout-minutes: 40
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: x86_64-unknown-linux-musl }
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: runner.environment != 'self-hosted'
with: { key: server-musl }
- name: Persistent Cargo target dir
@@ -264,13 +281,13 @@ jobs:
timeout-minutes: 30
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: wasm32-wasip2, components: "clippy, rustfmt" }
- if: runner.environment != 'self-hosted'
shell: bash
run: echo "CARGO_TARGET_DIR=$GITHUB_WORKSPACE/target-plugins" >> "$GITHUB_ENV"
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: runner.environment != 'self-hosted'
with:
key: plugins
@@ -300,9 +317,9 @@ jobs:
cargo test --locked --manifest-path "$dir/Cargo.toml"
echo "::endgroup::"
done
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with: { node-version: 22, package-manager-cache: false }
# Plugin web pages (`web-src/`, their own pnpm projects): typecheck and test.
- name: Web pages typecheck and test
@@ -329,9 +346,10 @@ jobs:
timeout-minutes: 15
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: taiki-e/install-action@cargo-deny
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
with: { tool: cargo-deny }
- run: cargo deny check
frontend:
@@ -341,17 +359,23 @@ jobs:
timeout-minutes: 30
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
# scripts/smoke-paths.test.ts runs `cargo metadata`, which is not preinstalled in the runner container.
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
if: runner.environment == 'self-hosted'
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
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
@@ -368,10 +392,10 @@ jobs:
timeout-minutes: 15
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -390,10 +414,10 @@ jobs:
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -401,7 +425,7 @@ jobs:
- run: pnpm install --frozen-lockfile
- run: pnpm exec playwright install --with-deps chromium
- run: pnpm e2e --shard=${{ matrix.shard }}/4
- uses: actions/upload-artifact@v6
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
if: failure()
with:
name: playwright-report-${{ matrix.shard }}
+3 -2
Переглянути файл
@@ -21,6 +21,7 @@ concurrency:
jobs:
mirror:
environment: release
runs-on: ubuntu-latest
timeout-minutes: 120
env:
@@ -35,10 +36,10 @@ jobs:
echo "::notice::CNB_TOKEN unset: not mirroring $TAG"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.token.outputs.skip != 'true'
with: { sparse-checkout: scripts }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.token.outputs.skip != 'true'
with: { node-version: 22 }
- name: Download release
+4 -3
Переглянути файл
@@ -23,6 +23,7 @@ concurrency:
jobs:
cask:
environment: release
runs-on: ubuntu-latest
timeout-minutes: 30
env:
@@ -41,16 +42,16 @@ jobs:
echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.check.outputs.skip != 'true'
with: { sparse-checkout: scripts }
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.check.outputs.skip != 'true'
with:
repository: ${{ env.TAP }}
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
path: tap
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.check.outputs.skip != 'true'
with: { node-version: 22 }
- name: Download DMGs
+25 -16
Переглянути файл
@@ -30,15 +30,20 @@ on:
- "src/ui/**"
- "src/editor/api.ts"
- "src/editor/navigationProviders.ts"
- "src/editor/refactorProviders.ts"
- "src/editor/relatedProviders.ts"
- "src/editor/core/cm/cornerInset.ts"
- "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"
- "src/editor/lsp/hint.ts"
- "src/editor/lsp/lsp.ts"
- "src/editor/lsp/positions.ts"
- "src/editor/lsp/snippet.ts"
- "src/bindings.ts"
- "src/styles/tokens.css"
- "src/test/setup.ts"
@@ -104,9 +109,9 @@ jobs:
# SDKs, build tools, the project model, Find Usages candidates, debug stream traces):
# cargo metadata, ide-host's direct deps ide-search/ide-streams and the deps of
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
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|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|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
@@ -152,9 +157,9 @@ jobs:
# stripping local-variable debuginfo from fixtures debugged in the smoke job (CodeLLDB).
CARGO_PROFILE_DEV_DEBUG: line-tables-only
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: runner.environment != 'self-hosted'
with:
shared-key: language-smoke
@@ -181,7 +186,7 @@ jobs:
test -x smoke-bin/language_smoke && test -x smoke-bin/project_smoke
# A tar keeps the executable bits, which artifacts drop.
tar -cf smoke-bin.tar smoke-bin
- uses: actions/upload-artifact@v6
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
smoke:
@@ -200,20 +205,20 @@ jobs:
env:
CARGO_MANIFEST_DIR: ${{ github.workspace }}/crates/ide-host
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
# Tool versions, shared with the evals (pnpm eval).
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { components: "rust-analyzer, rustfmt" }
- uses: actions/download-artifact@v6
- uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0
with: { name: smoke-bin }
- run: |
tar -xf smoke-bin.tar && rm smoke-bin.tar
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -239,19 +244,19 @@ jobs:
fi
- if: matrix.language == 'python'
uses: actions/setup-python@v5
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
with: { python-version: "3.12" }
- if: matrix.language == 'python'
run: pip install "basedpyright==$BASEDPYRIGHT" "ruff==$RUFF"
- if: matrix.language == 'go'
uses: actions/setup-go@v5
uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
with: { go-version: "1.27", cache: false }
- if: matrix.language == 'go'
run: go install "golang.org/x/tools/gopls@$GOPLS"
- if: matrix.language == 'java' || matrix.language == 'kotlin'
uses: actions/setup-java@v4
uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
- if: matrix.language == 'java'
run: |
@@ -263,7 +268,7 @@ jobs:
# The Kotlin fixture has no Gradle wrapper: the server imports it with the Gradle on PATH.
- if: matrix.language == 'kotlin'
uses: gradle/actions/setup-gradle@v4
uses: gradle/actions/setup-gradle@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
with: { gradle-version: "${{ env.GRADLE }}" }
- if: matrix.language == 'kotlin'
run: |
@@ -275,7 +280,7 @@ jobs:
# Xdebug for the debug smoke; Composer installs the fixture's Pest for the run smoke.
- if: matrix.language == 'php'
uses: shivammathur/setup-php@v2
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
with: { php-version: "8.5", coverage: xdebug, tools: composer }
- if: matrix.language == 'php'
run: npm install --global "intelephense@$INTELEPHENSE"
@@ -283,6 +288,10 @@ jobs:
# The binaries from the build job, run from the crate directory as `cargo test` does.
- working-directory: crates/ide-host
run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }}
# Problems › TypeScript Project Errors runs the project's own tsc: the global install stands in.
- if: matrix.language == 'typescript'
working-directory: crates/ide-host
run: ../../smoke-bin/language_smoke --ignored --exact typescript_project_errors typescript_import_style
- if: matrix.language == 'java'
working-directory: crates/ide-host
run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
+104
Переглянути файл
@@ -0,0 +1,104 @@
name: Nightly
# Builds main every night, when it has moved since the last nightly, into a prerelease
# v<next patch>-nightly.<date> (scripts/nightly-prepare.ts: the tag points at a commit on top of
# main that only sets the version). Nightly apps update from the rolling `nightly` release, which
# holds the newest nightly's latest.json; stable apps read releases/latest, which is never a
# prerelease, so they never see a nightly. The newest 14 nightlies are kept.
on:
schedule:
- cron: "0 18 * * *" # 02:00 Beijing
workflow_dispatch:
inputs:
force:
description: "Build even when main has not changed since the last nightly"
type: boolean
default: false
permissions:
contents: read
concurrency:
group: nightly
jobs:
prepare:
if: github.repository == 'l0ng-ai/openidea'
permissions:
contents: write
runs-on: ubuntu-latest
outputs:
tag: ${{ steps.tag.outputs.tag }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with: { ref: main, fetch-depth: 0 }
- id: changed
env:
FORCE: ${{ inputs.force == true }}
run: |
last="$(git tag --list 'v*-nightly.*' --sort=-creatordate | head -1)"
if [ "$FORCE" != true ] && [ -n "$last" ] && [ "$(git rev-parse "$last^")" = "$(git rev-parse HEAD)" ]; then
echo "::notice::main has not changed since $last"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.changed.outputs.skip != 'true'
with: { node-version: 22 }
- name: Version commit and tag
id: tag
if: steps.changed.outputs.skip != 'true'
env:
BUILD: ${{ github.run_number }}
run: |
version="$(node scripts/nightly-prepare.ts --date "$(date -u +%Y%m%d)" --build "$BUILD" | tail -1)"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add -A
git commit -q -m "chore: v$version"
git tag "v$version"
# Pushed with GITHUB_TOKEN, the tag does not start release.yml: the job below calls it.
git push origin "refs/tags/v$version"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
release:
needs: prepare
if: needs.prepare.outputs.tag != ''
permissions:
contents: write
uses: ./.github/workflows/release.yml
with:
tag: ${{ needs.prepare.outputs.tag }}
nightly: true
secrets: inherit
# Points the nightly channel at the new nightly and drops the old ones.
channel:
needs: [prepare, release]
permissions:
contents: write
runs-on: ubuntu-latest
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
TAG: ${{ needs.prepare.outputs.tag }}
steps:
- name: Nightly manifest
run: |
if ! gh release download "$TAG" -p latest.json -D "$RUNNER_TEMP/manifest"; then
echo "::warning::$TAG has no latest.json (unsigned build): the nightly channel stays where it was"
exit 0
fi
notes="The update channel of the [nightly builds](https://github.com/$GH_REPO/releases?q=nightly&expanded=true): its latest.json is the newest nightly's, [$TAG](https://github.com/$GH_REPO/releases/tag/$TAG)."
if gh release view nightly >/dev/null 2>&1; then
gh release edit nightly --notes "$notes"
else
gh release create nightly --prerelease --target main --title "OpenIDEA Nightly" --notes "$notes"
fi
gh release upload nightly "$RUNNER_TEMP/manifest/latest.json" --clobber
- name: Drop old nightlies
run: |
gh release list --limit 200 --json tagName,createdAt \
--jq '[.[] | select(.tagName | test("^v.*-nightly\\."))] | sort_by(.createdAt) | reverse | .[14:][] | .tagName' |
while read -r old; do
gh release delete "$old" --cleanup-tag --yes
done
+21 -3
Переглянути файл
@@ -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
@@ -18,7 +18,7 @@ jobs:
if: github.event.pull_request.user.type != 'Bot' && !github.event.pull_request.draft
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v8
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
script: |
const pr = context.payload.pull_request;
@@ -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);
+88 -26
Переглянути файл
@@ -19,6 +19,7 @@ env:
jobs:
plugin-keys:
permissions: {}
environment: release
runs-on: ubuntu-latest
outputs:
keys: ${{ steps.keys.outputs.keys }}
@@ -43,6 +44,7 @@ jobs:
contents: write
needs: plugin-keys
name: Build (${{ matrix.name }})
environment: release
env:
OPENIDEA_OFFICIAL_PLUGIN_KEYS: ${{ needs.plugin-keys.outputs.keys }}
strategy:
@@ -69,15 +71,15 @@ jobs:
target: x86_64-pc-windows-msvc
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with: { ref: "${{ env.TAG }}" }
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with: { node-version: 22, cache: pnpm }
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: "${{ matrix.target }}" }
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with: { key: "${{ matrix.target }}", cache-on-failure: true }
- name: Linux deps
if: runner.os == 'Linux'
@@ -85,40 +87,57 @@ jobs:
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf
- run: pnpm install --frozen-lockfile
# Signing is optional: only secrets that are set get exported, so forks and
# unconfigured repos produce unsigned builds instead of failing.
- name: Signing env
# Signing is optional: forks and unconfigured repos produce unsigned builds instead of
# failing. The secrets go only into the steps that sign (never $GITHUB_ENV), so the other
# steps and the actions' post steps never see them. Tauri treats a set-but-empty key as a
# key, so the unsigned build is a separate step without the secrets.
- name: Signing configured
id: signing
shell: bash
env:
UPDATER_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
APPLE_ID: ${{ runner.os == 'macOS' && secrets.APPLE_ID || '' }}
run: |
echo "updater=$([ -n "$UPDATER_KEY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
echo "apple=$([ -n "$APPLE_ID" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
- name: Build (signed)
if: steps.signing.outputs.updater == 'true'
uses: tauri-apps/tauri-action@84b9d35b5fc46c1e45415bdb6144030364f7ebc5 # v0.6.2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
APPLE_CERTIFICATE: ${{ runner.os == 'macOS' && secrets.APPLE_CERTIFICATE || '' }}
APPLE_CERTIFICATE_PASSWORD: ${{ runner.os == 'macOS' && secrets.APPLE_CERTIFICATE_PASSWORD || '' }}
APPLE_SIGNING_IDENTITY: ${{ runner.os == 'macOS' && secrets.APPLE_SIGNING_IDENTITY || '' }}
APPLE_ID: ${{ runner.os == 'macOS' && secrets.APPLE_ID || '' }}
APPLE_PASSWORD: ${{ runner.os == 'macOS' && secrets.APPLE_PASSWORD || '' }}
APPLE_TEAM_ID: ${{ runner.os == 'macOS' && secrets.APPLE_TEAM_ID || '' }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: |
for v in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD APPLE_SIGNING_IDENTITY APPLE_ID \
APPLE_PASSWORD APPLE_TEAM_ID TAURI_SIGNING_PRIVATE_KEY TAURI_SIGNING_PRIVATE_KEY_PASSWORD; do
[ -n "${!v}" ] && { echo "$v<<__EOF__"; echo "${!v}"; echo "__EOF__"; } >> "$GITHUB_ENV"
done
true
- uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
releaseId: ${{ inputs.release_id }}
tagName: ${{ env.TAG }}
args: --target ${{ matrix.target }}
# The parallel builds would race on one latest.json; `updater-manifest` writes it once.
uploadUpdaterJson: false
- name: Build (unsigned)
if: steps.signing.outputs.updater != 'true'
uses: tauri-apps/tauri-action@84b9d35b5fc46c1e45415bdb6144030364f7ebc5 # v0.6.2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
releaseId: ${{ inputs.release_id }}
tagName: ${{ env.TAG }}
args: --target ${{ matrix.target }}
uploadUpdaterJson: false
# tauri-action notarizes the .app but not the DMG around it; notarize and
# staple the DMG too, then replace the uploaded asset.
- name: Notarize DMG
if: runner.os == 'macOS' && env.APPLE_ID != ''
if: runner.os == 'macOS' && steps.signing.outputs.apple == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: |
for dmg in target/${{ matrix.target }}/release/bundle/dmg/*.dmg; do
xcrun notarytool submit "$dmg" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \
@@ -137,6 +156,8 @@ jobs:
shell: pwsh
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: |
$target = "${{ matrix.target }}"
$arch = if ($target -like "x86_64*") { "x64" } else { "arm64" }
@@ -176,11 +197,11 @@ jobs:
- { runner: macos-latest, target: x86_64-apple-darwin, os: macos, arch: x86_64 }
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with: { ref: "${{ env.TAG }}" }
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: "${{ matrix.target }}" }
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with: { key: "server-${{ matrix.target }}", cache-on-failure: true }
- name: musl toolchain
if: runner.os == 'Linux'
@@ -201,6 +222,45 @@ jobs:
if command -v sha256sum >/dev/null; then sha256sum "$ASSET"; else shasum -a 256 "$ASSET"; fi > "$ASSET.sha256"
gh release upload "$TAG" "$ASSET" "$ASSET.sha256" --clobber
# Signs every server archive with the updater key (`<asset>.sig`), so the app verifies a
# server from the CNB mirror as it does from GitHub (ide-tools `server::fetch`). Only this job
# gets the key; without it the archives keep only their .sha256.
server-signatures:
permissions:
contents: write
needs: server
environment: release
runs-on: ubuntu-latest
steps:
- name: Signing configured
id: signing
env:
UPDATER_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
run: echo "updater=$([ -n "$UPDATER_KEY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.signing.outputs.updater == 'true'
with: { ref: "${{ env.TAG }}" }
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
if: steps.signing.outputs.updater == 'true'
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.signing.outputs.updater == 'true'
with: { node-version: 22, cache: pnpm }
- if: steps.signing.outputs.updater == 'true'
run: pnpm install --frozen-lockfile
- name: Sign server archives
if: steps.signing.outputs.updater == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: |
gh release download "$TAG" -p 'openidea-server-*.gz' -D "$RUNNER_TEMP/server"
for asset in "$RUNNER_TEMP"/server/*.gz; do
pnpm exec tauri signer sign "$asset"
done
gh release upload "$TAG" "$RUNNER_TEMP"/server/*.gz.sig --clobber
# The updater manifest (latest.json), built once from the signed bundles every build uploaded.
# Fails when a platform is missing, so a release never ships a manifest without it.
updater-manifest:
@@ -209,7 +269,7 @@ jobs:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v8
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
RELEASE_ID: ${{ inputs.release_id }}
with:
@@ -224,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`]],
@@ -231,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$/),
+38 -16
Переглянути файл
@@ -7,19 +7,27 @@ on:
tag:
description: "Tag to release (e.g. v0.1.0); must already exist"
required: true
# nightly.yml: a nightly is a prerelease whose notes start at the previous nightly, without the
# official plugins, the CNB mirror or the Homebrew cask.
workflow_call:
inputs:
tag: { type: string, required: true }
nightly: { type: boolean, default: false }
permissions:
contents: read
concurrency:
group: release-${{ github.event.inputs.tag || github.ref_name }}
group: release-${{ inputs.tag || github.ref_name }}
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
TAG: ${{ github.event.inputs.tag || github.ref_name }}
TAG: ${{ inputs.tag || github.ref_name }}
COMMUNITY_PLUGINS_INDEX: https://github.com/l0ng-ai/openidea-plugins/releases/download/index/index.json
# The jobs that read a signing key or token, here and in the workflows called below, run in
# the `release` environment, which holds those secrets.
jobs:
# Creates (or reuses) one draft release that every platform build uploads into.
create-release:
@@ -29,7 +37,7 @@ jobs:
outputs:
release_id: ${{ steps.release.outputs.id }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with: { ref: "${{ env.TAG }}" }
- name: Tag matches app version
run: |
@@ -49,7 +57,9 @@ jobs:
exit 1
fi
- id: release
uses: actions/github-script@v8
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
NIGHTLY: ${{ inputs.nightly == true }}
with:
script: |
const tag = process.env.TAG;
@@ -61,8 +71,13 @@ jobs:
core.setOutput("id", existing.id);
return;
}
// Prereleases are skipped: the notes span stable release to stable release.
const previous = releases.find((r) => !r.draft && !r.prerelease);
// Prereleases are skipped: the notes span stable release to stable release. A
// nightly's span from the newest published release, nightly or stable (not the
// rolling `nightly` release, which only holds the channel's manifest).
const nightly = process.env.NIGHTLY === "true";
const previous = releases.find(
(r) => !r.draft && r.tag_name !== "nightly" && (nightly || !r.prerelease),
);
const { data: notes } = await github.rest.repos.generateReleaseNotes({
owner, repo, tag_name: tag, previous_tag_name: previous?.tag_name,
});
@@ -78,7 +93,7 @@ jobs:
needs: create-release
uses: ./.github/workflows/release-build.yml
with:
tag: ${{ github.event.inputs.tag || github.ref_name }}
tag: ${{ inputs.tag || github.ref_name }}
release_id: ${{ needs.create-release.outputs.release_id }}
secrets: inherit
@@ -96,29 +111,34 @@ jobs:
contents: write
needs: create-release
name: Official plugins
environment: release
runs-on: ubuntu-22.04
env:
SIGNING_KEY: ${{ secrets.PLUGIN_SIGNING_KEY }}
NIGHTLY: ${{ inputs.nightly == true }}
steps:
- id: key
run: |
if [ -z "$SIGNING_KEY" ]; then
if [ "$NIGHTLY" = true ]; then
echo "a nightly does not publish the official plugins"
echo "skip=true" >> "$GITHUB_OUTPUT"
elif [ -z "$SIGNING_KEY" ]; then
echo "::warning::PLUGIN_SIGNING_KEY is not set: the official plugins are not published"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.key.outputs.skip != 'true'
with: { ref: "${{ env.TAG }}" }
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
if: steps.key.outputs.skip != 'true'
with: { targets: wasm32-wasip2 }
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: steps.key.outputs.skip != 'true'
with: { key: release-plugins }
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
if: steps.key.outputs.skip != 'true'
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.key.outputs.skip != 'true'
with: { node-version: 22 }
# Builds the web pages; fails when a checked-in component isn't built from these sources.
@@ -163,7 +183,7 @@ jobs:
needs: [create-release, binaries, plugins]
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v8
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
with:
@@ -175,13 +195,15 @@ jobs:
# The China mirror the updater's CNB source reads; a failure here leaves the GitHub release as is.
cnb-mirror:
needs: publish
if: ${{ !inputs.nightly }}
uses: ./.github/workflows/cnb-mirror.yml
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
with: { tag: "${{ inputs.tag || github.ref_name }}" }
secrets: inherit
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
homebrew:
needs: publish
if: ${{ !inputs.nightly }}
uses: ./.github/workflows/homebrew.yml
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
with: { tag: "${{ inputs.tag || github.ref_name }}" }
secrets: inherit
+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/
+1
Переглянути файл
@@ -15,6 +15,7 @@
"src/editor/core/cm/jsp/parser*.ts",
"src/editor/core/cm/astro/parser*.ts",
"src/editor/core/cm/django/parser*.ts",
"src/editor/core/cm/freemarker/parser*.ts",
"plugins/themes.md",
"pnpm-lock.yaml",
"**/*.toml",
+4 -1
Переглянути файл
@@ -152,7 +152,10 @@
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
"excludeFiles": ["e2e/**"],
"rules": {
"no-await-in-loop": "error"
"no-await-in-loop": "error",
"react/no-array-index-key": "error",
"react/jsx-no-constructed-context-values": "error",
"react/no-object-type-as-default-prop": "error"
}
}
]
+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.
Створено
+125 -55
Переглянути файл
@@ -252,9 +252,9 @@ dependencies = [
[[package]]
name = "async-executor"
version = "1.14.0"
version = "1.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
dependencies = [
"async-task",
"concurrent-queue",
@@ -1552,9 +1552,9 @@ dependencies = [
[[package]]
name = "curve25519-dalek"
version = "5.0.0"
version = "5.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"
checksum = "94c1aa5a9b7626ed65ac0cf5ea9d4f1547af89017fbac20bd4de40022fff516f"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
@@ -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"
@@ -4154,7 +4167,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4166,23 +4179,26 @@ dependencies = [
"ide-tools",
"ide-vcs",
"ide-vfs",
"jiff",
"parking_lot 0.12.5",
"rustix",
"semver",
"serde",
"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]]
name = "ide-analysis"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4194,10 +4210,11 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"ide-core",
"serde",
"serde_json",
"specta",
"tempfile",
"which",
@@ -4205,7 +4222,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"blake3",
"chardetng",
@@ -4223,7 +4240,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4237,7 +4254,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4248,7 +4265,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -4259,7 +4276,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4281,7 +4298,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-run",
@@ -4294,7 +4311,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4305,6 +4322,7 @@ dependencies = [
"ide-jvm-attach",
"ide-jvm-inspect",
"ide-language",
"ide-run",
"libc",
"memchr",
"parking_lot 0.12.5",
@@ -4323,7 +4341,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4362,7 +4380,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"ide-core",
"serde",
@@ -4375,7 +4393,7 @@ dependencies = [
[[package]]
name = "ide-drag-out"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4389,7 +4407,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4409,7 +4427,7 @@ dependencies = [
[[package]]
name = "ide-flutter"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"ide-android",
"ide-core",
@@ -4420,7 +4438,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4432,7 +4450,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4444,7 +4462,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"criterion",
"ide-core",
@@ -4463,7 +4481,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4490,6 +4508,7 @@ dependencies = [
"ide-docker",
"ide-extension",
"ide-flutter",
"ide-github",
"ide-heap",
"ide-http",
"ide-index",
@@ -4509,6 +4528,7 @@ dependencies = [
"ide-spell",
"ide-ssh",
"ide-streams",
"ide-svn",
"ide-syntax",
"ide-terminal",
"ide-text",
@@ -4519,6 +4539,7 @@ dependencies = [
"ide-workspace",
"ignore",
"jsonschema",
"notify",
"parking_lot 0.12.5",
"quick-xml 0.42.0",
"regex-lite",
@@ -4544,11 +4565,15 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"http",
"hyper-util",
"ide-core",
"ide-vfs",
"objc2-cf-network",
"objc2-core-foundation",
"parking_lot 0.12.5",
"reqwest",
"rustls",
@@ -4563,7 +4588,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"blake3",
"criterion",
@@ -4586,7 +4611,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4598,7 +4623,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4614,7 +4639,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"libc",
"tempfile",
@@ -4623,7 +4648,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"futures",
"serde",
@@ -4634,7 +4659,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"blake3",
"criterion",
@@ -4675,6 +4700,7 @@ dependencies = [
"tree-sitter-make",
"tree-sitter-md",
"tree-sitter-nix",
"tree-sitter-objc",
"tree-sitter-ocaml",
"tree-sitter-php",
"tree-sitter-prisma-io",
@@ -4693,7 +4719,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"criterion",
"dunce",
@@ -4723,7 +4749,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"bytes",
"dunce",
@@ -4742,20 +4768,24 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"futures",
"ide-core",
"ide-http",
"ide-vfs",
"jupyter-protocol",
"jupyter-zmq-client",
"libc",
"parking_lot 0.12.5",
"reqwest",
"serde",
"serde_json",
"specta",
"specta-typescript",
"tempfile",
"tokio",
"tokio-tungstenite",
"uuid",
"windows-sys 0.61.2",
"zeromq",
@@ -4763,7 +4793,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"blake3",
"dunce",
@@ -4785,7 +4815,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4799,7 +4829,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"dunce",
"futures",
@@ -4819,8 +4849,9 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"blake3",
"dunce",
"encoding_rs",
"ide-build",
@@ -4831,6 +4862,7 @@ dependencies = [
"parking_lot 0.12.5",
"portable-pty",
"quick-xml 0.42.0",
"regex",
"serde",
"serde_json",
"specta",
@@ -4844,7 +4876,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-tools",
@@ -4860,7 +4892,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4886,7 +4918,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"criterion",
"encoding_rs",
@@ -4907,7 +4939,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"ide-core",
"parking_lot 0.12.5",
@@ -4920,7 +4952,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4945,7 +4977,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-language",
@@ -4956,9 +4988,24 @@ 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.54"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-language",
@@ -4973,7 +5020,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"ide-core",
"libc",
@@ -4987,7 +5034,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"criterion",
"ide-core",
@@ -5000,15 +5047,19 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"blake3",
"flate2",
"hex",
"http",
"hyper-util",
"ide-core",
"ide-http",
"ide-language",
"libc",
"minisign-verify",
"parking_lot 0.12.5",
"serde",
"serde_json",
@@ -5023,7 +5074,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"blake3",
"dunce",
@@ -5045,7 +5096,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"chardetng",
"dunce",
@@ -5072,7 +5123,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5088,7 +5139,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"blake3",
"dunce",
@@ -5098,6 +5149,7 @@ dependencies = [
"ide-text",
"ide-vfs",
"parking_lot 0.12.5",
"quick-xml 0.42.0",
"semver",
"serde",
"serde_json",
@@ -6319,6 +6371,15 @@ dependencies = [
"objc2-quartz-core 0.3.2",
]
[[package]]
name = "objc2-cf-network"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b4c9e30e636e2cd7d7414f320af2e0aa86f686adfc6f1bbe50b92366e4309c8"
dependencies = [
"objc2-core-foundation",
]
[[package]]
name = "objc2-cloud-kit"
version = "0.2.2"
@@ -6727,7 +6788,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.54"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -6747,7 +6808,6 @@ dependencies = [
"ide-drag-out",
"ide-extension",
"ide-fonts",
"ide-github",
"ide-host",
"ide-http",
"ide-jsonrpc",
@@ -9834,7 +9894,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"getrandom 0.3.4",
"once_cell",
"rustix",
"windows-sys 0.61.2",
@@ -10615,6 +10675,16 @@ dependencies = [
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-objc"
version = "3.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ca8bb556423fc176f0535e79d525f783a6684d3c9da81bf9d905303c129e1d2"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-ocaml"
version = "0.26.0"
+5 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.54"
version = "0.1.56"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
@@ -24,6 +24,8 @@ 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" }
ide-workspace = { path = "crates/ide-workspace" }
@@ -89,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"
@@ -98,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"
+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
+4 -1
Переглянути файл
@@ -18,15 +18,18 @@ ide-tools = { path = "../ide-tools" }
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"
[target.'cfg(unix)'.dependencies]
rustix = { version = "1", features = ["fs"] }
+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 }),
+393 -4
Переглянути файл
@@ -2,8 +2,8 @@
//! the agent reports them over ACP.
use crate::model::{
AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit,
AgentModelPricing, AgentTokens, AgentUsage,
AgentCommand, AgentCommandChoice, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia,
AgentCost, AgentLimit, AgentModelPricing, AgentTokens, AgentUsage,
};
use serde_json::{Value, json};
@@ -54,6 +54,21 @@ pub(crate) fn bypass_approvals(config: &[AgentConfigOption]) -> bool {
.any(|category| selected(category).zip(bypass_value(category)).is_some_and(|(value, bypass)| bypass(value)))
}
/// Canonical snapshot of approval-bearing config options (`mode`, `permissions`, `approval`)
/// so auto-resume can refuse to run silently if permission policy drifted while closed.
pub(crate) fn approval_fingerprint(config: &[AgentConfigOption]) -> Option<String> {
let mut parts: Vec<String> = config
.iter()
.filter(|o| matches!(o.category.as_deref(), Some("mode" | "permissions" | "approval")))
.filter_map(|o| Some(format!("{}={}", o.id, o.current.as_deref()?)))
.collect();
if parts.is_empty() {
return None;
}
parts.sort();
Some(parts.join(";"))
}
/// For an option of `category` that can approve everything, what tells its approving values.
fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
match category {
@@ -116,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`,
@@ -278,11 +549,30 @@ pub(crate) fn commands_of(update: &Value, provider: &str) -> Vec<AgentCommand> {
} else {
c.get("source").and_then(|s| serde_json::from_value(s.clone()).ok()).unwrap_or_default()
};
let mut seen_choices = std::collections::HashSet::new();
let choices = c
.pointer("/input/choices")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|ch| {
let choice_name =
ch.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty())?;
if !seen_choices.insert(choice_name.to_ascii_lowercase()) {
return None;
}
Some(AgentCommandChoice {
name: choice_name.to_owned(),
description: str_of(ch, "description").unwrap_or_default(),
})
})
.collect();
Some(AgentCommand {
name: name.to_owned(),
source,
description: str_of(c, "description").unwrap_or_default(),
hint: c.pointer("/input/hint").and_then(Value::as_str).filter(|h| !h.is_empty()).map(str::to_owned),
choices,
})
})
.collect()
@@ -635,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": [
@@ -654,6 +1025,7 @@ mod tests {
let old: AgentCommand =
serde_json::from_value(json!({"name": "review", "description": "Review", "hint": null})).unwrap();
assert_eq!(old.source, AgentCommandSource::Command);
assert!(old.choices.is_empty());
let skill = AgentCommand { source: AgentCommandSource::Skill, ..old };
assert_eq!(serde_json::from_value::<AgentCommand>(serde_json::to_value(&skill).unwrap()).unwrap(), skill);
}
@@ -663,13 +1035,30 @@ mod tests {
let cmds = commands_of(
&json!({"availableCommands": [
{"name": "review", "description": "Review changes", "input": {"hint": "what to review"}},
{"name": "/init", "description": "Write CLAUDE.md", "input": null}
{"name": "/init", "description": "Write CLAUDE.md", "input": null},
{"name": "skills", "description": "Manage skills", "input": {
"hint": "[list|info]",
"choices": [
{"name": "list", "description": "List all available skills"},
{"name": "LIST", "description": "Duplicate ignored"},
{"name": " ", "description": "Blank ignored"},
{"name": "info", "description": "Show details for a skill"}
]
}}
]}),
"claude",
);
assert_eq!(cmds[0].source, AgentCommandSource::Command);
assert_eq!(cmds[0].hint.as_deref(), Some("what to review"));
assert!(cmds[0].choices.is_empty());
assert_eq!((cmds[1].name.as_str(), cmds[1].hint.as_ref()), ("init", None));
assert_eq!(
cmds[2].choices,
vec![
AgentCommandChoice { name: "list".into(), description: "List all available skills".into() },
AgentCommandChoice { name: "info".into(), description: "Show details for a skill".into() },
]
);
let u = usage_of(&json!({"used": 1200, "size": 200000, "cost": {"amount": 0.42, "currency": "USD"}})).unwrap();
assert_eq!((u.used, u.size), (1200, 200000));
assert!(usage_of(&json!({"used": 1, "size": 0})).is_none());
+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();
+397 -3
Переглянути файл
@@ -2,9 +2,10 @@
//! scanned so they can be listed and imported as tasks instead of re-explained (#312).
//!
//! Only the native providers keep transcripts on disk in a readable form: Claude Code
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`) and Codex
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`), Codex
//! (`<home>/.codex/sessions/**`, rollout files with a `session_meta` line, named in
//! `<home>/.codex/session_index.jsonl`).
//! `<home>/.codex/session_index.jsonl`), and Copilot
//! (`<config>/session-state/<id>/workspace.yaml` plus `events.jsonl`).
use super::native::claude::history;
use serde::Serialize;
@@ -17,7 +18,7 @@ use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExternalSession {
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`).
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`, `copilot`).
pub provider: String,
/// The id resuming it names (`--resume`, `thread/resume`).
pub session_id: String,
@@ -26,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.
@@ -123,6 +127,7 @@ pub fn claude_sessions(config_dir: &Path, root: &Path) -> Vec<ExternalSession> {
title,
cwd,
updated_ms: mtime(&path),
in_use: false,
});
}
}
@@ -193,6 +198,7 @@ fn codex_file(path: &Path) -> Option<ExternalSession> {
session_id,
cwd,
updated_ms: mtime(path),
in_use: false,
})
}
@@ -246,6 +252,289 @@ pub fn codex_sessions(codex_home: &Path, root: &Path) -> Vec<ExternalSession> {
sessions
}
/// Whether `raw` is a YAML block-scalar header (`|`, `|-`, `|+`, `>`, `>-`, `>+`, with optional indent digit).
fn is_yaml_block_header(raw: &str) -> bool {
let mut chars = raw.chars();
matches!(chars.next(), Some('|' | '>')) && chars.all(|c| matches!(c, '-' | '+') || c.is_ascii_digit())
}
/// Unquotes a single-line YAML scalar value from Copilot's `workspace.yaml`.
fn parse_yaml_inline_value(raw: &str) -> String {
if raw.starts_with('"') {
serde_json::from_str(raw).unwrap_or_else(|_| raw.trim_matches('"').to_owned())
} else if raw.starts_with('\'') && raw.ends_with('\'') && raw.len() >= 2 {
raw[1..raw.len() - 1].replace("''", "'")
} else {
raw.to_owned()
}
}
/// Metadata for one Copilot session, read without opening its potentially multi-gigabyte event log.
/// Supports both inline scalars (`name: "Fix\nbug"`) and block scalars (`name: |-\n Fix\n bug`).
fn copilot_metadata(path: &Path) -> Option<HashMap<String, String>> {
let file = std::fs::File::open(path).ok()?;
let mut lines = std::io::BufReader::new(file).lines().map_while(Result::ok).peekable();
let mut metadata = HashMap::new();
while let Some(line) = lines.next() {
if line.is_empty() || line.starts_with(char::is_whitespace) || line.trim_start().starts_with('#') {
continue;
}
let Some((key, raw)) = line.split_once(':') else { continue };
let key = key.trim();
let raw = raw.trim();
if key.is_empty() {
continue;
}
if is_yaml_block_header(raw) {
let folded = raw.starts_with('>');
let mut block = Vec::new();
while let Some(next) = lines.peek() {
if next.is_empty() || next.starts_with(' ') || next.starts_with('\t') {
block.push(lines.next().unwrap_or_default());
} else {
break;
}
}
while block.last().is_some_and(|l| l.trim().is_empty()) {
block.pop();
}
let indent = block
.iter()
.filter(|l| !l.trim().is_empty())
.map(|l| l.bytes().take_while(|&b| b == b' ').count())
.min()
.unwrap_or(0);
let sep = if folded { " " } else { "\n" };
let joined = block
.iter()
.map(|l| if l.len() >= indent { &l[indent..] } else { l.trim_start() })
.collect::<Vec<_>>()
.join(sep);
if !joined.trim().is_empty() {
metadata.insert(key.to_owned(), joined);
}
} else if !raw.is_empty() {
metadata.insert(key.to_owned(), parse_yaml_inline_value(raw));
}
}
(!metadata.is_empty()).then_some(metadata)
}
/// The first real prompt in a Copilot event log, used when an old or unnamed session has no title.
fn copilot_prompt(path: &Path) -> Option<String> {
let file = std::fs::File::open(path).ok()?;
std::io::BufReader::new(file)
.lines()
.take(400)
.filter_map(|line| line.ok())
.filter_map(|line| serde_json::from_str::<serde_json::Value>(&line).ok())
.find_map(|event| {
(event.get("type").and_then(serde_json::Value::as_str) == Some("user.message"))
.then(|| event.pointer("/data/content").and_then(serde_json::Value::as_str).map(str::trim))
.flatten()
.filter(|text| !text.is_empty())
.map(short)
})
}
/// 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> {
let mut bases = vec![home.join("Library/Application Support"), home.join(".config"), home.join("AppData/Roaming")];
let real_home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));
if real_home.as_deref().is_some_and(|h| Path::new(h) == home) {
for var in ["XDG_CONFIG_HOME", "APPDATA"] {
if let Some(dir) = std::env::var_os(var).filter(|v| !v.is_empty()).map(PathBuf::from)
&& !bases.contains(&dir)
{
bases.push(dir);
}
}
}
let mut dbs = Vec::new();
for base in bases {
for app in ["Code", "Code - Insiders"] {
dbs.push(base.join(app).join("User/globalStorage/agent-host.db"));
}
}
for server in [".vscode-server", ".vscode-server-insiders"] {
dbs.push(home.join(server).join("data/User/globalStorage/agent-host.db"));
}
dbs.retain(|p| p.is_file());
dbs.sort_by(|a, b| mtime(a).total_cmp(&mtime(b)));
dbs
}
fn is_generic_vscode_placeholder(title: &str, source: Option<&str>) -> bool {
source != Some("user") && (title.eq_ignore_ascii_case("new session") || title.eq_ignore_ascii_case("new chat"))
}
fn pick_vscode_chat_title(
scs_title: Option<&str>,
scs_source: Option<&str>,
metadata_json: Option<&str>,
payload_json: Option<&str>,
) -> Option<String> {
if let Some(t) = scs_title.map(str::trim).filter(|t| !t.is_empty())
&& !is_generic_vscode_placeholder(t, scs_source)
{
return Some(t.to_owned());
}
for blob in [metadata_json, payload_json].into_iter().flatten() {
let Ok(v) = serde_json::from_str::<serde_json::Value>(blob) else { continue };
let summary = v.pointer("/data/summary").and_then(serde_json::Value::as_str).map(str::trim);
let source = v.pointer("/data/titleSource").and_then(serde_json::Value::as_str);
if let Some(t) = summary.filter(|t| !t.is_empty())
&& !is_generic_vscode_placeholder(t, source)
{
return Some(t.to_owned());
}
}
None
}
/// 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 \
LEFT JOIN session_chat_state scs \
ON scs.session_uri = c.owner_session_uri AND scs.chat_uri = c.chat_uri \
LEFT JOIN sessions_v2 s \
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";
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 [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.
pub fn copilot_sessions(copilot_home: &Path, home: Option<&Path>, root: &Path) -> Vec<ExternalSession> {
let mut pending: Vec<(ExternalSession, bool)> = std::fs::read_dir(copilot_home.join("session-state"))
.into_iter()
.flatten()
.flatten()
.filter_map(|entry| {
let dir = entry.path();
let events = dir.join("events.jsonl");
if !events.is_file() {
return None;
}
let metadata = copilot_metadata(&dir.join("workspace.yaml"))?;
let session_id = metadata.get("id").cloned().or_else(|| entry.file_name().to_str().map(str::to_owned))?;
let cwd = metadata.get("cwd").cloned().or_else(|| metadata.get("git_root").cloned());
if !in_project(cwd.as_deref(), root) {
return None;
}
let raw_name = metadata.get("name").map(String::as_str).map(str::trim).filter(|name| !name.is_empty());
let cli_user_named = metadata.get("user_named").is_some_and(|v| v == "true")
&& raw_name.is_some_and(|n| !n.eq_ignore_ascii_case("new session"));
let title = raw_name
.map(short)
.or_else(|| copilot_prompt(&events))
.unwrap_or_else(|| format!("Copilot session {}", &session_id[..session_id.len().min(8)]));
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() {
let vscode_titles = vscode_copilot_titles(home);
for (session, cli_user_named) in &mut pending {
if !*cli_user_named && let Some(title) = vscode_titles.get(&session.session_id) {
session.title = short(title);
}
}
}
pending.into_iter().map(|(s, _)| s).collect()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -344,6 +633,111 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
assert!(claude_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
assert!(codex_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
assert!(copilot_sessions(&tmp.path().join("nope"), None, Path::new("/work")).is_empty());
}
fn exec_sqlite(path: &Path, sql: &'static str) {
use sqlx::Connection;
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
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]
fn lists_copilot_sessions_with_names_block_scalars_vscode_titles_and_prompt_fallbacks() {
let tmp = tempfile::tempdir().unwrap();
let copilot_home = tmp.path().join(".copilot");
let session = copilot_home.join("session-state/copilot-1");
write(
&session.join("events.jsonl"),
&[
json!({"type": "session.start", "data": {}}),
json!({"type": "user.message", "data": {"content": "fix the parser"}}),
],
);
std::fs::write(
session.join("workspace.yaml"),
"id: copilot-1\ncwd: /work/app/api\nname: \"Fix parser\\nand tests\"\n",
)
.unwrap();
let block_scalar = copilot_home.join("session-state/copilot-block");
write(&block_scalar.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
std::fs::write(
block_scalar.join("workspace.yaml"),
"id: copilot-block\ncwd: /work/app\nname: |-\n check why excalidraw font\n is not displayed\nuser_named: false\n",
)
.unwrap();
let vscode_renamed = copilot_home.join("session-state/copilot-vscode");
write(
&vscode_renamed.join("events.jsonl"),
&[json!({"type": "user.message", "data": {"content": "create a branch deng/session add Create Session"}})],
);
std::fs::write(
vscode_renamed.join("workspace.yaml"),
"id: copilot-vscode\ncwd: /work/app\nclient_name: vscode-agent-host\nname: create a branch deng/session add Create Session\nuser_named: false\n",
)
.unwrap();
let vscode_placeholder = copilot_home.join("session-state/copilot-placeholder");
write(&vscode_placeholder.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
std::fs::write(
vscode_placeholder.join("workspace.yaml"),
"id: copilot-placeholder\ncwd: /work/app\nname: Greeting exchange\nuser_named: false\n",
)
.unwrap();
let unnamed = copilot_home.join("session-state/copilot-2");
write(
&unnamed.join("events.jsonl"),
&[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();
std::fs::write(empty.join("workspace.yaml"), "id: copilot-empty\ncwd: /work/app\n").unwrap();
let other = copilot_home.join("session-state/copilot-other");
write(
&other.join("events.jsonl"),
&[json!({"type": "user.message", "data": {"content": "unrelated project"}})],
);
std::fs::write(other.join("workspace.yaml"), "id: copilot-other\ncwd: /other\n").unwrap();
exec_sqlite(
&tmp.path().join(".config/Code/User/globalStorage/agent-host.db"),
"CREATE TABLE sessions_v2 (session_uri TEXT PRIMARY KEY, payload TEXT, modified_time INTEGER);
CREATE TABLE session_chat_state (session_uri TEXT, chat_uri TEXT, title TEXT, title_source TEXT);
CREATE TABLE chats_v2 (chat_uri TEXT PRIMARY KEY, owner_session_uri TEXT, chat_order INTEGER, provider_data TEXT, metadata TEXT, tombstoned INTEGER);
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs1', '{}', 100);
INSERT INTO chats_v2 VALUES ('chat:/vs1', 'copilotcli:/vs1', 0, '{\"sdkSessionId\":\"copilot-vscode\"}', '{\"data\":{\"summary\":\"Session\",\"titleSource\":\"user\"}}', 0);
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs2', '{}', 100);
INSERT INTO chats_v2 VALUES ('chat:/vs2', 'copilotcli:/vs2', 0, '{\"sdkSessionId\":\"copilot-placeholder\"}', '{\"data\":{\"summary\":\"New session\",\"titleSource\":\"auto\"}}', 0);",
);
let sessions = copilot_sessions(&copilot_home, Some(tmp.path()), Path::new("/work"));
assert_eq!(sessions.len(), 5);
let mut by_id: HashMap<_, _> = sessions.into_iter().map(|s| (s.session_id.clone(), s)).collect();
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");
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,
}
}
File diff suppressed because it is too large. Load diff
+750 -4
Переглянути файл
@@ -49,6 +49,75 @@ pub struct AgentCapabilities {
pub context_usage: bool,
}
/// Why `AgentManager` is shutting down its live tasks.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AgentShutdownReason {
WindowClose,
#[default]
Quit,
Restart,
BackendUpgrade,
BackendStop,
}
/// Why an in-flight turn stopped before completing.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum InterruptionReason {
WindowClose,
Quit,
Restart,
BackendUpgrade,
BackendStop,
UnexpectedExit,
NetworkTimeout,
CursorCapacity,
}
impl From<AgentShutdownReason> for InterruptionReason {
fn from(reason: AgentShutdownReason) -> Self {
match reason {
AgentShutdownReason::WindowClose => Self::WindowClose,
AgentShutdownReason::Quit => Self::Quit,
AgentShutdownReason::Restart => Self::Restart,
AgentShutdownReason::BackendUpgrade => Self::BackendUpgrade,
AgentShutdownReason::BackendStop => Self::BackendStop,
}
}
}
/// Recovery metadata recorded when an active turn was interrupted before finishing.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentInterrupted {
pub reason: InterruptionReason,
pub at_ms: f64,
#[serde(default, skip_serializing_if = "is_false")]
pub was_waiting_for_input: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub approval_mode: Option<String>,
#[serde(default, skip_serializing_if = "is_false")]
pub auto_resume_once: bool,
}
/// Summary returned when reconciling interrupted tasks for a connected project window.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentRecoveryReport {
/// Unique identifier of this `AgentManager` process incarnation.
pub instance_id: String,
/// `true` on the first reconciliation of this `AgentManager` incarnation.
pub first_reconcile: bool,
/// Task IDs automatically resumed during this reconciliation.
pub auto_resumed: Vec<String>,
/// Task IDs remaining in `Interrupted` (`Ask to resume`).
pub interrupted: Vec<String>,
}
fn is_false(b: &bool) -> bool {
!*b
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum Isolation {
@@ -113,10 +182,28 @@ pub struct AgentTask {
/// Per-session skill modes (`skill name` -> mode), on top of the settings' policies.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
/// Per-session memory overrides (auto-memory mode and per-entry modes), boxed to keep `AgentEvent::Task` small.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub memory_overrides: Option<Box<AgentMemoryOverrides>>,
/// Token counts of the last turn and context compressions, when the agent reports them.
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
#[serde(default)]
pub stats: Box<AgentSessionStats>,
/// Set when the task's last active turn was interrupted (window close, restart, crash, or
/// expired network retry window) and has not been resumed or dismissed yet.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub interrupted: Option<Box<AgentInterrupted>>,
/// Persisted unseen reply / input / failure state across window closes and remote reattaches.
#[serde(default, skip_serializing_if = "is_false")]
pub unread: bool,
/// 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)]
@@ -159,6 +246,9 @@ pub struct AgentRetry {
/// When the next attempt starts (ms since the epoch).
pub retry_at_ms: f64,
pub error: Option<String>,
/// Set when OpenIDEA holds an active turn in `Waiting for network` until `deadline_ms`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deadline_ms: Option<f64>,
}
/// Token pricing (Credits per 1M tokens) and context window capacity for one tier.
@@ -255,6 +345,14 @@ pub enum AgentCommandSource {
Skill,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentCommandChoice {
pub name: String,
#[serde(default)]
pub description: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentCommand {
@@ -265,6 +363,9 @@ pub struct AgentCommand {
pub hint: Option<String>,
#[serde(default)]
pub source: AgentCommandSource,
/// Fixed subcommand/argument choices advertised by the agent (e.g. `list`, `info` for `/skills`).
#[serde(default)]
pub choices: Vec<AgentCommandChoice>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -289,6 +390,9 @@ pub struct AgentContextUsage {
pub model: String,
pub is_auto_compact_enabled: Option<bool>,
pub auto_compact_threshold: Option<u32>,
/// Tokens reserved for model response / output buffer, when the agent reports it.
#[serde(default)]
pub reserved_tokens: Option<u32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -296,13 +400,16 @@ pub struct AgentContextCategory {
pub name: String,
pub tokens: u32,
pub kind: Option<String>,
/// Visual section group (e.g. `"System"`, `"User Context"`).
#[serde(default)]
pub group: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentCost {
pub amount: f64,
/// ISO 4217 code, e.g. `USD`.
/// ISO 4217 code (e.g. `USD`), or `"credits"` for AI-credit billing.
pub currency: String,
}
@@ -325,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 {
@@ -352,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`].
@@ -511,6 +639,12 @@ pub enum AgentEntry {
/// Sent into a running turn rather than starting one.
#[serde(default)]
steered: bool,
/// 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,
@@ -547,6 +681,9 @@ pub enum AgentEntry {
started_ms: Option<f64>,
#[serde(default)]
ended_ms: Option<f64>,
/// The command an `execute` call runs, from its structured input; `None` when the agent gave none.
#[serde(default)]
command: Option<String>,
},
Plan {
items: Vec<AgentPlanItem>,
@@ -730,6 +867,10 @@ pub struct NewAgentTask {
/// Per-session skill modes (`skill name` -> mode).
#[serde(default)]
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
/// Per-session memory overrides (auto-memory mode and per-entry modes).
#[serde(default)]
#[specta(optional)]
pub memory_overrides: Option<AgentMemoryOverrides>,
/// Creates the task without sending `prompt` (it only names the task): the composer's
/// `!` command runs in it first.
#[serde(default)]
@@ -808,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.
@@ -871,7 +1012,7 @@ pub enum AgentEvent {
pub use ide_core::settings::{AgentMcpServer, McpTransport};
/// Where an MCP server configuration is stored (`settings.toml` vs `.openidea/settings.toml`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum McpScope {
User,
@@ -906,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.
@@ -938,7 +1087,231 @@ fn default_true() -> bool {
true
}
pub use ide_core::settings::{AgentSkillMode, AgentSkillPolicy};
pub use ide_core::settings::{
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings,
AgentProviderMemoryPolicy, AgentSkillMode, AgentSkillPolicy, AutoMemoryMode,
};
/// Kind of discovered agent memory entry.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemoryKind {
/// Always-loaded instruction document (`AGENTS.md`, `CLAUDE.md`, `copilot-instructions.md`, `GEMINI.md`).
#[default]
Instruction,
/// Path-scoped or conditional rule (`.claude/rules/*.md`, `*.instructions.md`, `.cursor/rules/*.mdc`).
Rule,
/// Agent-authored cross-session memory note (`MEMORY.md`, Claude topic files, Codex summaries, Hermes `USER.md`).
AutoNote,
}
/// Which workspace, user, or CLI store a memory entry was discovered in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemorySource {
/// Portable workspace instructions: `AGENTS.md`, `AGENTS.override.md`.
#[default]
Workspace,
/// `CLAUDE.md`, `.claude/CLAUDE.md`, `CLAUDE.local.md`, `.claude/rules/**`.
ClaudeWorkspace,
/// `~/.claude/CLAUDE.md`, `~/.claude/rules/**`.
ClaudeUser,
/// `~/.claude/projects/<repo>/memory/**` (or custom `autoMemoryDirectory`).
ClaudeAuto,
/// `.github/copilot-instructions.md`, `.github/instructions/**/*.instructions.md`.
GithubWorkspace,
/// `~/.copilot/copilot-instructions.md`, `~/.copilot/instructions/**/*.instructions.md`.
CopilotUser,
/// `~/.codex/AGENTS.md`, `~/.codex/AGENTS.override.md`.
CodexUser,
/// `~/.codex/memories/**` / `~/.codex/memories_v2/**`.
CodexAuto,
/// `.cursor/rules/**/*.mdc`, `.cursorrules`.
CursorWorkspace,
/// `GEMINI.md`.
GeminiWorkspace,
/// `~/.gemini/GEMINI.md`.
GeminiUser,
/// `<hermes_profile>/memories/{MEMORY.md,USER.md}`.
HermesAuto,
}
impl AgentMemorySource {
/// True when the entry lives inside the current workspace and requires Workspace Trust.
pub fn is_workspace(self) -> bool {
matches!(
self,
Self::Workspace
| Self::ClaudeWorkspace
| Self::GithubWorkspace
| Self::CursorWorkspace
| Self::GeminiWorkspace
)
}
/// True when the entry is an agent's learned cross-session auto-memory store.
pub fn is_auto(self) -> bool {
matches!(self, Self::ClaudeAuto | Self::CodexAuto | Self::HermesAuto)
}
}
/// Which layer decided an [`AgentMemoryState::mode`] or [`AutoMemoryMode`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemoryOrigin {
#[default]
None,
Session,
Workspace,
User,
/// Locked `Off` because the workspace is untrusted.
Trust,
}
/// One discovered instruction file, rule file, or learned auto-memory note.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMemoryEntry {
/// Stable identifier (`"<source>::<rel_key>"`).
pub id: String,
pub title: String,
pub description: String,
pub kind: AgentMemoryKind,
pub source: AgentMemorySource,
/// Secondary sources whose symlink or `@AGENTS.md` import resolved to this same canonical file.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub also_in: Vec<AgentMemorySource>,
/// Canonical file path on disk.
pub path: IpcPath,
/// Normalized path-scoping globs (`paths:` in Claude, `applyTo:` in Copilot, `globs:` in Cursor).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub paths: Vec<String>,
/// Optional memory category (`user`, `feedback`, `project`, `reference`, `profile`).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub category: Option<String>,
/// Approximate prompt token cost (~4 chars/token).
pub approx_tokens: u32,
pub line_count: u32,
pub byte_len: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub modified_ms: Option<f64>,
/// True when OpenIDEA allows deleting or promoting-and-removing this file (auto-memory notes).
pub writable: bool,
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.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMemoryState {
pub entry: AgentMemoryEntry,
pub mode: AgentMemoryMode,
/// Optional provider filter from `[agents.memory.entries.<id>]`; empty means all agents.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub agents: Vec<String>,
pub origin: AgentMemoryOrigin,
}
/// Live auto-memory status and capability summary for one agent family.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentAutoMemoryStatus {
pub provider: String,
pub label: String,
pub mode: AutoMemoryMode,
pub origin: AgentMemoryOrigin,
pub note_count: u32,
pub rollout_count: u32,
pub approx_tokens: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub storage_path: Option<IpcPath>,
pub supports_auto_control: bool,
pub supports_file_exclusion: bool,
pub supports_reset: bool,
}
/// Full catalog returned to Settings › Agents › Memory and the Composer `MemoryPicker`.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMemoryCatalog {
pub entries: Vec<AgentMemoryState>,
pub providers: Vec<AgentAutoMemoryStatus>,
pub auto_memory: AutoMemoryMode,
pub auto_memory_origin: AgentMemoryOrigin,
}
/// Per-session memory overrides stored on an [`AgentTask`].
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentMemoryOverrides {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub auto_memory: Option<AutoMemoryMode>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub entries: BTreeMap<String, AgentMemoryMode>,
}
impl AgentMemoryOverrides {
pub fn is_empty(&self) -> bool {
self.auto_memory.is_none() && self.entries.is_empty()
}
}
/// Target format when creating a new memory or instruction file from Settings › Agents › Memory.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemoryCreateTarget {
/// `<workspace>/AGENTS.md` (or `~/.codex/AGENTS.md` in User scope).
#[default]
AgentsMd,
/// `<workspace>/.claude/rules/<slug>.md` or `~/.claude/rules/<slug>.md`.
ClaudeRule,
/// `<workspace>/.github/instructions/<slug>.instructions.md` or `~/.copilot/instructions/<slug>.instructions.md`.
CopilotInstruction,
/// `<workspace>/.cursor/rules/<slug>.mdc`.
CursorRule,
}
/// Payload for creating a new instruction or rule file.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CreateAgentMemoryInput {
pub scope: McpScope,
pub target: AgentMemoryCreateTarget,
#[serde(default)]
pub name: String,
#[serde(default)]
#[specta(optional)]
pub description: Option<String>,
#[serde(default)]
pub paths: Vec<String>,
pub content: String,
}
/// Payload for promoting an auto-memory note into `AGENTS.md`.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PromoteAgentMemoryInput {
pub source_id: String,
#[serde(default)]
#[specta(optional)]
pub heading: Option<String>,
#[serde(default)]
pub remove_source: bool,
}
/// Which CLI's own folders a skill was discovered in (Settings › Agents › Skills groups by it).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -1009,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
@@ -1070,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")]
+62 -6
Переглянути файл
@@ -174,10 +174,14 @@ struct Session {
mcp_off: Vec<String>,
/// The staged skills folder passed as `--add-dir` (its `.claude/skills` holds the copies).
skills_add_dir: Option<PathBuf>,
/// The staged memory rules folder passed as `--add-dir` (its `.claude/rules` holds shared rules).
memory_add_dir: Option<PathBuf>,
/// Load `.claude/rules` from `--add-dir` folders (`CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`).
additional_dirs_claude_md: bool,
/// The workspace's other roots, each passed as `--add-dir`.
additional_dirs: Vec<String>,
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
skills_settings: Option<String>,
/// Combined `--settings` JSON (`skillOverrides`, `autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`).
cli_settings: Option<String>,
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
ephemeral: bool,
shim: Weak<Shim>,
@@ -371,13 +375,20 @@ impl Shim {
}
});
let skills = params.pointer("/_meta/openidea/skills");
let memory = params.pointer("/_meta/openidea/memory");
let cli_settings = build_cli_settings(skills, memory);
let session = Arc::new(Session {
id: id.to_owned(),
mcp_config,
mcp_off,
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
memory_add_dir: memory.and_then(|m| m.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
additional_dirs_claude_md: memory
.and_then(|m| m.get("claudeAdditionalDirsClaudeMd"))
.and_then(Value::as_bool)
.unwrap_or(false),
additional_dirs: additional_dirs(params),
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
cli_settings,
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
shim: Arc::downgrade(self),
st: Mutex::new(State {
@@ -728,18 +739,28 @@ impl Session {
if let Some(dir) = &self.skills_add_dir {
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
}
if let Some(dir) = &self.memory_add_dir
&& self.skills_add_dir.as_ref() != Some(dir)
{
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
}
for dir in &self.additional_dirs {
args.extend(["--add-dir".to_owned(), dir.clone()]);
}
if let Some(settings) = &self.skills_settings {
if let Some(settings) = &self.cli_settings {
args.extend(["--settings".to_owned(), settings.clone()]);
}
if self.ephemeral {
args.push("--no-session-persistence".to_owned());
}
args.extend(start.args());
let launch =
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
let mut env = shim.config.env.clone();
if self.additional_dirs_claude_md
&& !env.iter().any(|(k, _)| k == "CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD")
{
env.push(("CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD".to_owned(), "1".to_owned()));
}
let launch = Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env };
let io = shim
.cli
.launch(&launch, shim.on_stderr.clone())
@@ -1601,6 +1622,41 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
/// Claude Code's own configuration stays off too.
/// Combines `skillOverrides` from `_meta.openidea.skills.claudeSettings` with memory
/// settings (`autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`) into one `--settings` JSON.
fn build_cli_settings(skills: Option<&Value>, memory: Option<&Value>) -> Option<String> {
let mut root = skills
.and_then(|s| s.get("claudeSettings"))
.and_then(Value::as_str)
.and_then(|raw| serde_json::from_str::<serde_json::Map<String, Value>>(raw).ok())
.unwrap_or_default();
if let Some(mem) = memory {
if let Some(auto) = mem.get("claudeAutoMemory").and_then(Value::as_bool) {
root.insert("autoMemoryEnabled".into(), json!(auto));
}
if let Some(excludes) = mem.get("claudeMdExcludes").and_then(Value::as_array) {
let clean: Vec<Value> =
excludes.iter().filter_map(Value::as_str).filter(|s| !s.is_empty()).map(|s| json!(s)).collect();
if !clean.is_empty() {
root.insert("claudeMdExcludes".into(), Value::Array(clean));
}
}
if let Some(inst) = mem.get("claudeInstructionFiles").and_then(Value::as_str).filter(|s| !s.is_empty()) {
root.insert(
"pluginConfigs".into(),
json!({
"cc-plugin-agents-md@builtin": {
"options": { "instructionFiles": inst }
}
}),
);
}
}
(!root.is_empty()).then(|| serde_json::to_string(&Value::Object(root)).expect("settings serialize"))
}
/// The session's `additionalDirectories`: the workspace's other roots.
fn additional_dirs(params: &Value) -> Vec<String> {
let dirs = params.get("additionalDirectories").and_then(Value::as_array);
+73
Переглянути файл
@@ -1442,3 +1442,76 @@ async fn an_ephemeral_session_is_not_saved() {
let args = cli.launched.lock()[0].clone();
assert!(args.contains(&"--no-session-persistence".to_owned()), "{args:?}");
}
#[tokio::test(flavor = "multi_thread")]
async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env() {
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": {
"skills": {
"claudeAddDir": "/tmp/farm-skills",
"claudeSettings": "{\"skillOverrides\":{\"tdd\":\"user-invocable-only\"}}"
},
"memory": {
"autoMemory": "readOnly",
"claudeAutoMemory": false,
"claudeMdExcludes": ["/repo/CLAUDE.local.md"],
"claudeInstructionFiles": "claude-md-and-agents-md",
"claudeAddDir": "/tmp/farm-memory",
"claudeAdditionalDirsClaudeMd": true
}
}
}
});
h.request("session/new", params).await.unwrap();
let args = cli.launched.lock()[0].clone();
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-skills"]), "{args:?}");
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-memory"]), "{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["skillOverrides"]["tdd"], "user-invocable-only");
assert_eq!(parsed["autoMemoryEnabled"], false);
assert_eq!(parsed["claudeMdExcludes"], json!(["/repo/CLAUDE.local.md"]));
assert_eq!(
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
"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());
}
+45 -5
Переглянути файл
@@ -8,43 +8,80 @@ pub(crate) struct BuiltinCommandSpec {
pub name: &'static str,
pub description: &'static str,
pub hint: Option<&'static str>,
pub choices: &'static [(&'static str, &'static str)],
}
pub(crate) const BUILTIN_COMMANDS: &[BuiltinCommandSpec] = &[
BuiltinCommandSpec { name: "plan", description: "Turn plan mode on or off.", hint: None },
BuiltinCommandSpec { name: "plan", description: "Turn plan mode on or off.", hint: None, choices: &[] },
BuiltinCommandSpec {
name: "mcp",
description: "Show the status of the MCP servers, or reconnect them.",
hint: Some("[reconnect]"),
choices: &[("reconnect", "Reload and reconnect MCP servers.")],
},
BuiltinCommandSpec { name: "skills", description: "List available skills.", hint: None, choices: &[] },
BuiltinCommandSpec {
name: "memories",
description: "Show, enable, disable, or reset cross-session Codex memories.",
hint: Some("[show|on|off|reset]"),
choices: &[
("show", "Show consolidated memory summary for this thread."),
("on", "Enable memory generation for this thread."),
("off", "Disable memory generation for this thread."),
("reset", "Clear local Codex memory files and summaries."),
],
},
BuiltinCommandSpec {
name: "status",
description: "Display session configuration and token usage.",
hint: None,
choices: &[],
},
BuiltinCommandSpec { name: "skills", description: "List available skills.", hint: None },
BuiltinCommandSpec { name: "status", description: "Display session configuration and token usage.", hint: None },
BuiltinCommandSpec {
name: "review",
description: "Review uncommitted changes, or review with custom instructions.",
hint: Some("optional review instructions"),
choices: &[],
},
BuiltinCommandSpec {
name: "review-branch",
description: "Review changes relative to a base branch.",
hint: Some("branch name"),
choices: &[],
},
BuiltinCommandSpec {
name: "review-commit",
description: "Review a specific commit.",
hint: Some("commit sha"),
choices: &[],
},
BuiltinCommandSpec { name: "review-commit", description: "Review a specific commit.", hint: Some("commit sha") },
BuiltinCommandSpec {
name: "compact",
description: "Summarize conversation to avoid hitting the context limit.",
hint: None,
choices: &[],
},
BuiltinCommandSpec {
name: "goal",
description: "Set a goal to keep pursuing.",
hint: Some("[<objective>|clear|pause|resume]"),
choices: &[
("clear", "Clear the current goal."),
("pause", "Pause the current goal."),
("resume", "Resume a paused goal."),
],
},
BuiltinCommandSpec {
name: "rename",
description: "Rename the current session.",
hint: Some("new name"),
choices: &[],
},
BuiltinCommandSpec { name: "rename", description: "Rename the current session.", hint: Some("new name") },
BuiltinCommandSpec {
name: "logout",
description: "Sign out of Codex. This option is available when you are logged in via ChatGPT.",
hint: None,
choices: &[],
},
];
@@ -53,6 +90,7 @@ pub(super) enum BuiltinCommand {
Plan,
Mcp,
Skills,
Memories,
Status,
Review,
ReviewBranch,
@@ -69,6 +107,7 @@ impl BuiltinCommand {
"plan" => Self::Plan,
"mcp" => Self::Mcp,
"skills" => Self::Skills,
"memories" => Self::Memories,
"status" => Self::Status,
"review" => Self::Review,
"review-branch" => Self::ReviewBranch,
@@ -124,6 +163,7 @@ mod tests {
"plan",
"mcp",
"skills",
"memories",
"status",
"review",
"review-branch",
+58 -1
Переглянути файл
@@ -14,7 +14,7 @@ mod tests;
use super::Shim;
use crate::acp::AUTH_REQUIRED;
use crate::provider::ProviderSpec;
use crate::{AgentCommand, AgentCommandSource};
use crate::{AgentCommand, AgentCommandChoice, AgentCommandSource};
use commands::{BuiltinCommand, ParsedCommand};
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
use parking_lot::Mutex;
@@ -47,6 +47,14 @@ pub(crate) fn builtin_commands() -> Vec<AgentCommand> {
description: command.description.to_owned(),
hint: command.hint.map(str::to_owned),
source: AgentCommandSource::Command,
choices: command
.choices
.iter()
.map(|(name, description)| AgentCommandChoice {
name: (*name).to_owned(),
description: (*description).to_owned(),
})
.collect(),
})
.collect()
}
@@ -354,6 +362,23 @@ fn apply_thread_config(params: &Value, request: &mut Value) {
{
map.insert("skills".into(), json!({ "config": off }));
}
if let Some(mem) = params.pointer("/_meta/openidea/memory")
&& let Some(map) = config.as_object_mut()
{
let mut mem_cfg = serde_json::Map::new();
if let Some(use_m) = mem.get("codexUseMemories").and_then(Value::as_bool) {
mem_cfg.insert("use_memories".into(), json!(use_m));
}
if let Some(gen_m) = mem.get("codexGenerateMemories").and_then(Value::as_bool) {
mem_cfg.insert("generate_memories".into(), json!(gen_m));
}
if !mem_cfg.is_empty() {
map.insert("memories".into(), Value::Object(mem_cfg));
}
if let Some(dev) = mem.get("codexDeveloperInstructions").and_then(Value::as_str).filter(|s| !s.is_empty()) {
map.insert("developer_instructions".into(), json!(dev));
}
}
if !config.as_object().is_some_and(|m| m.is_empty()) {
request["config"] = config;
}
@@ -700,6 +725,7 @@ impl CodexShim {
let found = self.call("skills/list", json!({ "cwds": [cwd] })).await?;
self.say(session, skills_text(&found));
}
BuiltinCommand::Memories => self.memories_command(session, &command.rest).await?,
BuiltinCommand::Mcp => match command.rest.as_str() {
"" => self.say(session, self.mcp_text(session).await?),
rest if rest.eq_ignore_ascii_case("reconnect") => {
@@ -739,6 +765,36 @@ impl CodexShim {
Ok(json!({ "stopReason": "end_turn" }))
}
async fn memories_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
let arg = rest.trim().to_ascii_lowercase();
match arg.as_str() {
"" | "show" => {
let res = self.call("thread/memory/read", json!({ "threadId": session })).await?;
let summary = res
.get("summary")
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.unwrap_or("No consolidated memories for this thread yet.");
self.say(session, summary);
}
"on" => {
self.call("thread/memoryMode/set", json!({ "threadId": session, "mode": "enabled" })).await?;
self.say(session, "Memory generation enabled for this thread.");
}
"off" => {
self.call("thread/memoryMode/set", json!({ "threadId": session, "mode": "disabled" })).await?;
self.say(session, "Memory generation disabled for this thread.");
}
"reset" => {
self.call("memory/reset", Value::Null).await?;
self.say(session, "Reset local Codex memories.");
}
_ => self.say(session, command_usage(BuiltinCommand::Memories)),
}
Ok(())
}
async fn goal_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
let argument = rest.trim();
if argument.is_empty() {
@@ -1510,6 +1566,7 @@ fn command_usage(command: BuiltinCommand) -> String {
match command {
BuiltinCommand::Plan => "Command \"/plan\" accepts no arguments.".to_owned(),
BuiltinCommand::Mcp => "Command \"/mcp\" accepts no arguments, or `reconnect`.".to_owned(),
BuiltinCommand::Memories => "Command \"/memories\" accepts `[show|on|off|reset]`.".to_owned(),
BuiltinCommand::ReviewBranch => "Command \"/review-branch\" requires branch name.".to_owned(),
BuiltinCommand::ReviewCommit => "Command \"/review-commit\" requires commit sha.".to_owned(),
BuiltinCommand::Goal => "Command \"/goal\" requires [<objective>|clear|pause|resume].".to_owned(),
+80
Переглянути файл
@@ -1695,6 +1695,57 @@ async fn goal_commands_set_pause_resume_and_clear_through_app_server() {
}
}
#[tokio::test(flavor = "multi_thread")]
async fn memories_commands_read_toggle_and_reset_through_app_server() {
for (prompt, method, has_thread_id, expected_params, result, expected_text) in [
(
"/memories",
"thread/memory/read",
true,
json!({ "threadId": "s" }),
json!({ "summary": "Remembered: run targeted tests first." }),
"Remembered: run targeted tests first.",
),
(
"/memories show",
"thread/memory/read",
true,
json!({ "threadId": "s" }),
json!({ "summary": null }),
"No consolidated memories for this thread yet.",
),
(
"/memories on",
"thread/memoryMode/set",
true,
json!({ "threadId": "s", "mode": "enabled" }),
json!({}),
"Memory generation enabled for this thread.",
),
(
"/memories off",
"thread/memoryMode/set",
true,
json!({ "threadId": "s", "mode": "disabled" }),
json!({}),
"Memory generation disabled for this thread.",
),
("/memories reset", "memory/reset", false, Value::Null, json!({}), "Reset local Codex memories."),
] {
let (results, client, frames, _meta, _codex) =
replay_transcript(Scenario::Command(prompt), command_transcript(&[(method, result)])).await;
let session = session_of(&results, "new");
let sent = sent(&frames, method);
assert_eq!(sent.len(), 1, "{prompt}");
let mut expected = expected_params;
if has_thread_id {
expected["threadId"] = json!(session);
assert_eq!(sent[0]["params"], expected, "{prompt}");
}
assert_eq!(client.text(&session, "agent_message_chunk"), expected_text, "{prompt}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn missing_review_arguments_print_usage_without_starting_a_turn() {
for prompt in ["/review-branch", "/review-commit", "/rename", "/goal"] {
@@ -2084,6 +2135,13 @@ fn skills_become_commands_with_their_invocation_names() {
let commands = crate::config::commands_of(&update, "codex");
assert!(commands.iter().all(|c| c.source == crate::AgentCommandSource::Skill));
assert_eq!(commands[0].name, "$review");
let builtins = builtin_commands();
let goal = builtins.iter().find(|c| c.name == "goal").unwrap();
assert_eq!(goal.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["clear", "pause", "resume"]);
let memories = builtins.iter().find(|c| c.name == "memories").unwrap();
assert_eq!(memories.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["show", "on", "off", "reset"]);
let mcp = builtins.iter().find(|c| c.name == "mcp").unwrap();
assert_eq!(mcp.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["reconnect"]);
assert!(skill_commands(&json!({"data": []})).unwrap()["availableCommands"].as_array().unwrap().is_empty());
assert!(skill_commands(&json!({})).is_none());
}
@@ -2097,6 +2155,28 @@ fn workspace_roots_join_the_thread_roots() {
let mut request = json!({});
apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request);
assert!(request.get("runtimeWorkspaceRoots").is_none());
let mut mem_req = json!({});
apply_thread_config(
&json!({
"cwd": "/w/api",
"mcpServers": [],
"_meta": {
"openidea": {
"skills": { "codexOff": [["noisy", "/repo/.agents/skills/noisy/SKILL.md"]] },
"memory": {
"codexUseMemories": true,
"codexGenerateMemories": false,
"codexDeveloperInstructions": "## Memory (style)\nUse targeted selectors."
}
}
}
}),
&mut mem_req,
);
assert_eq!(mem_req["config"]["memories"], json!({ "use_memories": true, "generate_memories": false }));
assert_eq!(mem_req["config"]["developer_instructions"], "## Memory (style)\nUse targeted selectors.");
assert_eq!(mem_req["config"]["skills"]["config"][0]["enabled"], false);
}
#[tokio::test(flavor = "multi_thread")]
+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()?))
+277 -10
Переглянути файл
@@ -37,6 +37,15 @@ const DISCOVER_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(5) } else
const EARLY_CANCEL: Duration = Duration::from_secs(2);
const EXIT_GRACE: Duration = Duration::from_millis(100);
/// Copilot's configuration directory (`COPILOT_HOME`, otherwise `<home>/.copilot`).
pub(crate) fn config_dir(env: &[(String, String)], home: Option<&Path>) -> Option<PathBuf> {
env.iter()
.find(|(key, _)| key == "COPILOT_HOME")
.map(|(_, value)| PathBuf::from(value))
.or_else(|| std::env::var_os("COPILOT_HOME").map(PathBuf::from))
.or_else(|| home.map(|home| home.join(".copilot")))
}
/// Pre-session discovery result for `Shared::fetch_settings`.
pub(crate) struct Discovered {
pub commands: Vec<Value>,
@@ -462,6 +471,38 @@ fn apply_skills(params: &Value, req: &mut Value) {
}
}
/// Applies `_meta.openidea.memory` to Copilot's `session.create` / `session.resume` payload:
/// gates `store_memory` when auto-memory is `ReadOnly` or `Off`, disables custom instructions
/// when all workspace/user instructions are muted, and appends shared OpenIDEA memories.
fn apply_memory(params: &Value, req: &mut Value) {
let Some(mem) = params.pointer("/_meta/openidea/memory") else {
return;
};
if mem.get("copilotExcludeStoreMemory").and_then(Value::as_bool) == Some(true) {
let mut excluded: Vec<String> = req
.get("excludedTools")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
if !excluded.iter().any(|t| t == "store_memory") {
excluded.push("store_memory".into());
}
req["excludedTools"] = json!(excluded);
}
if mem.get("copilotDisableCustomInstructions").and_then(Value::as_bool) == Some(true) {
req["customInstructions"] = json!(false);
}
if let Some(sys) = mem.get("copilotSystemMessage").and_then(Value::as_str).filter(|s| !s.is_empty()) {
req["systemMessage"] = json!({
"mode": "append",
"content": sys,
});
}
}
fn invalid(message: impl Into<String>) -> ResponseError {
error(codes::INVALID_PARAMS, message)
}
@@ -519,9 +560,11 @@ impl CopilotShim {
"initialize" => self.initialize().await,
"session/new" => self.new_session(&params).await,
"session/load" => self.load_session(&params).await,
"session/fork" => self.fork_session(&params).await,
"session/set_config_option" => self.set_config(&params).await,
"session/prompt" => self.prompt(&params, false).await,
"_openidea/steer" => self.prompt(&params, true).await,
"_openidea/context_usage" => self.context_usage(&params).await,
"_openidea/stop_task" => self.stop_task(&params).await,
"session/close" => self.close_session(&params).await,
_ => Err(error(codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))),
@@ -536,8 +579,8 @@ impl CopilotShim {
"loadSession": true,
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
"mcpCapabilities": { "http": true, "sse": true, "stdio": true },
"sessionCapabilities": { "close": {}, "list": {} },
"_meta": { "openidea": { "steer": true, "backgroundTasks": true } },
"sessionCapabilities": { "fork": {}, "close": {}, "list": {} },
"_meta": { "openidea": { "steer": true, "backgroundTasks": true, "contextUsage": true } },
},
"agentInfo": {
"name": "copilot",
@@ -587,6 +630,7 @@ impl CopilotShim {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
apply_memory(params, &mut req);
let created = self.call("session.create", req).await?;
let session_id = created
@@ -615,6 +659,25 @@ impl CopilotShim {
async fn load_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
let session_id = str_param(params, "sessionId")?.to_owned();
let loaded = self.resume_session(params, &session_id).await?;
let actual_id = loaded.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
self.replay_history(&actual_id).await;
Ok(loaded)
}
async fn fork_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
let source = str_param(params, "sessionId")?;
let forked = self.call("sessions.fork", json!({ "sessionId": source })).await?;
let target = forked
.get("sessionId")
.and_then(Value::as_str)
.filter(|id| !id.is_empty())
.ok_or_else(|| error(codes::INTERNAL_ERROR, "Copilot fork returned no sessionId"))?
.to_owned();
self.resume_session(params, &target).await
}
async fn resume_session(self: &Arc<Self>, params: &Value, session_id: &str) -> Result<Value, ResponseError> {
let cwd = str_param(params, "cwd")?;
let catalog = self.models().await?;
let defaults = fetch_user_defaults(self.copilot(), &self.args).await;
@@ -638,9 +701,11 @@ impl CopilotShim {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
apply_memory(params, &mut req);
let resumed = self.call("session.resume", req).await?;
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(session_id).to_owned();
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": actual_id })).await {
if let Some(model_id) = current.get("modelId").or_else(|| current.get("model")).and_then(Value::as_str) {
let _ = settings.set(&catalog, MODEL, model_id);
}
@@ -651,16 +716,72 @@ impl CopilotShim {
let _ = settings.set(&catalog, CONTEXT_TIER, tier);
}
}
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
let options = models::config_options(&catalog, &settings);
self.state.lock().sessions.insert(actual_id.clone(), SessionEntry::new(settings));
self.publish_commands(&actual_id, cwd);
self.sync_usage_metrics(&actual_id);
Ok(json!({
"sessionId": actual_id,
"configOptions": options,
}))
}
async fn replay_history(&self, session_id: &str) {
let history = match self.call("session.getMessages", json!({ "sessionId": session_id })).await {
Ok(history) => history,
Err(error) => {
tracing::warn!("copilot session {session_id}: could not load history: {}", error.message);
return;
}
};
let events = history.get("events").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
let updates = {
let mut state = self.state.lock();
let Some(entry) = state.sessions.get_mut(session_id) else { return };
events
.iter()
.flat_map(|event| entry.translator.translate_history(session_id, event, None).updates)
.collect::<Vec<_>>()
};
for (target_session, update) in updates {
self.send_update(&target_session, update);
}
}
fn sync_usage_metrics(self: &Arc<Self>, session_id: &str) {
let shim = self.clone();
let sid = session_id.to_owned();
self.runtime.spawn(async move {
let Ok(metrics) = shim.call("session.usage.getMetrics", json!({ "sessionId": sid })).await else {
return;
};
let Some(nano_aiu) = metrics.get("totalNanoAiu").and_then(Value::as_f64) else {
return;
};
let catalog = shim.catalog.try_lock().ok().and_then(|g| g.clone());
let update = {
let mut st = shim.state.lock();
st.sessions.get_mut(&sid).and_then(|entry| {
entry.translator.set_total_nano_aiu(nano_aiu);
let used = entry.translator.last_used_tokens?;
let size = entry
.translator
.last_usage_snapshot
.as_ref()
.map(|s| s.token_limit)
.filter(|&s| s > 0)
.or_else(|| {
catalog.as_deref().and_then(|m| entry.settings.active_context_tokens(m)).filter(|&s| s > 0)
})?;
Some(entry.translator.usage_update(used, size))
})
};
if let Some(update) = update {
shim.send_update(&sid, update);
}
});
}
fn publish_commands(self: &Arc<Self>, session_id: &str, cwd: &str) {
let shim = self.clone();
let sid = session_id.to_owned();
@@ -735,25 +856,152 @@ impl CopilotShim {
let new_limit = next_settings.active_context_tokens(&catalog);
let options = models::config_options(&catalog, &next_settings);
{
let usage_update = {
let mut st = self.state.lock();
if let Some(entry) = st.sessions.get_mut(session_id) {
entry.settings = next_settings;
if matches!(option, MODEL | CONTEXT_TIER)
&& let (Some(used), Some(size)) = (last_used, new_limit.filter(|&s| s > 0))
{
Some(entry.translator.usage_update(used, size))
} else {
None
}
} else {
None
}
}
if matches!(option, MODEL | CONTEXT_TIER)
&& let (Some(used), Some(size)) = (last_used, new_limit.filter(|&s| s > 0))
{
self.send_update(session_id, json!({ "sessionUpdate": "usage_update", "used": used, "size": size }));
};
if let Some(update) = usage_update {
self.send_update(session_id, update);
}
Ok(json!({ "configOptions": options }))
}
async fn context_usage(&self, params: &Value) -> Result<Value, ResponseError> {
let session_id = str_param(params, "sessionId")?;
let catalog = self.models().await.ok();
let (model_id, fallback_limit, snapshot) = {
let st = self.state.lock();
let entry = st.sessions.get(session_id).ok_or_else(|| invalid(format!("unknown session {session_id}")))?;
let limit = catalog.as_deref().and_then(|models| entry.settings.active_context_tokens(models));
(entry.settings.model.clone(), limit, entry.translator.last_usage_snapshot.clone())
};
let (attr_res, metrics_res) = tokio::join!(
self.call("session.metadata.getContextAttribution", json!({ "sessionId": session_id })),
self.call("session.usage.getMetrics", json!({ "sessionId": session_id })),
);
if let Ok(metrics) = metrics_res
&& let Some(nano_aiu) = metrics.get("totalNanoAiu").and_then(Value::as_f64)
&& let Some(entry) = self.state.lock().sessions.get_mut(session_id)
{
entry.translator.set_total_nano_aiu(nano_aiu);
}
let mut usage =
attr_res.ok().and_then(|v| translate::context_usage_from_attribution(&v, &model_id, fallback_limit));
if usage.is_none()
&& !model_id.is_empty()
&& let Ok(info) = self
.call("session.metadata.contextInfo", json!({ "sessionId": session_id, "modelName": model_id }))
.await
{
usage = translate::context_usage_from_context_info(&info, &model_id, fallback_limit);
}
let usage = usage
.or_else(|| snapshot.as_ref().map(|snap| translate::context_usage_from_snapshot(snap, &model_id)))
.ok_or_else(|| error(codes::INTERNAL_ERROR, "Context details are not available yet"))?;
let meter_update = {
let mut st = self.state.lock();
st.sessions.get_mut(session_id).map(|entry| {
entry.translator.last_used_tokens = Some(usage.total_tokens);
entry.translator.usage_update(usage.total_tokens, usage.max_tokens)
})
};
if let Some(update) = meter_update {
self.send_update(session_id, update);
}
serde_json::to_value(usage).map_err(|e| error(codes::INTERNAL_ERROR, e.to_string()))
}
async fn compact_session(&self, session_id: &str, instructions: Option<&str>) -> Result<Value, ResponseError> {
let mut req = json!({
"sessionId": session_id,
"trigger": "manual",
});
if let Some(text) = instructions.map(str::trim).filter(|s| !s.is_empty()) {
req["customInstructions"] = json!(text);
}
let res = self.call("session.history.compact", req).await?;
let success = res.get("success").and_then(Value::as_bool).unwrap_or(true);
if !success {
let msg = res.get("error").and_then(Value::as_str).unwrap_or("Conversation compaction failed");
return Err(error(codes::INTERNAL_ERROR, msg));
}
let catalog = self.models().await.ok();
let meter_update = {
let mut st = self.state.lock();
st.sessions.get_mut(session_id).and_then(|entry| {
let cw = res.get("contextWindow")?;
let used = cw.get("currentTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok())?;
let fallback_limit = catalog.as_deref().and_then(|models| entry.settings.active_context_tokens(models));
let size = cw
.get("tokenLimit")
.and_then(Value::as_u64)
.and_then(|n| u32::try_from(n).ok())
.filter(|&n| n > 0)
.or(fallback_limit.filter(|&n| n > 0))?;
let u32_field = |k: &str| cw.get(k).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
entry.translator.record_snapshot(translate::UsageSnapshot {
current_tokens: used,
token_limit: size,
system_tokens: u32_field("systemTokens"),
tool_definitions_tokens: u32_field("toolDefinitionsTokens"),
conversation_tokens: u32_field("conversationTokens"),
});
Some(entry.translator.usage_update(used, size))
})
};
if let Some(update) = meter_update {
self.send_update(session_id, update);
}
let tokens_removed = res.get("tokensRemoved").and_then(Value::as_u64).unwrap_or(0);
let messages_removed = res.get("messagesRemoved").and_then(Value::as_u64).unwrap_or(0);
let summary = if tokens_removed > 0 || messages_removed > 0 {
format!("Compacted conversation ({tokens_removed} tokens, {messages_removed} messages removed).")
} else {
"Conversation compacted.".to_owned()
};
self.send_update(
session_id,
json!({ "sessionUpdate": "agent_message_chunk", "content": { "type": "text", "text": summary } }),
);
if let Some(entry) = self.state.lock().sessions.get_mut(session_id) {
entry.early_cancel = None;
}
Ok(json!({ "stopReason": "end_turn" }))
}
async fn prompt(&self, params: &Value, steer: bool) -> Result<Value, ResponseError> {
let session_id = str_param(params, "sessionId")?.to_owned();
let blocks = params.get("prompt").and_then(Value::as_array).ok_or_else(|| invalid("missing prompt"))?;
let (text, attachments, temp_files) = build_prompt_payload(&session_id, blocks);
if !steer
&& attachments.is_empty()
&& let Some(instructions) = parse_compact_command(&text)
{
cleanup_files(&temp_files);
return self.compact_session(&session_id, instructions).await;
}
if steer {
let (is_running, main_busy) = {
let st = self.state.lock();
@@ -1070,6 +1318,21 @@ impl CopilotShim {
}
}
fn parse_compact_command(text: &str) -> Option<Option<&str>> {
let trimmed = text.trim();
if trimmed == "/compact" {
return Some(None);
}
let rest = trimmed.strip_prefix("/compact")?;
let first = rest.chars().next()?;
if first.is_whitespace() {
let focus = rest.trim();
Some((!focus.is_empty()).then_some(focus))
} else {
None
}
}
fn build_prompt_payload(session_id: &str, blocks: &[Value]) -> (String, Vec<Value>, Vec<PathBuf>) {
let mut text_parts = Vec::new();
let mut attachments = Vec::new();
@@ -1109,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);
}
+479
Переглянути файл
@@ -1,6 +1,11 @@
use super::models::{self, CONTEXT_TIER, EFFORT, MODEL, Mode, Settings, UserDefaults};
use super::translate::{
self, EventTranslator, UsageSnapshot, context_usage_from_attribution, context_usage_from_context_info,
context_usage_from_snapshot,
};
use super::{acp_args, acp_fallback_spec, attach, headless_args};
use crate::config;
use crate::model::{AgentContextCategory, AgentContextUsage};
use crate::provider::Driver;
use ide_jsonrpc::{Framing, Handler, Peer, codes};
use parking_lot::Mutex;
@@ -110,6 +115,18 @@ fn sample_price_units() -> Value {
})
}
#[test]
fn resolves_copilot_home_from_agent_env_or_user_home() {
let home = std::path::Path::new("/home/test");
assert_eq!(
super::config_dir(&[("COPILOT_HOME".into(), "/custom/copilot".into())], Some(home)).as_deref(),
Some(std::path::Path::new("/custom/copilot"))
);
if std::env::var_os("COPILOT_HOME").is_none() {
assert_eq!(super::config_dir(&[], Some(home)), Some(home.join(".copilot")));
}
}
#[test]
fn parses_an_enabled_auto_only_catalog() {
let list = json!({
@@ -429,6 +446,39 @@ impl Handler for FakeCopilotServer {
"skills.discover" => Ok(json!({ "skills": [] })),
"session.create" => Ok(json!({ "sessionId": "cop-sess-1" })),
"session.resume" => Ok(json!({ "sessionId": params["sessionId"] })),
"sessions.fork" => Ok(json!({ "sessionId": "cop-sess-fork" })),
"session.getMessages" => Ok(json!({
"events": [
{
"type": "user.message",
"data": { "content": "Fix the parser" }
},
{
"type": "assistant.message",
"data": {
"messageId": "history-message",
"reasoningText": "Inspect the grammar first.",
"content": "I fixed the parser."
}
},
{
"type": "tool.execution_start",
"data": {
"toolCallId": "history-tool",
"toolName": "view",
"arguments": { "path": "/tmp/parser.rs" }
}
},
{
"type": "tool.execution_complete",
"data": {
"toolCallId": "history-tool",
"success": true,
"result": { "content": "fn parse() {}" }
}
}
]
})),
"session.model.getCurrent" => Ok(json!({ "modelId": "gemini-4-carbon" })),
"session.model.switchTo" => Ok(json!({ "modelId": params["modelId"] })),
"session.mode.set" => Ok(json!({})),
@@ -443,6 +493,38 @@ impl Handler for FakeCopilotServer {
] })),
"session.tasks.cancel" => Ok(json!({ "cancelled": true })),
"session.abort" => Ok(json!({})),
"session.usage.getMetrics" => Ok(json!({
"totalNanoAiu": 4_211_400_000_000.0,
"totalPremiumRequestCost": 12.0,
})),
"session.metadata.getContextAttribution" => Ok(json!({
"contextAttribution": {
"totalTokens": 405_200,
"limit": 1_000_000,
"promptTokenLimit": 936_000,
"bufferTokens": 64_000,
"compactionThreshold": 800_000,
"modelId": "gemini-4-carbon",
"entries": [
{ "kind": "system", "id": "system:root", "label": "System", "tokens": 223_000 },
{ "kind": "system", "id": "system:prompt", "label": "System Prompt", "tokens": 20_000, "parentId": "system:root" },
{ "kind": "toolDefinition", "id": "toolDefinition:bash", "label": "bash", "tokens": 203_000, "parentId": "system:root" },
{ "kind": "tool", "id": "tool:bash", "label": "bash", "tokens": 69_000 }
]
}
})),
"session.history.compact" => Ok(json!({
"success": true,
"tokensRemoved": 250_000,
"messagesRemoved": 12,
"contextWindow": {
"currentTokens": 155_200,
"tokenLimit": 1_000_000,
"systemTokens": 20_000,
"toolDefinitionsTokens": 100_000,
"conversationTokens": 35_200
}
})),
"session.send" if self.background_shell => {
if let Some(peer) = self.peer.get().cloned() {
let sid = params["sessionId"].as_str().unwrap_or("cop-sess-1").to_owned();
@@ -637,6 +719,81 @@ async fn shim_creates_session_with_copilot_defaults_switches_tiers_and_streams_t
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shim_loads_and_replays_copilot_history() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates.clone(), move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let init: Value = client.request("initialize", json!({}), None).await.unwrap();
assert!(init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object());
let loaded: Value = client
.request("session/load", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
.await
.unwrap();
assert_eq!(loaded["sessionId"], "cop-sess-1");
assert!(
server
.calls
.lock()
.iter()
.any(|(method, params)| { method == "session.getMessages" && params["sessionId"] == "cop-sess-1" })
);
let seen = updates.0.lock();
assert!(
seen.iter().any(|u| u["sessionUpdate"] == "user_message_chunk" && u["content"]["text"] == "Fix the parser")
);
assert!(
seen.iter().any(
|u| u["sessionUpdate"] == "agent_thought_chunk" && u["content"]["text"] == "Inspect the grammar first."
)
);
assert!(
seen.iter()
.any(|u| u["sessionUpdate"] == "agent_message_chunk" && u["content"]["text"] == "I fixed the parser.")
);
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call" && u["toolCallId"] == "history-tool"));
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call_update" && u["toolCallId"] == "history-tool"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shim_forks_copilot_sessions_and_resumes_the_new_id() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates, move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
let forked: Value = client
.request("session/fork", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
.await
.unwrap();
assert_eq!(forked["sessionId"], "cop-sess-fork");
let calls = server.calls.lock();
assert!(calls.iter().any(|(method, params)| method == "sessions.fork" && params["sessionId"] == "cop-sess-1"));
assert!(calls.iter().any(|(method, params)| method == "session.resume" && params["sessionId"] == "cop-sess-fork"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shim_forwards_disabled_mcp_servers_on_create_and_resume() {
let server =
@@ -795,3 +952,325 @@ async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skil
assert!(params.get("enableConfigDiscovery").is_none(), "{method} must not auto-enable workspace MCP discovery");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn session_new_and_load_apply_copilot_memory_gating_and_system_message() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates, move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
let meta = json!({
"openidea": {
"memory": {
"autoMemory": "readOnly",
"copilotExcludeStoreMemory": true,
"copilotDisableCustomInstructions": true,
"copilotSystemMessage": "## Memory (shared)\nRun targeted tests."
}
}
});
let _: Value =
client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [], "_meta": meta }), None).await.unwrap();
let _: Value = client
.request(
"session/load",
json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [], "_meta": meta }),
None,
)
.await
.unwrap();
let calls = server.calls.lock();
for method in ["session.create", "session.resume"] {
let params = calls.iter().find_map(|(m, p)| (m == method).then_some(p)).expect(method);
assert_eq!(params["excludedTools"], json!(["store_memory"]), "{method}: {params}");
assert_eq!(params["customInstructions"], json!(false), "{method}: {params}");
assert_eq!(
params["systemMessage"],
json!({ "mode": "append", "content": "## Memory (shared)\nRun targeted tests." }),
"{method}: {params}"
);
}
}
#[test]
fn translates_context_attribution_without_double_counting_parent_rollups() {
let payload = json!({
"contextAttribution": {
"totalTokens": 405_200,
"limit": 1_000_000,
"bufferTokens": 64_000,
"compactionThreshold": 800_000,
"modelId": "gemini-4-carbon",
"entries": [
{ "kind": "system", "id": "system:root", "label": "System", "tokens": 223_000 },
{ "kind": "system", "id": "system:prompt", "label": "System Prompt", "tokens": 20_000, "parentId": "system:root" },
{ "kind": "toolDefinition", "id": "toolDefinition:bash", "label": "bash", "tokens": 120_000, "parentId": "system:root" },
{ "kind": "toolDefinition", "id": "toolDefinition:view", "label": "view", "tokens": 83_000, "parentId": "system:root" },
{ "kind": "tool", "id": "tool:bash", "label": "bash", "tokens": 69_000 },
{ "kind": "plugin", "id": "plugin:git", "label": "git", "tokens": 5_000 },
{ "kind": "skill", "id": "skill:pr", "label": "pr", "tokens": 5_000, "parentId": "plugin:git" }
]
}
});
let usage = context_usage_from_attribution(&payload, "fallback", None).unwrap();
assert_eq!(usage.total_tokens, 405_200);
assert_eq!(usage.max_tokens, 1_000_000);
assert_eq!(usage.reserved_tokens, Some(64_000));
assert_eq!(usage.auto_compact_threshold, Some(800_000));
assert_eq!(usage.is_auto_compact_enabled, Some(true));
assert_eq!(
usage.categories,
vec![
AgentContextCategory {
name: "System prompt".into(),
tokens: 20_000,
kind: Some("used".into()),
group: Some("System".into()),
},
AgentContextCategory {
name: "Tool Definitions".into(),
tokens: 203_000,
kind: Some("used".into()),
group: Some("System".into()),
},
AgentContextCategory {
name: "Tool Results".into(),
tokens: 69_000,
kind: Some("used".into()),
group: Some("User Context".into()),
},
AgentContextCategory {
name: "Messages".into(),
tokens: 108_200,
kind: Some("used".into()),
group: Some("User Context".into()),
},
AgentContextCategory {
name: "Skills".into(),
tokens: 5_000,
kind: Some("used".into()),
group: Some("User Context".into()),
},
AgentContextCategory { name: "Free space".into(), tokens: 530_800, kind: Some("free".into()), group: None },
]
);
}
#[test]
fn translates_context_info_and_usage_snapshot_fallbacks() {
let info = json!({
"contextInfo": {
"modelName": "claude-sonnet-4.5",
"systemTokens": 12_000,
"toolDefinitionsTokens": 48_000,
"conversationTokens": 40_000,
"totalTokens": 100_000,
"limit": 200_000,
"bufferTokens": 20_000,
"compactionThreshold": 160_000
}
});
let from_info = context_usage_from_context_info(&info, "fallback", None).unwrap();
assert_eq!(from_info.reserved_tokens, Some(20_000));
assert_eq!(
from_info.categories.iter().map(|c| (c.name.as_str(), c.tokens, c.group.as_deref())).collect::<Vec<_>>(),
vec![
("System prompt", 12_000, Some("System")),
("Tool Definitions", 48_000, Some("System")),
("Messages", 40_000, Some("User Context")),
("Free space", 80_000, None),
]
);
let from_snap = context_usage_from_snapshot(
&UsageSnapshot {
current_tokens: 50_000,
token_limit: 200_000,
system_tokens: Some(10_000),
tool_definitions_tokens: Some(25_000),
conversation_tokens: Some(15_000),
},
"gpt-5.6-sol",
);
assert_eq!(from_snap.total_tokens, 50_000);
assert_eq!(from_snap.max_tokens, 200_000);
assert_eq!(from_snap.categories.len(), 4);
}
#[test]
fn accumulates_copilot_credits_across_turns_subagents_and_compaction() {
let mut tr = EventTranslator::default();
let first = tr.translate(
"s1",
&json!({
"type": "session.usage_info",
"data": { "currentTokens": 40_000, "tokenLimit": 200_000, "systemTokens": 10_000, "toolDefinitionsTokens": 20_000, "conversationTokens": 10_000 }
}),
Some(200_000),
);
assert_eq!(first.updates[0].1["used"], 40_000);
assert!(first.updates[0].1.get("cost").is_none());
// Main-agent usage reports 1.5 credits; subagent usage adds 0.5 credits -> 2.0 credits total.
let main_usage = tr.translate(
"s1",
&json!({
"type": "assistant.usage",
"data": { "inputTokens": 45_000, "copilotUsage": { "totalNanoAiu": 1_500_000_000.0 } }
}),
Some(200_000),
);
assert_eq!(main_usage.updates[0].1["cost"]["currency"], "credits");
assert!((main_usage.updates[0].1["cost"]["amount"].as_f64().unwrap() - 1.5).abs() < 1e-6);
let sub_usage = tr.translate(
"s1",
&json!({
"type": "assistant.usage",
"agentId": "sub-1",
"data": { "inputTokens": 12_000, "copilotUsage": { "totalNanoAiu": 500_000_000.0 } }
}),
Some(200_000),
);
assert_eq!(sub_usage.updates[0].1["used"], 45_000);
assert!((sub_usage.updates[0].1["cost"]["amount"].as_f64().unwrap() - 2.0).abs() < 1e-6);
// Compaction updates token count while keeping accumulated credits.
let compacted = tr.translate(
"s1",
&json!({
"type": "session.compaction_complete",
"data": { "success": true, "postCompactionTokens": 22_000, "tokenLimit": 200_000 }
}),
Some(200_000),
);
assert_eq!(compacted.updates[0].1["used"], 22_000);
assert!((compacted.updates[0].1["cost"]["amount"].as_f64().unwrap() - 2.0).abs() < 1e-6);
}
#[test]
fn available_commands_includes_compact_when_omitted_by_server() {
let cmds = translate::available_commands(Some(&json!({ "commands": [{ "name": "review" }] })), None);
assert!(cmds.iter().any(|c| c["name"] == "compact"));
assert!(cmds.iter().any(|c| c["name"] == "review"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn context_usage_rpc_and_compact_command_work_end_to_end() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates.clone(), move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let init: Value = client.request("initialize", json!({}), None).await.unwrap();
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"]["contextUsage"], true);
let _: Value = client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [] }), None).await.unwrap();
let ctx: AgentContextUsage =
client.request("_openidea/context_usage", json!({ "sessionId": "cop-sess-1" }), None).await.unwrap();
assert_eq!(ctx.total_tokens, 405_200);
assert_eq!(ctx.max_tokens, 1_000_000);
assert_eq!(ctx.reserved_tokens, Some(64_000));
assert!(ctx.categories.iter().any(|c| c.name == "System prompt" && c.group.as_deref() == Some("System")));
assert!(ctx.categories.iter().any(|c| c.name == "Tool Definitions" && c.group.as_deref() == Some("System")));
assert!(ctx.categories.iter().any(|c| c.name == "Tool Results" && c.group.as_deref() == Some("User Context")));
assert!(ctx.categories.iter().any(|c| c.name == "Messages" && c.group.as_deref() == Some("User Context")));
// Syncing metrics updated usage_update with credits cost.
tokio::time::sleep(Duration::from_millis(20)).await;
assert!(updates.0.lock().iter().any(|u| {
u["sessionUpdate"] == "usage_update"
&& u["used"] == 405_200
&& u["cost"]["currency"] == "credits"
&& (u["cost"]["amount"].as_f64().unwrap_or(0.0) - 4211.4).abs() < 0.01
}));
// `/compact` invokes `session.history.compact` instead of `session.send`.
let res: Value = client
.request(
"session/prompt",
json!({ "sessionId": "cop-sess-1", "prompt": [{ "type": "text", "text": "/compact keep PR notes" }] }),
None,
)
.await
.unwrap();
assert_eq!(res["stopReason"], "end_turn");
assert!(server.calls.lock().iter().any(|(m, p)| {
m == "session.history.compact"
&& p["sessionId"] == "cop-sess-1"
&& p["trigger"] == "manual"
&& p["customInstructions"] == "keep PR notes"
}));
tokio::time::sleep(Duration::from_millis(20)).await;
assert!(updates.0.lock().iter().any(|u| u["sessionUpdate"] == "usage_update" && u["used"] == 155_200));
}
#[test]
fn available_commands_preserves_input_choices() {
let cmds = json!({
"commands": [
{
"name": "skills",
"description": "Manage skills for enhanced capabilities",
"input": {
"hint": "[list|info|reload]",
"choices": [
{ "name": "list", "description": "List all available skills" },
{ "name": "info", "description": "Show details for a skill" },
{ "name": "INFO", "description": "Duplicate ignored" },
{ "name": "", "description": "Empty ignored" },
{ "name": "reload", "description": "Reload skills from disk" }
]
}
},
{
"name": "subconscious",
"description": "Manage memory",
"input": {
"choices": [{ "name": "run", "description": "Consolidate now" }]
}
}
]
});
let list = super::translate::available_commands(Some(&cmds), None);
let parsed = crate::config::commands_of(&json!({ "availableCommands": list }), "copilot");
// Then the built-in /compact.
assert_eq!(parsed.len(), 3);
assert_eq!(parsed[2].name, "compact");
assert_eq!(parsed[0].name, "skills");
assert_eq!(parsed[0].hint.as_deref(), Some("[list|info|reload]"));
assert_eq!(
parsed[0].choices,
vec![
crate::AgentCommandChoice { name: "list".into(), description: "List all available skills".into() },
crate::AgentCommandChoice { name: "info".into(), description: "Show details for a skill".into() },
crate::AgentCommandChoice { name: "reload".into(), description: "Reload skills from disk".into() },
]
);
assert_eq!(parsed[1].name, "subconscious");
assert_eq!(parsed[1].hint, None);
assert_eq!(
parsed[1].choices,
vec![crate::AgentCommandChoice { name: "run".into(), description: "Consolidate now".into() }]
);
}
+413 -20
Переглянути файл
@@ -2,11 +2,22 @@
//! permissions, slash commands, MCP servers) and ACP v1.
use crate::LIMITS_UPDATE;
use crate::model::{AgentContextCategory, AgentContextUsage};
use serde_json::{Map, Value, json};
use std::collections::{HashMap, HashSet};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::Path;
const MAX_OUTPUT: usize = 64 * 1024;
const NANO_AIU_PER_CREDIT: f64 = 1_000_000_000.0;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct UsageSnapshot {
pub current_tokens: u32,
pub token_limit: u32,
pub system_tokens: Option<u32>,
pub tool_definitions_tokens: Option<u32>,
pub conversation_tokens: Option<u32>,
}
#[derive(Default)]
pub(super) struct EventTranslator {
@@ -18,6 +29,11 @@ pub(super) struct EventTranslator {
subagents: HashMap<String, String>,
/// Last reported prompt token count, used when updating context size.
pub last_used_tokens: Option<u32>,
/// Last reported `session.usage_info` / compaction breakdown, used as fallback when RPC metadata is absent.
pub last_usage_snapshot: Option<UsageSnapshot>,
/// Accumulated session AI-credit spend in nano-AIU (across main agent and subagents).
total_nano_aiu: f64,
has_nano_aiu: bool,
}
#[derive(Clone, Debug)]
@@ -46,6 +62,29 @@ impl EventTranslator {
self.streamed_messages.clear();
}
pub fn set_total_nano_aiu(&mut self, nano_aiu: f64) {
if nano_aiu.is_finite() && nano_aiu > 0.0 {
self.total_nano_aiu = nano_aiu;
self.has_nano_aiu = true;
}
}
pub fn record_snapshot(&mut self, snapshot: UsageSnapshot) {
self.last_used_tokens = Some(snapshot.current_tokens);
self.last_usage_snapshot = Some(snapshot);
}
pub fn usage_update(&self, used: u32, size: u32) -> Value {
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
if self.has_nano_aiu && self.total_nano_aiu > 0.0 {
update["cost"] = json!({
"amount": self.total_nano_aiu / NANO_AIU_PER_CREDIT,
"currency": "credits",
});
}
update
}
pub fn translate(&mut self, main_session: &str, event: &Value, fallback_limit: Option<u32>) -> Translated {
let mut out = Translated { updates: Vec::new(), terminal: None };
let event_type = str_of(event, "type").unwrap_or_default();
@@ -239,36 +278,75 @@ impl EventTranslator {
}
}
"session.usage_info" => {
let used = data.get("currentTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
let limit = data
.get("tokenLimit")
.and_then(Value::as_u64)
.and_then(|n| u32::try_from(n).ok())
.filter(|&n| n > 0)
.or(fallback_limit);
let used = u32_of(data, "currentTokens");
let limit = u32_of(data, "tokenLimit").filter(|&n| n > 0).or(fallback_limit);
if let (Some(used), Some(size)) = (used, limit) {
self.last_used_tokens = Some(used);
out.updates.push((
main_session.to_owned(),
json!({ "sessionUpdate": "usage_update", "used": used, "size": size }),
));
self.record_snapshot(UsageSnapshot {
current_tokens: used,
token_limit: size,
system_tokens: u32_of(data, "systemTokens"),
tool_definitions_tokens: u32_of(data, "toolDefinitionsTokens"),
conversation_tokens: u32_of(data, "conversationTokens"),
});
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
}
}
"assistant.usage" => {
let added_credits = data
.pointer("/copilotUsage/totalNanoAiu")
.and_then(Value::as_f64)
.filter(|n| n.is_finite() && *n > 0.0);
if let Some(nano_aiu) = added_credits {
self.total_nano_aiu += nano_aiu;
self.has_nano_aiu = true;
}
if agent_id.is_none() {
let used = data.get("inputTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
if let (Some(used), Some(size)) = (used, fallback_limit.filter(|&s| s > 0)) {
let used = u32_of(data, "inputTokens").or(self.last_used_tokens);
let size = self
.last_usage_snapshot
.as_ref()
.map(|s| s.token_limit)
.filter(|&s| s > 0)
.or(fallback_limit.filter(|&s| s > 0));
if let (Some(used), Some(size)) = (used, size) {
self.last_used_tokens = Some(used);
out.updates.push((
main_session.to_owned(),
json!({ "sessionUpdate": "usage_update", "used": used, "size": size }),
));
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
}
} else if added_credits.is_some()
&& let (Some(used), Some(size)) = (
self.last_used_tokens,
self.last_usage_snapshot
.as_ref()
.map(|s| s.token_limit)
.filter(|&s| s > 0)
.or(fallback_limit.filter(|&s| s > 0)),
)
{
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
}
if let Some(limits) = quota_limits(data.get("quotaSnapshots")) {
out.updates.push((main_session.to_owned(), limits));
}
}
"session.compaction_complete" if agent_id.is_none() => {
if data.get("success").and_then(Value::as_bool) == Some(true) {
let used = u32_of(data, "postCompactionTokens");
let size = u32_of(data, "tokenLimit")
.filter(|&n| n > 0)
.or_else(|| self.last_usage_snapshot.as_ref().map(|s| s.token_limit).filter(|&n| n > 0))
.or(fallback_limit.filter(|&n| n > 0));
if let (Some(used), Some(size)) = (used, size) {
self.record_snapshot(UsageSnapshot {
current_tokens: used,
token_limit: size,
system_tokens: u32_of(data, "systemTokens"),
tool_definitions_tokens: u32_of(data, "toolDefinitionsTokens"),
conversation_tokens: u32_of(data, "conversationTokens"),
});
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
}
}
}
"session.idle" if agent_id.is_none() => {
let mode = str_of(data, "mode").unwrap_or_default();
if mode != "autopilot" {
@@ -292,6 +370,55 @@ impl EventTranslator {
}
out
}
/// Translates one persisted Copilot event returned by `session.getMessages`. The live
/// event stream omits historical user messages and emits reasoning deltas, while the
/// persisted form has complete user and assistant messages.
pub fn translate_history(&mut self, main_session: &str, event: &Value, fallback_limit: Option<u32>) -> Translated {
let event_type = str_of(event, "type").unwrap_or_default();
let data = event.get("data").unwrap_or(&Value::Null);
if event_type == "user.message" {
let Some(text) = str_of(data, "content").map(str::trim).filter(|text| !text.is_empty()) else {
return Translated { updates: Vec::new(), terminal: None };
};
let target_session = str_of(event, "agentId")
.filter(|id| !id.is_empty())
.map(|id| format!("{main_session}:sub:{id}"))
.unwrap_or_else(|| main_session.to_owned());
return Translated {
updates: vec![(
target_session,
json!({
"sessionUpdate": "user_message_chunk",
"content": { "type": "text", "text": text },
}),
)],
terminal: None,
};
}
let mut translated = self.translate(main_session, event, fallback_limit);
if event_type == "assistant.message"
&& !(data.get("parentToolCallId").and_then(Value::as_str).is_some() && str_of(event, "agentId").is_none())
&& let Some(reasoning) = str_of(data, "reasoningText").map(str::trim).filter(|text| !text.is_empty())
{
let target_session = str_of(event, "agentId")
.filter(|id| !id.is_empty())
.map(|id| format!("{main_session}:sub:{id}"))
.unwrap_or_else(|| main_session.to_owned());
translated.updates.insert(
0,
(
target_session,
json!({
"sessionUpdate": "agent_thought_chunk",
"content": { "type": "text", "text": reasoning },
}),
),
);
}
translated
}
}
fn describe_tool(name: &str, args: &Value) -> ToolInfo {
@@ -542,11 +669,34 @@ pub(super) fn available_commands(commands_res: Option<&Value>, skills_res: Optio
continue;
}
let hint = cmd.pointer("/input/hint").and_then(Value::as_str).filter(|h| !h.is_empty());
let mut seen_choices = HashSet::new();
let choices: Vec<Value> = cmd
.pointer("/input/choices")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|ch| {
let choice_name = str_of(ch, "name").map(str::trim).filter(|n| !n.is_empty())?;
if !seen_choices.insert(choice_name.to_ascii_lowercase()) {
return None;
}
Some(json!({
"name": choice_name,
"description": str_of(ch, "description").unwrap_or_default(),
}))
})
.collect();
let input = match (hint, choices.is_empty()) {
(Some(h), false) => Some(json!({ "hint": h, "choices": choices })),
(Some(h), true) => Some(json!({ "hint": h })),
(None, false) => Some(json!({ "choices": choices })),
(None, true) => None,
};
out.push(json!({
"name": name,
"description": str_of(cmd, "description").unwrap_or_default(),
"source": "command",
"input": hint.map(|h| json!({ "hint": h })),
"input": input,
}));
}
for skill in skills_res.and_then(|v| v.get("skills")).and_then(Value::as_array).into_iter().flatten() {
@@ -573,9 +723,252 @@ pub(super) fn available_commands(commands_res: Option<&Value>, skills_res: Optio
"input": hint.map(|h| json!({ "hint": h })),
}));
}
if seen.insert("compact".to_owned()) {
out.push(json!({
"name": "compact",
"description": "Compact conversation history to free context window space",
"source": "command",
"input": { "hint": "optional focus instructions" },
}));
}
out
}
/// Converts Copilot's `session.metadata.getContextAttribution` payload into [`AgentContextUsage`],
/// grouping items into `System` (`System prompt`, `Tool Definitions`, …) and `User Context`
/// (`Tool Results`, `Messages`, `Skills`, …) without double-counting parent rollup entries.
pub(super) fn context_usage_from_attribution(
res: &Value,
fallback_model: &str,
fallback_limit: Option<u32>,
) -> Option<AgentContextUsage> {
let attr = res.get("contextAttribution").unwrap_or(res);
if !attr.is_object() {
return None;
}
let total_tokens = u32_of(attr, "totalTokens")?;
let max_tokens = u32_of(attr, "limit")
.filter(|&n| n > 0)
.or_else(|| u32_of(attr, "promptTokenLimit").filter(|&n| n > 0))
.or_else(|| fallback_limit.filter(|&n| n > 0))?;
let reserved_tokens = u32_of(attr, "bufferTokens").filter(|&n| n > 0);
let model = str_of(attr, "modelId").filter(|s| !s.is_empty()).unwrap_or(fallback_model).to_owned();
let auto_compact_threshold = u32_of(attr, "compactionThreshold").filter(|&n| n > 0);
let is_auto_compact_enabled = auto_compact_threshold.map(|_| true);
let mut categories = Vec::new();
let entries = attr.get("entries").and_then(Value::as_array).filter(|e| !e.is_empty());
if let Some(entries) = entries {
// Any entry referenced via `parentId` is a rollup parent whose children are accounted for individually.
let parent_ids: HashSet<&str> = entries.iter().filter_map(|e| str_of(e, "parentId")).collect();
let mut system_rows: Vec<(String, u32)> = Vec::new();
let mut tool_definitions: u32 = 0;
let mut tool_results: u32 = 0;
let mut skills: u32 = 0;
let mut subagents: u32 = 0;
let mut mcp_tools: u32 = 0;
let mut plugins: u32 = 0;
let mut other_user: BTreeMap<String, u32> = BTreeMap::new();
let mut accounted: u32 = 0;
for entry in entries {
if let Some(id) = str_of(entry, "id")
&& parent_ids.contains(id)
{
continue;
}
let tokens = u32_of(entry, "tokens").unwrap_or(0);
if tokens == 0 {
continue;
}
accounted = accounted.saturating_add(tokens);
match str_of(entry, "kind").unwrap_or_default() {
"system" => {
let label = normalize_system_label(str_of(entry, "label").unwrap_or("System prompt"));
if let Some((_, existing)) = system_rows.iter_mut().find(|(k, _)| k == &label) {
*existing = existing.saturating_add(tokens);
} else {
system_rows.push((label, tokens));
}
}
"toolDefinition" => tool_definitions = tool_definitions.saturating_add(tokens),
"tool" => tool_results = tool_results.saturating_add(tokens),
"skill" => skills = skills.saturating_add(tokens),
"subagent" => subagents = subagents.saturating_add(tokens),
"mcpServer" => mcp_tools = mcp_tools.saturating_add(tokens),
"plugin" => plugins = plugins.saturating_add(tokens),
kind => {
let label = str_of(entry, "label").filter(|s| !s.is_empty()).unwrap_or(kind).to_owned();
let slot = other_user.entry(label).or_insert(0);
*slot = slot.saturating_add(tokens);
}
}
}
for (name, tokens) in system_rows {
categories.push(used_category(name, tokens, "System"));
}
if tool_definitions > 0 {
categories.push(used_category("Tool Definitions", tool_definitions, "System"));
}
if tool_results > 0 {
categories.push(used_category("Tool Results", tool_results, "User Context"));
}
let messages = total_tokens.saturating_sub(accounted);
if messages > 0 {
categories.push(used_category("Messages", messages, "User Context"));
}
if skills > 0 {
categories.push(used_category("Skills", skills, "User Context"));
}
if subagents > 0 {
categories.push(used_category("Sub-agents", subagents, "User Context"));
}
if mcp_tools > 0 {
categories.push(used_category("MCP tools", mcp_tools, "User Context"));
}
if plugins > 0 {
categories.push(used_category("Plugins", plugins, "User Context"));
}
for (name, tokens) in other_user {
categories.push(used_category(name, tokens, "User Context"));
}
} else if let Some(cats) = attr.get("categories").and_then(Value::as_object) {
let get = |k: &str| cats.get(k).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok()).unwrap_or(0);
let sys_prompt = get("systemPrompt");
let custom_inst = get("customInstructions");
let tool_defs = get("systemTools").saturating_add(get("mcpTools"));
let messages = get("messages");
if sys_prompt > 0 {
categories.push(used_category("System prompt", sys_prompt, "System"));
}
if custom_inst > 0 {
categories.push(used_category("Custom instructions", custom_inst, "System"));
}
if tool_defs > 0 {
categories.push(used_category("Tool Definitions", tool_defs, "System"));
}
if messages > 0 {
categories.push(used_category("Messages", messages, "User Context"));
}
}
push_free_space(&mut categories, total_tokens, max_tokens, reserved_tokens);
Some(AgentContextUsage {
categories,
total_tokens,
max_tokens,
model,
is_auto_compact_enabled,
auto_compact_threshold,
reserved_tokens,
})
}
/// Converts Copilot's `session.metadata.contextInfo` payload into [`AgentContextUsage`].
pub(super) fn context_usage_from_context_info(
res: &Value,
fallback_model: &str,
fallback_limit: Option<u32>,
) -> Option<AgentContextUsage> {
let info = res.get("contextInfo").unwrap_or(res);
if !info.is_object() {
return None;
}
let total_tokens = u32_of(info, "totalTokens")?;
let max_tokens = u32_of(info, "limit")
.filter(|&n| n > 0)
.or_else(|| u32_of(info, "promptTokenLimit").filter(|&n| n > 0))
.or_else(|| fallback_limit.filter(|&n| n > 0))?;
let reserved_tokens = u32_of(info, "bufferTokens").filter(|&n| n > 0);
let model = str_of(info, "displayModelName")
.or_else(|| str_of(info, "modelName"))
.filter(|s| !s.is_empty())
.unwrap_or(fallback_model)
.to_owned();
let auto_compact_threshold = u32_of(info, "compactionThreshold").filter(|&n| n > 0);
let is_auto_compact_enabled = auto_compact_threshold.map(|_| true);
let mut categories = Vec::new();
if let Some(sys) = u32_of(info, "systemTokens").filter(|&n| n > 0) {
categories.push(used_category("System prompt", sys, "System"));
}
if let Some(tools) = u32_of(info, "toolDefinitionsTokens").filter(|&n| n > 0) {
categories.push(used_category("Tool Definitions", tools, "System"));
}
if let Some(conv) = u32_of(info, "conversationTokens").filter(|&n| n > 0) {
categories.push(used_category("Messages", conv, "User Context"));
}
push_free_space(&mut categories, total_tokens, max_tokens, reserved_tokens);
Some(AgentContextUsage {
categories,
total_tokens,
max_tokens,
model,
is_auto_compact_enabled,
auto_compact_threshold,
reserved_tokens,
})
}
/// Fallback breakdown from the latest `session.usage_info` / compaction snapshot.
pub(super) fn context_usage_from_snapshot(snap: &UsageSnapshot, model: &str) -> AgentContextUsage {
let mut categories = Vec::new();
if let Some(sys) = snap.system_tokens.filter(|&n| n > 0) {
categories.push(used_category("System prompt", sys, "System"));
}
if let Some(tools) = snap.tool_definitions_tokens.filter(|&n| n > 0) {
categories.push(used_category("Tool Definitions", tools, "System"));
}
if let Some(conv) = snap.conversation_tokens.filter(|&n| n > 0) {
categories.push(used_category("Messages", conv, "User Context"));
}
push_free_space(&mut categories, snap.current_tokens, snap.token_limit, None);
AgentContextUsage {
categories,
total_tokens: snap.current_tokens,
max_tokens: snap.token_limit,
model: model.to_owned(),
is_auto_compact_enabled: None,
auto_compact_threshold: None,
reserved_tokens: None,
}
}
fn used_category(name: impl Into<String>, tokens: u32, group: &str) -> AgentContextCategory {
AgentContextCategory { name: name.into(), tokens, kind: Some("used".to_owned()), group: Some(group.to_owned()) }
}
fn push_free_space(
categories: &mut Vec<AgentContextCategory>,
total_tokens: u32,
max_tokens: u32,
reserved_tokens: Option<u32>,
) {
let free = max_tokens.saturating_sub(total_tokens.saturating_add(reserved_tokens.unwrap_or(0)));
if free > 0 {
categories.push(AgentContextCategory {
name: "Free space".to_owned(),
tokens: free,
kind: Some("free".to_owned()),
group: None,
});
}
}
fn normalize_system_label(raw: &str) -> String {
match raw.trim().to_ascii_lowercase().as_str() {
"system prompt" | "system" | "system instructions" => "System prompt".to_owned(),
"custom instructions" => "Custom instructions".to_owned(),
_ => raw.trim().to_owned(),
}
}
fn u32_of(v: &Value, key: &str) -> Option<u32> {
v.get(key).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok())
}
/// The running entries of a `session.tasks.list` result, in the background-task shape the
/// app shows (`task_id`, `task_type`, `description`).
pub(super) fn background_tasks(list: &Value) -> Vec<Value> {
+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();
+124 -6
Переглянути файл
@@ -189,6 +189,11 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
/// `github/copilot-cli` publishes standalone archives and `SHA256SUMS.txt` on every GitHub
/// release. Supplying them installs Copilot without Node.js, npm, `~/.npmrc`, or mirror lag.
fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
let sys_root = if cfg!(target_os = "linux") { Some(Path::new("/")) } else { None };
add_copilot_release_binaries_with_root(entry, release_base, sys_root);
}
fn add_copilot_release_binaries_with_root(entry: &mut Entry, release_base: &str, sys_root: Option<&Path>) {
let tag = format!("v{}", entry.version.trim_start_matches('v'));
let base = format!("{}/{}", release_base.trim_end_matches('/'), tag);
let sha256_url = format!("{base}/SHA256SUMS.txt");
@@ -196,9 +201,12 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
Some(p) => (p.args.clone(), p.env.clone()),
None => (vec!["--acp".into()], BTreeMap::new()),
};
let linux = if cfg!(target_env = "musl") { "linuxmusl" } else { "linux" };
let linux_arm = format!("copilot-{linux}-arm64.tar.gz");
let linux_x64 = format!("copilot-{linux}-x64.tar.gz");
let linux_arm = format!(
"copilot-{}-arm64.tar.gz",
sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::Arm64))
);
let linux_x64 =
format!("copilot-{}-x64.tar.gz", sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::X64)));
let targets = [
("darwin-aarch64", "copilot-darwin-arm64.tar.gz", "./copilot"),
("darwin-x86_64", "copilot-darwin-x64.tar.gz", "./copilot"),
@@ -219,6 +227,22 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
}
}
/// Picks `linux` (glibc) or `linuxmusl` from the host's runtime dynamic linker rather than
/// `cfg!(target_env = "musl")`: `openidea-server` on Linux is built as static musl so it runs
/// on every distro, while Copilot's Linux archives dynamically link glibc or musl.
fn copilot_linux_variant_at(root: &Path, arch: Arch) -> &'static str {
let (glibc_rel, musl_rel) = match arch {
Arch::Arm64 => ("lib/ld-linux-aarch64.so.1", "lib/ld-musl-aarch64.so.1"),
Arch::X64 => ("lib64/ld-linux-x86-64.so.2", "lib/ld-musl-x86_64.so.1"),
};
let glibc = root.join(glibc_rel);
let has_musl_name = |p: PathBuf| p.file_name().is_some_and(|n| n.to_string_lossy().contains("musl"));
let points_to_musl =
fs::read_link(&glibc).is_ok_and(has_musl_name) || fs::canonicalize(&glibc).is_ok_and(has_musl_name);
let has_glibc = glibc.exists() && !points_to_musl;
if !has_glibc && root.join(musl_rel).exists() { "linuxmusl" } else { "linux" }
}
fn safe_segment(s: &str) -> bool {
!s.is_empty()
&& !s.starts_with('.')
@@ -296,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.
@@ -684,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)
}
@@ -765,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"])
@@ -1304,4 +1330,96 @@ esac
assert!(npm_bin.is_file());
assert_eq!(CustomAgent::read(&p.agent_file("copilot")).unwrap().command, npm_bin.to_string_lossy());
}
#[test]
fn selects_copilot_linux_archive_from_runtime_dynamic_linker() {
let index = r#"{"agents":[
{"id":"github-copilot-cli","name":"Copilot","version":"1.0.116",
"distribution":{"npx":{"package":"@github/[email protected]","args":["--acp"]}}}
]}"#;
let archives_for = |root: &Path| -> (String, String) {
let mut entry = parse(index).unwrap().remove(0);
entry.distribution.binary.clear();
add_copilot_release_binaries_with_root(&mut entry, "https://example.invalid/releases", Some(root));
(
entry.distribution.binary["linux-x86_64"].archive.clone(),
entry.distribution.binary["linux-aarch64"].archive.clone(),
)
};
let touch = |path: PathBuf| {
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, b"").unwrap();
};
// 1. Non-FHS root (neither loader present) defaults to glibc archives.
let empty = tempfile::tempdir().unwrap();
assert_eq!(
archives_for(empty.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
)
);
// 2. Standard glibc host (and glibc host with musl-tools also installed) uses `copilot-linux-*`,
// even when `openidea-server` itself is compiled for `*-unknown-linux-musl`.
let glibc = tempfile::tempdir().unwrap();
touch(glibc.path().join("lib64/ld-linux-x86-64.so.2"));
touch(glibc.path().join("lib/ld-linux-aarch64.so.1"));
assert_eq!(
archives_for(glibc.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
)
);
touch(glibc.path().join("lib/ld-musl-x86_64.so.1"));
touch(glibc.path().join("lib/ld-musl-aarch64.so.1"));
assert_eq!(
archives_for(glibc.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
)
);
// 3. musl-only host (e.g. Alpine) uses `copilot-linuxmusl-*`.
let musl = tempfile::tempdir().unwrap();
touch(musl.path().join("lib/ld-musl-x86_64.so.1"));
touch(musl.path().join("lib/ld-musl-aarch64.so.1"));
assert_eq!(
archives_for(musl.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
)
);
// 4. Alpine `libc6-compat` / `gcompat` symlinking `ld-linux` to `ld-musl` still picks `linuxmusl`.
#[cfg(unix)]
{
fs::create_dir_all(musl.path().join("lib64")).unwrap();
std::os::unix::fs::symlink("../lib/ld-musl-x86_64.so.1", musl.path().join("lib64/ld-linux-x86-64.so.2"))
.unwrap();
std::os::unix::fs::symlink("ld-musl-aarch64.so.1", musl.path().join("lib/ld-linux-aarch64.so.1")).unwrap();
assert_eq!(
archives_for(musl.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
)
);
}
#[cfg(target_os = "linux")]
{
let parsed = parse(index).unwrap().remove(0);
let expected_x64 = format!("copilot-{}-x64.tar.gz", copilot_linux_variant_at(Path::new("/"), Arch::X64));
assert!(
parsed.distribution.binary["linux-x86_64"].archive.ends_with(&expected_x64),
"unexpected linux-x86_64 archive: {}",
parsed.distribution.binary["linux-x86_64"].archive
);
}
}
}
+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
+1 -1
Переглянути файл
@@ -32,7 +32,7 @@ pub fn widens_access(params: &Value) -> bool {
tool.and_then(|t| t.pointer("/rawInput/networkApprovalContext")).is_some_and(|c| !c.is_null())
}
fn command_from_value(val: &Value) -> Option<String> {
pub(crate) fn command_from_value(val: &Value) -> Option<String> {
match val {
Value::String(s) => {
let trimmed = s.trim();
File diff suppressed because it is too large. Load diff
+37 -82
Переглянути файл
@@ -209,6 +209,7 @@ impl Frontmatter {
source,
description: truncate(&description),
hint: self.get("argument-hint").filter(|h| !h.is_empty()).map(str::to_owned),
choices: Vec::new(),
}
}
}
@@ -274,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();
@@ -337,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);
}
}
@@ -387,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> {
@@ -543,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,
}
}
@@ -913,6 +864,7 @@ pub fn menu_commands(offered: Vec<AgentCommand>, states: &[AgentSkillState]) ->
description: state.skill.description.clone(),
hint: state.skill.hint.clone(),
source: AgentCommandSource::Skill,
choices: Vec::new(),
});
}
}
@@ -938,6 +890,7 @@ mod tests {
description: description.into(),
hint: None,
source: AgentCommandSource::Command,
choices: Vec::new(),
}
}
@@ -1067,6 +1020,8 @@ mod tests {
paths: Vec::new(),
valid: true,
warnings: Vec::new(),
plugin_id: None,
plugin_name: None,
}
}
File diff suppressed because it is too large. Load diff
+40 -2
Переглянути файл
@@ -91,6 +91,7 @@ impl Timeline {
diffs: Vec::new(),
started_ms: Some(crate::now_ms()),
ended_ms: None,
command: None,
};
let index = match self.tools.get(&id) {
Some(&i) => {
@@ -154,7 +155,7 @@ impl Timeline {
}
fn merge_tool(&mut self, index: usize, update: &Value) {
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, command, .. } =
&mut self.entries[index]
else {
return;
@@ -171,6 +172,11 @@ impl Timeline {
*ended_ms = Some(crate::now_ms());
}
}
if let Some(raw) = update.pointer("/rawInput/command").or_else(|| update.pointer("/rawInput/cmd"))
&& let Some(cmd) = crate::security::command_from_value(raw)
{
*command = Some(crate::shell_script(&cmd).unwrap_or(cmd));
}
if update.get("locations").is_some_and(Value::is_array) {
*locs = locations(update.get("locations"));
}
@@ -471,6 +477,34 @@ mod tests {
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
}
#[test]
fn an_execute_call_keeps_the_command_from_its_structured_input() {
let mut t = Timeline::default();
let command = |t: &Timeline, i: usize| match &t.entries[i] {
AgentEntry::Tool { command, .. } => command.clone(),
_ => panic!(),
};
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "a", "title": "Run command", "kind": "execute",
"rawInput": {"command": "python hello_world.py"}}));
assert_eq!(command(&t, 0).as_deref(), Some("python hello_world.py"));
// An argv array whose shell wraps the script, sent with a later update.
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "b", "title": "Run command", "kind": "execute"}));
assert_eq!(command(&t, 1), None);
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "b",
"rawInput": {"cmd": ["bash", "-lc", "cargo test -p ide-agent"]}}));
assert_eq!(command(&t, 1).as_deref(), Some("cargo test -p ide-agent"));
// One shell line, unwrapped as the permission card does.
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "kind": "execute",
"rawInput": {"command": "/bin/zsh -lc 'node hello.js'"}}));
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
// A later update without one keeps it; tasks saved before the field load without it.
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "c", "status": "completed"}));
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
let mut old = serde_json::to_value(&t.entries[2]).unwrap();
old.as_object_mut().unwrap().remove("command");
assert!(matches!(serde_json::from_value(old).unwrap(), AgentEntry::Tool { command: None, .. }));
}
#[test]
fn tool_images_survive_updates_text_truncation_and_serialization() {
use base64::Engine;
@@ -489,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();
@@ -611,6 +645,8 @@ mod tests {
sent_ms: Some(sent),
done_ms: None,
steered: false,
recovery: None,
retry_attempt: None,
};
let mut t = Timeline::default();
t.push(user(1.0));
@@ -632,6 +668,8 @@ mod tests {
sent_ms: Some(sent),
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/*"
]
}
}
+2 -1
Переглянути файл
@@ -1,6 +1,6 @@
[package]
name = "ide-android"
description = "Android devices and logcat for the Logcat tool window, driven through the adb CLI"
description = "Android devices and iOS Simulators and their logs for the Logcat tool window, driven through adb and simctl"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -8,6 +8,7 @@ license.workspace = true
[dependencies]
ide-core.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
which = "8"
+199
Переглянути файл
@@ -0,0 +1,199 @@
//! iOS Simulators and their unified log, driven through `xcrun simctl` (macOS only).
//!
//! A simulator's log is followed with `simctl spawn <udid> log stream --style ndjson`
//! and parsed into the same [`LogcatLine`] the Android log uses, so the Logcat tool
//! window shows both with one level filter and one filter language.
use crate::model::{LogcatLevel, LogcatLine};
use crate::process;
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::process::Command;
use std::time::Duration;
const LIST: Duration = Duration::from_secs(20);
const BATCH_IDLE: Duration = Duration::from_millis(60);
const BATCH_MAX: usize = 300;
/// A booted simulator, as `simctl list devices booted -j` reports it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct BootedSimulator {
pub udid: String,
pub name: String,
/// e.g. `iOS 27.0`.
pub runtime: String,
}
/// Booted simulators; empty off macOS or without Xcode, so nothing iOS-related shows there.
pub fn booted_simulators() -> IdeResult<Vec<BootedSimulator>> {
if !cfg!(target_os = "macos") {
return Ok(Vec::new());
}
let mut cmd = Command::new("xcrun");
cmd.args(["simctl", "list", "devices", "booted", "-j"]);
match process::run(cmd, LIST, None) {
Ok(out) if out.success => Ok(parse_simulators(&out.stdout)),
// No Xcode (only the Command Line Tools, or none): there are no simulators.
_ => Ok(Vec::new()),
}
}
/// Parses `simctl list devices -j`, keeping booted devices.
pub fn parse_simulators(json: &str) -> Vec<BootedSimulator> {
#[derive(Deserialize)]
struct List {
devices: std::collections::BTreeMap<String, Vec<Device>>,
}
#[derive(Deserialize)]
struct Device {
udid: String,
name: String,
state: String,
}
let Ok(list) = serde_json::from_str::<List>(json) else {
return Vec::new();
};
let mut out = Vec::new();
for (runtime, devices) in list.devices {
// "com.apple.CoreSimulator.SimRuntime.iOS-27-0" → "iOS 27.0"
let short = runtime.rsplit('.').next().unwrap_or(&runtime);
let runtime = short.split_once('-').map_or(short.to_owned(), |(os, v)| format!("{os} {}", v.replace('-', ".")));
for d in devices.into_iter().filter(|d| d.state == "Booted") {
out.push(BootedSimulator { udid: d.udid, name: d.name, runtime: runtime.clone() });
}
}
out
}
/// Message type of the unified log → the logcat level the window filters and colors by.
fn level(message_type: &str) -> LogcatLevel {
match message_type {
"Debug" => LogcatLevel::Debug,
"Info" | "Default" => LogcatLevel::Info,
"Error" => LogcatLevel::Error,
"Fault" => LogcatLevel::Fatal,
_ => LogcatLevel::Verbose,
}
}
/// One NDJSON entry of `log stream --style ndjson`; `None` for anything that is not a
/// log message (activities, the trailing "terminated" notice). Unknown fields are ignored.
pub fn parse_ndjson(line: &str) -> Option<LogcatLine> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Entry {
event_type: String,
#[serde(default)]
message_type: String,
#[serde(default)]
timestamp: String,
#[serde(default)]
process_image_path: String,
#[serde(rename = "processID", default)]
pid: i64,
#[serde(rename = "threadID", default)]
tid: i64,
#[serde(default)]
subsystem: String,
#[serde(default)]
category: String,
#[serde(default)]
event_message: String,
}
let e: Entry = serde_json::from_str(line).ok()?;
if e.event_type != "logEvent" {
return None;
}
let process = e.process_image_path.rsplit('/').next().unwrap_or_default();
let tag = match (e.subsystem.is_empty(), e.category.is_empty()) {
(true, _) => process.to_owned(),
(false, true) => format!("{process} ({})", e.subsystem),
(false, false) => format!("{process} ({}:{})", e.subsystem, e.category),
};
// "2026-11-29 14:39:31.696480+0900" → "11-29 14:39:31.696", logcat's shape.
let time = e.timestamp.get(5..23).unwrap_or(&e.timestamp).to_owned();
Some(LogcatLine {
time,
pid: e.pid as i32,
tid: e.tid as i32,
level: level(&e.message_type),
tag,
message: e.event_message,
})
}
/// Follows simulator `udid`'s log until `cancel` fires or the simulator shuts down.
pub fn simulator_log(
udid: &str,
cancel: &CancellationToken,
on_batch: &mut dyn FnMut(Vec<LogcatLine>),
) -> IdeResult<()> {
let mut cmd = Command::new("xcrun");
cmd.args(["simctl", "spawn", udid, "log", "stream", "--style", "ndjson", "--level", "debug"]);
match process::stream_batched(cmd, cancel, BATCH_IDLE, BATCH_MAX, parse_ndjson, on_batch) {
Ok((ok, _)) if ok || cancel.is_cancelled() => Ok(()),
// `log stream` is killed when the simulator shuts down: that is an end, not a failure.
Ok((_, stderr)) if stderr.iter().any(|l| l.contains("terminated with signal")) => Ok(()),
Ok((_, stderr)) => Err(IdeError::unavailable(format!("log stream on {udid} stopped: {}", stderr.join("\n")))),
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => Ok(()),
Err(e) => Err(e),
}
}
#[cfg(test)]
mod tests {
use super::*;
const ENTRY: &str = r#"{"timezoneName":"","messageType":"Error","eventType":"logEvent","source":null,"subsystem":"com.apple.network","category":"endpoint","threadID":90176044,"processImagePath":"\/usr\/libexec\/remindd","timestamp":"2026-11-29 14:39:31.696480+0900","eventMessage":"endpoint has nothing to cleanup","processID":64339,"someFutureField":{"x":[1,2]}}"#;
#[test]
fn parses_an_entry_and_ignores_unknown_fields() {
let line = parse_ndjson(ENTRY).unwrap();
assert_eq!(line.time, "11-29 14:39:31.696");
assert_eq!(line.pid, 64339);
assert_eq!(line.tid, 90176044);
assert_eq!(line.level, LogcatLevel::Error);
assert_eq!(line.tag, "remindd (com.apple.network:endpoint)");
assert_eq!(line.message, "endpoint has nothing to cleanup");
}
#[test]
fn keeps_a_multi_line_message_whole() {
let entry = r#"{"eventType":"logEvent","messageType":"Default","processImagePath":"/a/MyApp","processID":7,"eventMessage":"first\nsecond"}"#;
let line = parse_ndjson(entry).unwrap();
assert_eq!(line.message, "first\nsecond");
assert_eq!(line.tag, "MyApp");
assert_eq!(line.level, LogcatLevel::Info);
}
#[test]
fn skips_what_is_not_a_log_message() {
assert!(parse_ndjson(r#"{"eventType":"activityCreateEvent","eventMessage":"x"}"#).is_none());
assert!(parse_ndjson("Child process terminated with signal 15: Terminated").is_none());
assert!(parse_ndjson("").is_none());
}
#[test]
fn maps_message_types_to_levels() {
assert_eq!(level("Debug"), LogcatLevel::Debug);
assert_eq!(level("Info"), LogcatLevel::Info);
assert_eq!(level("Default"), LogcatLevel::Info);
assert_eq!(level("Error"), LogcatLevel::Error);
assert_eq!(level("Fault"), LogcatLevel::Fatal);
assert_eq!(level("Signpost"), LogcatLevel::Verbose);
}
#[test]
fn reads_booted_simulators() {
let json = r#"{"devices":{"com.apple.CoreSimulator.SimRuntime.iOS-27-0":[
{"udid":"A","name":"iPhone Air","state":"Booted","isAvailable":true},
{"udid":"B","name":"iPhone 18","state":"Shutdown"}]}}"#;
assert_eq!(
parse_simulators(json),
vec![BootedSimulator { udid: "A".into(), name: "iPhone Air".into(), runtime: "iOS 27.0".into() }]
);
assert!(parse_simulators("not json").is_empty());
}
}
+2
Переглянути файл
@@ -7,9 +7,11 @@
//!
//! Every function blocks; callers run them off the UI / command threads.
mod ios;
mod model;
mod process;
pub use ios::{BootedSimulator, booted_simulators, parse_ndjson, parse_simulators, simulator_log};
pub use model::*;
use ide_core::process::{own_group, prepare};
+53 -9
Переглянути файл
@@ -85,13 +85,26 @@ gradle.projectsEvaluated {{
pub fn publish(root: &Path, cache: &Path, class_paths: &[String], main_class: &str) -> IdeResult<()> {
let output = PathBuf::from(fs::read_to_string(cache.join("resource-output.txt"))?.trim());
if !output.is_absolute() || !output.is_dir() {
return Err(IdeError::invalid("The resource build did not report an output directory"));
let invalid_output = "The resource build did not report an output directory";
if !output.is_absolute() {
return Err(IdeError::invalid(invalid_output));
}
let output = dunce::canonicalize(output)?;
let output = match fs::metadata(&output) {
Ok(metadata) if metadata.is_dir() => Some(dunce::canonicalize(output)?),
// Gradle's processResources can succeed with NO-SOURCE and never create its destination.
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
_ => return Err(IdeError::invalid(invalid_output)),
};
let paths: Vec<_> = class_paths.iter().filter_map(|p| dunce::canonicalize(root.join(p)).ok()).collect();
// A separate resource directory is already on the runtime classpath (e.g. build/resources/main).
if paths.contains(&output) {
if output.as_ref().is_some_and(|dir| paths.contains(dir)) {
return Ok(());
}
let previous: Vec<String> = fs::read(cache.join("published-resources.json"))
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default();
if output.is_none() && previous.is_empty() {
return Ok(());
}
// jdtls uses bin/main for Gradle, rather than Gradle's build/resources/main.
@@ -99,12 +112,10 @@ pub fn publish(root: &Path, cache: &Path, class_paths: &[String], main_class: &s
let destination = paths.iter().find(|p| p.join(&class_file).is_file()).ok_or_else(|| {
IdeError::invalid("Cannot find the running main class output directory; restart the application")
})?;
let previous: Vec<String> = fs::read(cache.join("published-resources.json"))
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default();
let mut current = Vec::new();
copy_resources(&output, &output, destination, &mut current)?;
if let Some(output) = output {
copy_resources(&output, &output, destination, &mut current)?;
}
for rel in previous.iter().filter(|p| !current.contains(p)) {
let path = destination.join(rel);
if path.is_file() {
@@ -220,6 +231,39 @@ mod tests {
}
}
#[test]
fn missing_resource_output_publishes_an_empty_set() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let output = root.join("build/resources/main");
let cache = root.join("cache");
let runtime = root.join("bin/main");
let class_paths = [runtime.to_string_lossy().into_owned()];
let resource = "application.properties";
fs::create_dir(&cache).unwrap();
fs::create_dir_all(runtime.join("example")).unwrap();
fs::write(cache.join("resource-output.txt"), output.to_string_lossy().as_bytes()).unwrap();
let class = runtime.join("example/Application.class");
fs::write(&class, "running").unwrap();
publish(root, &cache, &class_paths, "example.Application").unwrap();
assert!(!output.exists());
fs::create_dir_all(&output).unwrap();
fs::write(output.join(resource), "server.port=8081").unwrap();
publish(root, &cache, &class_paths, "example.Application").unwrap();
assert!(runtime.join(resource).is_file());
fs::remove_file(output.join(resource)).unwrap();
fs::remove_dir(&output).unwrap();
publish(root, &cache, &class_paths, "example.Application").unwrap();
assert!(!runtime.join(resource).exists());
assert_eq!(fs::read_to_string(class).unwrap(), "running");
fs::write(output, "not a directory").unwrap();
assert!(publish(root, &cache, &class_paths, "example.Application").is_err());
}
#[test]
fn leaves_separate_runtime_resource_directories_in_place_and_rejects_jar_only_runs() {
let tmp = tempfile::tempdir().unwrap();
+221 -14
Переглянути файл
@@ -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,
@@ -29,6 +29,7 @@ pub use up_to_date::{menu_up_to_date, record_menu_build};
use crate::process::{self, Stream};
use crate::{BuildModel, maven};
use ide_core::build_jobs::append_default_jobs;
use ide_core::settings::CMakeProfile;
use ide_core::{CancellationToken, Diagnostic, IdeError, IdeResult, Pos, Range, Severity};
use parse::{ColUnit, Format, OutputParser, RawMessage};
@@ -420,12 +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). The directory and
/// `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)
@@ -442,22 +445,54 @@ 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());
}
build.args.extend(profile.map(|p| p.build_args.clone()).unwrap_or_default());
append_default_jobs(&mut build.args);
build.env = env;
steps.push(build);
steps
@@ -812,6 +847,74 @@ pub fn run(
})
}
/// Messages of an `xcodebuild` whose output arrives line by line (an Xcode run configuration),
/// each reported once: xcodebuild prints a message for every architecture and again on retries.
pub struct XcodebuildMessages {
parser: OutputParser,
cwd: PathBuf,
paths: PathMap,
lines: Lines,
seen: HashSet<(Option<PathBuf>, Option<Range>, String)>,
/// xcodebuild printed its result (`** BUILD SUCCEEDED **`); what follows is the app's console.
done: bool,
}
impl XcodebuildMessages {
/// Relative paths resolve against `cwd`; paths under `root`'s canonical form map back to `root`.
pub fn new(root: &Path, cwd: &Path) -> Self {
XcodebuildMessages {
parser: OutputParser::new(Format::Xcode),
cwd: cwd.to_path_buf(),
paths: PathMap::new(root),
lines: Lines::default(),
seen: HashSet::new(),
done: false,
}
}
/// Messages completed by `line` (without its line break).
pub fn feed(&mut self, line: &str) -> Vec<BuildMessage> {
if self.done {
return Vec::new();
}
let result = parse::strip_ansi(line);
let result = result.trim();
if result.len() > 6 && result.starts_with("** ") && result.ends_with(" **") {
self.done = true;
return self.finish();
}
let raws = self.parser.feed(line).messages;
self.resolve(raws)
}
/// The message still waiting for detail lines.
pub fn finish(&mut self) -> Vec<BuildMessage> {
let raws = self.parser.finish();
self.resolve(raws)
}
fn resolve(&mut self, raws: Vec<RawMessage>) -> Vec<BuildMessage> {
raws.into_iter()
.map(|raw| {
let mut m = resolve(raw, &self.cwd, &self.paths, &mut self.lines);
// xcodebuild prints the folder it was started in, which may be a symlink to the project.
if let Some(path) = m.path.clone().map(PathBuf::from)
&& !path.starts_with(&self.paths.root)
&& let Ok(real) = dunce::canonicalize(&path)
&& let Some(real) = real.to_str()
{
let mapped = self.paths.resolve(real, &self.cwd, None);
if mapped.starts_with(&self.paths.root) {
m.path = Some(mapped.into());
}
}
m
})
.filter(|m| self.seen.insert((m.path.clone().map(Into::into), m.range, m.text.clone())))
.collect()
}
}
/// Per-file editor / Problems diagnostics of the messages that have a position.
pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
diagnostics_from(messages, DIAGNOSTICS_SOURCE)
@@ -915,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| {
@@ -1333,6 +1436,73 @@ mod tests {
}
use super::*;
#[test]
fn xcodebuild_messages_once_per_build() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("Warn.swift");
std::fs::write(&file, "func f() -> Int {\n var count = 1\n return count\n}\n").unwrap();
let mut x = XcodebuildMessages::new(tmp.path(), tmp.path());
let warning = format!("{}:2:9: warning: variable 'count' was never mutated", file.display());
let mut out = Vec::new();
// One copy per architecture, then the linker's per-architecture lists.
for line in [
warning.as_str(),
"SwiftCompile normal arm64 Compiling\\ Warn.swift",
warning.as_str(),
"Undefined symbols for architecture x86_64:",
" \"_sym\", referenced from:",
"ld: symbol(s) not found for architecture x86_64",
"Undefined symbols for architecture arm64:",
" \"_sym\", referenced from:",
] {
out.extend(x.feed(line));
}
out.extend(x.finish());
assert_eq!(out.len(), 2, "{out:?}");
assert_eq!(out[0].path.clone().map(PathBuf::from), Some(file));
// `count`, 0-based, underlined.
assert_eq!(out[0].range, Some(Range::new(Pos::new(1, 8), Pos::new(1, 13))));
assert_eq!(
(out[1].path.is_none(), out[1].text.as_str()),
(true, "Undefined symbols\n\"_sym\", referenced from:")
);
}
#[test]
fn xcodebuild_messages_stop_at_the_build_result() {
let tmp = tempfile::tempdir().unwrap();
let mut x = XcodebuildMessages::new(tmp.path(), tmp.path());
let mut out = Vec::new();
// An Xcode run configuration's output: the build, then the app's own console.
for line in [
"/p/Demo/Demo.xcodeproj: Demo: ld: warning: Could not find or use auto-linked framework 'UIUtilities'",
"** BUILD SUCCEEDED **",
"error: request failed",
"warning: low memory",
"Demo/ContentView.swift:12: Fatal error: Unexpectedly found nil while unwrapping an Optional value",
] {
out.extend(x.feed(line));
}
out.extend(x.finish());
let texts: Vec<_> = out.iter().map(|m| m.text.as_str()).collect();
assert_eq!(texts, ["Could not find or use auto-linked framework 'UIUtilities'"]);
}
#[cfg(unix)]
#[test]
fn xcodebuild_paths_through_a_symlink_map_to_the_project() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("Demo");
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join("A.swift"), "let x = y\n").unwrap();
let link = tmp.path().join("link");
std::os::unix::fs::symlink(&root, &link).unwrap();
let mut x = XcodebuildMessages::new(&root, &root);
x.feed(&format!("{}/A.swift:1:9: error: cannot find 'y' in scope", link.display()));
let out = x.finish();
assert_eq!(out[0].path.clone().map(PathBuf::from), Some(root.join("A.swift")));
}
/// Launch outputs use the platform separator throughout, so they compare equal to
/// the same directories as JDT LS reports them.
#[test]
@@ -1508,23 +1678,33 @@ mod tests {
let cm = tmp.path().join("cm");
write(&cm, "CMakeLists.txt", "project(app)");
let args = |p: &BuildPlan| p.steps.iter().map(|s| s.args.join(" ")).collect::<Vec<_>>();
let jobs = format!("-j {}", ide_core::build_jobs::default_jobs());
let p =
plan(&cm, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(p.system, BuildSystem::CMake);
assert_eq!(
args(&p),
[
"-S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON",
"--build build --config Debug"
"-S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON".to_owned(),
format!("--build build --config Debug {jobs}"),
],
"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!(
args(&p),
["--build cmake-build-release --config Debug --clean-first"],
[format!("--build cmake-build-release --config Debug --clean-first {jobs}")],
"a configured directory is reused"
);
let profile = CMakeProfile {
@@ -1555,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>");
+158
Переглянути файл
@@ -27,6 +27,10 @@ pub(crate) enum Format {
Gcc,
/// MSBuild (`dotnet build`): `C:\p\A.cs(12,5): error CS1002: msg [C:\p\App.csproj]`.
Msbuild,
/// `xcodebuild`: swiftc / clang lines like [`Format::Gcc`], their notes (`path:3:6: note:` or
/// Swift's `` `- note: `` in the code excerpt), `App.xcodeproj: App: ld: warning: msg` and
/// `Undefined symbols for architecture arm64:` with its indented details.
Xcode,
}
/// What a printed column counts.
@@ -331,6 +335,59 @@ fn gcc_line(line: &str) -> Option<RawMessage> {
(!msg.is_empty()).then(|| RawMessage::new(severity, msg, ColUnit::Byte).at(path, ln, col))
}
const UNDEFINED_SYMBOLS: &str = "Undefined symbols";
/// An `xcodebuild` message: a compiler line, a linker / build-system line without a location, or
/// the start of an undefined symbols list. Its architecture is dropped: every one prints the same.
fn xcode_line(line: &str) -> Option<RawMessage> {
if let Some(m) = gcc_line(line) {
return Some(m);
}
if line.starts_with("Undefined symbols for architecture ") {
return Some(RawMessage::new(Severity::Error, UNDEFINED_SYMBOLS, ColUnit::Byte));
}
// `/p/App.xcodeproj: App: ld: warning: msg`, `error: msg`, `xcodebuild: error: msg`.
let rest = [".xcodeproj: ", ".xcworkspace: "]
.into_iter()
.find_map(|c| line.find(c).map(|i| &line[i + c.len()..]))
.or_else(|| (!line.starts_with(char::is_whitespace)).then_some(line))?;
let (severity, msg) =
[("error: ", Severity::Error), ("warning: ", Severity::Warning)].into_iter().find_map(|(word, severity)| {
let at = rest.match_indices(word).map(|(i, _)| i).find(|&i| i == 0 || rest[..i].ends_with(": "))?;
// Only `tool: ` / `target: ` words may come before the severity, not a sentence.
rest[..at].split(": ").all(|w| !w.contains(' ')).then(|| (severity, rest[at + word.len()..].trim()))
})?;
(!msg.is_empty()).then(|| RawMessage::new(severity, msg, ColUnit::Byte))
}
/// Whether `line` belongs to the pending `xcodebuild` message (and is folded into it).
fn xcode_detail(msg: &mut RawMessage, line: &str) -> bool {
let t = line.trim_start();
// A `note:` with a location, as clang and `-diagnostic-style llvm` print it.
if let Some((_, _, _, rest)) = path_line_col(line)
&& let Some(note) = rest.strip_prefix(':').and_then(|r| r.trim_start().strip_prefix("note:"))
{
msg.text.push_str("\nnote: ");
msg.text.push_str(note.trim());
return true;
}
// The code excerpt: ` 9 | switch s {`, ` | `- note: add missing case`.
let excerpt = t.trim_start_matches(|c: char| c.is_ascii_digit()).trim_start().starts_with('|');
if excerpt {
if let Some(i) = t.find("- note: ") {
msg.text.push_str("\nnote: ");
msg.text.push_str(t[i + "- note: ".len()..].trim());
}
return true;
}
if msg.text.starts_with(UNDEFINED_SYMBOLS) && t.len() < line.len() && !t.is_empty() {
msg.text.push('\n');
msg.text.push_str(t);
return true;
}
false
}
/// rustc's JSON diagnostic (`reason: compiler-message`) → message and its rendered text.
fn cargo_json(v: &Value) -> Option<(Option<RawMessage>, String)> {
if v.get("reason")?.as_str()? != "compiler-message" {
@@ -412,6 +469,9 @@ impl OutputParser {
.map_or(line, |r| r.strip_prefix(' ').unwrap_or(r)),
_ => line,
};
if format == Format::Xcode {
return xcode_detail(&mut p.msg, line);
}
if matches!(format, Format::Maven | Format::Gradle | Format::Tsc)
&& body.starts_with(" ")
&& !body.trim().is_empty()
@@ -447,6 +507,7 @@ impl OutputParser {
Format::Go => go_line(&line),
Format::Gcc => gcc_line(&line),
Format::Msbuild => msbuild_line(&line),
Format::Xcode => xcode_line(&line),
Format::Cargo => None,
};
if let Some(msg) = parsed {
@@ -678,6 +739,103 @@ mod tests {
assert_eq!(out[2].text, "'missing.h' file not found");
}
// Real `xcodebuild build` output (Xcode 27.1, iOS Simulator, two architectures), paths shortened.
#[test]
fn xcodebuild_swift_error_warning_and_note() {
let out = parse(
Format::Xcode,
"SwiftCompile normal x86_64 Compiling\\ Warn.swift /p/Demo/Warn.swift (in target 'Demo' from project 'Demo')\n\
/p/Demo/Warn.swift:2:9: warning: variable 'count' was never mutated; consider changing to 'let' constant [#VariableNeverMutated]\n\
\x201 | func warnMe() -> Int {\n\
\x202 | var count = 1\n\
\x20 | `- warning: variable 'count' was never mutated; consider changing to 'let' constant [#VariableNeverMutated]\n\
\x203 | return count\n\
\x204 | }\n\
\n\
/p/Demo/Warn.swift:9:5: error: switch must be exhaustive\n\
\x207 | \n\
\x208 | func name(_ s: Shade) -> String {\n\
\x209 | switch s {\n\
\x20 | |- error: switch must be exhaustive\n\
\x20 | `- note: add missing case: '.dark'\n\
10 | case .light: return \"light\"\n\
11 | }\n\
\n\
[#VariableNeverMutated]: <https://docs.swift.org/compiler/documentation/diagnostics/variable-never-mutated>\n\
Failed frontend command:\n\
note: Removed stale file '/p/dd/Demo.swiftmodule'\n",
);
assert_eq!(out.len(), 2, "{out:?}");
assert_eq!(out[0].severity, Severity::Warning);
assert_eq!((out[0].path.as_deref(), out[0].line, out[0].col), (Some("/p/Demo/Warn.swift"), Some(2), Some(9)));
assert!(out[0].text.starts_with("variable 'count' was never mutated"), "{}", out[0].text);
assert_eq!(out[1].severity, Severity::Error);
assert_eq!(out[1].text, "switch must be exhaustive\nnote: add missing case: '.dark'");
assert_eq!((out[1].line, out[1].col), (Some(9), Some(5)));
}
#[test]
fn xcodebuild_clang_errors_with_note() {
let out = parse(
Format::Xcode,
"/p/Demo/Legacy.m:2:29: error: use of undeclared identifier 'undeclared_thing'\n\
\x20 2 | void legacy(void) { int x = undeclared_thing; }\n\
\x20 | ^~~~~~~~~~~~~~~~\n\
/p/Demo/Legacy.m:4:6: error: redefinition of 'twice'\n\
\x20 4 | void twice(void) {}\n\
\x20 | ^\n\
/p/Demo/Legacy.m:3:6: note: previous definition is here\n\
\x20 3 | void twice(void) {}\n\
\x20 | ^\n\
2 errors generated.\n",
);
assert_eq!(out.len(), 2, "{out:?}");
assert_eq!(out[0].text, "use of undeclared identifier 'undeclared_thing'");
assert_eq!((out[0].line, out[0].col), (Some(2), Some(29)));
assert_eq!(out[1].text, "redefinition of 'twice'\nnote: previous definition is here");
assert_eq!((out[1].line, out[1].col), (Some(4), Some(6)));
}
#[test]
fn xcodebuild_linker_errors_without_location() {
let out = parse(
Format::Xcode,
"Ld /p/dd/Demo.debug.dylib normal arm64 (in target 'Demo' from project 'Demo')\n\
\x20 cd /p/Demo\n\
\x20 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -Xlinker -reproducible -target arm64-apple-ios16.0-simulator -ferror-limit 19\n\
/p/Demo/Demo.xcodeproj: Demo: ld: warning: Could not find or use auto-linked framework 'UIUtilities': framework 'UIUtilities' not found\n\
Undefined symbols for architecture arm64:\n\
\x20 \"_missing_symbol_xyz\", referenced from:\n\
\x20 Demo.callMissing() -> () in Missing.o\n\
ld: symbol(s) not found for architecture arm64\n\
/p/Demo/Demo.xcodeproj: Demo: clang: error: linker command failed with exit code 1 (use -v to see invocation)\n\
\n\
** BUILD FAILED **\n\
\n\
The following build commands failed:\n\
\tLd /p/dd/Demo.debug.dylib normal arm64 (in target 'Demo' from project 'Demo')\n\
xcodebuild: error: Unable to find a destination matching the provided destination specifier\n",
);
let found: Vec<_> = out.iter().map(|m| (m.severity, m.text.as_str(), m.path.is_none())).collect();
assert_eq!(
found,
[
(
Severity::Warning,
"Could not find or use auto-linked framework 'UIUtilities': framework 'UIUtilities' not found",
true
),
(
Severity::Error,
"Undefined symbols\n\"_missing_symbol_xyz\", referenced from:\nDemo.callMissing() -> () in Missing.o",
true
),
(Severity::Error, "linker command failed with exit code 1 (use -v to see invocation)", true),
(Severity::Error, "Unable to find a destination matching the provided destination specifier", true),
]
);
}
#[test]
fn go_errors() {
let out = parse(
+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)]
+102 -24
Переглянути файл
@@ -4,7 +4,8 @@
//! same way into the test output, which also sees the production classes.
use super::*;
use ide_core::settings::{
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings,
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings, jar_files,
split_jar_glob,
};
use std::fs;
@@ -104,13 +105,17 @@ fn library_entries(root: &Path, ps: &ProjectStructureSettings, test: bool) -> Ve
module_deps.iter().find(|d| d.kind == "library" && d.target == lib.name).map_or(lib.scope, |d| d.scope);
if wanted(scope) {
for class in &lib.classes {
add(class_entry(root, class));
for entry in class_entries(root, class) {
add(entry);
}
}
}
}
for dep in module_deps.iter().filter(|d| d.kind == "library" && wanted(d.scope)) {
if !ps.libraries.iter().any(|l| l.name == dep.target) && !dep.target.trim().is_empty() {
add(class_entry(root, &dep.target));
for entry in class_entries(root, &dep.target) {
add(entry);
}
}
}
for facet in ps.facets.iter().filter(|f| f.kind == "web") {
@@ -133,29 +138,50 @@ fn web_root(root: &Path, facet: &ide_core::settings::FacetConfig) -> PathBuf {
root.join(dir)
}
/// The class archives and folders of a library path (`lib/*.jar` lists the folder's jars).
fn library_files(root: &Path, value: &str) -> Vec<PathBuf> {
let entry = class_entry(root, value);
match entry.strip_suffix('*') {
Some(dir) => {
let mut jars: Vec<PathBuf> = fs::read_dir(dir)
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "jar")).collect())
.unwrap_or_default();
jars.sort();
jars
/// The folders under `dir` (itself included) that hold `.jar` files, in walk order.
fn jar_dirs(dir: &Path) -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = Vec::new();
for jar in jar_files(dir, true) {
if let Some(parent) = jar.parent().filter(|p| !dirs.iter().any(|d| d == p)) {
dirs.push(parent.to_path_buf());
}
None => vec![PathBuf::from(entry)],
}
dirs
}
/// A classpath entry for a library path: a folder of jars (`lib/*`) stays a wildcard javac expands.
fn class_entry(root: &Path, value: &str) -> String {
let path = root.join(value.trim());
let text = path.to_string_lossy().into_owned();
if text.ends_with("/*.jar") || text.ends_with("\\*.jar") {
return text[..text.len() - 4].to_owned();
/// The class archives and folders of a library path (`lib/*.jar`, `lib/**/*.jar`, or a folder
/// containing JARs expands to those JARs; a folder without JARs stays a class folder).
fn library_files(root: &Path, value: &str) -> Vec<PathBuf> {
if let Some((base, recursive)) = split_jar_glob(value) {
return jar_files(&root.join(base), recursive);
}
text
let path = root.join(value.trim());
if path.is_dir() {
let jars = jar_files(&path, true);
if !jars.is_empty() {
return jars;
}
}
vec![path]
}
/// Classpath entries for a library path: `lib/*.jar` stays `lib/*` for javac to expand; a
/// directory containing JARs expands to `<dir>/*` per folder holding JARs.
fn class_entries(root: &Path, value: &str) -> Vec<String> {
let wildcard = |dir: &Path| format!("{}{}*", dir.to_string_lossy(), std::path::MAIN_SEPARATOR);
if let Some((base, recursive)) = split_jar_glob(value) {
let dir = root.join(base);
let dirs = if recursive { jar_dirs(&dir) } else { Vec::new() };
return if dirs.is_empty() { vec![wildcard(&dir)] } else { dirs.iter().map(|d| wildcard(d)).collect() };
}
let path = root.join(value.trim());
if path.is_dir() {
let dirs = jar_dirs(&path);
if !dirs.is_empty() {
return dirs.iter().map(|d| wildcard(d)).collect();
}
}
vec![path.to_string_lossy().into_owned()]
}
fn classpath(entries: &[String]) -> String {
@@ -440,7 +466,10 @@ pub fn structure_web_artifacts(ps: &ProjectStructureSettings) -> Vec<&ArtifactCo
ps.artifacts.iter().filter(|a| matches!(a.kind, ArtifactKind::War | ArtifactKind::WarExploded)).collect()
}
/// A build of `artifact` into the WAR `war` (Tomcat's deployment), compiling first.
/// A build of `artifact` for Tomcat's deployment, compiling production classes first.
/// When `war` is `Some`, packs a WAR archive at that path; when `None`, writes to the
/// artifact's own output (`artifact_file`: a `.war` archive for `War`, or the exploded
/// directory for `WarExploded`).
#[allow(clippy::too_many_arguments)]
pub fn structure_war_plan(
root: &Path,
@@ -449,7 +478,7 @@ pub fn structure_war_plan(
jdk: Option<&StructureJdk>,
language_level: &str,
artifact: &ArtifactConfig,
war: &Path,
war: Option<&Path>,
cache: &Path,
) -> IdeResult<BuildPlan> {
let mut plan = structure_plan(root, ps, roots, jdk, language_level, BuildKind::Build, cache)?
@@ -459,7 +488,7 @@ pub fn structure_war_plan(
plan.steps.retain(|s| !s.args.iter().any(|a| a.ends_with("test.args")));
plan.steps
.retain(|s| !matches!(&s.action, Some((Action::CopyResources { to, .. }, _)) if !to.starts_with(&main_out)));
plan.steps.extend(artifact_steps(root, ps, artifact, &main_out, Some(war), cache));
plan.steps.extend(artifact_steps(root, ps, artifact, &main_out, war, cache));
plan.title = artifact.name.clone();
Ok(plan)
}
@@ -1144,4 +1173,53 @@ mod tests {
bad_result.messages
);
}
#[test]
fn expands_jar_directory_libraries_for_javac_and_artifacts() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("app");
let cache = tmp.path().join("cache");
write(&root.join("src/A.java"), "class A {}");
write(&root.join("WebRoot/WEB-INF/lib/gson.jar"), "jar1");
write(&root.join("WebRoot/WEB-INF/lib/sub/extra.jar"), "jar2");
fs::create_dir_all(root.join("plain-classes")).unwrap();
write(&root.join("plain-classes/Helper.class"), "");
let ps = ProjectStructureSettings {
libraries: vec![
ProjectLibrary {
name: "web-libs".into(),
classes: vec!["WebRoot/WEB-INF/lib".into()],
..Default::default()
},
ProjectLibrary { name: "classes".into(), classes: vec!["plain-classes".into()], ..Default::default() },
],
artifacts: vec![ArtifactConfig {
name: "app:war exploded".into(),
kind: ArtifactKind::WarExploded,
module: ".".into(),
output_directory: "out/artifacts/app_war_exploded".into(),
main_class: String::new(),
include_libraries: vec!["web-libs".into()],
}],
..Default::default()
};
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
let plan = structure_plan(&root, &ps, &roots, None, "17", BuildKind::Artifacts, &cache).unwrap().unwrap();
let javac = &plan.steps[0];
let cp = &javac.args[javac.args.iter().position(|a| a == "-cp").unwrap() + 1];
let sep = std::path::MAIN_SEPARATOR;
assert!(cp.contains(&format!("lib{sep}*")), "expected JAR dir wildcard in cp: {cp}");
assert!(cp.contains(&format!("sub{sep}*")), "expected nested JAR dir wildcard in cp: {cp}");
assert!(cp.contains("plain-classes") && !cp.contains(&format!("plain-classes{sep}*")), "cp={cp}");
let layout = plan.steps.iter().find_map(|s| match &s.action {
Some((Action::Layout { entries, .. }, _)) => Some(entries),
_ => None,
});
let entries = layout.expect("layout step");
assert!(entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/gson.jar")), "{entries:?}");
assert!(entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/extra.jar")), "{entries:?}");
assert!(!entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/lib")), "{entries:?}");
}
}
+4 -3
Переглянути файл
@@ -323,7 +323,8 @@ mod tests {
"exclude": [path(&root.join("node_modules"))],
})
);
let a = root.join("packages/a");
// Chained joins: the configurations name native paths, `packages/a` would mix separators on Windows.
let a = root.join("packages").join("a");
assert_eq!(
copy(1),
json!({
@@ -336,14 +337,14 @@ mod tests {
"exclude": [path(&a.join("node_modules"))],
})
);
let b = root.join("packages/b");
let b = root.join("packages").join("b");
assert_eq!(
copy(2),
json!({
"extends": path(&b.join("tsconfig.json")),
"compilerOptions": {
"outDir": path(&scratch.join("2")), "tsBuildInfoFile": s("2.tsbuildinfo"),
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2/out.js")),
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2").join("out.js")),
},
"references": [{"path": s("1.json")}],
"exclude": [path(&b.join("node_modules")), path(&root.join("dist"))],
+72 -4
Переглянути файл
@@ -5,8 +5,10 @@
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::BTreeMap;
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{Duration, Instant};
pub const SETTINGS_FILES: &[&str] = &["settings.gradle.kts", "settings.gradle"];
pub const BUILD_FILES: &[&str] = &["build.gradle.kts", "build.gradle"];
@@ -227,9 +229,41 @@ pub fn build_dir(root: &Path) -> Option<PathBuf> {
build_dirs(root).into_iter().next()
}
/// How long [`cached_build_dirs`] reuses a walk. Project roots, content roots and the index
/// ask for the builds many times while a project opens; on a network share each walk is
/// thousands of round trips. A build file changing in a project calls [`forget_build_dirs`].
const BUILD_DIRS_TTL: Duration = Duration::from_secs(30);
type BuildDirsCache = HashMap<PathBuf, (Instant, Vec<PathBuf>)>;
static BUILD_DIRS: Mutex<Option<BuildDirsCache>> = Mutex::new(None);
/// Walks for builds now; the result also refreshes [`cached_build_dirs`].
fn build_dirs(root: &Path) -> Vec<PathBuf> {
let markers: Vec<_> = SETTINGS_FILES.iter().chain(BUILD_FILES).copied().collect();
ide_core::project_roots::discover(root, &markers)
let dirs = ide_core::project_roots::discover(root, &markers);
let now = Instant::now();
let mut guard = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner());
let map = guard.get_or_insert_with(HashMap::new);
map.retain(|_, (at, _)| now.duration_since(*at) < BUILD_DIRS_TTL);
map.insert(root.to_path_buf(), (now, dirs.clone()));
dirs
}
fn cached_build_dirs(root: &Path) -> Vec<PathBuf> {
let cached = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|m| m.get(root)).cloned();
match cached {
Some((at, dirs)) if at.elapsed() < BUILD_DIRS_TTL => dirs,
_ => build_dirs(root),
}
}
/// Forgets the discovered Gradle builds of `root`, and of folders above or below it
/// (after a build or settings script appeared, changed or was removed there).
pub fn forget_build_dirs(root: &Path) {
if let Some(map) = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
map.retain(|dir, _| !dir.starts_with(root) && !root.starts_with(dir));
}
}
fn wrapper(dir: &Path) -> String {
@@ -506,10 +540,23 @@ pub fn linked_project_key(root: &Path, dir: &str) -> String {
}
}
/// Linked build identities without reading their scripts (also used by index hot paths).
/// Linked build identities without reading their scripts, as of now (a sync, a build).
pub(crate) fn linked_dirs(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
linked_dirs_from(root, settings, build_dirs)
}
/// [`linked_dirs`] for hot paths (project and index roots): discovered builds are reused for a while.
pub(crate) fn linked_dirs_cached(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
linked_dirs_from(root, settings, cached_build_dirs)
}
fn linked_dirs_from(
root: &Path,
settings: &ide_core::settings::GradleSettings,
discover: fn(&Path) -> Vec<PathBuf>,
) -> Vec<String> {
match &settings.linked_projects {
None => build_dirs(root).iter().map(|dir| rel(root, dir)).collect(),
None => discover(root).iter().map(|dir| rel(root, dir)).collect(),
Some(dirs) => {
let mut out = Vec::new();
for dir in dirs {
@@ -1047,6 +1094,27 @@ pub(crate) fn has_war_plugin(script: &str) -> bool {
#[cfg(test)]
mod tests {
#[test]
fn discovered_builds_are_reused_until_forgotten() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
std::fs::create_dir_all(root.join("a")).unwrap();
std::fs::write(root.join("a/settings.gradle"), "").unwrap();
assert_eq!(super::cached_build_dirs(root), vec![root.join("a")]);
std::fs::create_dir_all(root.join("b")).unwrap();
std::fs::write(root.join("b/build.gradle"), "").unwrap();
// A walk per call is thousands of round trips on a network share.
assert_eq!(super::cached_build_dirs(root), vec![root.join("a")]);
super::forget_build_dirs(&root.join("b"));
assert_eq!(super::cached_build_dirs(root), vec![root.join("a"), root.join("b")]);
// A sync sees a new build at once, and so does every later lookup.
std::fs::create_dir_all(root.join("c")).unwrap();
std::fs::write(root.join("c/build.gradle"), "").unwrap();
let all = vec![root.join("a"), root.join("b"), root.join("c")];
assert_eq!(super::build_dirs(root), all);
assert_eq!(super::cached_build_dirs(root), all);
}
#[test]
fn default_linkage_discovers_all_shallow_builds() {
let temp = tempfile::tempdir().unwrap();
+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 {
+17 -12
Переглянути файл
@@ -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};
@@ -46,6 +46,16 @@ fn subdir(root: &Path, rel: &str) -> PathBuf {
root.join(rel).components().collect()
}
/// The `-pl` value selecting `projects` in their Maven reactor, by `groupId:artifactId`. Their
/// directories are the absolute `basedir`s Maven reported, which need not share a spelling with the
/// opened folder (drive letter case, separators, links), so a path selector could miss the reactor.
fn maven_project_selection<'a>(projects: impl Iterator<Item = &'a ProjectModel>) -> String {
let mut selection: Vec<String> = projects.map(|p| format!("{}:{}", p.group_id, p.artifact_id)).collect();
selection.sort();
selection.dedup();
selection.join(",")
}
/// The resident part of the build: javac servers and one lock per reactor.
#[derive(Default)]
pub struct JavaBuildService {
@@ -691,17 +701,12 @@ impl JavaBuild<'_> {
let out = model::output_root(self.cache, &top.key());
let step = match top {
Reactor::Maven(top) => {
let top_dir = subdir(self.root, &top.dir);
let mut selection: Vec<String> = changed
.iter()
.map(|(p, _, _)| {
let rel = p.dir.strip_prefix(&top_dir).unwrap_or(&p.dir).to_string_lossy().replace('\\', "/");
if rel.is_empty() { ".".to_owned() } else { rel }
})
.collect();
selection.sort();
selection.dedup();
let mut extra = vec!["-q".to_owned(), "-pl".to_owned(), selection.join(",")];
let selection = maven_project_selection(changed.iter().map(|(p, _, _)| *p));
// 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());
+51 -2
Переглянути файл
@@ -11,6 +11,50 @@ fn write(root: &Path, rel: &str, text: &str) {
fs::write(path, text).unwrap();
}
fn build_output_tail(events: &[BuildEvent]) -> String {
let mut lines: Vec<_> = events
.iter()
.filter_map(|event| match event {
BuildEvent::Output { text, .. } => Some(text.as_str()),
_ => None,
})
.flat_map(str::lines)
.rev()
.take(150)
.collect();
lines.reverse();
lines.join("\n")
}
#[test]
fn build_output_tail_keeps_the_last_150_lines_across_streams() {
let lines = |range: std::ops::Range<usize>| range.map(|n| n.to_string()).collect::<Vec<_>>().join("\n");
let events = [
BuildEvent::Output { text: lines(0..100), stderr: false },
BuildEvent::Progress { message: "building".into(), fraction: None },
BuildEvent::Output { text: lines(100..155), stderr: true },
];
assert_eq!(build_output_tail(&events), lines(5..155));
}
#[test]
fn maven_resources_select_projects_by_coordinates_not_by_basedir() {
// Maven reports absolute basedirs whose spelling can differ from the opened folder on Windows
// (`D:/worktree/jxc/organ` against `d:\\worktree\\jxc`); coordinates always name a reactor project.
let project = |dir: &str, artifact: &str| ProjectModel {
dir: PathBuf::from(dir),
group_id: "org.starry".into(),
artifact_id: artifact.into(),
..Default::default()
};
let projects = [
project("D:/worktree/jxc/organ", "organ"),
project("D:/worktree/jxc", "cloud"),
project("D:/worktree/jxc/organ", "organ"),
];
assert_eq!(maven_project_selection(projects.iter()), "org.starry:cloud,org.starry:organ");
}
/// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped).
fn tools() -> Option<(PathBuf, PathBuf)> {
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?;
@@ -139,7 +183,10 @@ impl Fixture {
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) {
Ok(Built::Done(outputs)) => outputs,
Ok(Built::Unsupported(reason)) => panic!("unsupported: {reason}"),
Ok(Built::Unsupported(reason)) => {
let output = build_output_tail(&self.events.lock().unwrap());
panic!("unsupported: {reason}\n{output}");
}
Err(e) => panic!("{e:?}"),
}
}
@@ -210,7 +257,9 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
f.write("app/src/main/resources/app.properties", "version=${project.version}\nmore=1\n");
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl app"), "{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.
+7 -4
Переглянути файл
@@ -91,12 +91,14 @@ fn plan(root: &Path, model: &BuildModel, cancel: &CancellationToken) -> IdeResul
/// Run the project's configured wrapper/settings/JDK and lifecycle, with an output
/// redirector loaded before Maven calculates its lifecycle execution plans.
/// Builds the Kotlin libraries; `on_progress` gets Maven's progress (message, fraction 0..1).
pub fn build(
root: &Path,
model: &BuildModel,
bundle: &Path,
generation: &Path,
cancel: &CancellationToken,
on_progress: &(dyn Fn(&str, Option<f32>) + Sync),
) -> IdeResult<Outcome> {
std::fs::create_dir_all(generation)?;
let mut plan = plan(root, model, cancel)?;
@@ -124,10 +126,10 @@ pub fn build(
for step in &plan.steps {
let mut reactor = plan.clone();
reactor.steps = vec![step.clone()];
let result = compile::run(root, &reactor, cancel, &|event| {
if let BuildEvent::Output { text, .. } = event {
tracing::debug!("kotlin bridge: {}", text.trim_end());
}
let result = compile::run(root, &reactor, cancel, &|event| match event {
BuildEvent::Output { text, .. } => tracing::debug!("kotlin bridge: {}", text.trim_end()),
BuildEvent::Progress { message, fraction } => on_progress(&message, fraction),
_ => {}
})?;
messages.extend(result.messages);
}
@@ -456,6 +458,7 @@ mod tests {
Path::new("unused.jar"),
&directory.path().join("private"),
&CancellationToken::new(),
&|_, _| {},
)
.err()
.unwrap();
+2 -2
Переглянути файл
@@ -129,7 +129,7 @@ pub fn gradle_external_roots(
cache_dir: &Path,
settings: &ide_core::settings::GradleSettings,
) -> Vec<PathBuf> {
let builds = gradle::linked_dirs(root, settings);
let builds = gradle::linked_dirs_cached(root, settings);
let dirs: Vec<String> = builds
.iter()
.flat_map(|dir| {
@@ -171,7 +171,7 @@ pub fn gradle_source_roots(
cache_dir: &Path,
settings: &ide_core::settings::GradleSettings,
) -> Vec<(PathBuf, gradle::ReportedRoot, PathBuf)> {
let reported = gradle::linked_dirs(root, settings)
let reported = gradle::linked_dirs_cached(root, settings)
.iter()
.flat_map(|dir| sync::reported_gradle_projects(&gradle::cache_dir(cache_dir, dir)).as_ref().clone())
.collect::<Vec<_>>();
+83 -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),
@@ -4461,4 +4488,58 @@ mod linkage_tests {
assert_eq!(poms, expected.map(|e| e.iter().map(|s| s.to_string()).collect::<Vec<_>>()), "{unlinked:?}");
}
}
#[test]
fn child_module_inherits_parent_declared_plugin_prefix_and_coordinates() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("child")).unwrap();
std::fs::write(
root.join("pom.xml"),
r#"<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules><module>child</module></modules>
<build>
<plugins>
<plugin>
<groupId>io.spring.javaformat</groupId>
<artifactId>spring-javaformat-maven-plugin</artifactId>
<version>0.0.38</version>
</plugin>
</plugins>
</build>
</project>"#,
)
.unwrap();
std::fs::write(
root.join("child/pom.xml"),
r#"<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example</groupId>
<artifactId>parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>child</artifactId>
</project>"#,
)
.unwrap();
let model = load_with_repo(root, None);
for pom in ["pom.xml", "child/pom.xml"] {
let proj = model.projects.iter().find(|p| p.pom == pom).expect(pom);
let plugin = proj
.plugins
.iter()
.find(|p| p.prefix == "spring-javaformat")
.unwrap_or_else(|| panic!("spring-javaformat plugin missing on {pom}: {:?}", proj.plugins));
assert_eq!(plugin.group_id, "io.spring.javaformat");
assert_eq!(plugin.artifact_id, "spring-javaformat-maven-plugin");
assert_eq!(plugin.version.as_deref(), Some("0.0.38"));
}
}
}
+116
Переглянути файл
@@ -340,6 +340,18 @@ mod imp {
const OPEN_ATTEMPTS: usize = 10;
const OPEN_RETRY: Duration = Duration::from_millis(20);
/// WARNING: reading or writing the clipboard from two threads at once crashes the whole
/// process. `OpenClipboard(NULL)` does not keep the other threads of this process out, and
/// a second `GetClipboardData` can free the block the first thread is still reading, so
/// `GlobalSize` finds a corrupted heap and Windows ends the app with 0xc0000374 (#6388:
/// restoring a minimized window starts several reads). Every function below that opens the
/// clipboard holds this lock from before `OpenClipboard` until after `CloseClipboard`.
static CLIPBOARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn lock() -> std::sync::MutexGuard<'static, ()> {
CLIPBOARD.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[link(name = "user32")]
unsafe extern "system" {
fn OpenClipboard(owner: Handle) -> i32;
@@ -389,6 +401,7 @@ mod imp {
}
pub fn png() -> Option<Vec<u8>> {
let _clipboard = lock();
if !open() {
return None;
}
@@ -405,6 +418,7 @@ mod imp {
}
pub fn text() -> Option<String> {
let _clipboard = lock();
// Empty rather than None: a None falls back to the WebView, which prompts the user.
if unsafe { IsClipboardFormatAvailable(CF_UNICODETEXT) } == 0 {
return Some(String::new());
@@ -447,6 +461,7 @@ mod imp {
}
pub fn files() -> std::io::Result<Vec<PathBuf>> {
let _clipboard = lock();
if !open() {
return Err(std::io::Error::last_os_error());
}
@@ -528,6 +543,7 @@ mod imp {
}
pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
let _clipboard = lock();
let (memory, _) = global_text(text);
if memory.is_null() {
return Err(std::io::Error::last_os_error());
@@ -551,6 +567,7 @@ mod imp {
}
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
let _clipboard = lock();
let dib = super::image::png_to_dib(png)?;
let format = png_format();
if format == 0 {
@@ -593,6 +610,7 @@ mod imp {
}
pub fn set_files(paths: &[PathBuf]) -> bool {
let _clipboard = lock();
let bytes = encode(paths);
if bytes.len() <= HEADER {
return false;
@@ -923,6 +941,104 @@ mod tests {
assert_eq!(unicode_text(&bytes), "héllo\r\n世界");
}
#[cfg(windows)]
const READ_TEXT: &str = "clipboard read test";
/// Reads the clipboard's text for 5 s from `threads` threads, one at a time when
/// `serialized`, in a child process: heap corruption ends a process, and the test
/// keeps the result. Replaces the clipboard with text and writes the earlier text
/// back afterwards; skipped where no clipboard can be written.
#[cfg(windows)]
fn reads_survive(test: &str, threads: usize, serialized: bool) {
use std::process::Command;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
const STAGE: &str = "IDE_CLIPBOARD_READ_STAGE";
if std::env::var_os(STAGE).is_some() {
#[link(name = "kernel32")]
unsafe extern "system" {
fn WerSetFlags(flags: u32) -> i32;
}
// WER_FAULT_REPORTING_NO_UI: a crash ends the child instead of waiting on a dialog.
unsafe { WerSetFlags(0x20) };
let stop = Instant::now() + Duration::from_secs(5);
let turn = Arc::new(Mutex::new(()));
let readers: Vec<_> = (0..threads)
.map(|_| {
let turn = turn.clone();
std::thread::spawn(move || {
let mut reads = 0usize;
while Instant::now() < stop {
let _turn = serialized.then(|| turn.lock().unwrap());
// None: another reader kept the clipboard open through every retry.
let read = text();
assert!(matches!(read.as_deref(), None | Some(READ_TEXT)), "read {read:?}");
reads += 1;
}
reads
})
})
.collect();
let reads: usize = readers.into_iter().map(|reader| reader.join().unwrap()).sum();
println!("reads: {reads}");
return;
}
// The tests share the one clipboard: one at a time, so none rewrites it under another.
static SERIAL: Mutex<()> = Mutex::new(());
let _serial = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let earlier = text();
if let Err(error) = set_text(READ_TEXT, 0) {
eprintln!("skipped: the clipboard cannot be written here ({error})");
return;
}
let mut child = Command::new(std::env::current_exe().unwrap())
.args(["--exact", test, "--test-threads=1", "--nocapture"])
.env(STAGE, "1")
.spawn()
.unwrap();
let deadline = Instant::now() + Duration::from_secs(60);
let status = loop {
if let Some(status) = child.try_wait().unwrap() {
break Some(status);
}
if Instant::now() > deadline {
let _ = child.kill();
break None;
}
std::thread::sleep(Duration::from_millis(100));
};
if let Some(earlier) = earlier.filter(|earlier| !earlier.is_empty()) {
let _ = set_text(&earlier, 0);
}
let status = status.expect("the reads did not finish within 60 s");
assert!(
status.success(),
"clipboard reads ended the process: exit code {:#x}",
status.code().unwrap_or_default() as u32
);
}
#[cfg(windows)]
#[test]
fn text_reads_on_one_thread_do_not_corrupt_the_heap() {
reads_survive("tests::text_reads_on_one_thread_do_not_corrupt_the_heap", 1, false);
}
#[cfg(windows)]
#[test]
fn text_reads_taking_turns_do_not_corrupt_the_heap() {
reads_survive("tests::text_reads_taking_turns_do_not_corrupt_the_heap", 8, true);
}
/// The project view reads the clipboard's text whenever a window gains focus, on
/// whichever worker thread the command lands, so restoring a minimized window can
/// start several reads at once (#6388).
#[cfg(windows)]
#[test]
fn concurrent_text_reads_do_not_corrupt_the_heap() {
reads_survive("tests::concurrent_text_reads_do_not_corrupt_the_heap", 8, false);
}
fn paths(list: &[&str]) -> Vec<PathBuf> {
list.iter().map(PathBuf::from).collect()
}
+1 -1
Переглянути файл
@@ -27,4 +27,4 @@ libc = "0.2"
[target.'cfg(windows)'.dependencies]
dirs.workspace = true
tracing.workspace = true
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }
+74
Переглянути файл
@@ -0,0 +1,74 @@
//! Parallelism for build tools whose default is one compiler process at a time.
//!
//! `cmake --build` with a Makefile generator (the default) compiles one file at a
//! time unless it is given `-j N`; the IDE asks for one job per logical CPU. A count
//! the user wrote into the build arguments is left alone.
/// Jobs a native build tool gets when the user did not choose a count.
pub fn default_jobs() -> usize {
std::thread::available_parallelism().map_or(1, |jobs| jobs.get())
}
/// Appends `-j <jobs>` unless `args` already carries the user's own count. The count
/// goes before a `--` separator, so cmake's own options stay cmake's and the native
/// build tool's options stay last.
pub fn append_default_jobs(args: &mut Vec<String>) {
if args.iter().any(|arg| is_jobs_flag(arg)) {
return;
}
let jobs = default_jobs().to_string();
let at = args.iter().position(|arg| arg == "--").unwrap_or(args.len());
args.splice(at..at, ["-j".to_owned(), jobs]);
}
/// `-j`, `-j8`, `--parallel`, `--parallel=8`, `--jobs`, `--jobs=8`.
fn is_jobs_flag(arg: &str) -> bool {
let count = |rest: &str| rest.chars().all(|c| c.is_ascii_digit());
arg.strip_prefix("-j").is_some_and(count)
|| arg.strip_prefix("--parallel=").is_some_and(count)
|| arg.strip_prefix("--jobs=").is_some_and(count)
|| arg == "--parallel"
|| arg == "--jobs"
}
#[cfg(test)]
mod tests {
use super::*;
fn args_of(values: &[&str]) -> Vec<String> {
values.iter().map(|value| (*value).to_owned()).collect()
}
#[test]
fn the_default_is_one_job_per_logical_cpu() {
let expected = std::thread::available_parallelism().map_or(1, |jobs| jobs.get());
assert_eq!(default_jobs(), expected);
}
#[test]
fn a_build_without_a_count_gets_one() {
let mut argv = args_of(&["--build", "build", "--config", "Debug"]);
append_default_jobs(&mut argv);
assert_eq!(argv, args_of(&["--build", "build", "--config", "Debug", "-j", &default_jobs().to_string()]));
}
#[test]
fn a_count_the_user_chose_is_left_alone() {
let own: [&[&str]; 6] =
[&["-j", "2"], &["-j8"], &["-j", "2"], &["--parallel", "2"], &["--parallel=2"], &["--jobs=2"]];
for flags in own {
let mut argv = args_of(&["--build", "build"]);
argv.extend(flags.iter().map(|value| (*value).to_owned()));
let expected = argv.clone();
append_default_jobs(&mut argv);
assert_eq!(argv, expected, "the build arguments set the count");
}
}
#[test]
fn the_count_stays_before_native_build_tool_options() {
let mut argv = args_of(&["--build", "build", "--", "VERBOSE=1"]);
append_default_jobs(&mut argv);
assert_eq!(argv, args_of(&["--build", "build", "-j", &default_jobs().to_string(), "--", "VERBOSE=1"]));
}
}
+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(())
}
+56
Переглянути файл
@@ -33,6 +33,10 @@ pub struct EditorGeneralSettings {
pub remove_trailing_blank_lines: bool,
/// Copy as rich text (HTML with syntax colours) by default.
pub rich_text_copy: bool,
/// Gutter › Highlight modified lines in the gutter: the VCS change bars next to the line numbers.
pub highlight_modified_lines: bool,
/// Gutter › Highlight modified lines in error stripe on the scrollbar (with `highlight_modified_lines`).
pub highlight_modified_lines_in_scrollbar: bool,
}
impl Default for EditorGeneralSettings {
@@ -51,6 +55,8 @@ impl Default for EditorGeneralSettings {
keep_trailing_on_caret_line: true,
remove_trailing_blank_lines: false,
rich_text_copy: true,
highlight_modified_lines: true,
highlight_modified_lines_in_scrollbar: true,
}
}
}
@@ -296,12 +302,42 @@ pub struct SmartKeysSettings {
pub simultaneous_tag_editing: bool,
/// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
pub reformat_on_paste: String,
/// Advanced Settings: Copy/Cut without a selection copies the whole caret lines.
pub copy_line_when_no_selection: bool,
/// Advanced Settings: Copy selects the lines copied without a selection.
pub select_copied_line: bool,
/// Advanced Settings: linewise paste `above` the caret | `caret` | `trim` at mid-line.
pub line_paste_mode: String,
pub escape_on_paste: bool,
pub smart_indent: bool,
/// Enter › Insert documentation comment stub: Enter after `/**` closes the comment.
pub insert_doc_stub: bool,
/// Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`.
pub backspace_unindent: String,
/// The styles Cycle Identifier Case goes through.
pub cycle_case: CycleCaseSettings,
}
/// Editor › General › Smart Keys › Cycle Identifier Case: the styles the action goes through.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CycleCaseSettings {
/// `snake_case`
pub snake: bool,
/// `SCREAMING_SNAKE_CASE`
pub screaming: bool,
/// `kebab-case`
pub kebab: bool,
/// `camelCase`
pub camel: bool,
/// `PascalCase`
pub pascal: bool,
}
impl Default for CycleCaseSettings {
fn default() -> Self {
Self { snake: true, screaming: true, kebab: true, camel: true, pascal: true }
}
}
impl Default for SmartKeysSettings {
@@ -316,10 +352,14 @@ impl Default for SmartKeysSettings {
semicolon_at_statement_end: true,
simultaneous_tag_editing: true,
reformat_on_paste: "indentEachLine".into(),
copy_line_when_no_selection: true,
select_copied_line: true,
line_paste_mode: "above".into(),
escape_on_paste: true,
smart_indent: true,
insert_doc_stub: true,
backspace_unindent: "autoindent".into(),
cycle_case: CycleCaseSettings::default(),
}
}
}
@@ -361,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,
@@ -396,6 +438,7 @@ impl Default for InlayHintsSettings {
fn default() -> Self {
Self {
types: true,
js_ts_types: true,
parameters: true,
other: true,
closing_labels: true,
@@ -670,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;
+87 -4
Переглянути файл
@@ -13,13 +13,70 @@ use std::sync::Arc;
/// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
/// started or failed to.
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
/// `RunConfig`, its before launch tasks already done) in the Run tool window as the user's
/// Run would, answered the same way. `DebugConfiguration` does the same in Debug mode, so
/// the window's own Debug action builds the launch. `Breakpoints` replaces the window's
/// breakpoints, which the editor owns, persists and mirrors to the backend.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum McpUiRequest {
Confirm { client: String, tool: String, subject: String, project: String, detail: Option<String> },
OpenFile { path: crate::IpcPath, line: Option<u32>, column: Option<u32> },
AgentRun { name: String, command: String, cwd: crate::IpcPath, env: BTreeMap<String, String> },
Confirm {
client: String,
tool: String,
subject: String,
project: String,
detail: Option<String>,
/// The project is served without a window: the request shows in another project's window,
/// which names it and keeps the keyboard focus where it is.
#[serde(default)]
background: bool,
},
OpenFile {
path: crate::IpcPath,
line: Option<u32>,
column: Option<u32>,
},
AgentRun {
name: String,
command: String,
cwd: crate::IpcPath,
env: BTreeMap<String, String>,
},
RunConfiguration {
#[specta(type = specta_typescript::Unknown)]
config: serde_json::Value,
},
/// Start a run configuration in Debug mode as the IDE's Debug action would.
DebugConfiguration {
#[specta(type = specta_typescript::Unknown)]
config: serde_json::Value,
},
/// Sets one line breakpoint in the window's own list, by absolute editor path. The window
/// applies the edit to its current list, so a user's pending edit is not overwritten.
SetBreakpoint {
path: String,
breakpoint: McpBreakpoint,
},
/// Removes breakpoints from the window's own list. With no path, removes every line
/// breakpoint; with a path but no line, removes all of that file's breakpoints.
RemoveBreakpoints {
path: Option<String>,
line: Option<u32>,
},
/// Flushes the editor's pending breakpoint syncs before an agent reads the backend list.
FlushBreakpoints,
}
/// A line breakpoint in an MCP request, with a 1-based line like every other MCP tool.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct McpBreakpoint {
pub line: u32,
pub enabled: bool,
pub condition: Option<String>,
pub hit_condition: Option<String>,
pub log_message: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -27,6 +84,10 @@ pub enum McpUiRequest {
pub enum IdeEvent {
/// Project data source settings changed; reload the Database tree.
DbSourcesChanged,
/// A Python run saved a matplotlib figure for the Plots tool window (a PNG file).
PlotAdded {
path: String,
},
McpRequest {
id: u32,
request: McpUiRequest,
@@ -38,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.
@@ -98,6 +161,8 @@ pub enum IdeEvent {
DocDiskConflict {
doc: DocId,
path: String,
/// The file no longer exists: saving recreates it, and there is nothing to load.
deleted: bool,
},
/// A complete workspace edit can be undone as one operation.
WorkspaceEditApplied {
@@ -117,6 +182,15 @@ pub enum IdeEvent {
/// See `DocumentInfo::ui_mode`.
ui_mode: Option<String>,
},
/// A reload from disk changed an open document's encoding, BOM or line ending (the file
/// was rewritten by another program), which the editor only learns when it opens.
DocEncoding {
doc: DocId,
encoding: String,
has_bom: bool,
/// A `LineEnding` in its serialized form: `lf`, `crLf` or `cr`.
line_ending: String,
},
/// Full replacement of diagnostics for one file from one producer.
Diagnostics {
path: crate::IpcPath,
@@ -179,6 +253,15 @@ pub enum IdeEvent {
message: String,
actions: Vec<String>,
},
/// A language server asked to show a document (`window/showDocument`), e.g. the
/// expansion file of sourcekit-lsp's Expand Macro. `path` is set for a file to open in
/// an editor, at `selection` when given; without it `uri` is a web link for the browser.
LspShowDocument {
uri: String,
path: Option<crate::IpcPath>,
selection: Option<crate::Range>,
take_focus: bool,
},
/// The request was answered or timed out; every window drops its dialog.
LspMessageRequestDone {
id: u32,
+3
Переглянути файл
@@ -4,7 +4,9 @@
//! feature crates depend on `ide-core` and never on each other's internals.
//! All IPC-facing types derive `specta::Type`, which generates `src/bindings.ts`.
pub mod build_jobs;
pub mod cli_process;
pub mod cmake_file_api;
pub mod editor_settings;
pub mod error;
pub mod event;
@@ -18,6 +20,7 @@ pub mod ipc_path;
pub mod java_runtime;
pub mod jsonc;
pub mod memory;
pub mod network_path;
pub mod output_encoding;
pub mod output_rate;
pub mod platform;
+72
Переглянути файл
@@ -1,5 +1,35 @@
//! Returning freed heap pages to the OS.
use std::sync::Mutex;
use std::time::{Duration, Instant};
/// Like [`release_free_pages`], on a background thread once 2 s pass without another call:
/// closing a project or a batch of tabs frees memory in bursts, released once.
pub fn release_free_pages_soon() {
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
debounce(&DUE, Duration::from_secs(2), release_free_pages);
}
/// Runs `run` on a background thread once `delay` passes after the last call.
fn debounce(due: &'static Mutex<Option<Instant>>, delay: Duration, run: fn()) {
let idle = due.lock().unwrap().replace(Instant::now() + delay).is_none();
if idle {
std::thread::spawn(move || {
loop {
let mut slot = due.lock().unwrap();
let left = slot.map_or(Duration::ZERO, |at| at.saturating_duration_since(Instant::now()));
if left.is_zero() {
*slot = None;
drop(slot);
return run();
}
drop(slot);
std::thread::sleep(left);
}
});
}
}
/// Hands pages the allocator has freed but kept back to the OS. Call after a burst of
/// short-lived allocations (a full index scan); until then they still count towards the
/// process's memory footprint.
@@ -18,3 +48,45 @@ pub fn release_free_pages() {
libc::malloc_trim(0);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
static RUNS: AtomicUsize = AtomicUsize::new(0);
fn count() {
RUNS.fetch_add(1, SeqCst);
}
#[test]
fn a_burst_of_calls_runs_once_after_the_delay() {
// Timing-based: a loaded CI machine can oversleep, so each check allows for that.
let delay = Duration::from_millis(500);
let (mut last, mut widest_gap) = (None::<Instant>, Duration::ZERO);
for _ in 0..5 {
debounce(&DUE, delay, count);
let now = Instant::now();
widest_gap = widest_gap.max(last.map_or(Duration::ZERO, |l| now - l));
last = Some(now);
std::thread::sleep(Duration::from_millis(20));
}
if last.unwrap().elapsed() < delay {
assert_eq!(RUNS.load(SeqCst), 0, "ran before the delay passed");
}
let deadline = Instant::now() + Duration::from_secs(10);
while RUNS.load(SeqCst) == 0 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
// A second run would come within another delay.
std::thread::sleep(delay);
if widest_gap < delay {
assert_eq!(RUNS.load(SeqCst), 1);
} else {
assert!(RUNS.load(SeqCst) >= 1);
}
release_free_pages_soon();
}
}
+53
Переглянути файл
@@ -0,0 +1,53 @@
//! Whether a path is on a network file system, where every stat is a round trip to a server.
use std::path::{Component, Path, Prefix};
/// A UNC path (`\\server\share`, `\\wsl.localhost\…`) or a drive letter mapped to a network
/// share (`Z:\`). Always `false` off Windows: there a mount point is not visible in the path.
pub fn is_network_path(path: &Path) -> bool {
match path.components().next() {
Some(Component::Prefix(prefix)) => match prefix.kind() {
Prefix::UNC(..) | Prefix::VerbatimUNC(..) => true,
Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => is_remote_drive(letter),
_ => false,
},
_ => false,
}
}
#[cfg(windows)]
fn is_remote_drive(letter: u8) -> bool {
use windows_sys::Win32::Storage::FileSystem::GetDriveTypeW;
/// `DRIVE_REMOTE` (WindowsProgramming).
const DRIVE_REMOTE: u32 = 4;
let root = [u16::from(letter), u16::from(b':'), u16::from(b'\\'), 0];
// SAFETY: `root` is a NUL-terminated wide string that outlives the call.
unsafe { GetDriveTypeW(root.as_ptr()) == DRIVE_REMOTE }
}
#[cfg(not(windows))]
fn is_remote_drive(_letter: u8) -> bool {
false
}
#[cfg(test)]
mod tests {
use super::is_network_path;
use std::path::Path;
#[test]
fn unc_paths_are_on_the_network() {
if cfg!(windows) {
assert!(is_network_path(Path::new(r"\\server\share\repo")));
assert!(is_network_path(Path::new(r"\\?\UNC\server\share\repo")));
assert!(is_network_path(Path::new(r"\\wsl.localhost\Ubuntu\home")));
}
assert!(!is_network_path(Path::new("relative/path")));
}
#[test]
fn a_local_directory_is_not() {
let dir = std::env::temp_dir();
assert!(!is_network_path(&dir), "{}", dir.display());
}
}
+116
Переглянути файл
@@ -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`].
@@ -622,6 +640,30 @@ pub fn host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
apply_changes(std::env::vars_os().collect(), &child_env_changes(Some(dir))).into_iter()
}
/// Whether `(key, value)` can go into a Windows environment block (`KEY=VALUE\0`
/// entries, then a final `\0`). `CreateProcessW` / `NtCreateUserProcess` returns
/// `ERROR_INVALID_PARAMETER` (os error 87) when an entry has an empty name or an
/// interior NUL. That happens when a `REG_MULTI_SZ` user environment value is
/// loaded into the process or re-read from the registry (#6806): the extra NUL
/// is treated as an entry separator and leaves a fragment with no `=`.
pub fn is_spawnable_env_pair(key: &OsStr, value: &OsStr) -> bool {
!key.is_empty() && !contains_ascii(key, 0) && !contains_ascii(key, b'=') && !contains_ascii(value, 0)
}
fn contains_ascii(s: &OsStr, byte: u8) -> bool {
s.as_encoded_bytes().contains(&byte)
}
/// [`host_vars`] without pairs that a Windows PTY spawn would reject.
pub fn spawnable_host_vars() -> impl Iterator<Item = (OsString, OsString)> {
host_vars().filter(|(k, v)| is_spawnable_env_pair(k, v))
}
/// [`host_vars_in`] without pairs that a Windows PTY spawn would reject.
pub fn spawnable_host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
host_vars_in(dir).filter(|(k, v)| is_spawnable_env_pair(k, v))
}
/// [`std::env::var_os`] as a child should see it (see [`host_env`]), the login shell's value
/// included when this process lacks the variable.
pub fn host_var_os(key: impl AsRef<OsStr>) -> Option<OsString> {
@@ -946,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()));
@@ -1176,6 +1240,29 @@ mod tests {
set_env_overlay(Vec::new());
}
#[test]
fn a_child_inside_a_project_gets_its_xcode() {
let root = std::path::Path::new("/openidea-test-process/xcode");
let xcode = "/Applications/Xcode-beta.app/Contents/Developer";
crate::project_env::set_developer_dir(root, Some(xcode.into()));
let developer_dir = |cmd: &Command| {
cmd.get_envs().find(|(n, _)| *n == "DEVELOPER_DIR").and_then(|(_, v)| v.map(OsStr::to_owned))
};
// xcodebuild, xcrun, a language server: a `Command` started in the project.
let mut tool = Command::new("xcodebuild");
prepare(tool.current_dir(root.join("App")));
assert_eq!(developer_dir(&tool), Some(xcode.into()));
// A terminal: a PTY applies the fixes itself.
assert!(host_env_fixes_in(root).contains(&("DEVELOPER_DIR".into(), Some(xcode.into()))));
let mut elsewhere = Command::new("xcodebuild");
prepare(elsewhere.current_dir("/openidea-test-process/other"));
assert_eq!(developer_dir(&elsewhere), None);
crate::project_env::set_developer_dir(root, None);
let mut tool = Command::new("xcodebuild");
prepare(tool.current_dir(root));
assert_eq!(developer_dir(&tool), None, "empty: the system default");
}
#[test]
fn a_child_inside_a_project_gets_its_environment() {
let root = std::path::Path::new("/openidea-test-process/project");
@@ -1217,6 +1304,35 @@ mod tests {
assert!(host_vars_in(root).all(|(k, _)| k != "OPENIDEA_PROJECT_VAR"));
}
fn os_from_bytes(bytes: &[u8]) -> OsString {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStringExt;
OsString::from_vec(bytes.to_vec())
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStringExt;
OsString::from_wide(&bytes.iter().copied().map(u16::from).collect::<Vec<_>>())
}
}
#[test]
fn spawnable_env_pairs_reject_empty_keys_equals_and_interior_nuls() {
let ok_key = OsString::from("PATH");
let ok_val = OsString::from("/bin");
assert!(is_spawnable_env_pair(&ok_key, &ok_val));
assert!(!is_spawnable_env_pair(OsStr::new(""), &ok_val));
assert!(!is_spawnable_env_pair(OsStr::new("FOO=BAR"), &ok_val));
// A REG_MULTI_SZ value's interior NUL would split the environment block,
// leaving a fragment with no `=` (#6806). An empty name is also rejected.
assert!(!is_spawnable_env_pair(&os_from_bytes(b""), &os_from_bytes(b"132786")));
assert!(!is_spawnable_env_pair(&ok_key, &os_from_bytes(b"1788051509\x00132786")));
assert!(!is_spawnable_env_pair(&os_from_bytes(b"132786\x00"), &ok_val));
assert!(spawnable_host_vars().all(|(k, v)| is_spawnable_env_pair(&k, &v)));
assert!(spawnable_host_vars().any(|(k, _)| k == "PATH" || k == "Path"));
}
#[test]
fn changes_apply_in_order() {
let vars = apply_changes(
+62 -2
Переглянути файл
@@ -16,13 +16,21 @@ struct Entry {
root: PathBuf,
direnv: Vec<(OsString, Option<OsString>)>,
github_token: Option<OsString>,
developer_dir: Option<OsString>,
changes: Changes,
loading: bool,
}
impl Entry {
fn new(root: PathBuf) -> Self {
Self { root, direnv: Vec::new(), github_token: None, changes: Changes::default(), loading: false }
Self {
root,
direnv: Vec::new(),
github_token: None,
developer_dir: None,
changes: Changes::default(),
loading: false,
}
}
fn rebuild(&mut self) {
@@ -33,11 +41,16 @@ impl Entry {
// `.envrc` entries override the project GitHub token when both define `GH_TOKEN`.
combined.retain(|(k, _)| !self.direnv.iter().any(|(dk, _)| dk == k));
combined.extend(self.direnv.iter().cloned());
// The project's chosen Xcode overrides a `DEVELOPER_DIR` from `.envrc`: it is set for this project only.
if let Some(dir) = &self.developer_dir {
combined.retain(|(k, _)| k != DEVELOPER_DIR);
combined.push((DEVELOPER_DIR.into(), Some(dir.clone())));
}
self.changes = Arc::new(combined);
}
fn is_idle_empty(&self) -> bool {
!self.loading && self.direnv.is_empty() && self.github_token.is_none()
!self.loading && self.direnv.is_empty() && self.github_token.is_none() && self.developer_dir.is_none()
}
}
@@ -144,6 +157,31 @@ pub fn set_github_token(root: &Path, token: Option<OsString>) -> bool {
}
}
const DEVELOPER_DIR: &str = "DEVELOPER_DIR";
/// Sets or clears the `DEVELOPER_DIR` (the Xcode `xcrun`, `xcodebuild` and sourcekit-lsp use)
/// injected for children started in `root`. Returns whether it changed.
pub fn set_developer_dir(root: &Path, dir: Option<OsString>) -> bool {
let dir = dir.filter(|d| !d.is_empty());
let mut entries = entries();
let idx = match entries.iter().position(|e| e.root == root) {
Some(idx) if entries[idx].developer_dir == dir => return false,
Some(idx) => idx,
None if dir.is_none() => return false,
None => {
entries.push(Entry::new(root.to_path_buf()));
entries.len() - 1
}
};
let entry = &mut entries[idx];
entry.developer_dir = dir;
entry.rebuild();
if entry.is_idle_empty() {
entries.remove(idx);
}
true
}
/// The project-scoped `GH_TOKEN` configured for the innermost project holding `dir`, if any.
pub fn github_token(dir: &Path) -> Option<OsString> {
find(&entries(), dir).and_then(|e| e.github_token.clone())
@@ -202,6 +240,28 @@ mod tests {
assert!(for_dir(inner).is_empty());
}
#[test]
fn the_projects_xcode_wins_over_envrc_and_clears() {
let root = Path::new("/openidea-test-env/xcode");
set(root, vec![change("DEVELOPER_DIR", Some("/envrc")), change("A", Some("1"))]);
assert!(set_developer_dir(root, Some("/Applications/Xcode-beta.app/Contents/Developer".into())));
assert!(!set_developer_dir(root, Some("/Applications/Xcode-beta.app/Contents/Developer".into())));
assert_eq!(
*for_dir(&root.join("App")),
[change("A", Some("1")), change("DEVELOPER_DIR", Some("/Applications/Xcode-beta.app/Contents/Developer"))]
);
assert!(set_developer_dir(root, None));
assert_eq!(*for_dir(root), [change("DEVELOPER_DIR", Some("/envrc")), change("A", Some("1"))]);
remove(root);
assert!(for_dir(root).is_empty());
let alone = Path::new("/openidea-test-env/xcode-alone");
assert!(!set_developer_dir(alone, Some("".into())), "empty is the system default");
assert!(set_developer_dir(alone, Some("/X".into())));
assert_eq!(*for_dir(alone), [change("DEVELOPER_DIR", Some("/X"))]);
assert!(set_developer_dir(alone, None));
assert!(entries().iter().all(|e| e.root != alone), "an empty entry is dropped");
}
#[test]
fn waiting_ends_once_the_environment_is_read() {
let root = Path::new("/openidea-test-env/waiting");
+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();
+7 -1
Переглянути файл
@@ -203,6 +203,9 @@ pub enum RunTargetKind {
Docker,
/// A new container of a Compose service (`docker compose run --rm`).
Compose,
/// A WSL distribution on this Windows machine (`wsl.exe -d <distro>`), the project read
/// through `/mnt/<drive>`.
Wsl,
}
/// Build, Execution, Deployment › Run Targets: run configurations on another machine
@@ -215,7 +218,8 @@ pub struct RunTarget {
pub name: String,
/// [`SshConfiguration::id`] (SSH).
pub ssh_config: String,
/// Remote folder the project is synchronised to and run from (SSH).
/// Remote folder the project is synchronised to and run from (SSH); the project's Linux
/// path, empty = its `/mnt/<drive>` path (WSL).
pub project_root: String,
/// Upload changed project files before each run (SSH).
pub sync_before_run: bool,
@@ -241,6 +245,8 @@ pub struct RunTarget {
pub run_options: String,
/// Run as the image's user instead of the project folder's owner (Linux).
pub image_user: bool,
/// Distribution name, as `wsl.exe -l -q` lists it (WSL).
pub distro: String,
}
/// A plugin-owned argv wrapper for project runs (API 1.4).
+580 -2
Переглянути файл
@@ -52,6 +52,8 @@ pub struct Settings {
/// Per language server, by name (`rust-analyzer`): launch and protocol
/// options on top of the language definition, or a server defined here.
pub language_servers: BTreeMap<String, LanguageServerSettings>,
/// Languages & Frameworks › JSON Schema Mappings: schemas for JSON and YAML files.
pub json_schemas: Vec<JsonSchemaMapping>,
/// Tools › Download sources: a mirror prefix for the release archives the installer fetches.
pub tool_downloads: ToolDownloadSettings,
/// Editor › Inspections profiles.
@@ -66,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).
@@ -78,6 +82,8 @@ pub struct Settings {
pub file_colors: FileColorSettings,
/// Database › Query Execution, Languages & Frameworks › SQL Resolution Scopes.
pub database: DatabaseSettings,
/// Settings › Settings Sync (global only, never synced itself).
pub settings_sync: SettingsSyncSettings,
/// Plugin settings (`[contributes.settings]`): plugin id → its values by key.
#[specta(type = BTreeMap<String, BTreeMap<String, specta_typescript::Unknown>>)]
pub plugins: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
@@ -99,6 +105,20 @@ pub struct AgentSettings {
pub smooth_text: bool,
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
pub fit_window_width: bool,
/// Chat text follows the interface font (Appearance › Use custom font).
pub chat_use_ui_font: bool,
/// Chat text family when it does not follow the interface font.
pub chat_font_family: String,
/// Covers characters the chat font lacks.
pub chat_font_fallback: String,
pub chat_font_size: u32,
/// Code in chat follows the built-in code font.
pub code_use_default_font: bool,
/// Code family when it does not follow the built-in code font.
pub code_font_family: String,
/// Covers characters the code font lacks.
pub code_font_fallback: String,
pub code_font_size: u32,
#[serde(deserialize_with = "or_default")]
#[specta(type = ThinkingDisplay)]
pub thinking: ThinkingDisplay,
@@ -120,6 +140,19 @@ pub struct AgentSettings {
#[serde(deserialize_with = "or_default")]
#[specta(type = NewTaskApprovals)]
pub new_task_approvals: NewTaskApprovals,
/// How long an in-flight turn hit by a transient network outage waits and probes for
/// connectivity before degrading to a manual Resume prompt.
#[serde(deserialize_with = "or_default")]
#[specta(type = NetworkRetryWindow)]
pub network_retry_window: NetworkRetryWindow,
/// What opening a project does with tasks interrupted when OpenIDEA closed or restarted.
/// User settings only.
#[serde(deserialize_with = "or_default")]
#[specta(type = ResumeInterruptedPolicy)]
pub resume_interrupted: ResumeInterruptedPolicy,
/// Warn before closing a local window whose project still has running agent tasks.
/// User settings only.
pub confirm_terminate_on_close: bool,
/// Settings new tasks of an agent start with: agent id → option id → value.
#[serde(deserialize_with = "agent_defaults")]
#[specta(type = BTreeMap<String, BTreeMap<String, String>>)]
@@ -134,6 +167,20 @@ pub struct AgentSettings {
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, AgentSkillPolicy>)]
pub skills: BTreeMap<String, AgentSkillPolicy>,
/// Agent memory policies (`[agents.memory]`): cross-session auto-memory mode, built-in
/// MCP memory bridge, and per-entry modes; tracked files on disk are never modified.
#[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 {
@@ -145,15 +192,29 @@ impl Default for AgentSettings {
show_cost: false,
smooth_text: true,
fit_window_width: false,
chat_use_ui_font: true,
chat_font_family: "Inter".into(),
chat_font_fallback: String::new(),
chat_font_size: 13,
code_use_default_font: true,
code_font_family: "JetBrains Mono".into(),
code_font_fallback: String::new(),
code_font_size: 13,
thinking: ThinkingDisplay::Auto,
tool_calls: ToolCallDisplay::Grouped,
expand_tool_output: false,
send_with: SendKey::Enter,
while_running: WhileRunning::Queue,
new_task_approvals: NewTaskApprovals::Bypass,
network_retry_window: NetworkRetryWindow::Hour1,
resume_interrupted: ResumeInterruptedPolicy::Ask,
confirm_terminate_on_close: true,
defaults: BTreeMap::new(),
mcp_servers: BTreeMap::new(),
skills: BTreeMap::new(),
memory: AgentMemorySettings::default(),
plugins: AgentPluginSettings::default(),
automations: AgentAutomationSettings::default(),
}
}
}
@@ -237,6 +298,169 @@ impl Default for AgentSkillPolicy {
}
}
/// How an agent instruction, rule, or memory entry may load (`[agents.memory.entries.<id>] mode = …`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemoryMode {
/// Load according to its native rules (always for instructions, matching files for path-scoped rules).
#[default]
Auto,
/// Force-load into every session regardless of path scoping.
Always,
/// Exclude from sessions where the harness supports it.
Off,
}
/// How an agent's automatic cross-session memory runs (`[agents.memory] autoMemory = …`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AutoMemoryMode {
/// Leave the agent's own configuration untouched.
#[default]
Inherit,
/// Read past memories and record new ones.
ReadWrite,
/// Read past memories without recording new ones.
ReadOnly,
/// Neither read nor record cross-session auto-memories.
Off,
}
/// One memory or instruction entry's policy in Settings › Agents › Memory.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentMemoryEntryPolicy {
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentMemoryMode)]
pub mode: AgentMemoryMode,
/// Agent provider ids this entry applies to; empty means all agents.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub agents: Vec<String>,
}
impl Default for AgentMemoryEntryPolicy {
fn default() -> Self {
Self { mode: AgentMemoryMode::Auto, agents: Vec::new() }
}
}
/// Per-provider auto-memory policy (`[agents.memory.providers.<id>]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentProviderMemoryPolicy {
#[serde(deserialize_with = "or_default")]
#[specta(type = AutoMemoryMode)]
pub auto_memory: AutoMemoryMode,
}
/// Agent memory settings (`[agents.memory]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentMemorySettings {
/// Default cross-session auto-memory policy across agents.
#[serde(deserialize_with = "or_default")]
#[specta(type = AutoMemoryMode)]
pub auto_memory: AutoMemoryMode,
/// Optional per-provider auto-memory overrides (`[agents.memory.providers.<provider>]`).
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
#[specta(type = BTreeMap<String, AgentProviderMemoryPolicy>)]
pub providers: BTreeMap<String, AgentProviderMemoryPolicy>,
/// Per-entry modes (`[agents.memory.entries.<id>]`).
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
#[specta(type = BTreeMap<String, AgentMemoryEntryPolicy>)]
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>
@@ -338,6 +562,49 @@ pub enum NewTaskApprovals {
Ask,
}
/// Default auto-retry window for transient network outages during an active agent turn.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
pub enum NetworkRetryWindow {
#[serde(rename = "off")]
Off,
#[serde(rename = "15m")]
Minutes15,
#[default]
#[serde(rename = "1h")]
Hour1,
#[serde(rename = "4h")]
Hours4,
#[serde(rename = "24h")]
Hours24,
}
impl NetworkRetryWindow {
pub fn minutes(self) -> u32 {
match self {
Self::Off => 0,
Self::Minutes15 => 15,
Self::Hour1 => 60,
Self::Hours4 => 240,
Self::Hours24 => 1440,
}
}
}
/// How interrupted agent tasks are handled when a project reopens.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum ResumeInterruptedPolicy {
/// Show Interrupted markers, banner and balloon; wait for the user to click Resume.
#[default]
Ask,
/// Auto-resume tasks interrupted by an IDE restart or backend upgrade within 15 minutes.
Restart,
/// Auto-resume tasks interrupted by close, quit or restart within the session recovery window.
Window,
/// Settle quietly to Ready with no Interrupted markers or balloons.
Off,
}
/// Which folders without an open window the MCP server still serves tools for.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -438,15 +705,91 @@ 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.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct SettingsSyncSettings {
/// Clone URL (a secret GitHub Gist's works too, though anyone with its link can read it);
/// empty = sync off.
pub repository: String,
/// Sync on startup and after the settings change, besides Sync Now.
pub auto: bool,
pub appearance: bool,
/// Editor settings, color schemes, code style, inspections and spelling.
pub editor: bool,
pub keymaps: bool,
/// Every other setting that is not machine-specific.
pub other: bool,
/// Live, file and postfix templates.
pub templates: bool,
pub macros: bool,
/// Tool window layouts and view options.
pub ui: bool,
/// The list of installed plugins: missing ones are offered, never installed or removed.
pub plugins: bool,
}
impl Default for SettingsSyncSettings {
fn default() -> Self {
Self {
repository: String::new(),
auto: true,
appearance: true,
editor: true,
keymaps: true,
other: true,
templates: true,
macros: true,
ui: true,
plugins: true,
}
}
}
/// Absent profiles retain automatic discovery for existing projects.
#[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)]
@@ -460,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 {
@@ -472,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 {
@@ -587,12 +981,15 @@ 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(),
scopes: Vec::new(),
json_schemas: Vec::new(),
file_colors: FileColorSettings::default(),
database: DatabaseSettings::default(),
settings_sync: SettingsSyncSettings::default(),
plugins: BTreeMap::new(),
}
}
@@ -612,6 +1009,17 @@ pub struct NamedScope {
pub pattern: String,
}
/// A schema for the JSON and YAML files matching `files`; wins over a built-in SchemaStore mapping.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct JsonSchemaMapping {
pub name: String,
/// A URL, or a file path relative to the project.
pub schema: String,
/// Project-relative paths or glob patterns (`config/*.json`, `**/*.app.yaml`).
pub files: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct FileColorSettings {
@@ -840,6 +1248,8 @@ pub struct AppearanceSettings {
pub smooth_scrolling: bool,
pub full_path_in_title: bool,
pub project_colors_in_toolbar: bool,
/// Strength of the project colour tint in the window header, in percent (10–70).
pub project_color_strength: u8,
pub dnd_with_alt_only: bool,
pub menu_icons: bool,
/// `hamburger` | `merged` | `toolbar` (a separate row): main menu presentation in the frameless title bar.
@@ -858,6 +1268,8 @@ pub struct AppearanceSettings {
pub widescreen_tool_windows: bool,
/// Each tool window keeps its own size; off, the windows of a side share one.
pub remember_tool_window_sizes: bool,
/// Tool window shortcuts hide an open unfocused window right away instead of focusing it first.
pub toggle_tool_windows_on_shortcut: bool,
/// View › Appearance › Toolbar; hidden leaves IDEA's compact window header.
pub show_main_toolbar: bool,
pub show_status_bar: bool,
@@ -979,6 +1391,7 @@ impl Default for AppearanceSettings {
smooth_scrolling: true,
full_path_in_title: false,
project_colors_in_toolbar: true,
project_color_strength: 22,
dnd_with_alt_only: false,
menu_icons: true,
main_menu_style: "hamburger".into(),
@@ -991,6 +1404,7 @@ impl Default for AppearanceSettings {
show_tool_window_badges: true,
widescreen_tool_windows: false,
remember_tool_window_sizes: false,
toggle_tool_windows_on_shortcut: false,
show_main_toolbar: true,
show_status_bar: true,
navigation_bar: NavigationBarPosition::StatusBar,
@@ -1228,6 +1642,7 @@ pub struct LanguagesSettings {
pub arduino: ArduinoSettings,
pub zig: ZigSettings,
pub flutter: FlutterSettings,
pub swift: SwiftSettings,
}
impl Default for LanguagesSettings {
@@ -1261,6 +1676,7 @@ impl Default for LanguagesSettings {
arduino: ArduinoSettings::default(),
zig: ZigSettings::default(),
flutter: FlutterSettings::default(),
swift: SwiftSettings::default(),
}
}
}
@@ -1283,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,
@@ -1295,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 {
@@ -1373,6 +1802,8 @@ pub struct ExternalFormatterSettings {
/// Prefer this formatter even when a language server offers formatting.
pub prefer: bool,
pub run_on_save: bool,
/// Ruff only: apply safe lint fixes (`ruff check --fix-only`) on save, independently of formatting.
pub fix_on_save: bool,
}
impl Default for ExternalFormatterSettings {
@@ -1401,6 +1832,7 @@ impl Default for ExternalFormatterSettings {
.collect(),
prefer: false,
run_on_save: false,
fix_on_save: false,
}
}
}
@@ -1429,6 +1861,12 @@ pub struct PythonSettings {
/// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses
/// it, else unittest), `pytest` or `unittest`.
pub test_runner: String,
/// What Profile runs Python under (Settings › Python › Profiler): `auto` (py-spy where it
/// is installed and samples without root, else cProfile), `cprofile` or `py-spy`.
pub profiler: String,
/// Show matplotlib figures of Python runs in the Plots tool window (the IDE sets `MPLBACKEND`
/// unless the run sets it); off: matplotlib's own window.
pub show_plots_in_tool_window: bool,
}
impl Default for PythonSettings {
@@ -1442,6 +1880,8 @@ impl Default for PythonSettings {
show_interpreter_paths: true,
interpreter_paths: BTreeMap::new(),
test_runner: "auto".into(),
profiler: "auto".into(),
show_plots_in_tool_window: true,
}
}
}
@@ -1534,6 +1974,26 @@ pub struct ZigSettings {
pub zig: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct SwiftSettings {
/// The Xcode (`Xcode.app` or its `Contents/Developer`) whose tools the project's sourcekit-lsp,
/// `xcodebuild`, `xcrun` and terminals use, as `DEVELOPER_DIR`. Empty = the `xcode-select` one.
pub xcode: String,
}
impl SwiftSettings {
/// [`Self::xcode`] as a `DEVELOPER_DIR` value (`Xcode.app` gets `/Contents/Developer`); `None` when unset.
pub fn developer_dir(&self) -> Option<std::path::PathBuf> {
let xcode = self.xcode.trim();
if xcode.is_empty() {
return None;
}
let path = std::path::Path::new(xcode);
Some(if path.extension().is_some_and(|e| e == "app") { path.join("Contents/Developer") } else { path.into() })
}
}
/// The Flutter plugin's "Flutter SDK path".
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -1740,6 +2200,10 @@ pub struct TypeScriptSettings {
/// plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the
/// vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
pub tsserver_max_memory: u32,
/// tsserver's log (`typescript.tsserver.log`). TypeScript: Open TS Server Log opens it.
#[serde(deserialize_with = "or_default")]
#[specta(type = TsServerLog)]
pub tsserver_log: TsServerLog,
/// Problems › TypeScript project errors: the project's own `tsc --watch` per root
/// `tsconfig.json` reports the errors of files that are not open.
pub watch_problems: bool,
@@ -1747,10 +2211,27 @@ pub struct TypeScriptSettings {
impl Default for TypeScriptSettings {
fn default() -> Self {
Self { version: "bundled".into(), tsserver_max_memory: 0, watch_problems: false }
Self {
version: "bundled".into(),
tsserver_max_memory: 0,
tsserver_log: TsServerLog::Off,
watch_problems: false,
}
}
}
/// tsserver's log verbosity, as vtsls' `typescript.tsserver.log` spells it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum TsServerLog {
#[default]
Off,
Terse,
Normal,
RequestTime,
Verbose,
}
/// Dependency scope for a module dependency or project library (IDEA's Modules › Dependencies).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -1776,6 +2257,37 @@ pub struct ProjectLibrary {
pub scope: DependencyScope,
}
/// A library class entry written as a jar glob: `dir/*.jar` → `(dir, false)`, `dir/**/*.jar` → `(dir, true)`.
pub fn split_jar_glob(entry: &str) -> Option<(&str, bool)> {
let entry = entry.trim();
if let Some(base) = entry.strip_suffix("/**/*.jar").or_else(|| entry.strip_suffix(r"\**\*.jar")) {
return Some((base, true));
}
entry.strip_suffix("/*.jar").or_else(|| entry.strip_suffix(r"\*.jar")).map(|base| (base, false))
}
/// The `.jar` files in `dir` (and its subfolders when `recursive`), sorted by name per folder.
pub fn jar_files(dir: &std::path::Path, recursive: bool) -> Vec<std::path::PathBuf> {
fn walk(dir: &std::path::Path, recursive: bool, out: &mut Vec<std::path::PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
let mut entries: Vec<_> = entries.flatten().collect();
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let path = entry.path();
match entry.file_type() {
Ok(t) if t.is_dir() && recursive => walk(&path, true, out),
Ok(t) if t.is_file() && path.extension().is_some_and(|x| x.eq_ignore_ascii_case("jar")) => {
out.push(path)
}
_ => {}
}
}
}
let mut out = Vec::new();
walk(dir, recursive, &mut out);
out
}
/// Dependency entry of a module (Project Structure › Modules › Dependencies).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -1923,6 +2435,44 @@ impl Settings {
mod tests {
use super::*;
#[test]
fn the_xcode_setting_becomes_a_developer_dir() {
let dir = |xcode: &str| SwiftSettings { xcode: xcode.into() }.developer_dir();
assert_eq!(dir(""), None);
assert_eq!(dir(" "), None);
assert_eq!(dir("/Applications/Xcode-beta.app"), Some("/Applications/Xcode-beta.app/Contents/Developer".into()));
assert_eq!(
dir("/Applications/Xcode.app/Contents/Developer"),
Some("/Applications/Xcode.app/Contents/Developer".into())
);
let s: Settings = serde_json::from_str(r#"{"languages":{"swift":{"xcode":"/X.app"}}}"#).unwrap();
assert_eq!(s.languages.swift.xcode, "/X.app");
}
#[test]
fn ruff_safe_fixes_on_save_default_off_and_round_trip() {
let old: Settings = serde_json::from_str(r#"{"languages":{"ruff":{"runOnSave":true}}}"#).unwrap();
assert!(old.languages.ruff.run_on_save);
assert!(!old.languages.ruff.fix_on_save);
let on: Settings = serde_json::from_str(r#"{"languages":{"ruff":{"fixOnSave":true}}}"#).unwrap();
assert!(on.languages.ruff.fix_on_save);
assert_eq!(serde_json::to_value(&on).unwrap()["languages"]["ruff"]["fixOnSave"], true);
}
#[test]
fn tsserver_log_reads_known_levels_and_drops_anything_else() {
let log = |v: &str| {
let s: Settings =
serde_json::from_str(&format!(r#"{{"languages":{{"typescript":{{"tsserverLog":{v}}}}}}}"#)).unwrap();
s.languages.typescript.tsserver_log
};
assert_eq!(log(r#""requestTime""#), TsServerLog::RequestTime);
assert_eq!(log(r#""verbose""#), TsServerLog::Verbose);
assert_eq!(log(r#""--trace""#), TsServerLog::Off);
assert_eq!(log("3"), TsServerLog::Off);
assert_eq!(serde_json::to_value(TsServerLog::RequestTime).unwrap(), "requestTime");
}
#[test]
fn python_interpreter_may_name_a_run_target() {
let python = |interpreter: &str| PythonSettings { interpreter: interpreter.into(), ..Default::default() };
@@ -1956,6 +2506,19 @@ mod tests {
assert_eq!(json["appearance"]["smoothScrolling"], false);
}
#[test]
fn database_output_destination_defaults_and_round_trips() {
let old: Settings = serde_json::from_str(r#"{"database":{"inEditorResults":true}}"#).unwrap();
assert_eq!(old.database.output_destination, DatabaseOutputDestination::DatabaseOutput);
assert!(old.database.in_editor_results);
let services: Settings = serde_json::from_str(r#"{"database":{"outputDestination":"services"}}"#).unwrap();
assert_eq!(services.database.output_destination, DatabaseOutputDestination::Services);
let saved = serde_json::to_value(&services).unwrap();
assert_eq!(saved["database"]["outputDestination"], "services");
assert_eq!(serde_json::from_value::<Settings>(saved).unwrap().database, services.database);
}
#[test]
fn window_close_settings_default_off_and_round_trip() {
for old in [r#"{}"#, r#"{"general":{"confirmExit":false}}"#] {
@@ -2117,6 +2680,21 @@ mod tests {
}
}
#[test]
fn toggle_tool_windows_on_shortcut_defaults_off_and_round_trips() {
let old: Settings = serde_json::from_str(r#"{"appearance":{"showToolWindowNames":true}}"#).unwrap();
assert!(!old.appearance.toggle_tool_windows_on_shortcut);
assert!(!Settings::default().appearance.toggle_tool_windows_on_shortcut);
for enabled in [true, false] {
let mut settings = Settings::default();
settings.appearance.toggle_tool_windows_on_shortcut = enabled;
let json = serde_json::to_value(&settings).unwrap();
assert_eq!(json["appearance"]["toggleToolWindowsOnShortcut"], enabled);
let restored: Settings = serde_json::from_value(json).unwrap();
assert_eq!(restored.appearance.toggle_tool_windows_on_shortcut, enabled);
}
}
#[test]
fn double_click_opens_diff_is_unset_by_default_and_round_trips() {
let old: Settings = serde_json::from_str(r#"{"vcs":{"commit":{"nonModal":true}}}"#).unwrap();
+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.
+103 -2
Переглянути файл
@@ -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(),
}
}
}
@@ -143,6 +173,9 @@ impl Default for GitAnnotateSettings {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GitSettings {
/// Git integration on: off, the IDE finds no repositories and runs no git at all
/// (no status, log, blame, fetch, clone or agent worktrees), and hides its Git UI.
pub enabled: bool,
pub annotate: GitAnnotateSettings,
/// Show blame after the current editor line.
pub inline_blame: bool,
@@ -201,6 +234,7 @@ pub struct GitSettings {
impl Default for GitSettings {
fn default() -> Self {
Self {
enabled: true,
annotate: GitAnnotateSettings::default(),
inline_blame: false,
inline_blame_clickable: true,
@@ -250,6 +284,8 @@ pub struct CommitSettings {
pub reformat: bool,
pub optimize_imports: bool,
pub cleanup: bool,
/// Apply Ruff's safe lint fixes before composing the commit, independently of formatting.
pub fix_on_commit: bool,
pub blank_line_after_subject: bool,
pub limit_subject: bool,
pub subject_limit: u32,
@@ -291,6 +327,7 @@ impl Default for CommitSettings {
reformat: false,
optimize_imports: false,
cleanup: false,
fix_on_commit: false,
blank_line_after_subject: true,
limit_subject: true,
subject_limit: 72,
@@ -402,13 +439,24 @@ impl Default for LogLevelColors {
#[serde(default, rename_all = "camelCase")]
pub struct DatabaseSettings {
/// A console's result sets show under the statements that produced them, in the editor,
/// instead of in the Services view's result tabs.
/// instead of in the output window's result tabs.
pub in_editor_results: bool,
/// The tool window that receives SQL query output and plans.
pub output_destination: DatabaseOutputDestination,
/// Languages & Frameworks › SQL Resolution Scopes: the data source SQL in a file or folder
/// resolves against (completion, inspections, navigation), most specific path first.
pub resolution_scopes: Vec<SqlResolutionScope>,
}
/// Database › Query Output: where SQL results open.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum DatabaseOutputDestination {
#[default]
DatabaseOutput,
Services,
}
/// One row of SQL Resolution Scopes.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -429,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 }
}
}
@@ -512,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 {
@@ -534,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(),
}
}
}
@@ -552,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")]
@@ -598,11 +659,17 @@ 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,
pub override_ide_shortcuts: bool,
pub shell_integration: bool,
pub highlight_hyperlinks: bool,
pub highlight_selection: bool,
/// Highlights typed commands the IDE recognises; Run Highlighted Command runs them with it.
pub run_commands_using_ide: bool,
pub option_as_meta: bool,
/// Escape moves focus to the editor instead of reaching the shell.
pub escape_to_editor: bool,
@@ -634,11 +701,14 @@ 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,
shell_integration: true,
highlight_hyperlinks: true,
highlight_selection: true,
run_commands_using_ide: true,
option_as_meta: false,
escape_to_editor: false,
cursor_shape: "block".into(),
@@ -728,6 +798,24 @@ impl Default for AgentSecuritySettings {
mod tests {
use super::*;
#[test]
fn ruff_safe_fixes_on_commit_default_off_and_round_trip() {
let old: CommitSettings = serde_json::from_str(r#"{"reformat":true}"#).unwrap();
assert!(old.reformat);
assert!(!old.fix_on_commit);
let on: CommitSettings = serde_json::from_str(r#"{"fixOnCommit":true}"#).unwrap();
assert!(on.fix_on_commit);
assert_eq!(serde_json::to_value(&on).unwrap()["fixOnCommit"], true);
}
#[test]
fn git_defaults_enabled_and_can_be_disabled() {
let missing: GitSettings = serde_json::from_str("{}").unwrap();
let off: GitSettings = serde_json::from_str(r#"{"enabled":false}"#).unwrap();
assert!(missing.enabled);
assert!(!off.enabled);
}
#[test]
fn clone_submodules_defaults_on_and_can_be_disabled() {
let missing: GitSettings = serde_json::from_str("{}").unwrap();
@@ -758,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);
}
}
+92
Переглянути файл
@@ -35,6 +35,24 @@ pub fn parse(path: &Path) -> Option<WslPath> {
Some(WslPath { distro: distro.to_owned(), path: format!("/{}", tail.trim_end_matches('/')) })
}
/// The Linux path of a Windows path seen from `distro`: `C:\a` → `/mnt/c/a` (WSL's default
/// automount root), `\\wsl.localhost\<distro>\a` → `/a`. `None` for another distro's share,
/// other network shares and relative paths.
pub fn linux_path(path: &Path, distro: &str) -> Option<String> {
if let Some(w) = parse(path) {
return w.distro.eq_ignore_ascii_case(distro).then_some(w.path);
}
let s = path.to_string_lossy().replace('\\', "/");
let s = s.strip_prefix("//?/").unwrap_or(&s);
let mut chars = s.chars();
let drive = chars.next().filter(char::is_ascii_alphabetic)?;
let rest = chars.as_str().strip_prefix(':')?;
if !(rest.is_empty() || rest.starts_with('/')) {
return None;
}
Some(format!("/mnt/{}{}", drive.to_ascii_lowercase(), rest.trim_end_matches('/')))
}
/// A distro name `wsl.exe -d` can be given safely: Windows creates them from letters, digits,
/// `.`, `_` and `-`. A leading `-` would be read as an option, so it is refused too.
pub fn is_valid_distro(name: &str) -> bool {
@@ -86,6 +104,57 @@ pub fn list_distros() -> Vec<String> {
Vec::new()
}
/// Where this machine reads `distro`'s file system.
pub fn share_root(distro: &str) -> std::path::PathBuf {
format!(r"\\wsl.localhost\{distro}").into()
}
/// The names of a Linux path, `.` dropped and `..` taking the name before it.
pub fn path_parts(linux: &str) -> Vec<&str> {
let mut parts: Vec<&str> = Vec::new();
for c in linux.split('/').filter(|c| !c.is_empty() && *c != ".") {
if c == ".." {
parts.pop();
} else {
parts.push(c);
}
}
parts
}
/// Where this machine reads the absolute path `linux` of `distro`: a drive mounted at
/// `/mnt/<drive>` is read directly, anything else through [`share_root`]. `..` goes up
/// within `linux`, never above the drive or the share.
pub fn windows_path(linux: &str, distro: &str) -> std::path::PathBuf {
let parts = path_parts(linux);
let base = match parts.as_slice() {
["mnt", drive, ..] if drive.len() == 1 && drive.chars().all(|c| c.is_ascii_alphabetic()) => {
let base = std::path::PathBuf::from(format!("{}:\\", drive.to_ascii_uppercase()));
return parts[2..].iter().fold(base, |p, c| p.join(c));
}
_ => share_root(distro),
};
parts.iter().fold(base, |p, c| p.join(c))
}
/// Runs `args` in `distro` without its shell and returns the standard output; a failed
/// run is an error with its output. `wsl.exe`'s own messages are UTF-16: their NULs go.
pub fn exec(distro: &str, args: &[&str], timeout: std::time::Duration) -> crate::IdeResult<String> {
use crate::cli_process::{CliTool, Decoding};
if !is_valid_distro(distro) {
return Err(crate::IdeError::invalid(format!("'{distro}' is not a WSL distribution name")));
}
let mut cmd = std::process::Command::new(EXE);
cmd.args(["-d", distro, "--exec"]).args(args);
let out = CliTool::new(EXE, Decoding::Utf8Lossy).run(cmd, timeout, None)?;
let (stdout, stderr) = (out.stdout.replace('\0', ""), out.stderr.replace('\0', ""));
if out.success {
return Ok(stdout);
}
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
Err(crate::IdeError::internal(format!("{EXE} -d {distro} --exec {}: {detail}", args.first().unwrap_or(&""))))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -103,6 +172,21 @@ mod tests {
assert_eq!(p(r"\\?\UNC\WSL.LOCALHOST\Ubuntu-24.04\home\me\app"), want);
}
#[test]
fn windows_paths_map_onto_the_distro() {
let l = |s: &str| linux_path(Path::new(s), "Ubuntu");
assert_eq!(l(r"C:\Users\me\app"), Some("/mnt/c/Users/me/app".into()));
assert_eq!(l(r"D:\"), Some("/mnt/d".into()));
assert_eq!(l("e:/work/x/"), Some("/mnt/e/work/x".into()));
assert_eq!(l(r"\\?\C:\proj"), Some("/mnt/c/proj".into()));
assert_eq!(l(r"\\wsl.localhost\ubuntu\home\me"), Some("/home/me".into()));
assert_eq!(l(r"\\wsl$\Debian\home\me"), None);
assert_eq!(l(r"\\server\share\a"), None);
assert_eq!(l(r"C:relative"), None);
assert_eq!(l("app"), None);
assert_eq!(l("/home/me"), None);
}
#[test]
fn distro_root_and_foreign_paths() {
assert_eq!(p(r"\\wsl.localhost\Debian"), Some(("Debian".to_owned(), "/".to_owned())));
@@ -127,6 +211,14 @@ mod tests {
assert!(parse_distro_list(b"").is_empty());
}
#[test]
fn linux_paths_are_read_on_their_drive_or_through_the_share() {
use std::path::PathBuf;
assert_eq!(windows_path("/mnt/d/lib/../x.py", "U"), PathBuf::from("D:\\").join("x.py"));
assert_eq!(windows_path("/usr/lib/a.py", "U"), share_root("U").join("usr").join("lib").join("a.py"));
assert_eq!(windows_path("/mnt/wsl/x", "U"), share_root("U").join("mnt").join("wsl").join("x"));
}
#[test]
fn distro_names_cannot_smuggle_options_or_paths() {
for bad in ["", "-d", "--exec", "a b", "a/b", r"a\b", "a;b", "a$(x)", "a\"b"] {
Loaded 100 of 2461 files, more files were not shown because too many files have changed in this diff. Show more