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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 678b2555b8 fix(vcs): open the GitHub sign-in terminal from the Get from Version Control window
The window never provided the embedded terminal, so Add account… failed with
"The terminal is not available in this window." It now loads the terminal on
first use, as the Settings window does.
2026-12-04 15:08:34 +08:00
l0ng-ai b16d485f35 feat(vcs): get files from the branch comparison window (#7953)
The Compare with Branch window gets a Get action (toolbar and dialog button) that replaces the selected local files with their content in the compared revision: missing files are created, files the revision lacks are deleted, and a renamed file is restored under its old path. The window can be maximized where the app draws its own title bar.

A file of the revision that is back in the working tree as an untracked file is now one change (modified, or omitted when identical) instead of a deletion plus an untracked file.

Closes #7917
2026-12-04 14:19:28 +08:00
l0ng-ai 34739e181d feat(plugins): download several marketplace plugins at once (#7950)
Installing a marketplace plugin disabled every other Install and Update button until it finished. Each marketplace plugin now tracks its own download: others can be installed meanwhile, and the install pages of finished downloads follow one another. A second click on a plugin already on its way does nothing.

Refs #7911
2026-12-04 14:03:58 +08:00
l0ng-ai 2cf5f5369f fix(run): put a Tomcat run tab's toolbar in its tab row (#7949)
The Tomcat run tab showed its Rerun / Stop / Debug / Update / Open in Browser toolbar on a row of its own above the Server, Deployment and log tabs. The toolbar now follows those tabs in their row, with Edit Configurations at the end, so the output gets that row back.

Closes #7912
2026-12-04 13:59:34 +08:00
l0ng-ai b27ef431a6 feat(vcs): show a changed file's whole path when the panel cuts its row off (#7947)
Hovering any part of a Commit window file row that the panel cuts off shows the file's path relative to its root; a row that fits keeps its parts' own tooltips. The tooltip host takes this as data-tooltip-clipped, shown while the element's content runs past a clipping ancestor or is ellipsised.

Closes #7926
2026-12-04 13:47:12 +08:00
l0ng-ai 166ef2dffa test(e2e): fix the main branch's failing layout and caret key specs (#7945)
caretKeysEverywhere bound "Control+H", which is not a key stroke, so Move Caret Left was never bound; it passed on macOS only because Ctrl+H deletes backward there. compactMode expects the 30px status bar, toolbarCustomization measures the first visible item after the Center group, the commit check spec accepts a sub-pixel clip, and codeLensLayout waits for the editor to measure.
2026-12-04 13:40:15 +08:00
l0ng-ai ed57059cad fix(editor): parameter info for a nested call whose arguments start on the next line (#7943)
Right after the `(` of a call followed by blanks or a line break, jdtls answers signature help for the enclosing call, so `outer(inner(⏎ args))` showed outer's signatures. The request now asks past those blanks.

Parameter info rows show the parameter list alone, without the method name and return type, and `<no parameters>` for an overload without any.

Fixes #7927
2026-12-04 13:24:33 +08:00
l0ng-ai 31e7b420ae feat(vcs): close a committed file's local changes diff after the commit (#7942)
When a commit leaves a file with no local changes, its HEAD/index vs working copy diff tab closes. Pinned tabs, files with changes left after a partial commit, and other diffs (Log, Compare with Branch) stay open.

Closes #7914
2026-12-04 13:04:44 +08:00
l0ng-ai 70a7932939 fix(run): keep Rerun and Stop readable on the running Run widget under icon themes (#7940)
An icon theme that replaces rerun-filled / stop-filled with coloured icons (Atom Material Icons) left a green icon on the green Rerun button and a red one on the red Stop button. A theme's icon for these on-fill names now keeps its shape but takes the button's foreground, and the filled buttons give monochrome icons that foreground.

Fixes #7923
2026-12-04 12:52:15 +08:00
l0ng-ai 8b1ca86526 fix(search): show a library class's archive instead of its document URI (#7938)
Search Everywhere listed classes from dependency jars and the JDK with the language server's raw jdt:// URI as their location. Library rows now show the archive or JDK module, and the status line the archive and package.

Refs #7919
2026-12-04 12:37:54 +08:00
l0ng-ai 16e160f5b9 feat(themes): let themes set the Git log's current-branch background (#7936)
The Git log tints commits on the current branch (View Options > Highlight > Current Branch) with --bg-log-current-branch, an accent mix themes could not override. It is now a themeable token in the vcs group (Harbor Night template and theme docs updated; palette themes keep their base's mix), and IntelliJ theme import reads it from VersionControl.Log.Commit.currentBranchBackground.

Refs #7918
2026-12-04 12:23:20 +08:00
l0ng-ai 0d3e9a27cc fix(titlebar): release the toolbar spacer when the Center group goes (#7935)
The main toolbar centres its Center group by giving the spacer before it a fixed width. The cleanup looked that spacer up by its marker attribute, which React had already removed, so the width stayed after the Center group went away (emptied, Restore Default Toolbar, or the main menu expanded) and the right group sat away from the right edge. The hook now keeps the spacer it sized and releases it.

Fixes #7915
2026-12-04 12:09:55 +08:00
l0ng-ai 3a31ec25aa feat(editor): rearrange code from Reformat File and on save (#7934)
Reformat File gains a Rearrange entries option (Python, TypeScript, JavaScript; whole-file scope only, remembered with the other options), and Tools > Actions on Save gains Rearrange code (actionsOnSave.rearrange, off by default), run after Optimize imports and before cleanup and reformatting. Rearranging from either place is quiet when nothing moves.

Refs #7783
2026-12-04 12:05:17 +08:00
audichuang 693b24bf65 fix(editor): keep the class brace in place when Rearrange Code moves the last method (#7921)
Rearrange Code moves TypeScript and JavaScript methods as whole lines. When a class's closing brace, or a block comment running on below, shared a line with the last method and that method moved up, the brace moved with it and the methods after it ended up outside the class. Such a class is now left alone; when the last method stays last, the class is rearranged as before.

Co-authored-by: audichuang <[email protected]>
2026-12-04 12:04:04 +08:00
@鹿 6304811ac9 fix(java): run a single Java file on the project JDK, including JDK 6 (#7925)
A single Java file ran on the java found on PATH, so a JDK 6/8 project could not start it: those launchers have no source mode. The file now runs on the project or module JDK; when that JDK has no source launcher, or the file belongs to an Eclipse module, it is compiled with the JDK's javac (source folders, jars, encoding and referenced workspace projects from .classpath) and started with java -cp. JDK 6 is detected from rt.jar's manifest. The class name comes from the package declaration, and the source path from where the package path starts, so Maven-style layouts resolve correctly. JDWP and VM options stay before -cp, program arguments after the class.

Co-authored-by: T-fenlin <[email protected]>
2026-12-04 11:24:42 +08:00
l0ng-ai d55f116add feat(editor): style Java static, constant and final fields separately (#7930)
Java fields get their own colour scheme attributes under Java > Class Fields: instance field, instance final field, static field and constant (static final field), each falling back through the field kind it refines to Language Defaults > Identifiers > Static field / Instance field. Interface fields count as constants. The resolver and settings preview follow the whole inherit chain; .icls import maps the matching attributes.

Fixes #7643
2026-12-04 11:17:26 +08:00
l0ng-ai d62c978032 fix(agents): place New Agent Task before Search and shorten its label
A saved main toolbar layout now puts widgets registered since next to their
default neighbours instead of at the end of the side, so New Agent Task lands
between the Run widget and Search Everywhere rather than after Search. The
toolbar button reads "New Task"; its tooltip still names the agent.

Refs #4000
2026-12-04 10:49:43 +08:00
l0ng-ai 5f452a8e36 Revert "fix(agents): keep following the chat end when a row grows after its render (#7811)"
This reverts commit 437008c517.
2026-12-04 10:49:02 +08:00
sonnartliao 7992063ef2 feat(editor): make inactive preprocessor dimming optional (#7913)
clangd reports inactive #if/#ifdef branches as comment semantic tokens, which the editor greys out. Projects without a compilation database (such as U-Boot without a board .config) end up with most of a file grey. A new editor.dimInactiveCode setting (default on, so existing settings keep the grey) adds a Dim inactive preprocessor code checkbox under Settings > Editor > Color Scheme > Language Defaults; turning it off keeps the syntax colours of inactive regions and re-decorates open editors immediately.

Co-authored-by: sonnartliao <[email protected]>
2026-12-04 10:47:35 +08:00
l0ng-ai 34cb6a45cd fix(workbench): restore the 30px status bar height
The status bar is a widget's label height plus StatusBar.Widget.widgetInsets 6,8 (30px at the
default font), not 34px; the breadcrumbs sit 1px above the middle per
StatusBar.Breadcrumbs.navBarInsets 3,0,4,4. Compact mode is unchanged.
2026-12-04 10:39:34 +08:00
LU XIANGRUIтаwildcatDownstairs e670463b8e feat(markdown): add configurable soft line breaks for preview (#7907)
Settings > Languages & Frameworks > Markdown > Preview gains a Soft line breaks option: Standard Markdown (default, a single newline collapses into a space) or Break on single newline (rendered as <br>). Stored as languages.markdown.softLineBreaks, defaulting to standard for existing settings files. Open previews re-render immediately; cached and parked preview markup is kept per mode, and the preview worker restarts with the new mode.

Closes #7844

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-04 10:38:45 +08:00
l0ng-ai 2b0cc6b733 fix(dotnet): build, clean and restore .NET projects in the Build window (#7922)
Build, Restore and Clean .NET Project ran dotnet as a background task of the .NET tool window, with no Build window output, no status bar progress and no notification; the output appeared only in the NuGet Packages window afterwards. They now run through a new build_dotnet_command host command on the shared .NET build runner, so output and errors stream into the Build window, Stop Build cancels, Rerun repeats, and a notification reports the result. The selected project is re-evaluated (and audited after a restore) only when the command succeeds.

Fixes #7853
2026-12-04 10:38:02 +08:00
Yohann CATHERINEтаyohannlog 152f7123a0 fix(terminal): Git Bash tabs no longer always count as running a command (#7839)
On Windows, a Git Bash tab's shell runs under a bash.exe launcher process, so the running-command check always found a child process and closing the tab or quitting always asked for confirmation. The check now looks past the shell's own launcher before deciding a command is running.

Co-authored-by: yohannlog <[email protected]>
2026-12-04 10:20:37 +08:00
LU XIANGRUIтаwildcatDownstairs a223f3e6b2 feat(dotnet): run with dotnet watch and publish projects from the IDE (#7910)
A .NET Project run configuration gains a Run with dotnet watch option: dotnet watch --non-interactive in the same Run tab, with launch profiles still applied and the terminal emulated so Stop ends the watcher; Debug and tests run without it.

C#, F# and Visual Basic projects gain Publish .NET Project...: choose a folder publish profile (server and container profiles are not listed), or set configuration, framework, runtime, self-contained and output folder. dotnet publish streams into the Build tool window, can be cancelled and rerun, through a new build_dotnet_publish command sharing the dotnet format runner.

Closes #7900

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-04 10:20:08 +08:00
LU XIANGRUIтаLU XIANGRUI 9c73f7d784 feat(updates): choose the update channel (Stable / Nightly) (#7684)
* feat(updates): choose the update channel (Stable / Nightly)

- Settings › System Settings › Updates gets an Update channel select next to Update source
- Its default follows the running build; nightly is on GitHub only, stable keeps the CNB mirror
- OPENIDEA_UPDATE_ENDPOINT still overrides both channels

* fix(updates): shorten the update channel hint so Check Now stays in view

- At 520px wide and 680px high the long hint pushed Check Now out of the Settings dialog
- The Updates e2e also checks that Update channel sits between the automatic check and Update source

---------

Co-authored-by: LU XIANGRUI <[email protected]>
2026-12-04 10:52:08 +09:00
Deng Liuтаdengliu 9ad7f91c04 fix(automations): allow scrolling overflowing schedule and run lists (#7901)
The list frame's overflow: hidden let it shrink to the editor height, so rows past the fold were clipped instead of scrolled. The header and tabs now stay pinned above a dedicated scroll body, the footer stays pinned below it, the scroll position resets on tab switch, and a deep-linked schedule row scrolls into view.

Co-authored-by: dengliu <[email protected]>
2026-12-04 09:46:43 +08:00
l0ng-ai 5ec05b3aca feat(keymap): rebound caret keys also move lists, popups and text fields (#7909)
Move Caret Up / Down / Left / Right / to Line Start / to Line End and their With Selection variants only acted in text editors. Where no text editor takes such a key, it now acts as the arrow / Home / End key on the focused list, tree, popup or text field, ahead of other actions on the same key; with the completion popup open, Move Caret Up / Down move its selection. Presets are unchanged.

Closes #7714
2026-12-04 09:42:18 +08:00
l0ng-ai 26688a79f7 feat(php): colour variables by name without server semantic tokens (#7905)
Semantic highlighting coloured locals only from server tokens, and Intelephense sends none, so PHP variables kept one colour with the option on. PHP now colours variables and parameters from the parse tree with the same name-to-colour rule; property declarations, static property access, $this and the superglobals are left out, and server tokens still win where they arrive.

Closes #7884
2026-12-04 09:27:27 +08:00
l0ng-ai c6428a8e4c fix(terminal): give the Windows environment tests a module of their own (#7886)
#7837 and #7838 were merged side by side and each added a Windows-only test module named windows_sessions to ide-terminal, so the Windows build failed with E0428. The registry environment test's module is renamed to windows_environment.
2026-12-04 09:23:15 +08:00
l0ng-ai 9e3077753d feat(window): Select Next / Previous Tab cycle a focused tool window's tabs (#7904)
In a focused tool window, Select Next Tab and Select Previous Tab select its next or previous content tab (terminal sessions, Run and Find tabs), wrapping around; with fewer than two tabs the key is left to the component. The terminal lets these actions through except on Alt+Left / Alt+Right, which a shell uses to move by a word.

Closes #7890
2026-12-04 09:22:46 +08:00
l0ng-ai 7d33b470f2 fix(keymap): let the terminal hand a shared key only to its allowed action (#7903)
#7892 ranked a preset binding whose keyWhen needs focus ahead of a context-free user binding everywhere, so in the editor a user's Ctrl+K for Move Caret Up lost to the preset's Cut to Line End and caretMovementActions.test.ts failed on main. The case it fixed belongs to the terminal: a key it passes to the IDE for an allowed action (New Tab's Ctrl+Shift+T) reached a user binding of Reopen Closed Tab instead. The terminal now limits such a keystroke to its allowed actions (limitKeyActions), and the dispatcher order is back to user bindings first.
2026-12-04 09:17:01 +08:00
Bruno Valladares 5bfdaf679d feat(plugins): reload linked plugins when their files change (#7888)
Plugins linked with openidea-plugin link are read in place, but edits showed only after Reload. Each linked folder is now watched (.git, target, node_modules and editor temp files ignored); a change wakes the plugin event pump, which reloads the plugin under the lifecycle lock. Installed and project plugins are not watched. A reloaded plugin that provides the selected theme restyles in place: the theme setting is reconciled after the contribution swap instead of in between, so the IDE no longer drops to the built-in theme.

Co-authored-by: Bruno0416 <[email protected]>
2026-12-04 09:10:21 +08:00
faysouтаfaysou ab08c3d245 fix(project-view): show a folder's loading row only when its read is slow (#7898)
Expanding an uncached folder put a Loading… row under it at once, so a folder read in a few milliseconds flashed the loader. The read still starts on expand, but the row appears only if the listing is pending after 250 ms and goes as soon as it finishes.

Co-authored-by: faysou <[email protected]>
2026-12-04 08:57:54 +08:00
koeriaтаkoeria 1ee5f0d71d fix(keymap): keep a focused component's preset shortcut ahead of a context-free user binding (#7892)
A user shortcut without a context was tried before every preset binding, so giving Reopen Closed Tab the terminal's Ctrl+Shift+T reopened an editor tab while the terminal had focus. A preset binding whose keyWhen needs some focus to hold (terminalFocus, projectViewFocus, …) now runs before a context-free user binding inside that context; broad guards such as !popupOpen still rank below the user's binding, so a user shortcut sharing a key with Jump to Navigation Bar keeps working.

Closes #7889

Co-authored-by: koeria <[email protected]>
2026-12-04 08:55:28 +08:00
faysouтаfaysou d2686f922d test(database): stub table editor request cancellation (#7893)
The table editor tests stubbed the page request but left cancelRequest wired to the Tauri IPC, so a page unmounting mid-request left unhandled rejections in the run. Stub it with the other commands.

Co-authored-by: faysou <[email protected]>
2026-12-04 08:50:30 +08:00
l0ng-ai 35682aadc2 fix(vcs): open diffs in the diff window under the modal commit interface (#7899)
Under the modal commit interface, diffs opened as a dialog inside the IDE window and needed Show Diff in New Window for a separate one. They now open in the diff window directly, as with the non-modal interface when Open diff as editor tab is off; a combined diff, the browser shell or a window that fails to open fall back to the front diff dialog.

Fixes #7675
2026-12-04 08:46:17 +08:00
l0ng-ai 35529ddd64 test(project-view): use a project name that fits a narrow tree on Linux too (#7897)
On the Linux runner's font the old project name alone was wider than the narrow tree, so the spec failed on every main run; a shorter name still needs the path to give way and fits on both platforms.
2026-12-04 08:33:19 +08:00
l0ng-ai f5abe8b509 fix(web): style the open-file confirmation with declared tokens (#7896)
The /api/file confirmation read --bg-surface, which no theme declares (customProperties.test.ts failed on main), and used fixed sizes; it now uses --bg-input and the spacing, radius and font-size tokens.
2026-12-04 08:32:26 +08:00
l0ng-ai c1cde544fb refactor(dotnet): register the NuGet source actions once (#7887)
The .NET feature listed dotnet.sources and dotnet.sourceChange twice (added by #7424 and again by #7434); the identical second copy is removed. No behaviour change.
2026-12-04 04:57:48 +08:00
Vadim LazukтаInf1mum 40ea4267bd feat(dotnet): show a project's folders and files under its solution tree node (#7882)
A .NET project node in the Project view's solution tree was a leaf for its .csproj holding only Dependencies. It now lists the project's folder (bin and obj left out) below Dependencies, keeps the project's .NET context actions, and Select Opened File reveals files of a project in the solution tree. The project file opens from the node's Edit '<name>.csproj' menu item.

Closes #7859

Co-authored-by: Inf1mum <[email protected]>
2026-12-04 04:56:41 +08:00
l0ng-ai 377e900e84 fix(java): go to the methods of a call whose arguments fit none (#7885)
jdtls resolves nothing for a Java call whose arguments fit no method (an argument being typed, a stray comma), so Go to Declaration reported no declaration. An unqualified call now goes to the current file's method of that name, or offers its overloads; a qualified call still needs its receiver's type and is left alone. The Cmd-hover link probe follows the same rule.

Fixes #7803
2026-12-04 04:48:40 +08:00
l0ng-ai 74b2b5113b fix(search): show the directory of same-named files in Find in Files rows (#7880)
Rows of the Find in Files popup showed only the file name in a single-project window, so matches in several index.vue files could not be told apart. Files that share a name in the results now get the distinguishing parent directory after the name, with the same rule as editor tabs and the Usages popup.

Fixes #7860
2026-12-04 04:31:57 +08:00
arookieofcтаarookieofc 68a322edad feat(web): add built-in HTTP /api/file/<path>:<line> server (#7360)
The built-in server now listens on a configurable loopback port (Settings > Build, Execution, Deployment > Debugger > Built-in Server, default 63342, falling back to the next free ports) and opens /api/file/<path>[:line[:column]] in the project window that holds the file. Paths resolve root-relative, under common source roots, or through the project's file-name index with a suffix match, and never leave a project root.

Requests from a web page (Origin, Referer or Sec-Fetch-Site) ask for confirmation in the project window first; an allowed origin is remembered for the session. Requests with a non-loopback Host are refused.

Browser previews keep a random port per root, so a fixed port never hands one project's browser storage to another.

Co-authored-by: arookieofc <[email protected]>
2026-12-04 04:26:18 +08:00
Deng Liuтаdengliu ba04c34710 feat(automations): configure effort level and context window (#7868)
The Create/Edit Automation dialog shows the selected model's settings (effort level, context size, and parameters such as Fast mode) next to the model picker, as the task composer does. Changing them on an automation that reuses a rolling session applies the new model first, then its per-model choices, to the live session, and then re-checks the unattended approval ceiling.

Co-authored-by: dengliu <[email protected]>
2026-12-04 04:14:34 +08:00
Vadim LazukтаInf1mum cddf57d4c7 fix(deployment): offer the deployment actions in Customize Main Toolbar (#7878)
Customize Main Toolbar lists only actions with an icon, and seven visible deployment actions (Upload to…, Download from…, Download from Default Server, the two Compare with Deployed Version actions and the two Sync with Deployed actions) had none. They now use the existing export, download, diff and refresh icons, so they can be added to the toolbar.

Closes #7863

Co-authored-by: Inf1mum <[email protected]>
2026-12-04 04:06:32 +08:00
l0ng-ai 8c82d9924c fix(http-client): join pasted curl cookies with "; " (#7879)
Several -b cookies of a pasted curl command are joined into one Cookie header with "; ", the RFC 6265 separator. The curl comparison test now ignores the whitespace after ";" in Cookie headers, since curl releases differ there (macOS curl 8.7 sends "a=1;b=2", ubuntu-latest sends "a=1; b=2").
2026-12-04 04:04:35 +08:00
Deng Liuтаdengliu a050a8054f fix(macos): honor keepAliveInBackground without requiring autoStartService (#7872)
Closing the last window on macOS kept the app alive for local automations only when autoStartService was also on. That setting is off by default while keepAliveInBackground is on, so with default settings the app quit and scheduled automations stopped. The app now stays alive while keepAliveInBackground is on and there are enabled schedules or in-flight runs.

A project retained headlessly on window close now keeps its internal automation watchers subscribed and drops only the window's UI sinks, so runs still record completion after the window closes.

Co-authored-by: dengliu <[email protected]>
2026-12-04 04:02:34 +08:00
Vadim LazukтаInf1mum a12999c3d5 fix(vcs): flip already-open diffs when clicking Swap Sides in Compare (#7875)
Swap Sides in the Compare tool window only changed the orientation of diffs opened afterwards, so a diff already open from that comparison kept its sides and Show Diff opened a second, opposite tab. Swap Sides now reopens the comparison's open diff tabs (single and all-in-one) with the sides flipped and closes the old ones, keeping the active tab last.

Closes #7869

Co-authored-by: Inf1mum <[email protected]>
2026-12-04 03:54:43 +08:00
koeriaтаkoeria 309a805794 fix(vcs): open Show Diff on multi-file selections as one diff chain (#7870)
Show Diff on the Changes changelist node, or on several changed files, opened the Changes between HEAD and Local Working Tree comparison window, because only single-file selections reached the file diff. A selection made only of changed files now opens one diff tab whose files form the F7 chain, as the modal commit interface already did; directories and changed submodule entries keep the comparison window.

Closes #7865

Co-authored-by: koeria <[email protected]>
2026-12-04 03:52:28 +08:00
audichuang ac9198dd52 fix(plugins): translate the command title in a failed plugin command's notification (#7874)
A failed plugin command's notification used the command's declared English title even when the plugin ships a translation that the menus and command palette already show. commandTitle now passes the title through that plugin's catalog.

Co-authored-by: audichuang <[email protected]>
2026-12-04 03:48:37 +08:00
Yohann CATHERINEтаyohannlog 7eed207163 fix(terminal): pick up environment changes made after the IDE started on Windows (#7837)
Children of the IDE copied the IDE's own environment, frozen at launch, so a tool installed while the IDE was open (Node.js, a JDK…) was not found in a new terminal until a restart. New terminals, runs and tools now read the user and machine environment from the registry again, so they see variables changed since the IDE started.

Closes #7762

Co-authored-by: yohannlog <[email protected]>
2026-12-04 03:46:47 +08:00
Yohann CATHERINEтаyohannlog 952c67f752 perf(terminal): show the PowerShell prompt sooner (#7838)
The PowerShell shell integration read Clear-Host with Get-Command and wrapped it in a closure before the first prompt, which cost about 90 ms. It now reads the function drive and defines a plain function.

Co-authored-by: yohannlog <[email protected]>
2026-12-04 03:46:23 +08:00
Yohann CATHERINEтаyohannlog e4d0a36b5a fix(terminal): recognise Windows shells whatever the case of their file name (#7841)
Windows file names ignore case, so shell detection now compares the shell's file name case-insensitively: a shell set as Bash.exe or BASH.EXE starts as bash with -l, MSYSTEM and CHERE_INVOKING, like bash.exe.

Co-authored-by: yohannlog <[email protected]>
2026-12-04 03:46:09 +08:00
l0ng-ai d1f311d2a3 fix(svn): line up the Merge dialog's fields (#7877)
Source branch/Source URL and Whitespace handling/Depth each share one grid, so their fields start at the same x.
2026-12-04 03:45:13 +08:00
RuyimgByCN 52e81f8158 feat(svn): add Incoming and Working Copies tabs, Configure Branches and Compare with Branch (#7355)
Adds an Incoming tab listing the changes an update would bring (with local edits and locks), a Working Copies Information panel that also lists switched descendants and offers Show Log, Update Project, Cleanup, Relocate, Switch to URL, Compare with Branch and Configure Branches for each working copy, per-root branch layouts shared by browsing, switching and merging, Switch to URL with revision, depth and ignore-ancestry options, and Compare with Branch for the selected working item against its counterpart on another branch.

The Working Copies panel replaces the earlier read-only view of the same tab. URL and revision validation is shared with the repository browser.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-04 03:42:45 +08:00
RuyimgByCN 7cca129a8e feat(svn): add a repository browser, Export dialog and checkout depth/revision options (#7353)
Adds a Subversion repository browser (list, history, preview, checkout, export, and remote copy/mkdir/delete) that keeps the selected revision through every view and disables remote changes in historical ones, an Export dialog with depth, externals and an explicit overwrite choice, and revision/depth/externals options for Subversion checkout.

Child URLs are built from encoded path segments, listings are keyed by URL and revision so a stale response cannot replace a newer one, historical paths are pegged at their revision, and a file preview checks its size before downloading. The Export dialog's fields share one grid so they line up.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-04 03:20:21 +08:00
RuyimgByCN 006ab617e8 feat(svn): add svn:ignore UI, properties diff and presets, cleanup/unlock/update options and Copy URL (#7347)
Adds Subversion working-copy operations: an svn:ignore dialog that adds names or patterns to the parent directory's property (escaping literal names, grouped by parent), a properties view with diffs and common presets, Cleanup with scoped options that skip nested VCS directories, Unlock, Update with revision/depth/externals options, and Copy URL.

Backed by new ide-svn operations and ide-host commands with tests; the Update dialog's revision and depth fields share one grid so they line up.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-04 03:02:06 +08:00
l0ng-ai fbc4c51c8f test: list maven_local_repository in the command snapshot (#7871)
#7719 added the command without updating src-tauri/tests/commands.snap.
2026-12-04 02:57:34 +08:00
JunChang Peng 6f68b8659d feat(plugins): make Ctrl+\ bindable in plugin keymaps; filter box for pick lists (#7488)
- Plugin keymaps accept the Backslash and Backquote key names (API 1.21), and a declared key is translated to the character the keystroke types, so Ctrl+Backslash (and Ctrl+Slash) from a plugin now match the key pressed.
- Pick dialogs with 15 or more candidates, and every plugin quickPick, get a filter field: with it the field holds focus and its arrows drive the list; without it the list keeps focus as before.

Co-authored-by: junchangpeng <[email protected]>
2026-12-04 02:27:14 +08:00
RuyimgByCN f49782daaf feat(plugins): add build.sdks and build.artifacts APIs (1.21) (#7775)
Plugin API 1.21 adds two read-only calls behind the build.read capability and the trusted-project gate:

- build.sdks(project, kind?): the installed JDKs, interpreters and toolchains of a kind (or all), with the one the project uses marked active.
- build.artifacts(project): the deployable WAR modules of the build model (origin build-model, with the ids the server run configurations use, e.g. maven:app/pom.xml) followed by the Project Structure > Artifacts entries (origin project-structure).

The Rust SDK, its mock and the docs cover both, and the official plugins and test fixtures are rebuilt. Used by https://github.com/RuyimgByCN/openidea-smart-tomcat.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-04 02:21:47 +08:00
RuyimgByCN 69374c8868 feat(plugins): support icons and optional text for statusBar items (#7737)
A [[contributes.statusBar]] item can declare an icon (a built-in icon name or a package SVG, with iconDark for dark themes) and leave text out, gated on plugin API 1.21. An icon-only item takes its tooltip, else the plugin's name, as its accessible label. The manifest docs list the new fields.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-04 02:14:18 +08:00
Muuтаmuutot 7c9fa1dc3b feat(settings): show the effective Maven local repository from the Maven home and settings file (#7719)
Closes #7654

The Local repository field of Settings > Build Tools > Maven now shows, as its placeholder, the repository a build actually reads: the <localRepository> of the user settings file (the configured one, else ~/.m2/settings.xml), then of the Maven home's global conf/settings.xml, then ~/.m2/repository. It is recomputed when the Maven home or the settings file changes. Neither setting is written, so -s and -Dmaven.repo.local stay as the user left them.

The resolution runs on the backend in a read-only maven_local_repository command that reuses ide-build's settings helpers, so under Remote Development the remote host's paths and Maven home are used. A home that names bin or the mvn executable is reduced to the installation root, with either path separator.

Co-authored-by: muutot <[email protected]>
2026-12-04 02:11:36 +08:00
l0ng-ai c412491972 fix(keymap): list Configure Current File Analysis in the VS Code keymap (#7866)
The VS Code preset lists every action an IntelliJ action id maps to; editor.highlightingLevel (PopupHector) was missing, which failed keymap.test.ts on main. It is added unbound.
2026-12-04 02:04:07 +08:00
LU XIANGRUIтаwildcatDownstairs 6fbbab6c6f fix(vcs): show the file's diff to the right of file history (#7744)
Fixes #6406

Git > Show History for a file now keeps the revisions and their commit details on the left (details below the revisions) and shows the selected revision's diff of that file on the right. Directory history keeps the repository log layout.

The diff follows Show Diff Preview and file history's own Diff Preview Location (Right by default; Bottom puts it below; Editor leaves it out and Show Diff opens a tab). The split is remembered per location. The details pane's change loading and preview are shared with the new pane, and the rename-aware matching of the history file's changes moved to historyFileChanges so Show Diff and the pane agree.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-04 02:00:01 +08:00
ntbang0901 eb2be13a1e fix(http-client): read pasted cURL commands as cURL does (#7861)
A pasted curl command often became a different request: -sX POST URL turned into GET POST, -D headers.txt URL into GET headers.txt, -I into a GET, -d @body.json was sent as that text, and commands copied with $'…' (bash) or ^"…^" (cmd) quoting were not converted.

The command is now split into words like the shell it was written for, every cURL option that takes a value is known and short-flag clusters are read, and data, form, upload, header and credential options map to what cURL sends. A command a request file can't express (standard input, several files joined with &, several commands) is pasted as it is. A test runs 31 commands through the real curl against a loopback server and compares them with the converted requests.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-04 01:54:16 +08:00
l0ng-ai 7fd5ad50b8 fix(ui): unify tool window icons as monochrome and fix dark-mode icon contrast (#7842)
Tool windows that borrowed coloured file, status, action or vendor icons (Documentation, Find Usages, GitHub Actions, Logcat, Python Console, NuGet, Python Packages, Jupyter Variables, Ports, the Flutter DevTools windows, Coverage) get dedicated monochrome icons at 16 and 20 px; the coloured originals stay where trees, badges and VCS use them. Database Consoles and Query Workspace get a console icon instead of the table grid, and data source entries use the database cylinder.

Icons in the project view, trees, tabs, menus and several popups take --fg-icon instead of --fg-muted / --fg-subtle, so monochrome icons have the same contrast in dark themes.
2026-12-04 01:52:52 +08:00
Yohann CATHERINEтаyohannlog b21be36bf8 perf(terminal): stop copying and shifting the scrollback on every output batch (#7840)
The reattach scrollback copied every output batch in full to find a clear marker split across the previous batch, and once 256 KiB were kept it shifted the whole buffer on every batch, under the lock output delivery also takes. Only the marker's length on each side of the boundary is checked now, and the oldest output is dropped 128 KiB at a time (a reattached terminal replays up to 384 KiB).

An alternate-screen switch split across two batches is now counted, so a reattached terminal comes back on the right screen.

Co-authored-by: yohannlog <[email protected]>
2026-12-04 01:47:46 +08:00
LU XIANGRUIтаwildcatDownstairs 35e4b4cc92 test: fix two Rust tests that fail CI on unrelated changes (#7833)
- folders_on_a_share_the_workspace_is_not_on_are_not_looked_up (Windows): Workspace::load now skips a refused project instead of failing, so the test asserts the refusal on normalize_projects and that load leaves the folder out.
- restricted_git_does_not_execute_signature_verifier_when_asked_to_verify: the fake verifier reads the payload before exiting, so git no longer dies of SIGPIPE while writing it.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-04 01:44:31 +08:00
Muuтаmuutot f1876f1260 feat(editor): highlighting level of the current file's editor (#7805)
Add Configure Current File Analysis… (editor.highlightingLevel, IDEA's PopupHector, Cmd+Alt+Shift+H / Ctrl+Alt+Shift+H) with the three levels None, Syntax and All Problems:

- All Problems (default): everything as before.
- Syntax: syntax and semantic colouring stay; diagnostics and their scrollbar marks leave the editor (Problems still lists them).
- None: plain text; the lezer highlighter is reconfigured out and semantic tokens are dropped.

The level lives in the editor state next to the other per-editor display overrides (cm/localAppearance.ts) and is not saved.

Co-authored-by: muutot <[email protected]>
2026-12-04 01:41:21 +08:00
Muuтаmuutot 703c33a089 feat(find): export results to a text file (#7835)
Add Export to Text File… (find.exportToTextFile) to the Find tool window's toolbar and results context menu. The report follows the tree as shown: the tab title, the match/file summary, then each file with its folder and its 1-based match lines; excluded matches are left out and a failed write shows an error notification.

The per-tab exclude/replace marks move to a small store in the find feature so the action can read them.

Co-authored-by: muutot <[email protected]>
2026-12-04 01:35:28 +08:00
Muuтаmuutot 16def0187c feat(editor): Move Caret to Text Start/End actions (#7836)
Add editor.textStart / editor.textEnd and their With Selection variants, mapped to EditorTextStart / EditorTextEnd / EditorTextStartWithSelection / EditorTextEndWithSelection for IdeaVim and imported keymaps.

The plain moves leave a single caret at the document boundary; the With Selection variants extend each selection from its anchor. The actions stay unbound in the default keymaps like the other plain caret moves, so the editor's own Ctrl+Home/End (Cmd+Home/End, Cmd+Up/Down on macOS) keep handling the keys and Navigation Bar, Jump to Source and Move Statement keep their macOS shortcuts.

Co-authored-by: muutot <[email protected]>
2026-12-04 01:31:14 +08:00
ntbang0901 d61ffa5430 feat(notebook): run cells from the keyboard with Ctrl/Cmd+Enter and Shift+Enter (#7845)
Ctrl+Enter (also Cmd+Enter on macOS) runs the notebook cell and keeps the caret in it, and Shift+Enter runs it and selects the next cell, adding a code cell at the end of the notebook. Run Cell, Run Cell and Select Below and Run Cell and Insert Below are actions in Find Action and the keymap settings; they take these keys only while the notebook has focus (notebookFocus), ahead of the editor's Split Line / Start New Line, and the notebook's own key handler is gone. Markdown cells render instead of running; while a cell runs, the keys do nothing on a code cell. Alt+Enter stays Show Intentions, so Insert Below has no default key except in the VS Code keymaps.

Closes #7624

Co-authored-by: ntbang0901 <[email protected]>
2026-12-04 01:27:05 +08:00
János Kranczlerтаjanoskranczler 9fcd7c1468 perf(agents): skip re-rendering conversation rows on unrelated task updates (#7815)
Each conversation row got the full task object, and every task update (usage, queue, settings) made a new one, so all replies rendered again while the agent worked. Rows now get a memoized RowTask with only the fields they show (id, provider, cwd, status, error, isolation, branch, base, fork/rollback capabilities); the RowTask type keeps a row from reading another field until it is added there. One usage_update in a 3580-entry session went from 185 ms (532 reply renders) to 3.3 ms (0).

Co-authored-by: janoskranczler <[email protected]>
2026-12-04 01:25:42 +08:00
l0ng-ai a6aa26ea2a fix(vcs): keep No Merges fast when pull requests branch off older commits (#7862)
With No Merges on, a hidden merge's graph parents are its parents' projections onto shown commits, merged. When pull requests branch off an older main commit, neither parent of a merge reaches the other, so each merge kept every feature merged before it and a 500K-commit repository never finished loading. The merged projection now drops the commits reachable through another of them (the same bounded walk that keeps a commit when unsure), in the graph builder and the filtered log view.

Fixes #7807
2026-12-04 01:17:06 +08:00
ntbang0901 ea4ac8cc6e fix(run): attribute Vitest and Jest results to their file, project and title (#7858)
Rerun Failed often ran no test and exited 0 for Vitest and Jest: a test file with (, ) or a space in its path (a Next.js route group such as app/(auth)/login.test.ts) was not recognised, so its failures landed on the previous file; Vitest project labels (|unit| src/a.test.ts) and Jest display names hid the file; and titles holding ' > ' were split, so -t matched nothing. Files are now read up to their extension, a project is a node under its file and the rerun passes --project, and names come from the printed tree where there is one; where the text can't tell a separator from a title the rerun pattern accepts both readings. Jest's Console block is no longer a failed test, and a Vitest file that cannot be loaded gets its error.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-04 01:09:25 +08:00
ntbang0901 f62b89fccc fix(run): rerun the failed cargo tests of the crate they belong to (#7856)
Rerun Failed on a failing should_panic test ran nothing and reported success, because the parser kept libtest's ' - should panic' suffix in the name. In a workspace the tests of every crate shared the node src/lib.rs, so a failure in one crate failed the same-named test of another and a rerun ran both; current cargo-nextest lines (FAIL [0.007s] (1/8) crate test) were read as tests of a crate called (1/8). A test binary's node is now 'src/lib.rs (crate)', renamed to cargo's selector ('src/lib.rs (-p a --lib)') when cargo prints it for a failed target. Rerun Failed and Run Selected use that selector, replace earlier names and targets, and start one run per test binary (one nextest run with a filterset).

Co-authored-by: ntbang0901 <[email protected]>
2026-12-04 01:07:43 +08:00
ntbang0901 3edc7ee1a0 fix(debugger): keep breakpoints when their file is renamed or moved (#7857)
After a file or folder was renamed or moved in the IDE, its breakpoints stayed stored under the old path and disappeared from the editor; nothing in the debugger listened to the IDE's file moves. Line breakpoints now follow with their id, properties and status, as do the source lines of method breakpoints and field watchpoints and an open properties popover; Undo moves them back. Where the new path already had a breakpoint on the same line, the moved file's stays. movedPath moves to platform/fileOps so the debugger can use it without importing the editor.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-04 01:06:00 +08:00
ntbang0901 42b6363646 fix(http-client): encode the credentials of Authorization: Basic user password (#7855)
Authorization: Basic user password in a .http file went out as written, so the server answered 401 to a correct password; a converted curl -u user:password writes that same line. The credentials are now Base64-encoded when the request is prepared. The line is split before variables are filled in, so a variable's value may contain spaces; credentials that are already encoded, also from a variable, are sent unchanged.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-04 01:02:52 +08:00
ntbang0901 7ff13704ff fix(maven): keep a model with JDK-activated modules current after a reload (#7854)
When a profile activated by <activation><jdk> added a module, the Maven model stayed out of date after every reload and its resolved dependencies were dropped: the sync read the POMs without a JDK while the host loads the model with the JDK Maven runs on, so their build-file hashes never matched. The sync now gets the same JDK and records which <jdk> conditions matched; switching to a JDK that flips one makes the model out of date, any other JDK change does not. The Dependency Analyzer model read by plugins loads the same way. Caches from before keep their state.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-04 01:02:04 +08:00
ntbang0901 a53e25f398 fix(http-client): send the files of a request body byte for byte (#7849)
A file included in a .http request body (< ./a.png, whole body or multipart part) was read as UTF-8 with replacement characters and lost its trailing line breaks, so images, archives and Latin-1 files arrived corrupted. The prepared body is now a list of text and file bytes and a file is sent exactly as it is on disk; included text files keep their trailing line break. A binary file shows as its < path line in the history and the Request tab, and Convert to cURL reads it by path (--data-binary @path, or a printf/cat pipe into --data-binary @- for a mixed body). History entries written by the previous version still load.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-04 00:58:04 +08:00
ntbang0901 ade8bdd36a fix(run): attach pytest failures to the test that failed (#7848)
With tests of the same name in several files, the test tree showed a failed test's traceback on another test and Rerun Failed could run nothing. The pytest parser matched a failure section to the first test whose name ended like the section title, cut short-summary ids at the first ' - ' (so test_eval[5 - 1-5] became a phantom test_eval[5), read a collection error as a test, and missed headings too long to be underlined. Sections are now held until the run ends and given to the tests reported with that outcome and title in report order, and ids are read with their [...] case in mind.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-04 00:55:37 +08:00
ntbang0901 0e221ba78a fix(database): ask before dropping a table's unsubmitted edits (#7850)
In a table tab, paging, reloading, sorting, filtering or changing the page size after editing a cell dropped the edit without a word, and paging or rerunning a result tab did the same. Both now ask "Changes are not submitted. Data will be lost. Continue?" first; Cancel keeps the edits and the page, sort, filter and page size as they were. Rows can't be edited or added while a page loads, since the load drops them.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-04 00:54:30 +08:00
ntbang0901 5f31f1292a fix(database): write copied and exported SQL for the table it was read from, with each dialect's literals (#7847)
SQL copied or exported from a grid could change the value or hit another table: MySQL backslashes were not escaped, "" and 0x10 in numeric columns were written unquoted, binary cells were quoted as their 0x... text, an UPDATE of a table whose columns are all keys had an empty SET, and statements named the table without its schema. Exports, One-Row copies and the console's log of submitted edits now share one literal writer per dialect (decimal numbers only, X'..' / 0x.. for binary columns), and statements name the table as the table tab or the query does, with the schema the query ran in when it has the table.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-04 00:40:37 +08:00
ntbang0901 5de7b0964e fix(database): keep a script's statements whole around each dialect's literals and comments (#7846)
The console's statement splitter cut some literals and comments, so part of one could run as a statement of its own (PostgreSQL /* outer /* inner */ ; DELETE FROM b; */ ran the DELETE). It now knows PostgreSQL and SQL Server nested comments, PostgreSQL E'...' strings and $ inside names, MySQL backslash escapes in double-quoted strings and its rule that -- needs a blank after it, SQL Server [a]]b] and SQLite [a;b] and backtick names. The TypeScript lexer behind the unsafe-statement warning reads the same literals alike.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-04 00:37:25 +08:00
Vadim LazukтаInf1mum 61418e9cb5 fix(vcs): honor the "Open project in" setting when opening worktrees (#7852)
Opening a worktree always spawned a new window because every entry point passed newWindow = true, which skips the Open project in policy. Double-click / Enter in the Worktrees panel, Create and Open in New Worktree, Open Existing Worktree in the branch menu and the Open Worktree action of an update failure now go through the policy; the explicit Open in New Window button and menu item still open a new window, and remote SSH/WSL worktrees still open a remote window.

Closes #7843

Co-authored-by: Inf1mum <[email protected]>
2026-12-04 00:35:43 +08:00
LU XIANGRUIтаwildcatDownstairs fd22254194 fix(automations): keep a run open until its scheduled turn starts (#7834)
A scheduled turn in an existing conversation could be recorded as Completed before it started: the run watcher reads the task status right after the prompt is accepted, and the previous turn's Ready stayed until the spawned turn showed its prompt. The status now turns Starting as soon as a scheduled prompt is accepted. This also fixes the intermittent SameTask failure of the automations safety-ceilings test.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-04 00:33:53 +08:00
LU XIANGRUIтаwildcatDownstairs e666bb2e33 fix(workbench): main toolbar, tool window stripe and status bar metrics (#7829)
Main toolbar items get a 10px pitch and the dropdowns 10/6px insets with a 16px chevron; stripe buttons get 5px padding on both sides; the status bar is 34px with 4px widget hover insets, its breadcrumbs lifted 5px, and the islands keep a 3px inset above it. Language Services moves after the caret position in the status bar. Compact mode keeps its previous metrics.

Fixed-viewport e2e layouts (commit checks, project tree second click, main toolbar label compression next to the New Agent Task button) get room for the wider gaps and the taller status bar.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-04 00:29:29 +08:00
l0ng-ai 4f2d85007b fix(agents): add scheduling to the new task composer (#7652)
The New Agent Task composer gets the clock button next to Start. It opens New Automation prefilled with the draft instructions, agent, model settings and workspace; opening or cancelling the dialog keeps the draft, and unattended permissions stay configured in the dialog.
2026-12-03 23:55:56 +08:00
l0ng-ai 6e5f91f7fd feat(agents): add a New Agent Task button to the main toolbar (#7718)
The main toolbar shows New Agent Task by default, between the Run widget and Search. It carries the selected agent's icon and runs agents.newTask; its menu lists the installed agents to start a task with another one, and ends with More Agents. Customize Main Toolbar can remove it. Below 480px the button is hidden so the toolbar keeps fitting the window.

Closes #4000
2026-12-03 23:28:13 +08:00
l0ng-ai e38599b82b fix(agents): restore the Install Skill dialog and memory picker styles (#7851)
The Settings > Agents redesign dropped the SkillsPage.module.css rules the Install Skill dialog uses and the MemoryPage.module.css rules of the memory picker's auto rows, and used an undeclared --space-2-5 (so those gaps were 0). The rules come back, the gaps are 10px, and Language smoke's paths follow the dialog's app icon to src/assets/openidea-logo.png. Fixes cssModules, customProperties and smoke-paths tests on main.
2026-12-03 23:27:39 +08:00
l0ng-ai 437008c517 fix(agents): keep following the chat end when a row grows after its render (#7811)
A row that changes height after its render (a message laid out late, a highlighted code block, an image loading) now scrolls the conversation to its end while it is following, instead of only being held in place.
2026-12-03 23:14:14 +08:00
LU XIANGRUIтаwildcatDownstairs 5947204022 fix(settings): Settings window title bar, tree, header, form indents and buttons (#7824)
The Settings window's title bar was 8px taller than the platform dialog, the search field, breadcrumb and content sat a few pixels off, the tree drew 12px chevrons, untitled sections were indented away from the group titles, checkbox rows were 26px apart and the button bar had no separator. The window is now titled "Settings – <project>", uses a 32px dialog title bar on macOS (--h-dialog-titlebar), 16px tree chevrons, 22px group and indent insets, 11/16/16/16 content padding, field-height checkbox rows and a hairline above the buttons. Also types the label/box pairs of the Appearance e2e check.

Closes #7817

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 23:13:14 +08:00
Anders JenboтаAJenbo d4a2a84c36 fix(php): give PHPantom the template, configuration and settings support it has (#7827)
PHPantom has its own Blade, Twig and framework support, but Twig, YAML and XML files were never sent to it, laravel-lsp kept running alongside it, and it was never told the project is trusted. PHPantom now joins twig, yaml and xml (XML limited to *.xml, *.xlf, *.xliff), replaces laravel-lsp, gets .phpantom.toml as a root marker, and configure_phpantom sends workspaceTrusted (servers only start outside Restricted Mode) plus the excluded folders and PHP file-type extensions as its indexing filters at startup and on every configuration change. Docs updated.

Co-authored-by: AJenbo <[email protected]>
2026-12-03 23:06:52 +08:00
János Kranczlerтаjanoskranczler 1c94aeb476 fix(agents): let a steered message join Claude's running turn (#7828)
In steer mode, a message sent while a Claude agent worked cancelled the running command: the driver sent it with priority now, which makes Claude Code cancel and start over. It now sends priority next, so Claude Code adds the message to the running turn after the current tool step (or when the turn ends) and the agent keeps working. Fixtures re-recorded with Claude Code 2.1.335, plus a recording for Stop while a steered message waits.

Co-authored-by: janoskranczler <[email protected]>
2026-12-03 23:02:36 +08:00
Vadim LazukтаInf1mum b9014f34cf fix(vcs): diff the selected commit's changes with Show Diff from the Git Log list (#7818)
Show Diff with focus in the Git Log's commit list said "Select a changed file to show its diff": the diff actions ask the focused view for its diff source and the commit list never registered one. The list now registers the changes pane's source: the pane's file selection when it has one, else the commit's first file with every file of the commit in the chain. A file-history list keeps its file-focused diff.

Closes #7810

Co-authored-by: Inf1mum <[email protected]>
2026-12-03 23:01:01 +08:00
Jacob Kjeldahlтаkjeldahl 0920f189d6 fix(syntax): class icon for Java 25 compact source files (#7819)
A Java 25 compact source file (JEP 512) took its Project view icon from its first top-level type (an enum or interface). Its top-level methods belong to the file's implicit class, so it now shows the class icon, the runnable one when it has a main (void main() or main(String[])). The Java main check is shared by class members and top-level methods.

Co-authored-by: kjeldahl <[email protected]>
2026-12-03 23:00:29 +08:00
l0ng-ai a3c7591624 fix(tools): find rust-analyzer with Homebrew rustup and install it for the project's toolchain (#7832)
Homebrew's rustup keeps its toolchain proxies in its own prefix (opt/rustup/bin), off PATH unless the shell adds it, so rust-analyzer was reported Missing even after Install succeeded. Those directories are now searched after ~/.cargo/bin and treated as rustup proxies at launch. The rustup status check, component add and component remove also run in the project, so a rust-toolchain.toml pin decides which toolchain gets the component and which one is checked.

Closes #7778
2026-12-03 22:50:25 +08:00
l0ng-ai 1ba9ace7e2 fix(java): import Maven projects linked below another project's folder into jdtls (#7831)
A pom.xml linked with Add Maven Projects inside the opened root, below a reactor that doesn't list it in <modules>, never reached jdtls: its folder scan stops at the first pom.xml and follows only that reactor's modules. Such links now give jdtls an explicit build-file list (projectConfigurations), as unlinked reactor modules and linked Gradle builds already do; configure_maven_import sets the list whenever one is given.

Closes #7789
2026-12-03 22:45:31 +08:00
l0ng-ai d8e58296be feat(agents): redesign Settings > Agents pages (#7825)
Reorganize Settings > Agents into General, Coding Agents, Permissions, Rules & Memory, Skills, MCP (External Servers, IDE Server), Agent Plugins and Automations, with redirects from the old MCP page ids. List pages share a master-detail layout and form pages align their fields. The IDE Server options stay in the settings search, and the docs use the new page names.
2026-12-03 22:32:31 +08:00
l0ng-ai 196057019f fix(build-tools): offer builds found in subfolders instead of syncing them on open (#7830)
Opening a folder whose Maven or Gradle builds sit only in subfolders (samples, fixtures) started mvn/gradle for each of them and showed an error when the tool was missing. Only builds at the project root (or a workspace member's root) and builds the user linked now load on their own; the rest are offered in a "Maven/Gradle build scripts found" notification with Load Maven Project / Load Gradle Project.

Closes #7802
2026-12-03 22:25:01 +08:00
l0ng-ai 272a183442 docs(plugins): mark released API versions with their OpenIDEA release (#7826)
API 1.11, 1.12, 1.14, 1.15, 1.19 and 1.20 were still listed as in development; each now names the release it shipped in, and the plugin overview names 1.20.0 as the latest released API and 1.21.0 as in development.
2026-12-03 22:12:14 +08:00
János Kranczlerтаjanoskranczler cd57b7f053 fix(agents): load an imported session's history when its task opens (#7816)
An imported (or forked) session showed no history when its background load failed or the app quit before it finished, because the history was only loaded with the first message. A task holding a recorded session but no history now loads it when its entries are first shown, once per run. A failed background load no longer makes the next message silently start a new session; only a failed message, which the user sees, does.

Co-authored-by: janoskranczler <[email protected]>
2026-12-03 22:10:51 +08:00
Jacob Kjeldahlтаkjeldahl 45dd96cdeb fix(run): gutter run for Java 25 compact source files (#7814)
A Java 25 compact source file (JEP 512: a top-level void main, no class) showed no gutter Run icon, because the run-target scanner only accepted main inside a class. A top-level main is now the main of the file's implicit class, named after the file, and the Java single-file producer launches such files with the source launcher (java File.java) instead of taking the first declared type as the main class.

Co-authored-by: kjeldahl <[email protected]>
2026-12-03 22:09:08 +08:00
Orca 22db3ab9c3 fix(editor): mark problems that have no text to underline (#7812)
A problem whose range is empty (an error at the end of a file ending in a blank line) or covers only a line break was listed in Problems and on the marker bar but not drawn in the editor, because the theme hid CodeMirror's lint point. It now draws one column of the severity's usual underline as a zero-width inline block, so WebKit paints it on empty lines too; hints stay hidden and the reported range is unchanged.

Closes #7784

Co-authored-by: og-orca <[email protected]>
2026-12-03 22:07:32 +08:00
LU XIANGRUIтаwildcatDownstairs 343dd51082 fix(project-view): match IntelliJ tree insets, indent and Scratches label (#7806)
Trees pad the whole Tree.border themselves: --tree-inset 12px (8px compact) plus 4px (2px) top and bottom, rows end 2px from the selection, indent 18px per level, 4px selection corners; tool window headers are 41px (32px compact). The old 6px inset assumed the island gap was inside the island. The Scratches root is now translated and relabelled when the UI language changes; agent task rows show Pin/Archive in place of the age on hover.

Closes #7795

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 22:01:47 +08:00
l0ng-ai 75c57e2691 feat(branding): use the gradient OpenIDEA logo (#7618)
Replace the OpenIDEA mark with the gradient ring artwork on the startup, welcome, About, clone and project-opening screens, in the OS icon bundle and in the documentation branding. The in-app logo is a bundled asset so it resolves under a Web IDE subpath. Dogfood keeps a greyscale version of the same artwork, and the Rust build tracks the embedded icon inputs so icon-only changes rebuild the development Dock icon.

Closes #3948
2026-12-03 21:59:06 +08:00
Vadim LazukтаInf1mum 856fc3009e fix(editor): navigate package.json dependencies to the installed package (#7800)
Go to Declaration / Cmd-click on a dependency entry of package.json had nothing to answer it. The reference fallback now resolves dependency entries of dependencies, devDependencies, peerDependencies and optionalDependencies: a name opens the installed package's package.json, a version reveals the package folder in the Project view, and an uninstalled package reports a missing reference. node_modules is looked up from the manifest upwards (hoisted installs, scoped packages); alias, workspace, path and URL ranges are skipped.

Closes #7665
Closes #7734

Co-authored-by: Inf1mum <[email protected]>
2026-12-03 21:17:00 +08:00
Bruno Valladares 3f7a072fa1 feat(plugins): icon theme choices that switch pattern groups, shown as radio buttons (#7694)
A choice option of an icon theme can list the groups it turns on (those groups are owned by the choice and leave the checkbox list), and can set the theme's default folder icons (folder, folderExpanded, folderOpen). A choice settings item takes presentation select, radio or segmented. Themes may declare up to 64 choices. Themes using none of the new keys produce the same mapping and page as before; stored per-group values of owned groups are ignored, not deleted.

Part of #7688.

Co-authored-by: Bruno0416 <[email protected]>
2026-12-03 21:11:10 +08:00
Bruno Valladares c9a2b6200e feat(plugins): let icon theme users show file icons instead of code element icons (#7695)
An icon theme can offer a fileIconsForCode checkbox (off by default). When on, Java and Kotlin files with a declaration show the theme's file icon in the Project tree and tabs, and the element kind stays visible as a corner badge in the tree. Off, or without a theme, nothing changes; settings written by older versions read as off.

Part of #7688.

Co-authored-by: Bruno0416 <[email protected]>
2026-12-03 21:05:34 +08:00
Bruno Valladares c1d552e578 feat(plugins): radio, segmented, slider, color and checkbox-list controls for plugin settings (#7693)
Plugin API 1.21 adds optional settings schema fields: presentation (select, radio, segmented, slider, color, checkbox-list), enumOptions (label, description, icon per enum value), minimum / maximum / step, and when conditions on another setting of the page. New src/ui primitives RadioGroup, SegmentedControl, CheckboxGroup, Slider and ColorInput. Schemas that use none of them render as before; manifests admitting an older API keep ignoring JSON Schema bounds.

Review changes: the fields are gated on API 1.21 (1.20 shipped in 0.1.57), and the colour swatch fill is stretched inside its button.

Part of #7688.

Co-authored-by: Bruno0416 <[email protected]>
2026-12-03 21:00:11 +08:00
Bruno Valladares 02d22fe658 feat(plugins): show icon previews on icon theme settings pages (#7692)
A group or a choice option of an icon theme can name one of the theme's icons with an optional icon key; the theme's settings page draws it whether or not the theme is applied. Previews are registered apart from the applied theme's icons and released with the page. Unknown icon ids are refused at install.

Part of #7688.

Co-authored-by: Bruno0416 <[email protected]>
2026-12-03 20:55:24 +08:00
Bruno Valladares 7f9a618cac feat(plugins): link an icon theme's settings page from the plugin details (#7691)
Each File Icon Themes row in a plugin's details gets a Settings… button while that theme's settings page is registered; it opens Settings at the page through file.settings.

Part of #7688.

Co-authored-by: Bruno0416 <[email protected]>
2026-12-03 20:53:31 +08:00
Bruno Valladares 1877d8c1a1 feat(ui): let icon themes tell Spring YAML and properties config files apart (#7690)
Spring application*/bootstrap* config files now use spring-config-yaml or spring-config-properties. Both render like spring-config by default and fall back to a theme's spring-config override, so existing themes keep working while a theme can override either one.

Part of #7688.

Co-authored-by: Bruno0416 <[email protected]>
2026-12-03 20:52:41 +08:00
Bruno Valladares 839da450f7 feat(plugins): let icon themes name folders that have a role (#7689)
An icon theme can list folder roles (source roots, packages, excluded, module folders, ...) in roleFolderNames; folders of a listed role then match the theme's folderNames and folder patterns before the role icon. An unmatched folder keeps the role icon only when the theme overrides it, otherwise it gets the theme's folder. Roles are validated at install; themes without the key behave as before.

Part of #7688.

Co-authored-by: Bruno0416 <[email protected]>
2026-12-03 20:51:49 +08:00
l0ng-ai ba42061885 fix(build): always compile with debug info in the IDE's Java build (#7809)
The IDE's Java build now always passes -g to javac and drops -g:none/-g:<level> from maven-compiler-plugin's <debug>, <debuglevel> and compiler args, so breakpoints work when launching with java-analyzer. Maven's own build still follows the POM.

Closes #7786
2026-12-03 20:41:00 +08:00
l0ng-ai 2b359f9a98 docs(plugins): format the manifest, versioning and README tables (#7808)
Run oxfmt on the plugin docs #7776 left unformatted, so pnpm format:check passes on main.
2026-12-03 20:40:02 +08:00
RuyimgByCN b83c1a60c2 feat(plugins): run lifecycle events, run.stop, configuration upsert, Java debug attach, log tail tabs and console toolbar (API 1.21) (#7776)
Plugin API 1.21:
- run-started events, and run-exited for user-launched plugin configurations (plugins on API 1.21 only).
- run.stop(id) for runs of the plugin's own configurations; run.upsert-configuration and run.open-edit-configurations for the plugin's own run configuration types.
- prepareCommand receives the run/debug mode; plugin configurations can declare a loopback JDWP attach target.
- runConfigTypes.ownsBeforeLaunch, log file tabs in the run console (plugin_run_log_tail, authorised by the plugin's project.read / fs.read grants), and the runConsole.toolbar menu in the Run and Debug consoles.

Review fixes: RunView log tab state keyed by the string session id, tail chunks cut on a UTF-8 boundary, user-run exits gated to API 1.21.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-03 20:29:31 +08:00
l0ng-ai f213999338 feat(agents): fork a running agent task up to its finished turns (#7720)
Fork was greyed out while a task's turn ran. It now copies the conversation up to the last finished turn while the source keeps running, and any finished turn can be forked from a message. The copy used to take the whole session and drop extra turns when it first loaded, which is wrong once the source has moved on: session/fork now takes _meta.openidea.forkTurns and the agent cuts the copy as it forks (Claude Code pins the fork point in its transcript, Codex rolls the forked thread back by the turns it holds). Agents without rollback still need the task to be idle; a task in its first turn has nothing to fork yet.
2026-12-03 20:04:10 +08:00
Deng Liuтаdengliu 920e321109 feat(agents): display plugin icons when browsing and previewing agent plugins (#7705)
Agent plugin marketplace entries and the plugin preview header showed text only, while MCP Connections › Browse shows server icons. Plugin icons are now resolved without extra network requests: explicit manifest or marketplace icon fields (https URLs validated, repo-relative images as raw.githubusercontent.com URLs or small data: URIs for local plugins), then conventional icon files in the fetched tree or local folder, then the GitHub owner's avatar. A shared AgentRemoteIcon tile renders them in both lists, theme-aware, with a fallback for monochrome icons.

Co-authored-by: dengliu <[email protected]>
2026-12-03 20:01:49 +08:00
Deng Liuтаdengliu ede0705bd5 feat(agents): discover deeply nested workspace skills via ProjectIndex (#7711)
Workspace skill discovery only walked two levels below each workspace root, so skills in deeper monorepo packages were missed. The skills policy now also takes the non-ignored SKILL.md files the project index already knows, and keeps those inside a known skills folder (.agents/skills, .openidea/skills, .claude/skills, .github/skills, .codex/skills, .cursor/skills) at depth 0-2, skipping hidden and build directories. The direct and depth 1-2 disk scans still come first, so discovery works before indexing completes and shallower packages win on name clashes. The Skills page reloads when indexing finishes.

Co-authored-by: dengliu <[email protected]>
2026-12-03 19:57:52 +08:00
LU XIANGRUIтаwildcatDownstairs a75c332905 feat(csharp): schema completion and validation for launchSettings.json and global.json (#7732)
Properties/launchSettings.json and global.json opened as plain JSON, with no key completion and no check of values such as commandName or rollForward. Both file names are now associated with their SchemaStore schemas in languages/json.toml, next to package.json and tsconfig.json; a $schema in the file still wins.

Closes #7729

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 19:52:36 +08:00
audichuang 954180beb0 feat(java): Spring bean gutter icons between beans and injection points (#7589)
Java files in Spring projects get gutter icons between beans and the places they are injected: an injection point (field, constructor or @Bean method parameter) navigates to the beans it receives, and a bean declaration to its injection points. One target jumps straight there; several open the inheritance chooser, with candidates marked. The editor asks once per file for a server-independent SpringBeanMarker shape, cancels stale requests and asks again after edits, when the server reports changed markers, or when a server settles or stops. java-analyzer is the first source (java-analyzer/springBeanMarkers, declared in its experimental capabilities); without such a server nothing is requested. Icons follow Gutter Icons, excluded folders and the server's features.

Refs #7140

Co-authored-by: audichuang <[email protected]>
2026-12-03 19:51:27 +08:00
l0ng-ai eb6483030c fix(run): browse the remote host for .env files and paths in a remote window (#7801)
Run/Debug Configurations opened their own local file dialog and hid every Browse button in a remote window, so .env files, the working directory and Tomcat paths on the remote host could only be typed. The run configuration form and the Tomcat settings now use the project-host chooser, which browses the remote host in a remote window and opens the system dialog locally.

Fixes #7715
2026-12-03 19:39:58 +08:00
l0ng-ai 6c9c02417e fix(ssh): reach older servers through the algorithm lists of ~/.ssh/config (#7799)
The built-in SSH client only offered russh's defaults and ignored the algorithm options of ~/.ssh/config, so a server that only speaks older algorithms could not be reached. The client now starts from the OpenSSH client's defaults (adding the ECDH key exchanges, aes128-gcm and the SHA-1 MACs) and applies KexAlgorithms, HostKeyAlgorithms, Ciphers and MACs with OpenSSH's +, - and ^ forms. They apply to SSH configurations that sign in with a password or key as well as to OpenSSH config hosts. When negotiation fails, the error names what the server offers and the line that allows it.

Fixes #7757
2026-12-03 19:36:01 +08:00
SwiftChenтаog-orca 9e7f842caf fix(toolbar): keep editor focus when clicking toolbar action buttons (#7792)
Editor actions on the main toolbar (Collapse All, Expand All) and plugin toolbar slots did nothing when clicked: the button took focus on mousedown, so editorFocus was false by the time the click dispatched and the action's when clause rejected it. A press on a toolbar action now leaves focus where it is, except while a tool window has focus, where actions gated on !toolWindowFocus (Reformat Code, Select Next Tab) still need the click to leave the tool window. Covers the main toolbar and contributed toolbars.

Closes #7758

Co-authored-by: swift98 <[email protected]>
Co-authored-by: og-orca <[email protected]>
2026-12-03 19:30:00 +08:00
l0ng-ai 0bda7b194b fix(svn): report the files an update changed instead of "All files are up-to-date" (#7797)
An update of a Subversion working copy has no commit range, so the update result always said all files were up to date, even when svn update changed files. Backend::update now returns how many files and folders the update added, deleted, changed or merged (read from svn update's status lines), vcs_remote returns it as an update report, and the result reads "N files updated". Covers Update Project and Update File / Update Directory.
2026-12-03 19:28:08 +08:00
LU XIANGRUIтаwildcatDownstairs 9ab90941ef feat(svn): Update File / Update Directory in the Subversion submenu (#7748)
The Subversion submenu had no way to update a single file or folder; only Update Project updated the whole working copy. A new svn.updateFiles action sits after Add and is named for the selection (Update File, Update Directory, Update Files, Update Directories). It runs `svn update` on the selected paths only, one update per working copy, through the same remote round as Update Project, so progress, console, conflicts and the result notification behave the same. Backend::update now takes the paths to update (empty means the whole working copy); a Git repository refuses the new RemoteOp::UpdateFiles.

Refs #7433

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 19:13:20 +08:00
Anka Tamaтаxirf 1dc1c67095 feat(agents): add Google Antigravity CLI as a built-in ACP agent (#7761)
Google Antigravity's CLI ships a native ACP server (`agy acp`, since v1.5.0), so it joins the built-in agents with `agy acp --login` as its sign-in command. A registry install of antigravity-acp runs a separate ACP server binary, so it keeps the generic sign-in hint instead of inheriting the CLI's login subcommand. Adds the Chinese text for the sign-in hint and the agent to the docs tables.

Co-authored-by: xirf <[email protected]>
2026-12-03 19:02:17 +08:00
LU XIANGRUIтаwildcatDownstairs 6f7c8e246f fix(run): keep a plugin form's errors blocking OK and Apply (#7787)
Since only added or edited configurations block saving, errors a plugin form reported with runConfig.setErrors on an unedited configuration left OK and Apply enabled, although the plugin API documents that they block them. The configuration on screen now blocks while its form reports errors; after selecting another one, an unedited configuration no longer blocks.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 18:54:24 +08:00
l0ng-ai 5638f8d04e test(plugins): edit the run configuration before its form errors block saving (#7791)
Since #7708 only configurations changed in Run/Debug Configurations block saving, so the plugin run configuration form test now patches the configuration before reporting errors.
2026-12-03 18:52:52 +08:00
l0ng-ai f156baa976 fix(tools,plugins): show updates installed in another project window (#7790)
Tool installs and the plugin host are shared by every project window, but each window kept its own copy of installed versions and updates, so after an update in one window another still offered it. After an install, uninstall, update or rollback, a window now writes a localStorage marker; the others read the tools or plugins (and the marketplace's installed versions) again on its storage event and take in the stored tool updates. The plugin update notice now has a key and is hidden once every update it offered is installed.

Fixes #7742
2026-12-03 18:51:27 +08:00
l0ng-ai d41bccc50c fix(editor): show no read-only banner above library sources (#7788)
Library sources opened from a language server or from the External Libraries showed a "Library source (read-only)" banner above the editor. They now open read-only without a notice, as the status bar's lock already shows the state; the banner stays for decompiled classes, Git revisions, generated C# sources and whenever there is something to act on (sources to download or choose).

Fixes #7735
2026-12-03 18:47:06 +08:00
JunChang Peng 9087fa61d9 perf(database): prefetch a table's DDL so Go to DDL opens at once (#7779)
Go to DDL queried the server on every click, so the editor opened a few hundred milliseconds late. A table's DDL is now prefetched when its data view opens and cached with the other metadata; Go to DDL serves the cache and fetches once on a miss. The cache is dropped on refresh, disconnect and after a console statement that changes the schema, and the generated file's Reload refreshes it.

Closes #7777

Co-authored-by: junchangpeng <[email protected]>
2026-12-03 18:41:58 +08:00
nICKтаNickYadance 6404c30718 fix(notebook): restore measured cell heights with scroll position (#7764)
Returning to a notebook tab restored the saved pixel offset against fresh 220 px cell estimates, because the virtualizer's measured heights were lost on unmount, so the viewport jumped away from the selected cell. The notebook session now keeps the virtualizer's measurement snapshot and restores it together with the scroll position.

Closes #7754

Co-authored-by: NickYadance <[email protected]>
2026-12-03 18:40:44 +08:00
Orca 66a765664c fix(editor): move a statement up past a function, method or class (#7785)
Move Statement Up did nothing when the line above ended a function, method or class: the lookup of the statement ending on that line stopped at the closing brace, and the guard against moving code into a function refused the move. Where a function or class body ends, the lookup now takes the whole declaration; if, for and try blocks are unchanged, so Up still moves a statement into them.

Closes #7765

Co-authored-by: og-orca <[email protected]>
2026-12-03 18:39:31 +08:00
Anka Tamaтаxirf fe1b5eacf8 fix(run): honor configured Node.js package manager in install prompts and config names (#7782)
An explicit Package manager in Settings > Languages & Frameworks > Node.js changed the spawned command, but the dependency-install notification and its run config, the package.json gutter fallback and detected npm run configuration names still showed the lockfile-detected manager. The configured manager now comes first in the gutter fallback, the install prompt rechecks when the setting changes (keeping an Ignore for the same dependency state), and detected config names have their leading package manager rewritten (bun run dev -> npm run dev, also after a workspace prefix).

Co-authored-by: xirf <[email protected]>
2026-12-03 18:38:19 +08:00
ntbang0901 21c4b08a5d fix(vcs): give the commit keys back when the focused commit list is removed (#7774)
Closing a file history tab with the keyboard while its commit list had focus left vcsLogCommitsFocus on, because React reports no blur for a focused element it removes; Left and Right in the editor then moved to the child or parent commit instead of the caret. The commit list now clears that context when it is removed, as it already did for vcsLogRevisionFocus.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-03 18:36:19 +08:00
ntbang0901 f8e0ad57ff fix(kotlin): wait for the jdtls import before replacing Kotlin libraries (#7773)
openidea.kotlin.replace was sent as soon as jdtls answered initialize, but jdtls holds commands while it imports the project, so an import longer than about two minutes hit the fixed 120 s timeout and the request was never resent; Java kept the old Kotlin API until a file changed. Each snapshot now waits for jdtls' ServiceReady first (shown in the status bar and cancellable there) and the 120 s count starts from there. A snapshot that times out, is refused or loses its server is retried after 5, 15 and 45 s before it is reported; a jdtls the user stopped is not started by a retry.

Closes #7726

Co-authored-by: ntbang0901 <[email protected]>
2026-12-03 18:35:27 +08:00
ntbang0901 72e1d6afc1 fix(project-tree): never lose an existing file to a copy or paste (#7772)
Copy or Save As of an open file onto a taken name in a folder the tree had not loaded replaced that file without asking, because the Copy dialog only knew loaded folders and copy_as overwrote its target. The dialog now reads the folder, and copy_as refuses any existing target. Pasting a file from the OS clipboard into its own folder (or dropping it there through another path) and choosing Overwrite trashed the source itself; such a file now gets a copy next to it, checked with a new fs_same_file command, and an overwrite whose import fails or is cancelled restores the old file.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-03 18:32:44 +08:00
ntbang0901 8ffd6c9e2c fix(search): read $1_new in a regex replacement as group 1 and report unknown groups (#7771)
With Regex on, Replace in Files read $1_new as a group named 1_new, which does not exist, so matches were replaced with nothing in every file. $1 now takes further digits only while the pattern has that group, and a template naming a group the pattern lacks is reported at the replacement field and changes no file. The editor's Replace now expands the same template, so $0, ${1}, $name and \$1 work there too and an optional group that did not match no longer writes undefined.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-03 18:27:33 +08:00
ntbang0901 dbfec0c433 fix(vcs): keep the other branch's changes in a merge commit with files left unchecked (#7770)
During a merge, an incoming file left unchecked went into the merge commit as HEAD had it, so the merge counted as done without that change and merging the branch again reported Already up to date; with nothing checked the whole merge could be dropped. With nothing checked, the commit now takes the merge as the index holds it. When some incoming changes (whole files or blocks) are left out, Commit first asks Changes Excluded from Merge Commit, with Cancel as the default. An unresolved conflict anywhere in a Git repository being committed now refuses the commit up front instead of failing later with a raw Git error.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-03 18:19:49 +08:00
ntbang0901 1bdd5b4094 fix(vcs): keep the file when a case-only rename is rolled back, left out or shelved (#7769)
On a case-insensitive disk, after git mv readme.md README.md (or a folder renamed the same way), Rollback deleted the file, a commit leaving the rename out committed its deletion, and Shelve reported no changes, because both names resolved to the one the index has. Unstage, a commit's excluded files, Shelve and Create Patch now act on both names of a staged case-only rename; Rollback and Shelve restore the old name on disk, and Unshelve brings the rename back by removing the old file first and putting the new name in the index.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-03 18:17:42 +08:00
koeriaтаkoeria 88eba9f3bd fix(workspace): keep a broken workspace manifest from making its folder impossible to open (#7768)
Opening a folder whose .openidea/workspace.json links a folder that contains it failed with "Store the workspace outside its linked project folders", and the folder could not be opened at all. Workspace::load now keeps the stored projects that are valid together, skips the others with a log warning, and leaves the file as it is until the workspace is saved again; writing still validates every manifest. A test checks that every manifest the write paths accept loads back.

Closes #7728

Co-authored-by: koeria <[email protected]>
2026-12-03 18:15:58 +08:00
RuyimgByCN 8044948178 fix(tomcat): build sibling Maven reactor dependencies before WAR launch (#7755)
When an aggregator listed sibling modules (parent/pom.xml with <module>../app</module>), the WAR build found its reactor by directory prefix, missed the aggregator and ran mvn package in the WAR module alone, so sibling dependencies were not rebuilt. The reactor is now resolved through <modules> membership, and -pl selectors are relative paths from the reactor root (../app, ..), with groupId:artifactId as a fallback. The Maven launch, multi-module compile and single-file classpath planners use the same helpers.

Closes #7704

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-03 18:09:41 +08:00
Orca 0425004ecd fix(agents): drop the task list focus when its focused element is removed (#7752)
Clicking a task in the Agents tool window replaces the list with the conversation while the list still has focus; React sends no blur for an element it removes, so the agentTaskListFocus context stayed on and Del in the editor asked to delete the open conversation. The same happened after picking a session from the history popup, archiving a row, or removing the last task while its search field had focus. The context is now cleared when the list element goes away and whenever focus lands outside the list.

Closes #7725

Co-authored-by: og-orca <[email protected]>
2026-12-03 18:07:49 +08:00
Ignacy Szreter c1b45b037d fix(csharp): colour Roslyn's record, delegate, extension method, field and constant tokens (#7756)
Roslyn sends records, delegates, extension methods, fields and constants with its own semantic token types (recordClass, recordStruct, delegate, extensionMethod, field, constant), which had no highlight class, so they showed as plain text. Each now maps to the standard type it extends.

Closes #7749

Co-authored-by: ignacyszreter <[email protected]>
2026-12-03 18:06:10 +08:00
ntbang0901 f5732dd706 fix(database): keep a console's transaction, temporary tables and settings on one connection (#7747)
In Tx: Auto each console statement ran on whichever pooled connection was free, so BEGIN ... ROLLBACK did not roll back, temporary tables and SET were lost between statements, and a forgotten BEGIN stayed open on a connection other features reused. A console now keeps its own connection from the first statement that leaves state on it (a transaction, a temporary table, a setting) until the console and its results are closed; plain queries and changes still run on the pool with the same result cursors. Applies to the built-in PostgreSQL, MySQL, SQL Server, Oracle and SQLite drivers; ClickHouse and JDBC already had console sessions, Snowflake and read-only PostgreSQL sources are unchanged. A pooled connection left inside a transaction is discarded instead of returned.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-03 18:04:58 +08:00
l0ng-ai e86e28ae63 fix(java): go to an interface method implemented by a superclass (#7781)
Go to Implementation on an interface method found nothing when the implementing class inherits the method from a superclass that does not implement the interface itself. The superclass's method is now listed, once however many classes inherit it.

Closes #7760
2026-12-03 18:03:56 +08:00
ntbang0901 82fdd97588 fix(vcs): keep a skipped rebase step's message off the commit below it (#7746)
In an interactive rebase, a reword or squash message was applied by an exec git commit --amend line that always ran, so when the step before it made no commit (Skip, a conflict resolved to nothing, an empty pick) it rewrote the commit below, including a published one. The line now compares HEAD with the HEAD recorded just before the step and does nothing when no commit was made; for a squash it also checks that the commit it goes into was made, since Git melds the squash into the commit below when that one was skipped.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-03 18:02:38 +08:00
l0ng-ai 1757d26e78 fix(debug): rerun a debug session with its configuration as saved now (#7780)
Rerun in the Debug tool window launched the configuration snapshot the session started with, so VM options edited since were ignored. It now launches the configuration saved under that id, or the snapshot when it was deleted.

Closes #7750
2026-12-03 18:01:23 +08:00
ntbang0901 766e1edc0c fix(vcs): keep patches and shelves independent of the user's diff and apply config (#7745)
The git diff calls that write a patch and the git apply calls that read it back took diff.noprefix, diff.mnemonicPrefix, diff.srcPrefix/dstPrefix, diff.context, diff.submodule and apply.whitespace/ignoreWhitespace from the user's config, so a shelf could unshelve into the wrong path, patches failed or landed on the wrong lines, and restored text was rewritten. They now share fixed option lists (patch::DIFF_FORMAT, patch::APPLY); an explicit path prefix, as a multi-repository shelf uses, still wins. Also covers the plugin working-tree patch, the per-file diffs of a pending commit and the partial-staging calls.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-03 18:01:14 +08:00
Isaac Gallartтаigallart fc52975be0 fix(project-tree): reuse effective roots across rows (#7739)
Every newly mounted Project row rebuilt the effective root list, which stalled scrollbar drags in workspaces with thousands of detected roots. ProjectView already computes that list for the tree; it now passes it to the rows, so their icons use the same roots without rebuilding it while scrolling.

Co-authored-by: igallart <[email protected]>
2026-12-03 17:59:10 +08:00
Orca c3726daed6 fix(project-tree): keep the clicked row in place between the clicks of a double-click (#7741)
With Always Select Opened File on, the first click of a double-click opened the preview tab and TreeHandle.reveal centered the row even though it was already visible, so the second click landed on another row. reveal now leaves a row that is in view where it is (1 px tolerance for fractional display scales) and centers only rows out of view. This applies to every tree that calls reveal.

Closes #7712

Co-authored-by: og-orca <[email protected]>
2026-12-03 17:57:49 +08:00
l0ng-ai 69c9521e85 fix(java): order the IDE build's Maven classpath as Maven does (#7767)
The build model listed a dependency's own dependencies after all of its siblings instead of right after it, so of two artifacts with the same classes (dom4j:dom4j 1.6.1 and org.dom4j:dom4j 2.x) javac could load the one Maven does not. Walk the resolved graph in pre-order and rebuild openidea-java-build.jar.

Closes #7743
2026-12-03 17:47:45 +08:00
LU XIANGRUIтаwildcatDownstairs fc60719d4b feat(python): move top-level functions, classes and variables to another module (#7680)
Refactor > Move (F6) in a .py file moves top-level functions, classes and variables to another module. The dialog has From file, To file (a .py path in the project, new or existing) and Elements to Move. An embedded ast-based helper, run with the pylsp-rope environment's Python, moves the code with its decorators and attached comments, places it by import-time dependencies, writes the imports both modules need and rewrites module.name uses; from ... import statements across the project go through the existing module-move rewriter. Unsaved buffers are read, a file changed meanwhile is refused, and every changed file is parsed again before the edit is returned. A name already defined at the destination is refused; risky cases are confirmed first. The tests needing pylsp are ignored by default.

Refs #901

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 17:41:54 +08:00
LU XIANGRUIтаwildcatDownstairs e35ba7d805 feat(python): Change Signature through rope (#7622)
Refactor > Change Signature works on Python functions, methods and classes (their __init__). pylsp-rope has no such command, so the IDE runs an embedded helper with the pylsp-rope environment's Python: rope finds the function, its overrides and calls and renames parameters scope-aware; the parameter list and arguments are rewritten from the ast so annotations, defaults, the * and / markers and keyword arguments survive. Unsaved buffers are read through an overlay, calls rope can't resolve come from the type checker's references, and calls that can't be rewritten or likely mistakes are listed in a confirmation first. The result is a normal workspace edit (Preview, Refactor, one undo). The dialog is the Java one reduced to Name and Default value. The rope tests are ignored by default.

Refs #901

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 17:36:01 +08:00
LU XIANGRUIтаwildcatDownstairs fa0783ab03 feat(python): search in comments and strings when renaming a symbol (#7679)
The Python Rename dialog offers Search in comments and strings (off by default, remembered; in-place rename follows it). Whole-word, case-sensitive matches in comments and string text are merged into the language server's workspace edit, so they preview, apply and undo with it; a rename that gains text matches is always previewed with the matches under Non-code usages, and applying fails if a matched file changed after the preview. Locals and parameters are searched in their function, other symbols in the project's .py / .pyi files including unsaved buffers; symlinks leading out of the project are skipped.

Refs #4968

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 17:23:45 +08:00
LU XIANGRUIтаwildcatDownstairs 5338a34008 feat(languages): Jinja2 templates in Flask projects, with template name completion and navigation (#7657)
.html files under a templates folder open as Jinja2 HTML when the nearest folder above that declares anything declares flask, quart, fastapi, starlette or jinja2 (pyproject.toml, requirements*.txt, Pipfile, setup.cfg, setup.py). A Django project (django declared or manage.py), package.json, angular.json, .git and the home folder end the search; File Types associations and Override File Type win; .htm is untouched; dependency files edited in place are detected again. Template names complete and navigate in extends / include / import / from and in render_template, stream_template, get_template, select_template and TemplateResponse.

Closes #7656

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 17:15:32 +08:00
LU XIANGRUIтаwildcatDownstairs 1d3547a953 feat(fsharp): tree-sitter grammars for outline, folding and symbols (#7640)
F# had only the CodeMirror mode, so without FsAutoComplete the Structure view was empty, indented blocks did not fold and F# declarations were missing from the symbol index. tree-sitter-fsharp 0.3.13 (MIT) is bundled: the main grammar for .fs / .fsx and its signature grammar for .fsi, with outline queries, folding, symbols and declaration-name highlighting over the existing mode. .fsi files are the language fsharp.signature, sharing one FsAutoComplete with source files and sent as languageId fsharp.

Closes #7637

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 17:10:44 +08:00
LU XIANGRUIтаwildcatDownstairs 14ed7aa647 feat(csharp): format with CSharpier and run dotnet format (#7645)
In a project that uses CSharpier (a dotnet tool manifest entry, or a .csharpierrc* / .csharpierignore with CSharpier installed), Reformat Code and format on save of a whole .cs file run CSharpier; selections and other projects keep the language server. CSharpier 0.x uses its pipe protocol. Solutions and projects get Run dotnet format and Verify dotnet format (No Changes) in the Project view and Find Action, with output in the Build window. The real SDK tests are ignored by default.

Closes #7626

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 16:58:35 +08:00
LU XIANGRUIтаwildcatDownstairs 27164e8919 fix(csharp): apply Roslyn's suppress and severity quick fixes (#7667)
Choosing Roslyn's "Suppress or configure issues" on a C# diagnostic did nothing: Roslyn returns its entries in the client command roslyn.client.nestedCodeAction, which the IDE did not handle. The entries are now listed by group (suppress, severity of the ID, of its category, of all analyzers) and applied like other code actions, so severities are written to .editorconfig. A newly created .editorconfig was ignored until a project reload, so the projects below it are now reported to Roslyn as changed. The real Roslyn test is ignored by default.

Closes #7646

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 16:45:44 +08:00
LU XIANGRUIтаwildcatDownstairs 62bac6ec8c feat(dotnet): run configurations for F# and Visual Basic projects (#7632)
Run configuration detection and its .sln / .slnx reader only accepted .csproj, so F# and Visual Basic projects got no run configurations. .fsproj and .vbproj now follow the C# rules. Visual Basic keeps launch profiles in My Project/launchSettings.json, where dotnet run looks, so profiles and the gutter run icons in that file read it. The real dotnet CLI test is ignored by default (no SDK in CI).

Closes #7631

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 16:39:50 +08:00
LU XIANGRUIтаwildcatDownstairs 17a32e0c1f feat(project-view): attach folders dropped on the Project view's blank area (#7634)
Folders dropped from the OS below the last row of the Project view now ask once to attach them to the current workspace, like File > Attach Project (one folder or a list of several), then attach each with the usual trust check. The primary project and folders already attached are skipped with a notice. While an all-folder drag is over the blank area the whole view is highlighted. Drops of files, or of files mixed with folders, drops on folder rows and drops in remote or LightEdit windows keep their previous behaviour.

Refs #7619

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 16:36:52 +08:00
LU XIANGRUIтаwildcatDownstairs e0ed6a0a3b feat(run): add Rerun Automatically for test tabs (#7686)
The test tree toolbar of every test runner (Jest and Vitest keep their watch mode) gets Rerun Automatically, with More Actions > Set AutoTest Delay (1-10 s, 3 by default). A delay after the last editor save of a project file, every tab with the toggle on runs its tests again in place without taking focus. Nothing runs while a saved file has a syntax error; a running test, a before launch build or a debug session of a configuration without parallel runs is not stopped but waited for; an automatic run saves no other file. The toggle lasts as long as the tab.

Part of #4968

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 16:33:14 +08:00
LeoChen8118таLeoChen8118 db0cdccd66 feat(sql): fold subqueries and the SELECT part of a statement (#7671)
SQL files had no folding. Parenthesised expressions (subqueries, IN (...), EXISTS (...)) fold like a bracket block, and a multi-line statement folds from the end of its own SELECT line to its end, so the SELECT line and an INSERT ... SELECT's INSERT line stay visible. The statement's SELECT is taken from the syntax tree, so a subquery's SELECT folds only its parentheses.

Co-authored-by: LeoChen8118 <[email protected]>
2026-12-03 16:29:34 +08:00
Muuтаmuutot 4237117f2c feat(build): offer Load Maven Changes and Load Gradle Changes above an edited build file (#7700)
A build file of a loaded project whose change left the imported model stale now shows a banner above the editor: "Build files changed since the last reload" with Load Maven Changes (a pom.xml of the Maven model) or Load Gradle Changes (a build or settings script of a Gradle build, reloading that build). It runs the same reload as the build tool window's banner and hides while a reload runs and before the first import.

Closes #7664

Co-authored-by: muutot <[email protected]>
2026-12-03 16:22:58 +08:00
Muuтаmuutot 26edc6d826 fix(vcs): close the front diff dialog when Show Diff in New Window opens the window (#7738)
Under the modal commit interface, Show Diff in New Window opened the diff window but left the front diff dialog open, so the same diff showed twice. showDiffWindow now resolves once the window is on its way and the action closes the open diff dialog; it stays when the window cannot open. On Windows and Linux the diff window's frameless title bar also gets the maximize button beside close.

Refs #7675

Co-authored-by: muutot <[email protected]>
2026-12-03 16:17:54 +08:00
Sameh Elhawaryтаsamehelhawary 92c71837cb feat(debugger): debug PHP in a Docker or Compose run target with Xdebug (#7613)
PHP configurations that run in a Docker or Compose run target can be debugged. The debugger listens first on a free port with the container's mounts mapped (run_container_xdebug), then the run starts with XDEBUG_MODE=debug, XDEBUG_SESSION=1 and XDEBUG_CONFIG pointing at host.docker.internal (docker run gets --add-host host-gateway); the debug session is linked to the run and stops with it. Install and Debug after installing php-debug repeats the whole flow. PHP on SSH targets stays refused.

Refs #4582

Co-authored-by: samehelhawary <[email protected]>
2026-12-03 16:12:19 +08:00
Sameh Elhawaryтаsamehelhawary 0791e73974 feat(php): run PHPStan and PHP-CS-Fixer in the container run target (#7616)
When PHP runs in a Docker or Compose run target, PHPStan and PHP-CS-Fixer run with that target's PHP, each in a new removed container (no published ports, entrypoint and service dependencies skipped, XDEBUG_MODE=off). PHPStan's report files are mapped back through the mounts; a cancelled check removes its container. PHP-CS-Fixer fixes a temporary copy mounted for that run only. The Settings › PHP hint now names these tools.

Refs #4582

Co-authored-by: samehelhawary <[email protected]>
2026-12-03 16:02:06 +08:00
Sameh Elhawaryтаsamehelhawary a8773a196c feat(php): show the version and Xdebug of a container run target's PHP (#7612)
When PHP runs in a Docker or Compose run target, Settings › PHP shows the version and Xdebug of the PHP in the container instead of this machine's. The IDE runs the target's PHP once in a removed container (entrypoint and service dependencies skipped, XDEBUG_MODE=off), keeps the answer per project and target configuration, and reads it again on refresh. php_probe_args shares the run/compose run part with the Python probe.

Refs #4582

Co-authored-by: samehelhawary <[email protected]>
2026-12-03 15:54:37 +08:00
audichuang 5f50469d7e fix(ui): keep a dialog on a frozen page from acting on keys (#7669)
During a Quit, a window waiting at the close barrier is frozen with inert on the body, but Dialog listens for keys on the document and accepted an Enter aimed at the body, so a confirmation left open (e.g. Delete from the Project view) ran its default button. A dialog inside an inert subtree now ignores keys.

Co-authored-by: audichuang <[email protected]>
2026-12-03 15:33:13 +08:00
LU XIANGRUIтаwildcatDownstairs 9e4fbe863d fix(csharp): show Roslyn's inlay hints and bold the right parameter (#7701)
Roslyn's inlay hints are off unless the client turns them on, and csharp.toml passed no csharp|inlay_hints settings, so C# showed no parameter name or type hints. csharp.toml and razor.toml now enable parameter hints for literals, new-expressions and indexers (with Roslyn's suppressions) and var/lambda parameter types. Parameter info matches string parameter labels as whole words from the parameter list on (all servers) and keeps a variadic last parameter (params, ..., *args) bold. The real-server test is ignored by default (needs the .NET SDK).

Closes #7678

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 15:31:16 +08:00
sonnartliao 7fdd39a628 fix(editor): navigate to C static inline definitions (#7721)
Go to Implementation on a C call to a static inline function found nothing or a prototype: the index stored prototypes and self-referencing macros like implementations. C/C++ index symbols now record whether they carry an implementation (index schema openidea-index-5, rebuilt once). The fallback skips prototypes, prefers functions over macros, prefers the header the file includes over arch copies, and collapses #ifdef duplicates to one target per file.

Co-authored-by: sonnartliao <[email protected]>
2026-12-03 15:27:17 +08:00
l0ng-ai 9d8fdab75e fix(agents): keep a Codex command that moved to the background from showing as failed (#7724)
A command Codex leaves running when its turn completes was still open at the turn's end, so the conversation settled its card as failed while it kept running. When a turn completes, the adapter now reports its still-open commands as done; the command's own completion reports how it ended. Interrupted and failed turns are unchanged.
2026-12-03 15:18:12 +08:00
l0ng-ai f09d51bd49 fix(agents): track and stop Codex background terminals (#7722)
A command Codex leaves running after its turn was invisible to the task, so the idle release stopped the app-server and the command kept running in its own process group. The Codex adapter now lists background terminals (thread/backgroundTerminals/list) after each turn until none runs and reports them as background tasks, which the idle release waits for; stop_task maps to terminate; session close and connection close run clean first. Older Codex versions report none.

Fixes #7655
2026-12-03 15:12:27 +08:00
l0ng-ai 00aef16862 fix(agents): render the composer stop button without a secondary border (#7682)
While an agent runs with an empty draft, the composer's submit button turns into Stop but kept the secondary variant, wrapping the outlined stop icon in a bordered box and shrinking it to 14px. The Stop state is now frameless at rest with toolbar hover/pressed backgrounds and the 16px stop icon, like the composer's other toolbar buttons and the IDE's Run/Debug stop buttons.
2026-12-03 14:51:21 +08:00
l0ng-ai 87b659b3ac fix(templates): expand live templates in PHP files (#7713)
The PHP grammar names its document node Template, and the check for being inside a comment or string treated any node named like a template string as one, so the whole PHP file counted as a string: code live templates (pubsf, prif, fore, ...) never expanded with Tab or showed in completion, and postfix templates were off too.

The document node no longer counts. The same name check in Emmet's JSX context, Move Caret to Code Block Start/End and Move Element Left/Right gets the same exception.

Fixes #7660
2026-12-03 14:49:44 +08:00
l0ng-ai 709cde907e fix(project-tree): reach the horizontal scrollbar without a sideways wheel (#7710)
The Project view's horizontal scrollbar is an overlay that only showed while the tree scrolled sideways, so with a plain mouse wheel there was no visible way to scroll a deeply nested tree to the right.

The overlay now also shows when the pointer is at the tree's bottom edge, where its thumb can be dragged. On Windows and Linux the Project view keeps the native horizontal scrollbar, visible whenever the tree is wider than the view.

Fixes #7648
2026-12-03 14:43:46 +08:00
l0ng-ai 6a69707220 fix(settings): show the folders of an attached project's module in Project Structure (#7709)
Modules of a project attached to the window come with absolute paths. The module list stripped the leading slash and the Sources tab joined the key to the window's root, so the folder tree read a path that doesn't exist and kept showing Loading... forever.

Absolute module keys are kept (or made relative when inside the window's project), the Sources tab reads the module's own folder, and a folder that can't be read shows as empty. Folders of an attached project are not marked from this project's settings.

Fixes #7647
2026-12-03 14:40:31 +08:00
l0ng-ai e30651473d fix(run): don't let an unedited invalid configuration block saving others (#7708)
Running the same Maven goals with different options (clean install / clean install -U) named two temporary configurations alike, which made both invalid; any invalid configuration disabled OK and Apply in Run/Debug Configurations, so no other configuration could be saved.

A temporary configuration whose name is taken now gets a numbered name, and only configurations added or changed in the dialog block saving. One that was already invalid when the dialog opened keeps its marker; Run and Debug stay disabled for it.

Fixes #7621
2026-12-03 14:37:37 +08:00
LU XIANGRUIтаwildcatDownstairs 8397e5e2a3 fix(xcode): build autocreated schemes in the background for code insight (#7650)
A project whose schemes Xcode autocreates has no .xcscheme files (a fresh XcodeGen project, or one never opened in Xcode). Schemes were read only from those files, so the background build for code insight failed with "The Xcode project has no scheme to build" and cross-file code intelligence stayed missing.

A .xcodeproj without any scheme file (shared or personal) now gets the schemes Xcode autocreates: one per target other than a unit-test or UI-test bundle, read from project.pbxproj without running xcodebuild (which resolves Swift packages first and can take seconds or hang offline). The index build uses the scheme Run builds first, and a project with nothing to build skips the index build quietly.

Closes #7644

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 14:34:49 +08:00
aconeshanaтаaconeshana 890fade636 fix(build): delete the output of resources the sources no longer have (#7687)
The resources step copies and overwrites but never deletes, so a resource removed from the sources (for example META-INF/spring.factories after switching branches) kept its copy in the build output and stayed on the launch classpath, failing Spring Boot with "Unable to read meta-data". Classes already have this through the incremental compile record; resources had none.

Each source set now records the output paths its resource roots map to (output folder, <targetPath>, path under the root, filtered by includes/excludes). After a successful resources step, and after a prepare run, files the previous record wrote that the sources no longer produce are deleted, along with folders they leave empty inside the output folder.

Closes #7630

Co-authored-by: aconeshana <[email protected]>
2026-12-03 14:31:49 +08:00
Orca dfe4784874 fix(plugins): give the truncated navigation notice its own title (#7685)
When plugin navigation stops at its file limit, the notice used the title of a failed index, so a working but truncated index looked broken. It is now titled "Plugin navigation indexing truncated"; the failure notice keeps its title.

Closes #7635

Co-authored-by: og-orca <[email protected]>
2026-12-03 14:30:15 +08:00
Orca 43c9053624 fix(http-client): open the variable of the selected environment (#7681)
Go to Declaration on {{name}} in a .http file listed the key of every environment. The lookup now receives the environment picked in Run with and follows the order a run reads it: the private file, the public file, $shared, then the last @name line of the file. With No Environment it still lists every key. Keys whose value is an object, an array or null are not variables and are skipped; escaped key names and a key written twice (the last one wins) are handled.

Closes #7672

Co-authored-by: og-orca <[email protected]>
2026-12-03 14:29:18 +08:00
koeriaтаkoeria 05c64c2475 fix(lsp): retry a pull of diagnostics the server rejected with ContentModified (#7696)
A pull of diagnostics that the server answered with ContentModified (an edit landed while it was computing) was dropped, so the file's diagnostics stayed stale until the next edit or save. Such a pull is now retried like a cancelled one, and textDocument/diagnostic is listed in retryOnContentModified so servers that honour staleRequestSupport retry on their own.

Refs #7651

Co-authored-by: koeria <[email protected]>
2026-12-03 14:19:24 +08:00
l0ng-ai 3334d1016b docs(readme): switch the WeChat group QR code to group 5 2026-12-03 14:09:42 +08:00
Deng Liuтаdengliu 637e227efa feat(agents): browse and install MCP servers from an MCP Registry (#7627)
Add an in-app MCP Registry browser to Settings › Agents › MCP Connections. It searches an open MCP Registry (v0.1, falling back to v0) — the GitHub MCP Registry by default, the official registry or a custom https URL — with infinite scroll and server icons. Servers install to Global or Project scope in one click when no input is needed, or through a dialog that asks for variables and secrets and confirms a missing local runtime. Installed servers record their registry name and URL.

Agent Plugins also offers two suggested marketplaces to browse or add when they are not registered yet.

Co-authored-by: dengliu <[email protected]>
2026-12-03 14:07:19 +08:00
Deng Liuтаdengliu 5432d7f288 feat(automations): sort Schedules tab by soonest upcoming run (#7610)
Order automations as an upcoming schedule queue: enabled automations with a next run first (soonest on top), then enabled ones without a next run, then paused ones, each by most recently updated. The same order applies to the Schedules tab, list_scoped and the MCP list_automations tool.

Co-authored-by: dengliu <[email protected]>
2026-12-03 13:16:04 +08:00
LU XIANGRUIтаwildcatDownstairs 2fdc024358 fix(kotlin): show the Gradle step of a kotlin-lsp import and warn when Gradle runs out of heap (#7670)
While kotlin-lsp imports a Gradle project it sends no $/progress reports, so the import task showed only its title and was marked "no progress for 180 s" even while Gradle was busy, and a Gradle daemon that ran out of heap (stuck in GC, the import never finishing) went unreported. kotlin-lsp forwards the build tool's console output as intellij/importLog, which was dropped; it is now handled: each line keeps the running import task alive, "> Task :…" and "> Configure project …" lines become the task's message, and Gradle's max-heap message, OutOfMemoryError or "GC overhead limit exceeded" raises one warning per session with the configured heap and how to raise it.

Closes #7668

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 12:34:02 +08:00
LU XIANGRUIтаwildcatDownstairs 84267f44ed fix(dotnet): explain how to get netcoredbg on Intel Macs and Windows on ARM64 (#7629)
Samsung publishes no prebuilt netcoredbg for Intel Macs or Windows on ARM64. On those platforms the tool installer offered an install that failed with "no release asset", and a .NET debug session reported only that the adapter was missing. Both now say there is no prebuilt build and how to get one (build from source, then put it on PATH or set its path in Language Servers settings); the debugger's notification opens those settings instead of retrying the launch. A netcoredbg on PATH or set in settings is still used. The release-asset check no longer treats an arm64-only macOS release as installable on an Intel Mac (only Apple silicon runs x64 builds through Rosetta).

Closes #7628

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 12:32:50 +08:00
Muuтаmuutot e08e455fe5 fix(python): say which formatter wins when both are selected (#7658)
Selecting Ruff and Black as the formatting provider at the same time was accepted silently, with Black formatting Python. While both are selected, the Ruff and Black formatter pages now show a note under the provider select saying Black wins, and the Ruff page says how to go back to Ruff. Other formatter pages are unchanged. Strings in en, zh and zh-TW.

Co-authored-by: muutot <[email protected]>
2026-12-03 12:30:56 +08:00
l0ng-ai ceb020857a chore: v0.1.57 2026-12-03 12:09:33 +08:00
l0ng-ai e8f5f6d6ba fix(vcs): align worktree review titles beside the path column 2026-12-03 12:07:06 +08:00
l0ng-ai b0f5c9aed0 ci: give the macOS Rust job 75 minutes (#7663)
Clippy and the test build take about 45 minutes on the macOS runner, so the job hit the 60-minute limit while tests were still running and main's Rust checks stayed red. macOS now gets the same limit as Windows.
2026-12-03 12:02:19 +08:00
l0ng-ai f40550e0cf fix(plugins): keep the plugin list from deadlocking with a grant change (#7676)
Building a plugin's info held the plugin's state lock while reading the ledger (net:setting: hosts, Java agent pin), while a grant change refreshing program pins holds the ledger and locks each plugin's state. Settings › Plugins stayed at Loading plugins and uninstall hung. info() now copies the state out and releases it before reading the ledger again.
2026-12-03 11:50:33 +08:00
l0ng-ai 43d668dc75 fix(run): save a Tomcat configuration whose before launch list has Build (#7662)
Validation treated the before launch Build of a Tomcat configuration (no
target) as an incomplete task, so a configuration with Build next to other
steps could not be applied or run.
2026-12-03 11:11:48 +08:00
l0ng-ai 81a746b8e2 fix(database): show a reloaded DDL in its open editor (#7659)
Reload in a generated DDL file and Go to DDL on an already open DDL file
wrote the file but left the open editor stale: the file lives outside the
project. The open document is now reloaded after the write.
2026-12-03 11:09:45 +08:00
l0ng-ai 0aaa586cec fix(java): apply the Java completion edits in Java editors (#7653)
The annotation completion without the trailing space and break / continue
ending with a semicolon compared the request language with "java", but the
request carried the display mode ("Java"). Requests now carry the language id.
2026-12-03 10:42:39 +08:00
koeriaтаkoeria 159f10ba82 fix(editor): restore the caret and scroll of files whose tab was closed (#7641)
Closing a file's tab and reopening it later came back at line 1: saveSession() built its files map from the open slots only, so a disposed slot's caret and scroll were gone at the next save, and the live Markdown source dropped the whole per-path preview state on docClosed. The controller now remembers the view state of a file that loses its last tab (untitled buffers skipped, LRU-bounded at 200), persists it in an optional `closed` map of the editor session next to `files`, and applies it once when the file opens again. An open tab's live state always wins, a navigation target still overrides the remembered position, deleted files drop their entry, and older session files load unchanged. The Markdown preview keeps its position and zoom across the close and drops only the rendered text.

Closes #7531

Co-authored-by: koeria <[email protected]>
2026-12-03 10:41:20 +08:00
LU XIANGRUIтаwildcatDownstairs 355d6005aa fix(sdk): list the JDK under External Libraries for Java modules only (#7642)
A Rust project listed a JDK under External Libraries: jdk_groups treated a folder without a Java build manifest as Java whenever languages.java.jdk was set or Project Structure had source roots, and those come from the merged global and project settings, so a JDK chosen once globally marked every project as Java. A module without pom.xml / Gradle files now gets the JDK only when it is a Java module: .classpath / .project, a Java .idea project or JAVA_MODULE .iml, Project Structure libraries, or .java files in the folder or a source root (bounded walk that skips ignored and hidden folders). The configured JDK only picks which JDK is shown.

Closes #7639

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 10:34:29 +08:00
Orca 98a6de6ff0 fix(github): open the selected file with Show Diff in the pull request trees (#7623)
Show Diff (Ctrl+D) on a file in the pull request Changes tree said "Select a changed file to show its diff": the diff actions ask the focused view for its selection through useDiffSource, and neither the pull request details tree nor the New Pull Request changes tree registered one. Both now do: the first selected file, else the tree's first file (a folder selection opens its first file), with the New Pull Request tree keeping its file chain for F7.

Closes #7614

Co-authored-by: og-orca <[email protected]>
2026-12-03 10:32:59 +08:00
Vadim LazukтаInf1mum 2f3f08efde fix(lsp): answer a server's own configuration section with its own settings block (#7611)
A server's Workspace Configuration never reached Intelephense: it asks workspace/configuration for its own section (`intelephense`) and takes the answer as its settings, but the handler only looked for that section under a `settings` key. The configuration editor saves the wrapped form (`{"intelephense": {...}}`), so the server got the whole configuration wrapped again and ignored files.maxSize, exclusions and the rest. The server's own section now also resolves to a top-level block of the same name; dotted sub-sections and the empty section are unchanged.

Closes #7609

Co-authored-by: Inf1mum <[email protected]>
2026-12-03 10:30:54 +08:00
LU XIANGRUIтаwildcatDownstairs 797904c308 fix(svn): update every working copy in a multi-root Update Project (#7620)
With two or more Subversion working copies, Update Project updated none of them: a multi-target round checked each root's upstream through vcsBranchInfo and skipped roots without one, which every working copy is. A non-Git root's update is now its own update (svn update / p4 sync) and skips the upstream check; Git roots without an upstream are still skipped. The console names the real command.

Refs #7433

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 10:27:59 +08:00
l0ng-ai c8f9f9cc37 fix(swift): run the SwiftLint set in Settings, and find SourceKit with only the Command Line Tools (#7625)
SwiftLint ran swiftlint from PATH and ignored the executable set in Settings;
it now runs the configured one. With only the Command Line Tools selected,
SwiftLint could not load SourceKit; it now gets TOOLCHAIN_DIR for them.
2026-12-03 09:31:21 +08:00
l0ng-ai db57c0961e fix(svn): require a trusted project to read a repository file at a revision (#7615)
svn_repository_file_at contacts the working copy's repository, like svn_repository_info, so
Restricted Mode no longer allows it. Fixes the Restricted Mode VCS command
sweep that failed on main.
2026-12-03 08:14:45 +08:00
Sameh Elhawaryтаsamehelhawary 70f6316a69 feat(php): a run target's PHP interpreter (#7608)
A run target gets a PHP interpreter field beside Python, Node.js and Java (Settings › Build, Execution, Deployment › Run Targets). A PHP run on the target uses it for php, versioned php8.3/php83 or a local interpreter path; empty keeps the target's PATH php. Tools written in PHP (phpunit, phpstan, composer) are not rewritten. Interpreter names are now matched case-insensitively (PHP.EXE, PYTHON.EXE).

Refs #4582

Co-authored-by: samehelhawary <[email protected]>
2026-12-03 06:10:29 +08:00
Deng Liuтаdengliu ac68fbe39e feat(agents): organize automated runs in a dedicated Automations group (#7605)
Automated agent runs get their own Automations group in the Agents tool window (below Ready to Review, active runs first, then latest update); runs that need input, failed or hit a usage limit escalate to those groups with an Automated cue. The default automated-run filter becomes Latest & Active: the latest run per schedule plus active, urgent and unread runs, so reading a rolling SameTask session no longer hides it. SameTask sessions are titled with the automation name, rows show a #run tag, orphaned runs a Detached pill, and context menus gain Open Automation and Pause/Resume Schedule.

Co-authored-by: dengliu <[email protected]>
2026-12-03 06:03:27 +08:00
l0ng-ai 41f4e22b29 feat(editor): Rearrange Code for TypeScript and JavaScript classes (#7607)
Rearrange Code orders the methods of TypeScript, TSX, JavaScript and JSX classes: the constructor, static methods, then instance methods, each public, protected, then private. Fields and static blocks before the first method stay put; methods move with their decorators and comments; adjacent overloads and accessor pairs move as one block. Classes where moving could change behaviour (fields or static blocks among methods, computed names, decorators naming other methods, region markers) are left alone.

Closes #7599
2026-12-03 05:53:04 +08:00
l0ng-ai af2e515d0f fix(svn): file history diffs, annotation details and new-file confirmation (#7606)
SVN annotation menu named the right system; single-revision history and cross-working-copy log diffs use each path's own previous revision and read paths outside the checkout from the repository; annotation details look up the requested revision; new SVN files follow the When files are created confirmation setting. Refs #7433.
2026-12-03 05:43:01 +08:00
l0ng-ai a1ed7af5cf test(plugins): use a Windows absolute path in the stop command parser test (#7604)
The test parsed a quoted /opt/... program, which has no drive on Windows, so validate_plugin_program rejected it and Rust (windows-latest) failed on main.
2026-12-03 05:14:21 +08:00
Deng Liuтаdengliu 43dac21ac3 fix(automations): support One-shot self-chaining and preserve agent schedule overrides (#7602)
Firing a OneShot automation with allowAgentSchedule disabled it before the agent turn started, so the agent's schedule_next_run failed with "The automation is disabled". Self-scheduling OneShot automations now stay enabled while their run is active and are disabled when the run finishes (or is abandoned) without a future seed or agent override. Saving non-schedule edits no longer wipes a pending agent override: it is kept unless the trigger changed, the automation or self-scheduling was turned off, maxRuns/disableAfter invalidates it, or the user clears it. The Edit dialog, dashboard and session banner show the agent-scheduled next run, with Clear/Keep override in the dialog.

Co-authored-by: dengliu <[email protected]>
2026-12-03 04:49:17 +08:00
l0ng-ai 0d3b001191 feat(database): external TCP tunnels for every network database (#7603)
The external tunnel helper (kubectl port-forward and the like) was offered only for PostgreSQL, though the route hands any driver a loopback endpoint. It is now available for every driver an SSH tunnel carries (MySQL/MariaDB, SQL Server, ClickHouse, Oracle). The helper also keeps KUBECONFIG and the gcloud/AWS/Azure CLI config locations from its cleared environment.

Closes #7591
2026-12-03 04:21:17 +08:00
l0ng-ai 0f328854a2 style(run): format clangdDatabase.ts (#7601)
pnpm format:check failed on main for src/features/run/clangdDatabase.ts (from #7551).
2026-12-03 03:53:28 +08:00
Furkan Şahin Kulaksız 5ae211ecd6 feat(plugins): add syntax-aware editor decoration providers (#7579)
Adds an optional syntax-decorations-provider export on plugin API 1.20: a plugin paints foreground colours on ranges of an open text editor from a bounded slice of the editor's own syntax tree (no second parser). A mark is a theme token (rainbow-1 … rainbow-5, mapped onto --syn-rainbow-*) or its own dark and light colours (#rrggbb / #rrggbbaa, the set-styled format; SyntaxMark::colored in the SDK). The host validates the snapshot, drops marks with unknown tokens or invalid colours, debounces and cancels superseded requests, and the editor stylesheet picks the dark or light colour, so a theme change does not ask the plugin again. Sticky Scroll lines keep the marks.

Co-authored-by: fsk <[email protected]>
2026-12-03 03:52:27 +08:00
l0ng-ai 55274d2dd1 feat(agents): install a built-in agent's CLI from Agent Setup, also on remote hosts (#7600)
Agent Setup offers Install CLI for a built-in agent whose CLI is missing, showing the host and exact command; it runs as a cancellable job on the project host and enables Sign In once the launcher is verified. npm packages cover nine built-ins, vendor installers the rest; update checks work in remote windows.

Fixes #7581
2026-12-03 03:44:57 +08:00
pHтаvvnadolskyy 72f7b59e3b fix(database): run Snowflake statements after switching to a role that can't use the current warehouse (#7596)
After switching to a role without usage on the current warehouse, Snowflake statements failed. The session now picks a warehouse the active role can use, the warehouse picker reads grants under the active role, and a schema refusal after reconnecting no longer restores stale session context.

Co-authored-by: vvnadolskyy <[email protected]>
2026-12-03 03:35:38 +08:00
Akbar Husain 581672eebc fix(run): pass the installed macOS SDK to clang for C/C++ files (#7595)
A compiler that derives its default sysroot from the macOS version it targets (e.g. Homebrew LLVM) can look for an SDK that is not installed, so single-file C/C++ runs failed with 'stdio.h' file not found. Tool lookup now resolves the SDK with xcrun --show-sdk-path (only when the developer tools are installed, since the xcrun stub otherwise opens an installer dialog; cached after the first lookup), and the generated compile command passes it as -isysroot.

Co-authored-by: akbar1214 <[email protected]>
2026-12-03 03:28:59 +08:00
l0ng-ai eace2fc741 perf(code-insight): read usage lines of many files in one call (#7598)
Usage lists read the line text of each file with one IPC call per file, which for ~1800 files took as long as the references request. fs_read_texts reads them in one call on a few threads (265-377 ms -> 57-59 ms on macOS); open editors and virtual documents keep using their editor text.

Refs #6823
2026-12-03 03:20:18 +08:00
Ivan f39b728947 fix(agents): sign in to Codex with a device code on remote hosts (#7586)
Signing in to Codex in a remote project uses the device-code flow on the project host, since the browser callback can't reach it; the code and link are shown in the IDE and the sign-in can be cancelled. Tokens stay in Codex's own credential store and out of remote wire logs.

Co-authored-by: Pecnikas <[email protected]>
2026-12-03 02:56:00 +08:00
Ivan f307355369 fix(remote): manage custom agents on the project host (#7585)
In a remote project, adding, editing and removing custom agents now acts on the project host instead of the local machine, with trust checks applied there. Edits run off the UI thread, concurrent writes are serialized, and sensitive values are kept out of remote wire logs.

Co-authored-by: Pecnikas <[email protected]>
2026-12-03 02:53:06 +08:00
l0ng-ai 611f40c6ce fix(ui): offer Cut, Copy, Paste and Select All on a right-click in a text field (#7593)
A right-click in a text field showed nothing: the webview's menu is blocked
everywhere and the fallback Copy menu skipped editable elements. A text
field, text area or contenteditable element without a menu of its own now
gets Cut, Copy, Paste and Select All, acting through the field's editing
commands so undo and input events follow. Cut and Paste are disabled in
read-only or disabled fields, Cut and Copy in password fields and without a
selection; non-text inputs get no menu.

Fixes #7570
2026-12-03 02:21:05 +08:00
Deng Liuтаdengliu 391b91539f feat(mcp): built-in MCP tools for project automations (#7377)
Agents can list, inspect and schedule the project's automations through built-in MCP tools. Calls carry an unspoofable per-session capability nonce, scheduling authority is tied to the live session that owns the active turn, project writes always ask for confirmation, and a run cannot undo a user pause. Self-scheduling needs an enabled automation, and the configured trigger and prompt survive an override. The Edit Automation dialog shows pending overrides and gets consistent insets.

Co-authored-by: dengliu <[email protected]>
2026-12-03 02:15:13 +08:00
audichuang 5633d76da1 feat(settings): Override File Type opens a list that filters as you type (#7578)
Override File Type shows a sorted list of file types that filters as you type, keeps its position as results narrow, tells apart languages with the same display name, and returns focus to where it was when closed.

Co-authored-by: audichuang <[email protected]>
2026-12-03 01:52:09 +08:00
l0ng-ai 310cbaad66 fix(vcs): scroll the merge window from its dividers (#7590)
The wheel over either merge-window divider now scrolls Result with the side panes and ribbons following; the two-way diff divider converts line and page wheel deltas to pixels.

Fixes #7566
2026-12-03 01:51:42 +08:00
Vadim LazukтаInf1mum bc63e8e029 fix(notebook): Copy Path/Reference and file bookmarks from a notebook cell (#7584)
Copy Path/Reference and file bookmarks work from a notebook cell: the chooser uses the same file path rows as the text editor, and file bookmarks target the active notebook tab even after focus leaves its cell.

Co-authored-by: Inf1mum <[email protected]>
2026-12-03 01:49:51 +08:00
Akbar Husain a579d81694 fix(vcs): navigate past deleted diffs in a chain (#7587)
Next/previous difference across a diff chain stopped at a file that was deleted (or added), because the viewer swaps sides for it and navigation read the swapped request. It now follows the original request, for direct file navigation and the difference-boundary hint in both directions.

Co-authored-by: akbar1214 <[email protected]>
2026-12-03 01:49:42 +08:00
faysouтаfaysou 6eb1f0713d test(vcs): verify the single-row Worktrees layout (#7588)
The Worktrees panel shows the folder, branch and path on one row, but the
layout spec still expected the folder above the branch and failed. It now
checks the three columns in order on one line, keeping the toolbar,
submodule and keyboard selection checks.

Co-authored-by: faysou <[email protected]>
2026-12-03 01:37:04 +08:00
audichuang 95d4a41b62 fix(vcs): close the Maximize Commit Message dialog before going to a linked commit (#7572)
Clicking a commit hash, parent or containing branch in the Maximize Commit
Message dialog selected the commit in the log behind the dialog, which stayed
open over it. The dialog now closes first, then goes to the commit; the log
list takes focus once the commit is selected unless focus moved elsewhere, and
a hash not in the log shows the "not found in the log" warning. Links in the
commit details pane are unchanged.

Closes #7554

Co-authored-by: audichuang <[email protected]>
2026-12-03 01:35:54 +08:00
l0ng-ai 18ac414b52 fix(code-insight): open Show Usages while a slow search has found nothing yet (#7583)
Show Usages opened early only once a partial result arrived, so a search
whose results come in one batch (usages of a Kotlin declaration found by
jdtls) showed only a caret hint until it was done. The popup now opens after
300 ms either way, with a spinner and "Searching for usages…", and fills in
as usages arrive. A search ending with none or one usage closes a popup that
showed none yet and answers with the hint or the jump. Ctrl+click on a
declaration drops its "Finding navigation target…" hint when it hands over
to Show Usages.

Refs #6823
2026-12-03 01:01:35 +08:00
tongkangwangтаchiyanking 10e399cbec fix(code-insight): fit the Show Usages filename column to its content (#7571)
The Show Usages filename column had a fixed cap, so widening the popup did
not reveal more of a truncated filename. The column now takes the width of
the longest filename among all results (measured off-screen, so virtualized
rows, speed search and filters keep the columns aligned), capped at 176px
(38% when narrow) or a fifth of a wider popup; the code column gets the rest.
It is remeasured when results or font metrics change. Same-named files keep
their directory captions.

Co-authored-by: chiyanking <[email protected]>
2026-12-03 00:56:09 +08:00
l0ng-ai ce4b2f9655 feat(deployment): compare a file with its deployed version (#7580)
Compare with Deployed Version (default server) and Compare with Deployed Version on… (choose a server) open the diff viewer with the editable local file against a read-only snapshot of the deployed one; binary and oversized files show a notice.

Fixes #7546
2026-12-03 00:41:16 +08:00
Sameh Elhawaryтаsamehelhawary 65686e246e feat(lsp): send a server the documents it registers a selector for (#7558)
A language server marked dynamic-documents (Phoxite for PHP and Blade) is sent the other-language documents it registers a document selector for, such as a framework's YAML, XML or JSON files, alongside their own servers.

Malformed selectors match no documents, relative glob restrictions are kept, and withdrawing a selector closes the documents it opened.

Co-authored-by: samehelhawary <[email protected]>
2026-12-03 00:39:11 +08:00
Sameh Elhawaryтаsamehelhawary 3078674a86 feat(http-client): Laravel and Symfony endpoints (#7559)
Laravel and Symfony routes are indexed as HTTP endpoints for the Endpoints view and HTTP client navigation. The route index publishes only after the latest reads finish, and exclusions are evaluated relative to each scanned project root.

Co-authored-by: samehelhawary <[email protected]>
2026-12-03 00:35:21 +08:00
l0ng-ai 82d8a6ea19 fix(lsp): stop syntax errors in files a shared server already checks (#7573)
One clangd serves C and C++. A header detected as C joined the instance started for C++, but the UI's list of the languages a running server checks was refreshed only on a status change, so the built-in syntax check parsed the C++ header as C and reported false syntax errors. A running server now reports its status again when it is given a new language; the Arduino server taking over a sketch's C++ files does the same.
2026-12-03 00:30:29 +08:00
Sameh Elhawaryтаsamehelhawary 3785b75582 feat(run): Symfony server run configuration (#7557)
Symfony projects (framework dependency, bin/console and public/index.php present) get a detected PHP built-in server run configuration serving through the front controller; Debug keeps PHP's web-server arguments.

Co-authored-by: samehelhawary <[email protected]>
2026-12-03 00:29:45 +08:00
Sameh Elhawaryтаsamehelhawary 15b55c66ca feat(php): Blade and Twig languages, and framework files read as PHP (#7556)
Blade and Twig templates get their own languages with highlighting, and framework files that are PHP under other names are associated with PHP.

The Blade highlighter's preceding-character check runs on WebKit, and language-server sharing between languages follows direct definitions only, preventing cycles and letting a shadowed server detach.

Co-authored-by: samehelhawary <[email protected]>
2026-12-03 00:28:52 +08:00
a2499123744-delтаa2499123744-del d6d6fd0909 fix(language): detect C++ standard headers from their first line (#7567)
Extensionless headers carrying an Emacs -*- C++ -*- mode line (libstdc++, libc++) or an MSVC "// <name> standard header" comment open as C++ even outside a known toolchain include tree, complementing the include-tree detection from #7547. Known extensions and shebangs keep precedence.

Co-authored-by: a2499123744-del <[email protected]>
2026-12-03 00:26:43 +08:00
RuyimgByCN 7bfad25bb5 feat(plugins): run configuration types with a plugin-provided form (#7445)
Plugins can contribute run configuration types (contributes.runConfigTypes, plugin API 1.20) whose settings form is rendered from the plugin's web view and prepared by the plugin.

Every plugin-owned configuration, including ones the user creates from such a form, is launched by the host only after checking the plugin's process grant and executable pin; the debugger launch rechecks them, and Stop revalidates the executable. Tests cover user-created configurations and grant revocation.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-03 00:26:01 +08:00
RuyimgByCN 5c31ccfe70 feat(svn): add Subversion merge dialog, eligible revisions picker, and reverse merge (#7344)
Subversion merge workflows on the built-in SVN backend. VCS > Subversion > Merge From... picks a source branch or URL, then merges selected eligible revisions (svn mergeinfo --show-revs eligible, paged), all revisions, or reintegrates a branch, with a test (dry-run) merge, depth, whitespace modes, --ignore-ancestry and --force. Reverse Merge (svn merge -c -REV) is in the VCS Log commit menu for Subversion revisions.

For a checkout of a subtree (trunk/module), the source URL keeps the working copy's path inside the branch. Revision ranges stay in SVN's native form (-r 100:120). Unsaved documents are saved and local changes are offered for review before merging. Streamed merge output runs under the working copy's write lock, so a merge cannot race Rollback.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-03 00:22:39 +08:00
Yohann CATHERINEтаyohannlog 304674d0fe feat(cpp): report functions declared but never defined (#7540)
A C or C++ function declared but never defined only failed at link time. A new inspection, Function declared but never defined (C/C++, weak warning), reports a prototype when clangd's go to definition finds only the declaration itself. Pure virtual, defaulted and deleted functions, operators, macro calls and Qt signals are left out. Quick fixes: Create Definition in the header's source file, and Implement Inline.

Co-authored-by: yohannlog <[email protected]>
2026-12-03 00:01:25 +08:00
Yohann CATHERINEтаyohannlog aa003541a3 feat(cpp): grey out inactive preprocessor code, show macro expansions, create library projects (#7539)
Three C / C++ gaps. Code left out by an #if / #ifdef branch is greyed out from clangd's inactive-code semantic tokens in C, C++ and Objective-C(++). View > Show Macro Expansion shows what the macro at the caret expands to, from clangd's hover. New Project > C/C++ has a project type: Executable, or a static or shared Library with a public include/ folder.

The template engine dropped only a bare LF after a block tag, so on Windows, where Git checks the generators out with CRLF, every {{#if}} line left a blank line in the generated files. It now drops a CRLF too.

Co-authored-by: yohannlog <[email protected]>
2026-12-03 00:00:14 +08:00
Yohann CATHERINEтаyohannlog d2699c430e feat(cpp): GoogleTest, Catch2, doctest and CTest results in the test tree (#7538)
C++ test executables ran as plain applications and CTest as one block of console output, so no test appeared in the test tree. CMake detection now marks an executable whose sources include GoogleTest, Catch2 v3 or doctest as a test configuration, and CTest as one too. Their output fills the test tree with each failure's message and location. GoogleTest, Catch2 and doctest test declarations get gutter icons that run one test through the framework's filter.

Co-authored-by: yohannlog <[email protected]>
2026-12-02 23:59:15 +08:00
Yohann CATHERINEтаyohannlog f404a33e7a feat(cpp): clangd reads the active CMake profile's compilation database (#7551)
In a CMake project with profiles or presets, clangd searched for compile_commands.json in each file's parent folders and their build/, so it could read another profile's or a stale database: test sources showed missing GoogleTest headers although the active profile compiles them. clangd now starts with --compile-commands-dir set to the active profile's build directory once it has a compile_commands.json. The window restarts this project's clangd when another profile becomes active, or when the IDE configures the active profile's directory for the first time. That first configure runs as a build task, so the restart follows the configurations reloading without the needs-configure mark instead of a run session's exit. An explicit --compile-commands-dir, a root compile_commands.json and a .clangd naming a CompilationDatabase are left alone.

Co-authored-by: yohannlog <[email protected]>
2026-12-02 23:55:03 +08:00
l0ng-ai 05e7db4be6 test(color-scheme): check bold on the Go package token (#7568)
Go package references have their own token since #7561, so Bold on the Go page sets --syn-go-package-bold; the settings test now reads that variable.
2026-12-02 23:36:23 +08:00
LU XIANGRUIтаwildcatDownstairs 8ad3fc4faf fix(vfs): keep a dangling Windows junction from listing as a folder (#7486)
On Windows, a dangling directory junction showed in the Project view as an expandable folder that listed nothing. lstat of a junction reports size 0, and the UI reads a size-0 link as a link to a folder. read_dir now sizes a dangling link by its target's length, which is what lstat already reports on macOS and Linux, so their behaviour is unchanged. A Windows test creates real junctions with mklink /J and lists them the way the Project view does. The Git workflow fixture names its extra clones by a hash so long paths stay under MAX_PATH.

Refs #7419

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 23:27:01 +08:00
faysouтаfaysou 3f7b83e8fd test: fix Windows Rust fixture paths (#7552)
Three Rust tests failed on Windows. Two dev-container tests built Unix-style labels while the Windows CLI supplies native paths, so their label lookups returned nothing. The Git batching test could hit Git for Windows' file path limit before it reached the command-line length case. The labels now use native paths, and the temporary test repositories enable core.longpaths.

Co-authored-by: faysou <[email protected]>
2026-12-02 23:25:22 +08:00
l0ng-ai 7fa280e9e0 feat(remote): open a dev container from the Welcome screen and from devcontainer.json (#7565)
The Welcome screen lists local dev container configurations and an open devcontainer.json offers Open in Container, both through the existing Reopen in Container flow with trust and host checks; the reopen prompt remembers dismissal per project.

Fixes #7417
2026-12-02 23:24:09 +08:00
l0ng-ai 3c8acf8ee3 feat(database): table DDL for custom JDBC sources (#7564)
The JDBC bridge builds CREATE TABLE from JDBC metadata (columns, defaults, primary key, indexes, foreign keys) for custom drivers and reports whether a failure is unsupported, a permission problem or a database error.

Fixes #7451
2026-12-02 23:23:59 +08:00
l0ng-ai 0d94a8973e feat(html): highlight HTML inside template script blocks (#7563)
text/html and text/template script blocks get the HTML parser, and the fallback syntax checker ignores errors inside complete FreeMarker directives.

Fixes #7400
2026-12-02 23:23:45 +08:00
l0ng-ai 18f28cd804 feat(code-insight): compact Language Services status widget for the current file (#7562)
The status item is a compact icon whose badge reflects the active file's servers; the popup lists the current file's servers first, then the project's others, keeping restart, log and update actions.

Fixes #7489
2026-12-02 23:23:37 +08:00
l0ng-ai 37f2dd3ced feat(go): distinct colours for variables, calls, packages and types (#7561)
gopls semantic roles for variables, package qualifiers, calls and types map to distinct colours in every bundled theme and are exposed in the Go colour scheme settings.

Fixes #7487
2026-12-02 23:23:29 +08:00
Muuтаmuutot ba5eb92c70 fix(python): let a selected Ruff format below [tool.black] (#7476)
Choosing Ruff as the Python formatter had no effect below a pyproject.toml with [tool.black]: the formatter lookup picked Black whenever Black was enabled and configured, before it looked at which tool the user had selected. An explicit choice now wins. A selected Black formats Python even without [tool.black] and before a selected Ruff. A selected Ruff formats Python below [tool.black]. Without an explicit choice, [tool.black] still hands formatting to Black.

The Ruff and Black settings pages stay where they are, and their hints now say how the two choices interact.

Fixes #7178

Co-authored-by: muutot <[email protected]>
2026-12-02 23:23:23 +08:00
l0ng-ai bbbcf23c77 feat(vim): move through the completion list with Ctrl+N / Ctrl+P in Insert mode (#7525)
With Vim on Windows and Linux, Ctrl+N and Ctrl+P in Insert mode went to the IDE keymap (Go to
Class, Parameter Info) even while a completion list was open. While a list is open in Insert
mode they now move its selection, unless the user set a handler for the stroke; Normal and Visual
modes are unchanged.

Fixes #7418
2026-12-02 23:19:12 +08:00
Isaac Gallartтаigallart ac9f745dcf feat(navigation-bar): reveal folders in Project on double-click (#7545)
Double-clicking a folder in the navigation bar or in its dropdown now selects it in the Project
view, closes the popup and focuses the tree. A single click still opens the dropdown; a folder
row in the dropdown waits briefly before browsing so a double-click can land on it.

Closes #7555

Co-authored-by: igallart <[email protected]>
2026-12-02 23:18:59 +08:00
faysouтаfaysou 86cfabfbe4 fix(markdown): align split scroll within lists and paragraphs (#7189)
The Markdown split view interpolated within whole top-level blocks, so the preview could land on a
different passage than the source when a list or paragraph wrapped unevenly. List items now carry
their source line offset (nested items included) and plain paragraphs map lines through the text
range, so scroll sync aligns within them; other blocks keep the existing mapping.

Co-authored-by: faysou <[email protected]>
2026-12-02 23:18:47 +08:00
Onur Ugur 6b038245fd fix(color-scheme): show Language Defaults overrides on a language's comment attributes (#7473)
A language's comment attribute (JavaScript Line comment) resolved against the scheme without the
user's Language Defaults overrides, so turning italic off under Language Defaults left the
language page's Italic checkbox checked. resolvedAttribute now applies those overrides for
language-scoped attributes, as the editor does.

The plugin-theme part of #7453 was fixed by #7474; this PR keeps the remaining fix.

Co-authored-by: OnurrUgur <[email protected]>
2026-12-02 23:18:35 +08:00
l0ng-ai e985322f3a fix(ui): use the spacing scale for new 2px gaps (#7560)
Services deployment rows and the dev container resources panel used a literal gap: 2px, failing spacingScale.test.ts on main; both use var(--space-0-5).
2026-12-02 23:16:55 +08:00
RuyimgByCN 1f329cbc87 feat(tomcat): show Tomcat in Services with deployment controls and log tabs (#7494)
Tomcat run configurations appear in the Services tool window with their deployed artifacts, deploy/redeploy/undeploy controls and separate server and application log tabs. Deployment state follows the server's lifecycle output rather than the presence of context XML, failed operations stay visible across refresh, and Run and Debug route like other run configurations.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-02 23:04:31 +08:00
Onur Ugur 0f0cdd4672 fix(macos): route Cmd+` natively and drop spurious Cmd text insertion (#7436)
On macOS, Cmd+/ and Cmd+` left a character at the caret (`/` and a backtick under ABC, `、` and
`·` under Pinyin), and Cmd+` did not switch project windows: WKWebView's performKeyEquivalent
routed the key through NSTextInputContext before NSMenu. WryWebView's performKeyEquivalent now
dispatches window.next / window.previous for Cmd+` / Cmd+Shift+`, and insertText is dropped for a
Command key-down without marked text. A frontend guard drops text beforeinput events right after
a Command key-down as a fallback.

Closes #7334

Co-authored-by: OnurrUgur <[email protected]>
2026-12-02 23:02:11 +08:00
audichuang 875b17938e fix(macos): wait for windows to finish leaving full screen before Merge All moves tabs (#7480)
Merge All Project Windows invoked from a group in native full screen aborted the app: tabs were
moved with `addTabbedWindow` while the full-screen exit animation was still running, and AppKit
threw. `merge` now waits (up to 3 s) for the windows that were in full screen, or already leaving
it, to finish, then re-checks the candidates before moving tabs.

Co-authored-by: audichuang <[email protected]>
2026-12-02 23:01:45 +08:00
audichuang 6820d27af5 fix(macos): keep the window group's selected tab when the Window menu switches tabs (#7462)
Picking another tab of a project window group from the macOS Window menu switched tabs in
AppKit without going through `window_groups::select`, so the group's saved selection stayed on
the previous tab and the group reopened on it after a restart. When a tab gains focus while its
native tab group shows it and holds every member of the model's group, the model's selection now
follows, emits the same events and persists as `window_group_select` does.

Co-authored-by: audichuang <[email protected]>
2026-12-02 23:01:31 +08:00
LU XIANGRUIтаwildcatDownstairs 02aa916a26 fix(xcode): show a short command line instead of the run's launch script (#7485)
An Xcode run or debug session printed its whole generated `/bin/sh -c 'set -e ...'` launch
script as the console's first line. `RunExtras` gains a `display` override (never saved or sent
to the frontend) that `invocation()` echoes instead of the real command line; `xcode::prepare`
sets it to the xcodebuild build plus what happens to the app (install & launch on a simulator or
device, or launch on the Mac). The real command line is still logged at debug level.

Closes #7483

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 22:49:26 +08:00
solhovoy a7b9529109 feat(bookmarks): start the Bookmarks tree collapsed and reveal new bookmarks (#7532)
The Bookmarks tool window tree starts collapsed and expands just enough to reveal a newly added bookmark. Expansion state is kept per tree, and a bookmark replaced by an edit is not treated as new.

Co-authored-by: solhovoy <[email protected]>
2026-12-02 22:44:07 +08:00
Yohann CATHERINEтаyohannlog 0303a513cd feat(cmake): Reload CMake Project and Reset Cache and Reload (#7537)
Adds Reload CMake Project, which configures the active profile again and refreshes its targets and compile_commands.json, and Reset Cache and Reload CMake Project, which first deletes the build directory's CMakeCache.txt and CMakeFiles through the new cmake_reset_cache command and keeps the build type the cache held. A failed delete is reported and nothing is configured. Both are in a Build > CMake submenu shown while the project has CMake configurations, in Find Action and in the title-bar CMake profile switcher; the configure output shows in the Run window.

Co-authored-by: yohannlog <[email protected]>
2026-12-02 22:05:29 +08:00
l0ng-ai a2bf7fb0c4 refactor(terminal): remove selection occurrence highlights
Selecting text in the terminal no longer highlights its other visible
occurrences; Find (⌘F) covers this with match counts and navigation.
Removes the terminal.highlightSelection setting and its toggle.
2026-12-02 22:05:18 +08:00
Yohann CATHERINEтаyohannlog 17dd723a3d feat(cpp): generate constructors, accessors and operators in C++ classes (#7536)
Generate (Cmd+N / Alt+Insert) in a C++ class or struct now offers Constructor, Getter, Setter, Getter and Setter, Equality Operators and Stream Output Operator next to clangd's own generate actions. Fields are picked in the member chooser and the members are written at the end of the class in a public section; accessors with no field left to write are listed greyed out with the reason. Stream output adds #include <ostream> when no stream header is included. Headers opened as C get the entries when they hold C++ code, and clangd's "Declare implicit copy/move members" now counts as a generate action.

Co-authored-by: yohannlog <[email protected]>
2026-12-02 21:59:57 +08:00
Isaac Gallartтаigallart f1097831d7 fix(project-tree): smooth scrollbar thumb dragging (#7541)
Dragging the vertical scrollbar thumb in a large tree could stutter: every pointer move updated the virtual rows and remeasured the scrollbar, and the tree remeasured the widths of rows that stayed mounted. The thumb drag now applies the latest pointer position once per frame (and on release), reuses the scrollbar geometry while dragging, and the tree measures only new or resized rows on scroll, remeasuring all of them when its content changes.

Closes #7543

Co-authored-by: igallart <[email protected]>
2026-12-02 21:57:32 +08:00
LU XIANGRUIтаwildcatDownstairs ad0a755f07 fix(vcs): let the branch tree collapse and expand while searching (#7471)
In Git > Log > Branches, folder arrows, Expand All and Collapse All did nothing while a search was active. A new search still shows every match expanded, but the user can now collapse and expand within it; clearing the search restores the expansion from before.

Fixes #7438

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 21:51:56 +08:00
faysouтаfaysou 099bb57abd fix(vcs): skip missing sources when jumping from Git Log (#7550)
Jump to Source in the Git Log opened an error tab when the selected file no longer exists at that path in the working tree. It now checks the working tree first and only opens an existing file. Open Repository Version still opens the historical snapshot.

Co-authored-by: faysou <[email protected]>
2026-12-02 21:51:42 +08:00
l0ng-ai 1ba2ce55bb fix(macos): keep project tab close confirmations visible (#7501)
Closing a macOS project tab group could cover the running-agent confirmation when a peer returned to Welcome and took focus. Confirmations and the Welcome transition now take turns, and background web views stay attached while their close checks are pending.
2026-12-02 21:43:58 +08:00
LU XIANGRUIтаwildcatDownstairs 24588b0975 perf(xcode): reuse the build description across xcodebuild runs of JSON5 projects (#7530)
In Tuist's JSON5 project format, package product build file GUIDs come from Swift's per-process hash seed, so every xcodebuild process recreated the build description (10-14 s). Runs, tests, Clean and the index build now start xcodebuild with SWIFT_DETERMINISTIC_HASHING=1, so a Rerun with nothing to rebuild reuses the previous description. The launched app does not get the variable.

Closes #7528

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 21:41:38 +08:00
Yohann CATHERINEтаyohannlog 8dc1fecc0e feat(templates): C and C++ live templates (#7535)
Adds live templates for C, C++ and Objective-C(++): a C set (main, fori, if/ife, while, do, sw, st, tds, en, inc/incl, incg include guard named after the file, ifdef/ifndef, pf) and a C++ set (iter, itit, ritit, cl, cls, nsp, tmpl, lam, try, cout/cerr/cin, uptr/sptr, sc, GoogleTest test, Catch2/doctest tc). Documented on the C/C++ language page.

Co-authored-by: yohannlog <[email protected]>
2026-12-02 21:40:11 +08:00
l0ng-ai cb7668d4f0 fix(settings): reorder the Agents settings pages (#7544)
Settings > Agents now lists Agent Setup, Chat, Command Rules, MCP Connections, IDE MCP Server, Skills, Memory, Plugins and Automations, in that order. Plugins and the IDE MCP Server page no longer share the same order value.
2026-12-02 21:40:03 +08:00
Ernstjan FreriksтаEjaYF 90377204aa fix(database): show a table icon for the Database Output tool window (#7519)
The Database Output tool window button used the db-console icon, the same glyph as the Terminal button. It now uses db-table, the icon its result tabs already use.

Co-authored-by: EjaYF <[email protected]>
2026-12-02 21:39:56 +08:00
l0ng-ai 1d3de3c366 fix(ui): tidy menu shortcuts, icons, Worktrees list and Project Trust placement
- Menus: shortcuts sit flush right; an empty chevron column is reserved only
  when a submenu row also has a shortcut.
- Database Consoles root uses the database icon; Project Structure icon is
  monochrome like the other menu icons.
- Worktrees: one line per worktree with aligned name, branch and path columns;
  a single repository lists its worktrees without a section row or expander.
- Settings: Project Trust moves under Appearance & Behavior.
2026-12-02 21:36:17 +08:00
l0ng-ai 4466a059b3 fix(agents): replace send with stop and simplify header (#7526)
While a session is running and there is nothing to send, the Send/Queue button becomes Stop; with a draft, Queue stays and Stop moves into the message actions menu. The Automations clock leaves the Agents header (Automations stays in the Options menu), and the gear opens Agent Settings instead of MCP Connections.
2026-12-02 21:35:18 +08:00
RuyimgByCN b7bacc8ff5 feat(build): incremental javac and artifact sync for Project Structure artifacts (#7496)
Building a Project Structure WAR artifact compiles incrementally with the Java build service and syncs only changed files into the artifact, falling back to a full javac build if the incremental build fails. The build streams progress and honours cancellation through the Tomcat run's build step.

Copied files and archives are checked byte for byte, archives are replaced atomically, and old staging directories migrate to a clean layout.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-02 21:28:30 +08:00
l0ng-ai 50508b0af0 fix(keymap): move database result tabs with Ctrl+PageUp/PageDown in NetBeans (#7549)
The NetBeans presets move editor tabs with Ctrl+PageDown/PageUp but kept the IntelliJ keys for database result tabs. Bind the result tabs to the same keys. The Search Everywhere narrow-window test now cycles through every tab, since the Endpoints tab was added.
2026-12-02 21:28:10 +08:00
Onur Ugur ef4458c04c feat(remote): show dev container resource limits, usage and OOM kills (#7518)
The remote status shows the dev container's CPU and memory limits and live usage, and says when the container hit its memory limit, using Docker's explicit OOM status rather than the exit code. Stale responses after a disconnect are discarded and host round-trip time is measured independently of Docker polling; MCP approval flow and tool registrations are kept.

Closes #7467

Co-authored-by: OnurrUgur <[email protected]>
2026-12-02 21:23:33 +08:00
solhovoy 0666f9ea5a feat(vcs): rename shelves with F2 and keep Shelf expansion state (#7527)
F2 renames the selected shelf when the Shelf list has focus. Root and group expansion in the Shelf tab survives remounts, with groups expanded by default.

Co-authored-by: solhovoy <[email protected]>
2026-12-02 21:19:46 +08:00
LU XIANGRUIтаwildcatDownstairs 3fe4e12252 feat(nuget): audit packages for vulnerabilities and deprecations (#7448)
After a successful restore, packages are audited for known vulnerabilities, deprecations and newer versions; findings show as markers in project and Directory.Packages.props files and as Problems entries.

Audits distinguish resolved versions, combine diagnostics for shared central package files, compute multi-line UTF-16 spans correctly, and run only after the actual target restored.

Closes #7439

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 21:18:25 +08:00
l0ng-ai 9ecb664036 fix(terminal): give wide emoji two columns (#7548)
Terminals and embedded terminals load xterm's Unicode 11 width provider before output, so wide emoji take two columns instead of one.

Fixes #7482
2026-12-02 21:17:12 +08:00
l0ng-ai e6c8d6d9ac fix(cpp): recognise extensionless standard library headers (#7547)
Extensionless files inside libstdc++, libc++ and MSVC include trees open as C++; an ordinary file named like a header elsewhere stays plain text, and explicit associations and first-line detection keep precedence.

Fixes #7503
2026-12-02 21:17:04 +08:00
LU XIANGRUIтаwildcatDownstairs a68ebc1293 fix(xcode): end a simulator run with how the app ended (#7456)
A crashing app on the iOS Simulator ended its run with exit code 0. The run now takes the app's real exit status from the simulator, keeps a nonzero simctl launch status, and a logged exit status no longer overrides an explicit Stop.

Fixes #7450

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 21:15:47 +08:00
Onur Ugur 8b267c6307 fix(run): stream Tomcat build progress and recognise localized startup lines (#7521)
The Tomcat run's build step ran silently with a dummy cancellation token. It now streams compile and packaging progress to the run console, can be cancelled while the build starts, recognises localized Tomcat startup lines, and ignores error-level lines when detecting readiness. Normal Maven and Gradle WAR packaging is kept so generated and transformed files reach the deployment.

Fixes #7458

Co-authored-by: OnurrUgur <[email protected]>
2026-12-02 21:14:44 +08:00
l0ng-ai 67460f1275 fix(app): update Tauri to 2.13 to stop random aborts on Linux (#7509)
Tauri before 2.13 cloned and dropped tao's event loop window target (a non-atomic Rc) on tokio worker threads, corrupting the heap and aborting the app at random on Linux. Tauri 2.13 keeps it on the main thread.

- tauri 2.13.0, tauri-runtime-wry 2.13.0, tao 0.38, wry 0.58; @tauri-apps/api and CLI 2.13
- gtk 0.19 and webkit2gtk 3 for our Linux code
- tauri-plugin-mcp-bridge 0.13.2 (debug-only E2E bridge) requires tauri ~2.12; a copy with only its version requirements widened lives in vendor/ and is applied through [patch.crates-io]

Fixes #5617
2026-12-02 21:05:50 +08:00
l0ng-ai 4a620287c8 fix(project): offer New › Package in source roots marked by hand in Maven and Gradle modules (#7542)
A folder marked as Sources or Test Sources Root by hand inside a Maven or Gradle module now offers New › Package and Java paste uses its package, instead of creating a single folder named com.example.
2026-12-02 20:37:58 +08:00
astesiaтаkirito1105 607812d8fa feat(editor): make the code insight file size limit configurable (#7461)
Settings › Editor gains a code insight file size limit (default 5 MiB). Files above it open without syntax analysis and language servers, with a banner saying why.

The size decision is fixed for each open document so syntax and LSP registration agree across reloads, the hard editing limit and undo snapshot budget stay independent, and read-only files above the limit get the right banner.

Co-authored-by: kirito1105 <[email protected]>
2026-12-02 20:07:47 +08:00
rolicon 90f9d4ffd0 feat(java): project-level Maven compile goals to ignore (#7479)
A goal bound to the compile phase that local runs don't need (maven-jar-plugin:jar and the like) made the build fall back from the built-in incremental javac to Maven. languages.java.maven.ignoredCompileGoals lists exact groupId:artifactId:goal entries to skip in that decision; the default empty list keeps the old behaviour, and Gradle, dependency and compiler checks are unchanged. Covered by a real Maven reactor test and documented in the Java build README.

Co-authored-by: rolicon <[email protected]>
2026-12-02 20:02:56 +08:00
l0ng-ai 0f359ddf3b fix(mybatis): link Kotlin mapper interfaces to their XML statements (#7534)
The navigator only registered for Java and scanned .java declarations. It now also registers for Kotlin, scans Kotlin interface declarations, and resolves XML namespaces and statement ids back to Kotlin methods, including files named differently from the interface. Plugin 0.4.3 with a rebuilt component.

Fixes #7459
2026-12-02 20:01:20 +08:00
l0ng-ai 51a6b40314 fix(vcs): annotate the focused diff pane from the keyboard (#7533)
Annotate with Git Blame resolved only the active editor, so its shortcut in a focused diff showed "Open a file to annotate it". The action now resolves the focused diff pane and revision for toggle state, enablement and run; Copy as Plain/Rich Text act on the focused diff selection too.

Fixes #7437
2026-12-02 20:00:39 +08:00
l0ng-ai bd5af356f4 fix(settings): align field edges across settings sections (#7522)
Project Structure and the language and VCS Settings pages share one label column across sections, reserve room for browse and refresh buttons so fields keep the same width, and stack labels on narrow panes.
2026-12-02 19:33:29 +08:00
l0ng-ai d3cb8513be fix(vcs): show why checkout was blocked (#7520)
When untracked files block a checkout, an error dialog lists them, says whether Git would overwrite or remove them, and the reason is recorded in the Git Console. Warnings and errors from explicit branch and worktree commands stay visible with background notifications muted, and Checkout and Update reports a failed HEAD read instead of silently skipping the update.
2026-12-02 19:33:22 +08:00
l0ng-ai 29d1a52d91 fix(agents): wait for attention before marking a chat unread (#7517)
Streamed reply entries no longer mark a background chat unread while the agent is still working. Task updates and attention events mark it unread when the turn finishes, needs input or fails.
2026-12-02 19:33:11 +08:00
Onur Ugur 5b24b61b49 feat(editor): register caret movement and line start/end actions (#7465)
Up, Down, Left, Right, Line Start, Line End and their With Selection variants were handled by the editor's keys only, so they could not be bound in keymapOverrides, imported IDEA keymaps (EditorUp, EditorLineStart, …) or IdeaVim. They are now Editor Actions running the same CodeMirror commands as the keys (smart Home, sticky selection), enabled in text editors and the editable side of a diff, with no default shortcut. A user override now wins over a preset binding on the same keystroke even when the overridden action already appears in the preset. Fixes #7452

Co-authored-by: OnurrUgur <[email protected]>
2026-12-02 19:21:42 +08:00
l0ng-ai 1dd8ea9b3b feat(markdown): zoom the focused preview with Cmd/Ctrl+= and Cmd/Ctrl+- (#7523)
With the Markdown preview focused, the editor's expand / collapse keys (Cmd/Ctrl+= and Cmd/Ctrl+-) run the new Increase / Decrease Preview Font Size actions, gated by a markdownPreviewFocus context key; in the editor they still expand and collapse folds. The Eclipse keymaps already give these keys to Increase / Decrease Font Size, which zooms the focused preview, so they leave the new actions unbound. Fixes #7380
2026-12-02 19:16:28 +08:00
Ivan 2221afad01 feat(mcp): tools for the project's dev container (#7378)
Five MCP tools report, start, rebuild and run commands in the project's dev container through the IDE's own Docker and Dev Containers support, inside its trust checks and confirmations.

Runs keep a structured host-or-container target and refuse to start when an approved container target is missing or no longer matches; the container is identified by both devcontainer labels, pinned to the approved ID, and its config may not escape the project through a symlink. The tools are listed and dispatched only on the local desktop.

Closes #7293

Co-authored-by: Pecnikas <[email protected]>
2026-12-02 19:06:17 +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
1896 змінених файлів з 135830 додано та 14400 видалено

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
Бінарний файл не відображається.

До

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

Бінарний файл не відображається.

Після

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

+14 -5
Переглянути файл
@@ -7,11 +7,20 @@
## How it was verified
<!-- Required. Commands you actually ran and their results; what else this could
affect and how you checked it still works.
Visible UI changes: before/after screenshots (not for removed UI or copy-only
changes). Multi-step interactions: a recording.
Backend changes: logs or command output. -->
<!-- Required, from the final version of this branch. Commands you actually ran and
their results; what else this could affect and how you checked it still works.
Then the evidence for each kind of change this PR makes (AGENTS.md § Issues & PRs):
- Bug fix: a test that fails on main and passes here, or exact repro steps
- Visible UI: before/after screenshots, same state and size; each theme touched
- Interaction (multi-step, drag, keyboard, focus): a recording
- Code intelligence / run / debug: language_smoke or smoke output on a fixture
- Performance: before/after numbers on the same machine, and the results unchanged
- Windows/Linux only: CI job plus a screenshot or log from a real machine
- Settings / persisted data: starting from the previous version's data
- Copy, docs, refactor, no UI change: write "No visible change"
Drag screenshots and recordings in here; don't commit them. -->
## Review focus
+9 -2
Переглянути файл
@@ -106,8 +106,9 @@ jobs:
if: needs.changes.outputs.rust == 'true'
permissions:
contents: read
# A Windows build that misses the Rust cache spends ~50 minutes compiling before the tests run.
timeout-minutes: ${{ matrix.os == 'windows-latest' && 75 || 60 }}
# A Windows build that misses the Rust cache spends ~50 minutes compiling before the tests run;
# on macOS clippy plus the test build alone take ~45 minutes.
timeout-minutes: ${{ matrix.os == 'ubuntu-latest' && 60 || 75 }}
strategy:
fail-fast: false
matrix:
@@ -370,6 +371,12 @@ jobs:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
# src/features/dotnet/edit.test.ts and *.cli.test.ts run the real `dotnet` CLI; with CI set they fail, not skip, when it is missing.
- uses: actions/setup-dotnet@v5
with:
dotnet-version: |
10.0.x
11.0.x
- run: pnpm install --frozen-lockfile
- run: pnpm typecheck
- run: pnpm lint
+3 -2
Переглянути файл
@@ -36,6 +36,7 @@ on:
- "src/editor/core/cm/iconArea.ts"
- "src/editor/core/cm/inlineBg.ts"
- "src/editor/core/cm/localAppearance.ts"
- "src/editor/core/cm/lineNumberOptions.ts"
- "src/editor/lsp/availability.ts"
- "src/editor/lsp/diagnostics.ts"
- "src/editor/lsp/files.ts"
@@ -46,7 +47,7 @@ on:
- "src/bindings.ts"
- "src/styles/tokens.css"
- "src/test/setup.ts"
- "src-tauri/icons/128x128.png"
- "src/assets/openidea-logo.png"
- "smoke/**"
- "vite.config.ts"
- "tsconfig.json"
@@ -110,7 +111,7 @@ jobs:
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|lineNumberOptions|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src/assets/openidea-logo\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
+20 -2
Переглянути файл
@@ -1,9 +1,9 @@
name: PR check
on:
# pull_request_target so the check can label PRs from forks. It never checks out
# or runs PR code: it only reads the PR title and description.
# or runs PR code: it only reads the PR title, description and changed file names.
pull_request_target:
types: [opened, edited, reopened, ready_for_review]
types: [opened, edited, reopened, ready_for_review, synchronize]
permissions:
issues: write
@@ -34,6 +34,24 @@ jobs:
const { owner, repo } = context.repo;
const issue_number = pr.number;
if (verified && verified[1].trim()) {
const section = verified[1];
const hasMedia =
/!\[[^\]]*\]\(|<img\b|<video\b|github\.com\/user-attachments\/|https?:\/\/\S+\.(png|jpe?g|gif|webp|mp4|mov|webm)\b/i.test(section);
const optedOut = /no visible change/i.test(section);
if (!hasMedia && !optedOut) {
const files = await github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number: issue_number, per_page: 100 });
const ui = files
.filter(f => f.status !== 'removed')
.map(f => f.filename)
.filter(name => /^src\/.*\.(tsx|css)$/.test(name) && !/\.(test|spec)\.tsx$/.test(name));
if (ui.length) {
const shown = ui.slice(0, 3).map(n => `\`${n}\``).join(', ') + (ui.length > 3 ? ', …' : '');
problems.push(`This PR changes UI files (${shown}). Add before/after screenshots, or a recording for interactions, to **How it was verified**; if nothing users see changed, write "No visible change" and say what you checked.`);
}
}
}
const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number });
const existing = comments.find(c => c.user.type === 'Bot' && c.body.includes(MARKER));
const labeled = pr.labels.some(l => l.name === LABEL);
+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
Переглянути файл
@@ -20,6 +20,7 @@
"pnpm-lock.yaml",
"**/*.toml",
"fixtures",
"vendor",
"plugins/*/web",
"plugins/official/*/web",
"crates/**/tests/fixtures"
+1
Переглянути файл
@@ -16,6 +16,7 @@
"src/editor/core/cm/angular/parser*.ts",
"src/editor/core/cm/astro/parser*.ts",
"fixtures",
"vendor",
"plugins",
"test-results",
"playwright-report",
+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.
Створено
+280 -411
File diff suppressed because it is too large. Load diff
+8 -2
Переглянути файл
@@ -2,10 +2,10 @@
resolver = "3"
members = ["crates/*", "src-tauri"]
# Plugins and the guest SDK build for wasm32-wasip2 in their own workspaces.
exclude = ["sdk", "plugins"]
exclude = ["sdk", "plugins", "vendor"]
[workspace.package]
version = "0.1.56"
version = "0.1.57"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
@@ -101,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"
@@ -160,3 +161,8 @@ opt-level = 3
panic = "unwind"
# Keep the symbol table: crash reports and logged backtraces name functions.
strip = "debuginfo"
# tauri-plugin-mcp-bridge 0.13.2 (debug-only E2E bridge) pins `tauri ~2.12`; this copy only widens
# that requirement to 2.13. Drop it once a release supporting tauri 2.13 is published.
[patch.crates-io]
tauri-plugin-mcp-bridge = { path = "vendor/tauri-plugin-mcp-bridge" }
+1 -1
Переглянути файл
@@ -74,7 +74,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
- [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">
<img src=".github/assets/wechat-group-5.png" alt="WeChat group QR code" width="200">
- Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup).
+1 -1
Переглянути файл
@@ -74,7 +74,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
- [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">
<img src=".github/assets/wechat-group-5.png" alt="WeChat grubu QR kodu" width="200">
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
+1 -1
Переглянути файл
@@ -72,7 +72,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
- [Discord](https://discord.gg/AsZqMgxZm):提问、反馈和版本发布消息。
- 微信群,扫码加入:
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
<img src=".github/assets/wechat-group-5.png" alt="微信群二维码" width="200">
- 参与贡献:参见 [CONTRIBUTING.md](CONTRIBUTING.md) 和[贡献者文档](https://openidea.sh/zh/contribute/setup)。
+28
Переглянути файл
@@ -288,6 +288,34 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## tree-sitter-fsharp queries
`crates/ide-language/queries/fsharp_signature/highlights.scm` is the signature grammar's
`highlights.scm` from [tree-sitter-fsharp](https://github.com/ionide/tree-sitter-fsharp)
0.3.13 (the grammar itself is a Cargo dependency).
### MIT License (tree-sitter-fsharp)
Copyright (c) 2023 Nikolaj Sidorenco
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## nvim-treesitter queries
`crates/ide-syntax/queries/<grammar>/locals.scm` are derived from the `locals.scm`
+1
Переглянути файл
@@ -105,6 +105,7 @@ fn manager(dir: &Path, agent: Arc<FakeV2Agent>) -> AgentManager {
store_dir: dir.join("store"),
worktrees_dir: dir.join("worktrees"),
models_file: dir.join("models.json"),
cli_dir: dir.join("agent-cli"),
custom_agents_dir: None,
home_dir: None,
env_secrets: None,
+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!({
+35
Переглянути файл
@@ -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
@@ -155,6 +189,7 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
store_dir: tmp.path().join("store"),
worktrees_dir: tmp.path().join("worktrees"),
models_file: tmp.path().join("models.json"),
cli_dir: tmp.path().join("agent-cli"),
custom_agents_dir: None,
home_dir: None,
env_secrets: None,
+67 -2
Переглянути файл
@@ -50,6 +50,10 @@ fn default_true() -> bool {
true
}
fn is_false(b: &bool) -> bool {
!*b
}
/// Whether each scheduled firing starts a fresh task or continues the previous task's conversation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -242,6 +246,10 @@ pub struct AgentAutomation {
#[specta(optional)]
pub memory_overrides: Option<AgentMemoryOverrides>,
pub trigger: AutomationTrigger,
/// When `true`, runs of this automation may call the `schedule_next_run` MCP tool to set
/// their own next firing time and prompt without interactive human confirmation.
#[serde(default, skip_serializing_if = "is_false")]
pub allow_agent_schedule: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub misfire_policy: Option<AutomationMisfirePolicy>,
@@ -254,6 +262,16 @@ pub struct AgentAutomation {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub next_run_ms: Option<f64>,
/// Pending one-time firing timestamp scheduled by the agent via `schedule_next_run`.
/// Consumed on the next firing without altering [`Self::trigger`].
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub next_run_override_ms: Option<f64>,
/// Pending one-time prompt instructions scheduled by the agent via `schedule_next_run`.
/// Consumed on the next firing without altering [`Self::prompt`].
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub next_prompt_override: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub paused_reason: Option<String>,
@@ -292,6 +310,13 @@ pub struct SaveAutomationInput {
pub memory_overrides: Option<AgentMemoryOverrides>,
pub trigger: AutomationTrigger,
#[serde(default)]
pub allow_agent_schedule: bool,
/// When `true` on an update, explicitly discards any pending agent-scheduled
/// `next_run_override_ms` / `next_prompt_override` and reverts to the regular `trigger`.
#[serde(default)]
#[specta(optional)]
pub clear_override: bool,
#[serde(default)]
#[specta(optional)]
pub misfire_policy: Option<AutomationMisfirePolicy>,
#[serde(default)]
@@ -739,6 +764,34 @@ pub fn preview_trigger_runs(trigger: &AutomationTrigger, from_ms: f64, count: us
}
}
/// Formats an epoch-millisecond timestamp in `trigger`'s timezone (or system local timezone for
/// `OneShot` / `Manual`) as an ISO-8601 zoned string.
pub fn format_trigger_timestamp(trigger: &AutomationTrigger, ms: f64) -> Option<String> {
if !ms.is_finite() {
return None;
}
let ts = jiff::Timestamp::from_millisecond(ms.round() as i64).ok()?;
let tz_name = match trigger {
AutomationTrigger::Hourly { time_zone, .. }
| AutomationTrigger::Daily { time_zone, .. }
| AutomationTrigger::Weekdays { time_zone, .. }
| AutomationTrigger::Weekly { time_zone, .. }
| AutomationTrigger::Cron { time_zone, .. } => time_zone.as_str(),
AutomationTrigger::Manual | AutomationTrigger::OneShot { .. } => "local",
};
let tz = resolve_time_zone(tz_name).ok()?;
Some(ts.to_zoned(tz).to_string())
}
/// Parses an ISO-8601 / RFC-3339 timestamp string into epoch milliseconds.
pub fn parse_iso_timestamp_ms(raw: &str) -> IdeResult<f64> {
let ts = raw
.trim()
.parse::<jiff::Timestamp>()
.map_err(|e| IdeError::invalid(format!("invalid ISO-8601 timestamp '{}': {e}", raw.trim())))?;
Ok(ts.as_millisecond() as f64)
}
/// Parses an interval string such as `"10m"`, `"90s"`, `"2h"`, `"1d"`, `"15 minutes"` into seconds.
pub fn parse_interval_secs(raw: &str, min_secs: u64, max_secs: u64) -> IdeResult<u64> {
let trimmed = raw.trim().to_ascii_lowercase();
@@ -783,6 +836,8 @@ pub struct PortableAutomation {
#[specta(optional)]
pub description: Option<String>,
pub trigger: AutomationTrigger,
#[serde(default, skip_serializing_if = "is_false")]
pub allow_agent_schedule: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub disable_after_ms: Option<f64>,
@@ -813,7 +868,7 @@ pub fn slugify_id(name: &str) -> String {
/// Exports an [`AgentAutomation`] into the portable `.automation.md` format (YAML frontmatter + prompt body).
pub fn export_markdown(automation: &AgentAutomation) -> IdeResult<String> {
let has_disable = automation.disable_after_ms.is_some() || automation.max_runs.is_some();
let version = if has_disable { 2 } else { 1 };
let version = if has_disable || automation.allow_agent_schedule { 2 } else { 1 };
let slug = slugify_id(&automation.name);
let id = if slug.is_empty() { automation.id.clone() } else { slug };
let mut out = String::new();
@@ -821,6 +876,9 @@ pub fn export_markdown(automation: &AgentAutomation) -> IdeResult<String> {
out.push_str(&format!("version: {version}\n"));
out.push_str(&format!("id: {}\n", yaml_scalar(&id)));
out.push_str(&format!("name: {}\n", yaml_scalar(&automation.name)));
if automation.allow_agent_schedule {
out.push_str("allowAgentSchedule: true\n");
}
out.push_str("schedule:\n");
match &automation.trigger {
AutomationTrigger::Manual => {
@@ -883,6 +941,7 @@ pub fn parse_markdown(markdown: &str) -> IdeResult<PortableAutomation> {
let mut id: Option<String> = None;
let mut name: Option<String> = None;
let mut description: Option<String> = None;
let mut allow_agent_schedule = false;
let mut sched_kind = String::from("manual");
let mut sched_expr: Option<String> = None;
let mut sched_run_at: Option<String> = None;
@@ -921,6 +980,7 @@ pub fn parse_markdown(markdown: &str) -> IdeResult<PortableAutomation> {
"id" => id = Some(val),
"name" => name = Some(val),
"description" => description = Some(val),
"allowAgentSchedule" => allow_agent_schedule = val.eq_ignore_ascii_case("true"),
_ => {}
}
}
@@ -989,7 +1049,7 @@ pub fn parse_markdown(markdown: &str) -> IdeResult<PortableAutomation> {
other => return Err(IdeError::invalid(format!("unsupported schedule kind '{other}'"))),
};
Ok(PortableAutomation { id, name, description, trigger, disable_after_ms, max_runs, prompt })
Ok(PortableAutomation { id, name, description, trigger, allow_agent_schedule, disable_after_ms, max_runs, prompt })
}
fn yaml_scalar(s: &str) -> String {
@@ -1182,10 +1242,13 @@ mod tests {
expression: "30 10 * * FRI".into(),
time_zone: "America/Los_Angeles".into(),
},
allow_agent_schedule: true,
misfire_policy: None,
disable_after_ms: Some(ts_ms("2027-03-01T00:00:00Z")),
max_runs: Some(25),
next_run_ms: None,
next_run_override_ms: None,
next_prompt_override: None,
paused_reason: None,
run_count: 0,
unread_runs: 0,
@@ -1194,9 +1257,11 @@ mod tests {
};
let md = export_markdown(&auto).unwrap();
assert!(md.contains("version: 2\n"));
assert!(md.contains("allowAgentSchedule: true\n"));
let parsed = parse_markdown(&md).unwrap();
assert_eq!(parsed.id, "weekly-review-core-rpc");
assert_eq!(parsed.name, "Weekly Review: Core & RPC");
assert!(parsed.allow_agent_schedule);
assert_eq!(parsed.disable_after_ms, Some(ts_ms("2027-03-01T00:00:00Z")));
assert_eq!(parsed.max_runs, Some(25));
assert_eq!(parsed.prompt, "Inspect open PRs and run /code-review.");
+8 -4
Переглянути файл
@@ -468,7 +468,9 @@ impl AgentCatalogs {
model: Option<String>,
result: Result<Discovered, String>,
) {
let current = provider::load(shared.paths.custom_agents_dir.as_deref(), shared.env_secrets())
let current = shared
.paths
.provider_specs()
.into_iter()
.find(|spec| spec.id == key.2)
.map(|spec| LaunchContext::new(spec, &shared.paths.project_root));
@@ -622,8 +624,7 @@ impl crate::AgentManager {
/// Return cached choices immediately and schedule discovery when eligible.
pub fn refresh_models(&self, provider: &str, force: bool, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
// Settings and environment secrets can change while this window is open.
*self.shared.providers.write() =
provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
*self.shared.providers.write() = self.shared.paths.provider_specs();
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force, model).0)
}
@@ -631,7 +632,10 @@ impl crate::AgentManager {
/// Probes Copilot's model catalog for a staged `account` selection (`""` = Copilot CLI
/// default) without mutating `models.json` or broadcasting to active sessions before Apply.
pub async fn preview_copilot_models(&self, account: &str, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
let mut spec = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets())
let mut spec = self
.shared
.paths
.provider_specs()
.into_iter()
.find(|p| p.id == "copilot")
.ok_or_else(|| IdeError::not_found("unknown agent 'copilot'"))?;
+1
Переглянути файл
@@ -157,6 +157,7 @@ fn make_manager_at(root: &Path, models_file: &Path, catalogs: Arc<AgentCatalogs>
store_dir: root.join("store"),
worktrees_dir: root.join("worktrees"),
models_file: models_file.to_path_buf(),
cli_dir: root.join("agent-cli"),
catalogs,
custom_agents_dir: Some(root.join("agents")),
home_dir: Some(root.to_path_buf()),
+148 -52
Переглянути файл
@@ -1,4 +1,4 @@
//! Checks and updates only the global npm installation selected by the agent launcher.
//! Installs built-in CLIs into IDE-owned npm prefixes and updates the npm installation selected by the launcher.
use crate::{AgentManager, AgentSource, provider};
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use serde::{Deserialize, Serialize};
@@ -29,6 +29,14 @@ pub enum AgentCliUpdateResult {
Error { code: String },
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "status", rename_all = "camelCase")]
pub enum AgentCliInstallResult {
Installed,
NodeRequired,
Error { code: String },
}
pub(crate) fn package(id: &str) -> Option<&'static str> {
Some(match id {
"claude" => "@anthropic-ai/claude-code",
@@ -45,6 +53,64 @@ pub(crate) fn package(id: &str) -> Option<&'static str> {
}
impl AgentManager {
/// Installs the built-in CLI into an npm prefix owned by the IDE on this host.
pub fn cli_install(
&self,
id: &str,
approved_command: &str,
cancel: &CancellationToken,
) -> IdeResult<AgentCliInstallResult> {
use AgentCliInstallResult::*;
let spec = self.shared.paths.provider_specs().into_iter().find(|spec| spec.id == id);
let (Some(spec), Some(pkg), Some(builtin)) = (spec, package(id), provider::builtin_spec(id)) else {
return Err(IdeError::invalid("This agent has no built-in CLI installer"));
};
if spec.source != AgentSource::Builtin || spec.command != builtin.command {
return Err(IdeError::invalid("This agent has no built-in CLI installer"));
}
let prefix = self.shared.paths.cli_dir.join(id);
if install_command(&prefix, pkg).as_deref() != Some(approved_command) {
return Err(IdeError::invalid("The CLI install command changed. Reopen Agent Setup and try again."));
}
if provider::installed_with_env(spec.executable(), &spec.env) {
return Ok(Installed);
}
let search = ide_core::tool_path::search_path();
let Some(npm) = ide_core::process::find_executable("npm", &search)
.filter(|_| ide_core::process::find_executable("node", &search).is_some())
else {
return Ok(NodeRequired);
};
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let _lock = lock_prefix(&prefix)?;
if managed_cli(&prefix, pkg, &builtin.command).is_some() {
return Ok(Installed);
}
let installation = Installation::at(&prefix, pkg, &builtin.command);
// Only publish a CLI after npm has finished and its launcher has been verified.
let marker = prefix.join(INSTALLED_MARKER);
if marker.exists() {
fs::remove_file(&marker)?;
}
let spec = format!("{pkg}@latest");
match run_npm(&npm, &install_args(prefix.to_str().unwrap(), &spec), cancel) {
Err(error) if error.kind == ErrorKind::Unavailable => return Ok(Error { code: error.message }),
result => result?,
};
if installation.version(&installation.link, pkg, &builtin.command)?.is_none()
|| !provider::installed_with_env(&installation.link.to_string_lossy(), &[])
{
return Err(IdeError::invalid("npm installation verification failed"));
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
fs::write(marker, [])?;
Ok(Installed)
}
pub fn cli_update(
&self,
id: &str,
@@ -61,14 +127,50 @@ impl AgentManager {
let Some(npm) = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path()) else {
return Ok(AgentCliUpdateResult::Unmanaged);
};
let prefix = self.shared.paths.cli_dir.join(id);
let managed = spec.managed_cli.is_some().then_some(prefix.as_path());
let _lock = if offer.is_some() { managed.map(lock_prefix).transpose()? } else { None };
let program = spec.resolve_for_launch(&self.shared.paths.project_root).command;
match maintain(&npm, Path::new(&program), &builtin.command, pkg, offer, cancel) {
match maintain(&npm, Path::new(&program), &builtin.command, pkg, managed, offer, cancel) {
Err(e) if e.kind == ErrorKind::Unavailable => Ok(AgentCliUpdateResult::Error { code: e.message }),
result => result,
}
}
}
const INSTALLED_MARKER: &str = ".openidea-installed";
fn lock_prefix(prefix: &Path) -> IdeResult<fs::File> {
fs::create_dir_all(prefix)?;
let lock = fs::OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.open(prefix.join(".openidea-install.lock"))?;
lock.try_lock().map_err(|error| match error {
fs::TryLockError::WouldBlock => IdeError::new(ErrorKind::AlreadyExists, "CLI installation is in progress"),
fs::TryLockError::Error(error) => error.into(),
})?;
Ok(lock)
}
pub(crate) fn managed_cli(prefix: &Path, pkg: &str, bin: &str) -> Option<PathBuf> {
let link = Installation::at(prefix, pkg, bin).link;
(prefix.join(INSTALLED_MARKER).is_file() && provider::installed_with_env(&link.to_string_lossy(), &[]))
.then_some(link)
}
pub(crate) fn install_command(prefix: &Path, pkg: &str) -> Option<String> {
let spec = format!("{pkg}@latest");
let args = install_args(prefix.to_str()?, &spec);
Some(provider::render_shell_command(Path::new("npm"), args, cfg!(windows)))
}
fn install_args<'a>(prefix: &'a str, spec: &'a str) -> [&'a str; 7] {
["install", "-g", "--prefix", prefix, "--no-audit", "--no-fund", spec]
}
struct Installation {
modules: PathBuf,
folder: PathBuf,
@@ -151,47 +253,19 @@ fn maintain(
program: &Path,
bin: &str,
pkg: &str,
managed: Option<&Path>,
approved: Option<&AgentCliOffer>,
cancel: &CancellationToken,
) -> IdeResult<AgentCliUpdateResult> {
use AgentCliUpdateResult::*;
let run = |args: &[&str]| {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut cmd = Command::new(npm);
cmd.args(args)
.current_dir(npm.parent().unwrap())
.env("NPM_CONFIG_UPDATE_NOTIFIER", "false")
.env("NPM_CONFIG_LOGLEVEL", "error");
ide_tools::run_streamed(cmd, cancel, &|_| {}).map_err(|e| {
if e.kind == ErrorKind::Cancelled {
return e;
}
// npm diagnostics can contain private registry URLs; expose only known codes.
let code = e
.message
.split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
.find(|w| {
matches!(
*w,
"EACCES"
| "EPERM"
| "EROFS"
| "ENOTFOUND"
| "EAI_AGAIN"
| "ETIMEDOUT"
| "E404"
| "E401"
| "E403"
)
})
.unwrap_or("npm");
IdeError::unavailable(code)
})
let run = |args: &[&str]| run_npm(npm, args, cancel);
let output;
let prefix = if let Some(prefix) = managed {
prefix
} else {
output = run(&["prefix", "-g"])?;
Path::new(output.trim_end())
};
let output = run(&["prefix", "-g"])?;
let prefix = Path::new(output.trim_end());
if !prefix.is_absolute() {
return Err(IdeError::invalid("Invalid npm global prefix"));
}
@@ -212,21 +286,42 @@ fn maintain(
if approved != Some(&offer) {
return Ok(Available(offer));
}
run(&[
"install",
"-g",
"--prefix",
prefix.to_str().unwrap(),
"--no-audit",
"--no-fund",
&format!("{pkg}@{}", offer.latest),
])?;
run(&install_args(prefix.to_str().unwrap(), &format!("{pkg}@{}", offer.latest)))?;
if installation.version(program, pkg, bin)?.as_ref() != Some(&offer.latest) {
return Err(IdeError::invalid("npm installation verification failed"));
}
Ok(Updated { current: offer.latest })
}
fn run_npm(npm: &Path, args: &[&str], cancel: &CancellationToken) -> IdeResult<String> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut cmd = Command::new(npm);
cmd.args(args)
.current_dir(npm.parent().unwrap())
.env("PATH", ide_core::tool_path::search_path())
.env("NPM_CONFIG_UPDATE_NOTIFIER", "false")
.env("NPM_CONFIG_LOGLEVEL", "error");
ide_tools::run_streamed(cmd, cancel, &|_| {}).map_err(|e| {
if e.kind == ErrorKind::Cancelled {
return e;
}
// npm diagnostics can contain private registry URLs; expose only known codes.
let code = e
.message
.split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
.find(|w| {
matches!(
*w,
"EACCES" | "EPERM" | "EROFS" | "ENOTFOUND" | "EAI_AGAIN" | "ETIMEDOUT" | "E404" | "E401" | "E403"
)
})
.unwrap_or("npm");
IdeError::unavailable(code)
})
}
#[cfg(test)]
mod tests {
use super::*;
@@ -314,8 +409,9 @@ esac"#;
let f = Fixture::new();
let npm = f.npm(NPM);
let cancel = CancellationToken::new();
let run =
|offer: Option<&AgentCliOffer>| maintain(&npm, &f.install.link, "claude", PKG, offer, &cancel).unwrap();
let run = |offer: Option<&AgentCliOffer>| {
maintain(&npm, &f.install.link, "claude", PKG, None, offer, &cancel).unwrap()
};
let latest = f.root.path().join("latest");
fs::write(&latest, r#""2.1.12""#).unwrap();
let Available(offer) = run(None) else { panic!("expected an offer") };
@@ -351,7 +447,7 @@ esac"#;
let npm = f.npm(NPM);
fs::write(f.root.path().join("latest"), r#""2.1.12""#).unwrap();
let run = |offer: Option<&AgentCliOffer>| {
maintain(&npm, &f.install.link, "claude", PKG, offer, &CancellationToken::new()).unwrap()
maintain(&npm, &f.install.link, "claude", PKG, None, offer, &CancellationToken::new()).unwrap()
};
let AgentCliUpdateResult::Available(offer) = run(None) else { panic!("expected an offer") };
fs::set_permissions(&f.install.folder, fs::Permissions::from_mode(0o555)).unwrap();
@@ -377,13 +473,13 @@ esac"#,
);
let cancel = CancellationToken::new();
let AgentCliUpdateResult::Available(offer) =
maintain(&npm, &f.install.link, "claude", PKG, None, &cancel).unwrap()
maintain(&npm, &f.install.link, "claude", PKG, None, None, &cancel).unwrap()
else {
panic!("expected an offer")
};
let started = f.root.path().join("started");
std::thread::scope(|s| {
let op = s.spawn(|| maintain(&npm, &f.install.link, "claude", PKG, Some(&offer), &cancel));
let op = s.spawn(|| maintain(&npm, &f.install.link, "claude", PKG, None, Some(&offer), &cancel));
let deadline = Instant::now() + Duration::from_secs(5);
while !started.exists() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
+12 -4
Переглянути файл
@@ -146,6 +146,10 @@ pub(crate) fn is_approval_option(opt: &AgentConfigOption) -> bool {
opt.id == CURSOR_APPROVAL || matches!(opt.category.as_deref(), Some("mode" | "permissions" | "approval"))
}
pub(crate) fn is_approval_option_id(id: &str) -> bool {
id == CURSOR_APPROVAL || matches!(id, "mode" | "allow_all" | "permissions" | "approval" | "approval_policy")
}
fn wanted_val(wanted: &[crate::model::AgentConfigChoice], id: &str) -> Option<String> {
wanted.iter().find(|c| c.id == id).map(|c| c.value.clone())
}
@@ -425,15 +429,19 @@ pub(crate) fn is_fast_option(id: &str) -> bool {
id == "fast"
}
/// Whether a raw config option id belongs to the selected model rather than the provider.
pub(crate) fn is_per_model_option_id(id: &str) -> bool {
matches!(id, "effort" | "reasoning_effort" | "thinking" | "reasoning" | "service_tier")
|| is_fast_option(id)
|| is_context_option(id)
}
/// Whether an option's available values and default belong to the selected model
/// (`thought_level`, `context_tier`, and `model_config` options like `context`, `fast` and `service_tier`)
/// rather than the provider as a whole.
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|| is_fast_option(&o.id)
|| is_context_option(&o.id)
|| o.id == "service_tier"
|| is_per_model_option_id(&o.id)
}
/// A `configOptions` array; only select options are kept (the UI shows them as dropdowns).
+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
+38
Переглянути файл
@@ -70,6 +70,8 @@ fn to_mcp_server(scope: McpScope, name: &str, cfg: &AgentMcpServer) -> McpServer
unapproved: false,
plugin_id: None,
plugin_name: None,
registry_name: cfg.registry_name.clone(),
registry_url: cfg.registry_url.clone(),
}
}
@@ -254,6 +256,28 @@ pub fn apply_save(
if input.scope == McpScope::Workspace && !has_workspace {
return Err("Open a project to configure workspace MCP servers".into());
}
let existing_meta = input.id.as_deref().and_then(parse_server_id).and_then(|(prev_scope, prev_name)| {
let map = match prev_scope {
McpScope::User => &*user,
McpScope::Workspace => &*workspace,
};
map.get(prev_name).map(|prev| (prev.registry_name.clone(), prev.registry_url.clone()))
});
let registry_name = input
.registry_name
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_owned)
.or_else(|| existing_meta.as_ref().and_then(|(rn, _)| rn.clone()));
let registry_url = input
.registry_url
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_owned)
.or_else(|| existing_meta.and_then(|(_, ru)| ru));
let cfg = match input.transport {
McpTransport::Stdio => {
let cmd = input.command.as_deref().map(str::trim).unwrap_or_default();
@@ -277,6 +301,8 @@ pub fn apply_save(
url: None,
headers: BTreeMap::new(),
agents: normalize_agents_list(input.agents),
registry_name,
registry_url,
}
}
McpTransport::Http | McpTransport::Sse => {
@@ -301,6 +327,8 @@ pub fn apply_save(
url: Some(url.to_owned()),
headers,
agents: normalize_agents_list(input.agents),
registry_name,
registry_url,
}
}
};
@@ -1018,6 +1046,8 @@ fn parse_one_server_def(obj: &serde_json::Map<String, Value>) -> Option<AgentMcp
url,
headers: parse_key_values_map(obj.get("headers")),
agents,
registry_name: None,
registry_url: None,
})
}
@@ -1272,6 +1302,8 @@ mod tests {
unapproved: false,
plugin_id: None,
plugin_name: None,
registry_name: None,
registry_url: None,
}
}
@@ -1327,6 +1359,8 @@ mod tests {
url: None,
headers: Vec::new(),
agents: Vec::new(),
registry_name: None,
registry_url: None,
},
)
.unwrap();
@@ -1347,6 +1381,8 @@ mod tests {
url: None,
headers: Vec::new(),
agents: Vec::new(),
registry_name: None,
registry_url: None,
},
)
.unwrap();
@@ -1367,6 +1403,8 @@ mod tests {
url: Some("https://example.com/mcp".into()),
headers: vec![McpKeyValue { name: "Authorization".into(), value: "Bearer secret".into() }],
agents: vec!["claude".into()],
registry_name: None,
registry_url: None,
},
)
.unwrap();
File diff suppressed because it is too large. Load diff
+38
Переглянути файл
@@ -71,6 +71,7 @@ pub enum InterruptionReason {
BackendStop,
UnexpectedExit,
NetworkTimeout,
CursorCapacity,
}
impl From<AgentShutdownReason> for InterruptionReason {
@@ -431,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 {
@@ -638,6 +642,9 @@ pub enum AgentEntry {
/// Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn.
#[serde(default)]
recovery: Option<InterruptionReason>,
/// One-based automatic retry number for this continuation.
#[serde(default)]
retry_attempt: Option<u32>,
},
Agent {
text: String,
@@ -753,6 +760,9 @@ pub struct AgentProvider {
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
/// Whether the command was found (on `PATH`).
pub installed: bool,
/// Command the project host can run to install this missing built-in CLI.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cli_install_command: Option<String>,
/// Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal.
#[serde(default)]
pub can_sign_in: bool,
@@ -1048,6 +1058,14 @@ pub struct McpServer {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_name: Option<String>,
/// Canonical MCP registry server identifier when installed from an MCP registry.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub registry_name: Option<String>,
/// Normalized MCP registry base URL when installed from an MCP registry.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub registry_url: Option<String>,
}
/// Payload for creating or updating a user or workspace MCP server.
@@ -1074,6 +1092,14 @@ pub struct McpServerInput {
/// Agent provider ids this server is enabled for; empty means enabled for all agents.
#[serde(default)]
pub agents: Vec<String>,
/// Canonical MCP registry server identifier when installed from an MCP registry.
#[serde(default)]
#[specta(optional)]
pub registry_name: Option<String>,
/// Normalized MCP registry base URL when installed from an MCP registry.
#[serde(default)]
#[specta(optional)]
pub registry_url: Option<String>,
}
fn default_true() -> bool {
@@ -1663,6 +1689,12 @@ pub struct AgentMarketplaceCandidate {
#[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 icon_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub icon_dark_url: Option<String>,
/// Source spec to pass to preview (`"owner/repo[/subpath][@ref]"` or local directory path).
pub source_spec: String,
pub subpath: String,
@@ -1751,6 +1783,12 @@ pub struct AgentPluginPreview {
#[specta(optional)]
pub version: Option<String>,
pub description: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub icon_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub icon_dark_url: Option<String>,
pub formats: Vec<AgentPluginFormat>,
pub capabilities: AgentPluginCapabilities,
pub files: Vec<crate::skill_installer::RemoteSkillFile>,
+11
Переглянути файл
@@ -209,6 +209,17 @@ pub(super) fn cut(chain: &[&Value], turns: usize) -> Result<Option<String>, Stri
Ok(parent(first_dropped).map(str::to_owned))
}
/// Where to fork `chain` to keep only its first `turns` turns: the entry the last kept
/// turn ends with, as [`cut`] reports it. `None` when the chain has fewer turns.
pub(super) fn keep(chain: &[&Value], turns: usize) -> Option<Option<String>> {
let total = chain.iter().filter(|e| is_turn_start(e)).count();
if turns > total {
return None;
}
// A turn that runs now is in the chain up to where it got: it is dropped like any other.
cut(chain, total - turns).ok()
}
/// The newest title Claude Code gave the session.
pub(crate) fn title(entries: &[Value]) -> Option<String> {
entries
+38 -3
Переглянути файл
@@ -58,7 +58,7 @@ pub(crate) fn connect(
on_stderr: Box<dyn Fn(String) + Send + Sync>,
) -> std::io::Result<Peer> {
let config = Config {
program: super::newest_install(&spec.command),
program: super::newest_install(spec.executable()),
args: spec.args.clone(),
env: spec.env.clone(),
config_dir: cli::config_dir(&spec.env),
@@ -347,6 +347,24 @@ impl Shim {
}
/// The conversation a session started with `start` begins with.
/// `start` (a fork's) cut after the source's first `turns` turns; `None` when the
/// transcript can't be read or has fewer turns.
fn pin_fork(&self, cwd: &Path, start: &Start, id: &str, turns: usize) -> Option<Start> {
let chain = match self.base_chain(cwd, start) {
Ok(chain) => chain,
Err(e) => {
tracing::debug!("Claude Code fork {id}: can't read the source transcript: {e}");
return None;
}
};
let refs: Vec<&Value> = chain.iter().collect();
Some(match (start, history::keep(&refs, turns)?) {
(_, None) => Start::New { id: id.to_owned() },
(Start::Fork { from, .. }, Some(at)) => Start::Fork { from: from.clone(), id: id.to_owned(), at: Some(at) },
_ => return None,
})
}
fn base_chain(&self, cwd: &Path, start: &Start) -> Result<Vec<Value>, String> {
let (id, at) = match start {
Start::New { .. } => return Ok(Vec::new()),
@@ -509,11 +527,28 @@ impl Shim {
// from its transcript on disk when the task's first prompt starts it.
None => (Start::Fork { from: source_id.to_owned(), id: id.clone(), at: None }, Settings::default()),
};
// Pinned now: the source may go on (or be running a turn) before the fork starts.
let wanted = params.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64);
let mut kept = None;
let start = match wanted {
Some(turns) => match self.pin_fork(&cwd, &start, &id, turns as usize) {
Some(pinned) => {
kept = Some(turns);
pinned
}
None => start,
},
None => start,
};
self.save_pending(&id, Some(&start));
let session = self.add_session(&id, cwd, start, true, &params);
session.st.lock().settings = settings;
let options = session.st.lock().settings.options();
Ok(json!({ "sessionId": id, "configOptions": options }))
let mut reply = json!({ "sessionId": id, "configOptions": options });
if let Some(turns) = kept {
reply["_meta"] = json!({ "openidea": { "forkTurns": turns } });
}
Ok(reply)
}
"session/set_config_option" | "session/set_mode" => {
let session = self.session(&params)?;
@@ -947,7 +982,7 @@ impl Session {
fn steer(&self, prompt: Value) -> Result<(), String> {
let uuid = new_uuid(true);
let mut message = user_message(&prompt, &uuid, true);
message["priority"] = json!("now");
message["priority"] = json!("next");
let mut st = self.st.lock();
let proc = st.proc.clone().ok_or("Claude Code is not running")?;
let turn = st.turn.as_mut().filter(|t| !t.cancelled).ok_or("no turn is running")?;
+111 -2
Переглянути файл
@@ -212,6 +212,30 @@ async fn steer(h: &Harness) -> (Outcome, String) {
(vec![outcome("prompt", r), outcome("steer", steered)], s)
}
/// Stops the turn while a steered message waits for the running tool.
async fn steer_stop(h: &Harness) -> (Outcome, String) {
let s = h.new_session().await;
let prompt = h.prompt(&s, "Run the Bash command `sleep 5 && echo done`, then tell me its output in one line.");
let steer_and_stop = async {
tokio::time::sleep(Duration::from_millis(3000)).await;
let steered = h
.request(
"_openidea/steer",
json!({ "sessionId": s, "prompt": [{ "type": "text", "text": "Also end your answer with the word BANANA." }] }),
)
.await;
tokio::time::sleep(Duration::from_millis(500)).await;
h.client.notify("session/cancel", json!({ "sessionId": s })).unwrap();
steered
};
let (r, steered) = tokio::join!(prompt, steer_and_stop);
if h.recording {
// Long enough for the CLI to run the steered message, had it kept it.
tokio::time::sleep(Duration::from_secs(8)).await;
}
(vec![outcome("prompt", r), outcome("steer", steered)], s)
}
async fn subagent(h: &Harness) -> (Outcome, String) {
let s = h.new_session().await;
h.answer(&[Some("allow"), Some("allow")]);
@@ -253,6 +277,7 @@ const SCENARIOS: &[(&str, ScenarioFn)] = &[
("tool_approval", |h| Box::pin(tool_approval(h))),
("interrupt", |h| Box::pin(interrupt(h))),
("steer", |h| Box::pin(steer(h))),
("steer_stop", |h| Box::pin(steer_stop(h))),
("subagent", |h| Box::pin(subagent(h))),
("resume", |h| Box::pin(resume(h))),
];
@@ -620,10 +645,20 @@ async fn replay_steer() {
assert_eq!(r.stop("prompt"), "end_turn");
assert!(r.h.text(&r.session, "agent_message_chunk").contains("BANANA"));
let steer = r.sent(0).into_iter().filter(|m| m["type"] == "user").nth(1).unwrap();
assert_eq!(steer["priority"], "now");
assert_eq!(steer["priority"], "next");
assert!(steer["uuid"].as_str().unwrap().ends_with(history::STEER_MARK));
}
#[tokio::test(flavor = "multi_thread")]
async fn replay_steer_stop() {
let r = replay("steer_stop").await;
assert!(r.result("steer").is_ok(), "{:?}", r.result("steer"));
assert_eq!(r.stop("prompt"), "cancelled");
assert!(!r.h.text(&r.session, "agent_message_chunk").contains("BANANA"));
let interrupt = r.sent(0).into_iter().find(|m| m["request"]["subtype"] == "interrupt").unwrap();
assert_eq!(interrupt["request"]["cancel_queued"], true);
}
#[tokio::test(flavor = "multi_thread")]
async fn replay_subagent() {
let r = replay("subagent").await;
@@ -695,6 +730,73 @@ async fn fork_session_can_start_a_recorded_session_under_the_hosts_id() {
assert_eq!(saved, json!({ "fork": source, "id": target, "at": null }));
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_pins_the_cut_to_the_kept_turns() {
struct NoLaunch;
impl Cli for NoLaunch {
fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result<cli::CliIo> {
panic!("session/fork must not launch the CLI")
}
}
let config = tempfile::tempdir().unwrap();
let pending = tempfile::tempdir().unwrap();
let h = Harness::connect(
Arc::new(NoLaunch),
config.path().to_path_buf(),
pending.path().to_path_buf(),
std::env::temp_dir(),
Vec::new(),
)
.await;
let source = "11111111-1111-4111-8111-111111111111";
// Two finished turns and a third still running.
let dir = config.path().join("projects").join(history::escape(&h.cwd));
std::fs::create_dir_all(&dir).unwrap();
let mut parent = Value::Null;
let mut lines = String::new();
for (uuid, kind, text) in [
("u1", "user", "one"),
("a1", "assistant", "1"),
("u2", "user", "two"),
("a2", "assistant", "2"),
("u3", "user", "three"),
("a3", "assistant", "partial"),
] {
let entry = json!({"type": kind, "uuid": uuid, "parentUuid": parent,
"message": {"role": kind, "content": [{"type": "text", "text": text}]}});
lines += &format!("{entry}\n");
parent = json!(uuid);
}
std::fs::write(dir.join(format!("{source}.jsonl")), lines).unwrap();
let fork = |target: &'static str, turns: u64| {
h.request(
"session/fork",
json!({
"sessionId": source,
"cwd": h.cwd,
"mcpServers": [],
"_meta": { "openidea": { "forkSessionId": target, "forkTurns": turns } }
}),
)
};
let saved = |target: &str| -> Value {
serde_json::from_slice(&std::fs::read(pending.path().join(format!("{target}.json"))).unwrap()).unwrap()
};
let target = "22222222-2222-4222-8222-222222222222";
let reply = fork(target, 2).await.unwrap();
assert_eq!(reply.pointer("/_meta/openidea/forkTurns"), Some(&json!(2)));
assert_eq!(saved(target), json!({ "fork": source, "id": target, "at": "a2" }));
// More turns than the transcript holds: left to the host to settle.
let target = "33333333-3333-4333-8333-333333333333";
let reply = fork(target, 4).await.unwrap();
assert_eq!(reply.pointer("/_meta/openidea/forkTurns"), None);
assert_eq!(saved(target), json!({ "fork": source, "id": target, "at": null }));
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_rejects_a_requested_id_that_is_not_canonical() {
struct NoLaunch;
@@ -799,7 +901,14 @@ fn scrub(frame: &mut Value) -> bool {
json!([{ "name": "review", "description": "Review a pull request", "argumentHint": "" },
{ "name": "init", "description": "Write a CLAUDE.md", "argumentHint": "" }]),
);
for k in ["agents", "account", "available_output_styles", "user_output_styles_dir", "output_style"] {
for k in [
"agents",
"account",
"stored_login_organization_uuid",
"available_output_styles",
"user_output_styles_dir",
"output_style",
] {
o.remove(k);
}
}
+188 -3
Переглянути файл
@@ -34,6 +34,14 @@ const OUTPUT_EVERY: Duration = Duration::from_millis(200);
const EARLY_CANCEL: Duration = Duration::from_secs(1);
/// How long the client's connection outlives codex.
const EXIT_GRACE: Duration = Duration::from_millis(100);
/// How often running background terminals are listed again: codex announces neither a
/// terminal that outlives its turn nor its end.
#[cfg(not(test))]
const TERMINAL_POLL: Duration = Duration::from_secs(3);
#[cfg(test)]
const TERMINAL_POLL: Duration = Duration::from_millis(20);
/// How long closing the connection waits for codex to stop the background terminals.
const TERMINAL_CLEAN: Duration = Duration::from_secs(3);
/// What a thread's name is asked for with, after its first turn.
const NAME_PROMPT: &str = "Name this conversation for a list of tasks: a short title of at most six words, in the \
language the user writes in. Reply with the title only, without quotes or a closing period.";
@@ -66,7 +74,7 @@ pub(crate) fn connect(
on_stderr: Box<dyn Fn(String) + Send + Sync>,
) -> std::io::Result<Peer> {
attach(client, |events| {
let command = super::newest_install(&spec.command);
let command = super::newest_install(spec.executable());
Peer::spawn_framed(&command, &spec.args, cwd, &spec.env, events, on_stderr, Framing::Lines)
})
}
@@ -187,6 +195,10 @@ fn attach(
}
tokio::spawn(async move {
to_client.closed().await;
// Background terminals run in process groups of their own: stopping codex alone
// would leave them running with nothing left to report or stop them.
let threads: Vec<String> = shim.state.lock().threads.keys().cloned().collect();
shim.clean_terminals(&threads).await;
codex.kill();
});
Ok(ours)
@@ -248,6 +260,14 @@ struct Thread {
token_usage: Option<Value>,
/// The thread has a name.
named: bool,
/// Running background terminals of this session and its subagents, by task id:
/// `(thread, processId)`.
terminals: HashMap<String, (String, String)>,
/// The background tasks reported last.
shown_tasks: Vec<Value>,
/// The background terminals are being followed; `relist` asks for another listing.
watching: bool,
relist: bool,
/// A name is being asked for.
naming: bool,
}
@@ -416,6 +436,7 @@ impl CodexShim {
"session/prompt" => self.prompt(&params).await,
"_openidea/steer" => self.steer(&params).await,
"_openidea/rollback" => self.rollback(&params).await,
"_openidea/stop_task" => self.stop_task(&params).await,
"session/close" => self.close(&params).await,
_ => Err(error(codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))),
}
@@ -439,7 +460,7 @@ impl CodexShim {
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
"mcpCapabilities": { "http": false, "sse": false, "stdio": true },
"sessionCapabilities": { "fork": {}, "close": {}, "additionalDirectories": {} },
"_meta": { "openidea": { "rollback": true, "steer": true } },
"_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true } },
},
"agentInfo": { "name": "codex", "title": "Codex", "version": version },
"authMethods": [],
@@ -568,9 +589,26 @@ impl CodexShim {
}
let result = self.call("thread/fork", request).await?;
let (id, options) = self.open_thread(&result, &models, settings);
// Cut by what the fork holds: a turn the source runs now may or may not be in it.
let wanted = params.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64);
let held = result.pointer("/thread/turns").and_then(Value::as_array).map(|t| t.len() as u64);
let mut kept = None;
if let (Some(turns), Some(held)) = (wanted, held)
&& turns <= held
{
let dropped = held - turns;
if dropped > 0 {
self.rollback(&json!({ "sessionId": id, "turns": dropped })).await?;
}
kept = Some(turns);
}
self.apply_skill_roots(&id, params).await;
self.publish_skills(&id).await;
Ok(json!({ "sessionId": id, "configOptions": options }))
let mut reply = json!({ "sessionId": id, "configOptions": options });
if let Some(turns) = kept {
reply["_meta"] = json!({ "openidea": { "forkTurns": turns } });
}
Ok(reply)
}
async fn set_config(&self, params: &Value) -> Result<Value, ResponseError> {
@@ -915,6 +953,16 @@ impl CodexShim {
/// Stops following the session's thread (codex unloads it once nothing follows it).
async fn close(&self, params: &Value) -> Result<Value, ResponseError> {
let session = str_param(params, "sessionId")?;
let threads: Vec<String> = {
let state = self.state.lock();
state
.threads
.iter()
.filter(|(id, t)| *id == session || t.parent.as_deref() == Some(session))
.map(|(id, _)| id.clone())
.collect()
};
self.clean_terminals(&threads).await;
let known = self.state.lock().threads.remove(session).is_some();
if known && let Err(e) = self.call("thread/unsubscribe", json!({ "threadId": session })).await {
tracing::debug!("codex: unsubscribing from {session}: {}", e.message);
@@ -922,6 +970,129 @@ impl CodexShim {
Ok(json!({}))
}
/// Follows the background terminals of `session` and its subagents until none runs:
/// codex keeps them running after the turn that started them.
fn watch_terminals(self: &Arc<Self>, session: &str) {
{
let mut state = self.state.lock();
if state.gone {
return;
}
let Some(t) = state.threads.get_mut(session) else { return };
if t.watching {
t.relist = true;
return;
}
t.watching = true;
}
let (shim, session) = (self.clone(), session.to_owned());
self.runtime.spawn(async move {
loop {
let running = shim.list_terminals(&session).await;
let relist = {
let mut state = shim.state.lock();
let Some(t) = state.threads.get_mut(&session) else { return };
let relist = std::mem::take(&mut t.relist);
if !relist && !running {
t.watching = false;
return;
}
relist
};
if !relist {
tokio::time::sleep(TERMINAL_POLL).await;
}
}
});
}
/// Reports the running background terminals of `session` and its subagents as the
/// session's background tasks; whether any runs. A codex without the (experimental)
/// listing has none to report.
async fn list_terminals(&self, session: &str) -> bool {
let threads: Vec<String> = {
let state = self.state.lock();
let children = state.threads.iter().filter(|(_, t)| t.parent.as_deref() == Some(session));
std::iter::once(session.to_owned()).chain(children.map(|(id, _)| id.clone())).collect()
};
let mut terminals = HashMap::new();
let mut tasks = Vec::new();
for thread in &threads {
let listed = match self.terminals_of(thread).await {
Ok(listed) => listed,
Err(e) => {
tracing::debug!("codex: listing the background terminals of {thread}: {}", e.message);
continue;
}
};
for (process, description) in listed {
let id = if thread == session { process.clone() } else { format!("{thread}:{process}") };
tasks.push(json!({ "task_id": id, "task_type": "local_bash", "description": description }));
terminals.insert(id, (thread.clone(), process));
}
}
let running = !tasks.is_empty();
let changed = {
let mut state = self.state.lock();
let Some(t) = state.threads.get_mut(session) else { return false };
t.terminals = terminals;
let changed = t.shown_tasks != tasks;
if changed {
t.shown_tasks = tasks.clone();
}
changed
};
if changed {
self.emit(session, json!({ "sessionUpdate": crate::BACKGROUND_TASKS_UPDATE, "tasks": tasks }));
}
running
}
/// The running background terminals of `thread`, as `(processId, description)`.
async fn terminals_of(&self, thread: &str) -> Result<Vec<(String, String)>, ResponseError> {
let mut all = Vec::new();
let mut cursor = Value::Null;
let mut seen = HashSet::new();
loop {
let page =
self.call("thread/backgroundTerminals/list", json!({ "threadId": thread, "cursor": cursor })).await?;
all.extend(translate::background_terminals(&page));
match page.get("nextCursor").and_then(Value::as_str) {
Some(next) if !next.is_empty() && seen.insert(next.to_owned()) => cursor = json!(next),
_ => return Ok(all),
}
}
}
/// `_openidea/stop_task`: stops one background terminal.
async fn stop_task(&self, params: &Value) -> Result<Value, ResponseError> {
let session = str_param(params, "sessionId")?;
let task = str_param(params, "taskId")?;
let known = self.state.lock().threads.get(session).and_then(|t| t.terminals.get(task).cloned());
let (thread, process) = known.unwrap_or_else(|| (session.to_owned(), task.to_owned()));
self.call("thread/backgroundTerminals/terminate", json!({ "threadId": thread, "processId": process })).await?;
self.list_terminals(session).await;
Ok(json!({}))
}
/// Stops the background terminals of `threads`; a codex without the (experimental)
/// method has none.
async fn clean_terminals(&self, threads: &[String]) {
if threads.is_empty() || self.state.lock().gone {
return;
}
let clean = async {
for thread in threads {
if let Err(e) = self.call("thread/backgroundTerminals/clean", json!({ "threadId": thread })).await {
tracing::debug!("codex: stopping the background terminals of {thread}: {}", e.message);
}
}
};
if tokio::time::timeout(TERMINAL_CLEAN, clean).await.is_err() {
tracing::warn!("codex: stopping the background terminals timed out");
}
}
/// `session/cancel`: interrupts the session's turn, or the one about to start.
fn cancel(&self, session: &str) {
let mut state = self.state.lock();
@@ -1261,6 +1432,19 @@ impl CodexShim {
t.turn = None;
}
t.completed = Some(id.to_owned());
// A command still open when its turn completed goes on in the background (a
// background terminal): its call returned, so it didn't fail with the turn. Its
// own completion reports how it ended. Sent before the prompt's answer settles the
// turn.
if completed {
let commands = t.items.values().filter(|i| i["type"] == "commandExecution");
for id in commands.filter_map(|i| i["id"].as_str()) {
self.emit(
thread,
json!({ "sessionUpdate": "tool_call_update", "toolCallId": id, "status": "completed" }),
);
}
}
t.items.clear();
t.last_chunk = None;
let error = t.error.take();
@@ -1275,6 +1459,7 @@ impl CodexShim {
t.naming |= name;
(t.parent.clone(), (answer, error), name)
};
self.watch_terminals(parent.as_deref().unwrap_or(thread));
if name {
let (shim, thread, turn) = (self.clone(), thread.to_owned(), id.to_owned());
self.runtime.spawn(async move { shim.name_thread(&thread, &turn).await });
+1
Переглянути файл
@@ -66,6 +66,7 @@ fn manager(dir: &Path, runtime: Arc<Runtime>) -> AgentManager {
store_dir: dir.join("store"),
worktrees_dir: dir.join("worktrees"),
models_file: dir.join("models.json"),
cli_dir: dir.join("agent-cli"),
custom_agents_dir: Some(agents),
home_dir: Some(dir.into()),
env_secrets: None,
+240 -4
Переглянути файл
@@ -125,6 +125,7 @@ for line in sys.stdin:
name: "Codex".into(),
driver: crate::provider::Driver::Codex,
command: script.to_string_lossy().into_owned(),
managed_cli: None,
args: Vec::new(),
additional_args_len: 0,
env: Vec::new(),
@@ -1019,10 +1020,12 @@ async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
.unwrap()
.unwrap_or_else(|| panic!("the shim closed before {frame}"));
let actual: Value = serde_json::from_str(&line).unwrap();
// Older recordings predate config inspection, skill discovery and thread naming; play an
// unsupported server.
// Older recordings predate config inspection, skill discovery, thread naming and
// background terminals; play an unsupported server.
let method = actual["method"].as_str().unwrap_or_default();
if matches!(method, "config/read" | "skills/list" | "thread/sample") && frame["method"] != method {
let unrecorded = matches!(method, "config/read" | "skills/list" | "thread/sample")
|| method.starts_with("thread/backgroundTerminals/");
if unrecorded && frame["method"] != method {
let reply = json!({ "id": actual["id"], "error": { "code": -32601, "message": "unsupported" } });
write.write_all(format!("{reply}\n").as_bytes()).await.unwrap();
continue;
@@ -1162,6 +1165,60 @@ impl Handler for TrustServer {
}
}
/// Forks a thread holding two finished turns and one cut off by the fork.
#[derive(Default)]
struct ForkServer {
calls: Mutex<Vec<(String, Value)>>,
}
impl Handler for ForkServer {
fn on_notification(&self, _: &str, _: Value) {}
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
self.calls.lock().push((method.to_owned(), params));
match method {
"initialize" | "thread/rollback" => Ok(json!({})),
"model/list" | "skills/list" => Ok(json!({"data": []})),
"config/read" => Ok(json!({"layers": []})),
"thread/fork" => Ok(json!({"thread": {"id": "copy", "turns": [
{"id": "t1", "status": "completed"},
{"id": "t2", "status": "completed"},
{"id": "t3", "status": "interrupted"},
]}})),
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
}
}
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_keeps_the_asked_turns_of_what_the_fork_holds() {
for (turns, rolled_back, kept) in [(Some(2), Some(1), Some(2)), (Some(3), None, Some(3)), (Some(4), None, None)] {
let server = Arc::new(ForkServer::default());
let (ours, theirs) = tokio::io::duplex(1 << 16);
let (read, write) = tokio::io::split(theirs);
let native = Peer::connect_framed(read, write, server.clone(), Framing::Lines);
let acp = attach(Arc::new(Client::default()), |events| {
let (read, write) = tokio::io::split(ours);
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
})
.unwrap();
request(&acp, "initialize", json!({})).await.unwrap();
let params = json!({"cwd": "/tmp", "sessionId": "source", "mcpServers": [],
"_meta": {"openidea": {"forkTurns": turns}}});
let reply = request(&acp, "session/fork", params).await.unwrap();
assert_eq!(reply["sessionId"], "copy");
assert_eq!(reply.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64), kept);
let rollbacks: Vec<Value> =
server.calls.lock().iter().filter(|(m, _)| m == "thread/rollback").map(|(_, p)| p.clone()).collect();
assert_eq!(
rollbacks,
rolled_back.map(|n| json!({"threadId": "copy", "numTurns": n})).into_iter().collect::<Vec<_>>()
);
acp.kill();
native.kill();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn project_trust_is_confirmed_before_new_resumed_and_forked_sessions() {
for method in ["session/new", "session/load", "session/fork"] {
@@ -1243,7 +1300,10 @@ async fn auth_failure_names_auth() {
let (results, _client, frames, _) = replay(Scenario::AuthFailure).await;
let init = result(&results, "initialize").as_ref().unwrap();
assert_eq!(init["agentCapabilities"]["loadSession"], true);
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"], json!({"rollback": true, "steer": true}));
assert_eq!(
init["agentCapabilities"]["_meta"]["openidea"],
json!({"rollback": true, "steer": true, "backgroundTasks": true})
);
assert!(init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object());
let new = result(&results, "new").as_ref().unwrap();
let categories: Vec<&str> =
@@ -2215,3 +2275,179 @@ async fn an_ephemeral_session_starts_an_ephemeral_thread() {
native.kill();
}
}
/// A codex whose background terminals listings come from `pages` (an empty list after
/// them); `None` answers like a codex without the method.
struct TerminalServer {
pages: Mutex<VecDeque<Value>>,
supported: bool,
calls: Mutex<Vec<(String, Value)>>,
}
impl TerminalServer {
fn new(pages: Vec<Value>, supported: bool) -> Arc<Self> {
Arc::new(Self { pages: Mutex::new(pages.into()), supported, calls: Mutex::default() })
}
fn calls_of(&self, method: &str) -> Vec<Value> {
self.calls.lock().iter().filter(|(m, _)| m == method).map(|(_, p)| p.clone()).collect()
}
}
impl Handler for TerminalServer {
fn on_notification(&self, _: &str, _: Value) {}
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
self.calls.lock().push((method.to_owned(), params));
match method {
"initialize" => Ok(json!({})),
"model/list" => Ok(json!({"data": []})),
"config/read" => Ok(json!({"layers": []})),
"thread/start" => Ok(json!({"thread": {"id": "s", "turns": []}, "cwd": "/w"})),
"skills/list" => Ok(json!({"data": []})),
"thread/unsubscribe" => Ok(json!({})),
m if m.starts_with("thread/backgroundTerminals/") && !self.supported => {
Err((codes::INVALID_REQUEST, format!("Invalid request: unknown variant `{m}`")))
}
"thread/backgroundTerminals/list" => {
Ok(self.pages.lock().pop_front().unwrap_or_else(|| json!({"data": [], "nextCursor": null})))
}
"thread/backgroundTerminals/terminate" => Ok(json!({"terminated": true})),
"thread/backgroundTerminals/clean" => Ok(json!({})),
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
}
}
}
fn terminal(process: &str, command: &str) -> Value {
json!({"itemId": format!("item-{process}"), "processId": process, "command": command, "cwd": "/w", "osPid": 4242})
}
/// A session over a codex playing `server`; the codex peer and the ACP peer.
async fn terminal_session(server: Arc<TerminalServer>, client: Arc<Client>) -> (Peer, Peer) {
let (ours, theirs) = tokio::io::duplex(1 << 16);
let (read, write) = tokio::io::split(theirs);
let native = Peer::connect_framed(read, write, server, Framing::Lines);
let acp = attach(client, |events| {
let (read, write) = tokio::io::split(ours);
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
})
.unwrap();
let init = request(&acp, "initialize", json!({})).await.unwrap();
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"]["backgroundTasks"], true);
request(&acp, "session/new", json!({"cwd": "/w", "mcpServers": []})).await.unwrap();
(native, acp)
}
fn shown_tasks(client: &Client) -> Vec<Value> {
client
.of("s")
.into_iter()
.filter(|u| u["sessionUpdate"] == crate::BACKGROUND_TASKS_UPDATE)
.map(|u| u["tasks"].clone())
.collect()
}
async fn until(what: &str, mut done: impl FnMut() -> bool) {
for _ in 0..200 {
if done() {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("timed out waiting for {what}");
}
#[tokio::test(flavor = "multi_thread")]
async fn background_terminals_outlive_their_turn_as_background_tasks_until_they_end() {
let running = json!({"data": [terminal("p1", "/bin/zsh -lc 'sleep 600; echo done'")], "nextCursor": null});
let server = TerminalServer::new(vec![running.clone(), running.clone(), running], true);
let client = Arc::new(Client::default());
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
until("the terminal to end", || shown_tasks(&client).len() == 2).await;
assert_eq!(
shown_tasks(&client),
[json!([{"task_id": "p1", "task_type": "local_bash", "description": "sleep 600; echo done"}]), json!([])]
);
let listed = server.calls_of("thread/backgroundTerminals/list").len();
assert!(listed >= 4, "listed until none ran, got {listed}");
tokio::time::sleep(Duration::from_millis(100)).await;
assert_eq!(server.calls_of("thread/backgroundTerminals/list").len(), listed, "stops listing once none runs");
acp.kill();
native.kill();
}
#[tokio::test(flavor = "multi_thread")]
async fn a_background_terminal_stops_on_request_and_all_stop_with_the_connection() {
let running = json!({"data": [terminal("p1", "cargo nextest run")], "nextCursor": null});
let server = TerminalServer::new(vec![running; 1000], true);
let client = Arc::new(Client::default());
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
until("the terminal to show", || !shown_tasks(&client).is_empty()).await;
request(&acp, "_openidea/stop_task", json!({"sessionId": "s", "taskId": "p1"})).await.unwrap();
assert_eq!(server.calls_of("thread/backgroundTerminals/terminate"), [json!({"threadId": "s", "processId": "p1"})]);
assert!(server.calls_of("thread/backgroundTerminals/clean").is_empty());
acp.kill();
until("the terminals to be cleaned", || !server.calls_of("thread/backgroundTerminals/clean").is_empty()).await;
assert_eq!(server.calls_of("thread/backgroundTerminals/clean"), [json!({"threadId": "s"})]);
native.kill();
}
#[tokio::test(flavor = "multi_thread")]
async fn closing_a_session_stops_its_background_terminals() {
let server = TerminalServer::new(Vec::new(), true);
let client = Arc::new(Client::default());
let (native, acp) = terminal_session(server.clone(), client).await;
request(&acp, "session/close", json!({"sessionId": "s"})).await.unwrap();
let calls: Vec<String> = server.calls.lock().iter().map(|(m, _)| m.clone()).collect();
let clean = calls.iter().position(|m| m == "thread/backgroundTerminals/clean").expect("cleaned");
let unsubscribe = calls.iter().position(|m| m == "thread/unsubscribe").expect("unsubscribed");
assert!(clean < unsubscribe);
acp.kill();
native.kill();
}
#[tokio::test(flavor = "multi_thread")]
async fn a_codex_without_background_terminals_reports_none() {
let server = TerminalServer::new(Vec::new(), false);
let client = Arc::new(Client::default());
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
until("the listing", || !server.calls_of("thread/backgroundTerminals/list").is_empty()).await;
tokio::time::sleep(Duration::from_millis(100)).await;
assert_eq!(server.calls_of("thread/backgroundTerminals/list").len(), 1);
assert!(shown_tasks(&client).is_empty());
assert!(request(&acp, "_openidea/stop_task", json!({"sessionId": "s", "taskId": "p1"})).await.is_err());
acp.kill();
native.kill();
}
#[tokio::test(flavor = "multi_thread")]
async fn a_command_left_running_by_a_completed_turn_is_not_a_failure() {
for (status, settled) in [("completed", true), ("interrupted", false)] {
let server = TerminalServer::new(Vec::new(), true);
let client = Arc::new(Client::default());
let (native, acp) = terminal_session(server, client.clone()).await;
let item = json!({"type": "commandExecution", "id": "call_1", "command": "/bin/zsh -lc 'sleep 240'",
"cwd": "/w", "status": "inProgress", "commandActions": []});
native.notify("item/started", json!({"threadId": "s", "turnId": "t1", "item": item})).unwrap();
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": status}})).unwrap();
until("the command card", || client.of("s").iter().any(|u| u["sessionUpdate"] == "tool_call")).await;
tokio::time::sleep(Duration::from_millis(50)).await;
let updates: Vec<Value> = client
.of("s")
.into_iter()
.filter(|u| u["sessionUpdate"] == "tool_call_update" && u["toolCallId"] == "call_1")
.collect();
let expected = if settled {
vec![json!({"sessionUpdate": "tool_call_update", "toolCallId": "call_1", "status": "completed"})]
} else {
Vec::new()
};
assert_eq!(updates, expected, "turn {status}");
acp.kill();
native.kill();
}
}
+20 -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()?))
@@ -876,6 +881,20 @@ pub(super) fn decisions(params: &Value, command: bool) -> Vec<Choice> {
out
}
/// One page of `thread/backgroundTerminals/list`: the running terminals as
/// `(processId, description)`.
pub(super) fn background_terminals(page: &Value) -> Vec<(String, String)> {
let data = page.get("data").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
data.iter()
.filter_map(|t| {
let process = t.get("processId").and_then(Value::as_str).filter(|p| !p.is_empty())?;
let command = t.get("command").and_then(Value::as_str).unwrap_or_default();
let description = crate::shell_script(command).unwrap_or_else(|| command.to_owned());
Some((process.to_owned(), description))
})
.collect()
}
/// A command prefix as typed: the script of a `<shell> -lc <script>` wrapper, else the words.
fn shell_unwrapped(argv: &[&str]) -> String {
match argv {
+5 -1
Переглянути файл
@@ -68,7 +68,7 @@ pub(crate) fn connect(
) -> std::io::Result<Peer> {
let launch_args = spec.args.clone();
attach_with_args(client, launch_args, |events| {
let command = super::newest_install(&spec.command);
let command = super::newest_install(spec.executable());
let args = headless_args(&spec.args);
Peer::spawn_framed(&command, &args, cwd, &spec.env, events, on_stderr, Framing::ContentLength)
})
@@ -1372,6 +1372,10 @@ fn build_prompt_payload(session_id: &str, blocks: &[Value]) -> (String, Vec<Valu
{
let path_str = saved.to_string_lossy().into_owned();
let name = saved.file_name().and_then(|n| n.to_str()).unwrap_or("image").to_owned();
// Copilot takes one text prompt and a separate attachments array.
if let Some(number) = block.pointer("/_meta/openideaImageNumber").and_then(Value::as_u64) {
text_parts.push(format!("[Image #{number}: {name}]"));
}
attachments.push(json!({ "type": "file", "path": path_str, "displayName": name }));
temp_files.push(saved);
}
+3 -1
Переглянути файл
@@ -4,7 +4,9 @@
//!
//! A shim speaks ACP v1 as the agent side, plus:
//! - `agentCapabilities.sessionCapabilities.fork` and `session/fork`
//! (`{ sessionId, cwd, mcpServers }` → a `session/new` result for the copy);
//! (`{ sessionId, cwd, mcpServers }` → a `session/new` result for the copy). With
//! `_meta.openidea.forkTurns`, the copy keeps only the source's first that many turns;
//! the result repeats it in its `_meta.openidea.forkTurns` when the shim cut the copy;
//! - `agentCapabilities._meta.openidea.rollback` and `_openidea/rollback`
//! (`{ sessionId, turns }`: drops the last `turns` user turns from the session);
//! - `agentCapabilities._meta.openidea.steer` and `_openidea/steer`
+516 -24
Переглянути файл
@@ -5,6 +5,7 @@
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::path::{Component, Path, PathBuf};
use base64::Engine as _;
use ide_core::settings::{AgentMcpServer, AgentPluginEntryPolicy, AgentPluginSettings};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
@@ -46,6 +47,37 @@ const MARKETPLACE_MANIFEST_PATHS: &[&str] = &[
".github/plugin/marketplace.json",
];
/// Maximum local icon file size inlined as a base64 `data:` URI (64 KiB).
const MAX_INLINE_ICON_BYTES: usize = 64 * 1024;
/// Conventional icon file locations checked inside a plugin directory when no explicit icon is declared.
const CONVENTIONAL_ICON_PATHS: &[&str] = &[
".claude-plugin/icon.png",
".claude-plugin/icon.svg",
".claude-plugin/icon.webp",
".plugin/icon.png",
".plugin/icon.svg",
".plugin/icon.webp",
".github/plugin/icon.png",
".github/plugin/icon.svg",
".github/plugin/icon.webp",
".codex-plugin/icon.png",
".codex-plugin/icon.svg",
".codex-plugin/icon.webp",
"assets/logo.png",
"assets/logo.svg",
"assets/logo.webp",
"assets/icon.png",
"assets/icon.svg",
"assets/icon.webp",
"icon.png",
"icon.svg",
"icon.webp",
"logo.png",
"logo.svg",
"logo.webp",
];
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InstalledPluginProvenance {
@@ -1461,6 +1493,8 @@ pub fn projected_mcp_servers(
unapproved: false,
plugin_id: Some(state.plugin.id.clone()),
plugin_name: Some(state.plugin.display_name.clone()),
registry_name: None,
registry_url: None,
});
}
}
@@ -1551,6 +1585,7 @@ pub fn browse_marketplace(
let tree = fetcher.git_tree(RepoRef { owner: &parsed.owner, repo: &parsed.repo, git_ref: &git_ref }, cancel)?;
let target = RepoRef { owner: &parsed.owner, repo: &parsed.repo, git_ref: &git_ref };
let tree_paths: HashSet<&str> = tree.tree.iter().filter(|e| e.kind == "blob").map(|e| e.path.as_str()).collect();
// 1. Check for a `marketplace.json` manifest in the repository (under `parsed.subpath` if given, or root).
let sub_prefix = parsed.subpath.as_deref().map(|s| format!("{s}/")).unwrap_or_default();
@@ -1561,10 +1596,9 @@ pub fn browse_marketplace(
let text = String::from_utf8(bytes).map_err(|_| IdeError::invalid("marketplace.json is not UTF-8"))?;
let (mkt_name, candidates) = parse_marketplace_json_remote(
&text,
&parsed.owner,
&parsed.repo,
&git_ref,
target,
parsed.subpath.as_deref(),
&tree_paths,
user_home,
workspace_root,
)?;
@@ -1614,6 +1648,7 @@ pub fn browse_marketplace(
let mut description = String::new();
let mut author = None;
let mut keywords = Vec::new();
let mut manifest_val: Option<Value> = None;
for (manifest_rel, _) in MANIFEST_CANDIDATES {
let p = format!("{prefix}{manifest_rel}");
@@ -1644,10 +1679,18 @@ pub fn browse_marketplace(
if keywords.is_empty() {
keywords = extract_string_array(val.get("keywords"));
}
manifest_val = Some(val);
break;
}
}
let (icon_url, icon_dark_url) = resolve_remote_plugin_icons(
manifest_val.as_ref(),
Some((&parsed.owner, &parsed.repo, &git_ref, root_dir.as_str(), Some(&tree_paths))),
None,
Some(&parsed.owner),
);
let source_spec = if root_dir.is_empty() {
format!("{}/{}#{git_ref}", parsed.owner, parsed.repo)
} else {
@@ -1661,6 +1704,8 @@ pub fn browse_marketplace(
description,
author,
marketplace: None,
icon_url,
icon_dark_url,
source_spec,
subpath: root_dir,
keywords,
@@ -1717,7 +1762,7 @@ pub fn preview_plugin(
}
let scanned = scan_local_subtree(&canon, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin")?;
let inspected =
inspect_fetched_subtree(&scanned, canon.file_name().and_then(|s| s.to_str()).unwrap_or("plugin"))?;
inspect_fetched_subtree(&scanned, canon.file_name().and_then(|s| s.to_str()).unwrap_or("plugin"), None)?;
let marketplace_source = marketplace
.and_then(|name| local_marketplace_source(&local_dir, name))
.map(|path| path.to_string_lossy().into_owned());
@@ -1746,6 +1791,8 @@ pub fn preview_plugin(
display_name: inspected.display_name,
version: inspected.version,
description: inspected.description,
icon_url: inspected.icon_url,
icon_dark_url: inspected.icon_dark_url,
formats: inspected.formats,
capabilities: inspected.capabilities,
files: scanned.files,
@@ -1764,7 +1811,11 @@ pub fn preview_plugin(
let scanned =
fetch_and_scan_subtree(fetcher, target, &subpath, None, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin", cancel)?;
let fallback_name = subpath.rsplit('/').next().filter(|s| !s.is_empty()).unwrap_or(&parsed.repo);
let inspected = inspect_fetched_subtree(&scanned, fallback_name)?;
let inspected = inspect_fetched_subtree(
&scanned,
fallback_name,
Some((&parsed.owner, &parsed.repo, &commit_sha, scanned.normalized_subpath.as_str())),
)?;
let targets = plugin_install_targets(
&inspected.name,
inspected.version.as_deref(),
@@ -1791,6 +1842,8 @@ pub fn preview_plugin(
display_name: inspected.display_name,
version: inspected.version,
description: inspected.description,
icon_url: inspected.icon_url,
icon_dark_url: inspected.icon_dark_url,
formats: inspected.formats,
capabilities: inspected.capabilities,
files: scanned.files,
@@ -1919,7 +1972,7 @@ pub fn install_plugin(
));
}
let inspected = inspect_fetched_subtree(&scanned, &fallback_name)?;
let inspected = inspect_fetched_subtree(&scanned, &fallback_name, None)?;
if let Some(reason) = plugin_install_blocker(
source,
&inspected.formats,
@@ -2057,16 +2110,23 @@ struct InspectedSubtreeMeta {
display_name: String,
version: Option<String>,
description: String,
icon_url: Option<String>,
icon_dark_url: Option<String>,
formats: Vec<AgentPluginFormat>,
capabilities: AgentPluginCapabilities,
}
fn inspect_fetched_subtree(scanned: &FetchedSubtree, fallback_name: &str) -> IdeResult<InspectedSubtreeMeta> {
fn inspect_fetched_subtree(
scanned: &FetchedSubtree,
fallback_name: &str,
remote_repo: Option<(&str, &str, &str, &str)>,
) -> IdeResult<InspectedSubtreeMeta> {
let mut formats = Vec::new();
let mut name: Option<String> = None;
let mut display_name: Option<String> = None;
let mut version: Option<String> = None;
let mut description = String::new();
let mut primary_manifest: Option<Value> = None;
let mut native_harnesses = BTreeSet::new();
let file_map: BTreeMap<String, &[u8]> =
@@ -2108,6 +2168,9 @@ fn inspect_fetched_subtree(scanned: &FetchedSubtree, fallback_name: &str) -> Ide
{
description = d.trim().to_owned();
}
if primary_manifest.is_none() {
primary_manifest = Some(val);
}
}
let mut skill_names = Vec::new();
@@ -2158,12 +2221,15 @@ fn inspect_fetched_subtree(scanned: &FetchedSubtree, fallback_name: &str) -> Ide
let final_name = name.unwrap_or_else(|| sanitize_plugin_slug(fallback_name));
let final_display = display_name.unwrap_or_else(|| final_name.clone());
let (icon_url, icon_dark_url) = resolve_subtree_icons(primary_manifest.as_ref(), &file_map, remote_repo);
Ok(InspectedSubtreeMeta {
name: final_name,
display_name: final_display,
version,
description,
icon_url,
icon_dark_url,
formats,
capabilities: AgentPluginCapabilities {
skill_count: skill_names.len() as u32,
@@ -3654,6 +3720,13 @@ fn browse_local_marketplace(
if source_spec.is_empty() {
continue;
}
let local_plugin_dir = Path::new(&source_spec);
let (icon_url, icon_dark_url) = if local_plugin_dir.is_dir() {
resolve_local_plugin_icons(Some(item), local_plugin_dir)
} else {
let ext_repo = source_spec.split('#').next();
resolve_remote_plugin_icons(Some(item), None, ext_repo, None)
};
let (already_user, already_ws) =
plugin_installed_anywhere(&name, Some(&mkt_name), user_home, workspace_root);
candidates.push(AgentMarketplaceCandidate {
@@ -3663,6 +3736,8 @@ fn browse_local_marketplace(
description,
author,
marketplace: Some(mkt_name.clone()),
icon_url,
icon_dark_url,
source_spec,
subpath,
keywords,
@@ -3685,6 +3760,11 @@ fn browse_local_marketplace(
// Direct local plugin folder. The source only selects how metadata is read; the target
// harness is chosen at install time.
if let Some(plug) = inspect_plugin_dir(local_path, AgentPluginSource::CopilotUser, McpScope::User, None, true) {
let manifest_val = MANIFEST_CANDIDATES.iter().find_map(|(rel, _)| {
let text = std::fs::read_to_string(local_path.join(rel)).ok()?;
parse_jsonc(&text).ok()
});
let (icon_url, icon_dark_url) = resolve_local_plugin_icons(manifest_val.as_ref(), local_path);
let (already_user, already_ws) = plugin_installed_anywhere(&plug.name, None, user_home, workspace_root);
return Ok(AgentMarketplaceBrowseResult {
source: raw_source.to_owned(),
@@ -3700,6 +3780,8 @@ fn browse_local_marketplace(
description: plug.description,
author: plug.author,
marketplace: None,
icon_url,
icon_dark_url,
source_spec: local_path.to_string_lossy().into_owned(),
subpath: String::new(),
keywords: Vec::new(),
@@ -3836,13 +3918,13 @@ fn safe_marketplace_repo(raw: &str) -> Option<String> {
fn parse_marketplace_json_remote(
text: &str,
owner: &str,
repo: &str,
git_ref: &str,
target: RepoRef<'_>,
base_subpath: Option<&str>,
tree_paths: &HashSet<&str>,
user_home: Option<&Path>,
workspace_root: Option<&Path>,
) -> IdeResult<(String, Vec<AgentMarketplaceCandidate>)> {
let RepoRef { owner, repo, git_ref } = target;
let val = parse_jsonc(text).map_err(|e| IdeError::invalid(format!("Invalid marketplace.json: {e}")))?;
let mkt_name =
val.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).unwrap_or(repo).to_owned();
@@ -3872,7 +3954,7 @@ fn parse_marketplace_json_remote(
let author = extract_author(item);
let keywords = extract_string_array(item.get("keywords"));
let (source_spec, subpath) = match item.get("source") {
let (source_spec, subpath, ext_repo_owner, in_marketplace_repo) = match item.get("source") {
Some(Value::String(rel)) => {
let Some(clean) = safe_marketplace_subpath(rel) else { continue };
let mut parts: Vec<&str> = Vec::new();
@@ -3891,7 +3973,7 @@ fn parse_marketplace_json_remote(
} else {
format!("{owner}/{repo}/{joined}#{git_ref}")
};
(spec, joined)
(spec, joined, None, true)
}
Some(Value::Object(obj)) => match obj.get("source").and_then(Value::as_str).unwrap_or_default() {
"local" => {
@@ -3916,7 +3998,7 @@ fn parse_marketplace_json_remote(
} else {
format!("{owner}/{repo}/{joined}#{git_ref}")
};
(spec, joined)
(spec, joined, None, true)
}
"github" => {
let Some(ext_repo) = obj.get("repo").and_then(Value::as_str).and_then(safe_marketplace_repo) else {
@@ -3926,9 +4008,9 @@ fn parse_marketplace_json_remote(
let Ok(r) = r.map(|r| safe_marketplace_ref(r).ok_or(())).transpose() else { continue };
let spec = match r {
Some(gr) => format!("{ext_repo}#{gr}"),
None => ext_repo.to_owned(),
None => ext_repo.clone(),
};
(spec, String::new())
(spec, String::new(), Some(ext_repo), false)
}
"git-subdir" => {
let Some(ext_repo) = obj
@@ -3949,15 +4031,19 @@ fn parse_marketplace_json_remote(
let Ok(r) = r.map(|r| safe_marketplace_ref(r).ok_or(())).transpose() else { continue };
let spec = match r {
Some(gr) => format!("{ext_repo}#{gr}"),
None => ext_repo.to_owned(),
None => ext_repo.clone(),
};
(spec, sub)
(spec, sub, Some(ext_repo), false)
}
_ => continue,
},
_ => continue,
};
let in_repo_ctx = in_marketplace_repo.then_some((owner, repo, git_ref, subpath.as_str(), Some(tree_paths)));
let (icon_url, icon_dark_url) =
resolve_remote_plugin_icons(Some(item), in_repo_ctx, ext_repo_owner.as_deref(), Some(owner));
let (already_user, already_ws) = plugin_installed_anywhere(&name, Some(&mkt_name), user_home, workspace_root);
out.push(AgentMarketplaceCandidate {
name,
@@ -3966,6 +4052,8 @@ fn parse_marketplace_json_remote(
description,
author,
marketplace: Some(mkt_name.clone()),
icon_url,
icon_dark_url,
source_spec,
subpath,
keywords,
@@ -3977,6 +4065,302 @@ fn parse_marketplace_json_remote(
Ok((mkt_name, out))
}
fn safe_https_icon_url(raw: &str) -> Option<String> {
let trimmed = raw.trim();
let rest = trimmed.strip_prefix("https://")?;
if trimmed.chars().any(|c| c.is_whitespace() || c.is_control()) {
return None;
}
let authority = rest.split('/').next().unwrap_or_default();
if authority.is_empty() || authority.contains('@') {
return None;
}
Some(trimmed.to_owned())
}
fn icon_mime_for_path(path: &str) -> Option<&'static str> {
let lower = path.to_ascii_lowercase();
if lower.ends_with(".png") {
Some("image/png")
} else if lower.ends_with(".svg") {
Some("image/svg+xml")
} else if lower.ends_with(".webp") {
Some("image/webp")
} else if lower.ends_with(".jpg") || lower.ends_with(".jpeg") {
Some("image/jpeg")
} else if lower.ends_with(".ico") {
Some("image/x-icon")
} else {
None
}
}
fn encode_data_uri(mime: &str, bytes: &[u8]) -> Option<String> {
if bytes.is_empty() || bytes.len() > MAX_INLINE_ICON_BYTES {
return None;
}
let b64 = base64::engine::general_purpose::STANDARD.encode(bytes);
Some(format!("data:{mime};base64,{b64}"))
}
fn percent_encode_path_segment(segment: &str) -> String {
let mut out = String::with_capacity(segment.len());
for byte in segment.bytes() {
let unreserved = byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~');
if unreserved {
out.push(byte as char);
} else {
out.push('%');
let hi = byte >> 4;
let lo = byte & 0x0f;
out.push(if hi < 10 { (b'0' + hi) as char } else { (b'A' + hi - 10) as char });
out.push(if lo < 10 { (b'0' + lo) as char } else { (b'A' + lo - 10) as char });
}
}
out
}
fn github_raw_file_url(owner: &str, repo: &str, git_ref: &str, repo_path: &str) -> String {
let enc_ref = git_ref.split('/').map(percent_encode_path_segment).collect::<Vec<_>>().join("/");
let enc_path = repo_path.split('/').map(percent_encode_path_segment).collect::<Vec<_>>().join("/");
format!("https://raw.githubusercontent.com/{owner}/{repo}/{enc_ref}/{enc_path}")
}
fn is_valid_github_owner(owner: &str) -> bool {
!owner.is_empty()
&& owner.len() <= 39
&& owner.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
&& !owner.starts_with('-')
&& !owner.ends_with('-')
}
fn github_owner_from_url(raw: &str) -> Option<&str> {
let trimmed = raw.trim();
let rest = trimmed
.strip_prefix("https://github.com/")
.or_else(|| trimmed.strip_prefix("http://github.com/"))
.or_else(|| trimmed.strip_prefix("https://www.github.com/"))?;
let owner = rest.split('/').next()?;
is_valid_github_owner(owner).then_some(owner)
}
fn github_owner_from_repo_slug(slug: &str) -> Option<&str> {
let owner = slug.trim().split('/').next()?;
is_valid_github_owner(owner).then_some(owner)
}
fn github_owner_avatar(val: Option<&Value>, ext_repo: Option<&str>, fallback_owner: Option<&str>) -> Option<String> {
if let Some(owner) = ext_repo.and_then(github_owner_from_repo_slug) {
return Some(format!("https://github.com/{owner}.png?size=64"));
}
if let Some(v) = val {
let candidate_urls = [
v.get("repository").and_then(|r| r.get("url").or(Some(r))).and_then(Value::as_str),
v.get("homepage").and_then(Value::as_str),
v.pointer("/author/url").and_then(Value::as_str),
];
for raw_url in candidate_urls.into_iter().flatten() {
if let Some(owner) = github_owner_from_url(raw_url) {
return Some(format!("https://github.com/{owner}.png?size=64"));
}
}
}
if let Some(owner) = fallback_owner.filter(|o| is_valid_github_owner(o)) {
return Some(format!("https://github.com/{owner}.png?size=64"));
}
None
}
/// Resolves explicit icon references `(light, dark)` from a marketplace entry or plugin manifest,
/// skipping any invalid/unresolvable entries before picking light/dark variants.
fn resolve_manifest_icon_refs(
val: &Value,
resolve: impl Fn(&str) -> Option<String>,
) -> (Option<String>, Option<String>) {
if let Some(icons) = val.get("icons").and_then(Value::as_array) {
let mut light: Option<String> = None;
let mut dark: Option<String> = None;
let mut unthemed: Option<String> = None;
let mut first: Option<String> = None;
for item in icons {
let Some(obj) = item.as_object() else { continue };
let Some(src) = obj.get("src").and_then(Value::as_str).and_then(&resolve) else {
continue;
};
if first.is_none() {
first = Some(src.clone());
}
match obj.get("theme").and_then(Value::as_str).map(|s| s.trim().to_ascii_lowercase()).as_deref() {
Some("light") if light.is_none() => light = Some(src),
Some("dark") if dark.is_none() => dark = Some(src),
None | Some("") if unthemed.is_none() => unthemed = Some(src),
_ => {}
}
}
let resolved_light = light.or_else(|| unthemed.clone()).or(first);
if resolved_light.is_some() {
let resolved_dark = dark.or(unthemed).filter(|d| Some(d.as_str()) != resolved_light.as_deref());
return (resolved_light, resolved_dark);
}
}
if let Some(icon) = val.get("icon") {
if let Some(resolved) = icon.as_str().and_then(&resolve) {
return (Some(resolved), None);
}
if let Some(obj) = icon.as_object() {
let light = obj.get("light").and_then(Value::as_str).and_then(&resolve);
let dark = obj.get("dark").and_then(Value::as_str).and_then(&resolve);
if light.is_some() || dark.is_some() {
let eff_light = light.or_else(|| dark.clone());
let eff_dark = dark.filter(|d| Some(d.as_str()) != eff_light.as_deref());
return (eff_light, eff_dark);
}
}
}
for candidate in [
val.get("logo"),
val.pointer("/interface/logo"),
val.pointer("/interface/composerIcon"),
val.get("iconUrl"),
val.get("icon_url"),
] {
if let Some(resolved) = candidate.and_then(Value::as_str).and_then(&resolve) {
return (Some(resolved), None);
}
}
(None, None)
}
fn join_repo_subpath(subpath: &str, rel: &str) -> String {
if subpath.is_empty() { rel.to_owned() } else { format!("{subpath}/{rel}") }
}
type RemoteRepoIconContext<'a> = (&'a str, &'a str, &'a str, &'a str, Option<&'a HashSet<&'a str>>);
fn resolve_remote_icon_ref(raw: &str, in_repo: Option<RemoteRepoIconContext<'_>>) -> Option<String> {
if let Some(https) = safe_https_icon_url(raw) {
return Some(https);
}
let (owner, repo, git_ref, subpath, tree_paths) = in_repo?;
let clean = safe_marketplace_subpath(raw).filter(|s| !s.is_empty())?;
icon_mime_for_path(clean)?;
let full = join_repo_subpath(subpath, clean);
if let Some(paths) = tree_paths
&& !paths.contains(full.as_str())
{
return None;
}
Some(github_raw_file_url(owner, repo, git_ref, &full))
}
fn resolve_remote_plugin_icons(
val: Option<&Value>,
in_repo: Option<RemoteRepoIconContext<'_>>,
ext_repo: Option<&str>,
fallback_owner: Option<&str>,
) -> (Option<String>, Option<String>) {
if let Some(v) = val {
let (light, dark) = resolve_manifest_icon_refs(v, |r| resolve_remote_icon_ref(r, in_repo));
if light.is_some() || dark.is_some() {
return (light, dark);
}
}
if let Some((owner, repo, git_ref, subpath, Some(tree_paths))) = in_repo {
for rel in CONVENTIONAL_ICON_PATHS {
let full = join_repo_subpath(subpath, rel);
if tree_paths.contains(full.as_str()) {
return (Some(github_raw_file_url(owner, repo, git_ref, &full)), None);
}
}
}
(github_owner_avatar(val, ext_repo, fallback_owner), None)
}
fn resolve_local_icon_ref(raw: &str, plugin_dir: &Path) -> Option<String> {
if let Some(https) = safe_https_icon_url(raw) {
return Some(https);
}
let clean = safe_marketplace_subpath(raw).filter(|s| !s.is_empty())?;
let mime = icon_mime_for_path(clean)?;
let path = contained_join(plugin_dir, clean).ok()?;
let meta = std::fs::metadata(&path).ok()?;
if !meta.is_file() || meta.len() > MAX_INLINE_ICON_BYTES as u64 {
return None;
}
let bytes = std::fs::read(&path).ok()?;
encode_data_uri(mime, &bytes)
}
fn resolve_local_plugin_icons(val: Option<&Value>, plugin_dir: &Path) -> (Option<String>, Option<String>) {
if let Some(v) = val {
let (light, dark) = resolve_manifest_icon_refs(v, |r| resolve_local_icon_ref(r, plugin_dir));
if light.is_some() || dark.is_some() {
return (light, dark);
}
}
for rel in CONVENTIONAL_ICON_PATHS {
if let Some(data_uri) = resolve_local_icon_ref(rel, plugin_dir) {
return (Some(data_uri), None);
}
}
(github_owner_avatar(val, None, None), None)
}
fn resolve_subtree_icon_ref(
raw: &str,
file_map: &BTreeMap<String, &[u8]>,
remote_repo: Option<(&str, &str, &str, &str)>,
) -> Option<String> {
if let Some(https) = safe_https_icon_url(raw) {
return Some(https);
}
let clean = safe_marketplace_subpath(raw).filter(|s| !s.is_empty())?;
let mime = icon_mime_for_path(clean)?;
let bytes = file_map.get(clean)?;
if let Some((owner, repo, git_ref, subpath)) = remote_repo {
let full = join_repo_subpath(subpath, clean);
return Some(github_raw_file_url(owner, repo, git_ref, &full));
}
encode_data_uri(mime, bytes)
}
fn resolve_subtree_icons(
val: Option<&Value>,
file_map: &BTreeMap<String, &[u8]>,
remote_repo: Option<(&str, &str, &str, &str)>,
) -> (Option<String>, Option<String>) {
if let Some(v) = val {
let (light, dark) = resolve_manifest_icon_refs(v, |r| resolve_subtree_icon_ref(r, file_map, remote_repo));
if light.is_some() || dark.is_some() {
return (light, dark);
}
}
for rel in CONVENTIONAL_ICON_PATHS {
if let Some(bytes) = file_map.get(*rel)
&& let Some(mime) = icon_mime_for_path(rel)
{
if let Some((owner, repo, git_ref, subpath)) = remote_repo {
let full = join_repo_subpath(subpath, rel);
return (Some(github_raw_file_url(owner, repo, git_ref, &full)), None);
}
if let Some(data_uri) = encode_data_uri(mime, bytes) {
return (Some(data_uri), None);
}
}
}
let fallback_owner = remote_repo.map(|(owner, _, _, _)| owner);
(github_owner_avatar(val, None, fallback_owner), None)
}
const INSTALL_SOURCES: [AgentPluginSource; 4] = [
AgentPluginSource::ClaudeUser,
AgentPluginSource::CopilotUser,
@@ -5553,7 +5937,7 @@ mod tests {
let on_disk = inspect_plugin_dir(&dir, AgentPluginSource::ClaudeUser, McpScope::User, Some("m"), true).unwrap();
let scanned = scan_local_subtree(&dir, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin").unwrap();
let preview = inspect_fetched_subtree(&scanned, "hooked").unwrap();
let preview = inspect_fetched_subtree(&scanned, "hooked", None).unwrap();
for hooks in [&on_disk.capabilities.hook_files, &preview.capabilities.hook_files] {
assert!(hooks.contains(&".claude-plugin/plugin.json#hooks".to_owned()), "{hooks:?}");
assert!(hooks.contains(&"config/copilot-hooks.json".to_owned()), "{hooks:?}");
@@ -5698,19 +6082,19 @@ mod tests {
{"name":"gh-bad-ref","source":{"source":"github","repo":"acme/tools","ref":"main#x"}},
{"name":"sub-bad","source":{"source":"git-subdir","url":"https://github.com/acme/tools.git","path":"../x"}}
]}"##;
let (_, candidates) =
parse_marketplace_json_remote(manifest, "acme", "repo", "main", None, None, None).unwrap();
let empty_tree = HashSet::new();
let target = RepoRef { owner: "acme", repo: "repo", git_ref: "main" };
let (_, candidates) = parse_marketplace_json_remote(manifest, target, None, &empty_tree, None, None).unwrap();
let specs: Vec<_> = candidates.iter().map(|c| (c.name.as_str(), c.source_spec.as_str())).collect();
assert_eq!(specs, [("ok", "acme/repo/plugins/ok#main"), ("gh-ok", "acme/tools#v1.2")]);
assert!(
parse_marketplace_json_remote(
r#"{"metadata":{"pluginRoot":"../up"},"plugins":[]}"#,
"acme",
"repo",
"main",
target,
None,
&empty_tree,
None,
None,
None
)
.is_err()
);
@@ -5828,4 +6212,112 @@ mod tests {
&& plugin.scope == McpScope::Workspace
}));
}
#[test]
fn marketplace_browse_and_preview_resolve_explicit_bundled_local_and_avatar_icons() {
let cancel = CancellationToken::new();
let marketplace_json = br#"{
"name": "claude-plugins-official",
"plugins": [
{
"name": "themed-ext",
"description": "Explicit light/dark icons",
"source": "./plugins/themed-ext",
"icons": [
{ "src": "javascript:alert(1)", "theme": "light" },
{ "src": "https://cdn.example.com/light.png", "theme": "light" },
{ "src": "https://cdn.example.com/dark.png", "theme": "dark" }
]
},
{
"name": "champion-kit",
"description": "Bundled .claude-plugin/icon.png",
"source": "./plugins/champion-kit"
},
{
"name": "adobe-for-creativity",
"description": "External git-subdir plugin",
"source": {
"source": "git-subdir",
"url": "https://github.com/adobe/skills.git",
"path": "plugins/creative-cloud/adobe-for-creativity"
}
},
{
"name": "first-party",
"description": "Falls back to marketplace repo owner avatar",
"source": "./plugins/first-party"
},
{
"name": "unsafe-icon",
"description": "Rejects http:// and escaping relative paths",
"source": "./plugins/unsafe-icon",
"icon": "../escape.png"
}
]
}"#;
let gh = FakeGitHub::new(
&[
(".claude-plugin/marketplace.json", marketplace_json.as_slice(), "100644"),
("plugins/champion-kit/.claude-plugin/plugin.json", br#"{"name":"champion-kit"}"#, "100644"),
("plugins/champion-kit/.claude-plugin/icon.png", b"\x89PNG\r\n\x1a\n", "100644"),
("plugins/first-party/.claude-plugin/plugin.json", br#"{"name":"first-party"}"#, "100644"),
],
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
);
let browse = browse_marketplace(&gh, "anthropics/claude-plugins-official", None, None, &cancel).unwrap();
let by = |name: &str| browse.candidates.iter().find(|c| c.name == name).unwrap();
assert_eq!(by("themed-ext").icon_url.as_deref(), Some("https://cdn.example.com/light.png"));
assert_eq!(by("themed-ext").icon_dark_url.as_deref(), Some("https://cdn.example.com/dark.png"));
assert_eq!(
by("champion-kit").icon_url.as_deref(),
Some(
"https://raw.githubusercontent.com/anthropics/claude-plugins-official/main/plugins/champion-kit/.claude-plugin/icon.png"
)
);
assert_eq!(by("adobe-for-creativity").icon_url.as_deref(), Some("https://github.com/adobe.png?size=64"));
assert_eq!(by("first-party").icon_url.as_deref(), Some("https://github.com/anthropics.png?size=64"));
assert_eq!(by("unsafe-icon").icon_url.as_deref(), Some("https://github.com/anthropics.png?size=64"));
// Remote preview also resolves bundled icons to raw.githubusercontent.com at commit_sha.
let remote_preview = preview_plugin(
&gh,
"anthropics/claude-plugins-official/plugins/champion-kit#main",
None,
Some("claude-plugins-official"),
None,
None,
&cancel,
)
.unwrap();
assert_eq!(
remote_preview.icon_url.as_deref(),
Some(
"https://raw.githubusercontent.com/anthropics/claude-plugins-official/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/plugins/champion-kit/.claude-plugin/icon.png"
)
);
// Local marketplace & preview inline small local PNG icons as data URIs.
let tmp = tempfile::tempdir().unwrap();
let local_plugin = tmp.path().join("my-local-plugin");
write(
&local_plugin.join(".codex-plugin/plugin.json"),
r#"{"name":"my-local-plugin","interface":{"logo":"./assets/logo.png"}}"#,
);
std::fs::create_dir_all(local_plugin.join("assets")).unwrap();
std::fs::write(local_plugin.join("assets/logo.png"), b"\x89PNG\r\n\x1a\n").unwrap();
let local_browse = browse_marketplace(&gh, local_plugin.to_str().unwrap(), None, None, &cancel).unwrap();
assert_eq!(local_browse.candidates.len(), 1);
assert!(
local_browse.candidates[0].icon_url.as_deref().is_some_and(|u| u.starts_with("data:image/png;base64,"))
);
let local_preview =
preview_plugin(&gh, local_plugin.to_str().unwrap(), None, None, None, None, &cancel).unwrap();
assert!(local_preview.icon_url.as_deref().is_some_and(|u| u.starts_with("data:image/png;base64,")));
}
}
+106 -13
Переглянути файл
@@ -35,6 +35,7 @@ pub(crate) struct ProviderSpec {
pub name: String,
pub driver: Driver,
pub command: String,
pub managed_cli: Option<String>,
pub args: Vec<String>,
/// Number of trailing arguments added by the built-in agent's settings.
pub additional_args_len: usize,
@@ -90,6 +91,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
("vibe", "Mistral Vibe", Driver::Acp, &["vibe-acp"], "Run `vibe` in a terminal and sign in."),
("omp", "OMP", Driver::Acp, &["omp", "acp"], "Run `omp` in a terminal and sign in."),
("hermes", "Hermes Agent", Driver::Acp, &["hermes", "acp"], "Run `hermes model` in a terminal."),
("antigravity-acp", "Google Antigravity", Driver::Acp, &["agy", "acp"], "Run `agy acp --login` in a terminal."),
];
fn builtins() -> Vec<ProviderSpec> {
@@ -100,6 +102,7 @@ fn builtins() -> Vec<ProviderSpec> {
name: (*name).into(),
driver: *driver,
command: cmd[0].into(),
managed_cli: None,
args: cmd[1..].iter().map(|a| (*a).to_owned()).collect(),
additional_args_len: 0,
env: Vec::new(),
@@ -110,6 +113,10 @@ fn builtins() -> Vec<ProviderSpec> {
}
impl ProviderSpec {
pub(crate) fn executable(&self) -> &str {
self.managed_cli.as_deref().unwrap_or(&self.command)
}
pub(crate) fn login_hint(&self, program: &Path) -> String {
if !program.is_absolute() {
return self.login_hint.clone();
@@ -135,7 +142,7 @@ impl ProviderSpec {
.flatten();
let hint = match terminal_args {
Some(args) => {
let command = render_login_command(program, args, cfg!(windows));
let command = render_shell_command(program, args, cfg!(windows));
format!("Run `{command}` in a terminal.")
}
None => self.login_hint(program),
@@ -179,7 +186,9 @@ impl ProviderSpec {
}
fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
if self.driver != Driver::Acp {
if let Some(program) = self.managed_cli.take() {
self.command = program;
} else if self.driver != Driver::Acp {
self.command = crate::native::newest_install(&self.command);
}
if is_copilot_provider(&self.id) {
@@ -222,7 +231,9 @@ impl ProviderSpec {
});
}
if let Some(builtin) = builtin_spec(&self.id) {
if let Some(builtin) = builtin_spec(&self.id)
&& !(matches!(self.source, AgentSource::Registry { .. }) && registry_uses_separate_binary(&self.id))
{
let args = terminal_auth_args
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
.map(<[String]>::to_vec)
@@ -533,7 +544,7 @@ fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>
return spec.login_hint.clone();
}
let (args, suffix) = rest.split_once('`').expect("built-in login hints delimit their command");
let command = render_login_command(program, args.split_whitespace(), windows);
let command = render_shell_command(program, args.split_whitespace(), windows);
match suffix {
" in a terminal." => format!("Run `{command}` in a terminal."),
" in a terminal and sign in." => format!("Run `{command}` in a terminal and sign in."),
@@ -541,7 +552,11 @@ fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>
}
}
fn render_login_command<'a>(program: &Path, args: impl IntoIterator<Item = &'a str>, windows: bool) -> String {
pub(crate) fn render_shell_command<'a>(
program: &Path,
args: impl IntoIterator<Item = &'a str>,
windows: bool,
) -> String {
let quote = |word: &str| {
if windows { format!("'{}'", word.replace('\'', "''")) } else { format!("'{}'", word.replace('\'', "'\\''")) }
};
@@ -585,6 +600,13 @@ pub(crate) fn is_unlisted(spec: &ProviderSpec) -> bool {
UNLISTED.contains(&spec.id.as_str()) && builtin_spec(&spec.id).as_ref() == Some(spec)
}
/// Built-in CLI agents whose ACP Registry archive ships a separate ACP server binary
/// rather than the CLI itself, so the built-in CLI's login subcommand does not apply
/// to a registry install.
fn registry_uses_separate_binary(id: &str) -> bool {
id == "antigravity-acp"
}
fn uses_package_runner(command: &str) -> bool {
matches!(command, "npx" | "bunx" | "uvx")
}
@@ -610,20 +632,21 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
AgentProvider {
id: spec.id.clone(),
name: spec.name.clone(),
command: std::iter::once(spec.command.as_str())
command: std::iter::once(spec.executable())
.chain(spec.args.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" "),
program: spec.command.clone(),
program: spec.executable().to_owned(),
args: spec.args.clone(),
additional_args,
default_program: builtin.as_ref().map(|b| b.command.clone()),
default_args: builtin.as_ref().map(|b| b.args.clone()).unwrap_or_default(),
login_hint: Some(spec.login_hint(&ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env))),
login_hint: Some(spec.login_hint(&ide_jsonrpc::resolve_spawn_program(spec.executable(), &spec.env))),
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_with_env(&spec.command, &spec.env),
installed: installed_with_env(spec.executable(), &spec.env),
cli_install_command: None,
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(),
@@ -747,6 +770,20 @@ fn update_builtin(
agent.write_with(&file, id, secrets)
}
/// Project backends can share a config directory. Keep the ID check, credential
/// changes and file write in the same critical section.
fn lock_custom_agents(custom_dir: &Path) -> std::io::Result<std::fs::File> {
std::fs::create_dir_all(custom_dir)?;
let lock = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(custom_dir.join(".custom-agents.lock"))?;
lock.lock()?;
Ok(lock)
}
/// Saves a new custom agent; refuses built-in and ACP Registry ids, taken ids
/// and an empty command. The id is also the agent file's name, so it must be
/// a safe file stem.
@@ -762,6 +799,7 @@ pub(crate) fn save_custom(
if input.command.trim().is_empty() {
return Err(IdeError::invalid("the agent command must not be empty"));
}
let _lock = lock_custom_agents(custom_dir)?;
let file = custom_dir.join(format!("{id}.toml"));
if file.try_exists()? {
if CustomAgent::read(&file).is_ok_and(|a| a.registry.is_some()) {
@@ -790,6 +828,7 @@ pub(crate) fn remove_custom(custom_dir: &Path, secrets: Option<&dyn EnvSecrets>,
if builtin_spec(id).is_some() {
return Err(IdeError::invalid(format!("{id} is a built-in agent and cannot be removed")));
}
let _lock = lock_custom_agents(custom_dir)?;
let file = custom_dir.join(format!("{id}.toml"));
let agent =
CustomAgent::read(&file).map_err(|_| IdeError::not_found(format!("there is no custom agent '{id}'")))?;
@@ -829,6 +868,7 @@ pub(crate) fn import_acp(
}
let parsed: AcpJson =
serde_json::from_str(text).map_err(|e| IdeError::invalid(format!("not an acp.json file: {e}")))?;
let _lock = lock_custom_agents(custom_dir)?;
let mut outcomes = Vec::with_capacity(parsed.agent_servers.len());
for (name, server) in parsed.agent_servers {
let id = slugify_id(&name);
@@ -1024,6 +1064,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
name: agent.name.unwrap_or_else(|| id.clone()),
driver: agent.driver,
command: agent.command,
managed_cli: None,
args: agent.args,
additional_args_len: 0,
env,
@@ -1033,7 +1074,9 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
};
match specs.iter_mut().find(|s| s.id == spec.id) {
Some(existing) => {
spec.login_hint = existing.login_hint.clone();
if !(matches!(spec.source, AgentSource::Registry { .. }) && registry_uses_separate_binary(&spec.id)) {
spec.login_hint = existing.login_hint.clone();
}
if !explicit_driver && existing.driver == Driver::Copilot && spec.driver == Driver::Acp {
// Registry installs (`github-copilot-cli`) record `args = ["--acp"]` with no
// `driver`; upgrade them in place to the native headless driver (which
@@ -1102,6 +1145,55 @@ mod tests {
assert_eq!(info.login_hint.as_deref(), Some("Run `hermes model` in a terminal."));
}
#[test]
fn antigravity_is_built_in_over_acp() {
let spec = builtin_spec("antigravity-acp").unwrap();
assert_eq!(spec.driver, Driver::Acp);
assert!(!is_builtin("antigravity-acp"));
let info = describe(&spec);
assert_eq!((info.name.as_str(), info.command.as_str()), ("Google Antigravity", "agy acp"));
assert_eq!(info.login_hint.as_deref(), Some("Run `agy acp --login` in a terminal."));
assert!(info.command_editable);
assert_eq!(info.additional_args, Some(vec![]));
}
#[test]
fn registry_antigravity_does_not_inherit_cli_login_subcommand() {
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join(if cfg!(windows) { "agy_acp_server.exe" } else { "agy_acp_server.par" });
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
}
CustomAgent {
name: Some("Google Antigravity".into()),
driver: Driver::Acp,
command: bin.to_string_lossy().into_owned(),
args: Vec::new(),
additional_args: Vec::new(),
env: BTreeMap::new(),
registry: Some(RegistryRef { id: "antigravity-acp".into(), version: "1.5.2".into() }),
}
.write(&dir.path().join("antigravity-acp.toml"))
.unwrap();
let reg = load(Some(dir.path()), None).into_iter().find(|s| s.id == "antigravity-acp").unwrap();
assert_eq!(reg.source, AgentSource::Registry { version: "1.5.2".into(), update: None });
assert_eq!(reg.login_hint, "Sign in with the agent's own command line first.");
assert_eq!(describe(&reg).login_hint.as_deref(), Some("Sign in with the agent's own command line first."));
assert!(reg.login_launch(dir.path(), None).is_none());
let terminal_launch = reg.login_launch(dir.path(), Some(&["--login".into()])).unwrap();
assert_eq!(terminal_launch.program, bin);
assert_eq!(terminal_launch.args, ["--login"]);
std::fs::remove_file(dir.path().join("antigravity-acp.toml")).unwrap();
let builtin = load(Some(dir.path()), None).into_iter().find(|s| s.id == "antigravity-acp").unwrap();
assert_eq!(builtin.source, AgentSource::Builtin);
assert_eq!((builtin.command.as_str(), builtin.args.as_slice()), ("agy", &["acp".to_owned()][..]));
}
#[test]
fn qoder_global_and_cn_editions_are_both_built_in() {
let info = |id: &str| describe(&load(None, None).into_iter().find(|s| s.id == id).unwrap());
@@ -1154,6 +1246,7 @@ mod tests {
assert_eq!(args("copilot"), ["login"]);
assert_eq!(args("goose"), ["configure"]);
assert_eq!(args("hermes"), ["model"]);
assert_eq!(args("antigravity-acp"), ["acp", "--login"]);
assert!(args("qwen").is_empty());
}
@@ -1228,7 +1321,7 @@ mod tests {
(true, "& '/agent''s tools/$cli' auth login --account 'user name' 'a''b' '$token' ''"),
] {
assert_eq!(
render_login_command(
render_shell_command(
Path::new("/agent's tools/$cli"),
["auth", "login", "--account", "user name", "a'b", "$token", ""],
windows
@@ -1280,10 +1373,10 @@ mod tests {
for p in &defaults {
assert_eq!(p.source, AgentSource::Builtin);
assert!(p.default_program.is_some());
assert_eq!(p.command_editable, !p.id.ends_with("-acp"));
assert_eq!(p.command_editable, !uses_package_runner(&p.program));
assert_eq!(
p.command_read_only_reason,
p.id.ends_with("-acp").then_some(AgentCommandReadOnlyReason::PackageRunner)
uses_package_runner(&p.program).then_some(AgentCommandReadOnlyReason::PackageRunner)
);
}
set_builtin_command(dir.path(), None, "codex", Some("/path with spaces/codex")).unwrap();
+1
Переглянути файл
@@ -22,6 +22,7 @@ fn paths(dir: &Path) -> AgentPaths {
store_dir: dir.join("store"),
worktrees_dir: dir.join("worktrees"),
models_file: dir.join("models.json"),
cli_dir: dir.join("agent-cli"),
custom_agents_dir: None,
home_dir: None,
env_secrets: None,
+154
Переглянути файл
@@ -296,6 +296,24 @@ pub fn discover_skills_with_agent_plugins(
home: Option<&Path>,
plugin_skill_dirs: &[PathBuf],
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
) -> Vec<AgentSkill> {
discover_skills_with_indexed_files(workspaces, home, plugin_skill_dirs, agent_plugin_roots, &[])
}
/// Discovers skills across `workspaces`, `home`, OpenIDEA IDE-plugin skill folders (`plugin_skill_dirs`),
/// resolved agent plugin bundle roots (`agent_plugin_roots`), and deeply nested workspace packages
/// inferred from `indexed_skill_files` (typically `ProjectIndex::files_with_names(&["SKILL.md"])`).
///
/// Direct workspace roots and shallow monorepo packages (depth 1–2) are scanned directly on disk
/// first so discovery works before indexing finishes and preserves shallow-over-deep precedence.
/// Any deeper package roots discovered via `indexed_skill_files` are scanned next, sorted from
/// shallowest to deepest and deduplicated by canonical path.
pub fn discover_skills_with_indexed_files(
workspaces: &[PathBuf],
home: Option<&Path>,
plugin_skill_dirs: &[PathBuf],
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
indexed_skill_files: &[PathBuf],
) -> Vec<AgentSkill> {
let mut out: Vec<AgentSkill> = Vec::new();
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
@@ -321,6 +339,13 @@ pub fn discover_skills_with_agent_plugins(
}
}
}
// Deeply nested packages (arbitrary depth) surfaced by the project file index.
for sub in indexed_package_roots(&all_workspaces, indexed_skill_files) {
let sub_canon = dunce::canonicalize(&sub).unwrap_or_else(|_| sub.clone());
if seen_workspaces.insert(sub_canon) {
roots.extend(WORKSPACE_ROOTS.iter().map(|(rel, source)| (sub.join(rel), *source)));
}
}
if let Some(home) = home {
roots.extend(HOME_ROOTS.iter().map(|(rel, source)| (home.join(rel), *source)));
}
@@ -413,6 +438,74 @@ fn monorepo_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
out
}
/// Extracts workspace package roots from indexed `SKILL.md` file paths.
///
/// Only accepts `SKILL.md` files located inside one of [`WORKSPACE_ROOTS`] at depth 0, 1, or 2
/// below `<dot_dir>/skills` (`skills/SKILL.md`, `skills/<name>/SKILL.md`, or
/// `skills/<category>/<name>/SKILL.md`), rejecting unrelated fixture/doc `SKILL.md` files as well
/// as packages under hidden directories or [`SKIP_MONOREPO_DIRS`]. Returns roots sorted from
/// shallowest to deepest (then lexicographically) so shallower packages always win on name clashes.
fn indexed_package_roots(workspaces: &[PathBuf], indexed_skill_files: &[PathBuf]) -> Vec<PathBuf> {
if workspaces.is_empty() || indexed_skill_files.is_empty() {
return Vec::new();
}
let workspace_pairs: Vec<(&Path, Option<PathBuf>)> =
workspaces.iter().map(|ws| (ws.as_path(), dunce::canonicalize(ws).ok())).collect();
let mut candidates: Vec<(usize, PathBuf)> = Vec::new();
for file in indexed_skill_files {
let Some(pkg_root) = package_root_of_skill_file(file) else { continue };
let Some(rel) = relative_within_workspaces(&pkg_root, &workspace_pairs) else { continue };
if rel.components().any(|c| match c {
std::path::Component::Normal(seg) => {
seg.to_str().is_none_or(|s| s.starts_with('.') || SKIP_MONOREPO_DIRS.contains(&s))
}
_ => true,
}) {
continue;
}
if !pkg_root.is_dir() {
continue;
}
candidates.push((rel.components().count(), pkg_root));
}
candidates.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
candidates.dedup_by(|a, b| a.1 == b.1);
candidates.into_iter().map(|(_, p)| p).collect()
}
/// If `skill_md` sits inside `<pkg>/<dot_dir>/skills[/<category>][/<name>]/SKILL.md` for one of
/// [`WORKSPACE_ROOTS`], returns `<pkg>`.
fn package_root_of_skill_file(skill_md: &Path) -> Option<PathBuf> {
if skill_md.file_name().and_then(|n| n.to_str()) != Some("SKILL.md") {
return None;
}
let mut cur = skill_md.parent()?;
for _ in 0..=2 {
if cur.file_name().and_then(|n| n.to_str()) == Some("skills")
&& let Some(dot_dir) = cur.parent()
&& let Some(dot_name) = dot_dir.file_name().and_then(|n| n.to_str())
&& WORKSPACE_ROOTS.iter().any(|(rel, _)| rel.split('/').next() == Some(dot_name))
&& let Some(pkg_root) = dot_dir.parent()
{
return Some(pkg_root.to_path_buf());
}
cur = cur.parent()?;
}
None
}
fn relative_within_workspaces(pkg_root: &Path, workspaces: &[(&Path, Option<PathBuf>)]) -> Option<PathBuf> {
let pick_shortest =
|iter: &mut dyn Iterator<Item = &Path>| iter.min_by_key(|rel| rel.components().count()).map(Path::to_path_buf);
let mut direct = workspaces.iter().filter_map(|(ws, _)| pkg_root.strip_prefix(ws).ok());
if let Some(rel) = pick_shortest(&mut direct) {
return Some(rel);
}
let canon_pkg = dunce::canonicalize(pkg_root).ok()?;
let mut canonical = workspaces.iter().filter_map(|(_, canon_ws)| canon_pkg.strip_prefix(canon_ws.as_ref()?).ok());
pick_shortest(&mut canonical)
}
/// 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> {
@@ -1469,4 +1562,65 @@ mod tests {
let staged_md = std::fs::read_to_string(farm.join("copilot/verify-ux/SKILL.md")).unwrap();
assert_eq!(staged_md, raw_md);
}
#[test]
fn indexed_skill_files_discover_deep_monorepo_skills_and_respect_filters_and_precedence() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let ws = root.join("ws");
let deep_grafana =
ws.join("mango/tools/mai-grafana-dashboards/.github/skills/edit-grafana-dashboards/SKILL.md");
let deep_category = ws.join("a/b/c/.agents/skills/ops/deploy/SKILL.md");
let deep_named_skills = ws.join("a/b/c/.claude/skills/skills/SKILL.md");
let shallow_clash = ws.join("pkg/.agents/skills/shared/SKILL.md");
let deep_clash = ws.join("a/b/c/.github/skills/shared/SKILL.md");
let depth3_clash = ws.join("x/y/z/.github/skills/depth-race/SKILL.md");
let depth4_clash = ws.join("x/y/z/w/.agents/skills/depth-race/SKILL.md");
let fixture_skill = ws.join("crates/ide-plugin/tests/fixtures/agent-skills/skills/fixture-only/SKILL.md");
let hidden_dir_skill = ws.join(".worktrees/branch/.github/skills/wt-only/SKILL.md");
let target_dir_skill = ws.join("crates/app/target/gen/.github/skills/build-only/SKILL.md");
write(&deep_grafana, "---\nname: edit-grafana-dashboards\ndescription: Edit Grafana dashboards\n---\n");
write(&deep_category, "---\nname: deploy\ndescription: Deploy service\n---\n");
write(&deep_named_skills, "---\nname: skills\ndescription: Skill named skills\n---\n");
write(&shallow_clash, "---\nname: shared\ndescription: Shallow copy\n---\n");
write(&deep_clash, "---\nname: shared\ndescription: Deep copy\n---\n");
write(&depth3_clash, "---\nname: depth-race\ndescription: Depth 3 wins\n---\n");
write(&depth4_clash, "---\nname: depth-race\ndescription: Depth 4 loses\n---\n");
write(&fixture_skill, "---\nname: fixture-only\ndescription: Fixture not under a skill root\n---\n");
write(&hidden_dir_skill, "---\nname: wt-only\ndescription: Inside hidden dir\n---\n");
write(&target_dir_skill, "---\nname: build-only\ndescription: Inside target dir\n---\n");
// Without indexed files, depth-3+ packages are beyond the 2-level direct walk.
let shallow_only = discover_skills(&ws, None);
assert!(shallow_only.iter().all(|s| s.name != "edit-grafana-dashboards"));
assert!(shallow_only.iter().any(|s| s.name == "shared" && s.description == "Shallow copy"));
// Passing indexed `SKILL.md` paths (even in reversed depth order) surfaces deep skills
// while keeping shallow-over-deep precedence and ignoring fixtures/hidden/build dirs.
let indexed = vec![
depth4_clash,
depth3_clash,
deep_clash,
deep_grafana,
deep_category,
deep_named_skills,
fixture_skill,
hidden_dir_skill,
target_dir_skill,
];
let found = discover_skills_with_indexed_files(std::slice::from_ref(&ws), None, &[], &[], &indexed);
let by = |n: &str| found.iter().find(|s| s.name == n);
let grafana = by("edit-grafana-dashboards").expect("depth-3 .github/skills discovered");
assert_eq!(grafana.source, AgentSkillSource::GithubWorkspace);
assert!(by("deploy").is_some(), "category skill under depth-3 package discovered");
assert!(by("skills").is_some(), "skill named `skills` under depth-3 package discovered");
assert_eq!(by("shared").unwrap().description, "Shallow copy", "shallow package beats deep package");
assert_eq!(by("depth-race").unwrap().description, "Depth 3 wins", "depth 3 beats depth 4");
assert!(by("fixture-only").is_none(), "unrelated fixture SKILL.md ignored");
assert!(by("wt-only").is_none(), "hidden directory tree ignored");
assert!(by("build-only").is_none(), "SKIP_MONOREPO_DIRS tree ignored");
}
}
+510 -7
Переглянути файл
@@ -65,10 +65,16 @@ struct FakeAgent {
mcp_calls: Mutex<Vec<(String, Vec<String>)>>,
/// The params of every `session/fork`, in order.
forks: Mutex<Vec<Value>>,
/// Cuts a fork at `_meta.openidea.forkTurns` itself, as the native agents do.
cuts_forks: bool,
/// The content blocks of each `session/prompt`.
prompts: Mutex<Vec<Value>>,
/// Queued errors returned on the next `session/prompt` calls before succeeding.
prompt_errors: Mutex<VecDeque<(i64, String)>>,
/// Number of prompts that stream Cursor's capacity diagnostic before returning end_turn.
capacity_errors: Mutex<u32>,
/// Queued errors returned on the next session-open calls before succeeding.
open_errors: Mutex<VecDeque<(i64, String, Option<Value>)>>,
/// Recorded `(method, _meta.openidea.memory)` payloads across `session/new`, `session/load`, and `session/fork`.
memory_calls: Mutex<Vec<(String, Option<Value>)>>,
}
@@ -150,6 +156,12 @@ impl Handler for FakeAgent {
let data = json!({"openidea": {"usageLimit": {"resetsAtMs": 1234.0}}});
return Err((codes::INTERNAL_ERROR, "You've hit your usage limit".into(), Some(data)));
}
if matches!(method, "session/new" | "session/load" | "session/fork")
&& let Some(err) = self.open_errors.lock().pop_front()
{
self.calls.lock().push(method.to_owned());
return Err(err);
}
self.on_request(method, params).map_err(|(code, message)| (code, message, None))
}
@@ -220,7 +232,13 @@ impl Handler for FakeAgent {
"session/fork" => {
self.forks.lock().push(params.clone());
let requested = params.pointer("/_meta/openidea/forkSessionId").and_then(Value::as_str);
Ok(json!({ "sessionId": requested.unwrap_or("s2") }))
let mut reply = json!({ "sessionId": requested.unwrap_or("s2") });
if self.cuts_forks
&& let Some(turns) = params.pointer("/_meta/openidea/forkTurns")
{
reply["_meta"] = json!({ "openidea": { "forkTurns": turns } });
}
Ok(reply)
}
"_openidea/stop_task" => {
self.calls.lock().push(format!("{method} {}", params["taskId"]));
@@ -289,6 +307,22 @@ impl Handler for FakeAgent {
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
{
let mut remaining = self.capacity_errors.lock();
if *remaining > 0 {
*remaining -= 1;
if text == "edit once" {
self.update(
&session,
json!({"sessionUpdate": "tool_call", "toolCallId": "edit",
"title": "Edit file", "kind": "edit", "status": "completed"}),
);
}
self.say(&session, "\n\nError: RetriableError: ");
self.say(&session, "[resource_exhausted] Error");
return Ok(json!({"stopReason": "end_turn"}));
}
}
if text.starts_with("The previous turn was interrupted because ") {
self.say(&session, "resumed cleanly");
return Ok(json!({"stopReason": "end_turn"}));
@@ -629,6 +663,30 @@ async fn subscribers_do_not_replace_or_close_each_other() {
mgr.shutdown();
}
#[tokio::test]
async fn detach_ui_sinks_preserves_internal_host_subscribers() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let ui = Arc::new(Mutex::new(Vec::new()));
let watcher = Arc::new(Mutex::new(Vec::new()));
let subscribe = |key: &str, events: &Arc<Mutex<Vec<AgentEvent>>>| {
let events = events.clone();
mgr.subscribe_as(key, Arc::new(move |event| events.lock().push(event)));
};
subscribe("main", &ui);
subscribe("__automation_watch_run1", &watcher);
mgr.detach_ui_sinks();
mgr.shared.emit(AgentEvent::Providers);
assert_eq!(ui.lock().len(), 0, "UI window sink must be detached");
assert_eq!(watcher.lock().len(), 1, "internal __-prefixed automation watcher must stay attached");
mgr.detach_sinks();
mgr.shared.emit(AgentEvent::Providers);
assert_eq!(watcher.lock().len(), 1, "detach_sinks clears all remaining sinks");
mgr.shutdown();
}
fn manager_at(dir: &Path, models_file: &Path, agent: Arc<FakeAgent>) -> AgentManager {
// These tests speak to FakeAgent, never an installed CLI, including after a provider reload.
let agents = dir.join("agents");
@@ -648,6 +706,7 @@ fn manager_at(dir: &Path, models_file: &Path, agent: Arc<FakeAgent>) -> AgentMan
store_dir: dir.join("store"),
worktrees_dir: dir.join("worktrees"),
models_file: models_file.to_path_buf(),
cli_dir: dir.join("agent-cli"),
custom_agents_dir: Some(agents),
// The project is the boundary of the skill walk: nothing above it (such as the
// user's profile, when temp lives under it) leaks into the test.
@@ -2248,6 +2307,175 @@ async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
mgr.shutdown();
}
fn warming_up_error() -> (i64, String, Option<Value>) {
(
codes::INTERNAL_ERROR,
"Internal error: Internal service failure".to_owned(),
Some(json!({"errorName": "ServiceUnavailableError"})),
)
}
#[tokio::test(flavor = "multi_thread")]
async fn session_open_retries_while_the_agent_finishes_starting_up() {
// OpenCode rejects session opens until its plugins and MCP servers finish activating.
let tmp = tempfile::tempdir().unwrap();
let agent =
Arc::new(FakeAgent { open_errors: Mutex::new(VecDeque::from([warming_up_error()])), ..Default::default() });
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/new").count(), 2, "retried the startup race");
let saved = mgr.task(&task.id).unwrap().state.lock().session_id.clone().expect("a session");
mgr.shutdown();
// The same race when reopening a saved session.
let agent =
Arc::new(FakeAgent { open_errors: Mutex::new(VecDeque::from([warming_up_error()])), ..Default::default() });
let mgr = manager(tmp.path(), agent.clone());
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/load").count(), 2, "retried the startup race");
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some(saved.as_str()));
mgr.shutdown();
}
async fn wait_for_session_open_attempts(agent: &FakeAgent, method: &str, attempts: usize) {
tokio::time::timeout(Duration::from_secs(5), async {
while agent.calls.lock().iter().filter(|call| call.as_str() == method).count() < attempts {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("agent received the session-open requests");
}
#[tokio::test]
async fn retry_after_warmup_expires_loads_the_saved_session_again() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let saved = mgr.task(&task.id).unwrap().state.lock().session_id.clone().unwrap();
mgr.shutdown();
let agent = Arc::new(FakeAgent {
open_errors: Mutex::new(std::iter::repeat_with(warming_up_error).take(16).collect()),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for_session_open_attempts(&agent, "session/load", 2).await;
tokio::time::pause();
tokio::time::advance(WARMUP_WINDOW - WARMUP_DELAY * 2).await;
tokio::time::resume();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
assert!(mgr.entries(&task.id, None).unwrap().iter().any(|entry| matches!(
entry, AgentEntry::Error { message } if message.contains("Try again") && !message.contains("new session")
)));
agent.open_errors.lock().clear();
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert!(!agent.calls.lock().iter().any(|call| call == "session/new"));
let handle = mgr.task(&task.id).unwrap();
assert_eq!(handle.live.lock().as_ref().unwrap().session, saved);
mgr.shutdown();
}
#[tokio::test]
async fn a_stalled_warmup_retry_times_out_and_closes_the_connection() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent {
open_errors: Mutex::new(VecDeque::from([warming_up_error()])),
hold_session_new: AtomicBool::new(true),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for_session_open_attempts(&agent, "session/new", 2).await;
tokio::time::pause();
tokio::time::advance(WARMUP_WINDOW).await;
tokio::time::resume();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
assert!(mgr.entries(&task.id, None).unwrap().iter().any(|entry| matches!(
entry, AgentEntry::Error { message } if message.contains("timed out")
)));
tokio::time::timeout(Duration::from_secs(5), agent.latest().closed())
.await
.expect("the timed-out connection closes");
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn session_open_authenticates_after_a_warmup_reply() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent {
open_errors: Mutex::new(VecDeque::from([warming_up_error()])),
auth_on_new: true,
authenticate_method: Some("agent_login".into()),
auth_methods: vec![json!({"id": "agent_login", "name": "Sign in"})],
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let calls = agent.calls.lock();
let setup: Vec<_> = calls
.iter()
.map(String::as_str)
.filter(|call| call.starts_with("session/") || call.starts_with("authenticate"))
.collect();
assert_eq!(
setup,
["session/new", "session/new", "authenticate", "authenticate agent_login", "session/new", "session/prompt"]
);
drop(calls);
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn session_open_does_not_retry_unrelated_internal_errors() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent {
open_errors: Mutex::new(VecDeque::from([(
codes::INTERNAL_ERROR,
"Internal error: Internal service failure".into(),
Some(json!({"errorName": "SQLiteError"})),
)])),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/new").count(), 1, "no retry on a real failure");
mgr.shutdown();
}
fn text(t: &str) -> AgentPrompt {
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
}
@@ -2628,7 +2856,12 @@ async fn subagents_get_their_own_conversation() {
#[test]
fn image_blocks_declare_the_type_of_their_bytes() {
let image = |mime: &str, data: &str| AgentImage { mime_type: mime.into(), data: data.into(), name: None };
let image = |mime: &str, data: &str| AgentImage {
mime_type: mime.into(),
data: data.into(),
name: None,
inline_number: None,
};
let cases = [
// A browser's JPEG pasted as PNG.
(image("image/png", "/9j/4AAQSkZJRgABAQ"), "image/jpeg"),
@@ -2650,7 +2883,7 @@ fn prompts_become_acp_content_blocks() {
let p = AgentPrompt {
text: "look".into(),
files: vec![IpcPath(PathBuf::from("/p/my file.rs"))],
images: vec![AgentImage { mime_type: "image/png".into(), data: "AAA".into(), name: None }],
images: vec![AgentImage { mime_type: "image/png".into(), data: "AAA".into(), name: None, inline_number: None }],
};
assert_eq!(
blocks(&p, &[]),
@@ -2682,6 +2915,32 @@ fn prompts_become_acp_content_blocks() {
assert!(clean(text(" ")).is_none());
}
#[test]
fn inline_images_are_distinct_content_blocks_in_text_order() {
let older: AgentImage = serde_json::from_value(json!({"mimeType":"image/png", "data":"AAA", "name":null})).unwrap();
assert!(older.inline_number.is_none());
let image = |number, data: &str| AgentImage {
mime_type: "image/png".into(),
data: data.into(),
name: None,
inline_number: Some(number),
};
let prompt = AgentPrompt {
text: "😀 [Image #2] then [Image #1] and [Image #99]".into(),
images: vec![image(1, "AAA"), image(2, "BBB"), image(3, "CCC")],
..Default::default()
};
let content = blocks(&prompt, &[]);
assert_eq!(content.len(), 5);
assert_eq!(content[0], json!({"type": "text", "text": "😀 "}));
assert_eq!(content[1]["type"], "image");
assert_eq!(content[1]["data"], "BBB");
assert_eq!(content[2], json!({"type": "text", "text": " then "}));
assert_eq!(content[3]["type"], "image");
assert_eq!(content[3]["data"], "AAA");
assert_eq!(content[4], json!({"type": "text", "text": " and [Image #99]"}));
}
#[tokio::test(flavor = "multi_thread")]
async fn claude_questions_keep_the_answer_object_as_the_option_id() {
let tmp = tempfile::tempdir().unwrap();
@@ -2911,6 +3170,7 @@ async fn real_claude_task_in_a_worktree() {
store_dir: tmp.path().join("store"),
worktrees_dir: tmp.path().join("wt"),
models_file: tmp.path().join("models.json"),
cli_dir: tmp.path().join("agent-cli"),
custom_agents_dir: None,
home_dir: None,
env_secrets: None,
@@ -3254,6 +3514,62 @@ fn plant_claude_session(mgr: &AgentManager, root: &Path, session_id: &str) {
.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn forks_a_running_task_up_to_its_finished_turns() {
for cuts_forks in [false, true] {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent { cuts_forks, ..Default::default() });
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.prompt(&task.id, text("wait"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Running).await;
// The running turn stays behind, whatever was asked for.
for turns in [None, Some(2)] {
let copy = mgr.fork(&task.id, turns).await.unwrap();
assert_eq!(copy.status, AgentStatus::Ready);
let entries = mgr.entries(&copy.id, None).unwrap();
assert_eq!(turn_starts(&entries).len(), 1);
assert!(!entries.iter().any(|e| matches!(e, AgentEntry::User { text, .. } if text == "wait")));
let pending = mgr.task(&copy.id).unwrap().state.lock().pending_rollback;
assert_eq!(pending, if cuts_forks { 0 } else { 1 });
assert_eq!(agent.forks.lock().last().unwrap().pointer("/_meta/openidea/forkTurns"), Some(&json!(1)));
}
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Running);
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_running_first_turn_cannot_be_forked() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("wait"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Running).await;
assert!(mgr.fork(&task.id, None).await.is_err());
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_starts_a_ready_task_as_the_recorded_session_s_fork() {
let tmp = tempfile::tempdir().unwrap();
@@ -3350,6 +3666,79 @@ async fn imports_copilot_sessions_and_loads_their_history() {
mgr.shutdown();
}
fn session_calls(agent: &FakeAgent) -> Vec<String> {
agent.calls.lock().iter().filter(|c| c.starts_with("session/")).cloned().collect()
}
/// Imports a claude session whose load fails, which leaves what a quit during the load leaves
/// too: a task that holds the recorded session but no conversation.
async fn import_without_history(dir: &Path) -> String {
let agent = Arc::new(FakeAgent {
load_error: Some((codes::INTERNAL_ERROR, "Claude Code exited".into())),
..Default::default()
});
let mgr = manager(dir, agent.clone());
let _down = ShutDown(&mgr);
plant_claude_session(&mgr, dir, NATIVE_SOURCE);
let id = mgr.import_session("claude", NATIVE_SOURCE).unwrap().id;
for _ in 0..300 {
if !session_calls(&agent).is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(session_calls(&agent), ["session/load"]);
assert_eq!(saved_task(&task_file(dir, &id)).unwrap().1, 0);
id
}
#[tokio::test(flavor = "multi_thread")]
async fn an_imported_task_without_its_history_loads_it_when_shown() {
let tmp = tempfile::tempdir().unwrap();
let id = import_without_history(tmp.path()).await;
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let _down = ShutDown(&mgr);
for _ in 0..300 {
if !mgr.entries(&id, None).unwrap().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let entries = mgr.entries(&id, None).unwrap();
assert!(matches!(&entries[0], AgentEntry::User { text, .. } if text == "earlier question"), "{entries:?}");
assert_eq!(session_calls(&agent), ["session/load"], "loaded once, however often it is shown");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_failed_history_load_leaves_the_new_session_to_the_user() {
let tmp = tempfile::tempdir().unwrap();
let id = import_without_history(tmp.path()).await;
let agent = Arc::new(FakeAgent {
load_error: Some((codes::INTERNAL_ERROR, "no conversation found".into())),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
let _down = ShutDown(&mgr);
mgr.entries(&id, None).unwrap();
for _ in 0..300 {
if !session_calls(&agent).is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
mgr.entries(&id, None).unwrap();
assert_eq!(session_calls(&agent), ["session/load"], "tried once in this run");
mgr.prompt(&id, text("again"), false).await.unwrap();
wait_for(&mgr, &id, AgentStatus::Failed).await;
assert_eq!(session_calls(&agent), ["session/load", "session/load"], "no new session behind the user's back");
assert!(mgr.entries(&id, None).unwrap().iter().any(|e| matches!(e,
AgentEntry::Error { message } if message.contains("Send the message again"))));
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_uses_the_id_codex_assigns() {
let tmp = tempfile::tempdir().unwrap();
@@ -4295,6 +4684,7 @@ async fn reload_providers_updates_registry_install_clears_stale_probes_and_notif
store_dir: tmp.path().join("store"),
worktrees_dir: tmp.path().join("worktrees"),
models_file: tmp.path().join("models.json"),
cli_dir: tmp.path().join("agent-cli"),
custom_agents_dir: Some(agents_dir.clone()),
home_dir: None,
env_secrets: None,
@@ -4360,6 +4750,7 @@ async fn a_failed_probe_is_retried_instead_of_remembered() {
store_dir: tmp.path().join("store"),
worktrees_dir: tmp.path().join("worktrees"),
models_file: tmp.path().join("models.json"),
cli_dir: tmp.path().join("agent-cli"),
custom_agents_dir: None,
home_dir: None,
env_secrets: None,
@@ -4623,6 +5014,7 @@ async fn delete_running_agent(no_load: bool) {
store_dir: root.join("store"),
worktrees_dir: root.join("worktrees"),
models_file: root.join("models.json"),
cli_dir: root.join("agent-cli"),
custom_agents_dir: None,
home_dir: None,
env_secrets: None,
@@ -4680,14 +5072,21 @@ async fn delete_running_agent(no_load: bool) {
fn mcp_servers_follow_server_state_and_agent_capabilities() {
let root = std::path::Path::new("/project");
let exe = std::path::Path::new("/app/openidea");
assert!(super::stdio_mcp_servers(None, true, root).is_empty());
assert!(super::stdio_mcp_servers(Some(exe), false, root).is_empty());
let servers = super::stdio_mcp_servers(Some(exe), true, root);
assert!(super::stdio_mcp_servers(None, true, root, None).is_empty());
assert!(super::stdio_mcp_servers(Some(exe), false, root, None).is_empty());
let servers = super::stdio_mcp_servers(Some(exe), true, root, None);
assert_eq!(
servers,
vec![json!({"name":"OpenIDEA","command":"/app/openidea",
"args":["--mcp-stdio","--project","/project"],"env":[]})]
);
let nonce_servers = super::stdio_mcp_servers(Some(exe), true, root, Some("nonce_secret_abc"));
assert_eq!(
nonce_servers,
vec![json!({"name":"OpenIDEA","command":"/app/openidea",
"args":["--mcp-stdio","--project","/project"],
"env":[{"name": ide_mcp::SESSION_NONCE_ENV, "value":"nonce_secret_abc"}]})]
);
}
#[tokio::test(flavor = "multi_thread")]
@@ -4952,7 +5351,7 @@ fn a_running_tools_output_is_sent_as_appends() {
// An image the tool returned is not part of the appended text: it goes with the whole entry.
let mut shown = titled.clone();
if let AgentEntry::Tool { images, output, .. } = &mut shown {
images.push(AgentImage { mime_type: "image/png".into(), data: "AAAA".into(), name: None });
images.push(AgentImage { mime_type: "image/png".into(), data: "AAAA".into(), name: None, inline_number: None });
output.as_mut().unwrap().push('!');
}
let imaged = event(&mut streamed, None, 2, &shown).unwrap();
@@ -6128,6 +6527,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
unapproved: false,
plugin_id: None,
plugin_name: None,
registry_name: None,
registry_url: None,
},
McpServer {
id: "user::slack".into(),
@@ -6144,6 +6545,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
unapproved: false,
plugin_id: None,
plugin_name: None,
registry_name: None,
registry_url: None,
},
]
}));
@@ -6450,6 +6853,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
store_dir: dir.join("store"),
worktrees_dir: dir.join("worktrees"),
models_file: dir.join("models.json"),
cli_dir: dir.join("agent-cli"),
custom_agents_dir: None,
home_dir: None,
env_secrets: None,
@@ -6573,6 +6977,7 @@ done
store_dir: tmp.path().join("store"),
worktrees_dir: tmp.path().join("worktrees"),
models_file: tmp.path().join("models.json"),
cli_dir: tmp.path().join("agent-cli"),
custom_agents_dir: Some(agents_dir),
home_dir: None,
env_secrets: None,
@@ -7055,6 +7460,85 @@ async fn transient_network_outage_probes_with_zero_prompts_and_auto_resumes_when
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_capacity_retry_pauses_after_three_continuations_and_resumes_on_request() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.capacity_errors.lock() = 4;
let mgr = manager(tmp.path(), agent.clone());
let _down = ShutDown(&mgr);
let task = mgr
.create(NewAgentTask { provider: "cursor".into(), prompt: text("edit once"), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let handle = mgr.task(&task.id).unwrap();
let snap = handle.state.lock().snapshot();
assert_eq!(snap.interrupted.unwrap().reason, InterruptionReason::CursorCapacity);
assert!(snap.retry.is_none());
let entries = mgr.entries(&task.id, None).unwrap();
let attempts: Vec<_> = entries
.iter()
.filter_map(|e| match e {
AgentEntry::User { retry_attempt, .. } => *retry_attempt,
_ => None,
})
.collect();
assert_eq!(attempts, [1, 2, 3]);
assert_eq!(entries.iter().filter(|e| matches!(e, AgentEntry::Tool { .. })).count(), 1);
assert_eq!(agent.prompts.lock().len(), 4);
mgr.resume(&task.id).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert!(handle.state.lock().task.interrupted.is_none());
assert_eq!(agent.prompts.lock().len(), 5);
assert!(
agent
.prompts
.lock()
.iter()
.skip(1)
.all(|p| p[0]["text"].as_str().unwrap().contains("Inspect the current workspace"))
);
assert!(
matches!(mgr.entries(&task.id, None).unwrap().last(), Some(AgentEntry::Agent { text }) if text == "resumed cleanly")
);
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_capacity_retry_can_be_stopped_or_replaced_during_backoff() {
for send_now in [false, true] {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.capacity_errors.lock() = 1;
let mgr = manager(tmp.path(), agent.clone());
let _down = ShutDown(&mgr);
let task = mgr
.create(NewAgentTask { provider: "cursor".into(), prompt: text("edit once"), ..Default::default() })
.await
.unwrap();
let handle = mgr.task(&task.id).unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
while handle.state.lock().task.retry.is_none() {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.unwrap();
let retry = handle.state.lock().task.retry.clone().unwrap();
assert_eq!((retry.attempt, retry.max_retries, retry.deadline_ms), (1, Some(3), None));
if !send_now {
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.prompts.lock().len(), 1);
assert!(handle.state.lock().task.retry.is_none());
}
mgr.prompt(&task.id, text("again"), send_now).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.prompts.lock().len(), 2);
assert_eq!(agent.prompts.lock()[1][0]["text"], "again");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn network_outage_window_off_or_expired_degrades_to_interrupted_and_auth_errors_fail_fast() {
use ide_core::settings::{NetworkRetryWindow, ResumeInterruptedPolicy};
@@ -7144,3 +7628,22 @@ async fn metadata_edits_do_not_bump_updated_ms() {
.unwrap();
assert_eq!(after_memory.updated_ms, fixed_ms);
}
/// An automation reads the status as soon as its prompt is accepted: the previous turn's
/// `Ready` would complete the run before its turn started.
#[tokio::test]
async fn an_accepted_scheduled_prompt_no_longer_reads_as_ready() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let _down = ShutDown(&mgr);
let task = mgr
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.prompt_scheduled(&task.id, text("again"), ScheduledTurnMeta::default()).await.unwrap();
// The single-threaded runtime has not started the spawned turn yet.
assert_eq!(mgr.task_snapshot(&task.id).unwrap().status, AgentStatus::Starting);
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
}
+3 -1
Переглянути файл
@@ -523,7 +523,7 @@ mod tests {
t.apply(&update);
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "status": "completed"}));
let AgentEntry::Tool { images, output, status, .. } = &t.entries[0] else { panic!() };
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None }]);
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None, inline_number: None }]);
assert!(output.as_ref().unwrap().len() < MAX_OUTPUT + 100);
assert_eq!(*status, AgentToolStatus::Completed);
let saved = serde_json::to_string(&t.entries[0]).unwrap();
@@ -646,6 +646,7 @@ mod tests {
done_ms: None,
steered: false,
recovery: None,
retry_attempt: None,
};
let mut t = Timeline::default();
t.push(user(1.0));
@@ -668,6 +669,7 @@ mod tests {
done_ms: None,
steered,
recovery: None,
retry_attempt: None,
};
let mut t = Timeline::default();
t.push(user(1.0, false));
+107 -111
Переглянути файл
@@ -1,112 +1,108 @@
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6"]}
{"from":"shim","msg":{"request":{"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","feedback_mode":{"kind":"post"},"ide_rc_auto_enable_gate":true,"models":[{"description":"Sonnet 5.5 · Efficient for routine tasks","displayName":"Default (recommended)","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.1","resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","resolvedModel":"claude-sonnet-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-4-6"}],"pid":23982,"remote_control_auto_connect_default":false,"remote_control_auto_enable":false,"remote_control_auto_on_by_default":false,"remote_control_available":true,"session_state":"idle"},"subtype":"success"},"type":"control_response"}}
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","a89e008b-23b6-41ea-bebb-612440f38e3c"]}
{"from":"shim","msg":{"request":{"perTaskStopAffordance":true,"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1"],"claude_code_version":"2.1.335","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_state":"off","feedback_mode":{"kind":"post"},"hook_on_failure_supported":true,"hooks_when_unanswered_kept":0,"ide_rc_auto_enable_gate":true,"models":[{"description":"Opus 5.5 · Best for everyday, complex tasks","displayName":"Default (recommended)","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.2","resolvedModel":"claude-fable-5-2","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5.1","overflow":true,"resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5-1"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","overflow":true,"resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","overflow":true,"resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","overflow":true,"resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","overflow":true,"resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","overflow":true,"resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","overflow":true,"resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","overflow":true,"resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","overflow":true,"resolvedModel":"claude-sonnet-4-6","supportedEffortLevelsLine truncated
{"from":"shim","msg":{"request":{"subtype":"get_settings"},"request_id":"req_2","type":"control_request"}}
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"effort":"medium","model":"claude-haiku-5-5","ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false},"effective":{"model":"opus"}},"subtype":"success"},"type":"control_response"}}
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 3 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace"}}
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"running","subtype":"session_state_changed","type":"system","uuid":"5e39fde0-9f18-47f0-8b7e-21007ec957c0"}}
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"queued","type":"command_lifecycle","uuid":"ad1291e3-8d79-4048-a10c-599eafd30c9b"}}
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"started","type":"command_lifecycle","uuid":"0ed63980-6c4a-40b9-b94d-3bc062cddd58"}}
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","output_style":"Concise","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"init","terminal_slash_commands":["doctor","color","focus","reload-plugins"],"type":"system","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"17b7ad4c-6ad3-4d9c-aeef-2e027b0d75ae","view_mode":"default"}}
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"requesting","subtype":"status","type":"system","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"7b8f8fcd-669e-4606-ad6f-3368116e7a75"}}
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"org_level_disabled","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1793203800,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1793203800,"status":"allowed","utilization":0.31},"seven_day":{"resetsAt":1793631600,"status":"allowed","utilization":0.32}}},"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"rate_limit_event","uuid":"b3ef3e2a-11ad-46f9-8ea5-fd01f8d0fe39"}}
{"from":"cli","msg":{"commands":[{"argumentHint":"","description":"Review a pull request","name":"review"}],"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"commands_changed","type":"system","uuid":"5f60f663-94ff-4885-9167-b12cae835fca"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CgUhj5mGEZkoUv4HmADLr","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","ttft_ms":1661,"type":"stream_event","user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"4fb86b8a-bfa9-439b-b46b-6ef6e381d243"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","input":{},"name":"Bash","type":"tool_use"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"0bc16cbc-fcbb-4d52-bd5b-4d864b307bbd"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"0510612a-2068-496a-85f4-f61706fb8cd5"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"{\"command\": \"sleep 3","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"281a35ac-8285-4591-8c60-5ddc743b7036"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":" && echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"44c02159-084d-48d1-a23c-5bd3628e69e7"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"ca641c1e-c60b-4943-a07b-9ea03c9b8845"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"leep 3 se","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"bc5c34f0-653a-4041-a6cf-42c0dcd0fc2c"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"conds then echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"00cd396e-f45d-4b60-b484-9fb0ddfc3384"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"6987c232-0dbf-43be-83fe-2164d6d701ee"}}
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","input":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhj5mGEZkoUv4HmADLr","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhj5SvXJc5aP46FPBxn","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:00.931Z","type":"assistant","user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"b7befa90-ef05-44ff-9822-ec00f61130b2","wire_tool_inputs":{"toolu_01RLgKZhL3rEQrnb6R4yD7LH":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"}}}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"01897941-b66d-4657-a87b-14dde2420f38"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0}}},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"daf07992-fd3c-46c2-8fe7-3014bf6e6cf0"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"6c4b9511-1539-45a7-9184-9efc1ce9384d"}}
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"now","session_id":"","type":"user","uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee"}}
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"queued","type":"command_lifecycle","uuid":"6ae9f6be-c8d5-4feb-8c17-71bfc3d4880e"}}
{"from":"cli","msg":{"description":"Sleep 3 seconds then echo done","is_backgrounded":false,"run_id":"0mvs568cx-76274178","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"task_started","task_id":"bk6c5st9v","task_type":"local_bash","tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"system","uuid":"e45f0b55-eb72-4cc6-8bb7-0ba207583cc7"}}
{"from":"cli","msg":{"output_file":"","run_id":"0mvs568cx-76274178","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"completed","subtype":"task_notification","summary":"Sleep 3 seconds then echo done","task_id":"bk6c5st9v","tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"system","uuid":"0d23dced-54be-49b0-963b-a9e67ae4b75c"}}
{"from":"cli","msg":{"message":{"content":[{"content":"done","is_error":false,"tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:04.328Z","tool_result_meta":[{"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","permission_decision":{"decision":"accept","reason_type":"subcommandResults","source":"config"}}],"tool_use_result":{"interrupted":false,"isImage":false,"noOutputExpected":false,"stderr":"","stdout":"done"},"type":"user","uuid":"998e4d6c-47bf-4e81-b630-1eb86398d192"}}
{"from":"cli","msg":{"api_error_status":null,"duration_api_ms":2891,"duration_ms":5544,"fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","first_content_frame_ms":1797,"first_request_input_tokens":29936,"is_error":false,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":15110,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":15110,"cacheReadInputTokens":14824,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0033443400000000003,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":15110,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":15110,"cacheReadInputTokens":14824,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0033443400000000003,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"num_turns":2,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":1,"request_sent_wall_ms":1793193598927,"result":"","result_index":0,"safety_stops":0,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","stop_reason":"tool_use","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"aborted_tools","time_to_request_ms":138,"total_cost_usd":0.0033443400000000003,"ttft_ms":2142,"ttft_stream_ms":1797,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"a4afa59a-be05-41e3-bc85-4cc8e9b28506"}}
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"cancelled","type":"command_lifecycle","uuid":"4911bef5-6b3d-4c0e-803e-5f21202ce766"}}
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"started","type":"command_lifecycle","uuid":"89c8590f-1c08-4183-b430-5e888745fbfc"}}
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","output_style":"Concise","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"init","terminal_slash_commands":["doctor","color","focus","reload-plugins"],"type":"system","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"a05d013f-558f-4581-9ac1-49e4329e9d7d","view_mode":"default"}}
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"requesting","subtype":"status","type":"system","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"d00d3b7f-227d-4373-9092-676090723763"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","ttft_ms":1500,"type":"stream_event","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"c634f9c8-ff1c-44fa-9138-5d357a418f58"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0db4c93b-e0cb-4fcf-857f-c79fed9a2609"}}
{"from":"cli","msg":{"estimated_tokens":1,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"e7d95fb9-826f-45e1-8e7c-4e6abcdef7c9"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"27c0c433-3ee8-42fc-830a-90d67cb371d1"}}
{"from":"cli","msg":{"estimated_tokens":2,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"cc8a606b-0251-4927-96c5-160880f430f6"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" s","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"1c859e8c-52fe-4fb3-8ad1-0122752cdccf"}}
{"from":"cli","msg":{"estimated_tokens":5,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"202bcadf-3533-4744-a259-97bfc7bef0e3"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"leep task","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2a273607-1f22-4a49-860c-30184e6bfe01"}}
{"from":"cli","msg":{"estimated_tokens":9,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"63d703f5-6eec-4a89-a6c7-c38245001004"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" completed with","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"dba1141d-78a3-406a-9125-bf02b5b4a2a3"}}
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"2618ae50-9e26-4724-89f6-7fda1f105f42"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" output \"done.\"","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"ba6f0b4d-aa70-4347-903e-46119eaa15e6"}}
{"from":"cli","msg":{"estimated_tokens":16,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"beaeb52e-0825-47b9-ba7e-e09d6de4818c"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" The user as","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"3408f5ca-fe05-4bbf-8ae0-b1bc4db97033"}}
{"from":"cli","msg":{"estimated_tokens":18,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"b5f0f099-f629-469e-a51b-bcb1abaf5f66"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ked me","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"32b263d1-ff54-48f3-a61d-96e98eddce23"}}
{"from":"cli","msg":{"estimated_tokens":22,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"581160fb-90e0-4831-b087-d702a7a42fa4"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" to end my answ","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"af0f7710-cb0d-4192-85b6-2a458a17a463"}}
{"from":"cli","msg":{"estimated_tokens":25,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1ea97064-de2c-4b80-9f32-09ce3a9ce60b"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"er with the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"ad449330-cf10-4919-b4a0-9f510c259d38"}}
{"from":"cli","msg":{"estimated_tokens":28,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"9c7d8148-ced4-4647-bdb0-fca91d88aab9"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" word BAN","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2e4fed14-2110-4d2c-81d0-033f66954ed6"}}
{"from":"cli","msg":{"estimated_tokens":29,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"dea229d8-9c12-4bf9-9cea-bf9813d41840"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"AN","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"a4c1bb86-c884-4f6b-b752-3d57bbb36b1c"}}
{"from":"cli","msg":{"estimated_tokens":31,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1cbe8e9c-f44c-4dfb-b6e0-8032d35991db"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"A, which","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0a79f76a-a558-4de1-8323-7547d8628d28"}}
{"from":"cli","msg":{"estimated_tokens":34,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1961a504-ee75-484f-9c2d-8418496ff795"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" is a har","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"5fa188a2-6e70-4af5-8900-13c30c78c7ad"}}
{"from":"cli","msg":{"estimated_tokens":41,"estimated_tokens_delta":7,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"a4d053b7-4485-4d18-8fd2-2354b2a22310"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"mless request, and there's a","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"d734fe28-ce41-4002-ad2f-ea0dbc0857a0"}}
{"from":"cli","msg":{"estimated_tokens":43,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"7fa6189b-3633-4814-9755-a93619616466"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" note","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"6dfd60d4-172b-456e-bb66-4f2d6c966233"}}
{"from":"cli","msg":{"estimated_tokens":45,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"4aa94d3f-16be-48dc-aa05-1a85105921bb"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" about","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"9eb2805d-f684-40ee-b368-468facc4890a"}}
{"from":"cli","msg":{"estimated_tokens":47,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"992053c7-e234-4d72-9c11-d00786dd2c52"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" repl","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"10f0c715-33ad-44fc-8818-7d1a4549fef3"}}
{"from":"cli","msg":{"estimated_tokens":49,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"e1dad1ff-ec95-4ce1-b07b-b3b42c5f0a15"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ying in","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"244ce6fc-4dfd-4f6e-abf5-57f860663fdc"}}
{"from":"cli","msg":{"estimated_tokens":54,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"6f4e3a68-8a38-4ef1-a1d8-5d16b0bdb9e0"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" Chinese per inst","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"6fce552c-bfa4-4705-b50e-1e162b487f9d"}}
{"from":"cli","msg":{"estimated_tokens":58,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"491e90c9-da11-4f2f-96d1-2e6c501a13b9"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ructions, but","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"cee9edc1-dac1-4997-9b0e-a64e6cc17173"}}
{"from":"cli","msg":{"estimated_tokens":61,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"2ad92491-7893-4f66-9f8c-8e0c49a0dd21"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" the user w","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0d10f6b1-daf3-4c40-92cc-78a3b7addc0d"}}
{"from":"cli","msg":{"estimated_tokens":65,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"48d2ff82-0a78-43f7-bd6e-41170fd9be53"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"rote in English—","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"7af06734-f004-4264-aa76-0e5404fb1da7"}}
{"from":"cli","msg":{"estimated_tokens":66,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"a607027c-4b06-467b-bd39-99a40085c05b"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"I","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"f651bfee-b7bb-4d2f-8872-bc43aff55c2b"}}
{"from":"cli","msg":{"estimated_tokens":72,"estimated_tokens_delta":6,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"862b7d4a-8d66-48ce-a954-764541537982"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"'ll decide how to handle","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"f9a8266d-7203-49f1-b14e-cdbcd5311bda"}}
{"from":"cli","msg":{"estimated_tokens":75,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"c5bc3ec1-229c-4acc-8a9a-b1184be9a1bf"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" that bal","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"1ea067e9-fbb8-4685-a217-e42170c35740"}}
{"from":"cli","msg":{"estimated_tokens":80,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"ce143939-c780-4938-ba2c-f6a54b8f4a6f"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ance while including","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"77668dd2-c3ad-4df5-87a3-4b76a2219c65"}}
{"from":"cli","msg":{"estimated_tokens":81,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"0475f779-b12b-4ae0-a42a-4ae723a6d468"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" B","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"49727b38-d58a-4ad0-9728-aa4bc223b54d"}}
{"from":"cli","msg":{"estimated_tokens":86,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"02f8ee0c-36d8-4de5-af74-fe7d19969366"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ANANA at the end.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2adc15b2-5b1c-4add-b3ad-1ceaaa665bae"}}
{"from":"cli","msg":{"estimated_tokens":87,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"eb0ae205-deb6-4b79-9726-98fd9d1d533c"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"40e6df26-1321-45ea-8ca5-9d96ca00087b"}}
{"from":"cli","msg":{"estimated_tokens":287,"estimated_tokens_delta":200,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"57a445b0-9671-4073-89c6-f72835125be3"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"aaf131b8-99e0-4fd9-9169-00be0b4e360a"}}
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"The sleep task completed with output \"done.\" The user asked me to end my answer with the word BANANA, which is a harmless request, and there's a note about replying in Chinese per instructions, but the user wrote in English—I'll decide how to handle that balance while including BANANA at the end.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhjUTmHT72RxnP7ze5J","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","thinking_duration_ms":3423,"timestamp":"2026-10-28T13:20:09.346Z","type":"assistant","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"ecaa1288-7581-48ad-9c59-89e4bb9f063f"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"549a0ef9-e0b3-40af-bb4a-8aba4c08eb8d"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"content_block":{"text":"","type":"text"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"d3049aaf-53af-4878-b273-68835033ff92"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"命","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"4a3271f3-0c7d-427c-9407-c610ad454b15"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"令输出为 `done`","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"3558f94f-6fcb-4c7a-96a5-6f6e415a5f93"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"。\n\nB","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"fea97b73-1f25-4f88-94db-0f0fdd401d2b"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"ANANA","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"303a047a-fc87-48ea-9524-e102e112b10a"}}
{"from":"cli","msg":{"message":{"container":null,"content":[{"text":"命令输出为 `done`。\n\nBANANA","type":"text"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhjUTmHT72RxnP7ze5J","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:09.358Z","type":"assistant","uuid":"73a78906-d0d9-432d-b1d7-a34ac4d05707"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"d665c80a-e37f-476e-ac86-e12d44f26fad"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"end_turn","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"output_tokens":209,"type":"message"}],"output_tokens":209,"output_tokens_details":{"thinking_tokens":192}}},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"46798358-6519-4878-af21-22006f465f53"}}
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"fe0e0673-335a-41a0-b7c2-7b5d78e99739"}}
{"from":"cli","msg":{"api_error_status":null,"duration_api_ms":7859,"duration_ms":5066,"fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","first_content_frame_ms":1586,"first_request_input_tokens":33868,"is_error":false,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":19042,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":19042,"cacheReadInputTokens":44758,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00453478,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":318,"provider":"firstParty","thinkingTokens":192,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":3932,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":3932,"cacheReadInputTokens":29934,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00119044,"inputTokens":2,"maxOutputTokens":128000,"outputTokens":209,"provider":"firstParty","thinkingTokens":192,"webSearchRequests":0}},"num_turns":1,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":0,"request_sent_wall_ms":1793193604397,"result":"命令输出为 `done`。\n\nBANANA","result_index":1,"safety_stops":0,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","stop_reason":"end_turn","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"completed","time_to_request_ms":59,"total_cost_usd":0.00453478,"ttft_ms":5008,"ttft_stream_ms":1563,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"output_tokens":209,"type":"message"}],"output_tokens":209,"output_tokens_details":{"thinking_tokens":192},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"8172897e-6304-4855-9480-f4e579da730f"}}
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"completed","type":"command_lifecycle","uuid":"3c5163f4-90c0-4939-a3e5-aba1cf13bca3"}}
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"idle","subtype":"session_state_changed","type":"system","uuid":"57c31a3d-da32-4a0c-9124-372c880779b7"}}
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"apiProvider":"firstParty","effort":"medium","launchEnvLeftOwnFilesInPlace":false,"model":"claude-haiku-5-5","outsideBlocksCountLaunchFoldersOnly":false,"outsideFileToolReadsBlocked":false,"outsideFileToolWritesBlocked":false,"ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false,"ultrathinkAvailable":false},"effective":{"model":null}},"subtype":"success"},"type":"control_response"}}
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 3 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d"}}
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"queued","type":"command_lifecycle","uuid":"e745940b-18ac-4078-b11e-72be2ae6401b","written_at":"2026-12-03T13:51:32.578Z"}}
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"started","type":"command_lifecycle","uuid":"f85c6752-6469-4ce7-bbb2-0349f3fabfa8","written_at":"2026-12-03T13:51:32.579Z"}}
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","withdrawn_files_note_v2","withdrawn_tools_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1","silent_resend_files_v1","lifecycle_idle_v1","comment_images_v1"],"claude_code_version":"2.1.335","cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpX66GLs","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpX66GLs","output_style":"default","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"sandbox_enabled":false,"scratchpad_path":"/private/tmp/claude-501/s/992375695253/scratchpad","served_by_anthropic":true,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","startup_timing":{"entrypoint":"claude-vscode","flag_fetch_kick":"not_eligible","flag_fetch_kick_judged_at_ms":84,"hooks_init_origin_ms":{"official_plugin":69,"other_plugin":17,"user_settings":37},"hooks_init_source":"startup","hooks_init_without_silent_ms":{"any":69,"own":69},"phase_start_ms":{"first_message_handle_ms":282,"first_message_read_ms":0,"grove_check_ms":187,"headless_post_load_ms":257,"headless_prologue_ms":186,"hooks_init_ms":178,"init_emit_ms":343,"initial_messages_load_ms":189,"input_ready_ms":0,"mcp_client_module_load_ms":192,"mcp_config_wait_ms":170,"mcp_connect_ms":182,"mcp_prewait_ms":283,"model_catalog_decision_ms":166,"node_boot_ms":0,"permission_context_ms":89,"pre_action_client_data_url_ms":84,"pre_action_init_ms":46,"pre_action_managed_settings_ms":84,"pre_action_mdm_keychain_ms":45,"pre_action_migrations_ms":84,"pre_action_ms":45,"print_import_ms":183,"prompt_submit_hooks_ms":301,"qe_plugin_skills_load_ms":341,"qe_system_prompt_ms":286,"sdk_mcp_update_ms":282,"settings_load_ms":44,"setup_file_watcher_ms":118,"setup_hooks_snapshot_ms":118,"setup_import_ms":93,"setup_ms":96,"setup_release_notes_ms":119,"setup_uds_dir_ms":96,"setup_uds_listen_ms":114,"setup_uds_messaging_ms":95,"setup_uds_publish_ms":117,"skills_load_ms":95,"tools_commands_load_ms":130},"phases":{"first_message_handle_cpu_ms":0,"first_message_handle_loop_lag_ms":0,"first_message_handle_ms":0,"first_message_read_ms":282,"grove_check_ms":1,"headless_post_load_ms":1,"headless_prologue_ms":2,"hooks_init_ms":78,"init_emit_ms":1,"initial_messages_load_ms":68,"input_ready_ms":265,"mcp_client_module_load_ms":0,"mcp_config_load_ms":62,"mcp_config_wait_ms":2,"mcp_connect_ms":1,"mcp_prewait_ms":0,"model_catalog_decision_ms":3,"node_boot_ms":43,"permission_context_ms":3,"pre_action_client_data_url_ms":0,"pre_action_init_ms":37,"pre_action_managed_settings_ms":1,"pre_action_mdm_keychain_ms":1,"pre_action_migrations_ms":0,"pre_action_ms":43,"print_import_ms":3,"prompt_submit_hooks_ms":37,"qe_plugin_skills_load_ms":1,"qe_system_prompt_ms":4,"sdk_mcp_update_ms":0,"settings_load_ms":0,"setup_file_watcher_ms":0,"setup_hooks_snapshot_ms":0,"setup_import_ms":0,"setup_ms":31,"setup_release_notes_ms":8,"setup_uds_dir_ms":18,"setup_uds_listen_ms":3,"setup_uds_messaging_ms":23,"setup_uds_publish_ms":0,"skills_load_ms":66,"tools_commands_load_ms":35},"plugin_full_loads":0,"sdk_mcp_dial_runs":0,"sdk_mcp_servers_dialed":0,"time_origin_ms":1796305892295.906,"user_context_builds":2,"warm_spare_claimed":false},"subtype":"init","terminal_slash_commands":["doctor","send-to-project","color","focus","reload-plugins"],"type":"system","ultrathink_available":false,"ultrathink_typed_raises":false,"user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"488f600b-a63e-4882-99b1-8dcdfe076157","view_mode":"default","written_at":"2026-12-03T13:51:32.639Z"}}
{"from":"cli","msg":{"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"requesting","subtype":"status","type":"system","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"b6a40890-0e2f-40ab-afc9-8a609749d59e","written_at":"2026-12-03T13:51:32.642Z"}}
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"out_of_credits","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1796320200,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1796320200,"status":"allowed","utilization":0.21},"seven_day":{"resetsAt":1796889600,"status":"allowed","utilization":0.13}}},"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"rate_limit_event","uuid":"0cafd103-637f-4025-913d-3d23ec776453","written_at":"2026-12-03T13:51:33.412Z"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"owed_rows":[],"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","ttft_ms":1089,"type":"stream_event","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"1eba9396-f0bb-4de5-8627-5cebfc962d2a"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"8b5abf5f-2492-4471-b355-ffb886685b08"}}
{"from":"cli","msg":{"estimated_tokens":1,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"3df5ecdd-e701-43ab-8ad3-90428c0a9bf4"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a78c66ea-06f0-4c08-93c3-073ac79ce208"}}
{"from":"cli","msg":{"estimated_tokens":3,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"58e5f0b8-1cae-4e6e-8142-28c83c20d09c"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" user w","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a66bf075-7a36-4bb4-9b94-090567a1047e"}}
{"from":"cli","msg":{"estimated_tokens":5,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"c1baabcf-b72e-438b-8b98-42b628a6c14b"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ants a","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"25f84cb1-9180-49b0-b722-0ae6617e00f5"}}
{"from":"cli","msg":{"estimated_tokens":11,"estimated_tokens_delta":6,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"9d1b3935-0637-45ca-a613-f1d02b08bf36"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" Bash command run. The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"de8666db-803f-4a33-8cb2-9faa68ff3e2a"}}
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"e0d0e6f0-dad3-4075-95d3-cf993ac621d9"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" session","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"85784fb7-e5a4-4e17-acb8-2018e82e8458"}}
{"from":"cli","msg":{"estimated_tokens":18,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"962c83d1-069c-4ff4-b27f-1199d1b3d1b9"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"-start hook points","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bd405da7-abb7-443d-b309-ac6e805014ed"}}
{"from":"cli","msg":{"estimated_tokens":19,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"c77e142c-8284-48f4-b67f-24f6fd1cc99b"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" to","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"4957baf5-5e7a-4e23-bfe6-7bd1be56cee1"}}
{"from":"cli","msg":{"estimated_tokens":24,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"2f3e6875-f0b9-4da6-806b-6420f8e11801"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ward skills, but n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"ec0306de-6581-4dcb-8ef0-8bc9a2dffe5b"}}
{"from":"cli","msg":{"estimated_tokens":28,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"08432ff1-c798-4640-bb4e-9c6bcb1fa879"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"othing here cal","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"934bdb11-4eac-4db8-ba78-d751a132767a"}}
{"from":"cli","msg":{"estimated_tokens":33,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"b68b320e-d34a-4dd2-a52f-d4eb23b6e631"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ls for one, so I'll","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"1a0911c3-5d56-4df6-a490-ca853de74fe0"}}
{"from":"cli","msg":{"estimated_tokens":40,"estimated_tokens_delta":7,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"a0659fe6-3f44-4ee7-8f28-86561a981c00"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" just run the command direct","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"d243b5f8-2ad4-4137-abc0-993b12b30faf"}}
{"from":"cli","msg":{"estimated_tokens":41,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"0ff88c48-df4d-4fb0-9e10-aad67ea6f912"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ly.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"43859418-f19d-4dab-b439-e24db14015f1"}}
{"from":"cli","msg":{"estimated_tokens":42,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"bcb9947d-4522-4206-bc6c-2fe20b0ee3f0"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"480e67e5-6243-4a07-80dc-5e7218eea10d"}}
{"from":"cli","msg":{"estimated_tokens":198,"estimated_tokens_delta":156,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"72763f2b-38bb-45f8-b9b4-6dce76fe87dd"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2c35aff5-f8f1-423d-ab16-a50fe7f92d2c"}}
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"The user wants a Bash command run. The session-start hook points toward skills, but nothing here calls for one, so I'll just run the command directly.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuFePCVDFQ6Zs47Mqbi","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","thinking_duration_ms":1155,"timestamp":"2026-12-03T13:51:35.067Z","type":"assistant","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"f53249a7-87bb-48d3-8a4d-46fb2bc373c3"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"50eafebf-1675-454d-b48d-4c33f9c46fd0"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","input":{},"name":"Bash","type":"tool_use"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"df423477-fdd3-40b4-bd3f-a6e5e2f4285a"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2840ddf3-7a52-45a6-bcee-28d02c695ce1"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"{\"command\": \"sleep 3 && ech","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"f279d761-fe64-4811-ba7a-d3389c7fa1d6"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"o done","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2d7cc471-fe87-49cc-975e-5aefe894bd35"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"77a255b8-8924-4cd2-8239-13d56352e157"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"leep 3 seconds","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5ddf158c-a8ed-475e-b425-4d6aa69d9216"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":" then echo done","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"8c902fdc-adb0-4db8-91fd-a3c9f799193b"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"1019a3dc-64e5-4166-981a-f57347563c32"}}
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","input":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuFePCVDFQ6Zs47Mqbi","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:35.072Z","type":"assistant","uuid":"717bc1de-feb1-41aa-81d7-3ac47c772112","wire_tool_inputs":{"toolu_012tPQXDR9Kw59zBCFJqSuXP":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"}}}}
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"next","session_id":"","type":"user","uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"149df489-36d1-4db3-8f19-ae26b6733dc9"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"input_tokens":2,"output_tokens":142,"type":"message"}],"output_tokens":142,"output_tokens_details":{"thinking_tokens":51}}},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"84156816-f10d-4dd6-8dca-f441fea39795"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"93925996-0953-4359-9383-f6db7885eb3f"}}
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"queued","type":"command_lifecycle","uuid":"58a87b31-0fab-415d-b450-0ed1f58ec0bc","written_at":"2026-12-03T13:51:35.084Z"}}
{"from":"cli","msg":{"content":"A hook gave no usable answer, so it didn't check this action.","hook_no_verdict":{"hook_event":"PreToolUse","timed_out":false,"tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP"},"level":"warning","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"informational","tag":"hook_no_verdict","type":"system","uuid":"1bb27652-e9f7-4277-8138-8840aa03937c","written_at":"2026-12-03T13:51:35.090Z"}}
{"from":"cli","msg":{"description":"Sleep 3 seconds then echo done","is_backgrounded":false,"run_id":"0mx7m5ix4-f838229f","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"task_started","task_id":"bzep4576h","task_type":"local_bash","tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"system","uuid":"9f3e9fb8-34cd-4f9c-95f9-b4a7af80eb18","written_at":"2026-12-03T13:51:39.785Z"}}
{"from":"cli","msg":{"duration_ms":3020,"output_file":"","run_id":"0mx7m5ix4-f838229f","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"completed","subtype":"task_notification","summary":"Sleep 3 seconds then echo done","task_id":"bzep4576h","tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"system","uuid":"63898564-4e95-4aa3-8e90-7fc67025ddce","written_at":"2026-12-03T13:51:39.802Z"}}
{"from":"cli","msg":{"message":{"content":[{"content":"done","is_error":false,"tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:39.838Z","tool_result_meta":[{"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","permission_decision":{"decision":"accept","reason_type":"subcommandResults","source":"config"}}],"tool_use_result":{"interrupted":false,"isImage":false,"noOutputExpected":false,"stderr":"","stdout":"done"},"type":"user","uuid":"8103e7bc-d615-4e6a-9c31-c7d36db98577"}}
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"started","type":"command_lifecycle","uuid":"93252284-65fe-4529-ba8f-485b97e6734a","written_at":"2026-12-03T13:51:39.892Z"}}
{"from":"cli","msg":{"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"requesting","subtype":"status","type":"system","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d","5cf21cb4-f4c7-4360-8932-61818a8e57ee"],"uuid":"1f01a672-b108-46e4-9637-57b2abd60258","written_at":"2026-12-03T13:51:39.892Z"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","ttft_ms":931,"type":"stream_event","uuid":"29de849c-06bb-40e5-a9ad-b70c2f061329"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"92b49174-c189-466f-ad5d-5eea3b3afc2e"}}
{"from":"cli","msg":{"estimated_tokens":2,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"b8ec03ca-333f-4fac-a597-c43aa181360f"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"I need","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"ab10276f-535b-4f19-948c-3f31c090a94e"}}
{"from":"cli","msg":{"estimated_tokens":8,"estimated_tokens_delta":6,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"44beb4b3-366d-4725-8781-17a8ab0c2743"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" to make sure the answ","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"fa8db41b-008b-4779-8269-e3df396df9b2"}}
{"from":"cli","msg":{"estimated_tokens":10,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"58821ddd-b1aa-437b-b6ea-120c4a781f6b"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"er fin","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a4b2ec90-2589-4308-b773-1d95de4e39ab"}}
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":3,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"11a853c1-af93-4d0d-b600-e7f2e51a3a16"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ishes with B","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"3a9a743b-6a39-4572-b86e-4b07355aad6c"}}
{"from":"cli","msg":{"estimated_tokens":17,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"42ca95a6-a59d-4e50-8633-8689136027ad"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ANANA, and the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"e1173332-7e42-470a-bba6-28348e046d10"}}
{"from":"cli","msg":{"estimated_tokens":21,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"1c94c3c4-4eba-42e7-a8a4-00c60bb98763"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" Bash result was","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"c9e62676-e267-4934-85f2-79d124d4bae8"}}
{"from":"cli","msg":{"estimated_tokens":25,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"03d96f9b-adf7-4f6f-b28b-d427db8b8630"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" just \"done.\" So","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bcbdb107-0d53-4872-a6d0-ea0443ab46a6"}}
{"from":"cli","msg":{"estimated_tokens":26,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"383344f4-e9c7-4fc6-8156-2a455fc315d4"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bd677e6a-ccc0-460c-b78c-d146e412fdfc"}}
{"from":"cli","msg":{"estimated_tokens":27,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"95673280-0801-43f2-a343-0e1e2294440d"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" re","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"3ceba820-e7a1-406d-85cc-4e737440db84"}}
{"from":"cli","msg":{"estimated_tokens":34,"estimated_tokens_delta":7,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"ec3fefec-de8f-49c3-832f-ee8cdb9098ba"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ply will start with \"Output:","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"479a0469-81c6-44ed-901f-3b5ba5919286"}}
{"from":"cli","msg":{"estimated_tokens":38,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"f1187702-1431-4c3f-b55b-b5d6b6e1b4cf"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" done\" and close","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"256ff2f5-a3c1-4c39-ba87-85a6f8a66995"}}
{"from":"cli","msg":{"estimated_tokens":43,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"db91d155-3a27-4751-8f44-9f55e24a2d56"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" with BANANA on the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"96de0914-3708-4b8f-afcd-6b1834e0a46a"}}
{"from":"cli","msg":{"estimated_tokens":46,"estimated_tokens_delta":3,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"f315f874-841c-471a-aa95-c7b30c4ecca9"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" last line.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"8b5125ea-c014-4134-9967-bfc89d40f300"}}
{"from":"cli","msg":{"estimated_tokens":47,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"7be0f157-678f-462f-b2ed-f69ee1306d62"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"e17e4edd-aef5-4819-ae50-94d9b359f5e9"}}
{"from":"cli","msg":{"estimated_tokens":199,"estimated_tokens_delta":152,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"344c71df-0721-4f7a-bf9d-a2c9ac2b0431"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5e790c6d-4323-451b-9dbf-9f36e94b59d0"}}
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"I need to make sure the answer finishes with BANANA, and the Bash result was just \"done.\" So the reply will start with \"Output: done\" and close with BANANA on the last line.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuGA4t6XHrNhvpU1gjW","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","thinking_duration_ms":1170,"timestamp":"2026-12-03T13:51:42.004Z","type":"assistant","uuid":"19f7c707-0b92-43f4-a1ff-6f6ba28c9158"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"66f6946c-8aa7-4893-8a3f-fc7c023ea3f6"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"content_block":{"text":"","type":"text"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"6bef1d9a-bcfa-42d8-b3fa-865bbe31804e"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":"The command print","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5866afb3-f9f8-42ba-9ae6-928e88f63709"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":"ed `done`.","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"22c7b7dc-dfa8-49c6-a931-a2a5f179eebe"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":" BANANA","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"265276d2-0f17-4bd8-8719-b6c0464079fc"}}
{"from":"cli","msg":{"message":{"container":null,"content":[{"text":"The command printed `done`. BANANA","type":"text"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuGA4t6XHrNhvpU1gjW","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:42.006Z","type":"assistant","uuid":"4edeb5e3-ae9c-4e64-ab43-dd864db6636c"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"950b3a05-26db-4a0b-bb6e-62d584a38638"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"end_turn","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"output_tokens":72,"type":"message"}],"output_tokens":72,"output_tokens_details":{"thinking_tokens":58}}},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"3fb8dfd0-35eb-49ff-a0f9-94c6cff59bcd"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"eafb6e94-6aeb-4c20-929f-6d5dc4f8df6a"}}
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"completed","type":"command_lifecycle","uuid":"e5548a7e-c304-42d1-a536-2e123ebd58d4","written_at":"2026-12-03T13:51:42.067Z"}}
{"from":"cli","msg":{"api_error_status":null,"begun_message_ids":["msg_011CheuFeb6zou7Nmj7hYFnf","msg_011CheuGALWJsYSxwR2j7F3W"],"credential_expires_at":"2026-12-30T17:21:30.368Z","duration_api_ms":4974,"duration_ms":9488,"fast_mode_state":"off","first_content_frame_ms":1332,"first_request_cache_read_input_tokens":26096,"first_request_input_tokens":42859,"input_attachments_detail":{"ambient_start_ms":1,"ambient_wait_ms":5,"cpu_ms":15,"major_faults":0,"producers":44,"prompt_producers_ms":0,"render_ms":0,"setup_ms":0,"slowest_producer":"deferred_tools_delta","slowest_producer_ms":6,"token_counts":0},"is_error":false,"message_normalization_detail":{"after_ms":0,"before_ms":0,"images_ms":0,"messages":19,"normalize_ms":0,"other_ms":1,"post_process_ms":0,"wire_messages":2},"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":28926,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":28926,"cacheReadInputTokens":68953,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0067110300000000015,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":233,"provider":"firstParty","thinkingTokens":109,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":28926,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":28926,"cacheReadInputTokens":68953,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0067110300000000015,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":233,"provider":"firstParty","thinkingTokens":109,"webSearchRequests":0}},"num_turns":2,"origin":{"kind":"human"},"permission_denials":[],"process_turn_index":0,"queued_turn_count":0,"request_build_detail":{"cache_break_record_ms":1,"headers_ms":0,"other_ms":0,"plans_ms":0,"record_attempt_ms":0,"records_ms":0,"retry_setup_ms":0,"sent_build_cache_breakpoints_ms":0,"sent_build_ms":1,"sent_build_safety_context_ms":0,"sent_build_surrogate_scan_ms":0,"system_ms":0},"request_sent_wall_ms":1796305892823,"result":"The command printed `done`. BANANA","result_index":0,"safety_stops":0,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","stop_reason":"end_turn","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"completed","time_to_request_cpu_ms":107,"time_to_request_loop_lag_ms":1,"time_to_request_major_faults":1,"time_to_request_ms":243,"time_to_request_phases_ms":{"autocompact":1,"client_creation":2,"conversation_append":1,"engine_pickup":1,"init_frame_send":1,"init_message":2,"input_attachments":8,"input_hooks":37,"loop_entry":1,"message_normalization":1,"message_prep":1,"model_config_wait":0,"model_gates":163,"other":2,"process_user_input":2,"query_setup":0,"request_announcements":3,"request_build":2,"resume_other":0,"system_prompt":5,"tool_pool_refresh":1,"tool_schema_build":8,"transcript_persist":1},"tool_schema_build_detail":{"after_ms":0,"betas_ms":0,"new_schemas":13,"other_ms":0,"placement_ms":2,"render_ms":3,"tools":13,"waits_ms":3},"total_cost_usd":0.0067110300000000015,"ttft_ms":2487,"ttft_stream_ms":1331,"turn_start_resume_kind":"none","type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":28926,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":28926,"cache_read_input_tokens":68953,"fallback_credit":null,"inference_geo":"global","input_tokens":4,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"output_tokens":72,"type":"message"}],"output_tokens":214,"output_tokens_details":{"thinking_tokens":109},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d","5cf21cb4-f4c7-4360-8932-61818a8e57ee"],"uuid":"d3f210c9-67ad-4ec5-b122-3d4477ae65b5","written_at":"2026-12-03T13:51:42.069Z"}}
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"completed","type":"command_lifecycle","uuid":"32e0888f-d2b7-4721-bc7c-6c5320d3c99c","written_at":"2026-12-03T13:51:42.070Z"}}
+34
Переглянути файл
@@ -0,0 +1,34 @@
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","f782ff38-9bfe-4bd7-a857-f3cb10b38bcf"]}
{"from":"shim","msg":{"request":{"perTaskStopAffordance":true,"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1"],"claude_code_version":"2.1.335","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_state":"off","feedback_mode":{"kind":"post"},"hook_on_failure_supported":true,"hooks_when_unanswered_kept":0,"ide_rc_auto_enable_gate":true,"models":[{"description":"Opus 5.5 · Best for everyday, complex tasks","displayName":"Default (recommended)","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.2","resolvedModel":"claude-fable-5-2","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5.1","overflow":true,"resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5-1"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","overflow":true,"resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","overflow":true,"resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","overflow":true,"resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","overflow":true,"resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","overflow":true,"resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","overflow":true,"resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","overflow":true,"resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","overflow":true,"resolvedModel":"claude-sonnet-4-6","supportedEffortLevelsLine truncated
{"from":"shim","msg":{"request":{"subtype":"get_settings"},"request_id":"req_2","type":"control_request"}}
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"apiProvider":"firstParty","effort":"medium","launchEnvLeftOwnFilesInPlace":false,"model":"claude-haiku-5-5","outsideBlocksCountLaunchFoldersOnly":false,"outsideFileToolReadsBlocked":false,"outsideFileToolWritesBlocked":false,"ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false,"ultrathinkAvailable":false},"effective":{"model":null}},"subtype":"success"},"type":"control_response"}}
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 5 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"750456ba-c54c-493b-bb61-40a9d825a457"}}
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"queued","type":"command_lifecycle","uuid":"b57b173d-a184-4e10-8ac6-46bd57c905b2","written_at":"2026-12-03T13:52:52.103Z"}}
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"started","type":"command_lifecycle","uuid":"cd26e730-c57b-49c0-bfed-0ed2202ba6f5","written_at":"2026-12-03T13:52:52.104Z"}}
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","withdrawn_files_note_v2","withdrawn_tools_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1","silent_resend_files_v1","lifecycle_idle_v1","comment_images_v1"],"claude_code_version":"2.1.335","cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpbIsGYj","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpbIsGYj","output_style":"default","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"sandbox_enabled":false,"scratchpad_path":"/private/tmp/claude-501/s/443805216073/scratchpad","served_by_anthropic":true,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","startup_timing":{"entrypoint":"claude-vscode","flag_fetch_kick":"not_eligible","flag_fetch_kick_judged_at_ms":84,"hooks_init_origin_ms":{"official_plugin":79,"other_plugin":23,"user_settings":51},"hooks_init_source":"startup","hooks_init_without_silent_ms":{"any":79,"own":79},"phase_start_ms":{"first_message_handle_ms":299,"first_message_read_ms":0,"grove_check_ms":193,"headless_post_load_ms":273,"headless_prologue_ms":192,"hooks_init_ms":184,"init_emit_ms":361,"initial_messages_load_ms":196,"input_ready_ms":0,"mcp_client_module_load_ms":200,"mcp_config_wait_ms":175,"mcp_connect_ms":188,"mcp_prewait_ms":300,"model_catalog_decision_ms":170,"node_boot_ms":0,"permission_context_ms":90,"pre_action_client_data_url_ms":84,"pre_action_init_ms":45,"pre_action_managed_settings_ms":84,"pre_action_mdm_keychain_ms":44,"pre_action_migrations_ms":84,"pre_action_ms":44,"print_import_ms":189,"prompt_submit_hooks_ms":319,"qe_plugin_skills_load_ms":360,"qe_system_prompt_ms":302,"sdk_mcp_update_ms":299,"settings_load_ms":43,"setup_file_watcher_ms":119,"setup_hooks_snapshot_ms":119,"setup_import_ms":93,"setup_ms":96,"setup_release_notes_ms":120,"setup_uds_dir_ms":97,"setup_uds_listen_ms":116,"setup_uds_messaging_ms":95,"setup_uds_publish_ms":119,"skills_load_ms":96,"tools_commands_load_ms":132},"phases":{"first_message_handle_cpu_ms":0,"first_message_handle_loop_lag_ms":0,"first_message_handle_ms":0,"first_message_read_ms":299,"grove_check_ms":2,"headless_post_load_ms":1,"headless_prologue_ms":3,"hooks_init_ms":89,"init_emit_ms":1,"initial_messages_load_ms":77,"input_ready_ms":280,"mcp_client_module_load_ms":0,"mcp_config_load_ms":67,"mcp_config_wait_ms":2,"mcp_connect_ms":1,"mcp_prewait_ms":0,"model_catalog_decision_ms":2,"node_boot_ms":43,"permission_context_ms":3,"pre_action_client_data_url_ms":0,"pre_action_init_ms":39,"pre_action_managed_settings_ms":1,"pre_action_mdm_keychain_ms":1,"pre_action_migrations_ms":0,"pre_action_ms":45,"print_import_ms":3,"prompt_submit_hooks_ms":38,"qe_plugin_skills_load_ms":1,"qe_system_prompt_ms":5,"sdk_mcp_update_ms":0,"settings_load_ms":0,"setup_file_watcher_ms":0,"setup_hooks_snapshot_ms":0,"setup_import_ms":0,"setup_ms":32,"setup_release_notes_ms":9,"setup_uds_dir_ms":19,"setup_uds_listen_ms":3,"setup_uds_messaging_ms":24,"setup_uds_publish_ms":0,"skills_load_ms":69,"tools_commands_load_ms":38},"plugin_full_loads":0,"sdk_mcp_dial_runs":0,"sdk_mcp_servers_dialed":0,"time_origin_ms":1796305971804.1318,"user_context_builds":2,"warm_spare_claimed":false},"subtype":"init","terminal_slash_commands":["doctor","send-to-project","color","focus","reload-plugins"],"type":"system","ultrathink_available":false,"ultrathink_typed_raises":false,"user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"4614d51b-c114-4e3a-87c1-474dd3221ccb","view_mode":"default","written_at":"2026-12-03T13:52:52.166Z"}}
{"from":"cli","msg":{"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","status":"requesting","subtype":"status","type":"system","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"1334ad42-52e2-4940-a881-df02701bbce2","written_at":"2026-12-03T13:52:52.168Z"}}
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"out_of_credits","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1796320200,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1796320200,"status":"allowed","utilization":0.22},"seven_day":{"resetsAt":1796889600,"status":"allowed","utilization":0.13}}},"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"rate_limit_event","uuid":"2d31cd09-90af-4542-9ab8-d6d35208343a","written_at":"2026-12-03T13:52:52.848Z"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuMVnw6EQjt4etKk278","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"owed_rows":[],"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","thinking_display":"summarized","ttft_ms":870,"type":"stream_event","user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"a07fd809-d225-4ae9-8a9a-1cfcd3ba452b"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_013cYTr5SPmttma9grssUDvs","input":{},"name":"Bash","type":"tool_use"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"d87d4b0c-0817-44f3-ba3d-506b145416eb"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"7ebaa4fa-4334-42cd-87b9-86efb45b06fd"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"{\"command\": \"sleep 5","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"92f03d38-e933-444a-af9e-5d97a3bc17e1"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":" && echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"156dfb71-8647-402b-81f1-d28209de7f6b"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"f2218947-8767-4812-b6e9-5081d444668e"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"leep 5 seconds","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"645079d4-6f4f-403c-aef0-add49e320bdb"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":" then echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"fc1582cb-4fe7-4747-b65a-5d57351c1749"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"8de2ab6a-1c5f-43be-99c5-accf562bded5"}}
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_013cYTr5SPmttma9grssUDvs","input":{"command":"sleep 5 && echo done","description":"Sleep 5 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuMVnw6EQjt4etKk278","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuMVa2bRTBYmxzHrdZU","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:53.341Z","type":"assistant","user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"543df181-f94c-4c59-8a54-6790d7c146fe","wire_tool_inputs":{"toolu_013cYTr5SPmttma9grssUDvs":{"command":"sleep 5 && echo done","description":"Sleep 5 seconds then echo done"}}}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"c95ced13-7ba7-4081-96dc-72e2e1ee9c67"}}
{"from":"cli","msg":{"content":"A hook gave no usable answer, so it didn't check this action.","hook_no_verdict":{"hook_event":"PreToolUse","timed_out":false,"tool_use_id":"toolu_013cYTr5SPmttma9grssUDvs"},"level":"warning","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","subtype":"informational","tag":"hook_no_verdict","type":"system","uuid":"c5ce69e8-b5c8-4e04-b6af-b1a4d9760a3d","written_at":"2026-12-03T13:52:53.356Z"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0}}},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"f1c31fc2-e095-4a52-a92c-752feb90d83c"}}
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"5fd7d71c-5822-414a-b3e1-d11395fd7022"}}
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"next","session_id":"","type":"user","uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee"}}
{"from":"cli","msg":{"command_uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"queued","type":"command_lifecycle","uuid":"d4038320-e65f-4937-b14c-8948234e08c4","written_at":"2026-12-03T13:52:55.103Z"}}
{"from":"shim","msg":{"request":{"cancel_queued":true,"subtype":"interrupt"},"request_id":"req_3","type":"control_request"}}
{"from":"cli","msg":{"command_uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"cancelled","type":"command_lifecycle","uuid":"24e8c7aa-31e8-455f-a456-12ee15e0e8f9","written_at":"2026-12-03T13:52:55.604Z"}}
{"from":"cli","msg":{"response":{"request_id":"req_3","response":{"cancelled":["6e50c1f5-335e-4d89-a2ef-725e845b57ee"],"still_queued":[]},"subtype":"success"},"type":"control_response"}}
{"from":"cli","msg":{"message":{"content":[{"content":"The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed. Correction to the text above: this call was stopped while running, not refused before it ran. It may have run in part or in full, and its changes may have been written. No permission prompt was involved. Work it started elsewhere (a remote command, a background process) may still be running, so check before starting the same work again. The instruction to stop and wait still stands.","is_error":true,"tool_use_id":"toolu_013cYTr5SPmttma9grssUDvs","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:55.608Z","tool_result_meta":[{"id":"toolu_013cYTr5SPmttma9grssUDvs","non_execution_kind":"user-rejected"}],"tool_use_result":"User rejected tool use","type":"user","uuid":"087df73f-b2fe-42d9-9de4-f3fab77aefe0"}}
{"from":"cli","msg":{"message":{"content":[{"text":"[Request interrupted by user for tool use]","type":"text"}],"role":"user"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:55.610Z","type":"user","uuid":"900c03e1-b662-4e5f-aaf6-384263031910"}}
{"from":"cli","msg":{"begun_message_ids":["msg_011CheuMVnw6EQjt4etKk278"],"credential_expires_at":"2026-12-30T17:21:30.368Z","duration_api_ms":1721,"duration_ms":3506,"errors":["[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=tool_use"],"fast_mode_state":"off","is_error":true,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":14749,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":14749,"cacheReadInputTokens":28109,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00340499,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":14749,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":14749,"cacheReadInputTokens":28109,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00340499,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"num_turns":3,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":0,"result_index":0,"safety_stops":0,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","stop_reason":"tool_use","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"error_during_execution","terminal_reason":"aborted_tools","total_cost_usd":0.00340499,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"5c62e1de-fdfc-44f7-ae20-cd70b87590e5","written_at":"2026-12-03T13:52:55.613Z"}}
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","idle":true,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"cancelled","type":"command_lifecycle","uuid":"53cf7918-cf6e-4c94-984c-8401081fa93e","written_at":"2026-12-03T13:52:55.615Z"}}
+1 -1
Переглянути файл
@@ -63,7 +63,7 @@ pub(crate) fn stream_batched<T>(
}
}
flush(&mut batch, on_batch);
Ok((lines.finish(cancel)?, stderr_tail))
Ok((lines.finish(cancel)?.success(), stderr_tail))
}
#[cfg(all(test, unix))]
+323 -29
Переглянути файл
@@ -21,8 +21,9 @@ pub use single::{
module_classpaths, single_file_classpath, single_file_target,
};
pub use structure::{
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
StructureBuildContext, StructureJdk, StructureRoots, artifact_file, artifact_output, language_release,
structure_build, structure_build_war, structure_compile_file_plan, structure_outputs, structure_plan,
structure_war_plan, structure_web_artifacts,
};
pub use tsc_watch::{tsc_watch, tsc_watch_roots};
pub use up_to_date::{menu_up_to_date, record_menu_build};
@@ -358,16 +359,14 @@ pub(super) fn maven_steps(
};
// The reactor root containing the module builds it with what it depends on (`-pl … -am`).
let rel = rel_str(root, module);
if !m.projects.iter().any(|p| p.dir == rel) {
let Some(target) = m.projects.iter().find(|p| p.dir == rel) else {
return Err(IdeError::not_found("no linked Maven project found for module"));
}
};
let top = maven_reactor(m, &rel).ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
let top_dir = subdir(root, &top.dir);
if module == top_dir {
return Ok(vec![step(top, &[])]);
if let Some(pl) = maven::module_selector(root, top, target) {
return Ok(vec![step(top, &["-pl".into(), pl, "-am".into()])]);
}
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or(rel);
Ok(vec![step(top, &["-pl".into(), pl, "-am".into()])])
Ok(vec![step(top, &[])])
}
fn gradle_steps(root: &Path, model: &BuildModel, kind: BuildKind, module: Option<&Path>) -> IdeResult<Vec<BuildStep>> {
@@ -421,13 +420,14 @@ fn cargo_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
}
/// CLion's Build Project for a CMake project: configures the build directory when it has no
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild), one job per
/// `CMakeCache.txt` or no File API reply yet, then `cmake --build` (`--clean-first` to rebuild), one job per
/// logical CPU unless the profile's build arguments choose a count. The directory and
/// options come from the CMake profile; without one, a configured directory of the project
/// (the first by name), else `build`, as the generated run configurations use.
fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> Vec<BuildStep> {
let build_dir = match profile {
Some(p) if !p.build_dir.trim().is_empty() => p.build_dir.trim().to_owned(),
Some(p) if p.build_type.is_empty() => "cmake-build-default".into(),
Some(p) => format!("cmake-build-{}", p.build_type.to_lowercase()),
None => {
let mut configured: Vec<String> = std::fs::read_dir(dir)
@@ -444,18 +444,49 @@ fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> V
let build_type = profile.map_or("Debug", |p| p.build_type.as_str());
let env = profile.map(|p| p.env.clone()).unwrap_or_default();
let mut steps = Vec::new();
if !dir.join(&build_dir).join("CMakeCache.txt").is_file() {
let mut configure = BuildStep::new("cmake", &["-S", ".", "-B", &build_dir], dir, Format::Gcc);
if let Some(p) = profile.filter(|p| !p.generator.trim().is_empty()) {
configure.args.extend(["-G".into(), p.generator.clone()]);
}
configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}"));
let preset = profile.and_then(|p| p.preset.as_ref());
// The profile's toolchain may bring its own cmake.
let cmake = profile.and_then(|p| p.cmake_program.as_ref()).map_or("cmake".into(), |c| c.to_string_lossy());
let cmake = cmake.as_ref();
let build_path = dir.join(&build_dir);
// Configured without the File API queries (by another tool, or before they were written):
// configure again so the targets, and their run configurations, become known.
let fresh = !build_path.join("CMakeCache.txt").is_file();
if fresh || !build_path.join(ide_core::cmake_file_api::REPLY).is_dir() {
// Best effort: without the queries the build still runs, only the targets stay unknown.
let _ = ide_core::cmake_file_api::write_queries(&build_path);
let mut configure = match preset {
// The preset sets the generator and cache variables.
Some(preset) => BuildStep::new(cmake, &["--preset", &preset.configure], dir, Format::Gcc),
None => {
let mut configure = BuildStep::new(cmake, &["-S", ".", "-B", &build_dir], dir, Format::Gcc);
// A configured directory keeps its generator (CMake refuses another one) and,
// without a profile, its build type.
if let Some(p) = profile.filter(|p| fresh && !p.generator.trim().is_empty()) {
configure.args.extend(["-G".into(), p.generator.clone()]);
}
if fresh || profile.is_some() {
configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}"));
}
configure
}
};
configure.args.push("-DCMAKE_EXPORT_COMPILE_COMMANDS=ON".into());
configure.args.extend(profile.map(|p| p.cmake_args.clone()).unwrap_or_default());
configure.env = env.clone();
steps.push(configure);
}
let mut build = BuildStep::new("cmake", &["--build", &build_dir, "--config", build_type], dir, Format::Gcc);
let mut build = match preset.and_then(|p| p.build.as_deref()) {
Some(build) => BuildStep::new(cmake, &["--build", "--preset", build], dir, Format::Gcc),
None => {
let mut build = BuildStep::new(cmake, &["--build", &build_dir], dir, Format::Gcc);
// CLion's "Default" build type: no configuration at all.
if !build_type.is_empty() {
build.args.extend(["--config".into(), build_type.into()]);
}
build
}
};
if kind == BuildKind::Rebuild {
build.args.push("--clean-first".into());
}
@@ -538,6 +569,77 @@ fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
Ok(vec![step])
}
/// A `dotnet` command the .NET tool window runs on a solution or project file.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum DotnetCommand {
Build,
Clean,
Restore,
}
/// `dotnet build` / `clean` / `restore` of one solution or project file, followed by `options`
/// (`--configuration`, `--framework`, `-p:…`).
pub fn dotnet_command_plan(file: &Path, command: DotnetCommand, options: &[String]) -> IdeResult<BuildPlan> {
let verb = match command {
DotnetCommand::Build => "build",
DotnetCommand::Clean => "clean",
DotnetCommand::Restore => "restore",
};
dotnet_file_plan(file, verb, true, options)
}
/// `dotnet publish` of one project file with the publish dialog's `options` (`-p:PublishProfile=…`,
/// or `--configuration` / `--runtime` / `--output`).
pub fn dotnet_publish_plan(file: &Path, options: &[String]) -> IdeResult<BuildPlan> {
dotnet_file_plan(file, "publish", false, options)
}
fn dotnet_file_plan(file: &Path, verb: &str, solutions: bool, options: &[String]) -> IdeResult<BuildPlan> {
let ext = file.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
let accepted = match ext.as_str() {
"csproj" | "fsproj" | "vbproj" => true,
"sln" | "slnx" => solutions,
_ => false,
};
let (Some(dir), Some(name), true) = (file.parent(), file.file_name(), accepted) else {
return Err(IdeError::invalid(if solutions {
format!("dotnet {verb} needs a solution or a C#, F# or VB project")
} else {
format!("dotnet {verb} needs a C#, F# or VB project")
}));
};
if !file.is_file() {
return Err(IdeError::not_found(format!("{} does not exist", file.display())));
}
let name = name.to_string_lossy();
let mut step = BuildStep::new("dotnet", &[verb, &name, "-nologo", "-clp:NoSummary"], dir, Format::Msbuild);
step.args.extend_from_slice(options);
step.env.insert("MSBUILDTERMINALLOGGER".into(), "off".into());
Ok(BuildPlan { system: BuildSystem::Dotnet, title: format!("dotnet {verb} {name}"), steps: vec![step] })
}
/// `dotnet format` of a solution or C# / VB project file; `verify` only reports what it would
/// change and fails when there is anything.
pub fn dotnet_format_plan(file: &Path, verify: bool) -> IdeResult<BuildPlan> {
let ext = file.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
let (Some(dir), Some(name), true) =
(file.parent(), file.file_name(), matches!(ext.as_str(), "sln" | "slnx" | "csproj" | "vbproj"))
else {
return Err(IdeError::invalid("dotnet format needs a solution or a C# / VB project"));
};
if !file.is_file() {
return Err(IdeError::not_found(format!("{} does not exist", file.display())));
}
let name = name.to_string_lossy();
// Verbose output names the files it changed; verifying changes none.
let options: &[&str] = if verify { &["--verify-no-changes"] } else { &["--verbosity", "normal"] };
let mut step = BuildStep::new("dotnet", &["format", &name], dir, Format::Msbuild);
step.args.extend(options.iter().map(|o| (*o).to_owned()));
step.env.insert("MSBUILDTERMINALLOGGER".into(), "off".into());
Ok(BuildPlan { system: BuildSystem::Dotnet, title: format!("dotnet format {name}"), steps: vec![step] })
}
fn ts_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
let script = has_build_script(dir);
if script && (kind == BuildKind::Artifacts || !dir.join("tsconfig.json").is_file()) {
@@ -926,17 +1028,7 @@ pub fn has_non_java_sources(module: &Path) -> bool {
}
fn reactor_projects<'a>(m: &'a maven::MavenModel, top: &'a maven::MavenProject) -> Vec<&'a maven::MavenProject> {
let mut projects = Vec::new();
let mut pending = vec![top];
let mut seen = HashSet::new();
while let Some(p) = pending.pop() {
if !seen.insert(&p.pom) {
continue;
}
projects.push(p);
pending.extend(m.projects.iter().filter(|child| p.modules.contains(&child.pom)));
}
projects
maven::reactor_projects(m, top)
}
/// A step running Maven, its output parsed as Maven's.
@@ -962,7 +1054,7 @@ pub(crate) fn reactor_projects_of<'a>(
}
fn maven_reactor<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
m.projects.iter().filter(|p| !p.aggregated).find(|top| reactor_projects(m, top).iter().any(|p| p.dir == module))
maven::reactor_for_dir(m, module)
}
/// Launch module first, followed by its upstream modules in the same Maven reactor.
@@ -1659,6 +1751,15 @@ mod tests {
"an unconfigured project is configured first"
);
write(&cm, "cmake-build-release/CMakeCache.txt", "");
let p =
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(
p.steps[0].args,
["-S", ".", "-B", "cmake-build-release", "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"],
"configured again, as it was, when it has no File API reply"
);
assert!(cm.join("cmake-build-release/.cmake/api/v1/query/client-openidea/codemodel-v2").is_file());
std::fs::create_dir_all(cm.join("cmake-build-release").join(ide_core::cmake_file_api::REPLY)).unwrap();
let p =
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(
@@ -1694,6 +1795,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>");
@@ -1993,6 +2121,34 @@ mod tests {
);
}
#[test]
fn sibling_reactor_launch_uses_relative_module_selector() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(
root,
"parent/pom.xml",
"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>",
);
write(
root,
"common/pom.xml",
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
);
write(
root,
"app/pom.xml",
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId></project>",
);
let model = BuildModel { maven: Some(maven::load(root)), ..Default::default() };
let plan =
launch_plan(root, &model, &root.join("app"), false, BuildKind::Build, &CancellationToken::new()).unwrap();
assert_eq!(plan.steps.len(), 1);
assert_eq!(plan.steps[0].cwd, root.join("parent"));
let pl = plan.steps[0].args.iter().position(|a| a == "-pl").unwrap();
assert_eq!(&plan.steps[0].args[pl..pl + 3], &["-pl", "../app", "-am"]);
}
#[cfg(unix)]
#[test]
fn external_launch_returns_upstream_outputs_and_blocks_failure_or_cancellation() {
@@ -2162,4 +2318,142 @@ mod tests {
assert_eq!(whole.steps[0].cwd, root);
assert_eq!(whole.steps[0].args, ["build", "./..."]);
}
#[test]
fn dotnet_format_runs_on_the_given_solution_or_project() {
let dir = tempfile::tempdir().unwrap();
for name in ["App.sln", "App.slnx", "App.csproj", "App.vbproj", "App.fsproj", "A.cs"] {
std::fs::write(dir.path().join(name), "").unwrap();
}
for name in ["App.sln", "App.slnx", "App.csproj", "App.vbproj"] {
let plan = super::dotnet_format_plan(&dir.path().join(name), false).unwrap();
assert_eq!(plan.steps[0].args, ["format", name, "--verbosity", "normal"]);
assert_eq!(plan.steps[0].cwd, dir.path());
let verify = super::dotnet_format_plan(&dir.path().join(name), true).unwrap();
assert_eq!(verify.steps[0].args, ["format", name, "--verify-no-changes"]);
}
for name in ["App.fsproj", "A.cs", "Missing.sln"] {
assert!(super::dotnet_format_plan(&dir.path().join(name), false).is_err(), "{name}");
}
}
/// The real `dotnet format` (`-- --ignored`): verifying reports and changes nothing, formatting rewrites.
#[test]
#[ignore = "needs the .NET SDK"]
fn dotnet_format_reports_and_rewrites_with_the_real_sdk() {
let found = std::process::Command::new("dotnet").arg("--version").output().is_ok_and(|o| o.status.success());
if !found {
return;
}
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
for args in [
&["new", "console", "-n", "App", "-o", "App"][..],
&["new", "sln", "-n", "Sln", "--format", "slnx"],
&["new", "sln", "-n", "Classic", "--format", "sln"],
&["sln", "Sln.slnx", "add", "App/App.csproj"],
&["sln", "Classic.sln", "add", "App/App.csproj"],
] {
assert!(std::process::Command::new("dotnet").args(args).current_dir(&root).status().unwrap().success());
}
let source = root.join("App").join("中 A.cs");
let messy = "class A{void M( ){var x=1;}}\n";
for target in ["Sln.slnx", "Classic.sln", "App/App.csproj"] {
std::fs::write(&source, messy).unwrap();
let run = |verify| {
let plan = super::dotnet_format_plan(&root.join(target), verify).unwrap();
super::run(&root, &plan, &CancellationToken::new(), &|_| {}).unwrap()
};
let verified = run(true);
assert!(!verified.success, "{target}");
let message = verified.messages.iter().find(|m| m.code.as_deref() == Some("WHITESPACE")).unwrap();
assert!(message.path.as_ref().unwrap().ends_with("中 A.cs"), "{message:?}");
assert_eq!(std::fs::read_to_string(&source).unwrap(), messy);
assert!(run(false).success, "{target}");
assert_ne!(std::fs::read_to_string(&source).unwrap(), messy);
assert!(run(true).success, "{target}");
}
}
#[test]
fn dotnet_publish_runs_on_one_project_file() {
let dir = tempfile::tempdir().unwrap();
for name in ["App.csproj", "App.fsproj", "App.vbproj", "Sln.slnx"] {
std::fs::write(dir.path().join(name), "").unwrap();
}
let options = ["-p:PublishProfile=My Folder".to_owned()];
for name in ["App.csproj", "App.fsproj", "App.vbproj"] {
let plan = super::dotnet_publish_plan(&dir.path().join(name), &options).unwrap();
assert_eq!(
plan.steps[0].args,
["publish", name, "-nologo", "-clp:NoSummary", "-p:PublishProfile=My Folder"]
);
}
for name in ["Sln.slnx", "Missing.csproj"] {
assert!(super::dotnet_publish_plan(&dir.path().join(name), &[]).is_err(), "{name}");
}
}
#[test]
fn dotnet_commands_run_on_one_solution_or_project_file() {
use super::DotnetCommand;
let dir = tempfile::tempdir().unwrap();
for name in ["App.csproj", "Sln.sln", "Sln.slnx", "notes.txt"] {
std::fs::write(dir.path().join(name), "").unwrap();
}
let options = ["--configuration".to_owned(), "Release".to_owned()];
for (name, command, verb) in [
("Sln.sln", DotnetCommand::Build, "build"),
("Sln.slnx", DotnetCommand::Clean, "clean"),
("App.csproj", DotnetCommand::Restore, "restore"),
] {
let plan = super::dotnet_command_plan(&dir.path().join(name), command, &options).unwrap();
assert_eq!(plan.title, format!("dotnet {verb} {name}"));
assert_eq!(plan.steps[0].args, [verb, name, "-nologo", "-clp:NoSummary", "--configuration", "Release"]);
assert_eq!(plan.steps[0].cwd, dir.path());
}
for name in ["notes.txt", "Missing.sln"] {
assert!(super::dotnet_command_plan(&dir.path().join(name), DotnetCommand::Build, &[]).is_err(), "{name}");
}
assert!(super::dotnet_publish_plan(&dir.path().join("Sln.sln"), &[]).is_err(), "publish takes a project");
}
/// The real `dotnet publish` (`-- --ignored`): publishes, reports compile errors, and stops
/// when cancelled.
#[test]
#[ignore = "needs the .NET SDK"]
fn dotnet_publish_publishes_fails_and_cancels_with_the_real_sdk() {
let found = std::process::Command::new("dotnet").arg("--version").output().is_ok_and(|o| o.status.success());
if !found {
return;
}
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let new = ["new", "console", "-n", "App", "-o", "App"];
assert!(std::process::Command::new("dotnet").args(new).current_dir(&root).status().unwrap().success());
let project = root.join("App").join("App.csproj");
let options = ["--output".to_owned(), "out dir".to_owned()];
let plan = super::dotnet_publish_plan(&project, &options).unwrap();
let published = super::run(&root, &plan, &CancellationToken::new(), &|_| {}).unwrap();
assert!(published.success);
let output = root.join("App").join("out dir").join("App.dll");
assert!(output.is_file());
std::fs::remove_dir_all(root.join("App").join("out dir")).unwrap();
let token = CancellationToken::new();
let cancel = token.clone();
let result = super::run(&root, &plan, &token, &|e| {
if matches!(e, BuildEvent::Output { .. }) {
cancel.cancel();
}
});
assert!(result.is_err(), "a cancelled publish is not a result");
assert!(!output.exists());
std::fs::write(root.join("App").join("Program.cs"), "nope\n").unwrap();
let failed = super::run(&root, &plan, &CancellationToken::new(), &|_| {}).unwrap();
assert!(!failed.success);
assert!(failed.messages.iter().any(|m| m.path.as_ref().is_some_and(|p| p.ends_with("Program.cs"))));
}
}
+46 -6
Переглянути файл
@@ -72,15 +72,19 @@ fn affected_projects(reactor: &[&maven::MavenProject], changed: &HashSet<String>
/// `-pl` entries of the affected modules, relative to the reactor root the step
/// runs in, sorted so the command line does not depend on the model's project
/// order (Maven reorders the selection into its own reactor order anyway).
fn selection(reactor: &[&maven::MavenProject], top_dir: &str, affected: &HashSet<String>) -> String {
fn selection(
root: &Path,
top: &maven::MavenProject,
reactor: &[&maven::MavenProject],
affected: &HashSet<String>,
) -> String {
let mut entries: Vec<String> = reactor
.iter()
.filter(|p| affected.contains(&p.dir))
.map(|p| {
Path::new(&p.dir).strip_prefix(top_dir).unwrap_or(Path::new(&p.dir)).to_string_lossy().replace('\\', "/")
})
.filter_map(|p| maven::module_selector(root, top, p))
.collect();
entries.sort();
entries.dedup();
entries.join(",")
}
@@ -130,8 +134,12 @@ pub(super) fn narrowed_maven_steps(
if affected.len() >= reactor.len() || affected.contains(&top.dir) {
steps.push(step(top, &[]));
} else {
let pl = selection(&reactor, &top.dir, &affected);
steps.push(step(top, &["-pl".into(), pl, "-am".into()]));
let pl = selection(root, top, &reactor, &affected);
if pl.is_empty() {
steps.push(step(top, &[]));
} else {
steps.push(step(top, &["-pl".into(), pl, "-am".into()]));
}
}
}
Ok(Some(steps))
@@ -405,4 +413,36 @@ mod tests {
assert_eq!(steps.len(), 1);
assert_eq!(steps[0].cwd, subdir(root, "solo"));
}
#[test]
fn sibling_reactor_narrows_with_relative_module_selectors() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
write(
root,
"parent/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>"#,
);
write(
root,
"common/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>"#,
);
write(
root,
"app/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>common</artifactId><version>1</version></dependency></dependencies></project>"#,
);
write(root, "common/src/main/java/t/C.java", "package t; public class C {}");
write(root, "app/src/main/java/t/A.java", "package t; public class A {}");
let model = BuildModel { maven: Some(maven::load(root)), ..Default::default() };
let cache = root.join("cache");
record_module_build(&cache, root, &model, &CancellationToken::new());
write(root, "common/src/main/java/t/C.java", "package t; public class C { int x; }");
let steps = steps(&cache, root, &model).unwrap();
assert_eq!(steps.len(), 1);
assert_eq!(steps[0].cwd, subdir(root, "parent"));
assert_eq!(pl_arg(&steps[0]), "../app,../common");
assert!(steps[0].args.contains(&"-am".into()));
}
}
+2 -4
Переглянути файл
@@ -143,8 +143,7 @@ pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeRe
let module = subdir(root, &project.dir);
let top = maven_reactor(m, &project.dir)
.ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
let top_dir = subdir(root, &top.dir);
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
let pl = maven::module_selector(root, top, project).unwrap_or_default();
// Test sources see the test classpath and compile into test classes.
let test = is_test_source(&rel);
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
@@ -164,8 +163,7 @@ fn module_target(root: &Path, model: &BuildModel, module: &Path, test: bool) ->
.ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
let top = maven_reactor(m, &project.dir)
.ok_or_else(|| IdeError::not_found("no linked Maven reactor found for module"))?;
let top_dir = subdir(root, &top.dir);
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
let pl = maven::module_selector(root, top, project).unwrap_or_default();
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
}
File diff suppressed because it is too large. Load diff
+398 -241
Переглянути файл
@@ -64,9 +64,300 @@ pub struct JavaBuildService {
}
impl JavaBuildService {
fn lock(&self, dir: &Path) -> Arc<Mutex<()>> {
pub(crate) fn lock(&self, dir: &Path) -> Arc<Mutex<()>> {
self.locks.lock().unwrap().entry(dir.to_path_buf()).or_default().clone()
}
/// Compiles what changed in one source set (see [`incremental`]).
pub fn compile_incremental(
&self,
set: &IncrementalSet<'_>,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
messages: &mut Vec<BuildMessage>,
) -> IdeResult<IncrementalOutcome> {
if set.clean {
remove_classes(&set.output);
let _ = std::fs::remove_dir_all(&set.generated_dir);
let _ = std::fs::remove_file(&set.state_file);
}
let source_stamps: BTreeMap<PathBuf, FileStamp> =
set.sources.iter().filter_map(|s| Some((s.clone(), file_stamp(s)?))).collect();
let previous = incremental::load_state(&set.state_file);
let reactor: Vec<PathBuf> = set.upstream_states.iter().map(|(o, _)| o.clone()).collect();
let stamp = SetStamp {
options: set.options.clone(),
libraries: set.libraries.iter().map(|e| (e.clone(), file_stamp(e))).collect(),
reactor,
processor_path: set.processor_path.iter().map(|p| (p.clone(), file_stamp(p))).collect(),
java_home: set.java_home.clone(),
};
// What the upstream outputs it compiles against changed since it last compiled.
let mut upstream = BTreeMap::new();
let mut upstream_changed = BTreeSet::new();
let mut upstream_all = false;
for (entry, up_state_file) in &set.upstream_states {
let state = incremental::load_state(up_state_file);
let generation = state.as_ref().map_or(0, |s| s.generation);
upstream.insert(entry.clone(), generation);
let recorded = previous.as_ref().and_then(|p| p.upstream.get(entry)).copied();
if recorded == Some(generation) {
continue;
}
match (recorded, state.and_then(|s| s.changes_since(recorded?))) {
(Some(_), Some(changed)) => upstream_changed.extend(changed),
_ => upstream_all = true,
}
}
let had_state = previous.is_some();
let previous = previous.unwrap_or_default();
let mut changed: BTreeSet<PathBuf> = source_stamps
.iter()
.filter(|(path, stamp)| {
previous.sources.get(*path) != Some(*stamp)
|| previous.dirty.contains(*path)
|| set.force.contains(*path)
})
.map(|(path, _)| path.clone())
.collect();
let removed: BTreeSet<PathBuf> =
previous.sources.keys().filter(|p| !source_stamps.contains_key(*p)).cloned().collect();
let mut from_scratch = !had_state
|| previous.stamp != stamp
|| upstream_all
|| !set.output.is_dir()
|| (!previous.success && previous.dirty.is_empty());
if had_state && !from_scratch {
for record in previous.classes.values() {
if !record.file.is_file() {
match &record.source {
Some(src) if source_stamps.contains_key(src) => {
changed.insert(src.clone());
}
Some(src) if removed.contains(src) => {}
_ => {
from_scratch = true;
break;
}
}
}
}
}
if !from_scratch && changed.is_empty() && removed.is_empty() && upstream_changed.is_empty() {
return Ok(IncrementalOutcome { failed: false, compiled_files: 0, outputs_changed: false });
}
// Processors that aggregate (or name no originating source) can't be followed class by class.
let has_changes = !changed.is_empty() || !removed.is_empty() || !upstream_changed.is_empty();
let from_scratch =
from_scratch || ((!previous.generated.is_empty() || !previous.unowned.is_empty()) && has_changes);
let mut state = SetState {
stamp,
sources: source_stamps.clone(),
generation: previous.generation,
upstream,
classes: previous.classes,
changes: previous.changes,
..Default::default()
};
let mut api_changed = BTreeSet::new();
let mut constants_changed = false;
// Classes of removed sources go first, and count as changed.
let gone: Vec<String> = state
.classes
.iter()
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| removed.contains(s)))
.map(|(n, _)| n.clone())
.collect();
let gone_empty = gone.is_empty();
for name in gone {
let record = state.classes.remove(&name).expect("listed");
let _ = std::fs::remove_file(&record.file);
constants_changed |= record.constants != incremental::NO_CONSTANTS;
api_changed.insert(name);
}
let mut to_compile: BTreeSet<PathBuf> = if from_scratch || constants_changed {
remove_classes(&set.output);
for file in previous.generated.iter().chain(&previous.unowned) {
let _ = std::fs::remove_file(file);
}
let _ = std::fs::remove_dir_all(&set.generated_dir);
state.classes.retain(|_, r| r.source.is_some());
source_stamps.keys().cloned().collect()
} else {
let affected =
incremental::with_subclasses(&state.classes, &upstream_changed.union(&api_changed).cloned().collect());
changed.iter().cloned().chain(incremental::dependent_sources(&state.classes, &affected)).collect()
};
std::fs::create_dir_all(&set.output)?;
std::fs::create_dir_all(&set.generated_dir)?;
let total = source_stamps.len();
let mut compiled: BTreeSet<PathBuf> = BTreeSet::new();
let mut server = None;
loop {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let batch: BTreeSet<PathBuf> = to_compile
.iter()
.filter(|s| !compiled.contains(*s) && source_stamps.contains_key(*s))
.cloned()
.collect();
if batch.is_empty() {
break;
}
// The classes the batch replaces: their files go first, so nothing stale is left.
let replaced: BTreeMap<String, ClassRecord> = state
.classes
.iter()
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| batch.contains(s)))
.map(|(n, r)| (n.clone(), r.clone()))
.collect();
for (name, record) in &replaced {
let _ = std::fs::remove_file(&record.file);
state.classes.remove(name);
}
let files: Vec<PathBuf> = batch.iter().cloned().collect();
let noun = if total == 1 { "file" } else { "files" };
let count = if files.len() == total {
format!("{total} {noun}")
} else {
format!("{} of {total} {noun}", files.len())
};
on_event(BuildEvent::Step {
command: format!("javac {} ({}, {count})", set.module_name, set.set_name),
cwd: set.cwd.clone().into(),
});
if server.is_none() {
let key = ServerKey { java_home: set.java_home.clone(), jvm_args: set.jvm_args.clone() };
server = Some(self.servers.server(set.jar, &key)?);
}
let mut written: Vec<(PathBuf, Option<PathBuf>)> = Vec::new();
let result =
server.as_ref().expect("started").compile(&set.options, &files, set.encoding, cancel, |reply| {
match reply {
Reply::Output { path, source } => written.push((path.clone(), source.clone())),
Reply::Generated { path, .. } => state.generated.push(path.clone()),
Reply::OutputText { text } => {
on_event(BuildEvent::Output { text: text.clone(), stderr: false })
}
Reply::Diagnostic { .. } => {
if let Some(m) = diagnostic(reply) {
on_event(BuildEvent::Output {
text: message_text(&m),
stderr: m.severity == Severity::Error,
});
on_event(BuildEvent::Message { message: m.clone() });
messages.push(m);
}
}
Reply::Done { .. } => {}
}
});
if !matches!(result, Ok(true)) {
for (path, _) in &written {
let _ = std::fs::remove_file(path);
}
// The next build starts from the state this one started from, with whatever this
// one had to compile still to compile. Its earlier rounds' classes are not the
// baseline: compared with them, the API and constant changes those rounds found
// would never reach this set's dependents or the sets compiled against it.
let mut retry = incremental::load_state(&set.state_file).unwrap_or_default();
retry.dirty.extend(to_compile.union(&compiled).filter(|s| source_stamps.contains_key(*s)).cloned());
retry.success = false;
let _ = model::write_json(&set.state_file, &retry);
return result.map(|_| IncrementalOutcome {
failed: true,
compiled_files: compiled.len(),
outputs_changed: false,
});
}
// javac names sources as they were passed; other spellings are matched canonically,
// and classes of sources outside the set (processors' output) are unowned.
let canonical: HashMap<PathBuf, &PathBuf> =
batch.iter().filter_map(|s| Some((dunce::canonicalize(s).ok()?, s))).collect();
let own = |source: PathBuf| -> Option<PathBuf> {
if source_stamps.contains_key(&source) {
return Some(source);
}
canonical.get(&dunce::canonicalize(&source).ok()?).map(|s| (*s).clone())
};
let mut fresh = BTreeMap::new();
for (path, source) in written {
let source = source.and_then(own);
let class = (path.extension().is_some_and(|e| e == "class"))
.then(|| std::fs::read(&path).ok())
.flatten()
.and_then(|bytes| classfile::parse(&bytes));
match (class, source) {
(Some(class), Some(source)) => {
let (name, record) = ClassRecord::new(class, path, Some(source));
fresh.insert(name, record);
}
_ => state.unowned.push(path),
}
}
let round = incremental::diff(&replaced, &fresh);
constants_changed |= round.constants;
api_changed.extend(round.api.iter().cloned());
state.classes.extend(fresh);
compiled.extend(batch);
if constants_changed {
// Constants are copied into the classes that use them: compile the rest too.
to_compile.extend(source_stamps.keys().cloned());
continue;
}
let affected =
incremental::with_subclasses(&state.classes, &round.api.union(&upstream_changed).cloned().collect());
to_compile.extend(incremental::dependent_sources(&state.classes, &affected));
to_compile.extend(incremental::shadowed_sources(&state.classes, &round.added));
}
state.success = true;
if !compiled.is_empty() || !api_changed.is_empty() {
let changed =
incremental::with_subclasses(&state.classes, &api_changed.union(&upstream_changed).cloned().collect());
state.log(now_generation(), changed, !had_state || constants_changed);
}
model::write_json(&set.state_file, &state)?;
Ok(IncrementalOutcome {
failed: false,
compiled_files: compiled.len(),
outputs_changed: !compiled.is_empty() || !gone_empty,
})
}
}
/// Inputs for compiling one source set incrementally with the resident `javac` server.
pub struct IncrementalSet<'a> {
pub module_name: String,
pub set_name: &'static str,
pub cwd: PathBuf,
pub sources: Vec<PathBuf>,
pub output: PathBuf,
pub options: Vec<String>,
pub libraries: Vec<PathBuf>,
/// Upstream `(output_dir, state_file)` pairs this set compiles against.
pub upstream_states: Vec<(PathBuf, PathBuf)>,
pub processor_path: Vec<PathBuf>,
pub java_home: PathBuf,
pub jvm_args: Vec<String>,
pub encoding: Option<&'a str>,
pub state_file: PathBuf,
pub generated_dir: PathBuf,
pub force: &'a BTreeSet<PathBuf>,
pub jar: &'a Path,
pub clean: bool,
}
/// Result of compiling one source set incrementally.
#[derive(Debug, Default)]
pub struct IncrementalOutcome {
pub failed: bool,
pub compiled_files: usize,
pub outputs_changed: bool,
}
/// One build of the IDE's Java build service.
@@ -79,6 +370,8 @@ pub struct JavaBuild<'a> {
/// Changes when the jar does, so models recorded by an older extension are prepared again.
pub jar_version: &'a str,
pub local_repo: Option<PathBuf>,
/// Explicit Maven goals the project's settings allow the IDE to skip in compile phases.
pub ignored_maven_compile_goals: &'a [String],
pub service: &'a JavaBuildService,
/// The JDK home that compiles for a release, when Maven's environment names none.
pub jdk: &'a (dyn Fn(Option<u32>) -> Option<PathBuf> + Sync),
@@ -250,15 +543,11 @@ fn java_sources(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<Vec<Pa
Ok(out)
}
/// `-g`, `-g:lines,vars` or `-g:none`, as maven-compiler-plugin passes them.
fn debug_args(c: &CompilerConfig) -> Vec<String> {
if c.debug == Some(false) {
return vec!["-g:none".into()];
}
match c.debuglevel.as_deref().map(str::trim).filter(|l| !l.is_empty()) {
Some(level) => vec![format!("-g:{level}")],
None => vec!["-g".into()],
}
/// A javac debug-info option (`-g`, `-g:none`, `-g:lines,vars`). The IDE's build always
/// compiles with `-g`: breakpoints need line numbers and local variables, whatever
/// maven-compiler-plugin's `<debug>` / `<debuglevel>` ask of Maven's own build (#7786).
fn is_debug_option(arg: &str) -> bool {
arg == "-g" || arg.starts_with("-g:")
}
/// The JDK feature version of `release` / `source` (`1.8` → 8).
@@ -294,7 +583,7 @@ fn javac_options(set: &SourceSet, classpath: &[PathBuf], generated: &Path, jdk_m
if let Some(proc) = c.proc.as_deref().filter(|p| !p.is_empty()) {
args.push(format!("-proc:{proc}"));
}
args.extend(debug_args(&c));
args.push("-g".into());
if c.parameters == Some(true) {
args.push("-parameters".into());
}
@@ -323,15 +612,19 @@ fn javac_options(set: &SourceSet, classpath: &[PathBuf], generated: &Path, jdk_m
}
}
for (key, value) in &c.compiler_arguments {
args.push(if key.starts_with('-') { key.clone() } else { format!("-{key}") });
let key = if key.starts_with('-') { key.clone() } else { format!("-{key}") };
if is_debug_option(&key) {
continue;
}
args.push(key);
if let Some(value) = value.as_ref().filter(|v| !v.is_empty()) {
args.push(value.clone());
}
}
if let Some(argument) = &c.compiler_argument {
args.extend(argument.split_whitespace().map(str::to_owned));
args.extend(argument.split_whitespace().filter(|a| !is_debug_option(a)).map(str::to_owned));
}
args.extend(c.compiler_args.iter().filter(|a| !a.is_empty()).cloned());
args.extend(c.compiler_args.iter().filter(|a| !a.is_empty() && !is_debug_option(a)).cloned());
args
}
@@ -558,7 +851,7 @@ impl JavaBuild<'_> {
}
};
for (project, test) in &projects {
if let Some(reason) = project.unsupported(*test) {
if let Some(reason) = project.unsupported(*test, self.ignored_maven_compile_goals) {
return Ok(Built::Unsupported(reason));
}
// A launch of a Java module runs it from the module path, which the language server reports.
@@ -667,6 +960,7 @@ impl JavaBuild<'_> {
for project in &reactor_model.projects {
for test in [false, true] {
let stamp = resource_stamp(project.set(test), cancel)?;
self.prune_resources(dir, project, test, cancel)?;
model::write_json(&state_path(dir, project, test, "resources"), &stamp)?;
}
}
@@ -734,11 +1028,42 @@ impl JavaBuild<'_> {
}));
}
for (project, test, stamp) in changed {
self.prune_resources(dir, project, test, cancel)?;
model::write_json(&state_path(dir, project, test, "resources"), &stamp)?;
}
Ok(None)
}
/// Removes what the sources no longer have from a source set's output: the resources step
/// copies and overwrites, it never deletes, so a file deleted from the sources would stay on
/// the launch's classpath (a stale `META-INF/spring.factories` then fails the application).
fn prune_resources(
&self,
dir: &Path,
project: &ProjectModel,
test: bool,
cancel: &CancellationToken,
) -> IdeResult<()> {
let set = project.set(test);
let expected = resource_outputs(set, cancel)?;
let recorded: BTreeSet<PathBuf> = std::fs::read(state_path(dir, project, test, "resource-outputs"))
.ok()
.and_then(|b| serde_json::from_slice(&b).ok())
.unwrap_or_default();
for stale in recorded.difference(&expected) {
let _ = std::fs::remove_file(stale);
// The folders a removed resource leaves empty are not part of the output either.
let mut parent = stale.parent();
while let Some(folder) = parent.filter(|d| d.starts_with(&set.output) && *d != set.output) {
if std::fs::remove_dir(folder).is_err() {
break;
}
parent = folder.parent();
}
}
model::write_json(&state_path(dir, project, test, "resource-outputs"), &expected)
}
/// Removes the classes of a source set and its record: the next build compiles it from scratch.
fn clean(&self, dir: &Path, project: &ProjectModel, test: bool) -> IdeResult<()> {
let set = project.set(test);
@@ -762,244 +1087,46 @@ impl JavaBuild<'_> {
return Ok(false);
}
let sources = java_sources(set, cancel)?;
let source_stamps: BTreeMap<PathBuf, FileStamp> =
sources.iter().filter_map(|s| Some((s.clone(), file_stamp(s)?))).collect();
let state_file = state_path(dir, project, test, "compile");
let previous = incremental::load_state(&state_file);
let config = set.compiler.clone().unwrap_or_default();
let release = config.release.as_deref().or(config.source.as_deref()).and_then(feature);
let java_home = self.java_home(top, &config, release)?;
let generated = generated_dir(dir, project, test);
let generated_dir = generated_dir(dir, project, test);
let classpath: Vec<PathBuf> = if test {
std::iter::once(project.main.output.clone()).chain(set.classpath.iter().cloned()).collect()
} else {
set.classpath.clone()
};
let options = javac_options(set, &classpath, &generated, jdk_major(&java_home));
let reactor: Vec<PathBuf> =
classpath.iter().filter(|e| **e != set.output && outputs.contains_key(*e)).cloned().collect();
let stamp = SetStamp {
options: options.clone(),
libraries: classpath
.iter()
.filter(|e| **e != set.output && !outputs.contains_key(*e))
.map(|e| (e.clone(), file_stamp(e)))
.collect(),
reactor: reactor.clone(),
processor_path: config.processor_path.iter().flatten().map(|p| (p.clone(), file_stamp(p))).collect(),
java_home: java_home.clone(),
};
// What the reactor outputs it compiles against changed since it last compiled.
let mut upstream = BTreeMap::new();
let mut upstream_changed = BTreeSet::new();
let mut upstream_all = false;
for entry in &reactor {
let (key, entry_test) = &outputs[entry];
let state = incremental::load_state(&state_path_of(dir, key, *entry_test, "compile"));
let generation = state.as_ref().map_or(0, |s| s.generation);
upstream.insert(entry.clone(), generation);
let recorded = previous.as_ref().and_then(|p| p.upstream.get(entry)).copied();
if recorded == Some(generation) {
continue;
}
match (recorded, state.and_then(|s| s.changes_since(recorded?))) {
(Some(_), Some(changed)) => upstream_changed.extend(changed),
_ => upstream_all = true,
}
}
let had_state = previous.is_some();
let previous = previous.unwrap_or_default();
let changed: BTreeSet<PathBuf> = source_stamps
let options = javac_options(set, &classpath, &generated_dir, jdk_major(&java_home));
let upstream_states: Vec<(PathBuf, PathBuf)> = classpath
.iter()
.filter(|(path, stamp)| {
previous.sources.get(*path) != Some(*stamp) || previous.dirty.contains(*path) || force.contains(*path)
.filter(|e| **e != set.output)
.filter_map(|e| {
outputs.get(e).map(|(key, entry_test)| (e.clone(), state_path_of(dir, key, *entry_test, "compile")))
})
.map(|(path, _)| path.clone())
.collect();
let removed: BTreeSet<PathBuf> =
previous.sources.keys().filter(|p| !source_stamps.contains_key(*p)).cloned().collect();
let from_scratch = !had_state
|| previous.stamp != stamp
|| upstream_all
|| !set.output.is_dir()
|| (!previous.success && previous.dirty.is_empty());
if !from_scratch && changed.is_empty() && removed.is_empty() && upstream_changed.is_empty() {
return Ok(false);
}
// Processors that aggregate (or name no originating source) can't be followed class by class.
let from_scratch = from_scratch
|| (!previous.generated.is_empty() || !previous.unowned.is_empty())
&& !(changed.is_empty() && removed.is_empty() && upstream_changed.is_empty());
let mut state = SetState {
stamp,
sources: source_stamps.clone(),
generation: previous.generation,
upstream,
classes: previous.classes,
changes: previous.changes,
..Default::default()
let libraries: Vec<PathBuf> =
classpath.iter().filter(|e| **e != set.output && !outputs.contains_key(*e)).cloned().collect();
let incremental_set = IncrementalSet {
module_name: project.artifact_id.clone(),
set_name: if test { "tests" } else { "main" },
cwd: project.dir.clone(),
sources,
output: set.output.clone(),
options,
libraries,
upstream_states,
processor_path: config.processor_path.unwrap_or_default(),
jvm_args: jvm_config(top, &subdir(self.root, top.rel_dir())),
java_home,
encoding: config.encoding.as_deref(),
state_file: state_path(dir, project, test, "compile"),
generated_dir,
force,
jar: self.jar,
clean: false,
};
let mut api_changed = BTreeSet::new();
let mut constants_changed = false;
// Classes of removed sources go first, and count as changed.
let gone: Vec<String> = state
.classes
.iter()
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| removed.contains(s)))
.map(|(n, _)| n.clone())
.collect();
for name in gone {
let record = state.classes.remove(&name).expect("listed");
let _ = std::fs::remove_file(&record.file);
constants_changed |= record.constants != incremental::NO_CONSTANTS;
api_changed.insert(name);
}
let mut to_compile: BTreeSet<PathBuf> = if from_scratch || constants_changed {
remove_classes(&set.output);
for file in previous.generated.iter().chain(&previous.unowned) {
let _ = std::fs::remove_file(file);
}
let _ = std::fs::remove_dir_all(&generated);
state.classes.retain(|_, r| r.source.is_some());
source_stamps.keys().cloned().collect()
} else {
let affected =
incremental::with_subclasses(&state.classes, &upstream_changed.union(&api_changed).cloned().collect());
changed.iter().cloned().chain(incremental::dependent_sources(&state.classes, &affected)).collect()
};
std::fs::create_dir_all(&set.output)?;
std::fs::create_dir_all(&generated)?;
let set_name = if test { "tests" } else { "main" };
let total = source_stamps.len();
let mut compiled: BTreeSet<PathBuf> = BTreeSet::new();
let mut server = None;
loop {
let batch: BTreeSet<PathBuf> = to_compile
.iter()
.filter(|s| !compiled.contains(*s) && source_stamps.contains_key(*s))
.cloned()
.collect();
if batch.is_empty() {
break;
}
// The classes the batch replaces: their files go first, so nothing stale is left.
let replaced: BTreeMap<String, ClassRecord> = state
.classes
.iter()
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| batch.contains(s)))
.map(|(n, r)| (n.clone(), r.clone()))
.collect();
for (name, record) in &replaced {
let _ = std::fs::remove_file(&record.file);
state.classes.remove(name);
}
let files: Vec<PathBuf> = batch.iter().cloned().collect();
let noun = if total == 1 { "file" } else { "files" };
let count = if files.len() == total {
format!("{total} {noun}")
} else {
format!("{} of {total} {noun}", files.len())
};
on_event(BuildEvent::Step {
command: format!("javac {} ({set_name}, {count})", project.artifact_id),
cwd: project.dir.clone().into(),
});
if server.is_none() {
let key = ServerKey {
java_home: java_home.clone(),
jvm_args: jvm_config(top, &subdir(self.root, top.rel_dir())),
};
server = Some(self.service.servers.server(self.jar, &key)?);
}
let mut written: Vec<(PathBuf, Option<PathBuf>)> = Vec::new();
let result = server.as_ref().expect("started").compile(
&options,
&files,
config.encoding.as_deref(),
cancel,
|reply| match reply {
Reply::Output { path, source } => written.push((path.clone(), source.clone())),
Reply::Generated { path, .. } => state.generated.push(path.clone()),
Reply::OutputText { text } => on_event(BuildEvent::Output { text: text.clone(), stderr: false }),
Reply::Diagnostic { .. } => {
if let Some(m) = diagnostic(reply) {
on_event(BuildEvent::Output {
text: message_text(&m),
stderr: m.severity == Severity::Error,
});
on_event(BuildEvent::Message { message: m.clone() });
messages.push(m);
}
}
Reply::Done { .. } => {}
},
);
if !matches!(result, Ok(true)) {
for (path, _) in &written {
let _ = std::fs::remove_file(path);
}
// The next build starts from the state this one started from, with whatever this
// one had to compile still to compile. Its earlier rounds' classes are not the
// baseline: compared with them, the API and constant changes those rounds found
// would never reach this set's dependents or the sets compiled against it.
let mut retry = incremental::load_state(&state_file).unwrap_or_default();
retry.dirty.extend(to_compile.union(&compiled).filter(|s| source_stamps.contains_key(*s)).cloned());
retry.success = false;
let _ = model::write_json(&state_file, &retry);
return result.map(|_| true);
}
// javac names sources as they were passed; other spellings are matched canonically,
// and classes of sources outside the set (processors' output) are unowned.
let canonical: HashMap<PathBuf, &PathBuf> =
batch.iter().filter_map(|s| Some((dunce::canonicalize(s).ok()?, s))).collect();
let own = |source: PathBuf| -> Option<PathBuf> {
if source_stamps.contains_key(&source) {
return Some(source);
}
canonical.get(&dunce::canonicalize(&source).ok()?).map(|s| (*s).clone())
};
let mut fresh = BTreeMap::new();
for (path, source) in written {
let source = source.and_then(own);
let class = (path.extension().is_some_and(|e| e == "class"))
.then(|| std::fs::read(&path).ok())
.flatten()
.and_then(|bytes| classfile::parse(&bytes));
match (class, source) {
(Some(class), Some(source)) => {
let (name, record) = ClassRecord::new(class, path, Some(source));
fresh.insert(name, record);
}
_ => state.unowned.push(path),
}
}
let round = incremental::diff(&replaced, &fresh);
constants_changed |= round.constants;
api_changed.extend(round.api.iter().cloned());
state.classes.extend(fresh);
compiled.extend(batch);
if constants_changed {
// Constants are copied into the classes that use them: compile the rest too.
to_compile.extend(source_stamps.keys().cloned());
continue;
}
let affected =
incremental::with_subclasses(&state.classes, &round.api.union(&upstream_changed).cloned().collect());
to_compile.extend(incremental::dependent_sources(&state.classes, &affected));
to_compile.extend(incremental::shadowed_sources(&state.classes, &round.added));
}
state.success = true;
if !compiled.is_empty() || !api_changed.is_empty() {
let changed =
incremental::with_subclasses(&state.classes, &api_changed.union(&upstream_changed).cloned().collect());
state.log(now_generation(), changed, !had_state || constants_changed);
}
model::write_json(&state_file, &state)?;
Ok(false)
let outcome = self.service.compile_incremental(&incremental_set, cancel, on_event, messages)?;
Ok(outcome.failed)
}
/// The JDK compiling a source set: the compiler plugin's forked `executable`, else Maven's
@@ -1133,5 +1260,35 @@ fn resource_stamp(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTre
Ok(out)
}
/// Where `process-resources` puts each file of a source set's resource folders: the output folder,
/// the root's target path, then the path under the root, filtered by its includes and excludes.
fn resource_outputs(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTreeSet<PathBuf>> {
let mut out = BTreeSet::new();
for root in &set.resources {
let mut pending = vec![root.directory.clone()];
while let Some(dir) = pending.pop() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
for entry in entries.flatten() {
let path = entry.path();
if entry.file_type().is_ok_and(|t| t.is_dir()) {
pending.push(path);
continue;
}
let rel = path.strip_prefix(&root.directory).unwrap_or(&path).to_string_lossy().replace('\\', "/");
let included = root.includes.is_empty() || root.includes.iter().any(|p| ant_match(p, &rel));
if !included || root.excludes.iter().any(|p| ant_match(p, &rel)) {
continue;
}
let target = root.target_path.as_deref().unwrap_or("").replace('\\', "/");
out.insert(set.output.join(target.trim_matches('/')).join(&rel));
}
}
}
Ok(out)
}
#[cfg(test)]
mod tests;
+16 -3
Переглянути файл
@@ -105,13 +105,26 @@ impl ProjectModel {
}
/// Why the IDE can't compile this project with javac itself, if it can't.
pub fn unsupported(&self, test: bool) -> Option<String> {
pub fn unsupported(&self, test: bool, ignored_maven_compile_goals: &[String]) -> Option<String> {
// What the build tool couldn't resolve or read: the model would be incomplete.
if let Some(problem) = self.problems.first() {
return Some(format!("{}: {problem}", self.artifact_id));
}
if !self.other_compilers.is_empty() {
return Some(format!("{} also compiles with {}", self.artifact_id, self.other_compilers.join(", ")));
// Keep the recorded model intact: adding or removing a project override must also
// affect an already prepared model. Gradle tasks never use Maven overrides.
let other_compilers: Vec<&str> = self
.other_compilers
.iter()
.filter(|execution| {
!(self.gradle_path.is_none()
&& execution.split_once('@').is_some_and(|(goal, _)| {
ignored_maven_compile_goals.iter().any(|ignored| ignored.trim() == goal)
}))
})
.map(String::as_str)
.collect();
if !other_compilers.is_empty() {
return Some(format!("{} also compiles with {}", self.artifact_id, other_compilers.join(", ")));
}
if test && !self.test_generators.is_empty() {
return Some(format!(
+235 -9
Переглянути файл
@@ -55,6 +55,75 @@ fn maven_resources_select_projects_by_coordinates_not_by_basedir() {
assert_eq!(maven_project_selection(projects.iter()), "org.starry:cloud,org.starry:organ");
}
#[test]
fn maven_compile_goal_overrides_apply_to_cached_models_and_can_be_removed() {
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
let project = ProjectModel {
artifact_id: "app".into(),
other_compilers: vec![format!("{goal}@default-jar"), format!("{goal}@extra-jar")],
..Default::default()
};
let cached: ProjectModel = serde_json::from_str(&serde_json::to_string(&project).unwrap()).unwrap();
assert!(cached.unsupported(false, &[]).unwrap().contains(goal));
assert_eq!(cached.unsupported(false, &[goal.into()]), None);
assert_eq!(cached.unsupported(false, &[format!(" {goal} ")]), None);
assert!(cached.unsupported(false, &[]).unwrap().contains(goal));
assert_eq!(cached.other_compilers, project.other_compilers);
}
#[test]
fn maven_compile_goal_overrides_match_exact_goals_and_keep_other_executions() {
let jar = "org.apache.maven.plugins:maven-jar-plugin:jar";
let kotlin = "org.jetbrains.kotlin:kotlin-maven-plugin:compile";
let mut project = ProjectModel {
artifact_id: "app".into(),
other_compilers: vec![format!("{jar}@default-jar")],
..Default::default()
};
for unmatched in [
"",
"*",
"org.apache.maven.plugins:maven-jar-plugin",
"maven-jar-plugin:jar",
"org.apache.maven.plugins:maven-jar-plugin:test-jar",
"org.apache.maven.plugins:*:jar",
] {
assert!(project.unsupported(false, &[unmatched.into()]).is_some(), "{unmatched}");
}
project.other_compilers.push(format!("{kotlin}@compile"));
let reason = project.unsupported(false, &[jar.into()]).unwrap();
assert!(reason.contains(kotlin));
assert!(!reason.contains(jar));
}
#[test]
fn maven_compile_goal_overrides_do_not_affect_gradle_or_other_safety_checks() {
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
let ignored = [goal.into()];
let mut project = ProjectModel {
artifact_id: "app".into(),
other_compilers: vec![format!("{goal}@default-jar")],
..Default::default()
};
project.gradle_path = Some(":app".into());
assert!(project.unsupported(false, &ignored).is_some());
project.gradle_path = None;
project.problems.push("unresolved dependency".into());
assert!(project.unsupported(false, &ignored).unwrap().contains("unresolved dependency"));
project.problems.clear();
project.test_generators.push("org.example:generator:test@tests".into());
assert_eq!(project.unsupported(false, &ignored), None);
assert!(project.unsupported(true, &ignored).unwrap().contains("generates test sources"));
project.test_generators.clear();
project.main.compiler = Some(CompilerConfig { compiler_id: Some("eclipse".into()), ..Default::default() });
assert!(project.unsupported(false, &ignored).unwrap().contains("eclipse"));
project.main.compiler = Some(CompilerConfig { multi_release_output: Some(true), ..Default::default() });
assert!(project.unsupported(false, &ignored).unwrap().contains("multi-release"));
project.main.compiler =
Some(CompilerConfig { processor_path_error: Some("missing processor".into()), ..Default::default() });
assert!(project.unsupported(false, &ignored).unwrap().contains("missing processor"));
}
/// 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())?;
@@ -169,6 +238,17 @@ impl Fixture {
}
fn build(&self, target: Target) -> LaunchOutputs {
match self.try_build(target, &[]) {
Ok(Built::Done(outputs)) => outputs,
Ok(Built::Unsupported(reason)) => {
let output = build_output_tail(&self.events.lock().unwrap());
panic!("unsupported: {reason}\n{output}");
}
Err(e) => panic!("{e:?}"),
}
}
fn try_build(&self, target: Target, ignored_maven_compile_goals: &[String]) -> IdeResult<Built> {
let jdk = |_: Option<u32>| None;
let build = JavaBuild {
root: &self.root,
@@ -177,18 +257,12 @@ impl Fixture {
jar: Path::new(JAR),
jar_version: "test",
local_repo: None,
ignored_maven_compile_goals,
service: &self.service,
jdk: &jdk,
};
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)) => {
let output = build_output_tail(&self.events.lock().unwrap());
panic!("unsupported: {reason}\n{output}");
}
Err(e) => panic!("{e:?}"),
}
build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event)
}
/// The steps of the launch builds since the last call.
@@ -213,6 +287,37 @@ impl Fixture {
}
}
#[test]
fn a_real_maven_compile_goal_can_be_skipped_with_a_cached_reactor() {
let pom = APP_POM.replace(
"</build>",
concat!(
"<plugins><plugin><groupId>org.apache.maven.plugins</groupId>",
"<artifactId>maven-jar-plugin</artifactId><version>3.4.1</version>",
"<executions><execution><id>early-jar</id><phase>compile</phase>",
"<goals><goal>jar</goal></goals></execution></executions></plugin></plugins></build>",
),
);
let Some(f) = Fixture::new(&[
("app/pom.xml", &pom),
("lib/src/main/java/l/L.java", "package l; public class L {}"),
("app/src/main/java/a/A.java", "package a; public class A { l.L dependency; }"),
]) else {
return;
};
let module = f.root.join("app");
let go = |ignored: &[String]| f.try_build(Target::Launch { module: &module, test: false }, ignored).unwrap();
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
assert!(matches!(go(&[]), Built::Unsupported(reason) if reason.contains(goal)));
f.steps();
let Built::Done(output) = go(&[goal.into()]) else { panic!("expected the configured build to use javac") };
assert!(output.failure.is_none(), "{:?}", output.messages);
assert!(f.out("t.app/classes/a/A.class").is_file());
assert!(!f.root.join("app/target/app-1.jar").exists());
assert!(f.steps().iter().all(|step| step.starts_with("javac")), "the prepared model was reused");
assert!(matches!(go(&[]), Built::Unsupported(reason) if reason.contains(goal)));
}
#[test]
fn builds_maven_modules_with_javac_and_only_what_changed() {
let Some(f) = Fixture::new(&[
@@ -311,6 +416,104 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
assert!(f.out("t.app/test-classes/a/AggTest.class").is_file());
}
/// #7743: a dependency's own dependencies come before its next sibling on the classpath, as in
/// `mvn compile`, so of two artifacts with the same classes (`dom4j:dom4j` 1.x and
/// `org.dom4j:dom4j` 2.x) javac sees the one Maven does.
#[test]
fn maven_classpath_lists_dependencies_in_maven_order() {
let module = |name: &str, deps: &[&str]| {
let deps: String = deps
.iter()
.map(|d| {
format!("<dependency><groupId>t</groupId><artifactId>{d}</artifactId><version>1</version></dependency>")
})
.collect();
format!(
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId>\
<version>1</version></parent><artifactId>{name}</artifactId><dependencies>{deps}</dependencies></project>"
)
};
let root = ROOT_POM.replace(
"<module>lib</module>",
"<module>newdom</module><module>olddom</module><module>x</module><module>lib</module>",
);
let (newdom, olddom, x, lib) =
(module("newdom", &[]), module("olddom", &[]), module("x", &["newdom"]), module("lib", &["x", "olddom"]));
let Some(f) = Fixture::new(&[
("pom.xml", &root),
("newdom/pom.xml", &newdom),
("olddom/pom.xml", &olddom),
("x/pom.xml", &x),
("lib/pom.xml", &lib),
("newdom/src/main/java/d/Element.java", "package d;\npublic class Element { public void fresh() {} }\n"),
("olddom/src/main/java/d/Element.java", "package d;\npublic class Element {}\n"),
("app/src/main/java/a/A.java", "package a;\nclass A { void f() { new d.Element().fresh(); } }\n"),
]) else {
return;
};
let built = f.launch(false);
assert_eq!(built.failure, None, "{:?}", built.messages);
let position = |name: &str| built.class_paths.iter().position(|p| *p == f.out(&format!("t.{name}/classes")));
assert!(position("newdom") < position("olddom"), "{:?}", built.class_paths);
}
#[test]
fn maps_resources_to_the_output_paths_the_build_tool_writes() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
write(&root, "src/main/resources/app.properties", "a=1");
write(&root, "src/main/resources/notes.txt", "n");
write(&root, "src/main/resources/deep/app.properties", "b=2");
let resources = root.join("src/main/resources");
let output = root.join("out/classes");
let set = SourceSet {
output: output.clone(),
resources: vec![
ResourceRoot { directory: resources.clone(), ..Default::default() },
// A `<targetPath>` and an `<includes>` pattern, as a POM can configure them.
ResourceRoot {
directory: resources,
target_path: Some("META-INF".into()),
includes: vec!["*.properties".into()],
..Default::default()
},
],
..Default::default()
};
assert_eq!(
resource_outputs(&set, &CancellationToken::new()).unwrap(),
BTreeSet::from([
output.join("app.properties"),
output.join("notes.txt"),
output.join("deep/app.properties"),
output.join("META-INF/app.properties"),
])
);
}
#[test]
fn deletes_the_output_of_a_resource_removed_from_the_sources() {
let Some(f) = Fixture::new(&[
("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"),
("app/src/main/resources/app.properties", "version=${project.version}\n"),
("app/src/main/resources/META-INF/spring.factories", "a.A\n"),
]) else {
return;
};
assert_eq!(f.launch(false).failure, None);
assert_eq!(fs::read_to_string(f.out("t.app/classes/META-INF/spring.factories")).unwrap(), "a.A\n");
assert!(f.steps_of_launch().is_empty());
// A deleted resource leaves no copy behind: the launch would read a file the sources no longer have.
fs::remove_file(f.root.join("app/src/main/resources/META-INF/spring.factories")).unwrap();
let steps = f.steps_of_launch();
assert!(steps.iter().any(|s| s.contains("resources:resources")), "{steps:?}");
assert!(!f.out("t.app/classes/META-INF/spring.factories").exists(), "the removed resource stays on the classpath");
// The resource that is still there keeps its copy, and a launch with nothing changed runs nothing.
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
assert!(f.steps_of_launch().is_empty());
}
#[test]
fn recompiles_the_classes_an_api_change_reaches() {
let Some(f) = Fixture::new(&[
@@ -487,7 +690,7 @@ fn javac_options_follow_the_compiler_configuration() {
"-processorpath /p.jar",
"-processor a.P",
"-proc:none",
"-g:lines,vars",
"-g",
"-parameters",
"-nowarn",
"-encoding UTF-8",
@@ -502,6 +705,28 @@ fn javac_options_follow_the_compiler_configuration() {
assert!(old.contains("-source 1.8") && !old.contains("--release"), "{old}");
}
#[test]
fn javac_options_always_keep_debug_info() {
// `<debug>false</debug>` makes Maven pass `-g:none`; the IDE's build still emits the line
// numbers and variables the debugger needs (#7786).
let set = SourceSet {
output: PathBuf::from("/o"),
compiler: Some(CompilerConfig {
debug: Some(false),
debuglevel: Some("source".into()),
compiler_args: vec!["-g:none".into(), "-Xlint:all".into()],
compiler_argument: Some("-g:source -Xlint:none".into()),
compiler_arguments: [("g:none".to_owned(), None)].into(),
..Default::default()
}),
..Default::default()
};
let args = javac_options(&set, &[], Path::new("/gen"), Some(21));
let debug: Vec<_> = args.iter().filter(|a| a.starts_with("-g")).collect();
assert_eq!(debug, ["-g"], "{args:?}");
assert!(args.iter().any(|a| a == "-Xlint:all") && args.iter().any(|a| a == "-Xlint:none"), "{args:?}");
}
#[test]
fn builds_gradle_projects_with_javac_and_only_what_changed() {
let Some(f) = Fixture::gradle(&[
@@ -583,6 +808,7 @@ fn leaves_gradle_projects_with_other_compilers_to_gradle() {
jar: Path::new(JAR),
jar_version: "test",
local_repo: None,
ignored_maven_compile_goals: &[],
service: &f.service,
jdk: &jdk,
};
+116
Переглянути файл
@@ -43,6 +43,10 @@ pub struct MavenModel {
/// Build files changed since that sync.
pub stale: bool,
pub sync_error: Option<String>,
/// The `<activation><jdk>` values of the projects' own POMs that the JDK matches.
#[serde(skip)]
#[specta(skip)]
pub(crate) jdk_activations: std::collections::BTreeSet<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
@@ -92,6 +96,100 @@ impl MavenProject {
}
}
/// All projects belonging to the Maven reactor rooted at `top`, traversed through `<modules>`.
pub(crate) fn reactor_projects<'a>(m: &'a MavenModel, top: &'a MavenProject) -> Vec<&'a MavenProject> {
let mut projects = Vec::new();
let mut pending = vec![top];
let mut seen = HashSet::new();
while let Some(p) = pending.pop() {
if !seen.insert(&p.pom) {
continue;
}
projects.push(p);
pending.extend(m.projects.iter().filter(|child| p.modules.contains(&child.pom)));
}
projects
}
fn reactor_for<'a>(m: &'a MavenModel, target: &'a MavenProject) -> &'a MavenProject {
if !target.aggregated {
return target;
}
let mut matches =
m.projects.iter().filter(|top| !top.aggregated && reactor_projects(m, top).iter().any(|p| p.pom == target.pom));
let first = matches.next();
let ancestor = first
.into_iter()
.chain(matches)
.filter(|top| top.dir.is_empty() || target.dir == top.dir || target.dir.starts_with(&format!("{}/", top.dir)))
.max_by_key(|top| top.dir.len());
ancestor.or(first).unwrap_or(target)
}
/// The linked reactor root owning the project at `pom` (project-relative).
pub(crate) fn reactor_for_pom<'a>(m: &'a MavenModel, pom: &str) -> Option<&'a MavenProject> {
m.projects.iter().find(|p| p.pom == pom).map(|target| reactor_for(m, target))
}
/// The linked reactor root owning the project at `dir` (project-relative).
pub(crate) fn reactor_for_dir<'a>(m: &'a MavenModel, dir: &str) -> Option<&'a MavenProject> {
m.projects.iter().find(|p| p.dir == dir).map(|target| reactor_for(m, target))
}
/// `/`-separated relative path from `from` to `to`, supporting sibling (`../app`) and parent (`..`)
/// module layouts. Returns `None` when the paths do not share a root/drive.
pub(crate) fn relative_module_path(from: &Path, to: &Path) -> Option<String> {
use std::path::Component;
let from = crate::gradle::normalize(from);
let to = crate::gradle::normalize(to);
let from_comps: Vec<_> = from.components().collect();
let to_comps: Vec<_> = to.components().collect();
let common = from_comps.iter().zip(&to_comps).take_while(|(a, b)| a == b).count();
let mut parts = Vec::new();
for comp in &from_comps[common..] {
match comp {
Component::Normal(_) => parts.push("..".into()),
Component::CurDir => {}
Component::ParentDir | Component::Prefix(_) | Component::RootDir => return None,
}
}
for comp in &to_comps[common..] {
match comp {
Component::Normal(s) => parts.push(s.to_string_lossy().into_owned()),
Component::ParentDir => parts.push("..".into()),
Component::CurDir => {}
Component::Prefix(_) | Component::RootDir => return None,
}
}
Some(parts.join("/"))
}
/// Maven `-pl` selector for `module` when invoked from reactor `top` (`None` when `module` is `top`).
pub(crate) fn module_selector(root: &Path, top: &MavenProject, module: &MavenProject) -> Option<String> {
if top.pom == module.pom {
return None;
}
let base = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
let resolve_dir = |dir: &str| {
let raw = if dir.is_empty() { base.clone() } else { base.join(dir) };
dunce::canonicalize(&raw).unwrap_or(raw)
};
let from = resolve_dir(&top.dir);
let to = resolve_dir(&module.dir);
if let Some(rel) = relative_module_path(&from, &to)
&& !rel.is_empty()
{
return Some(rel);
}
if !module.group_id.is_empty() && !module.artifact_id.is_empty() {
Some(format!("{}:{}", module.group_id, module.artifact_id))
} else if !module.artifact_id.is_empty() {
Some(format!(":{}", module.artifact_id))
} else {
None
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MavenPlugin {
@@ -1340,6 +1438,22 @@ pub fn external_pom_dirs(root: &Path, linked: &[String]) -> Vec<PathBuf> {
out
}
/// Linked POMs inside the opened root that a folder scan doesn't reach: it stops at the
/// first folder with a `pom.xml` and follows only that project's modules, so a POM linked
/// below another Maven project's folder (a deployable module its parent doesn't list) is
/// never found. jdtls imports this way.
pub fn linked_poms_below_projects(root: &Path, linked: &[String]) -> Vec<PathBuf> {
let base = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
linked_poms(root, linked)
.into_iter()
.filter(|pom| {
let Some(dir) = pom.parent() else { return false };
dir.starts_with(&base)
&& dir.ancestors().skip(1).take_while(|d| d.starts_with(&base)).any(|d| is_pom_file(&d.join("pom.xml")))
})
.collect()
}
type FileStamp = Option<(Option<std::time::SystemTime>, u64)>;
fn file_stamp(path: &Path) -> FileStamp {
@@ -1510,6 +1624,8 @@ pub fn load_with_linked_jdk(
for p in resolver.active(&pom.profiles) {
module_names.extend(p.modules.iter().cloned());
}
let jdks = pom.profiles.iter().filter_map(|p| p.activation_jdk.as_ref());
model.jdk_activations.extend(jdks.filter(|spec| jdk_matches(spec, jdk_version)).cloned());
let mut modules: Vec<PathBuf> = Vec::new();
for m in module_names {
let mut mp = crate::gradle::normalize(&dir.join(i(&m)));
+103 -3
Переглянути файл
@@ -10,7 +10,7 @@ use crate::process::{self, Output};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use specta::Type;
use std::collections::{BTreeMap, HashMap};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex};
use std::time::SystemTime;
@@ -32,6 +32,8 @@ pub struct SyncOptions {
pub profiles: Vec<String>,
/// Extra environment (`JAVA_HOME`).
pub env: BTreeMap<String, String>,
/// Major version of the JDK Maven runs on, the same as the model is loaded with.
pub jdk_version: Option<u32>,
/// Maven launcher replacing the project's `mvnw` / `mvn` (Settings › Maven home).
pub maven_command: Option<String>,
/// Resolved Gradle launcher from Settings.
@@ -62,6 +64,9 @@ struct MavenCache {
/// The trees list omitted occurrences (`-Dverbose`); older caches are reloaded.
#[serde(default)]
verbose: bool,
/// [`MavenModel::jdk_activations`] of the sync; `None` in caches from before they were recorded.
#[serde(default)]
jdk_activations: Option<BTreeSet<String>>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
@@ -233,7 +238,9 @@ pub fn apply_maven_cache(root: &Path, cache_dir: &Path, model: &mut MavenModel)
}
model.synced_at = Some(cache.at_ms);
model.sync_error = cache.error;
let changed = cache.hash != hash_files(&maven::build_files(root, model));
// Another JDK can switch profiles of the same build files.
let changed = cache.hash != hash_files(&maven::build_files(root, model))
|| cache.jdk_activations.is_some_and(|jdks| jdks != model.jdk_activations);
model.stale = !cache.verbose || changed;
// A cache older than the current build files: its effective-POM plugins and
// resolved dependencies would hide what the POMs declare now (a just added
@@ -368,10 +375,11 @@ pub fn sync_maven(
cancel: &CancellationToken,
progress: &dyn Fn(SyncProgress),
) -> IdeResult<()> {
let mut model = maven::load_with_linked(
let mut model = maven::load_with_linked_jdk(
root,
maven::default_local_repo(),
&options.maven_settings.profiles(&options.profiles),
options.jdk_version,
&options.maven_settings.linked_projects,
);
maven::UnlinkedProjects::from_model(&model, &options.maven_settings).filter(&mut model);
@@ -380,6 +388,7 @@ pub fn sync_maven(
version: MAVEN_CACHE_VERSION,
hash: hash_files(&maven::build_files(root, &model)),
verbose: true,
jdk_activations: Some(model.jdk_activations.clone()),
..MavenCache::default()
};
// Where the build resolves its jars, and therefore where the plugin goals are read from.
@@ -683,6 +692,7 @@ mod tests {
at_ms: 5.0,
error: None,
verbose: true,
jdk_activations: None,
projects: vec![CachedMavenProject {
key: "g:a".into(),
plugins: vec![maven::plugin(
@@ -733,6 +743,7 @@ mod tests {
at_ms: 5.0,
error: None,
verbose: true,
jdk_activations: None,
projects: vec![CachedMavenProject {
key: "g:a".into(),
plugins: vec![maven::plugin(
@@ -1055,6 +1066,95 @@ mod tests {
assert_eq!(std::fs::metadata(&mvnw).unwrap().permissions().mode() & 0o777, 0o644);
}
/// `root` with module `core`, and what `profile` adds when the JDK activates it: the module
/// `modern` or only a property. Synced with `jdk` by a launcher printing `core`'s tree.
#[cfg(unix)]
fn synced_with_a_jdk_profile(base: &Path, profile: &str, jdk: Option<u32>) -> (PathBuf, PathBuf) {
use std::os::unix::fs::PermissionsExt;
let (root, cache) = (base.join("p"), base.join("cache"));
let project = "<project><groupId>g</groupId><version>1</version>";
for module in ["core", "modern"] {
std::fs::create_dir_all(root.join(module)).unwrap();
let pom = format!("{project}<artifactId>{module}</artifactId></project>");
std::fs::write(root.join(module).join("pom.xml"), pom).unwrap();
}
let pom = format!(
"{project}<artifactId>root</artifactId><packaging>pom</packaging><modules><module>core</module></modules>\
<profiles><profile><id>modern</id><activation><jdk>[11,)</jdk></activation>{profile}</profile></profiles>\
</project>"
);
std::fs::write(root.join("pom.xml"), pom).unwrap();
let launcher = base.join("mvn");
let tree = "[INFO] --- dependency:3.8.1:tree (default-cli) @ core ---\\n[INFO] g:core:jar:1\\n\
[INFO] \\\\- g:lib:jar:1:compile\\n[INFO] \\\\- g:transitive:jar:1:compile\\n";
std::fs::write(&launcher, format!("#!/bin/sh\nprintf '{tree}'\n")).unwrap();
std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
let options = SyncOptions {
maven_command: Some(launcher.to_string_lossy().into_owned()),
jdk_version: jdk,
..Default::default()
};
sync_maven(&root, &cache, &options, &CancellationToken::new(), &|_| {}).unwrap();
(root, cache)
}
#[cfg(unix)]
fn loaded_with_jdk((root, cache): &(PathBuf, PathBuf), jdk: Option<u32>) -> MavenModel {
crate::load_linked_with_jdk(root, cache, None, &Default::default(), &Default::default(), jdk).maven.unwrap()
}
#[cfg(unix)]
const MODULE: &str = "<modules><module>modern</module></modules>";
#[cfg(unix)]
const PROPERTY: &str = "<properties><x>1</x></properties>";
#[cfg(unix)]
#[test]
fn a_synced_model_with_a_jdk_profile_is_current() {
for (profile, jdk, modules) in
[(MODULE, Some(17), 3), (MODULE, Some(8), 2), (MODULE, None, 2), (PROPERTY, Some(17), 2)]
{
let tmp = tempfile::tempdir().unwrap();
let model = loaded_with_jdk(&synced_with_a_jdk_profile(tmp.path(), profile, jdk), jdk);
assert_eq!(model.projects.len(), modules, "{profile} {jdk:?}");
assert!(!model.stale, "{profile} {jdk:?}");
let core = model.projects.iter().find(|p| p.artifact_id == "core").unwrap();
assert_eq!(core.dependencies[0].children[0].artifact_id, "transitive", "{profile} {jdk:?}");
}
}
#[cfg(unix)]
#[test]
fn a_jdk_change_is_stale_when_it_switches_a_profile() {
for profile in [MODULE, PROPERTY] {
for (synced, loaded, stale) in [
(Some(17), Some(21), false),
(Some(17), Some(8), true),
(Some(8), Some(17), true),
(Some(17), None, true),
(None, Some(17), true),
(None, Some(8), false),
] {
let tmp = tempfile::tempdir().unwrap();
let model = loaded_with_jdk(&synced_with_a_jdk_profile(tmp.path(), profile, synced), loaded);
assert_eq!(model.stale, stale, "{profile} {synced:?} {loaded:?}");
let core = model.projects.iter().find(|p| p.artifact_id == "core").unwrap();
assert_eq!(core.dependencies.is_empty(), stale, "{profile} {synced:?} {loaded:?}");
}
}
}
#[cfg(unix)]
#[test]
fn a_sync_from_before_jdk_profiles_were_recorded_stays_current() {
let tmp = tempfile::tempdir().unwrap();
let project = synced_with_a_jdk_profile(tmp.path(), PROPERTY, Some(17));
let mut json: serde_json::Value = read_cache(&project.1, MAVEN_CACHE).unwrap();
assert!(json.as_object_mut().unwrap().remove("jdk_activations").is_some());
write_cache(&project.1, MAVEN_CACHE, &json).unwrap();
assert!(!loaded_with_jdk(&project, Some(17)).stale);
}
#[cfg(unix)]
#[test]
fn maven_sync_runs_the_daemon_command_serially() {
+93 -19
Переглянути файл
@@ -110,27 +110,15 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
}
fs::write(cache.join("artifact-id.txt"), id)?;
if let Some(pom) = id.strip_prefix("maven:") {
let p = model
.maven
.as_ref()
.and_then(|m| m.projects.iter().find(|p| p.pom == pom && p.packaging == "war"))
.ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
let projects = &model.maven.as_ref().unwrap().projects;
let top = projects
let maven = model.maven.as_ref().ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
let p = maven
.projects
.iter()
.filter(|t| {
!t.aggregated && (t.dir.is_empty() || p.dir == t.dir || p.dir.starts_with(&format!("{}/", t.dir)))
})
.max_by_key(|t| t.dir.len())
.unwrap_or(p);
.find(|p| p.pom == pom && p.packaging == "war")
.ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
let top = crate::maven::reactor_for_pom(maven, &p.pom).unwrap_or(p);
let mut args = top.options.clone();
if top.pom != p.pom {
let module = root
.join(&p.dir)
.strip_prefix(root.join(&top.dir))
.map_err(|e| IdeError::invalid(e.to_string()))?
.to_string_lossy()
.replace('\\', "/");
if let Some(module) = crate::maven::module_selector(root, top, p) {
args.extend(["-pl".into(), module, "-am".into()]);
}
// help:evaluate runs once, in the reactor's first project. Query the selected
@@ -316,4 +304,90 @@ mod tests {
assert!(!action.contains("p.") && !action.contains("war."), "{action}");
}
}
#[test]
fn maven_sibling_reactor_builds_war_through_aggregator_with_relative_pl() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
for dir in ["parent", "common", "app"] {
fs::create_dir_all(root.join(dir)).unwrap();
}
fs::write(
root.join("parent/pom.xml"),
"<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>",
)
.unwrap();
fs::write(
root.join("common/pom.xml"),
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
)
.unwrap();
fs::write(
root.join("app/pom.xml"),
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId><packaging>war</packaging><dependencies><dependency><groupId>test</groupId><artifactId>common</artifactId><version>1</version></dependency></dependencies></project>",
)
.unwrap();
let model = crate::load(root, &root.join("cache"), None);
let a = artifacts(root, &model);
assert_eq!(a.len(), 1);
assert_eq!(a[0].id, "maven:app/pom.xml");
let plan = build(root, &model, &a[0].id, &root.join("base")).unwrap();
assert_eq!(plan.cwd, "parent");
assert_eq!(&plan.args[..3], &["-pl", "../app", "-am"]);
let (probe, _) = plan.maven_project.as_ref().unwrap();
assert!(probe.contains(&root.join("app/pom.xml").to_string_lossy().into_owned()));
}
#[test]
fn maven_subfolder_aggregator_builds_root_war_with_parent_pl() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
for dir in ["parent", "common"] {
fs::create_dir_all(root.join(dir)).unwrap();
}
fs::write(
root.join("pom.xml"),
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>parent/pom.xml</relativePath></parent><artifactId>app</artifactId><packaging>war</packaging></project>",
)
.unwrap();
fs::write(
root.join("parent/pom.xml"),
"<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../</module><module>../common</module></modules></project>",
)
.unwrap();
fs::write(
root.join("common/pom.xml"),
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
)
.unwrap();
let settings =
ide_core::settings::MavenSettings { linked_projects: vec!["parent/pom.xml".into()], ..Default::default() };
let model = crate::load_linked(root, &root.join("cache"), None, &settings, &Default::default());
let plan = build(root, &model, "maven:pom.xml", &root.join("base")).unwrap();
assert_eq!(plan.cwd, "parent");
assert_eq!(&plan.args[..3], &["-pl", "..", "-am"]);
}
#[test]
fn maven_independent_sibling_wars_keep_own_reactor() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
for dir in ["a", "b"] {
fs::create_dir_all(root.join(dir)).unwrap();
fs::write(
root.join(dir).join("pom.xml"),
format!("<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>{dir}</artifactId><version>1</version><packaging>war</packaging></project>"),
)
.unwrap();
}
let model = crate::load(root, &root.join("cache"), None);
for dir in ["a", "b"] {
let plan = build(root, &model, &format!("maven:{dir}/pom.xml"), &root.join("base")).unwrap();
assert_eq!(plan.cwd, dir);
assert!(!plan.args.contains(&"-pl".into()));
}
}
}
+1 -1
Переглянути файл
@@ -16,7 +16,7 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["std",
png = "0.18"
[target.'cfg(target_os = "linux")'.dependencies]
gtk = "0.18"
gtk = "0.19"
[dev-dependencies]
png = "0.18"
+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_Storage_FileSystem", "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_Environment", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }
+5 -5
Переглянути файл
@@ -175,7 +175,7 @@ impl CliTool {
Poll::Finished => break,
}
}
Ok((lines.finish(cancel)?, stderr_tail))
Ok((lines.finish(cancel)?.success(), stderr_tail))
}
/// Starts `cmd` with a reader thread per pipe, for a caller that drives the loop itself
@@ -301,9 +301,9 @@ impl Lines {
}
}
/// Waits for the child to exit and returns whether it did so successfully. Fails, after
/// killing it, when `cancel` fires first.
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<bool> {
/// Waits for the child to exit and returns how it exited. Fails, after killing it, when
/// `cancel` fires first.
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<std::process::ExitStatus> {
let status = loop {
if let Some(status) = self.child.try_wait()? {
break status;
@@ -314,6 +314,6 @@ impl Lines {
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(status.success())
Ok(status)
}
}
+20
Переглянути файл
@@ -0,0 +1,20 @@
//! The CMake File API queries the IDE writes into a build directory, shared by the run
//! configurations (which read the replies) and Build Project (which configures).
use std::path::Path;
/// The objects asked for: targets, cache, toolchains and the CMake files.
pub const QUERIES: [&str; 4] = ["codemodel-v2", "cache-v2", "toolchains-v1", "cmakeFiles-v1"];
const QUERY: &str = ".cmake/api/v1/query/client-openidea";
/// Where CMake writes its replies, relative to the build directory.
pub const REPLY: &str = ".cmake/api/v1/reply";
/// Asks CMake to answer [`QUERIES`] on the next configure of `build`.
pub fn write_queries(build: &Path) -> std::io::Result<()> {
let query = build.join(QUERY);
std::fs::create_dir_all(&query)?;
for name in QUERIES {
std::fs::write(query.join(name), "")?;
}
Ok(())
}
+16
Переглянути файл
@@ -401,6 +401,8 @@ impl Default for CodeEditingSettings {
#[serde(default, rename_all = "camelCase")]
pub struct InlayHintsSettings {
pub types: bool,
/// Inferred variable and field types from the JavaScript and TypeScript servers (on, as in WebStorm).
pub js_ts_types: bool,
pub parameters: bool,
/// Hints of other kinds (chaining, closing labels…).
pub other: bool,
@@ -436,6 +438,7 @@ impl Default for InlayHintsSettings {
fn default() -> Self {
Self {
types: true,
js_ts_types: true,
parameters: true,
other: true,
closing_labels: true,
@@ -710,6 +713,19 @@ mod folding_tests {
}
}
#[cfg(test)]
mod inlay_hints_tests {
use super::InlayHintsSettings;
#[test]
fn existing_settings_enable_js_ts_type_hints_by_default() {
let settings: InlayHintsSettings = serde_json::from_str(r#"{"parameters":false}"#).unwrap();
assert!(settings.types);
assert!(settings.js_ts_types);
assert!(!settings.parameters);
}
}
#[cfg(test)]
mod sticky_lines_tests {
use super::CodeEditingSettings;
+31
Переглянути файл
@@ -11,6 +11,14 @@ use specta::Type;
use std::collections::BTreeMap;
use std::sync::Arc;
/// The execution target recorded with an MCP agent run.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum McpAgentRunTarget {
Host,
Container { id: String },
}
/// 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. `RunConfiguration` starts a run configuration (a serialized
@@ -42,6 +50,7 @@ pub enum McpUiRequest {
command: String,
cwd: crate::IpcPath,
env: BTreeMap<String, String>,
target: McpAgentRunTarget,
},
RunConfiguration {
#[specta(type = specta_typescript::Unknown)]
@@ -108,6 +117,14 @@ pub enum IdeEvent {
host: String,
#[serde(default)]
taken_over: bool,
/// Plain-language explanation when a dev container exited from the OOM killer (`OOMKilled` / exit 137).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
oom_message: Option<String>,
/// Local configuration file (`devcontainer.json` or Compose file) that sets the container's limit.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
oom_config_path: Option<String>,
},
ProjectTrustChanged {
root: crate::IpcPath,
@@ -311,6 +328,18 @@ pub enum IdeEvent {
AskpassDone {
id: u64,
},
/// An external `/api/file` request asks the target project window to confirm opening a file;
/// answered with `web_file_api_confirm`.
FileApiConfirm {
id: u64,
source: String,
path: crate::IpcPath,
line: Option<u32>,
},
/// File-open confirmation prompt `id` was answered or cancelled.
FileApiConfirmDone {
id: u64,
},
/// The kernel of an open notebook changed state (`starting`, `idle`, `busy`,
/// `dead`); `message` says why it failed to start or died.
NotebookKernel {
@@ -430,6 +459,8 @@ pub enum LspRefreshKind {
Inheritance,
/// The Dart server published a document's Flutter outline.
FlutterOutline,
/// Spring bean markers of open documents may have changed.
SpringBeanMarkers,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
+1
Переглянути файл
@@ -6,6 +6,7 @@
pub mod build_jobs;
pub mod cli_process;
pub mod cmake_file_api;
pub mod editor_settings;
pub mod error;
pub mod event;
+405 -8
Переглянути файл
@@ -285,6 +285,190 @@ fn taskkill_tree_of(pid: u32) {
windows_tree::wait_all(&started, TREE_EXIT_WAIT);
}
/// The registry environment behind [`registry_env_changes`], read with
/// `CreateEnvironmentBlock` as Explorer does for the programs it starts after a
/// `WM_SETTINGCHANGE`. It is read again only after `HKCU\Environment` or the machine's
/// `Environment` key reports a change, so spawning a child costs two event polls.
#[cfg(windows)]
mod registry_env {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::sync::Mutex;
use windows_sys::Win32::Foundation::{ERROR_SUCCESS, HANDLE, WAIT_OBJECT_0};
use windows_sys::Win32::Security::{TOKEN_DUPLICATE, TOKEN_IMPERSONATE, TOKEN_QUERY};
use windows_sys::Win32::System::Environment::{CreateEnvironmentBlock, DestroyEnvironmentBlock};
use windows_sys::Win32::System::Registry::{
HKEY, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_NOTIFY, REG_NOTIFY_CHANGE_LAST_SET, REG_NOTIFY_CHANGE_NAME,
REG_NOTIFY_THREAD_AGNOSTIC, RegCloseKey, RegNotifyChangeKeyValue, RegOpenKeyExW,
};
use windows_sys::Win32::System::Threading::{
CreateEventW, GetCurrentProcess, OpenProcessToken, ResetEvent, WaitForSingleObject,
};
type Vars = Vec<(OsString, OsString)>;
/// An open registry key and the event its next change signals.
struct Watch {
key: HKEY,
event: OwnedHandle,
}
// SAFETY: a registry key handle is a kernel handle, usable from any thread.
unsafe impl Send for Watch {}
impl Watch {
fn new(root: HKEY, path: &str) -> Option<Self> {
let path: Vec<u16> = path.encode_utf16().chain(Some(0)).collect();
let mut key: HKEY = std::ptr::null_mut();
// SAFETY: `path` is NUL-terminated; `key` receives a handle the watch owns.
if unsafe { RegOpenKeyExW(root, path.as_ptr(), 0, KEY_NOTIFY, &mut key) } != ERROR_SUCCESS {
return None;
}
// SAFETY: plain call; a non-null result is a manual-reset event handle owned here.
let event = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) };
if event.is_null() {
// SAFETY: `key` was opened above and is closed once.
unsafe { RegCloseKey(key) };
return None;
}
// SAFETY: as above.
let watch = Watch { key, event: unsafe { OwnedHandle::from_raw_handle(event) } };
watch.arm().then_some(watch)
}
/// Asks to be told of the key's next change; `false` when it cannot be watched.
fn arm(&self) -> bool {
let filter = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET | REG_NOTIFY_THREAD_AGNOSTIC;
// SAFETY: both handles are owned by the watch and open.
let status = unsafe { RegNotifyChangeKeyValue(self.key, 0, filter, self.event.as_raw_handle(), 1) };
status == ERROR_SUCCESS
}
/// Whether the key changed since the last call; re-arms the watch when it did.
fn changed(&self) -> bool {
let event: HANDLE = self.event.as_raw_handle();
// SAFETY: an event handle owned by the watch.
if unsafe { WaitForSingleObject(event, 0) } != WAIT_OBJECT_0 {
return false;
}
// SAFETY: as above.
unsafe { ResetEvent(event) };
self.arm();
true
}
}
impl Drop for Watch {
fn drop(&mut self) {
// SAFETY: the key was opened by `Watch::new` and is closed once.
unsafe { RegCloseKey(self.key) };
}
}
struct State {
startup: Vars,
current: Vars,
watches: Vec<Watch>,
}
static STATE: Mutex<Option<State>> = Mutex::new(None);
pub(super) fn record() {
let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
if state.is_none() {
*state = Some(start());
}
}
fn start() -> State {
// Watch before reading: a change in between is then read again, not missed.
let watches = [
(HKEY_CURRENT_USER, "Environment"),
(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"),
]
.into_iter()
.filter_map(|(root, path)| Watch::new(root, path))
.collect();
let startup = read().unwrap_or_default();
State { current: startup.clone(), startup, watches }
}
pub(super) fn changes() -> Vec<(OsString, Option<OsString>)> {
let mut guard = STATE.lock().unwrap_or_else(|e| e.into_inner());
let state = guard.get_or_insert_with(start);
// Poll every watch: each one that fired must be re-armed.
let changed = state.watches.iter().fold(false, |any, watch| watch.changed() | any);
if changed && let Some(fresh) = read() {
state.current = fresh;
}
if state.current == state.startup {
return Vec::new();
}
super::registry_diff(&|k| std::env::var_os(k), &state.startup, &state.current)
}
/// The environment a program Explorer starts now would get; `None` when it cannot be read.
pub(super) fn read() -> Option<Vars> {
let mut token: HANDLE = std::ptr::null_mut();
let access = TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE;
// SAFETY: this process's pseudo-handle; `token` receives a handle owned here.
if unsafe { OpenProcessToken(GetCurrentProcess(), access, &mut token) } == 0 {
return None;
}
// SAFETY: as above.
let token = unsafe { OwnedHandle::from_raw_handle(token) };
let mut block: *mut core::ffi::c_void = std::ptr::null_mut();
// SAFETY: an open token; `block` receives a block destroyed below.
if unsafe { CreateEnvironmentBlock(&mut block, token.as_raw_handle(), 0) } == 0 || block.is_null() {
return None;
}
// SAFETY: the block holds `NAME=VALUE` entries, each NUL-terminated, then a final NUL.
let vars = unsafe { parse_block(block as *const u16) };
// SAFETY: the block was created above and is destroyed once.
unsafe { DestroyEnvironmentBlock(block) };
Some(vars)
}
/// # Safety
/// `block` points to UTF-16 entries, each NUL-terminated, ended by an empty one.
unsafe fn parse_block(block: *const u16) -> Vars {
let mut vars = Vars::new();
let mut at = block;
loop {
let mut len = 0;
// SAFETY: the caller guarantees the terminating NULs.
while unsafe { *at.add(len) } != 0 {
len += 1;
}
if len == 0 {
return vars;
}
// SAFETY: the `len` units before the NUL were just read.
let entry = unsafe { std::slice::from_raw_parts(at, len) };
// Per-drive directories (`=C:=C:\dir`) have an empty name: skip them.
if let Some(eq) = entry.iter().skip(1).position(|&c| c == u16::from(b'=')) {
let eq = eq + 1;
vars.push((OsString::from_wide(&entry[..eq]), OsString::from_wide(&entry[eq + 1..])));
}
// SAFETY: the entry's NUL is followed by the next entry or the final NUL.
at = unsafe { at.add(len + 1) };
}
}
#[cfg(test)]
mod tests {
#[test]
fn reads_this_users_environment() {
let vars = super::read().expect("environment block");
let get = |k: &str| vars.iter().find(|(n, _)| n.eq_ignore_ascii_case(k)).map(|(_, v)| v.clone());
assert!(get("SystemRoot").is_some_and(|v| !v.is_empty()), "{vars:?}");
assert!(get("Path").is_some_and(|v| !v.is_empty()), "{vars:?}");
assert!(vars.iter().all(|(k, _)| !k.is_empty() && !k.to_string_lossy().contains('=')));
}
}
}
#[cfg(windows)]
mod windows_tree {
use std::collections::HashSet;
@@ -676,7 +860,7 @@ pub fn host_var_os_in(dir: &Path, key: impl AsRef<OsStr>) -> Option<OsString> {
}
fn host_var_os_for(dir: Option<&Path>, key: &OsStr) -> Option<OsString> {
match child_env_changes(dir).into_iter().find(|(k, _)| k == key) {
match child_env_changes(dir).into_iter().find(|(k, _)| same_key(k, key)) {
Some((_, fixed)) => fixed,
None => std::env::var_os(key).or_else(|| shell_env_for(dir).find(|(k, _)| k == key).map(|(_, v)| v)),
}
@@ -688,7 +872,7 @@ fn apply_changes(
changes: &[(OsString, Option<OsString>)],
) -> Vec<(OsString, OsString)> {
for (key, value) in changes {
let at = vars.iter().position(|(k, _)| k == key);
let at = vars.iter().position(|(k, _)| same_key(k, key));
match (at, value) {
(Some(i), Some(v)) => vars[i].1 = v.clone(),
(Some(i), None) => {
@@ -701,25 +885,126 @@ fn apply_changes(
vars
}
/// The AppImage fixes, the overlay, the manual proxy's, then those of the project holding
/// `dir` (a later one wins); one entry per name.
/// The registry's changes (Windows), the AppImage fixes, the overlay, the manual proxy's,
/// then those of the project holding `dir` (a later one wins); one entry per name.
fn child_env_changes(dir: Option<&Path>) -> Vec<(OsString, Option<OsString>)> {
let mut changes = appimage_fixes();
let mut changes = registry_env_changes();
changes.extend(appimage_fixes());
let overlay = env_overlay();
changes.retain(|(k, _)| !overlay.iter().any(|(o, _)| o == k));
changes.retain(|(k, _)| !overlay.iter().any(|(o, _)| same_key(o, k)));
changes.extend(overlay.iter().cloned());
// A manual HTTP proxy reaches tools that read `HTTP_PROXY` (language servers, git, curl).
let proxy = crate::proxy_settings::proxy().child_env();
changes.retain(|(k, _)| !proxy.iter().any(|(p, _)| p == k));
changes.retain(|(k, _)| !proxy.iter().any(|(p, _)| same_key(p, k)));
changes.extend(proxy);
if let Some(dir) = dir {
let project = crate::project_env::for_dir(dir);
changes.retain(|(k, _)| !project.iter().any(|(p, _)| p == k));
changes.retain(|(k, _)| !project.iter().any(|(p, _)| same_key(p, k)));
changes.extend(project.iter().cloned());
}
changes
}
/// Whether two variable names are the same variable: Windows ignores case (`Path` is `PATH`).
fn same_key(a: &OsStr, b: &OsStr) -> bool {
if cfg!(windows) { a.eq_ignore_ascii_case(b) } else { a == b }
}
/// What changed in the environment Windows gives new programs (the registry's machine and
/// user variables) since this process started. A program installed meanwhile (Node.js, a
/// JDK) adds its folder to `Path`; a child of the IDE must find it, as a program started
/// from Explorer would, without restarting the IDE. Empty elsewhere.
fn registry_env_changes() -> Vec<(OsString, Option<OsString>)> {
#[cfg(windows)]
{
registry_env::changes()
}
#[cfg(not(windows))]
{
Vec::new()
}
}
/// Remembers the registry environment this process starts with, so that later changes reach
/// new children. Call at startup (otherwise the first child spawn records it). Does nothing
/// outside Windows.
pub fn record_startup_registry_env() {
#[cfg(windows)]
registry_env::record();
}
/// The entry of a `PATH`-like list as compared: without a trailing separator, and on
/// Windows without case.
#[cfg_attr(not(windows), allow(dead_code))]
fn path_entry_key(dir: &Path) -> String {
let text = dir.to_string_lossy();
let text = text.trim_end_matches(['\\', '/']);
if cfg!(windows) { text.to_ascii_lowercase() } else { text.to_owned() }
}
/// `old` → `fresh` applied to this process's `PATH`-like list `process`: entries that
/// `fresh` dropped are removed and those it added are appended, so what the IDE put on
/// `PATH` itself (managed tools, the user's `Path`) stays where it is.
#[cfg_attr(not(windows), allow(dead_code))]
fn rebase_path_list(process: &OsStr, old: &OsStr, fresh: &OsStr) -> OsString {
let entries = |list: &OsStr| -> Vec<std::path::PathBuf> {
std::env::split_paths(list).filter(|d| !d.as_os_str().is_empty()).collect()
};
let old: Vec<String> = entries(old).iter().map(|d| path_entry_key(d)).collect();
let fresh = entries(fresh);
let fresh_keys: Vec<String> = fresh.iter().map(|d| path_entry_key(d)).collect();
let mut out: Vec<std::path::PathBuf> = entries(process)
.into_iter()
.filter(|d| {
let key = path_entry_key(d);
!old.contains(&key) || fresh_keys.contains(&key)
})
.collect();
for (dir, key) in fresh.into_iter().zip(fresh_keys) {
if !old.contains(&key) && !out.iter().any(|d| path_entry_key(d) == key) {
out.push(dir);
}
}
std::env::join_paths(out).unwrap_or_else(|_| process.to_owned())
}
/// The changes that bring this process's environment (`process`) from the registry
/// environment it started with (`old`) to the current one (`fresh`): new and changed
/// variables; removed ones while this process still has the value it started with; and
/// `PATH` rebased ([`rebase_path_list`]).
#[cfg_attr(not(windows), allow(dead_code))]
fn registry_diff(
process: &dyn Fn(&OsStr) -> Option<OsString>,
old: &[(OsString, OsString)],
fresh: &[(OsString, OsString)],
) -> Vec<(OsString, Option<OsString>)> {
let get =
|vars: &[(OsString, OsString)], k: &OsStr| vars.iter().find(|(n, _)| same_key(n, k)).map(|(_, v)| v.clone());
let mut out = Vec::new();
for (key, value) in fresh {
let before = get(old, key);
if before.as_ref() == Some(value) {
continue;
}
let current = process(key);
if key.eq_ignore_ascii_case("PATH") {
let current = current.unwrap_or_default();
let rebased = rebase_path_list(&current, before.as_deref().unwrap_or_default(), value);
if rebased != current {
out.push((key.clone(), Some(rebased)));
}
} else if current.as_ref() != Some(value) {
out.push((key.clone(), Some(value.clone())));
}
}
for (key, value) in old {
if get(fresh, key).is_none() && process(key).as_ref() == Some(value) {
out.push((key.clone(), None));
}
}
out
}
/// Read on every call, not cached: startup rewrites `PATH` (login shell, managed tools).
fn appimage_fixes() -> Vec<(OsString, Option<OsString>)> {
if !cfg!(target_os = "linux") || std::env::var_os("APPDIR").is_none() {
@@ -1459,6 +1744,118 @@ mod tests {
assert!(fixes(&[("APPDIR", "/"), ("PATH", "/usr/bin")]).is_empty());
}
fn os(vars: &[(&str, &str)]) -> Vec<(OsString, OsString)> {
vars.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect()
}
fn list(dirs: &[&str]) -> OsString {
std::env::join_paths(dirs).unwrap()
}
#[test]
fn registry_path_changes_keep_what_the_ide_added_to_path() {
// The IDE put `tools` first at startup; meanwhile an installer appended `node`
// and an uninstaller removed `old`.
let process = list(&["tools", "sys", "old", "user"]);
let rebased = rebase_path_list(&process, &list(&["sys", "old", "user"]), &list(&["sys", "user", "node"]));
assert_eq!(rebased, list(&["tools", "sys", "user", "node"]));
// Nothing to add when the entry is already there (a trailing separator aside).
let sep = std::path::MAIN_SEPARATOR.to_string();
let rebased =
rebase_path_list(&list(&["sys", "node"]), &list(&["sys"]), &list(&["sys", &format!("node{sep}")]));
assert_eq!(rebased, list(&["sys", "node"]));
}
#[test]
fn registry_changes_are_new_changed_and_removed_variables() {
let old = os(&[("KEEP", "1"), ("CHANGED", "a"), ("GONE", "x"), ("OVERRIDDEN", "y"), ("PATH", "sys")]);
let fresh = os(&[("KEEP", "1"), ("CHANGED", "b"), ("NEW", "n"), ("PATH", "sys")]);
// The IDE was launched with `OVERRIDDEN` set otherwise: that value stays.
let process = |k: &OsStr| match k.to_str()?.to_ascii_uppercase().as_str() {
"KEEP" => Some("1".into()),
"CHANGED" => Some("a".into()),
"GONE" => Some("x".into()),
"OVERRIDDEN" => Some("launcher".into()),
"PATH" => Some(list(&["tools", "sys"])),
_ => None,
};
let got = registry_diff(&process, &old, &fresh);
let want: Vec<(OsString, Option<OsString>)> =
vec![("CHANGED".into(), Some("b".into())), ("NEW".into(), Some("n".into())), ("GONE".into(), None)];
assert_eq!(got, want);
assert!(registry_diff(&process, &old, &old).is_empty());
// A `Path` change reaches the process `PATH` (another case of the same variable).
let got = registry_diff(&process, &os(&[("Path", "sys")]), &os(&[("Path", "sys;node")]));
if cfg!(windows) {
assert_eq!(got, vec![("Path".into(), Some(list(&["tools", "sys", "node"])))]);
}
}
#[test]
fn changes_match_variable_names_as_the_platform_does() {
let vars = os(&[("Path", "a")]);
let got = apply_changes(vars, &[("PATH".into(), Some("b".into()))]);
if cfg!(windows) {
assert_eq!(got, os(&[("Path", "b")]));
} else {
assert_eq!(got, os(&[("Path", "a"), ("PATH", "b")]));
}
}
/// A variable set in `HKCU\Environment` after startup (as an installer or the System
/// Properties dialog does) reaches the next child without a restart.
#[cfg(windows)]
#[test]
fn a_user_variable_set_after_startup_reaches_new_children() {
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::System::Registry::{HKEY_CURRENT_USER, REG_SZ, RegDeleteKeyValueW, RegSetKeyValueW};
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(Some(0)).collect()
}
struct Cleanup(Vec<u16>);
impl Drop for Cleanup {
fn drop(&mut self) {
// SAFETY: NUL-terminated names of a value this test created.
unsafe { RegDeleteKeyValueW(HKEY_CURRENT_USER, wide("Environment").as_ptr(), self.0.as_ptr()) };
}
}
record_startup_registry_env();
let name = format!("OPENIDEA_REGISTRY_ENV_TEST_{}", std::process::id());
let value = wide("installed");
let wide_name = wide(&name);
// SAFETY: NUL-terminated names; the data is `value`'s bytes, NUL included.
let status = unsafe {
RegSetKeyValueW(
HKEY_CURRENT_USER,
wide("Environment").as_ptr(),
wide_name.as_ptr(),
REG_SZ,
value.as_ptr().cast(),
(value.len() * 2) as u32,
)
};
assert_eq!(status, ERROR_SUCCESS);
let cleanup = Cleanup(wide_name);
let deadline = std::time::Instant::now() + Duration::from_secs(5);
let seen = loop {
let seen = host_var_os(&name);
if seen.is_some() || std::time::Instant::now() >= deadline {
break seen;
}
std::thread::sleep(Duration::from_millis(20));
};
assert_eq!(seen.as_deref(), Some(OsStr::new("installed")));
assert!(spawnable_host_vars().any(|(k, v)| k == name.as_str() && v == "installed"));
drop(cleanup);
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while host_var_os(&name).is_some() && std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
}
assert_eq!(host_var_os(&name), None, "a removed variable is gone again");
}
#[test]
fn host_env_keeps_what_the_call_site_set() {
let mut cmd = Command::new("true");
+1
Переглянути файл
@@ -227,6 +227,7 @@ pub struct RunTarget {
pub python: String,
pub node: String,
pub java: String,
pub php: String,
/// Id of a Docker connection of the Services tool window (Docker, Compose);
/// empty = the CLI's own daemon.
pub docker_connection: String,
+165 -4
Переглянути файл
@@ -68,6 +68,8 @@ pub struct Settings {
/// Build, Execution, Deployment › Run Targets.
pub run_targets: Vec<RunTarget>,
pub cmake: CMakeSettings,
/// Build, Execution, Deployment › Toolchains; the first is the default.
pub toolchains: Vec<Toolchain>,
/// Settings › Agents.
pub agents: AgentSettings,
/// Agents › MCP Server (global only).
@@ -160,6 +162,9 @@ pub struct AgentSettings {
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, AgentMcpServer>)]
pub mcp_servers: BTreeMap<String, AgentMcpServer>,
/// Custom MCP Registry base URL (`agents.mcpRegistryUrl`); empty = GitHub MCP Registry.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub mcp_registry_url: String,
/// How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
/// files on disk are never modified.
#[serde(deserialize_with = "or_default")]
@@ -209,6 +214,7 @@ impl Default for AgentSettings {
confirm_terminate_on_close: true,
defaults: BTreeMap::new(),
mcp_servers: BTreeMap::new(),
mcp_registry_url: String::new(),
skills: BTreeMap::new(),
memory: AgentMemorySettings::default(),
plugins: AgentPluginSettings::default(),
@@ -251,6 +257,14 @@ pub struct AgentMcpServer {
/// empty means enabled for all agents.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub agents: Vec<String>,
/// Canonical MCP registry server identifier (e.g. `microsoft/playwright-mcp`) when installed from a registry.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub registry_name: Option<String>,
/// Normalized MCP registry base URL (e.g. `https://api.mcp.github.com`) when installed from a registry.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub registry_url: Option<String>,
}
impl Default for AgentMcpServer {
@@ -264,6 +278,8 @@ impl Default for AgentMcpServer {
url: None,
headers: BTreeMap::new(),
agents: Vec::new(),
registry_name: None,
registry_url: None,
}
}
}
@@ -703,6 +719,8 @@ pub struct ToolDownloadSettings {
/// Maven Central, dependency version completion from Maven Central, npm, PyPI and
/// crates.io). Off by default.
pub configured_registries_only: bool,
/// The managed Vue Language Server release. Empty selects it from the project's Vue dependency.
pub vue_language_server_version: String,
}
/// Settings › Settings Sync: the Git repository the IDE settings sync through, and what syncs.
@@ -750,9 +768,42 @@ impl Default for SettingsSyncSettings {
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CMakeSettings {
#[serde(skip_serializing_if = "Option::is_none")]
/// Serialized as `null` when absent, so `cmake.profiles` stays a known settings key.
#[specta(optional)]
pub profiles: Option<Vec<CMakeProfile>>,
/// `true` ignores `CMakePresets.json` / `CMakeUserPresets.json`; otherwise every visible
/// configure preset whose condition holds is listed after the explicit profiles.
pub ignore_presets: bool,
/// Configure presets (by name) enabled as profiles. As in CLion, a preset is listed but
/// disabled until enabled here.
pub enabled_presets: Vec<String>,
/// The profile (by name) that build, run and debug use, as CLion's toolbar switcher;
/// empty or unknown = the first enabled one.
pub active_profile: String,
}
/// The presets a profile made from `CMakePresets.json` runs with.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CMakePresetRef {
pub configure: String,
/// The first build preset of `configure`, used by `cmake --build --preset`.
#[serde(skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub build: Option<String>,
/// The first test preset of `configure`, used by `ctest --preset`.
#[serde(skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub test: Option<String>,
/// Cache variables the resolved preset sets itself, read when presets are loaded (never
/// saved): a toolchain does not override them.
#[serde(skip)]
#[specta(skip)]
pub cache_variables: Vec<String>,
/// The preset names a toolchain file, which picks the compilers.
#[serde(skip)]
#[specta(skip)]
pub toolchain_file: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -766,6 +817,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 {
@@ -778,10 +846,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 {
@@ -893,6 +995,7 @@ impl Default for Settings {
deployment: DeploymentSettings::default(),
run_targets: Vec::new(),
cmake: CMakeSettings::default(),
toolchains: Vec::new(),
agents: AgentSettings::default(),
mcp_server: McpServerSettings::default(),
agent_security: AgentSecuritySettings::default(),
@@ -997,6 +1100,8 @@ pub struct GeneralSettings {
pub project_name: String,
/// Where updates come from: `auto` (the CNB mirror for the Chinese UI, else GitHub) | `github` | `cnb`.
pub update_source: String,
/// `stable` | `nightly`; defaults to the running build's channel.
pub update_channel: String,
pub auto_check_updates: bool,
/// System Settings › Updates: open the What's New page after the app starts a new version.
pub show_whats_new_after_update: bool,
@@ -1019,6 +1124,7 @@ impl Default for GeneralSettings {
power_save_mode: false,
project_name: String::new(),
update_source: "auto".into(),
update_channel: crate::updates::UpdateChannel::of_version(env!("CARGO_PKG_VERSION")).as_str().into(),
auto_check_updates: true,
show_whats_new_after_update: true,
last_run_version: String::new(),
@@ -1258,6 +1364,7 @@ pub struct FileIconThemeOptions {
pub hollow_folders: bool,
pub hide_ui_icons: bool,
pub hide_psi_icons: bool,
pub file_icons_for_code: bool,
pub monochrome: Option<String>,
pub saturation: Option<u8>,
pub opacity: Option<u8>,
@@ -1341,6 +1448,10 @@ pub struct CustomColorScheme {
pub struct EditorSettings {
pub font_family: String,
pub font_size: f32,
/// Largest document (in MiB) eligible for syntax analysis and language-server features.
#[serde(deserialize_with = "code_insight_limit_mb")]
#[specta(type = u8)]
pub max_code_insight_file_size_mb: u8,
pub line_height: f32,
pub tab_size: u32,
pub insert_spaces: bool,
@@ -1358,6 +1469,9 @@ pub struct EditorSettings {
/// Color Scheme › Language Defaults › Semantic highlighting: local variables and
/// parameters get a colour derived from their name (IDEA's rainbow identifiers).
pub semantic_highlighting: bool,
/// Color Scheme › Language Defaults › Dim inactive preprocessor code: grey out the
/// `#if`/`#ifdef` branches clangd reports as inactive (C and C++).
pub dim_inactive_code: bool,
/// Docstring markup format whose tags and keywords the Python editor highlights
/// (`plain`, `rest`, `epytext`, `google`, `numpy`).
pub docstring_format: String,
@@ -1394,11 +1508,23 @@ pub struct EditorSettings {
pub encodings: EncodingSettings,
}
pub const DEFAULT_CODE_INSIGHT_LIMIT_MB: u8 = 5;
pub const MAX_CODE_INSIGHT_LIMIT_MB: u8 = 50;
fn code_insight_limit_mb<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u8, D::Error> {
Ok(serde_json::Value::deserialize(d)?
.as_u64()
.and_then(|n| u8::try_from(n).ok())
.filter(|n| (1..=MAX_CODE_INSIGHT_LIMIT_MB).contains(n))
.unwrap_or(DEFAULT_CODE_INSIGHT_LIMIT_MB))
}
impl Default for EditorSettings {
fn default() -> Self {
Self {
font_family: "JetBrains Mono".into(),
font_size: 13.0,
max_code_insight_file_size_mb: DEFAULT_CODE_INSIGHT_LIMIT_MB,
line_height: 22.0,
tab_size: 4,
insert_spaces: true,
@@ -1411,6 +1537,7 @@ impl Default for EditorSettings {
color_overrides: BTreeMap::new(),
custom_schemes: BTreeMap::new(),
semantic_highlighting: false,
dim_inactive_code: true,
docstring_format: "rest".into(),
rainbow_brackets: false,
rainbow_bracket_kinds: RainbowBracketKinds::default(),
@@ -1610,6 +1737,8 @@ 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>,
/// How single newlines inside a paragraph are rendered in the Markdown preview.
pub soft_line_breaks: MarkdownSoftLineBreaks,
/// Whether `.mdx` previews ask before running JSX components/imports, run automatically in
/// trusted projects, or stay in static safe mode.
pub mdx_execution: MdxExecutionPolicy,
@@ -1625,6 +1754,7 @@ impl Default for MarkdownSettings {
Self {
preview_layout: MarkdownPreviewLayout::default(),
preview_font_size: None,
soft_line_breaks: MarkdownSoftLineBreaks::default(),
mdx_execution: MdxExecutionPolicy::default(),
run_commands: true,
command_directory: None,
@@ -1632,6 +1762,16 @@ impl Default for MarkdownSettings {
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MarkdownSoftLineBreaks {
/// Standard Markdown: a single newline collapses into a space.
#[default]
Standard,
/// Render each single newline inside a paragraph as a line break (`<br>`).
Break,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MdxExecutionPolicy {
@@ -2049,6 +2189,8 @@ pub struct MavenSettings {
pub active_profiles: String,
/// Delegate IDE build/run actions to Maven: launches build with Maven (`javac`) instead of jdtls (ECJ).
pub delegate_build: bool,
/// Maven goals (`groupId:artifactId:goal`) the IDE may skip in compile phases. Empty by default.
pub ignored_compile_goals: Vec<String>,
/// Download `-sources.jar` of dependencies when the Java language server imports the
/// project (jdtls `java.maven.downloadSources`). Off: sources are fetched on demand
/// from a library class's Download Sources banner.
@@ -2455,12 +2597,16 @@ mod tests {
let old: Settings = serde_json::from_str(r#"{"languages":{"markdown":{"previewFontSize":16}}}"#).unwrap();
assert_eq!(old.languages.markdown.preview_layout, MarkdownPreviewLayout::SideBySide);
assert_eq!(old.languages.markdown.preview_font_size, Some(16));
assert_eq!(old.languages.markdown.soft_line_breaks, MarkdownSoftLineBreaks::Standard);
let stacked: Settings =
serde_json::from_str(r#"{"languages":{"markdown":{"previewLayout":"stacked"}}}"#).unwrap();
serde_json::from_str(r#"{"languages":{"markdown":{"previewLayout":"stacked","softLineBreaks":"break"}}}"#)
.unwrap();
assert_eq!(stacked.languages.markdown.preview_layout, MarkdownPreviewLayout::Stacked);
assert_eq!(stacked.languages.markdown.soft_line_breaks, MarkdownSoftLineBreaks::Break);
let saved = serde_json::to_value(&stacked).unwrap();
assert_eq!(saved["languages"]["markdown"]["previewLayout"], "stacked");
assert_eq!(saved["languages"]["markdown"]["softLineBreaks"], "break");
assert_eq!(serde_json::from_value::<Settings>(saved).unwrap().languages.markdown, stacked.languages.markdown);
}
@@ -2487,12 +2633,12 @@ mod tests {
let old: Settings = serde_json::from_str(r#"{"appearance":{"fileIconTheme":"p/t"}}"#).unwrap();
assert!(old.appearance.file_icon_theme_options.is_empty());
let json = serde_json::json!({"appearance":{"fileIconThemeOptions":{"p/t":{
"groups":{"tests":true},"choices":{"arrows":"plusminus"},"hideFiles":true,"hideFolders":false,"hollowFolders":true,"hideUiIcons":true,"hidePsiIcons":false,
"groups":{"tests":true},"choices":{"arrows":"plusminus"},"hideFiles":true,"hideFolders":false,"hollowFolders":true,"hideUiIcons":true,"hidePsiIcons":false,"fileIconsForCode":true,
"monochrome":"#546e7a","saturation":5,"opacity":80,"iconSize":20,"rowHeight":30,"accent":"#009688"}}}});
let settings: Settings = serde_json::from_value(json.clone()).unwrap();
let options = &settings.appearance.file_icon_theme_options["p/t"];
assert!(options.hide_files && options.hollow_folders && !options.hide_folders);
assert!(options.hide_ui_icons && !options.hide_psi_icons);
assert!(options.hide_ui_icons && !options.hide_psi_icons && options.file_icons_for_code);
assert!(options.groups["tests"]);
assert_eq!(options.choices["arrows"], "plusminus");
assert_eq!(
@@ -2508,6 +2654,7 @@ mod tests {
assert_eq!(plain["hideFiles"], false);
assert_eq!(plain["hideUiIcons"], false);
assert_eq!(plain["hidePsiIcons"], false);
assert_eq!(plain["fileIconsForCode"], false);
assert_eq!(plain["monochrome"], serde_json::Value::Null);
assert_eq!(plain["groups"], serde_json::json!({}));
}
@@ -2576,6 +2723,20 @@ mod tests {
}
}
#[test]
fn dim_inactive_code_defaults_on_and_round_trips() {
let mut settings = Settings::default();
assert!(settings.editor.dim_inactive_code);
settings.editor.dim_inactive_code = false;
let json = serde_json::to_value(&settings).unwrap();
assert_eq!(json["editor"]["dimInactiveCode"], false);
let restored: Settings = serde_json::from_value(json).unwrap();
assert!(!restored.editor.dim_inactive_code);
// Settings written before the option existed keep clangd's inactive-code grey.
let old: Settings = serde_json::from_str(r#"{"editor":{"semanticHighlighting":true}}"#).unwrap();
assert!(old.editor.dim_inactive_code);
}
#[test]
fn tool_window_badges_default_on_and_round_trip() {
let old: Settings = serde_json::from_str(r#"{"appearance":{"showToolWindowNames":true}}"#).unwrap();
+25 -1
Переглянути файл
@@ -8,6 +8,21 @@ use std::collections::HashSet;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
/// Why netcoredbg can't be installed here, for the two platforms Samsung publishes no build
/// for; the tool installer and the debugger's "not found" error both say it.
pub fn netcoredbg_no_prebuilt(intel_mac: bool, windows_arm64: bool) -> Option<String> {
let platform = match (intel_mac, windows_arm64) {
(true, _) => "Intel Macs",
(_, true) => "Windows on ARM64",
_ => return None,
};
Some(format!(
"Samsung publishes no prebuilt netcoredbg for {platform}. Build it from source \
(https://github.com/Samsung/netcoredbg#building-from-source-code), then put `netcoredbg` on PATH \
or set its executable path in Settings › Languages & Frameworks › Language Servers"
))
}
/// Where executables are looked up: this process's `PATH` (the login shell's in the
/// app), the login shell's `PATH` as last read, then per-user directories and mise's,
/// asdf's and pyenv's shims, for when the shell's setup didn't reach the app. Language server
@@ -133,6 +148,7 @@ fn search_dirs(
dirs.extend(USER_DIRS.iter().map(|d| home.join(d)));
dirs.extend(nvm_bins(&home.join(".nvm/versions/node")));
}
dirs.extend(RUSTUP_PROXY_DIRS.iter().map(PathBuf::from));
// Version managers' shims after real tool directories: a shim exists for a command any
// installed version has, and fails when the selected one lacks it. Before the system's,
// as the managers' shell setup puts them.
@@ -165,6 +181,11 @@ const USER_DIRS: &[&str] = &[
"Library/pnpm",
];
/// Homebrew's `rustup` keeps its toolchain proxies (`cargo`, `rust-analyzer`, …) in its own
/// prefix, off `PATH` unless the shell adds it: these play the part of `~/.cargo/bin`.
pub const RUSTUP_PROXY_DIRS: &[&str] =
&["/opt/homebrew/opt/rustup/bin", "/usr/local/opt/rustup/bin", "/home/linuxbrew/.linuxbrew/opt/rustup/bin"];
const SYSTEM_DIRS: &[&str] = &["/opt/homebrew/bin", "/usr/local/go/bin", "/usr/local/bin", "/usr/bin", "/bin"];
/// Whether `dir` is one of the system's own bin directories, which [`search_path`] adds
@@ -250,13 +271,16 @@ mod tests {
assert!(at("/home/me/.npm-global/bin") < at("/home/me/.pyenv/shims"));
// Global .NET tools (fsautocomplete, csharp-ls) install here, off PATH.
assert!(at("/home/me/.dotnet/tools") < at("/usr/local/bin"));
// Homebrew rustup's proxies, after rustup-init's.
assert!(at("/home/me/.cargo/bin") < at("/opt/homebrew/opt/rustup/bin"));
assert!(at("/opt/homebrew/opt/rustup/bin") < at("/opt/homebrew/bin"));
assert!(at("/home/me/.local/share/mise/shims") < at("/usr/local/bin"));
assert!(dirs.iter().all(|d| d.is_absolute()));
let unique: HashSet<&PathBuf> = dirs.iter().collect();
assert_eq!(unique.len(), dirs.len());
// A `:` can't be in a `PATH` entry: those below such a home are left out.
let dirs = search_dirs(Some(OsStr::new("/usr/bin")), None, None, Some(Path::new("/home/a:b")), &[]);
assert!(dirs.contains(&PathBuf::from("/usr/bin")) && !dirs.iter().any(|d| d.starts_with("/home")));
assert!(dirs.contains(&PathBuf::from("/usr/bin")) && !dirs.iter().any(|d| d.starts_with("/home/a:b")));
}
#[test]
+46
Переглянути файл
@@ -30,6 +30,38 @@ impl UpdateSource {
}
}
/// System Settings › Updates › Update channel: which release line updates come from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UpdateChannel {
/// `releases/latest`, never a prerelease, mirrored on CNB.
Stable,
/// The rolling `nightly` release (nightly.yml), on GitHub only.
Nightly,
}
impl UpdateChannel {
/// The channel a build of `version` updates from unless the setting says otherwise.
pub fn of_version(version: &str) -> Self {
if version.contains("-nightly.") { Self::Nightly } else { Self::Stable }
}
/// The `general.updateChannel` setting; anything else follows this build.
pub fn resolve(preference: &str) -> Self {
match preference {
"stable" => Self::Stable,
"nightly" => Self::Nightly,
_ => Self::of_version(env!("CARGO_PKG_VERSION")),
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::Stable => "stable",
Self::Nightly => "nightly",
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct UpdateInfo {
@@ -109,6 +141,20 @@ mod tests {
}
}
#[test]
fn channel_follows_the_build_unless_chosen() {
assert_eq!(UpdateChannel::of_version("0.1.57"), UpdateChannel::Stable);
assert_eq!(UpdateChannel::of_version("0.1.58-nightly.20261203"), UpdateChannel::Nightly);
assert_eq!(UpdateChannel::of_version("0.1.58-nightly.20261203.2"), UpdateChannel::Nightly);
assert_eq!(UpdateChannel::of_version("0.2.0-beta.1"), UpdateChannel::Stable);
assert_eq!(UpdateChannel::resolve("stable"), UpdateChannel::Stable);
assert_eq!(UpdateChannel::resolve("nightly"), UpdateChannel::Nightly);
let build = UpdateChannel::of_version(env!("CARGO_PKG_VERSION"));
for other in ["", "auto", "Nightly", "eap"] {
assert_eq!(UpdateChannel::resolve(other), build);
}
}
#[test]
fn checks_at_startup_and_every_four_hours_even_after_failure() {
let mut policy = UpdatePolicy::default();
+23 -3
Переглянути файл
@@ -31,6 +31,17 @@ pub struct VcsSettings {
pub svn: SvnSettings,
}
/// Settings › Version Control › Subversion (`vcs.svn`).
/// Branch and tag URL layout configured for one Subversion repository.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct SvnBranchConfig {
/// Trunk URL (e.g. `https://svn.example.com/repos/project/trunk`).
pub trunk_url: String,
/// Folders holding branches/tags (e.g. `["https://svn.example.com/repos/project/branches"]`).
pub branch_locations: Vec<String>,
}
/// Settings › Version Control › Subversion (`vcs.svn`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -43,6 +54,8 @@ pub struct SvnSettings {
/// Pass `--config-dir config_dir` to every svn command.
pub use_custom_config_dir: bool,
pub config_dir: String,
/// Configured trunk/branch locations keyed by normalized repository root URL or WC root.
pub branch_configurations: std::collections::BTreeMap<String, SvnBranchConfig>,
}
impl Default for SvnSettings {
@@ -54,6 +67,7 @@ impl Default for SvnSettings {
interactive: !cfg!(windows),
use_custom_config_dir: false,
config_dir: String::new(),
branch_configurations: std::collections::BTreeMap::new(),
}
}
}
@@ -477,12 +491,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 }
}
}
@@ -559,6 +576,8 @@ pub struct DebuggerSettings {
pub flutter_hot_reload_on_save: bool,
/// Java: whether to reload changed classes into running debug sessions after compilation.
pub hot_swap_after_compile: HotSwapPolicy,
/// Built-in Server: starting loopback port for `/api/file/<path>:<line>` requests.
pub built_in_server_port: u16,
pub python: PythonDebuggerSettings,
pub cpp: CppDebuggerSettings,
}
@@ -582,6 +601,7 @@ impl Default for DebuggerSettings {
debug_server_page: false,
flutter_hot_reload_on_save: true,
hot_swap_after_compile: HotSwapPolicy::Ask,
built_in_server_port: 63342,
python: PythonDebuggerSettings::default(),
cpp: CppDebuggerSettings::default(),
}
@@ -664,7 +684,6 @@ pub struct TerminalSettings {
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,
@@ -704,7 +723,6 @@ impl Default for TerminalSettings {
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,
@@ -726,6 +744,8 @@ impl Default for TerminalSettings {
#[serde(default, rename_all = "camelCase")]
pub struct ActionsOnSaveSettings {
pub optimize_imports: bool,
/// Rearrange code: class members in arrangement order, for the languages that have it.
pub rearrange: bool,
/// Run code cleanup (`source.fixAll`).
pub cleanup: bool,
}
+21 -1
Переглянути файл
@@ -613,11 +613,20 @@ pub fn not_standalone(spec: &AdapterSpec) -> IdeError {
}
pub fn missing(spec: &AdapterSpec) -> IdeError {
let no_prebuilt = ide_core::tool_path::netcoredbg_no_prebuilt(
cfg!(all(target_os = "macos", target_arch = "x86_64")),
cfg!(all(windows, target_arch = "aarch64")),
)
.filter(|_| spec.adapter == "netcoredbg");
missing_with(spec, no_prebuilt.as_deref().or(spec.install_hint.as_deref()))
}
fn missing_with(spec: &AdapterSpec, hint: Option<&str>) -> IdeError {
let mut msg = format!(
"debug adapter `{}` not found (`{}` is neither installed by OpenIDEA nor on PATH)",
spec.adapter, spec.command
);
if let Some(hint) = &spec.install_hint {
if let Some(hint) = hint {
msg.push_str(". ");
msg.push_str(hint);
}
@@ -1205,6 +1214,17 @@ mod tests {
assert!(err.message.contains("Settings › Languages & Frameworks › Language Servers"));
}
#[test]
fn missing_netcoredbg_without_a_build_says_how_to_get_one() {
let spec = resolve(&builtin("netcoredbg").unwrap(), std::env::temp_dir());
let hint = ide_core::tool_path::netcoredbg_no_prebuilt(true, false).unwrap();
let message = missing_with(&spec, Some(&hint)).message;
assert!(message.starts_with("debug adapter `netcoredbg` not found"), "{message}");
assert!(message.contains("no prebuilt netcoredbg for Intel Macs"), "{message}");
assert!(message.contains("on PATH"), "{message}");
assert_eq!(ide_core::tool_path::netcoredbg_no_prebuilt(false, false), None);
}
#[tokio::test]
async fn process_launcher_reports_missing_binary() {
let mut spec = resolve(&builtin("netcoredbg").unwrap(), std::env::temp_dir());
+9
Переглянути файл
@@ -1055,6 +1055,15 @@ impl DebugManager {
if let Some(command) = custom_command(&spec.command) {
spec.command = command;
}
// The debugger of the run configuration's toolchain (a MinGW gdb), over every other choice.
if let Some(command) = arguments
.as_object_mut()
.and_then(|o| o.remove(native::ADAPTER_COMMAND))
.and_then(|v| v.as_str().map(str::to_owned))
{
spec.command = command;
spec.pinned = None;
}
// debugpy: run the adapter with the debuggee's interpreter (venvs carry their own debugpy),
// or with the launcher's when the debuggee runs through a manager (`uv run python`).
if config.adapter == "debugpy" {
+26
Переглянути файл
@@ -8,6 +8,10 @@ use ide_core::{IdeError, IdeResult};
use serde_json::{Map, Value, json};
use std::path::{Path, PathBuf};
/// Launch argument naming the debugger to run (a toolchain's gdb or lldb-dap), which replaces
/// the search: lldb-dap if its name says so, else GDB.
pub const ADAPTER_COMMAND: &str = "__adapterCommand";
/// Prefix of the error when none of them is there; the UI offers to install CodeLLDB on it.
pub const NO_NATIVE_DEBUGGER: &str = "No C/C++ debugger found";
@@ -20,7 +24,16 @@ pub async fn choose(
if config.adapter != "lldb-dap" || config.request != "launch" {
return Ok(config);
}
let chosen = config
.extra_json
.as_deref()
.and_then(|e| serde_json::from_str::<Value>(e).ok())
.and_then(|e| e[ADAPTER_COMMAND].as_str().map(PathBuf::from));
let found = tokio::task::spawn_blocking(move || {
if let Some(chosen) = chosen {
let name = chosen.file_stem().map(|s| s.to_string_lossy().to_lowercase()).unwrap_or_default();
return if name.contains("lldb-dap") { Found::LldbDap } else { Found::Gdb(chosen) };
}
if lookup("lldb-dap").is_some() {
return Found::LldbDap;
}
@@ -154,6 +167,19 @@ mod tests {
assert_eq!(extra(&config)["swiftpm"]["product"], "app");
}
#[tokio::test]
async fn a_toolchain_debugger_replaces_the_search() {
let mut launch = cmake_launch();
launch.extra_json = Some(json!({"env": ["A=1"], ADAPTER_COMMAND: "/opt/mingw/bin/gdb.exe"}).to_string());
// lldb-dap is there, but the toolchain names its GDB (an unknown version is left to GDB).
let config = choose(launch, only(&["lldb-dap"])).await.unwrap();
assert_eq!(config.adapter, "gdb");
assert_eq!(extra(&config)[ADAPTER_COMMAND], "/opt/mingw/bin/gdb.exe", "kept for the adapter launch");
let mut launch = cmake_launch();
launch.extra_json = Some(json!({ADAPTER_COMMAND: "/opt/llvm/bin/lldb-dap"}).to_string());
assert_eq!(choose(launch, only(&[])).await.unwrap().adapter, "lldb-dap");
}
#[tokio::test]
async fn without_any_debugger_says_what_to_install() {
let e = choose(cmake_launch(), only(&[])).await.unwrap_err();
+80 -10
Переглянути файл
@@ -805,7 +805,7 @@ macro_rules! backend_id {
mod cursor;
mod pg_read_only;
pub(crate) use cursor::{Cursors, Key as CursorKey};
pub(crate) use pg_read_only::validate as validate_pg_read_only;
pub(crate) use pg_read_only::{leading_word, validate as validate_pg_read_only};
/// Whether the pages of `sql`'s result can be read by a cursor (see [`cursor`]): a query that
/// leaves the session as it was.
@@ -1058,7 +1058,8 @@ impl Pool {
opts = opts.statement_cache_capacity(n);
}
let pool = SqlitePoolOptions::new()
.max_connections(MAX)
// sqlx opens connections for a pool only, so console sessions count here.
.max_connections(MAX + crate::console_session::MAX_SESSIONS)
.acquire_timeout(timeout)
.after_connect(after_connect!())
.connect_with(opts)
@@ -1428,6 +1429,7 @@ impl Pool {
conn.discard().await;
return Err(IdeError::cancelled());
}
conn.release_after(sql, self.driver()).await;
r
}
@@ -1513,13 +1515,38 @@ impl Pool {
}
}
/// A connection taken out of a pool: for one statement, or held by a
/// manual-commit console across statements with its transaction open.
/// A connection of a pool, or one opened beside it that closes when dropped.
pub enum Lease<M: ManageConnection> {
Pooled(bb8::PooledConnection<'static, M>),
Own(M::Connection),
}
impl<M: ManageConnection> std::ops::Deref for Lease<M> {
type Target = M::Connection;
fn deref(&self) -> &Self::Target {
match self {
Lease::Pooled(c) => c,
Lease::Own(c) => c,
}
}
}
impl<M: ManageConnection> std::ops::DerefMut for Lease<M> {
fn deref_mut(&mut self) -> &mut Self::Target {
match self {
Lease::Pooled(c) => c,
Lease::Own(c) => c,
}
}
}
/// A connection taken out of a pool: for one statement, or held by a console
/// across statements (its manual transaction or its session).
pub enum Held {
Sqlite(PoolConnection<Sqlite>),
Postgres(Box<bb8::PooledConnection<'static, PgManager>>),
Mysql(Box<bb8::PooledConnection<'static, MysqlManager>>),
SqlServer(Box<bb8::PooledConnection<'static, MssqlConnectionManager>>),
Postgres(Box<Lease<PgManager>>),
Mysql(Box<Lease<MysqlManager>>),
SqlServer(Box<Lease<MssqlConnectionManager>>),
Clickhouse(crate::clickhouse::ClickhousePool),
Oracle(Box<crate::oracle::OracleConnection>),
/// The shared session, and the schema this holder's statements run in.
@@ -1531,9 +1558,11 @@ impl Held {
Ok(match pool {
Pool::Jdbc(_) => return Err(IdeError::invalid("Custom JDBC manual transactions are unsupported")),
Pool::Sqlite(p) => Held::Sqlite(p.acquire().await.map_err(db_err)?),
Pool::Postgres(p) => Held::Postgres(Box::new(p.get().await?)),
Pool::Mysql(p) => Held::Mysql(Box::new(p.get().await?)),
Pool::SqlServer(p) => Held::SqlServer(Box::new(p.get_owned().await.map_err(mssql_pool_err)?)),
Pool::Postgres(p) => Held::Postgres(Box::new(Lease::Pooled(p.get().await?))),
Pool::Mysql(p) => Held::Mysql(Box::new(Lease::Pooled(p.get().await?))),
Pool::SqlServer(p) => {
Held::SqlServer(Box::new(Lease::Pooled(p.get_owned().await.map_err(mssql_pool_err)?)))
}
Pool::Clickhouse(p) => {
if p.is_closed() {
return Err(IdeError::new(ErrorKind::Io, "ClickHouse connection is closed"));
@@ -1550,6 +1579,47 @@ impl Held {
})
}
/// A connection that takes none of the pool's; [`discard`](Self::discard) it when done.
pub(crate) async fn acquire_own(pool: &Pool) -> IdeResult<Self> {
Ok(match pool {
Pool::Postgres(p) => {
Held::Postgres(Box::new(Lease::Own(p.inner.dedicated_connection().await.map_err(db_err)?)))
}
Pool::Mysql(p) => Held::Mysql(Box::new(Lease::Own(p.inner.dedicated_connection().await.map_err(db_err)?))),
Pool::SqlServer(p) => {
Held::SqlServer(Box::new(Lease::Own(p.dedicated_connection().await.map_err(mssql_err)?)))
}
Pool::Oracle(p) => Held::Oracle(Box::new(p.open_own().await?)),
_ => Self::acquire(pool).await?,
})
}
/// Whether the server still answers, also inside a failed transaction.
pub(crate) async fn is_alive(&mut self) -> bool {
let ping = async {
match self {
Held::Sqlite(c) => c.ping().await.is_ok(),
Held::Postgres(c) => c.conn.is_some() && c.ping().await.is_ok(),
Held::Mysql(c) => c.conn.is_some() && c.ping().await.is_ok(),
Held::SqlServer(c) => c.0.is_some() && mssql_command(c, "SELECT 1").await.is_ok(),
Held::Oracle(c) => {
crate::oracle::run(c, "SELECT 1 FROM DUAL", 0, 1, Cells::Text, &CancellationToken::new())
.await
.is_ok()
}
Held::Clickhouse(_) | Held::Snowflake(..) => true,
}
};
tokio::time::timeout(Duration::from_secs(5), ping).await.unwrap_or(false)
}
/// Returns the connection that ran `sql` to its pool, unless `sql` left a transaction open on it.
pub(crate) async fn release_after(self, sql: &str, driver: DbDriver) {
if crate::console_session::opens_transaction(sql, driver) {
self.discard().await;
}
}
fn context(&mut self) -> Option<&mut Context> {
match self {
Held::Postgres(c) => Some(&mut c.context),
+2 -1
Переглянути файл
@@ -7,7 +7,8 @@ use sqlx::{Executor, SqlSafeStr};
// Take the first snapshot before user SQL, fixing the transaction characteristics on this backend.
pub(super) const BEGIN: &str = "BEGIN READ ONLY; SELECT 1";
fn leading_word<'a>(input: &mut &'a str) -> &'a str {
/// Takes the first word off `input`, past comments; empty when something else comes first.
pub(crate) fn leading_word<'a>(input: &mut &'a str) -> &'a str {
loop {
*input = input.trim_start_matches([' ', '\t', '\r', '\n', '\x0c', '\x0b', ';']);
if let Some(comment) = input.strip_prefix("--") {
+289
Переглянути файл
@@ -0,0 +1,289 @@
//! The connection a SQL console keeps in auto-commit mode.
//!
//! Plain queries and changes run on any connection of the pool. The first statement that leaves
//! something on its connection (a transaction, a temporary table, a setting) opens the console's
//! own one, which then runs everything the console runs until the console is released.
use crate::conn::{Held, Pool, leading_word};
use crate::source::DbDriver;
use crate::{QueryResult, split};
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{Mutex as AsyncMutex, OwnedSemaphorePermit, Semaphore};
/// Consoles of one target that can keep a connection, beside those of the pool.
pub(crate) const MAX_SESSIONS: u32 = 4;
/// `Some(true)`: `sql` opens a transaction, `Some(false)`: it ends the open one.
fn transaction_control(sql: &str, driver: DbDriver) -> Option<bool> {
let mut rest = sql;
let first = leading_word(&mut rest).to_ascii_uppercase();
let second = leading_word(&mut rest).to_ascii_uppercase();
match first.as_str() {
// A block, not a transaction.
"BEGIN" if driver == DbDriver::Oracle => None,
"BEGIN" if driver == DbDriver::SqlServer => second.starts_with("TRAN").then_some(true),
"BEGIN" | "SAVEPOINT" => Some(true),
"START" if second == "TRANSACTION" => Some(true),
"SET" if matches!(second.as_str(), "AUTOCOMMIT" | "IMPLICIT_TRANSACTIONS") => Some(true),
"COMMIT" | "END" | "ABORT" => Some(false),
"ROLLBACK" if !sql.split_whitespace().any(|word| word.eq_ignore_ascii_case("TO")) => Some(false),
_ => None,
}
}
fn statements(sql: &str, driver: DbDriver) -> Vec<String> {
// The `;` in the body of a routine or trigger ends none of its creator's statements.
if sql.contains(';') && !leading_word(&mut &*sql).eq_ignore_ascii_case("CREATE") {
split::split(sql, driver).into_iter().map(|s| s.text).collect()
} else {
vec![sql.to_owned()]
}
}
pub(crate) fn opens_transaction(sql: &str, driver: DbDriver) -> bool {
statements(sql, driver).iter().any(|sql| transaction_control(sql, driver) == Some(true))
}
/// Whether a later statement of the console depends on `sql` having run on its connection.
/// Unknown statements do.
fn needs_session(sql: &str, driver: DbDriver) -> bool {
statements(sql, driver).iter().any(|sql| {
let mut rest = sql.as_str();
let mut first = leading_word(&mut rest);
while first.is_empty()
&& let Some(inner) = rest.strip_prefix('(')
{
rest = inner;
first = leading_word(&mut rest);
}
let first = first.to_ascii_uppercase();
let words = || rest.split_whitespace().map(str::to_ascii_uppercase);
match first.as_str() {
"SELECT" | "WITH" | "VALUES" | "TABLE" | "INSERT" | "UPDATE" | "DELETE" | "REPLACE" | "MERGE" => {
let text = rest.to_ascii_uppercase();
let into = words().any(|word| word == "INTO");
["SET_CONFIG", "ADVISORY_LOCK", "GET_LOCK", ":="].iter().any(|state| text.contains(state))
|| (into && words().any(|word| is_temporary(&word, driver)))
}
"CREATE" => words().take(4).any(|word| is_temporary(&word, driver)),
"ALTER" => words().next().is_some_and(|word| word == "SESSION"),
"SHOW" | "EXPLAIN" | "DESCRIBE" | "DESC" | "DROP" | "TRUNCATE" | "RENAME" | "COMMENT" | "GRANT"
| "REVOKE" | "ANALYZE" | "VACUUM" | "REINDEX" | "OPTIMIZE" | "COMMIT" | "END" | "ABORT" | "ROLLBACK" => {
false
}
_ => true,
}
})
}
fn is_temporary(word: &str, driver: DbDriver) -> bool {
matches!(word, "TEMP" | "TEMPORARY")
|| (driver == DbDriver::SqlServer
&& word.starts_with(['#', '['])
&& word.trim_start_matches('[').starts_with('#'))
}
struct Open {
connection: Held,
_permit: OwnedSemaphorePermit,
/// The console's schema the connection was last put in. Reapplied only when the console picks
/// another one, so a `USE` or `SET search_path` of the user stays.
schema: Option<String>,
transaction: bool,
/// The schema was set inside the open transaction, whose rollback may restore the one before.
schema_in_transaction: bool,
}
impl Open {
async fn new(pool: &Pool, capacity: &Arc<Semaphore>, schema: Option<&str>) -> IdeResult<Self> {
let permit = capacity.clone().try_acquire_owned().map_err(|_| {
IdeError::unavailable(format!(
"{MAX_SESSIONS} consoles already keep a session on this data source. Close one of them and its results, then run the statement again."
))
})?;
let mut connection = Held::acquire_own(pool).await?;
connection.apply_context(schema).await?;
Ok(Self {
connection,
_permit: permit,
schema: schema.map(str::to_owned),
transaction: false,
schema_in_transaction: false,
})
}
async fn run(
&mut self,
pool: &Pool,
statement: &str,
skip: usize,
max_rows: usize,
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<QueryResult> {
let driver = pool.driver();
// A failed transaction refuses everything but its end, switching the schema included.
if self.schema.as_deref() != schema && transaction_control(statement, driver) != Some(false) {
self.connection.apply_context(schema).await?;
self.schema = schema.map(str::to_owned);
self.schema_in_transaction = self.transaction;
}
let result = self.connection.execute_from(pool, statement, skip, max_rows, cancel).await?;
for control in statements(statement, driver).iter().filter_map(|sql| transaction_control(sql, driver)) {
self.transaction = control;
}
if !self.transaction && std::mem::take(&mut self.schema_in_transaction) {
self.connection.apply_context(self.schema.as_deref()).await?;
}
Ok(result)
}
async fn close(mut self) {
if self.transaction {
let _ = tokio::time::timeout(Duration::from_secs(5), self.connection.finish_manual(false)).await;
}
self.connection.discard().await;
}
}
#[derive(Default)]
struct Slot {
open: Option<Open>,
/// The connection ended inside a transaction, so the statements that follow must not commit on their own.
lost_transaction: bool,
}
#[derive(Default)]
pub(super) struct ConsoleSession {
slot: AsyncMutex<Slot>,
retired: CancellationToken,
}
impl ConsoleSession {
/// Runs `statement` on the console's connection; `None` when it has none and needs none.
#[allow(clippy::too_many_arguments)]
pub(super) async fn execute(
&self,
pool: &Pool,
capacity: &Arc<Semaphore>,
statement: &str,
skip: usize,
max_rows: usize,
request: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<Option<QueryResult>> {
let cancel = self.retired.child_token();
let mut slot = tokio::select! {
biased;
() = request.cancelled() => return Err(IdeError::cancelled()),
() = cancel.cancelled() => return Err(IdeError::cancelled()),
slot = self.slot.lock() => slot,
};
if std::mem::take(&mut slot.lost_transaction) {
return Err(IdeError::new(
ErrorKind::OutOfSync,
"The console's connection was closed and its open transaction rolled back. Run the statement again to start over in a new session.",
));
}
let schema = schema.filter(|s| !s.is_empty());
if slot.open.is_none() {
if !needs_session(statement, pool.driver()) {
return Ok(None);
}
slot.open = Some(tokio::select! {
biased;
() = request.cancelled() => return Err(IdeError::cancelled()),
() = cancel.cancelled() => return Err(IdeError::cancelled()),
open = Open::new(pool, capacity, schema) => open?,
});
}
let open = slot.open.as_mut().expect("opened above");
let result = {
let execute = open.run(pool, statement, skip, max_rows, &cancel, schema);
tokio::pin!(execute);
tokio::select! {
biased;
() = request.cancelled() => {
cancel.cancel();
execute.await
}
result = &mut execute => result,
}
};
let cancelled = cancel.is_cancelled();
if cancelled || (result.is_err() && !open.connection.is_alive().await) {
let open = slot.open.take().expect("opened above");
slot.lost_transaction = open.transaction;
open.connection.discard().await;
}
if cancelled {
return Err(IdeError::cancelled());
}
result.map(Some)
}
/// Stops a running statement, rolls back and closes the connection.
pub(super) async fn retire(&self) {
self.retired.cancel();
let open = self.slot.lock().await.open.take();
if let Some(open) = open {
open.close().await;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn statements_that_leave_something_on_their_connection_need_a_session() {
use DbDriver::{Mysql, Oracle, Postgres, SqlServer, Sqlite};
for (driver, sql) in [
(Sqlite, "/* note */ BEGIN"),
(Sqlite, "PRAGMA foreign_keys = ON"),
(Sqlite, "ATTACH 'other.db' AS other"),
(Postgres, "SET work_mem = '64MB'"),
(Postgres, "CREATE TEMP TABLE t (id int)"),
(Postgres, "create local temporary table t (id int)"),
(Postgres, "SELECT * INTO TEMP t FROM u"),
(Postgres, "SELECT pg_advisory_lock(1)"),
(Postgres, "INSERT INTO t VALUES (1); BEGIN"),
(Mysql, "USE shop"),
(Mysql, "SELECT @n := 1"),
(Mysql, "LOCK TABLES t WRITE"),
(SqlServer, "BEGIN TRAN"),
(SqlServer, "CREATE TABLE #work (id int)"),
(SqlServer, "SELECT * INTO #work FROM t"),
(Oracle, "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY'"),
] {
assert!(needs_session(sql, driver), "{sql}");
}
for (driver, sql) in [
(Postgres, "SELECT temp FROM weather"),
(Postgres, "-- all\n(SELECT 1) UNION (SELECT 2)"),
(Postgres, "WITH x AS (SELECT 1) SELECT * FROM x"),
(Postgres, "INSERT INTO t VALUES ('a;b')"),
(Postgres, "CREATE TABLE t (temp int)"),
(Postgres, "ALTER TABLE t ADD c int"),
(Postgres, "ROLLBACK"),
(Sqlite, "DELETE FROM t; DELETE FROM u"),
(Mysql, "SHOW TABLES"),
] {
assert!(!needs_session(sql, driver), "{sql}");
}
}
#[test]
fn blocks_and_partial_rollbacks_do_not_change_the_transaction() {
assert_eq!(transaction_control("BEGIN NULL; END;", DbDriver::Oracle), None);
assert_eq!(transaction_control("BEGIN TRY SELECT 1 END TRY", DbDriver::SqlServer), None);
assert_eq!(transaction_control("rollback to savepoint s", DbDriver::Postgres), None);
assert_eq!(transaction_control("-- done\nROLLBACK", DbDriver::Mysql), Some(false));
assert_eq!(transaction_control("START TRANSACTION", DbDriver::Mysql), Some(true));
assert!(opens_transaction("DELETE FROM t; BEGIN", DbDriver::Sqlite));
assert!(!opens_transaction("SELECT 'BEGIN; x'", DbDriver::Sqlite));
}
}
+7
Переглянути файл
@@ -255,6 +255,13 @@ impl Helper {
"TEMP",
"TMP",
"SSH_AUTH_SOCK",
// kubectl, gcloud and other cloud CLIs find their configuration here.
"KUBECONFIG",
"CLOUDSDK_CONFIG",
"AWS_PROFILE",
"AWS_CONFIG_FILE",
"AWS_SHARED_CREDENTIALS_FILE",
"AZURE_CONFIG_DIR",
"NO_PROXY",
"no_proxy",
] {
+39 -2
Переглянути файл
@@ -4,6 +4,7 @@
pub mod catalog;
mod clickhouse;
mod console_session;
mod external_tunnel;
pub use external_tunnel::stop_external_tunnels_on_exit;
mod jdbc;
@@ -1652,11 +1653,19 @@ impl DbManager {
let pool = self.pool(id).await?;
let driver = pool.driver();
let missing = || IdeError::not_found(format!("{schema}.{name}"));
if let Pool::Jdbc(jdbc) = &*pool {
return jdbc
.metadata(&["tableDdl", schema, name])
.await?
.into_iter()
.find_map(|row| row.into_iter().next().flatten())
.ok_or_else(missing);
}
let cells = |rows: Vec<Vec<Option<String>>>, i: usize| -> Vec<String> {
rows.into_iter().filter_map(|r| r.into_iter().nth(i).flatten()).collect()
};
match driver {
DbDriver::Jdbc => Err(IdeError::invalid("Custom JDBC sources do not provide vendor-specific DDL")),
DbDriver::Jdbc => unreachable!("JDBC uses driver metadata"),
DbDriver::Sqlite => {
let stmts = cells(pool.rows(&sql::sqlite_ddl(schema, name), MAX_META_ROWS).await?, 0);
if stmts.is_empty() {
@@ -2095,6 +2104,8 @@ impl DbManager {
let _ = self.run(id, &plan::oracle_plan_cleanup(&plan_id), 0, 0, cancel, None, None).await;
return nodes;
}
// SHOWPLAN is a setting of the connection that would stay on in the console's session.
let console = console.filter(|_| driver != DbDriver::SqlServer);
let result = self
.run(id, &plan::explain_statement(driver, statement), 0, MAX_META_ROWS, cancel, schema, console)
.await?;
@@ -2142,6 +2153,7 @@ impl DbManager {
{
return p.execute_in_console(statement, skip, max_rows, cancel, console).await;
}
let editor = console.filter(|_| !matches!(&*pool, Pool::Snowflake(_)) && !pool.transaction_read_only());
let console = console.filter(|_| matches!(&*pool, Pool::Postgres(_)));
let session = match console {
Some(console) => connection.console_transactions.session(console),
@@ -2156,6 +2168,15 @@ impl DbManager {
// A cursor's open statement could keep this one waiting (a lock), and would show data from before it.
self.cursors.release_target(id);
}
if session.is_none()
&& let Some(editor) = editor
&& let Some(result) = connection
.console_transactions
.execute_auto(editor, &pool, statement, skip, max_rows, cancel, schema)
.await?
{
return Ok(result);
}
if paging && session.is_none() && (skip > 0 || protected) && pool.keeps_cursors() && cursor {
let key = conn::CursorKey::new(id, statement, schema).with_console(console);
let started = std::time::Instant::now();
@@ -2188,6 +2209,7 @@ impl DbManager {
conn.discard().await;
return Err(IdeError::cancelled());
}
conn.release_after(statement, pool.driver()).await;
return r;
};
if pool.driver() == DbDriver::Clickhouse {
@@ -2208,6 +2230,12 @@ impl DbManager {
if self.source(id)?.driver == DbDriver::Clickhouse {
return Err(IdeError::invalid("ClickHouse manual transactions are unsupported"));
}
if self.source(id)?.driver != DbDriver::Postgres
&& let Some(connection) = self.opened_connection(id)
{
// Their statements now run in the transaction of the whole data source.
connection.console_transactions.release_all_auto().await;
}
self.sessions.lock().entry(id.to_owned()).or_default();
} else {
let session = self.sessions.lock().remove(id);
@@ -2237,7 +2265,9 @@ impl DbManager {
return Err(IdeError::invalid("Scoped manual transactions require a PostgreSQL data source"));
}
if manual {
self.connection(id).await?.console_transactions.enable(console)
let connection = self.connection(id).await?;
connection.console_transactions.release_auto(console).await;
connection.console_transactions.enable(console)
} else {
if let Some(connection) = self.opened_connection(id) {
connection.console_transactions.release(console).await?;
@@ -2443,10 +2473,17 @@ mod tests {
DataSource { url_only: true, ..source.clone() },
DataSource { plugin_owner: Some("sample".into()), ..source.clone() },
DataSource { driver: DbDriver::Jdbc, ..source.clone() },
DataSource { driver: DbDriver::Sqlite, ..source.clone() },
DataSource { driver: DbDriver::Snowflake, ..source.clone() },
DataSource { ssh: Some(DbSsh { enabled: true, ..Default::default() }), ..source.clone() },
] {
assert!(db.approve_external_tunnel(&bad).await.is_err());
}
// Every driver an SSH tunnel can carry can use a helper too (kubectl port-forward and the like).
for driver in [DbDriver::Postgres, DbDriver::Mysql, DbDriver::SqlServer, DbDriver::Clickhouse, DbDriver::Oracle]
{
assert!(db.external_config(&DataSource { driver, ..source.clone() }).is_ok(), "{driver:?}");
}
}
#[tokio::test]
+48 -1
Переглянути файл
@@ -1,3 +1,4 @@
use crate::console_session::{ConsoleSession, MAX_SESSIONS};
use crate::{ConsoleId, Held, Pool, QueryResult};
use ide_core::{CancellationToken, IdeError, IdeResult};
use parking_lot::Mutex;
@@ -144,14 +145,23 @@ impl ManualSession {
pub(super) struct ConsoleTransactions {
sessions: Mutex<HashMap<ConsoleKey, Session>>,
/// Consoles in auto-commit mode.
auto: Mutex<HashMap<ConsoleKey, Arc<ConsoleSession>>>,
closed: CancellationToken,
/// The four-slot pool also serves ordinary work and one retained result cursor.
pub(super) capacity: Arc<Semaphore>,
auto_capacity: Arc<Semaphore>,
}
impl Default for ConsoleTransactions {
fn default() -> Self {
Self { sessions: Mutex::default(), closed: CancellationToken::new(), capacity: Arc::new(Semaphore::new(2)) }
Self {
sessions: Mutex::default(),
auto: Mutex::default(),
closed: CancellationToken::new(),
capacity: Arc::new(Semaphore::new(2)),
auto_capacity: Arc::new(Semaphore::new(MAX_SESSIONS as usize)),
}
}
}
@@ -178,7 +188,43 @@ impl ConsoleTransactions {
}
}
/// Runs `statement` in the console's session; `None` when it has none and needs none.
#[allow(clippy::too_many_arguments)]
pub(super) async fn execute_auto(
&self,
console: ConsoleId<'_>,
pool: &Pool,
statement: &str,
skip: usize,
max_rows: usize,
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<Option<QueryResult>> {
let session = {
let mut auto = self.auto.lock();
if self.closed.is_cancelled() {
return Err(IdeError::cancelled());
}
auto.entry(key(console)).or_default().clone()
};
// Boxed: the connect inside would double the size of every statement's future.
Box::pin(session.execute(pool, &self.auto_capacity, statement, skip, max_rows, cancel, schema)).await
}
pub(super) async fn release_auto(&self, console: ConsoleId<'_>) {
let session = self.auto.lock().remove(&key(console));
if let Some(session) = session {
session.retire().await;
}
}
pub(super) async fn release_all_auto(&self) {
let sessions = std::mem::take(&mut *self.auto.lock());
futures::future::join_all(sessions.values().map(|session| session.retire())).await;
}
pub(super) async fn release(&self, console: ConsoleId<'_>) -> IdeResult<()> {
self.release_auto(console).await;
let session = self.sessions.lock().remove(&key(console));
if let Some(session) = session {
session.retire().await?;
@@ -198,5 +244,6 @@ impl ConsoleTransactions {
for session in sessions.into_values() {
let _ = session.rollback_and_release().await;
}
self.release_all_auto().await;
}
}
+7 -2
Переглянути файл
@@ -203,7 +203,12 @@ impl OraclePool {
/// A connection taken out of the pool for one statement or a held session.
pub async fn get(&self) -> IdeResult<OracleConnection> {
let pooled = self.pool.get_owned().await.map_err(|e| pool_err(e).into_ide())?;
Ok(OracleConnection { state: self.state.clone(), pooled })
Ok(OracleConnection { state: self.state.clone(), pooled: crate::conn::Lease::Pooled(pooled) })
}
pub(crate) async fn open_own(&self) -> IdeResult<OracleConnection> {
let own = self.pool.dedicated_connection().await.map_err(OracleError::into_ide)?;
Ok(OracleConnection { state: self.state.clone(), pooled: crate::conn::Lease::Own(own) })
}
pub fn is_closed(&self) -> bool {
@@ -273,7 +278,7 @@ impl ManageConnection for OracleConnectionManager {
/// unless its statement was cancelled (then it is discarded).
pub struct OracleConnection {
state: Arc<State>,
pooled: bb8::PooledConnection<'static, OracleConnectionManager>,
pooled: crate::conn::Lease<OracleConnectionManager>,
}
impl OracleConnection {
+8 -3
Переглянути файл
@@ -8,7 +8,7 @@
//! statement valid, which the ignored live test does for the commands that only read.
use super::tests::{CLOSED_OK, LOGIN_OK, bind, ok, result, serve, source};
use super::{first_word, is_write};
use super::{Use, first_word, is_write, use_kind};
use crate::conn::Pool;
use crate::source::DbDriver;
use crate::split::split;
@@ -106,11 +106,16 @@ async fn every_command_reaches_the_server_as_written_and_its_answer_is_read() {
let mut replies = vec![ok(LOGIN_OK)];
let mut entered = true;
for c in commands.iter().filter(|c| !transfers(c)) {
if !entered && first_word(&c.sql) != "USE" {
// A role switch enters the schema first, like a statement that runs in it.
let switch = use_kind(&c.sql);
if !entered && matches!(switch, None | Some(Use::Role)) {
replies.push(ok(status.clone()));
}
// These leave the session wherever they went: its schema is entered again afterwards.
entered = !matches!(first_word(&c.sql).as_str(), "USE" | "CALL" | "EXECUTE");
// A warehouse leaves it as it was.
if switch != Some(Use::Warehouse) {
entered = switch != Some(Use::Place) && !matches!(first_word(&c.sql).as_str(), "CALL" | "EXECUTE");
}
let dml = matches!(first_word(&c.sql).as_str(), "INSERT" | "UPDATE" | "DELETE" | "MERGE");
replies.push(ok(if c.reads && first_word(&c.sql) != "USE" {
rows.clone()
+8 -3
Переглянути файл
@@ -259,12 +259,17 @@ pub(crate) async fn catalog(pool: &SnowflakePool, database: &str) -> IdeResult<V
pub(crate) async fn session(pool: &SnowflakePool) -> IdeResult<crate::SessionContext> {
// The consoles' session: `USE WAREHOUSE` / `USE ROLE` there is what the pickers show.
let sql = "SELECT CURRENT_WAREHOUSE(), CURRENT_ROLE(), CURRENT_AVAILABLE_ROLES()";
let current = pool.execute(sql, 1, &CancellationToken::new()).await?.rows;
// It names no table: the role just switched to may not use this target's schema.
let cancel = CancellationToken::new();
let current = pool.execute_here(sql, 1, &cancel).await?.rows;
let cell = |i: usize| current.first().and_then(|r| r.get(i).cloned().flatten()).unwrap_or_default();
let mut roles: Vec<String> = serde_json::from_str(&cell(2)).unwrap_or_default();
roles.sort();
let warehouses = match show(pool, "SHOW WAREHOUSES").await {
Ok(shown) => shown.values("name").flatten().map(str::to_owned).collect(),
let warehouses = match pool.execute_here("SHOW WAREHOUSES", MAX_ROWS, &cancel).await {
Ok(result) => {
let shown = Shown { columns: result.columns.into_iter().map(|c| c.name).collect(), rows: result.rows };
shown.values("name").flatten().map(str::to_owned).collect()
}
Err(_) => Vec::new(),
};
Ok(crate::SessionContext { warehouse: cell(0), role: cell(1), warehouses, roles })
+86 -8
Переглянути файл
@@ -209,7 +209,8 @@ fn typed(name: &str) -> String {
crate::sql::quote_ident(crate::DbDriver::Snowflake, &name)
}
fn first_word(sql: &str) -> String {
/// `sql` without the comments and blanks it starts with.
fn skip_comments(sql: &str) -> &str {
let mut sql = sql.trim_start();
loop {
if let Some(rest) = sql.strip_prefix("--").or_else(|| sql.strip_prefix("//")) {
@@ -220,7 +221,41 @@ fn first_word(sql: &str) -> String {
break;
}
}
sql.split(|c: char| !c.is_ascii_alphanumeric() && c != '_').next().unwrap_or_default().to_ascii_uppercase()
sql
}
fn word(sql: &str) -> &str {
sql.split(|c: char| !c.is_ascii_alphanumeric() && c != '_').next().unwrap_or_default()
}
fn first_word(sql: &str) -> String {
word(skip_comments(sql)).to_ascii_uppercase()
}
/// What a `USE` statement switches.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Use {
/// `USE ROLE`, `USE SECONDARY ROLES`: what the session may reach changes, not where it is.
Role,
/// `USE WAREHOUSE`: neither.
Warehouse,
/// `USE DATABASE`, `USE SCHEMA`, `USE <name>`: the session moves.
Place,
}
fn use_kind(sql: &str) -> Option<Use> {
let sql = skip_comments(sql);
let first = word(sql);
if !first.eq_ignore_ascii_case("USE") {
return None;
}
let rest = skip_comments(&sql[first.len()..]);
// `USE "ROLE"` is a database of that name.
Some(match word(rest).to_ascii_uppercase().as_str() {
"ROLE" | "SECONDARY" => Use::Role,
"WAREHOUSE" => Use::Warehouse,
_ => Use::Place,
})
}
/// Whether `sql` may change data or objects (a read-only data source refuses it).
@@ -657,17 +692,33 @@ impl SnowflakePool {
() = self.closed.cancelled() => return Err(closed()),
turn = self.lane().turn.lock() => turn,
};
let switch = use_kind(sql);
// A `USE` needs no schema to run in, and may be what makes the schema reachable. Ending a
// transaction needs none either, and must not fail because the schema is gone meanwhile.
let context = match first_word(sql).as_str() {
"USE" | "COMMIT" | "ROLLBACK" => None,
let first = first_word(sql);
let context = match first.as_str() {
"USE" => {
// The role being left may use this schema and the next one may not: the session
// goes there first, and stays there, as a session of its own would. Refused: the
// new role may be the one that can.
if switch == Some(Use::Role)
&& let Err(error) = self.enter(schema, cancel).await
&& error.kind != ErrorKind::InvalidInput
{
return Err(error);
}
None
}
"COMMIT" | "ROLLBACK" => None,
_ => {
self.enter(schema, cancel).await?;
self.context(schema)
}
};
// These can move the session to another database or schema.
let moves = matches!(first_word(sql).as_str(), "USE" | "CALL" | "EXECUTE");
// These can move the session to another database or schema. A role or a warehouse does
// not: the schema is not asked for again, which the new role may not be allowed to use
// while its statements name what they read in full.
let moves = switch == Some(Use::Place) || matches!(first.as_str(), "CALL" | "EXECUTE");
let result = self.statement(sql, skip, max_rows, Lost::Enter(context.as_deref()), cancel).await;
if moves {
*self.lane().context.lock() = None;
@@ -675,18 +726,45 @@ impl SnowflakePool {
result.map_err(|error| explain_use(sql, error))
}
/// A statement about the session itself (its role, its warehouse): it runs wherever the
/// session is and leaves it there, so the session's role need not be allowed to use this
/// target's schema.
pub(crate) async fn execute_here(
&self,
sql: &str,
max_rows: usize,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
let _turn = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
() = self.closed.cancelled() => return Err(closed()),
turn = self.lane().turn.lock() => turn,
};
self.statement(sql, 0, max_rows, Lost::Enter(None), cancel).await
}
/// Puts the session under this target's database and `schema` when it is not there already.
async fn enter(&self, schema: Option<&str>, cancel: &CancellationToken) -> IdeResult<()> {
if let Some(wanted) = self.context(schema)
&& self.lane().context.lock().as_deref() != Some(wanted.as_str())
{
*self.lane().context.lock() = None;
// Refused (the session's role may not use this database or schema): the statement
// does not run, since the session is still wherever it was, which may be another
// target's database. Tried again with the next statement.
if let Err(error) = self.statement(&wanted, 0, 0, Lost::Enter(None), cancel).await {
// Snowflake's own refusal leaves the session where it was known to be; after
// anything else (cancelled, the session lost) it may be anywhere.
if error.kind != ErrorKind::InvalidInput {
*self.lane().context.lock() = None;
}
let hint = if error.kind == ErrorKind::InvalidInput {
"\nChoose a schema the current role can use, or switch roles."
} else {
""
};
return Err(IdeError {
message: format!("{wanted} failed, so the statement was not run: {}", error.message),
message: format!("{wanted} failed, so the statement was not run: {}{hint}", error.message),
..error
});
}
+152 -18
Переглянути файл
@@ -764,22 +764,122 @@ async fn a_console_schema_is_switched_with_its_statement_and_only_when_needed()
);
}
fn status() -> String {
json!({ "success": true, "data": { "rowtype": [{ "name": "status", "type": "text" }],
"rowset": [["Statement executed successfully."]], "queryResultFormat": "json", "statementTypeId": 0x5000 } })
.to_string()
}
const REFUSED: &str = r#"{"success":false,"code":"002043","message":"SQL compilation error:\nObject does not exist, or operation cannot be performed."}"#;
#[test]
fn a_use_statement_says_whether_it_moves_the_session() {
assert_eq!(use_kind("use role auditor"), Some(Use::Role));
assert_eq!(use_kind("-- admin\n/* now */ USE /* the */ ROLE \"Auditor\""), Some(Use::Role));
assert_eq!(use_kind("Use Secondary Roles ALL"), Some(Use::Role));
assert_eq!(use_kind("use warehouse wh"), Some(Use::Warehouse));
assert_eq!(use_kind("use database d"), Some(Use::Place));
assert_eq!(use_kind("use schema d.s"), Some(Use::Place));
assert_eq!(use_kind("use d.s"), Some(Use::Place));
// A database called ROLE.
assert_eq!(use_kind("use \"ROLE\""), Some(Use::Place));
assert_eq!(use_kind("use"), Some(Use::Place));
assert_eq!(use_kind("select 'use role x'"), None);
assert_eq!(use_kind("user_defined()"), None);
}
#[tokio::test]
async fn a_role_that_may_not_use_the_schema_runs_nothing_elsewhere() {
let status = || {
json!({ "success": true, "data": { "rowtype": [{ "name": "status", "type": "text" }],
"rowset": [["Statement executed successfully."]], "queryResultFormat": "json", "statementTypeId": 0x5000 } })
.to_string()
};
let refused = r#"{"success":false,"code":"002043","message":"SQL compilation error:\nObject does not exist, or operation cannot be performed."}"#;
async fn a_role_switch_keeps_the_session_where_it_is() {
let (listener, port) = bind().await;
// use role | the schema is refused, the statement is not sent | asked again, refused again |
// use role back, the schema is entered, the statement runs
// The schema is not asked for again after a role or a warehouse: the new role may not use it,
// and statements that name what they read in full still run.
let replies =
vec![ok(LOGIN_OK), ok(status()), ok(one()), ok(status()), ok(one()), ok(status()), ok(one()), ok(CLOSED_OK)];
let server = serve(listener, replies);
let pool = Pool::connect(&source(port), None, None).await.unwrap();
let cancel = CancellationToken::new();
let statements =
["use role auditor", "select 1", "USE WAREHOUSE \"Big\"", "select 2", "use secondary roles all", "select 3"];
for sql in statements {
pool.execute(sql, 1, &cancel).await.unwrap();
}
pool.close().await;
let sent: Vec<String> =
server.await.unwrap()[1..7].iter().map(|r| r.json()["sqlText"].as_str().unwrap().to_owned()).collect();
assert_eq!(sent, statements);
}
#[tokio::test]
async fn a_role_switch_first_enters_the_consoles_schema() {
let (listener, port) = bind().await;
// select 1 in PUBLIC | the console's schema, while the role being left may use it, use role |
// select 2 without asking for the schema again
let replies = vec![ok(LOGIN_OK), ok(one()), ok(status()), ok(status()), ok(one()), ok(CLOSED_OK)];
let server = serve(listener, replies);
let pool = Pool::connect(&source(port), None, None).await.unwrap();
let cancel = CancellationToken::new();
pool.execute("select 1", 1, &cancel).await.unwrap();
let mut console = crate::conn::Held::acquire(&pool).await.unwrap();
console.apply_context(Some("SALES")).await.unwrap();
console.execute(&pool, "use role auditor", 0, &cancel).await.unwrap();
console.execute(&pool, "select 2", 1, &cancel).await.unwrap();
pool.close().await;
let sent: Vec<String> =
server.await.unwrap()[1..5].iter().map(|r| r.json()["sqlText"].as_str().unwrap().to_owned()).collect();
assert_eq!(sent, ["select 1", "USE SCHEMA \"ANALYTICS\".\"SALES\"", "use role auditor", "select 2"]);
}
#[tokio::test]
async fn reading_the_role_and_warehouse_leaves_the_session_where_it_is() {
let (listener, port) = bind().await;
let current = json!({ "success": true, "data": { "rowtype": [{ "name": "W", "type": "text" },
{ "name": "R", "type": "text" }, { "name": "A", "type": "text" }],
"rowset": [["WH", "AUDITOR", "[\"AUDITOR\",\"ANALYST\"]"]], "queryResultFormat": "json" } })
.to_string();
let warehouses = json!({ "success": true, "data": { "rowtype": [{ "name": "name", "type": "text" }],
"rowset": [["AUDIT_WH"]], "queryResultFormat": "json" } })
.to_string();
// Both pickers read the console session, where the new role is active.
let replies = vec![ok(LOGIN_OK), ok(status()), ok(status()), ok(current), ok(warehouses), ok(one()), ok(CLOSED_OK)];
let server = serve(listener, replies);
let pool = Pool::connect(&source(port), None, None).await.unwrap();
let Pool::Snowflake(snowflake) = &pool else { unreachable!() };
let cancel = CancellationToken::new();
let mut console = crate::conn::Held::acquire(&pool).await.unwrap();
console.apply_context(Some("SALES")).await.unwrap();
console.execute(&pool, "use role auditor", 0, &cancel).await.unwrap();
let session = meta::session(snowflake).await.unwrap();
assert_eq!((session.role.as_str(), session.roles.len()), ("AUDITOR", 2));
assert_eq!(session.warehouses, ["AUDIT_WH"]);
console.execute(&pool, "select 1", 1, &cancel).await.unwrap();
pool.close().await;
let seen = server.await.unwrap();
let sent: Vec<String> = seen.iter().filter_map(|r| r.json()["sqlText"].as_str().map(str::to_owned)).collect();
assert_eq!(
sent,
[
"USE SCHEMA \"ANALYTICS\".\"SALES\"",
"use role auditor",
"SELECT CURRENT_WAREHOUSE(), CURRENT_ROLE(), CURRENT_AVAILABLE_ROLES()",
"SHOW WAREHOUSES",
"select 1"
]
);
}
#[tokio::test]
async fn a_schema_the_role_may_not_use_runs_nothing_elsewhere() {
let (listener, port) = bind().await;
// use role in PUBLIC | the console's schema is refused, its statement is not sent | select 2
// in PUBLIC, where the session still is | refused again | refused before use role, which is
// sent all the same | the schema is entered, select 4
let replies = vec![
ok(LOGIN_OK),
ok(status()),
ok(refused),
ok(refused),
ok(REFUSED),
ok(one()),
ok(REFUSED),
ok(REFUSED),
ok(status()),
ok(status()),
ok(one()),
@@ -788,8 +888,10 @@ async fn a_role_that_may_not_use_the_schema_runs_nothing_elsewhere() {
let server = serve(listener, replies);
let pool = Pool::connect(&source(port), None, None).await.unwrap();
let cancel = CancellationToken::new();
let mut console = crate::conn::Held::acquire(&pool).await.unwrap();
console.apply_context(Some("SALES")).await.unwrap();
pool.execute("use role auditor", 0, &cancel).await.unwrap();
let error = pool.execute("delete from t", 1, &cancel).await.unwrap_err();
let error = console.execute(&pool, "delete from t", 1, &cancel).await.unwrap_err();
assert!(
error.message.contains("USE SCHEMA")
&& error.message.contains("was not run")
@@ -797,14 +899,46 @@ async fn a_role_that_may_not_use_the_schema_runs_nothing_elsewhere() {
"{}",
error.message
);
assert!(pool.execute("select 2", 1, &cancel).await.is_err());
pool.execute("use role analyst", 0, &cancel).await.unwrap();
pool.execute("select 3", 1, &cancel).await.unwrap();
pool.execute("select 2", 1, &cancel).await.unwrap();
assert!(console.execute(&pool, "select 3", 1, &cancel).await.is_err());
console.execute(&pool, "use role analyst", 0, &cancel).await.unwrap();
console.execute(&pool, "select 4", 1, &cancel).await.unwrap();
pool.close().await;
let sent: Vec<String> =
server.await.unwrap()[1..7].iter().map(|r| r.json()["sqlText"].as_str().unwrap().to_owned()).collect();
let schema = "USE SCHEMA \"ANALYTICS\".\"PUBLIC\"";
assert_eq!(sent, ["use role auditor", schema, schema, "use role analyst", schema, "select 3"]);
server.await.unwrap()[1..9].iter().map(|r| r.json()["sqlText"].as_str().unwrap().to_owned()).collect();
let sales = "USE SCHEMA \"ANALYTICS\".\"SALES\"";
assert_eq!(sent, ["use role auditor", sales, "select 2", sales, sales, "use role analyst", sales, "select 4"]);
}
#[tokio::test]
async fn a_schema_refusal_after_login_does_not_restore_the_old_context() {
let (listener, port) = bind().await;
let gone = r#"{"success":false,"code":"390114","message":"Session closed."}"#;
let server = serve(
listener,
vec![
ok(LOGIN_OK),
ok(status()),
ok(status()),
ok(gone),
ok(LOGIN_OK),
ok(REFUSED),
ok(status()),
ok(one()),
ok(CLOSED_OK),
],
);
let pool = Pool::connect(&source(port), None, None).await.unwrap();
let cancel = CancellationToken::new();
let mut sales = crate::conn::Held::acquire(&pool).await.unwrap();
sales.apply_context(Some("SALES")).await.unwrap();
sales.execute(&pool, "use role auditor", 0, &cancel).await.unwrap();
assert!(pool.execute("select 1", 1, &cancel).await.is_err());
sales.execute(&pool, "select 2", 1, &cancel).await.unwrap();
pool.close().await;
let seen = server.await.unwrap();
assert_eq!(seen[6].json()["sqlText"], "USE SCHEMA \"ANALYTICS\".\"SALES\"");
assert_eq!(seen[7].json()["sqlText"], "select 2");
}
#[tokio::test]
+116 -11
Переглянути файл
@@ -1,5 +1,7 @@
//! Splitting SQL scripts into statements (`;`-terminated), aware of string
//! literals, quoted identifiers, comments and PostgreSQL dollar quoting.
//! MySQL strings take backslash escapes (no `NO_BACKSLASH_ESCAPES`) and double
//! quotes (no `ANSI_QUOTES`), its defaults; the console's lexer.ts reads them alike.
//! Offsets are UTF-16 code units, like everything on the IPC boundary.
use crate::DbDriver;
@@ -22,12 +24,13 @@ enum State {
Single,
Double,
Backtick,
Bracket,
LineComment,
BlockComment,
}
// Starts just after the opening `/*`. ClickHouse supports nested block comments.
fn after_clickhouse_block_comment(mut text: &str) -> &str {
// Starts just after the opening `/*`.
fn after_nested_block_comment(mut text: &str) -> &str {
let mut depth = 1usize;
while let Some(at) = text.find(['/', '*']) {
text = &text[at..];
@@ -55,7 +58,7 @@ pub(super) fn clickhouse_keyword<'a>(sql: &mut &'a str) -> Option<&'a str> {
if let Some(comment) = text.strip_prefix('#').or_else(|| text.strip_prefix("--")) {
text = comment.split_once('\n').map_or("", |(_, rest)| rest);
} else if let Some(comment) = text.strip_prefix("/*") {
text = after_clickhouse_block_comment(comment);
text = after_nested_block_comment(comment);
} else {
break;
}
@@ -76,6 +79,10 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
// PL/SQL: `;` inside BEGIN…END / DECLARE…END blocks does not terminate a statement.
let plsql = driver == DbDriver::Oracle;
let snowflake = driver == DbDriver::Snowflake;
let postgres = driver == DbDriver::Postgres;
let sqlite = driver == DbDriver::Sqlite;
let sql_server = driver == DbDriver::SqlServer;
let nested_comments = clickhouse || postgres || sql_server;
let chars: Vec<(usize, char)> = text.char_indices().collect();
// UTF-16 offset of each char index (plus the end).
let mut u16_at = Vec::with_capacity(chars.len() + 1);
@@ -105,6 +112,8 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
let mut script = false;
// The segment may carry a Scripting block as its body (`CREATE TASK … AS BEGIN … END`).
let mut defines = false;
// The open string is PostgreSQL's `E'…'`.
let mut escape_string = false;
let push = |out: &mut Vec<SqlStatement>, s: usize, e: usize, has_code: bool| {
if !has_code {
return;
@@ -164,6 +173,18 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
defines = false;
}
';' => has_code = true,
// Words are read whole: the `E` of `E'…'` starts one, and a `$` inside one quotes nothing.
_ if postgres && (c.is_alphabetic() || c == '_') => {
has_code = true;
if matches!(c, 'E' | 'e') && next == Some('\'') {
(state, escape_string) = (State::Single, true);
i += 1;
} else {
while chars.get(i + 1).is_some_and(|&(_, c)| c.is_alphanumeric() || matches!(c, '_' | '$')) {
i += 1;
}
}
}
'\'' => {
state = State::Single;
has_code = true;
@@ -172,13 +193,17 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
state = State::Double;
has_code = true;
}
'`' if mysql || clickhouse => {
'`' if mysql || clickhouse || sqlite => {
state = State::Backtick;
has_code = true;
}
'[' if sqlite || sql_server => {
state = State::Bracket;
has_code = true;
}
'/' if next == Some('*') => {
if clickhouse {
let rest = after_clickhouse_block_comment(&text[byte_at(i + 2)..]);
if nested_comments {
let rest = after_nested_block_comment(&text[byte_at(i + 2)..]);
let end = text.len() - rest.len();
i = chars.partition_point(|&(offset, _)| offset < end);
continue;
@@ -199,7 +224,10 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
block = false;
package = false;
}
'-' if next == Some('-') => {
// MySQL reads `5--1` as a subtraction.
'-' if next == Some('-')
&& (!mysql || chars.get(i + 2).is_none_or(|&(_, c)| c == ' ' || c.is_ascii_control())) =>
{
state = State::LineComment;
i += 1;
}
@@ -213,7 +241,7 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
state = State::LineComment;
i += 1;
}
'$' if driver == DbDriver::Postgres || snowflake => {
'$' if postgres || snowflake => {
// `$tag$ … $tag$` (tag may be empty); `$1` parameters are not quotes.
let rest = &text[byte_at(i)..];
let tag_len = rest[1..].find('$').filter(|&n| {
@@ -289,18 +317,18 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
_ => {}
},
State::Single => {
if (mysql || clickhouse || snowflake) && c == '\\' {
if (mysql || clickhouse || snowflake || escape_string) && c == '\\' {
i += 1;
} else if c == '\'' {
if next == Some('\'') {
i += 1;
} else {
state = State::Code;
(state, escape_string) = (State::Code, false);
}
}
}
State::Double => {
if clickhouse && c == '\\' {
if (mysql || clickhouse) && c == '\\' {
i += 1;
} else if c == '"' {
if next == Some('"') {
@@ -317,6 +345,13 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
state = State::Code;
}
}
State::Bracket => {
if sql_server && c == ']' && next == Some(']') {
i += 1;
} else if c == ']' {
state = State::Code;
}
}
State::LineComment => {
if c == '\n' {
state = State::Code;
@@ -510,6 +545,76 @@ mod tests {
);
}
#[test]
fn postgres_and_sql_server_nest_block_comments() {
let sql = "/* outer /* inner */ ; DELETE FROM b; */ SELECT 1";
for driver in [DbDriver::Postgres, DbDriver::SqlServer] {
assert_eq!(texts(&format!("{sql}; SELECT 2"), driver), vec![sql, "SELECT 2"]);
assert_eq!(statement_at(sql, 25, driver).map(|s| s.text).as_deref(), Some(sql));
assert_eq!(texts("/* open /* ; */ ; DELETE FROM b", driver), Vec::<String>::new());
}
for driver in [DbDriver::Mysql, DbDriver::Sqlite, DbDriver::Oracle, DbDriver::Snowflake] {
assert_eq!(texts("/* a /* b */ SELECT 1; SELECT 2", driver), vec!["/* a /* b */ SELECT 1", "SELECT 2"]);
}
}
#[test]
fn postgres_escape_strings_and_dollars_in_names() {
for sql in [r"SELECT E'it\'s; DELETE FROM b; --'", r"SELECT e'a\\', E'it''s; \';'"] {
assert_eq!(texts(&format!("{sql}; SELECT 2"), DbDriver::Postgres), vec![sql, "SELECT 2"]);
assert_eq!(statement_at(sql, 22, DbDriver::Postgres).map(|s| s.text).as_deref(), Some(sql));
}
// A backslash is plain in other strings, also after a word that ends in `e`.
for sql in [r"SELECT 'a\'", r"SELECT date'\'", r"SELECT U&'\'", r#"SELECT "a\""#] {
assert_eq!(texts(&format!("{sql}; SELECT 2"), DbDriver::Postgres), vec![sql, "SELECT 2"]);
}
// A `$` inside a name opens no dollar quote.
assert_eq!(
texts("SELECT a$b$ FROM t; SELECT b$b$ FROM t", DbDriver::Postgres),
vec!["SELECT a$b$ FROM t", "SELECT b$b$ FROM t"]
);
}
#[test]
fn mysql_double_quoted_strings_and_dashes() {
let sql = r#"SELECT "say \"hi; DELETE FROM b; \"", 'a''b;', "c"";", `d``;`"#;
assert_eq!(texts(&format!("{sql}; SELECT 2"), DbDriver::Mysql), vec![sql, "SELECT 2"]);
assert_eq!(statement_at(sql, 24, DbDriver::Mysql).map(|s| s.text).as_deref(), Some(sql));
// `--` starts a comment only before whitespace, a control character or the end.
assert_eq!(texts("SELECT 5--1; SELECT 2", DbDriver::Mysql), vec!["SELECT 5--1", "SELECT 2"]);
for comment in ["-- a;", "--\ta;", "--"] {
assert_eq!(texts(&format!("SELECT 5 {comment}\n+ 1; SELECT 2"), DbDriver::Mysql).len(), 2);
assert_eq!(texts(&format!("SELECT 1; {comment}"), DbDriver::Mysql), vec!["SELECT 1"]);
}
for driver in [DbDriver::Postgres, DbDriver::Sqlite, DbDriver::SqlServer, DbDriver::Oracle] {
assert_eq!(texts("SELECT 5--1; SELECT 2", driver), vec!["SELECT 5--1; SELECT 2"]);
}
}
#[test]
fn bracketed_and_backtick_names() {
for (sql, driver) in [
("SELECT * FROM [a;b]", DbDriver::SqlServer),
("SELECT * FROM [a]];'b]", DbDriver::SqlServer),
("SELECT * FROM `a;b`, `c``;'d`", DbDriver::Sqlite),
("SELECT * FROM [c;d], [it's]", DbDriver::Sqlite),
("SELECT * FROM [e[;]", DbDriver::Sqlite),
] {
assert_eq!(texts(&format!("{sql}; SELECT 2"), driver), vec![sql, "SELECT 2"]);
assert_eq!(statement_at(sql, 16, driver).map(|s| s.text).as_deref(), Some(sql));
}
// Array subscripts and literals elsewhere.
assert_eq!(texts("SELECT a[1; SELECT 2", DbDriver::Postgres), vec!["SELECT a[1", "SELECT 2"]);
assert_eq!(texts("SELECT [1; SELECT 2", DbDriver::Clickhouse), vec!["SELECT [1", "SELECT 2"]);
}
#[test]
fn a_selection_keeps_literals_whole() {
let sql = "SELECT 0; SELECT E'\\';'; SELECT 2";
let s = statements_in(sql, 10, sql.len() as u32, DbDriver::Postgres);
assert_eq!(s.iter().map(|s| s.text.as_str()).collect::<Vec<_>>(), vec!["SELECT E'\\';'", "SELECT 2"]);
}
#[test]
fn utf16_offsets() {
let sql = "select '😀';\nselect 2;";
+3 -3
Переглянути файл
@@ -1,6 +1,6 @@
//! Only an explicit desktop action can trust a helper. The project file is portable;
//! the authorization belongs to this machine and to the reviewed destination.
use crate::{DataSource, DbDriver, DbExternalTunnel, DbManager, DbSslMode, local_settings::persist_local};
use crate::{DataSource, DbExternalTunnel, DbManager, DbSslMode, local_settings::persist_local};
use ide_core::{IdeError, IdeResult};
use std::path::{Path, PathBuf};
@@ -14,9 +14,9 @@ impl DbManager {
if !self.local_external_tunnels {
return Err(IdeError::invalid("External database tunnels require a local desktop project"));
}
if source.driver != DbDriver::Postgres || source.plugin_owner.is_some() || source.url_only {
if !crate::tunneled(source.driver) || source.plugin_owner.is_some() || source.url_only {
return Err(IdeError::invalid(
"Use a user-managed PostgreSQL source with host and port for an external tunnel",
"Use a user-managed network database source with host and port for an external tunnel",
));
}
if source.ssh.as_ref().is_some_and(|ssh| ssh.enabled) {
+142
Переглянути файл
@@ -0,0 +1,142 @@
use ide_core::{CancellationToken, IdeResult, error::ErrorKind};
use ide_db::{ConsoleId, DataSource, DbDriver, DbManager, QueryResult};
use std::sync::Arc;
use std::time::Duration;
const TARGET: &str = "fixture";
const A: ConsoleId<'static> = ConsoleId::new("main", "a.sql");
const B: ConsoleId<'static> = ConsoleId::new("main", "b.sql");
const ROWS: &str = "SELECT id FROM public.console_session ORDER BY id";
async fn run_in(db: &DbManager, console: ConsoleId<'_>, sql: &str, schema: &str) -> IdeResult<QueryResult> {
let cancel = CancellationToken::new();
// Boxed: one test awaiting this many statements inline overflows a debug build's stack.
Box::pin(db.execute_in_console(TARGET, sql, 0, 10, &cancel, Some(schema), Some(console))).await
}
async fn run(db: &DbManager, console: ConsoleId<'_>, sql: &str) -> IdeResult<QueryResult> {
run_in(db, console, sql, "public").await
}
async fn value(db: &DbManager, console: ConsoleId<'_>, sql: &str) -> IdeResult<String> {
Ok(run(db, console, sql).await?.rows[0][0].clone().unwrap())
}
#[tokio::test]
#[ignore = "requires a disposable local PostgreSQL fixture with OPENIDEA_PG_CONSOLE_PORT and console_fixture db/user"]
async fn console_sessions_keep_transactions_settings_and_temporary_tables() -> IdeResult<()> {
let dir = tempfile::tempdir()?;
let root = dir.path();
let ssh = Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
let db = DbManager::new(root.into(), root.join("passwords.json"), root.join("history.json"), ssh);
db.save_sources(vec![DataSource {
id: TARGET.into(),
name: "Local PostgreSQL".into(),
driver: DbDriver::Postgres,
host: "127.0.0.1".into(),
port: Some(std::env::var("OPENIDEA_PG_CONSOLE_PORT").expect("disposable fixture port").parse().unwrap()),
user: "console_fixture".into(),
database: "console_fixture".into(),
..Default::default()
}])
.await?;
let cancel = CancellationToken::new();
for sql in [
"DROP TABLE IF EXISTS public.console_session",
"CREATE TABLE public.console_session (id int PRIMARY KEY)",
"CREATE SCHEMA IF NOT EXISTS console_other",
] {
db.execute(TARGET, sql, 0, &cancel).await?;
}
let observer = db.pool(TARGET).await?;
run(&db, A, "BEGIN").await?;
run(&db, A, "INSERT INTO console_session VALUES (1)").await?;
let pid = value(&db, A, "SELECT pg_backend_pid()").await?;
assert!(run(&db, B, ROWS).await?.rows.is_empty());
assert!(observer.rows(ROWS, 10).await?.is_empty());
run(&db, A, "ROLLBACK").await?;
assert!(run(&db, A, ROWS).await?.rows.is_empty());
assert_eq!(value(&db, A, "SELECT pg_backend_pid()").await?, pid);
run(&db, A, "SET work_mem = '77MB'").await?;
run(&db, A, "CREATE TEMP TABLE work AS SELECT 7 AS n").await?;
assert_eq!(value(&db, A, "SHOW work_mem").await?, "77MB");
assert_eq!(value(&db, A, "SELECT n FROM work").await?, "7");
assert!(run(&db, B, "SELECT n FROM work").await.is_err());
assert_ne!(value(&db, B, "SHOW work_mem").await?, "77MB");
// The picker's schema is applied when it changes and leaves the user's own SET alone otherwise.
run(&db, A, "SET search_path TO console_other").await?;
assert_eq!(value(&db, A, "SELECT current_schema()").await?, "console_other");
run(&db, A, "BEGIN").await?;
assert_eq!(run_in(&db, A, "SELECT current_schema()", "pg_catalog").await?.rows, [[Some("pg_catalog".into())]]);
assert!(run_in(&db, A, "SELECT 1/0", "pg_catalog").await.is_err());
run(&db, A, "ROLLBACK").await?;
assert_eq!(value(&db, A, "SELECT current_schema()").await?, "public");
assert_eq!(value(&db, A, "SELECT pg_backend_pid()").await?, pid, "errors keep the session");
// Every session slot taken, both manual slots and a result cursor leave ordinary work running.
let paths: Vec<_> = (0..4).map(|n| format!("{n}.sql")).collect();
for path in &paths[..3] {
run(&db, ConsoleId::new("main", path), "SET work_mem = '5MB'").await?;
}
let full = run(&db, ConsoleId::new("main", &paths[3]), "BEGIN").await.unwrap_err();
assert_eq!(full.kind, ErrorKind::Unavailable);
for path in ["m.sql", "n.sql"] {
let console = ConsoleId::new("main", path);
db.set_postgres_console_manual(TARGET, console, true).await?;
run(&db, console, ROWS).await?;
}
let page = db
.execute_in_console(TARGET, "SELECT generate_series(1, 1000)", 10, 10, &cancel, Some("public"), Some(B))
.await?;
assert!(page.has_more);
tokio::time::timeout(Duration::from_secs(5), db.completion(TARGET)).await.expect("completion does not wait")?;
assert_eq!(value(&db, A, "SELECT n FROM work").await?, "7");
for path in paths[..3].iter().map(String::as_str).chain(["m.sql", "n.sql"]) {
db.release_console(ConsoleId::new("main", path)).await?;
}
// A session that ends inside a transaction is reported before anything else commits on its own.
run(&db, A, "BEGIN").await?;
run(&db, A, "INSERT INTO console_session VALUES (2)").await?;
observer.rows(&format!("SELECT pg_terminate_backend({pid})"), 1).await?;
assert!(run(&db, A, "INSERT INTO console_session VALUES (3)").await.is_err());
assert_eq!(run(&db, A, "INSERT INTO console_session VALUES (3)").await.unwrap_err().kind, ErrorKind::OutOfSync);
assert!(run(&db, A, ROWS).await?.rows.is_empty());
run(&db, A, "BEGIN").await?;
run(&db, A, "INSERT INTO console_session VALUES (4)").await?;
let stop = CancellationToken::new();
let (stopped, ()) = tokio::join!(
db.execute_in_console(TARGET, "SELECT pg_sleep(8)", 0, 10, &stop, Some("public"), Some(A)),
async {
tokio::time::sleep(Duration::from_millis(300)).await;
stop.cancel();
}
);
assert_eq!(stopped.unwrap_err().kind, ErrorKind::Cancelled);
assert_eq!(run(&db, A, "SELECT 1").await.unwrap_err().kind, ErrorKind::OutOfSync);
assert!(observer.rows(ROWS, 10).await?.is_empty());
run(&db, A, "BEGIN").await?;
run(&db, A, "INSERT INTO console_session VALUES (5)").await?;
db.release_console(A).await?;
run(&db, A, "BEGIN").await?;
run(&db, A, "INSERT INTO console_session VALUES (5)").await?;
assert!(db.set_postgres_console_manual(TARGET, A, true).await?);
assert!(run(&db, A, ROWS).await?.rows.is_empty(), "manual mode starts its own transaction");
db.release_console(A).await?;
db.execute(TARGET, "BEGIN", 0, &cancel).await?;
db.execute_from(TARGET, "START TRANSACTION", 0, 0, &cancel, Some("public")).await?;
let open = "SELECT count(*) FROM pg_stat_activity WHERE state LIKE 'idle in transaction%'";
assert_eq!(observer.rows(open, 1).await?, [[Some("0".into())]]);
run(&db, A, "BEGIN").await?;
tokio::time::timeout(Duration::from_secs(5), db.disconnect(TARGET)).await.expect("disconnects");
let observer = db.pool(TARGET).await?;
assert_eq!(observer.rows(open, 1).await?, [[Some("0".into())]]);
Ok(())
}
+186
Переглянути файл
@@ -0,0 +1,186 @@
//! What a SQL console in auto-commit mode keeps between its statements.
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use ide_db::{CellValue, ConsoleId, DataSource, DbDriver, DbManager, DbRowEdit, QueryResult};
use std::time::Duration;
const A: ConsoleId<'static> = ConsoleId::new("main", "a.sql");
const B: ConsoleId<'static> = ConsoleId::new("main", "b.sql");
const COUNT: &str = "SELECT count(*) FROM t";
async fn setup() -> (tempfile::TempDir, DbManager) {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().to_path_buf();
std::fs::File::create(root.join("app.db")).unwrap();
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
let db = DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
db.save_sources(vec![DataSource {
id: "s1".into(),
name: "app".into(),
driver: DbDriver::Sqlite,
file: Some("app.db".into()),
..Default::default()
}])
.await
.unwrap();
for sql in ["CREATE TABLE t (id INTEGER PRIMARY KEY)", "INSERT INTO t VALUES (1), (2), (3)"] {
db.execute("s1", sql, 0, &CancellationToken::new()).await.unwrap();
}
(tmp, db)
}
async fn run(db: &DbManager, console: ConsoleId<'_>, sql: &str) -> IdeResult<QueryResult> {
db.execute_in_console("s1", sql, 0, 10, &CancellationToken::new(), None, Some(console)).await
}
async fn run_all(db: &DbManager, console: ConsoleId<'_>, script: &[&str]) -> IdeResult<()> {
for sql in script {
run(db, console, sql).await.map_err(|e| IdeError::invalid(format!("{sql}: {}", e.message)))?;
}
Ok(())
}
async fn count(db: &DbManager, console: Option<ConsoleId<'_>>) -> IdeResult<String> {
let token = CancellationToken::new();
let result = db.execute_in_console("s1", COUNT, 0, 10, &token, None, console).await?;
Ok(result.rows[0][0].clone().unwrap())
}
async fn insert_in_table_editor(db: &DbManager, id: &str) -> IdeResult<u64> {
let values = vec![CellValue { column: "id".into(), value: Some(id.into()) }];
db.apply_edits("s1", "main", "t", &[DbRowEdit::Insert { values }]).await
}
#[tokio::test]
async fn rollback_undoes_the_statements_since_begin() -> IdeResult<()> {
let (_tmp, db) = setup().await;
run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?;
assert_eq!(count(&db, Some(A)).await?, "0");
assert_eq!(count(&db, Some(B)).await?, "3", "another console reads committed rows");
assert_eq!(count(&db, None).await?, "3", "so does a statement outside any console");
run(&db, A, "ROLLBACK").await?;
assert_eq!(count(&db, Some(A)).await?, "3");
run_all(&db, A, &["-- comment first\nBEGIN IMMEDIATE", "DELETE FROM t WHERE id = 1", "COMMIT"]).await?;
assert_eq!(count(&db, Some(B)).await?, "2");
Ok(())
}
#[tokio::test]
async fn temporary_tables_and_settings_belong_to_their_console() -> IdeResult<()> {
let (_tmp, db) = setup().await;
run_all(&db, A, &["CREATE TEMP TABLE work (id INTEGER)", "PRAGMA cache_size = 123"]).await?;
run_all(&db, A, &["INSERT INTO work SELECT id FROM t"; 3]).await?;
assert_eq!(run(&db, A, "SELECT count(*) FROM work").await?.rows, [[Some("9".into())]]);
assert_eq!(run(&db, A, "PRAGMA cache_size").await?.rows, [[Some("123".into())]]);
assert!(run(&db, B, "SELECT count(*) FROM work").await.is_err());
assert_ne!(run(&db, B, "PRAGMA cache_size").await?.rows, [[Some("123".into())]]);
let outside = db.execute("s1", "SELECT count(*) FROM work", 10, &CancellationToken::new()).await;
assert!(outside.is_err());
// A later page of the console's own result reads the same session.
let page = db
.execute_in_console("s1", "SELECT id FROM work ORDER BY id", 3, 3, &CancellationToken::new(), None, Some(A))
.await?;
assert_eq!(page.rows, vec![vec![Some("2".to_owned())]; 3]);
Ok(())
}
#[tokio::test]
async fn closing_a_console_rolls_back_and_frees_the_file() -> IdeResult<()> {
let (_tmp, db) = setup().await;
run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?;
db.release_target_console(A, Some("other")).await?;
assert_eq!(count(&db, Some(A)).await?, "0", "another target's release leaves this session alone");
db.release_console(A).await?;
assert_eq!(count(&db, None).await?, "3");
assert_eq!(insert_in_table_editor(&db, "4").await?, 1);
assert_eq!(count(&db, Some(A)).await?, "4");
Ok(())
}
#[tokio::test]
async fn disconnecting_rolls_back_an_open_transaction() -> IdeResult<()> {
let (_tmp, db) = setup().await;
run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?;
tokio::time::timeout(Duration::from_secs(5), db.disconnect("s1")).await.expect("the pool closes");
assert_eq!(count(&db, Some(A)).await?, "3");
Ok(())
}
#[tokio::test]
async fn manual_mode_ends_the_console_sessions_of_its_data_source() -> IdeResult<()> {
let (_tmp, db) = setup().await;
run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?;
db.set_manual_commit("s1", true).await?;
assert_eq!(count(&db, Some(A)).await?, "3");
run(&db, B, "INSERT INTO t VALUES (4)").await?;
db.finish_transaction("s1", true).await?;
db.set_manual_commit("s1", false).await?;
assert_eq!(count(&db, Some(A)).await?, "4");
Ok(())
}
#[tokio::test]
async fn a_session_without_a_transaction_leaves_the_table_editor_free() -> IdeResult<()> {
let (_tmp, db) = setup().await;
run_all(&db, A, &["CREATE TEMP TABLE work (id INTEGER)", "BEGIN", "INSERT INTO t VALUES (4)", "COMMIT"]).await?;
let token = CancellationToken::new();
// The rows after the first stay unread on the session's connection.
assert!(db.execute_in_console("s1", "SELECT id FROM t", 0, 1, &token, None, Some(A)).await?.has_more);
let saved = tokio::time::timeout(Duration::from_secs(2), insert_in_table_editor(&db, "5"));
assert_eq!(saved.await.expect("the table editor does not wait for the console")?, 1);
assert_eq!(count(&db, Some(A)).await?, "5");
Ok(())
}
#[tokio::test]
async fn cancelling_rolls_back_and_the_next_statement_says_so() -> IdeResult<()> {
let (_tmp, db) = setup().await;
run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?;
let slow = "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 3000000) SELECT sum(i) FROM n";
let token = CancellationToken::new();
let (stopped, ()) = tokio::join!(db.execute_in_console("s1", slow, 0, 10, &token, None, Some(A)), async {
tokio::time::sleep(Duration::from_millis(50)).await;
token.cancel();
});
assert_eq!(stopped.unwrap_err().kind, ErrorKind::Cancelled);
let refused = run(&db, A, "DELETE FROM t WHERE id = 1").await.unwrap_err();
assert_eq!(refused.kind, ErrorKind::OutOfSync, "it would commit outside the transaction: {}", refused.message);
assert_eq!(count(&db, Some(A)).await?, "3");
run_all(&db, A, &["BEGIN", "DELETE FROM t", "ROLLBACK"]).await?;
assert_eq!(count(&db, None).await?, "3");
Ok(())
}
#[tokio::test]
async fn sessions_are_bounded_and_leave_ordinary_statements_their_connections() -> IdeResult<()> {
let (_tmp, db) = setup().await;
let paths: Vec<_> = (0..5).map(|n| format!("{n}.sql")).collect();
let consoles: Vec<_> = paths.iter().map(|path| ConsoleId::new("main", path)).collect();
for console in &consoles[..4] {
run(&db, *console, "PRAGMA cache_size = 99").await?;
}
let refused = run(&db, consoles[4], "BEGIN").await.unwrap_err();
assert_eq!(refused.kind, ErrorKind::Unavailable, "{}", refused.message);
assert_eq!(count(&db, Some(consoles[4])).await?, "3", "a plain query needs no session");
run(&db, consoles[4], "INSERT INTO t VALUES (4)").await?;
db.completion("s1").await?;
assert_eq!(insert_in_table_editor(&db, "5").await?, 1);
db.release_console(consoles[0]).await?;
run_all(&db, consoles[4], &["BEGIN", "DELETE FROM t", "ROLLBACK"]).await?;
assert_eq!(count(&db, None).await?, "5");
Ok(())
}
#[tokio::test]
async fn a_transaction_opened_outside_a_console_never_reaches_another_statement() -> IdeResult<()> {
let (_tmp, db) = setup().await;
let token = CancellationToken::new();
db.execute("s1", "BEGIN", 0, &token).await?;
db.execute("s1", "BEGIN; DELETE FROM t", 0, &token).await?;
assert_eq!(count(&db, None).await?, "3");
assert_eq!(insert_in_table_editor(&db, "4").await?, 1);
db.execute("s1", "BEGIN; DELETE FROM t WHERE id = 1; COMMIT", 0, &token).await?;
assert_eq!(count(&db, None).await?, "3");
Ok(())
}
+17 -2
Переглянути файл
@@ -7,8 +7,8 @@
use crate::{
COMPOSE_DIR, COMPOSE_FILES, COMPOSE_PROJECT, COMPOSE_SERVICE, ContainerOp, DockerAvailability, DockerContainer,
DockerEndpoint, DockerImage, DockerImageLayer, DockerLogLine, DockerNetwork, DockerObject, DockerProcessList,
DockerSnapshot, DockerVolume, split_csv,
DockerEndpoint, DockerHostResources, DockerImage, DockerImageLayer, DockerLogLine, DockerNetwork, DockerObject,
DockerProcessList, DockerSnapshot, DockerVolume, parse_info, split_csv,
};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::Deserialize;
@@ -356,6 +356,21 @@ fn server_version(addr: &Address, timeout: Duration) -> IdeResult<String> {
.map_err(|e| IdeError::internal(format!("the Docker daemon version is not JSON: {e}")))
}
/// CPU and memory capacity of `ep`'s Docker daemon / VM (`GET /info`).
pub(crate) fn info(ep: &DockerEndpoint, timeout: Duration) -> Option<IdeResult<DockerHostResources>> {
let addr = address(ep)?;
Some((|| {
let body = check(request(&addr, "GET", "/info", timeout)?)?;
parse_info(&body).ok_or_else(|| IdeError::internal("the Docker daemon info is not JSON"))
})())
}
/// Containers of `ep`'s daemon (`GET /containers/json?all=1`).
pub(crate) fn containers(ep: &DockerEndpoint, timeout: Duration) -> Option<IdeResult<Vec<DockerContainer>>> {
let addr = address(ep)?;
Some(list_containers(&addr, timeout))
}
/// Everything the Services tree shows, fetched straight from the Engine API.
pub(crate) fn snapshot(ep: &DockerEndpoint, timeout: Duration) -> Option<DockerSnapshot> {
let addr = address(ep)?;
+54
Переглянути файл
@@ -193,6 +193,25 @@ pub fn snapshot(ep: &DockerEndpoint) -> DockerSnapshot {
snap
}
/// The containers (running or not) that carry every label in `labels`, each `key=value` (or
/// just `key`): `docker ps --all --filter label=…`.
pub fn containers(ep: &DockerEndpoint, labels: &[String]) -> IdeResult<Vec<DockerContainer>> {
if docker_executable().is_none()
&& let Some(listed) = engine::containers(ep, QUICK)
{
let has = |c: &DockerContainer, label: &String| match label.split_once('=') {
Some((key, value)) => c.labels.get(key).is_some_and(|v| v == value),
None => c.labels.contains_key(label),
};
return listed.map(|all| all.into_iter().filter(|c| labels.iter().all(|l| has(c, l))).collect());
}
let filters: Vec<String> = labels.iter().flat_map(|l| ["--filter".to_owned(), format!("label={l}")]).collect();
let mut args: Vec<&str> = vec!["ps", "--all", "--no-trunc"];
args.extend(filters.iter().map(String::as_str));
args.extend(["--format", PS_FORMAT]);
run(ep, &args, QUICK).map(|text| parse_containers(&text))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum ContainerOp {
@@ -324,6 +343,41 @@ pub fn container_stats(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerContain
parse_container_stats(&out).ok_or_else(|| IdeError::not_found("no container stats returned"))
}
/// CPU and memory capacity of the Docker daemon / VM (`docker info`).
pub fn host_resources(ep: &DockerEndpoint) -> IdeResult<DockerHostResources> {
if docker_executable().is_none()
&& let Some(res) = engine::info(ep, QUICK)
{
return res;
}
let out = run(ep, &["info", "--format", INFO_FORMAT], QUICK)?;
parse_info(&out).ok_or_else(|| IdeError::internal("docker info did not return JSON"))
}
/// Resource limits (`HostConfig`), OOM state (`State`) and labels of container `id`.
pub fn container_resource_inspect(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerContainerResourceInspect> {
let id = check_id(id)?;
let out = inspect(ep, DockerObject::Container, id)?;
parse_container_resource_inspect(&out).ok_or_else(|| IdeError::internal("docker inspect did not return JSON"))
}
/// Finds the dev container matching local `folder` (and optional `config_path`).
pub fn find_devcontainer(
ep: &DockerEndpoint,
folder: &Path,
config_path: Option<&Path>,
) -> IdeResult<Option<DockerContainer>> {
let containers = if docker_executable().is_none()
&& let Some(list) = engine::containers(ep, QUICK)
{
list?
} else {
let out = run(ep, &["ps", "--all", "--no-trunc", "--format", PS_FORMAT], QUICK)?;
parse_containers(&out)
};
Ok(find_devcontainer_in(&containers, folder, config_path))
}
/// Per-volume disk usage (`docker system df -v --format '{{json .Volumes}}'`).
pub fn volume_sizes(ep: &DockerEndpoint) -> IdeResult<std::collections::BTreeMap<String, String>> {
if docker_executable().is_none()
+277
Переглянути файл
@@ -145,6 +145,50 @@ pub struct DockerContainerStats {
pub pids: String,
}
/// CPU and memory capacity of the Docker daemon / VM (`docker info`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DockerHostResources {
pub cpus: Option<u32>,
pub memory_bytes: Option<u64>,
pub operating_system: Option<String>,
}
/// Effective cgroup resource limits on a Docker container (`HostConfig`).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DockerContainerLimits {
/// CPU core limit (`NanoCpus / 1e9`, else `CpuQuota / CpuPeriod`), `None` if unlimited.
pub cpus: Option<f64>,
/// Memory limit in bytes (`HostConfig.Memory`), `None` if unlimited (`0`).
pub memory_bytes: Option<u64>,
/// Memory + swap limit in bytes (`HostConfig.MemorySwap`, if > 0).
pub memory_swap_bytes: Option<u64>,
}
/// Exit / OOM state of a Docker container (`State`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DockerContainerOomState {
/// A stopped container whose `State.OOMKilled` flag is set.
pub oom_killed: bool,
/// Raw `State.OOMKilled` flag reported by Docker.
pub oom_killed_flag: bool,
pub exit_code: Option<i64>,
pub running: bool,
pub status: String,
pub finished_at: Option<String>,
}
/// Limits, OOM state and labels extracted from `docker inspect <container>`.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DockerContainerResourceInspect {
pub limits: DockerContainerLimits,
pub oom: DockerContainerOomState,
pub labels: BTreeMap<String, String>,
}
/// Everything the Services tree shows, fetched in one go.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -473,6 +517,163 @@ pub fn parse_container_stats(text: &str) -> Option<DockerContainerStats> {
})
}
/// `docker info --format` template for daemon / VM CPU and memory capacity.
pub const INFO_FORMAT: &str =
r#"{"NCPU":{{json .NCPU}},"MemTotal":{{json .MemTotal}},"OperatingSystem":{{json .OperatingSystem}}}"#;
#[derive(Deserialize, Default)]
#[serde(default)]
struct RawInfo {
#[serde(rename = "NCPU")]
ncpu: Option<u32>,
#[serde(rename = "MemTotal")]
mem_total: Option<u64>,
#[serde(rename = "OperatingSystem")]
operating_system: Option<String>,
}
/// Parses `docker info --format` [`INFO_FORMAT`] or Engine API `GET /info` JSON.
pub fn parse_info(text: &str) -> Option<DockerHostResources> {
let raw: RawInfo = text
.lines()
.find(|l| l.trim_start().starts_with('{'))
.and_then(|l| serde_json::from_str(l).ok())
.or_else(|| serde_json::from_str(text).ok())?;
Some(DockerHostResources {
cpus: raw.ncpu.filter(|&n| n > 0),
memory_bytes: raw.mem_total.filter(|&m| m > 0),
operating_system: raw.operating_system.map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()),
})
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct RawInspect {
host_config: RawInspectHostConfig,
state: RawInspectState,
config: RawInspectConfig,
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct RawInspectHostConfig {
nano_cpus: i64,
cpu_quota: i64,
cpu_period: i64,
memory: i64,
memory_swap: i64,
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct RawInspectState {
status: String,
running: bool,
#[serde(rename = "OOMKilled")]
oom_killed: bool,
exit_code: Option<i64>,
finished_at: String,
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct RawInspectConfig {
labels: Option<BTreeMap<String, String>>,
}
/// Parses resource limits (`HostConfig`), OOM/exit status (`State`) and labels from `docker inspect` JSON
/// (either a single container object or a 1-element array).
pub fn parse_container_resource_inspect(text: &str) -> Option<DockerContainerResourceInspect> {
let value: serde_json::Value = serde_json::from_str(text).ok()?;
let obj = match value {
serde_json::Value::Array(mut items) => items.drain(..).next()?,
other => other,
};
let raw: RawInspect = serde_json::from_value(obj).ok()?;
let cpus = if raw.host_config.nano_cpus > 0 {
Some(raw.host_config.nano_cpus as f64 / 1_000_000_000.0)
} else if raw.host_config.cpu_quota > 0 {
let period = if raw.host_config.cpu_period > 0 { raw.host_config.cpu_period } else { 100_000 };
Some(raw.host_config.cpu_quota as f64 / period as f64)
} else {
None
};
let memory_bytes = (raw.host_config.memory > 0).then_some(raw.host_config.memory as u64);
let memory_swap_bytes = (raw.host_config.memory_swap > 0).then_some(raw.host_config.memory_swap as u64);
let oom_killed_flag = raw.state.oom_killed;
let oom_killed = !raw.state.running && oom_killed_flag;
let finished_at = (!raw.state.finished_at.is_empty() && !raw.state.finished_at.starts_with("0001-01-01"))
.then_some(raw.state.finished_at);
Some(DockerContainerResourceInspect {
limits: DockerContainerLimits { cpus, memory_bytes, memory_swap_bytes },
oom: DockerContainerOomState {
oom_killed,
oom_killed_flag,
exit_code: raw.state.exit_code,
running: raw.state.running,
status: raw.state.status,
finished_at,
},
labels: raw.config.labels.unwrap_or_default(),
})
}
fn normalize_label_path(path: &str) -> String {
let normalized = path.trim().replace('\\', "/");
let trimmed = normalized.trim_end_matches('/');
if trimmed.is_empty() && normalized.starts_with('/') { "/".to_owned() } else { trimmed.to_owned() }
}
/// Finds the dev container matching `folder` (and optional `config_path`) among `containers`,
/// preferring running containers and exact config file matches.
pub fn find_devcontainer_in(
containers: &[DockerContainer],
folder: &std::path::Path,
config_path: Option<&std::path::Path>,
) -> Option<DockerContainer> {
let want_folder = normalize_label_path(&folder.to_string_lossy());
let want_canon = std::fs::canonicalize(folder).ok().map(|p| normalize_label_path(&p.to_string_lossy()));
let want_cfg = config_path.map(|p| normalize_label_path(&p.to_string_lossy()));
let want_cfg_canon =
config_path.and_then(|p| std::fs::canonicalize(p).ok()).map(|p| normalize_label_path(&p.to_string_lossy()));
let mut matches: Vec<(u8, &DockerContainer)> = containers
.iter()
.filter_map(|c| {
let label_folder = c
.labels
.get("devcontainer.local_folder")
.or_else(|| c.labels.get("vsch.local.folder"))
.map(|s| normalize_label_path(s))?;
let folder_match = label_folder == want_folder
|| want_canon.as_deref() == Some(label_folder.as_str())
|| std::fs::canonicalize(&label_folder)
.ok()
.map(|p| normalize_label_path(&p.to_string_lossy()))
.is_some_and(|p| p == want_folder || want_canon.as_deref() == Some(p.as_str()));
if !folder_match {
return None;
}
let cfg_score: u8 = match (&want_cfg, c.labels.get("devcontainer.config_file")) {
(Some(want), Some(actual)) => {
let norm = normalize_label_path(actual);
if norm == *want || want_cfg_canon.as_deref() == Some(norm.as_str()) {
2
} else {
return None;
}
}
(Some(_), None) => 1,
(None, _) => 1,
};
let run_score: u8 = if c.running() { 4 } else { 0 };
Some((run_score + cfg_score, c))
})
.collect();
matches.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.name.cmp(&b.1.name)));
matches.into_iter().next().map(|(_, c)| c.clone())
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct RawVolumeUsage {
@@ -660,4 +861,80 @@ mod tests {
assert_eq!(parse_event(daemon), None);
assert_eq!(parse_event("not json"), None);
}
#[test]
fn parses_docker_info_and_container_resource_inspect() {
let info = parse_info(r#"{"NCPU":6,"MemTotal":8589934592,"OperatingSystem":"OrbStack"}"#).unwrap();
assert_eq!(
info,
DockerHostResources {
cpus: Some(6),
memory_bytes: Some(8 * 1024 * 1024 * 1024),
operating_system: Some("OrbStack".into()),
}
);
let inspect_nano = r#"[{
"HostConfig": { "NanoCpus": 2500000000, "Memory": 4294967296, "MemorySwap": 8589934592 },
"State": { "Status": "exited", "Running": false, "OOMKilled": true, "ExitCode": 137, "FinishedAt": "2026-12-02T10:00:00Z" },
"Config": { "Labels": { "devcontainer.local_folder": "/work/app" } }
}]"#;
let parsed = parse_container_resource_inspect(inspect_nano).unwrap();
assert_eq!(parsed.limits.cpus, Some(2.5));
assert_eq!(parsed.limits.memory_bytes, Some(4 * 1024 * 1024 * 1024));
assert_eq!(parsed.limits.memory_swap_bytes, Some(8 * 1024 * 1024 * 1024));
assert!(parsed.oom.oom_killed);
assert!(parsed.oom.oom_killed_flag);
assert_eq!(parsed.oom.exit_code, Some(137));
// CpuQuota/CpuPeriod fallback. A SIGKILL alone does not identify an OOM exit.
let inspect_quota = r#"{
"HostConfig": { "NanoCpus": 0, "CpuQuota": 150000, "CpuPeriod": 100000, "Memory": 0, "MemorySwap": -1 },
"State": { "Status": "exited", "Running": false, "OOMKilled": false, "ExitCode": 137, "FinishedAt": "0001-01-01T00:00:00Z" },
"Config": {}
}"#;
let parsed_quota = parse_container_resource_inspect(inspect_quota).unwrap();
assert_eq!(parsed_quota.limits.cpus, Some(1.5));
assert_eq!(parsed_quota.limits.memory_bytes, None);
assert_eq!(parsed_quota.limits.memory_swap_bytes, None);
assert!(!parsed_quota.oom.oom_killed);
assert!(!parsed_quota.oom.oom_killed_flag);
assert_eq!(parsed_quota.oom.finished_at, None);
}
#[test]
fn finds_matching_devcontainer_preferring_running() {
let make = |id: &str, state: &str, folder: &str, cfg: &str| DockerContainer {
id: id.into(),
name: id.into(),
image: "debian".into(),
command: "sleep".into(),
state: state.into(),
status: state.into(),
ports: String::new(),
created_at: String::new(),
compose_project: None,
compose_service: None,
compose_working_dir: None,
compose_files: Vec::new(),
mounts: Vec::new(),
networks: Vec::new(),
labels: BTreeMap::from([
("devcontainer.local_folder".into(), folder.into()),
("devcontainer.config_file".into(), cfg.into()),
]),
};
let list = vec![
make("stopped-c", "exited", "/work/app", "/work/app/.devcontainer/devcontainer.json"),
make("running-c", "running", "/work/app", "/work/app/.devcontainer/devcontainer.json"),
make("other-c", "running", "/work/other", "/work/other/.devcontainer/devcontainer.json"),
];
let found = find_devcontainer_in(
&list,
std::path::Path::new("/work/app"),
Some(std::path::Path::new("/work/app/.devcontainer/devcontainer.json")),
)
.unwrap();
assert_eq!(found.id, "running-c");
}
}
+1 -1
Переглянути файл
@@ -8,7 +8,7 @@ license.workspace = true
[dependencies]
[target.'cfg(target_os = "linux")'.dependencies]
gtk = "0.18"
gtk = "0.19"
[target.'cfg(any(windows, target_os = "macos"))'.dependencies]
raw-window-handle = "0.6"
+5 -1
Переглянути файл
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
pub const MANIFEST_FILE: &str = "plugin.toml";
/// The plugin API (engine) version this host implements.
pub const ENGINE_VERSION: &str = "1.20.0";
pub const ENGINE_VERSION: &str = "1.21.0";
/// The longest `[capabilities.reasons]` entry, in characters: a sentence or two.
pub const MAX_CAPABILITY_REASON: usize = 500;
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
@@ -168,6 +168,7 @@ impl ActivationEvent {
pub const EVENT_KINDS: &[&str] = &[
"document-changed",
"websocket-ready",
"run-started",
"run-exited",
"terminal-exited",
"content-tab-action",
@@ -475,6 +476,9 @@ impl Manifest {
{
self.needs_api(&format!("`{event}`"), 18)?;
}
if matches!(event, ActivationEvent::Event(kind) if kind == "run-started") {
self.needs_api(&format!("`{event}`"), 21)?;
}
if !seen.insert(event) {
return Err(format!("duplicate activation event {event}"));
}
+362 -44
Переглянути файл
@@ -301,11 +301,12 @@ impl AutomationService {
(self.now_ms() as u64) >= ready_at
}
/// Whether any scheduled (non-manual) automation or unpaused session schedule is enabled.
/// Whether any scheduled automation (including a `Manual` automation with a pending agent
/// override) or unpaused session schedule is enabled.
pub fn has_enabled_schedules(&self) -> bool {
self.reload_from_disk();
let state = self.state.lock();
let has_auto = state.automations.iter().any(|a| a.enabled && !matches!(a.trigger, AutomationTrigger::Manual));
let has_auto = state.automations.iter().any(is_actively_scheduled);
let has_sess = state.session_schedules.iter().any(|s| !s.paused);
has_auto || has_sess
}
@@ -318,6 +319,18 @@ impl AutomationService {
self.has_enabled_schedules() || self.has_running_runs()
}
/// Whether the local desktop host should stay alive in the background when editor windows close.
///
/// Independent of `auto_start_service` (the opt-in OS login service that runs `--scheduler`
/// after the desktop app quits). Covers both active schedules and in-flight runs (such as a
/// manual run or an already-fired one-shot run) so closing the last window does not abort them.
pub fn keeps_local_host_alive(&self, host: &Host) -> bool {
if !host.global_settings.effective().agents.automations.keep_alive_in_background {
return false;
}
self.has_enabled_schedules() || self.has_running_runs()
}
pub fn has_running_runs(&self) -> bool {
self.reconcile_abandoned_claims(None);
self.reload_from_disk();
@@ -392,6 +405,7 @@ impl AutomationService {
now: f64,
) -> bool {
let mut mutated = false;
let mut abandoned_auto_ids: Vec<String> = Vec::new();
for run in &mut state.runs {
if matches!(run.status, AutomationRunStatus::Running | AutomationRunStatus::NeedsInput)
&& !self.is_claim_owner_live(run.owner_instance_id.as_deref(), &run.id, in_flight_runs)
@@ -400,6 +414,12 @@ impl AutomationService {
run.finished_ms = Some(now);
run.error = Some("Interrupted: host exited before run finished".into());
run.unread = true;
abandoned_auto_ids.push(run.automation_id.clone());
mutated = true;
}
}
for auto_id in abandoned_auto_ids {
if finalize_exhausted_oneshot_locked(state, &auto_id, now) {
mutated = true;
}
}
@@ -466,8 +486,7 @@ impl AutomationService {
// Strict lock order: `self.state` -> `self.in_flight`.
let state = self.state.lock();
let in_flight = self.in_flight.lock();
let has_enabled =
state.automations.iter().any(|a| a.enabled && !matches!(a.trigger, AutomationTrigger::Manual));
let has_enabled = state.automations.iter().any(is_actively_scheduled);
let live_runs = state
.runs
.iter()
@@ -503,9 +522,7 @@ impl AutomationService {
self.reload_from_disk();
let boot_state = self.boot.status(host.home_dir().as_deref(), remote);
let state = self.state.lock();
let active_schedules =
state.automations.iter().filter(|a| a.enabled && !matches!(a.trigger, AutomationTrigger::Manual)).count()
as u32;
let active_schedules = state.automations.iter().filter(|a| is_actively_scheduled(a)).count() as u32;
let running_runs = state.runs.iter().filter(|r| r.status == AutomationRunStatus::Running).count() as u32;
let needs_input_runs = state.runs.iter().filter(|r| r.status == AutomationRunStatus::NeedsInput).count() as u32;
let unread_runs = state.runs.iter().filter(|r| r.unread).count() as u32;
@@ -598,7 +615,7 @@ impl AutomationService {
})
.cloned()
.collect();
out.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
out.sort_by(compare_automations_by_schedule);
out
}
@@ -660,23 +677,47 @@ impl AutomationService {
}
let now = self.now_ms();
let computed_next = if input.enabled {
let next = input.trigger.next_run_after(now)?;
if matches!(input.trigger, AutomationTrigger::OneShot { .. }) && next.is_none() {
return Err(IdeError::invalid("one-shot timestamp must be in the future when enabled"));
}
next
} else {
// Still validate syntax even when saved disabled.
let _ = input.trigger.next_run_after(now)?;
None
};
// Always validate trigger syntax even when disabled or when an agent override is preserved.
let regular_next = input.trigger.next_run_after(now)?;
let saved = self.with_mutated_state(|state| {
if let Some(existing_id) = input.id.as_deref() {
let has_active_run = state.runs.iter().any(|r| {
r.automation_id == existing_id
&& matches!(r.status, AutomationRunStatus::Running | AutomationRunStatus::NeedsInput)
});
let Some(existing) = state.automations.iter_mut().find(|a| a.id == existing_id) else {
return Err(IdeError::not_found(format!("unknown automation '{existing_id}'")));
};
let trigger_unchanged = existing.trigger == input.trigger;
let max_runs_reached = input.max_runs.is_some_and(|max| existing.run_count >= max);
let preserved_override = if input.enabled
&& input.allow_agent_schedule
&& !input.clear_override
&& trigger_unchanged
&& !max_runs_reached
{
existing
.next_run_override_ms
.filter(|&ms| ms > now && input.disable_after_ms.is_none_or(|exp| ms < exp))
} else {
None
};
let effective_next = if !input.enabled {
None
} else if let Some(ov) = preserved_override {
Some(ov)
} else {
if matches!(input.trigger, AutomationTrigger::OneShot { .. })
&& regular_next.is_none()
&& !(trigger_unchanged && input.allow_agent_schedule && has_active_run)
{
return Err(IdeError::invalid("one-shot timestamp must be in the future when enabled"));
}
regular_next
};
existing.name = name;
existing.enabled = input.enabled;
existing.paused_reason = None;
@@ -690,13 +731,25 @@ impl AutomationService {
existing.skill_overrides = input.skill_overrides;
existing.memory_overrides = input.memory_overrides;
existing.trigger = input.trigger;
existing.allow_agent_schedule = input.allow_agent_schedule;
existing.misfire_policy = input.misfire_policy;
existing.disable_after_ms = input.disable_after_ms;
existing.max_runs = input.max_runs;
existing.next_run_ms = computed_next;
if let Some(ov) = preserved_override {
existing.next_run_override_ms = Some(ov);
} else {
existing.next_run_override_ms = None;
existing.next_prompt_override = None;
}
existing.next_run_ms = effective_next;
existing.updated_ms = now;
Ok((existing.clone(), true))
} else {
if input.enabled && matches!(input.trigger, AutomationTrigger::OneShot { .. }) && regular_next.is_none()
{
return Err(IdeError::invalid("one-shot timestamp must be in the future when enabled"));
}
let computed_next = if input.enabled { regular_next } else { None };
let id = format!("auto_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
let out = AgentAutomation {
id,
@@ -713,10 +766,13 @@ impl AutomationService {
skill_overrides: input.skill_overrides,
memory_overrides: input.memory_overrides,
trigger: input.trigger,
allow_agent_schedule: input.allow_agent_schedule,
misfire_policy: input.misfire_policy,
disable_after_ms: input.disable_after_ms,
max_runs: input.max_runs,
next_run_ms: computed_next,
next_run_override_ms: None,
next_prompt_override: None,
paused_reason: None,
run_count: 0,
unread_runs: 0,
@@ -744,14 +800,23 @@ impl AutomationService {
check_workspace_trust(host, &auto.workspace).map_err(IdeError::invalid)?;
}
let next = if enabled {
let computed = auto.trigger.next_run_after(now)?;
if matches!(auto.trigger, AutomationTrigger::OneShot { .. }) && computed.is_none() {
return Err(IdeError::invalid(
"one-shot timestamp is in the past; update its schedule before enabling",
));
let valid_override = auto.next_run_override_ms.filter(|&ms| ms > now);
if let Some(ov) = valid_override {
Some(ov)
} else {
auto.next_run_override_ms = None;
auto.next_prompt_override = None;
let computed = auto.trigger.next_run_after(now)?;
if matches!(auto.trigger, AutomationTrigger::OneShot { .. }) && computed.is_none() {
return Err(IdeError::invalid(
"one-shot timestamp is in the past; update its schedule before enabling",
));
}
computed
}
computed
} else {
auto.next_run_override_ms = None;
auto.next_prompt_override = None;
None
};
auto.enabled = enabled;
@@ -794,6 +859,8 @@ impl AutomationService {
auto.enabled = false;
auto.paused_reason = None;
auto.next_run_ms = None;
auto.next_run_override_ms = None;
auto.next_prompt_override = None;
auto.updated_ms = now;
n += 1;
}
@@ -970,6 +1037,8 @@ impl AutomationService {
skill_overrides: Default::default(),
memory_overrides: None,
trigger: parsed.trigger,
allow_agent_schedule: parsed.allow_agent_schedule,
clear_override: false,
misfire_policy: None,
disable_after_ms: parsed.disable_after_ms,
max_runs: parsed.max_runs,
@@ -982,6 +1051,129 @@ impl AutomationService {
preview_trigger_runs(trigger, self.now_ms(), n)
}
/// Previews up to `max_count` upcoming firing timestamps for MCP callers without altering the
/// IPC command's `1..=10` clamp.
pub fn preview_schedule_capped(
&self,
trigger: &AutomationTrigger,
count: u32,
max_count: u32,
) -> IdeResult<Vec<f64>> {
let n = count.clamp(1, max_count) as usize;
preview_trigger_runs(trigger, self.now_ms(), n)
}
/// Resolves a live per-session MCP capability nonce across all in-memory [`AgentManager`]s of
/// `host` without touching disk or running claim reconciliation.
pub fn resolve_mcp_caller(&self, host: &Host, session_nonce: &str) -> Option<ide_agent::McpCallerSession> {
for p in host.projects() {
if let Some(caller) = p.agents.resolve_mcp_session_nonce(session_nonce) {
return Some(caller);
}
}
if let Some(caller) =
self.headless_agents.lock().values().find_map(|mgr| mgr.resolve_mcp_session_nonce(session_nonce))
{
return Some(caller);
}
if let Some(caller) =
self.chat_agents.lock().as_ref().and_then(|mgr| mgr.resolve_mcp_session_nonce(session_nonce))
{
return Some(caller);
}
None
}
/// Unattended self-rescheduling invoked by `schedule_next_run` ONLY while `caller` is actively
/// executing a scheduled turn of an [`AgentAutomation`] whose `allow_agent_schedule` is `true`.
///
/// Keeps the user's `trigger` and `prompt` untouched, storing a one-time override
/// (`next_run_override_ms` + `next_prompt_override`) consumed on the next firing. `done: true`
/// clears any pending override and lets the regular `trigger` continue, leaving `Manual`
/// automations idle.
pub(crate) fn schedule_next_run_from_agent(
&self,
host: &Arc<Host>,
caller: &ide_agent::McpCallerSession,
schedule: Option<SelfScheduleTime>,
next_prompt: Option<String>,
) -> IdeResult<AgentAutomation> {
const MIN_SELF_SCHEDULE_DELAY_MS: f64 = 60_000.0;
let Some(auto_id) = caller.active_automation_id.as_deref() else {
return Err(IdeError::invalid(
"schedule_next_run can only be called while an Agent Automation's scheduled run is actively executing; interactive turns cannot self-schedule",
));
};
let cleaned_prompt = next_prompt.map(|p| p.trim().to_owned()).filter(|p| !p.is_empty());
let updated = self.with_mutated_state(|state| {
let now = self.now_ms();
let Some(auto) = state.automations.iter_mut().find(|a| a.id == auto_id) else {
return Err(IdeError::not_found(format!("unknown automation '{auto_id}'")));
};
if !auto.allow_agent_schedule {
return Err(IdeError::invalid(format!(
"Automation '{}' does not allow unattended self-scheduling; enable 'Allow agent to schedule its next run' in the automation settings",
auto.name
)));
}
if !auto.enabled {
return Err(IdeError::invalid("The automation is disabled; enable it before scheduling another run"));
}
let Some(schedule) = schedule else {
auto.next_run_override_ms = None;
auto.next_prompt_override = None;
auto.next_run_ms = auto.trigger.next_run_after(now)?;
if matches!(auto.trigger, AutomationTrigger::OneShot { .. }) && auto.next_run_ms.is_none() {
auto.enabled = false;
}
auto.updated_ms = now;
return Ok((auto.clone(), true));
};
let target_ms = match schedule {
SelfScheduleTime::After(delay_ms) => now + delay_ms,
SelfScheduleTime::At(run_at_ms) => run_at_ms,
};
if !target_ms.is_finite() || target_ms < now + MIN_SELF_SCHEDULE_DELAY_MS {
return Err(IdeError::invalid("next run must be at least 60 seconds in the future"));
}
check_workspace_trust(host, &auto.workspace).map_err(IdeError::invalid)?;
if let Some(max) = auto.max_runs
&& auto.run_count >= max
{
return Err(IdeError::invalid(format!(
"Automation '{}' reached its maxRuns limit ({max}); further runs cannot be scheduled",
auto.name
)));
}
if let Some(exp) = auto.disable_after_ms
&& target_ms >= exp
{
return Err(IdeError::invalid(format!(
"Requested next run exceeds the disableAfter date of automation '{}'",
auto.name
)));
}
auto.next_run_override_ms = Some(target_ms);
auto.next_prompt_override = cleaned_prompt;
auto.next_run_ms = Some(target_ms);
auto.updated_ms = now;
Ok((auto.clone(), true))
})?;
self.sync_boot_service(host);
self.notify.notify_waiters();
self.broadcast_changed(host);
Ok(updated)
}
// -----------------------------------------------------------------------
// In-Session Schedules (`Send Later` and `/loop`)
// -----------------------------------------------------------------------
@@ -1163,6 +1355,8 @@ impl AutomationService {
if expired_date || expired_runs {
state.automations[idx].enabled = false;
state.automations[idx].next_run_ms = None;
state.automations[idx].next_run_override_ms = None;
state.automations[idx].next_prompt_override = None;
state.automations[idx].updated_ms = now;
mutated = true;
disabled_any = true;
@@ -1178,14 +1372,42 @@ impl AutomationService {
let late_ms = now - scheduled_for;
let is_misfire = late_ms >= misfire_threshold;
let policy = state.automations[idx].misfire_policy.unwrap_or(default_misfire);
let skip_misfire = is_misfire && policy == AutomationMisfirePolicy::Skip;
// Idempotency by stable occurrence_id + single active scheduled slot per automation.
let duplicate_occ =
state.runs.iter().any(|r| r.occurrence_id.as_deref() == Some(occurrence_id.as_str()));
let already_active = state.runs.iter().any(|r| {
r.automation_id == auto_id
&& matches!(r.status, AutomationRunStatus::Running | AutomationRunStatus::NeedsInput)
});
let will_launch = !skip_misfire && !duplicate_occ && !already_active;
// Advance schedule past `now` inside the same `state.lock` transaction as the claim.
// Consume any one-time agent override and advance the underlying regular schedule
// past `now` inside the same `state.lock` transaction as the claim.
let had_override = state.automations[idx].next_run_override_ms.take().is_some();
let override_prompt = state.automations[idx].next_prompt_override.take();
let allow_self_sched = state.automations[idx].allow_agent_schedule;
match &state.automations[idx].trigger {
AutomationTrigger::OneShot { run_at_ms } if *run_at_ms > now => {
state.automations[idx].next_run_ms = Some(*run_at_ms);
}
AutomationTrigger::OneShot { .. } if allow_self_sched && (will_launch || already_active) => {
// Keep self-scheduling OneShot enabled while its run executes so the agent
// can call `schedule_next_run`; `finish_run` disables it if no follow-up
// override is scheduled.
state.automations[idx].next_run_ms = None;
}
AutomationTrigger::OneShot { .. } => {
state.automations[idx].enabled = false;
state.automations[idx].next_run_ms = None;
disabled_any = true;
}
AutomationTrigger::Manual => {
state.automations[idx].next_run_ms = None;
if had_override {
disabled_any = true;
}
}
trigger => {
state.automations[idx].next_run_ms = trigger.next_run_after(now).ok().flatten();
}
@@ -1193,17 +1415,7 @@ impl AutomationService {
state.automations[idx].updated_ms = now;
mutated = true;
if is_misfire && policy == AutomationMisfirePolicy::Skip {
continue;
}
// Idempotency by stable occurrence_id + single active scheduled slot per automation.
let duplicate_occ =
state.runs.iter().any(|r| r.occurrence_id.as_deref() == Some(occurrence_id.as_str()));
let already_active = state.runs.iter().any(|r| {
r.automation_id == auto_id
&& matches!(r.status, AutomationRunStatus::Running | AutomationRunStatus::NeedsInput)
});
if duplicate_occ || already_active {
if !will_launch {
continue;
}
@@ -1212,6 +1424,7 @@ impl AutomationService {
idx,
AutomationRunOrigin::Scheduled { scheduled_for_ms: scheduled_for, catch_up: is_misfire },
occurrence_id,
override_prompt,
&self.owner.instance_id,
now,
&mut disabled_any,
@@ -1478,6 +1691,8 @@ impl AutomationService {
{
auto.enabled = false;
auto.next_run_ms = None;
auto.next_run_override_ms = None;
auto.next_prompt_override = None;
auto.paused_reason = Some(reason.to_owned());
auto.updated_ms = now;
mutated = true;
@@ -1498,8 +1713,7 @@ impl AutomationService {
let (has_enabled, has_live_claims) = {
let state = self.state.lock();
let in_flight = self.in_flight.lock();
let has_enabled =
state.automations.iter().any(|a| a.enabled && !matches!(a.trigger, AutomationTrigger::Manual));
let has_enabled = state.automations.iter().any(is_actively_scheduled);
let live_runs = state
.runs
.iter()
@@ -1552,12 +1766,29 @@ impl AutomationService {
}
let occ_id = format!("manual:{automation_id}:{}", uuid::Uuid::new_v4().simple());
let had_override = state.automations[auto_idx].next_run_override_ms.take().is_some();
let override_prompt = state.automations[auto_idx].next_prompt_override.take();
if had_override && state.automations[auto_idx].enabled {
let regular_next = state.automations[auto_idx].trigger.next_run_after(now).ok().flatten();
match &state.automations[auto_idx].trigger {
AutomationTrigger::OneShot { .. } if regular_next.is_none() => {
if !state.automations[auto_idx].allow_agent_schedule {
state.automations[auto_idx].enabled = false;
}
state.automations[auto_idx].next_run_ms = None;
}
_ => {
state.automations[auto_idx].next_run_ms = regular_next;
}
}
}
let mut disabled_max = false;
let work = allocate_claimed_run_locked(
state,
auto_idx,
AutomationRunOrigin::Manual,
occ_id,
override_prompt,
&self.owner.instance_id,
now,
&mut disabled_max,
@@ -1600,6 +1831,8 @@ impl AutomationService {
{
stored.enabled = false;
stored.next_run_ms = None;
stored.next_run_override_ms = None;
stored.next_prompt_override = None;
stored.paused_reason = Some(reason.clone());
stored.updated_ms = now;
return Ok(((), true));
@@ -1752,7 +1985,11 @@ impl AutomationService {
AutomationWorkspace::ChatOnly => (Isolation::Local, None, None),
};
let title = format!("{} (#{run_number})", auto.name);
let title = if auto.continuity == AutomationContinuity::SameTask {
auto.name.clone()
} else {
format!("{} (#{run_number})", auto.name)
};
let created = agents
.create_automated(
NewAgentTask {
@@ -2122,7 +2359,10 @@ impl AutomationService {
run.branch = branch;
}
run.worktree_cleaned = worktree_cleaned;
Ok((run.clone(), true))
let finished = run.clone();
let auto_id = finished.automation_id.clone();
let _ = finalize_exhausted_oneshot_locked(state, &auto_id, now);
Ok((finished, true))
})?;
self.sync_boot_service(host);
self.broadcast_changed(host);
@@ -2155,6 +2395,8 @@ impl AutomationService {
run.branch = branch;
}
run.worktree_cleaned = worktree_cleaned;
let auto_id = run.automation_id.clone();
let _ = finalize_exhausted_oneshot_locked(state, &auto_id, now);
Ok(((), true))
} else {
Ok(((), false))
@@ -2882,7 +3124,7 @@ impl AutomationService {
}
}
fn check_workspace_trust(host: &Host, workspace: &AutomationWorkspace) -> Result<(), String> {
pub(crate) fn check_workspace_trust(host: &Host, workspace: &AutomationWorkspace) -> Result<(), String> {
let AutomationWorkspace::Project { root, isolation, .. } = workspace else {
return Ok(());
};
@@ -2902,11 +3144,82 @@ fn check_workspace_trust(host: &Host, workspace: &AutomationWorkspace) -> Result
Ok(())
}
pub(crate) enum SelfScheduleTime {
After(f64),
At(f64),
}
fn is_actively_scheduled(a: &AgentAutomation) -> bool {
a.enabled
&& match a.trigger {
AutomationTrigger::Manual => a.next_run_override_ms.is_some(),
AutomationTrigger::OneShot { .. } => a.next_run_ms.is_some() || a.next_run_override_ms.is_some(),
_ => true,
}
}
/// Orders automations as an upcoming schedule queue:
/// 1. Enabled schedules with a future `next_run_ms` (soonest first),
/// 2. Enabled idle/manual schedules with no upcoming firing (most recently updated first),
/// 3. Paused automations (most recently updated first).
fn compare_automations_by_schedule(a: &AgentAutomation, b: &AgentAutomation) -> std::cmp::Ordering {
let tier = |x: &AgentAutomation| -> u8 {
if !x.enabled {
2
} else if x.next_run_ms.is_some() {
0
} else {
1
}
};
tier(a)
.cmp(&tier(b))
.then_with(|| {
match (a.enabled.then_some(a.next_run_ms).flatten(), b.enabled.then_some(b.next_run_ms).flatten()) {
(Some(na), Some(nb)) => na.total_cmp(&nb),
_ => std::cmp::Ordering::Equal,
}
})
.then_with(|| b.updated_ms.total_cmp(&a.updated_ms))
.then_with(|| a.name.cmp(&b.name))
}
/// Disables a `OneShot` automation whose seed timestamp has elapsed once no active run remains
/// and the agent did not schedule a future `next_run_override_ms`.
fn finalize_exhausted_oneshot_locked(state: &mut StoredState, automation_id: &str, now: f64) -> bool {
let has_active_run = state.runs.iter().any(|r| {
r.automation_id == automation_id
&& matches!(r.status, AutomationRunStatus::Running | AutomationRunStatus::NeedsInput)
});
if has_active_run {
return false;
}
let Some(auto) = state.automations.iter_mut().find(|a| a.id == automation_id) else {
return false;
};
if !auto.enabled || !matches!(auto.trigger, AutomationTrigger::OneShot { .. }) {
return false;
}
let has_future_override = auto.next_run_override_ms.is_some_and(|ms| ms > now);
let has_future_seed = auto.trigger.next_run_after(now).ok().flatten().is_some();
if has_future_override || has_future_seed {
return false;
}
auto.enabled = false;
auto.next_run_ms = None;
auto.next_run_override_ms = None;
auto.next_prompt_override = None;
auto.updated_ms = now;
true
}
#[allow(clippy::too_many_arguments)]
fn allocate_claimed_run_locked(
state: &mut StoredState,
auto_idx: usize,
origin: AutomationRunOrigin,
occurrence_id: String,
override_prompt: Option<String>,
owner_instance_id: &str,
now: f64,
disabled_any: &mut bool,
@@ -2917,10 +3230,15 @@ fn allocate_claimed_run_locked(
if auto.max_runs.is_some_and(|max| run_number >= max) {
auto.enabled = false;
auto.next_run_ms = None;
auto.next_run_override_ms = None;
auto.next_prompt_override = None;
*disabled_any = true;
}
auto.updated_ms = now;
let cloned_auto = auto.clone();
let mut cloned_auto = auto.clone();
if let Some(prompt_text) = override_prompt {
cloned_auto.prompt.text = prompt_text;
}
let project_root = match &cloned_auto.workspace {
AutomationWorkspace::Project { root, .. } => Some(root.clone()),
Loaded 100 of 1896 files, more files were not shown because too many files have changed in this diff. Show more