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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 3eab276239 feat(agents): group the task list by project in a workspace
With several projects in the window, a Group by Project toggle in the
Agents tool window header lists the active tasks under their project
(in the workspace's order, each in attention order) instead of under
their status. Pinned and custom groups, Archived and Automated stay as
they are. Manual reordering is off while grouped, and the project tag on
each row is hidden since the group names it. The choice is remembered.
2026-12-05 02:20:04 +08:00
l0ng-ai cf5493959b feat(keymap): add Visual Studio and ReSharper keymap presets (#8106)
Settings › Keymap gains Visual Studio and ReSharper presets for Windows/Linux and macOS, generated from JetBrains' Visual Studio and ReSharper keymaps with the same parent chain (Visual Studio on the OS's IntelliJ preset, ReSharper on Visual Studio). Inherited bindings of context-free actions are dropped where a preset gives their key to another action. IDEA_ACTIONS gains 64 standard IDEA action ids, which also helps imported IDEA keymaps and IdeaVim's :action, and imported keymaps based on Visual Studio, ReSharper or NetBeans pick that preset as their parent.
2026-12-05 02:14:45 +08:00
Jason HanтаJackzigen 8f1d2afb0c fix(github): add a root node to the pull request changes tree (#8101)
The pull request changes tree had no node for the whole change set, so F7 walked only from the file first opened and root dotfiles sorted before it were reachable only with Shift+F7. The tree now has the repository's node on top (named after the repository folder, with the file count beside it), in both groupings; selecting it selects every change, so Show Diff walks the whole pull request and the viewed toggle covers every file. An empty pull request shows no root row.

Co-authored-by: Jackzigen <[email protected]>
2026-12-05 02:01:20 +08:00
l0ng-ai d48146f52d fix(agents): keep agent_refresh_models off the main thread and cache newest_install (#8070)
Opening the New Agent Task page froze the UI when a native agent such as Codex had several installs on PATH: agent_refresh_models was a synchronous command, so it resolved provider specs and ran <agent> --version for every candidate on the main thread, while agent_commands, agent_probe and catalog completion repeated the same blocking lookup on Tokio workers. agent_refresh_models now runs on the blocking pool, the remaining provider_specs / resolve_for_launch / catalog requests move to spawn_blocking, and newest_install probes candidates in parallel with a per-binary cache (canonical path, mtime, size, inode; 60 s) and single-flight deduplication.
2026-12-05 01:59:50 +08:00
Christer Söderlundтаchristerso 5cfd5157d0 feat(scaffold): add an Odin project to New Project, with Odin icons (#8096)
New Project gains an Odin entry. Odin has no init command, so the generator writes main.odin, an ols.json and a .gitignore, and checks that odin is installed. .odin files get a file icon (light and dark), and New Project uses the Odin logo from Simple Icons, credited in THIRD_PARTY_LICENSES.md.

Co-authored-by: christerso <[email protected]>
2026-12-05 01:45:16 +08:00
Christer Söderlundтаchristerso 0ba39f732e feat(languages): add Odin with OLS, its tree-sitter grammar and outline (#8095)
.odin files open as Odin: highlighting from tree-sitter-odin, a Structure view from a new outline query (every name of a multi-name field listed), and OLS as the language server, installable from Language Servers settings. OLS release archives name the program after the platform (ols-x86_64-pc-windows-msvc.exe), so the installer also locates ols-*.

Co-authored-by: christerso <[email protected]>
2026-12-05 01:43:26 +08:00
arookieofc-ai[bot]таarookieofc-ai 194b01d74f feat(scaffold): add CakePHP project generator (#8090)
New Project › PHP gains CakePHP, generated with composer create-project cakephp/app (PHP 8.2 or later and Composer required).

Co-authored-by: arookieofc-ai <[email protected]>
2026-12-05 01:28:12 +08:00
arookieofc-ai[bot]таarookieofc-ai 6ea187f0d0 feat(scaffold): add CodeIgniter project generator (#8088)
New Project › PHP gains CodeIgniter, generated with composer create-project codeigniter4/appstarter (PHP 8.2 or later and Composer required).

Co-authored-by: arookieofc-ai <[email protected]>
2026-12-05 01:27:01 +08:00
arookieofc-ai[bot]таarookieofc-ai 0fe7fa9b48 feat(scaffold): add Fastify project generator (#8086)
New Project › JavaScript gains Fastify, generated with the official create-fastify package, with the package manager choice and the optional dependency install the other Node generators have.

Co-authored-by: arookieofc-ai <[email protected]>
2026-12-05 01:26:47 +08:00
l0ng-ai f75b1c0a04 feat(java): copy string concatenation text to the clipboard (#8100)
A Java intention copies the text a string concatenation at the caret builds, with ? for each operand that isn't a literal and a line break where the operands continue on a new line; on a lone string literal or text block it copies the literal's value (escapes interpreted, text block indentation removed). It reads the syntax tree, so it is offered before jdtls is ready.
2026-12-05 01:24:05 +08:00
audichuang e5642b0631 fix(i18n): keep known text a locale lacks in English instead of half-translating it (#8083)
In a locale that lacked a sentence, txTemplate matched the English source against loose templates such as '{count} class' and translated only the literal part, so hints and notifications showed half-translated text. A text that is a key of text/en.json and missing from the locale now comes back in English with no template matching (decided in #8047); runtime text that is not in the catalog still matches templates, and the same check runs before text built by a tx tag is rebuilt. text/en.json is loaded with any other locale; if it fails to load, translation behaves as before.

Co-authored-by: audichuang <[email protected]>
2026-12-05 01:16:05 +08:00
faysouтаfaysou 632ee77580 perf(project-tree): avoid pairwise library root comparisons (#8085)
Building the Project tree model counted, for each library root of a group, how many sibling roots hold it by comparing it with every sibling. SDK groups with thousands of roots made that quadratic and delayed expanding even small folders. Nested roots are now counted by looking up each root's normalized directory prefixes, with the same result (same-path roots with a different spelling, trailing separators and Windows paths included).

Co-authored-by: faysou <[email protected]>
2026-12-05 01:10:26 +08:00
l0ng-ai 51227d5898 fix(agents): keep text an agent sends before the prompt out of the reply (#8098)
pi-acp sends its startup info as an agent message right after session/new, before the prompt. The timeline appended the reply to that entry, so Generate Commit Message with Agent put the startup info into the commit message. The timeline is now sealed when session/prompt is sent, so the reply's text (agent or thought) starts an entry of its own.
2026-12-05 01:08:53 +08:00
l0ng-ai f5180392f2 fix(vcs): focus the changes tree when the Commit tool window opens (#8097)
Opening the Commit tool window put the focus in the commit message, which was the window's activation target. The changes tree now takes the activation focus; Commit… (Cmd/Ctrl+K) requests the message through the commit store, and the message keeps the activation focus until it loses focus. The modal Commit dialog still focuses its message.
2026-12-05 01:02:28 +08:00
Serbin Yaroslavтаwislert 3278eab0c8 fix(viewers): zoom the image viewer a step per Ctrl+wheel notch (#8089)
One Ctrl+wheel notch could zoom the image viewer from 94% to 693% on Windows: the handler multiplied the zoom by exp(-deltaY * 0.01) with no per-event limit, so a large pixel-mode notch zoomed several times over. The wheel curve the Mermaid preview already used (about 15% a notch, at most x1.5 or /1.5 per event, trackpads continuous) is now shared as wheelZoomFactor and used by the image viewer and the database ER diagram, which had the same formula.

Co-authored-by: wislert <[email protected]>
2026-12-05 00:56:28 +08:00
l0ng-ai 71bfc70996 feat(github): browse and work on repository issues (#8077)
* feat(github): browse and work on repository issues

* fix(github): fix issue browse assignee filter, list keyboard navigation, and edge cases
2026-12-05 00:54:51 +08:00
l0ng-ai 1e6ab2ecff fix(java): repair a jdtls workspace that Eclipse can no longer open (#8091)
jdtls exited with code 13 on every start when its workspace's saved resource tree no longer matched itself (ResourcesPlugin.start → SaveManager.restore → ObjectNotFoundException). Before each start, if the last session in the workspace's .metadata/.log failed inside SaveManager.restore, the saved resource tree (.metadata/.plugins/org.eclipse.core.resources) is removed so jdtls imports the projects again; JDT's index is kept.

Fixes #7908
2026-12-05 00:37:53 +08:00
Akbar Husainтаl0ng-ai 0f0e3e73e7 feat(java): use java-analyzer's extract interface requests (#7987)
* feat(java): use java-analyzer's extract interface requests

* feat(java): match the merged extract interface protocol

* fix(java): handle null extractInterfaceInfo, keep source className, and add protocol tests

---------

Co-authored-by: l0ng-ai <[email protected]>
2026-12-05 00:33:19 +08:00
tongkangwangтаl0ng-ai a2498f096a fix(code-insight): stabilize Show Usages popup sizing and placement (#8080)
* fix(code-insight): stabilize Show Usages popup sizing and placement

The popup used a fixed 680px width and 14-row limit. Restoring a saved
size also prevented it from adapting to incoming results. Follow the
IntelliJ popup sizing and placement flow while limiting the filename
column to 25% of the popup width to leave space for code.

Sizing and columns:
- Restore both saved dimensions while waiting for results. Once results
  arrive, cap the natural width at the saved width and calculate the
  height from content. Only preview mode also uses the saved height.
- Measure filenames, line numbers and code with the actual fonts, with
  a 500px natural width limit per column. Fit short filenames to their
  content and ellipsize long names at 25% of the row width. Reserve 5ch
  for line numbers and at least 8em for code, which fills the remaining
  space.
- Include the filename cap, code minimum width, header, controls, borders
  and gaps in the natural popup width. Do not widen the popup for text
  that the filename column will clip.
- Cache maximum natural widths during streaming and filtering. After a
  manual resize, keep updating filename measurements but stop resizing
  the popup automatically until it is reopened or preview is toggled.
- Show up to 30 rows normally or 20 with preview. Leave half a row when
  the list scrolls, and let the list fill the available height.
- Preserve the 360x160 minimum size and existing storage keys. Fit the
  viewport when it is smaller, and save the actual size on close.

Placement and preview:
- Open below the caret. When it is outside the visible editor, use a
  point one third across and halfway down the visible editing area.
- Add optional fitToScreen placement to Popup. Keep the fitted position
  when content shrinks, and move only when necessary to stay visible.
  Reset placement when the anchor changes or preview rebuilds the popup.
- Reuse the shared split panels with a default 60/40 list/preview split,
  persisted proportions, mouse dragging and keyboard adjustment. Set the
  preview minimum to five actual editor lines and update it after font
  or editor geometry changes.
- Preserve the preview's pixel height while manually resizing the outer
  popup. Wait for the splitter's final measurement before restoring it.
- Add onResizeStart on the first pointer movement. Clicking the resize
  handle alone does not lock preview height. Toggling preview clears
  saved dimensions, measurements, manual size and drag position, and
  cancels pending resize callbacks.
- Add a translated accessible label to the preview divider and preserve
  its keyboard controls alongside usage-list navigation.

Verification:
- 17 Playwright layout and demo tests passed in local Google Chrome,
  covering both themes, the 25% cap, narrow windows, filtering, saved
  dimensions, position stability, preview, keyboard controls and resize.
  Both filename-cap regression cases failed before the fix and passed
  afterward.
- Wait for fonts and entry animations before dragging the one-pixel
  divider or measuring dimensions. Account for popup growth when the
  search caption changes while checking the filename cap.
- 49 Popup and Show Usages unit tests passed on the final version.
- pnpm typecheck and pnpm build passed, including Safari 15.4 checks.
  Changed-file oxlint, oxfmt and git diff --check passed.
- An earlier full test run had 20,483 passed, 65 skipped and two existing
  translation-check failures in color-preview/varColors.ts and
  vcs/rebase.tsx. Earlier full lint and knip checks passed. Full format
  checking failed on an existing untracked .workbuddy memory file.
- Before/after screenshots for both themes and narrow windows, plus
  interaction recordings, are retained in temporary verification folders.
  Tests used browser fixtures; the native Tauri webview was not tested
  because no Tauri MCP bridge was available.

* fix(code-insight): restore focus across preview toggle, avoid width ratchet, and clean up cancelled resizes

---------

Co-authored-by: l0ng-ai <[email protected]>
2026-12-05 00:29:34 +08:00
l0ng-ai 494d1a9bf5 fix(plugins): keep plugin gutter actions and markers coming while navigation indexes (#8087)
Plugin language visuals, plugin colours, server code lenses and plugin line markers restarted a 300-400 ms debounce on every trigger and threw away the request in flight. While a project indexes, plugin navigation notifies about every 250 ms, so the request was never sent or its answer was always dropped: a new editor never got its gutter actions. A shared CoalescedRefresh now runs at the latest after a maximum wait and only drops a result older than one already shown.

Fixes #8056
2026-12-05 00:25:58 +08:00
RuyimgByCN 417ecfed50 perf(plugins): batch navigation indexing, skip empty edges, and isolate bad files (#8013)
Plugin navigation indexing sent 8 files per IPC call, invalidated each batch first and slept 20 ms between batches, and one invalid document failed its whole batch. The frontend now sends 128-file batches (active editors first) without the separate invalidation; the host loads them, calls the plugin in chunks of 16 so interactive requests interleave, skips and evicts invalid or oversized documents one by one, and does not store documents without edges, so they no longer take graph slots. A full graph still skips uncovered files before running the plugin. Discovery stays at one graph's 20,000 files, so the covers-N-of-M notice stays true. Sparse 20k files: 780 ms → 373 ms indexing, same navigation results.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-05 00:06:00 +08:00
Markus Hofmann 94653b487d fix(editor): align filled indent steps and keep them under the selection (#8038)
With Fill indent levels on, each stripe started two pixels left of the
indent step it marks: the offset that keeps a 1px guide off the glyph
edge was applied to the step-wide stripes too, so a stripe ended short
of the code and the first one ran into the line's left padding.

The stripes were also painted on the guide layer above the text, which
is right for a thin line but tints a selection and the caret row across
the indentation. As a row background they belong below the selection
layer, where the theme comment already says they are.
2026-12-05 00:03:26 +08:00
Serbin YaroslavтаClaude a5473e896a feat(color-preview): open a resolved variable's declaration from its gutter swatch (#8075)
Clicking the swatch of a var(--name) usage opens the declaration its color
comes from (the variable written at the usage, the document's own declaration
first), also in read-only editors. Literal swatches keep the color picker;
color functions with var() inside stay display-only.

Refs #8017

Co-authored-by: Claude <[email protected]>
2026-12-05 00:00:29 +08:00
LU XIANGRUIтаwildcatDownstairs 8483c355c8 fix(workspace): remove a workspace member whose folder is gone (#8069)
The Project view's context menu returned early for an unavailable path, before the branch that offers Remove from Workspace / Detach Project for a member root, so a member whose folder had moved or been deleted could not leave the workspace. The member entry now comes from one helper used by both the available and the unavailable branch.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-04 23:57:39 +08:00
audichuang 8d2d2d27e6 fix(code-insight): keep Show Usages' scope chooser on Project Files while that search takes a while (#8064)
* fix(code-insight): keep Show Usages' scope chooser on Project Files while that search takes a while

* test(code-insight): Show Usages widens when invoked again during the chooser's slow Project Files search
2026-12-04 23:56:58 +08:00
LU XIANGRUIтаwildcatDownstairs 72db7ecb97 perf(debug): share one lldb-dap server across Xcode debug sessions (#7442)
Every Xcode attach started a fresh lldb-dap, which parses the symbol tables of the ~550 system libraries an iOS app loads before reaching a breakpoint. Xcode attaches on macOS now reuse one lldb-dap server (keyed by working directory, lldb-dap binary and environment, over a private Unix socket) that keeps the parsed modules; it ends after 10 minutes without a session, when the IDE quits, or when another configuration replaces it. Overlapping attaches and custom adapter invocations keep their own process. Measured on an iOS Simulator: attach to stopped-with-frames 1.74 s before, 0.49 s with a warm server, 1.56 s cold.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-04 23:55:28 +08:00
l0ng-ai 406cf4e474 fix(debugger): keep the editor still while stepping when the execution line is on screen (#8076)
Each stop selected the top frame through openFile with a selection, which always scrolled the line to the centre of the editor, so stepping through visible code moved the text on every step. OpenOptions gains scroll: "visible" (leave an on-screen selection where it is, centre an off-screen one); the debugger uses it for the top frame on each stop and for Show Execution Point. Selecting another frame and Jump to Source still centre the line.

Fixes #7963
2026-12-04 23:39:41 +08:00
RuyimgByCNтаl0ng-ai bc019ace9d feat(plugins): add database schema discovery and query execution APIs (API 1.21) (#7958)
* feat(plugins): add database schema discovery and query execution APIs (API 1.21)

* docs(plugins): list API 1.21 database discovery and query additions in versioning

* fix(plugins): address database discovery/query review findings and rebuild dist

---------

Co-authored-by: l0ng-ai <[email protected]>
2026-12-04 23:38:50 +08:00
Vadim LazukтаInf1mum 55c9787996 feat(color-scheme): C# interface, enum, struct, type parameter and predefined type colours (#8063)
csharp-ls sends interface, enum, struct and typeParameter as their own semantic token types, but the generic mapping folded them all into the class-name colour, and predefined types (int, string, bool…) also showed in the class colour. The C# Colour Scheme page gains Interface name, Enum name, Struct name and Type parameter (inheriting Class name) and Predefined type (inheriting Keyword); a new C# semantic module tags the tokens, recognising predefined types by their text. The preview shows each new attribute.

Co-authored-by: Inf1mum <[email protected]>
2026-12-04 23:33:19 +08:00
l0ng-ai 5b1e4a31f2 fix(remote-dev): show remote project loading inside its new tab (#8055)
* fix(remote-dev): show remote project loading inside its new tab

* fix(remote-dev): preserve active remote session on cancel and style grouped Welcome tabs
2026-12-04 23:32:03 +08:00
LU XIANGRUIтаwildcatDownstairs f3582403f3 fix(svn): show each working copy's svn update output in the console (#8065)
Update Project over several working copies only showed the first one's output: every repository's vcs_remote call shared one Tauri channel, and a channel stops delivering once its command ends. Each command now gets its own channel (also for the multi-repository Git branch update). The Subversion backend streams svn update's own lines (Updating, the U/A/D/C/G file lines, Updated to revision N) instead of a single summary line.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-04 23:21:44 +08:00
a5f958d544 fix(windows): roll back failed macOS tab joins (#8036)
* fix(windows): roll back failed macOS tab joins

* fix(windows): notify on join rollback, preserve existing groups, and show standalone fallback

---------

Co-authored-by: arookieofc <[email protected]>
Co-authored-by: l0ng-ai <[email protected]>
2026-12-04 23:19:54 +08:00
Michał Dobaczewskiтаl0ng-ai 4aeeb4d883 feat(agents): duplicate a built-in agent to run it with its own configuration (#8048)
* feat(agents): duplicate a built-in agent to run it with its own configuration

* fix(agents): preserve instance launch command, login secrets, provider cache, and reactive icons

---------

Co-authored-by: l0ng-ai <[email protected]>
2026-12-04 23:19:46 +08:00
l0ng-ai 15f3eadcf1 fix(syntax): detect expressions when caret sits after closing delimiter (#8051)
* fix(syntax): detect expressions when caret sits after closing delimiter

* fix(syntax): detect nested postfix and JSX expressions before closing delimiter
2026-12-04 23:19:38 +08:00
ae9804bc8b feat(vcs): add option to filter Git Log on single click in Branches pane (#8040)
* feat(vcs): add option to filter Git Log on single click in Branches pane

* fix(vcs): do not update branch filter on context-menu right click

---------

Co-authored-by: LU XIANGRUI <[email protected]>
Co-authored-by: l0ng-ai <[email protected]>
2026-12-04 23:19:31 +08:00
faysou 644a380616 perf(project-tree): reuse file rows when expanding folders (#8046)
Reuse the file rows from unchanged directory listings when another folder opens. Recompute rows when filtering, sorting, or the listing changes, and keep compact folder chains dependent on their descendants.
2026-12-04 23:19:24 +08:00
l0ng-ai 4a41b14992 fix(database): select the matching cell when navigating into a CSV file shown as Data (#8067)
Find in Files, Go to Line and other navigation into a CSV file on its Data tab moved the caret in the hidden Text editor only. The table now maps the revealed offset to its record and field the way the CSV parser reads the file (quotes, CRLF, blank lines, header row), scrolls to that cell wherever local sorting put it, selects it and takes the focus; a row hidden by a filter is left alone.

Fixes #8043
2026-12-04 23:11:43 +08:00
audichuang 551328c901 fix(code-insight): say no usages were found when a search in the open Show Usages popup ends with none (#8058)
When a new search in the open Show Usages popup found nothing (e.g. switching the scope to Project Files for a symbol used only in libraries), the list said "No usages match the access filters" with no filter set. It now says "No usages found" when the search found nothing, and keeps the access-filter text for results the filters hide.

Co-authored-by: audichuang <[email protected]>
2026-12-04 23:04:08 +08:00
Vadim LazukтаInf1mum 54ce7ac6f8 fix(editor): re-ask semantic tokens when a server settles after a slow project load (#8060)
A file opened while csharp-ls was still loading the solution never got semantic colours: its only semantic tokens request timed out (a protocol error the plugin ignores), and csharp-ls sends no workspace/semanticTokens/refresh when the load ends. The semantic plugin now also re-requests when a server's long busy spell settles, the recovery signal inlay hints and code lens already use. Server-initiated refreshes and the unavailable backoff are unchanged.

Closes #8052

Co-authored-by: Inf1mum <[email protected]>
2026-12-04 23:02:47 +08:00
l0ng-ai a33c46465b fix(settings): use theme-aware Project Structure icons 2026-12-04 22:59:23 +08:00
l0ng-ai b747e81cb6 fix(lsp): offer the kotlin-lsp update when a running build expires (#8059)
A kotlin-lsp build past its date only crashes when it starts. A running one reports that its license expired, keeps working for a short grace period, then parks and stops answering, so Go to Declaration silently did nothing and no update was offered. A license-expiry notice in window/showMessage or window/logMessage now marks the running instance; its Ready/Busy status says the build expired, and the UI offers the same update as for a crashed expired build, once per instance. The "renew or activate a license" notice is no longer shown as is.

Fixes #8033
2026-12-04 22:47:03 +08:00
l0ng-ai 24fdbb54db fix(i18n): translate the Edit Commit Message warning title and allow the var() swatch tooltip (#8057)
textCatalog.test.ts failed on main: the pushed-history warning of Edit Commit Message passed an untranslated "Edit commit message" literal as its title, now the action's catalog title "Edit Commit Message"; and the color gutter's var(--name) = value tooltip is CSS shown as written, now listed in TEMPLATES_AS_WRITTEN.
2026-12-04 22:35:56 +08:00
LU XIANGRUIтаwildcatDownstairs 535f7584ee fix(maven): show default-active profiles in grey and pass explicit -P choices (#8042)
Profiles active by default (activeByDefault in a POM or settings.xml, or listed in settings.xml activeProfiles) now show a grey check, and a profile the user checks explicitly is always passed in -P: before, checking a default-active profile next to another one left it out of -P, so Maven deactivated it. A click goes from the default to explicitly disabled, then explicitly enabled, then back to the default; an inactive profile goes enabled and back. activeByDefault is read case-insensitively, declarations of one profile in parent, module and settings.xml are merged, and profile ids are shown verbatim instead of through the text catalog.

Closes #8005

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-04 22:24:17 +08:00
audichuang 49e26d1de1 fix(code-insight): hide the usage count while Show Usages is still searching with nothing found (#8041)
Show Usages opens 300 ms into a slow search, before anything is found, and its header then read "0 found" as if the search had finished empty. The count is hidden while the search runs with no results; the header spinner and "Searching for usages…" show progress, and the count appears once usages arrive or the search ends.

Refs #6823

Co-authored-by: audichuang <[email protected]>
2026-12-04 22:10:49 +08:00
audichuang 40fb4923e6 fix(editor): keep Rearrange Code from moving a generator under a field without a semicolon (#8039)
Rearrange Code could move a method starting with *, in or instanceof to the top of a class right below a field with no semicolon, where it continued the field's initializer (x = 1 then *gen() {} reads as 1 * gen()). The same happened when the only semicolon ending the field sat on a comment line that moved with the method. Such classes are now left alone; a semicolon or static block above, or a first method that stays first, still lets the class rearrange.

Co-authored-by: audichuang <[email protected]>
2026-12-04 22:08:27 +08:00
LU XIANGRUIтаwildcatDownstairs 8fefbc1c82 fix(vcs): allow editing commit message of merge commits (#8037)
Edit Commit Message refused any range with a merge commit because it validated the range like an interactive rebase, and the backend reword kept only one parent. Rewording never changes trees, so it now keeps every parent of the commit and rewrites its ancestry-path descendants with their parents remapped, which preserves the history graph; the index and working tree stay untouched. Works for a merge commit at HEAD (right after a merge) and earlier on the current branch; commits outside the current branch and protected history are still refused.

Closes #7991

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-04 22:05:40 +08:00
LU XIANGRUIтаwildcatDownstairs 059dca5b34 fix(editor): isolate ParseContext skipped ranges across state updates (#8035)
ParseContext.changes() in @codemirror/language handed the parent context's skipped array to the child whenever there was nothing to remap, so a speculative state.update() (paste reindent, Shift+Enter, Move Line, Complete Statement) let StreamLanguage's skipUntilInView push a range past the live document's end into the live state's array. Applying the real transaction then threw RangeError in ChangeSet.mapPos and broke the editor for .properties and other StreamLanguage files longer than the viewport. The patch gives every child context its own skipped array.

Closes #7989

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-04 21:51:46 +08:00
Vadim LazukтаInf1mum 277464e93b feat(color-preview): resolve var() usages and detect modern color syntaxes in the gutter (#8026)
The color gutter now shows a swatch for every color on a line, side by side in source order: literals as before, plus each var(--name) whose value resolves to a color through the project's custom properties (web_css_variables, the same data the var( completion uses), following nested references and fallbacks with a depth limit and cycle check. oklch(), oklab(), lch(), lab(), hwb(), color() and color-mix() are detected as colors (swatch only). A color function with var() inside takes the project's values instead of the IDE's own custom properties, and shows no swatch when one doesn't resolve.

Closes #8017

Co-authored-by: Inf1mum <[email protected]>
2026-12-04 21:35:17 +08:00
Vadim LazukтаInf1mum a6e9c79c96 feat(editor): fill indent levels under rainbow indent guides (opt-in) (#8018)
Adds Editor > General > Appearance > Rainbow indent guides > Fill indent levels (off by default). With it on, each indent level's whitespace is tinted in its rainbow colour at low strength, including code lens rows and blank lines; the caret's and matched-brace levels are highlighted the same way. The setting is declared in the backend settings schema so it can be saved.

Closes #7883

Co-authored-by: Inf1mum <[email protected]>
2026-12-04 21:25:24 +08:00
audichuang 1a6c0dff36 ci: run the Kotlin smoke against kotlin-lsp 271.3588.0 (#8034)
* ci: run the Kotlin smoke against kotlin-lsp 271.3588.0

* docs(smoke): list kotlin-lsp 271.3588.0 as the pinned version
2026-12-04 21:17:16 +08:00
l0ng-ai 73708c8e7d test(e2e): wait for editor session stream before zooming in agentMarkdown (#8045) 2026-12-04 21:16:53 +08:00
l0ng-ai d2cc2093b1 docs: escape placeholder angle brackets in MDX files (#8044) 2026-12-04 21:16:46 +08:00
Vadim LazukтаInf1mum ff9a48eb0e feat(vcs): open branch and revision comparisons as Compare tool window tabs (#8021)
Compare with Branch… / Compare with Revision… on a folder or multi-selection, two-commit Compare Versions from the Git Log, the branches' Show Branch Diff and Show Diff with Working Tree now open one closable, titled tab per comparison in the Compare tool window instead of a separate comparison window. Only the active comparison loads; closing the last tab, or switching projects, removes the stripe button, which shows the number of open comparisons as its badge. The tabs use the shared Tabs strip (hidden-tabs dropdown, Close Tab / Close All Tabs / Close Other Tabs). Compare with Current keeps the two-pane branch comparison editor and a single file still opens its diff tab.

Closes #7813

Co-authored-by: Inf1mum <[email protected]>
2026-12-04 21:08:45 +08:00
l0ng-ai 24e42bb302 fix(terminal): let PowerShell run npm.ps1 and other script shims on Windows (#7939)
Windows PowerShell's default execution policy is Restricted, so in the integrated terminal npm.ps1, nvm/Volta Node shims and a virtualenv's Activate.ps1 could not run. A plain PowerShell start in the terminal now gets -ExecutionPolicy Bypass (process scope) before -NoExit -Command <init>, and MCP run_command running a line in PowerShell on Windows gets the same. Process scope changes nothing outside that PowerShell process, a Group Policy setting still takes precedence, and a shell with explicitly configured arguments starts as configured.

Fixes #7920
2026-12-04 20:52:22 +08:00
arookieofc-ai[bot]таarookieofc-ai 67c00a986a feat(plugins): add clone sources to the Clone Repository dialog (#7948)
[[contributes.cloneSources]] (API 1.21) adds an entry to the Get from VCS source list whose required web page lists repositories and hands the chosen one to the dialog with {"op": "clone-url", "url": …}. The page is served and messaged like other plugin web UI under the key cloneSources/<id>; the dialog fills its URL and directory and git only runs what the user confirms. The standalone Get from VCS window registers only this contribution point. plugin_web_page and plugin_view_event now also run in projectless windows (outside_restricted); Restricted Mode still runs no plugin UI or code. Docs list the point under API 1.21.

Fixes #5572

Co-authored-by: arookieofc-ai <[email protected]>
2026-12-04 20:46:11 +08:00
l0ng-ai 896ec3b924 fix(agents): keep following the chat end when a row grows after its render (#8015)
While a reply streamed, the conversation followed the end only after a React render or when the stream itself resized, so a row that grew later on its own (a highlighted code block, a laid-out diagram or image) left the end of the reply hidden under the composer. The rows' ResizeObserver now brings the view back to the end while it follows the end and nothing else moved the offset: not while the reader scrolls up, drags, uses Find, has fold slack below, or while the tab is hidden.
2026-12-04 20:30:49 +08:00
ambersariya 2f18cacbaf fix(project-tree): reveal individual folders in compacted chains (#8029)
New and Paste on a compacted folder row (TEST/123) always target the deepest folder, so a folder in the middle of the chain could not be reached from the tree. A Show Individual Folders entry in the context menu of a compacted row now shows each folder of that chain as its own row for the current session, so an intermediate folder can be selected for New, Paste and the other folder actions. The compacted row keeps targeting its deepest folder, and the Compact Middle Packages option is unchanged.

Fixes #8022

Co-authored-by: ambersariya <[email protected]>
2026-12-04 20:23:15 +08:00
Vadim LazukтаInf1mum 2cad48b401 fix(build-tools): running a goal or task from the tool window leaves the selected configuration alone (#8028)
Running a Maven goal or Gradle task from its tool window went through run.runConfig with a temporary configuration, and adoptTemporary always selected it, so the just-run goal replaced the configuration selected in the Run Configurations dropdown. The tool window now passes select: false and adoptTemporary only selects when asked; editor and gutter runs still select their temporary configuration.

Fixes #8016

Co-authored-by: Inf1mum <[email protected]>
2026-12-04 20:17:47 +08:00
LU XIANGRUIтаwildcatDownstairs 1f8cf7e3a8 feat(vcs): one changelist at a time and included counts in the Commit Changes dialog (#8012)
The modal Commit Changes dialog now has a Changelist chooser above the changes. It starts at the active changelist; the tree shows that list's changes plus unversioned files, and only that list's changes are committed, so a file ticked in another changelist can no longer slip into the commit. A legend below the tree counts the included files as added (new + unversioned), modified and deleted. The non-modal commit view is unchanged.

Refs #7433

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-04 20:12:41 +08:00
Deng Liuтаdengliu 978bcd6dd4 feat(roots): auto-exclude nested linked Git worktrees from indexing and search (#7967)
Linked worktrees of the repository at the project root that live below the root (any path, e.g. some/folder or .wt/topic) are now detected from <common_dir>/worktrees/*/gitdir and marked excluded, so they stay out of indexing, the file watcher, Find in Files and the Commit module list. Worktrees of other repositories, submodules, a linked worktree opened as the project root, attached workspace members and Cancel Exclusion are unaffected.

Co-authored-by: dengliu <[email protected]>
2026-12-04 20:01:51 +08:00
l0ng-aiтаarookieofc a1d406beb3 test(plugins): expect the editor's visible lines in remote focus events (#8032)
API 1.21 added the editor's visible lines as a third element of an event's editor payload, null when the client sent none. The remote focus test still expected the two-element form and failed on every Linux run.

Co-authored-by: arookieofc <[email protected]>
2026-12-04 19:47:38 +08:00
faysouтаfaysou b46c467fc3 fix(markdown): enable Find in rendered previews (#8014)
The Find shortcut did nothing in Markdown Preview Only. It now opens the console find bar above the preview (Match Case, Words, Regex, match counter, previous/next), searches the rendered text including inline formatting and offscreen matches, follows the configured Find shortcuts, and Escape returns focus to the preview. The source editor keeps its own Find in split and editor views.

Co-authored-by: faysou <[email protected]>
2026-12-04 19:02:30 +08:00
Isaac Gallartтаigallart 091dd85ef0 fix(vcs): use symlink target history in the editor (#7891)
The repository scan skips symlinks, so a file opened through a file symlink or a symlinked directory whose target lies outside the registered Git roots had no Git Blame or change markers, even when Git tracked the target. Read-only editor commands (blame, line hunks) now use the target's repository, discovered with the restricted read policy and never registered for status or Commit; excluded mappings and a disabled Git integration are honoured. The editor probes once per open file whether the link has committed history: only then do Annotate and the markers apply, and ordinary files in projects without Git make no further backend calls on edits.

Co-authored-by: igallart <[email protected]>
2026-12-04 18:57:51 +08:00
LU XIANGRUIтаwildcatDownstairs 4eab243ef2 fix(vcs): mark the active changelist bold and list it first (#8004)
The Commit tool window meant to draw only the active changelist in bold, but the stylesheet only gave inactive lists font-weight 400, the weight every group label already has, so the active list looked like the others. Lists also appeared in creation order. The active list is now bold and comes first, the other lists follow by name in natural order, and Unversioned Files stays last.

Refs #7433

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-04 18:44:43 +08:00
LU XIANGRUIтаwildcatDownstairs 56c6e8090a fix(diff): cap the Next Difference scroll at 100 ms and move both panes together (#8002)
Next / Previous Difference scrolled with the browser's smooth scroll, whose duration grows with the distance, and the other pane only followed on scroll events, a frame behind. The jump now animates with an ease-out for at most 100 ms (none for a line or less, full length from eleven lines on), the other pane moves in the same frame, a wheel or pointer still interrupts it, and reduced motion still jumps instantly. The unified diff uses the same animation and stops an unfinished jump before the next one.

Refs #7433

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-04 18:39:49 +08:00
LU XIANGRUIтаwildcatDownstairs bd3f0cb651 fix(notebook): apply the Markdown soft line breaks setting to Markdown cells (#8000)
Notebook Markdown cells always parsed with a single Marked instance with breaks off and didn't read languages.markdown.softLineBreaks, so "Break on single newline" had no effect there. Markdown cells now use the setting and re-render when it changes; hard breaks, code blocks and math are unchanged.

Fixes #7941

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-04 18:30:41 +08:00
l0ng-ai fe1838aca6 fix(plugins): skip files a full navigation graph can't take instead of failing (#8011)
Once a project has more matching files than a plugin navigation graph covers, discovery fills the graph with exactly that many files. Opening, saving or changing any other matching file then failed its whole index batch with "navigation file limit reached", showed a raw error notification, and ran the plugin's indexer before throwing the result away.

A full graph now keeps updating the files it covers and skips the others before calling the plugin. Discovery picks the covered files by path, so the same files keep navigation across index rebuilds.

Fixes #7985
2026-12-04 18:07:07 +08:00
aLiEz 9737adb66c feat(run): open recent projects from Run Anything (#7959)
Typing open in Run Anything lists recent projects and filters them as the user keeps typing. Choosing one opens it as Open Recent does: an open project's window comes to the front, otherwise the Open project in setting applies. Opening a project is not added to the Run Anything command history (new optional RunAnythingItem.addToHistory).

Co-authored-by: aLIEz1 <[email protected]>
2026-12-04 17:56:14 +08:00
Александр Юрченкотаyaleksandr89 1c4aa9f1b2 docs(readme): add Russian translation (#7993)
Adds README.ru.md and links it from the language switcher of every README; the Chinese README also gains its missing link to the Turkish one.

Co-authored-by: yaleksandr89 <[email protected]>
2026-12-04 17:51:15 +08:00
l0ng-ai 4335cf46af feat(plugins): popup dialogs that close on a click outside (API 1.21) (#8009)
A plugin dialog is modal: like the IDE's own dialogs, a click outside it does nothing. popup = true on [[contributes.dialogs]] (API 1.21) opens it as a lightweight popup instead, as Search Everywhere is: the title heads the popup rather than a title bar, and a click outside it or switching to another window closes it, with the same closed view event. Without the field nothing changes.

Closes #7974
2026-12-04 17:49:49 +08:00
l0ng-ai f2b602a48e fix(editor): keep the current find match readable, show more Search Everywhere results (#8007)
Find selects the current match, and the selection is repainted inside the match's own mark. The selected text kept the match's foreground, meant for the yellow match fill, so on a dark theme the current match was dark text on the blue selection. Selected text inside a find match now takes the scheme's selection foreground, or the editor's when the scheme sets none.

The All tab of Search Everywhere showed 6 results per group before "more"; it now shows 15, as many as each "more" adds.

Fixes #7972
2026-12-04 17:39:59 +08:00
l0ng-ai b4c8a6708c fix(plugins): give the keyboard to a plugin dialog's or tool window's page (#8003)
A plugin dialog focused its Close button while its page loaded, and a plugin web tool window left the focus on its body when activated, so typing went nowhere until the user clicked into the page. WebKit doesn't let a sandboxed frame focus a field before the user acts on it, so the page's autofocus or focus() could not help.

The dialog and the tool window now focus the plugin frame, and the frame bridge sends a key typed while nothing in the page has the focus to the page's autofocus field. Shortcuts, Tab and Escape keep their meaning.

Fixes #7973
2026-12-04 17:31:55 +08:00
l0ng-ai 8e36365bc4 fix(vcs): keep agent worktrees and new worktrees out of the project (#7964)
Agents create full checkouts of the repository in .worktrees and .claude/worktrees below the project root, so Find in Files returned every file twice and navigation could land in the copy. Both folders are now excluded directly below the project root and each workspace project's root, like a Project Structure excluded folder; jdtls gets them as import exclusions only when they exist, so other Java projects keep their workspace.

New Worktree suggested the repository's parent folder, which is the project itself when the project is a folder holding the repository. The default location now starts next to the project folder and moves up while it is still inside the project, a content root or the repository.

Closes #7957
2026-12-04 17:19:48 +08:00
l0ng-ai b5a8a77cfa fix(vcs): open the GitHub sign-in terminal from the Get from Version Control window (#7965)
The clone window booted without the workbench and never provided the embedded terminal service the Sign In to GitHub CLI dialog uses, so Add account… showed "The terminal is not available in this window." The clone window now provides it lazily, as the Settings window does. The Sign In button on the not-logged-in state uses the same dialog.
2026-12-04 17:10:03 +08:00
Mollo-i 70a4fbec3a test(editor): cover the Rearrange code row in the Actions on Save layout test (#7992)
#7934 added Rearrange code to Settings > Actions on Save, so the table has five rows, but actionsOnSaveLayout.spec.ts still expected four and failed on main. The test now expects the new row, includes it in the alignment checks and asserts its trigger cell stays empty while the action is off.

Co-authored-by: Greenker <[email protected]>
2026-12-04 16:58:45 +08:00
l0ng-ai b640078b11 fix(settings): show the default font in font pickers and select the current one (#7995)
A cleared font field showed nothing and the font list gave no hint of the default family. Font pickers with a default (UI, editor, terminal, chat and chat code fonts) now show it as the placeholder of an empty field and mark it Default in the list, and opening the list selects and scrolls to the current family.

Fixes #7952
2026-12-04 16:54:24 +08:00
Deng Liuтаdengliu e186f74782 fix(agents): wrap long answered user choices inline and fold long question context (#7979)
Settled answers to agent questions and ACP elicitation forms were drawn in the single-line, ellipsized permission record, in reverse order (choice before question), and with a minus icon because permissionResult treated answers that matched no permission option as rejected. Answered questions and forms now render through a shared QuestionRecord row: a check or minus icon, the chosen answer wrapped in full, short prompts inline, and long or multi-item question or form context folded behind the existing Fold disclosure. Tool and command approval records stay single-line.

Co-authored-by: dengliu <[email protected]>
2026-12-04 16:47:23 +08:00
Mollo-i 25d0294947 fix(editor): keep the caret in place on screen when reformatting (#7971)
Reformat applied its edits with scrollIntoView: false and CodeMirror kept scrollTop, so when the formatter added or removed lines above the caret, the caret slid up or down on screen. The edit now measures the caret's viewport row before the transaction and compensates scrollTop after it, falling back to the caret's line block when its row is no longer drawn. Explicit Reformat Code, format on save and the external formatters all go through this path.

Co-authored-by: Greenker <[email protected]>
2026-12-04 16:39:05 +08:00
Ivan 5d26e44c0e fix(diff): navigate from the working-copy pane with the keyboard (#7961)
Go to Implementation(s), Go to Declaration or Usages, Go to Type Declaration and Super Method required an active text editor tab, so they did nothing while a diff had focus. They now run on the focused diff pane when it shows a file's document; revision panes have no document and keep them disabled. Option+Command-click focuses the clicked pane before checking whether the action is enabled.

Closes #7960

Co-authored-by: Pecnikas <[email protected]>
2026-12-04 16:29:18 +08:00
l0ng-ai 6e327e6ffc feat(remote): remember the backend choice when closing a remote window (#7990)
The Close Remote Development Window dialog gets a Don't ask again checkbox that saves Stop Backend or Keep Backend Running to the new client setting general.closeRemoteWindow (ask | keep | stop); later closes apply it without asking. Settings > Tools > Remote Development > When closing a remote window changes it back.

Refs #7929
2026-12-04 16:12:43 +08:00
l0ng-ai 81d1285e38 fix(sdk): grant every capability without a value in MockHost::install() (#7983)
The mock's default grant list lacked project.write, database.schema, secrets, agents and java.agent, so tests using MockHost::install() got Denied from calls the mock itself checks. It now has every capability that takes no value; an SDK test pins it to the names the mock requires and a host test to the capabilities the manifest parser accepts. Plugin components rebuilt.

Fixes #7946
2026-12-04 15:54:46 +08:00
l0ng-ai 8a92a7b10c fix(remote): trust the projects of a trusted remote folder on this machine too (#7977)
Trust Folder in a remote window trusted the parent folder on the server, but this machine kept only the one project's decision, so opening another project in that folder asked again. The desktop now records trusted folders per remote target and treats projects under them as trusted (an explicit Don't Trust still wins); Remove Trusted Location in a remote window forgets the folder here too. Existing per-project decisions keep their key.

Refs #7929
2026-12-04 15:40:44 +08:00
audichuang 3eb4b54525 fix(workspace): restore a file's case when undoing a case-only rename (#7944)
On a case-insensitive file system a case-only rename's two roots name one directory entry. The workspace edit snapshotted both, and restore deleted and recreated each in turn, so undo left the new spelling on disk. Now only the spelling on disk keeps a snapshot, and restore clears the roots without one before recreating the others.

Co-authored-by: audichuang <[email protected]>
2026-12-04 15:16:29 +08:00
l0ng-ai 5dd0565456 feat(plugins): tell plugins which editor lines are on screen (API 1.21) (#7969)
text-editor.visible-lines (editor.read) returns the first and last document line shown in the editor when the command or event was invoked, or none when the editor is not on screen. The workbench fills it from the focused editor view with the rest of the plugin editor context; older clients leave it out. SDK: TextEditor::visible_lines and MockHost::set_visible_lines. Plugin components rebuilt.

Refs #7928
2026-12-04 15:12:17 +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
1591 змінених файлів з 94705 додано та 10953 видалено

No files matched your search

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

До

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

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

Після

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

+1 -1
Переглянути файл
@@ -7,7 +7,7 @@ BASEDPYRIGHT=1.40.2
RUFF=0.17.3
GOPLS=v0.24.0
JDTLS=1.63.0-202610191322
KOTLIN_LSP=271.2085.0
KOTLIN_LSP=271.3588.0
GRADLE=8.14.3
INTELEPHENSE=1.18.5
# The JDK projects compile against (JAVA_HOME): library navigation opens its sources.
+3 -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:
+2 -2
Переглянути файл
@@ -47,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"
@@ -111,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|lineNumberOptions|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
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
Створено
+72 -49
Переглянути файл
@@ -4154,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4185,7 +4185,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4197,7 +4197,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"ide-core",
"serde",
@@ -4209,7 +4209,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"blake3",
"chardetng",
@@ -4227,7 +4227,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4241,7 +4241,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4252,7 +4252,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"heck",
"proc-macro2",
@@ -4263,7 +4263,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4285,7 +4285,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"ide-core",
"ide-run",
@@ -4298,7 +4298,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4328,7 +4328,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4367,7 +4367,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"ide-core",
"serde",
@@ -4380,7 +4380,7 @@ dependencies = [
[[package]]
name = "ide-drag-out"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4394,7 +4394,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4414,7 +4414,7 @@ dependencies = [
[[package]]
name = "ide-flutter"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"ide-android",
"ide-core",
@@ -4425,7 +4425,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4437,7 +4437,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4449,7 +4449,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"criterion",
"ide-core",
@@ -4468,7 +4468,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4552,7 +4552,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"base64 0.22.1",
"http",
@@ -4575,7 +4575,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"blake3",
"criterion",
@@ -4598,7 +4598,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4610,7 +4610,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4626,7 +4626,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"libc",
"tempfile",
@@ -4635,7 +4635,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"futures",
"serde",
@@ -4646,7 +4646,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"blake3",
"criterion",
@@ -4672,6 +4672,7 @@ dependencies = [
"tree-sitter-css",
"tree-sitter-dart",
"tree-sitter-elixir",
"tree-sitter-fsharp",
"tree-sitter-gdscript",
"tree-sitter-go",
"tree-sitter-graphql",
@@ -4689,6 +4690,7 @@ dependencies = [
"tree-sitter-nix",
"tree-sitter-objc",
"tree-sitter-ocaml",
"tree-sitter-odin",
"tree-sitter-php",
"tree-sitter-prisma-io",
"tree-sitter-proto",
@@ -4706,7 +4708,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"criterion",
"dunce",
@@ -4736,7 +4738,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"bytes",
"dunce",
@@ -4755,7 +4757,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"futures",
"ide-core",
@@ -4780,7 +4782,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"blake3",
"dunce",
@@ -4802,7 +4804,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4816,7 +4818,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"dunce",
"futures",
@@ -4836,7 +4838,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"blake3",
"dunce",
@@ -4863,7 +4865,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"ide-core",
"ide-tools",
@@ -4879,7 +4881,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4905,7 +4907,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"criterion",
"encoding_rs",
@@ -4926,7 +4928,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"ide-core",
"parking_lot 0.12.5",
@@ -4939,7 +4941,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4964,7 +4966,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"ide-core",
"ide-language",
@@ -4977,7 +4979,7 @@ dependencies = [
[[package]]
name = "ide-svn"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"dunce",
"encoding_rs",
@@ -4992,7 +4994,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"ide-core",
"ide-language",
@@ -5007,7 +5009,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"ide-core",
"libc",
@@ -5021,7 +5023,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"criterion",
"ide-core",
@@ -5034,7 +5036,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -5061,7 +5063,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"blake3",
"dunce",
@@ -5083,7 +5085,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"chardetng",
"dunce",
@@ -5110,7 +5112,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5126,7 +5128,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"blake3",
"dunce",
@@ -6781,7 +6783,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.56"
version = "0.1.57"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -6826,6 +6828,7 @@ dependencies = [
"percent-encoding",
"reqwest",
"security-framework",
"semver",
"serde",
"serde_json",
"specta",
@@ -10395,6 +10398,16 @@ dependencies = [
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-fsharp"
version = "0.3.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "248fccdffd6f029b4932cf2c619b0a40ccaeab3c32764c237316a717c0c72aa2"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-gdscript"
version = "6.1.0"
@@ -10561,6 +10574,16 @@ dependencies = [
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-odin"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24db210fe9ba2237c71c5030d7b146c7025420ba72dd8013d13cd822c3a8d77a"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-php"
version = "0.25.1"
+1 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins", "vendor"]
[workspace.package]
version = "0.1.56"
version = "0.1.57"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+2 -2
Переглянути файл
@@ -10,7 +10,7 @@
</p>
<p align="center">
English · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a>
English · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a>
</p>
<p align="center">
@@ -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).
+85
Переглянути файл
@@ -0,0 +1,85 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="src-tauri/icons/source/openidea-wordmark-dark.svg">
<img src="src-tauri/icons/source/openidea-wordmark.svg" alt="OpenIDEA" height="56">
</picture>
</p>
<p align="center">
Знакомая вам IDE, переписанная на Rust.
</p>
<p align="center">
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a> · Русский
</p>
<p align="center">
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>Скачать</b></a>
&nbsp;·&nbsp;
<a href="https://openidea.sh">Документация</a>
&nbsp;·&nbsp;
<a href="#сравнение-производительности">Производительность</a>
&nbsp;·&nbsp;
<a href="#плагины">Плагины</a>
&nbsp;·&nbsp;
<a href="#сообщество">Сообщество</a>
</p>
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
OpenIDEA переносит привычные для пользователей IntelliJ IDEA сочетания клавиш, окна инструментов
и глобальный поиск в нативное приложение с ядром на Rust.
Редактор, средства анализа кода, отладчик, Git, терминал, клиенты для работы с базами данных и HTTP.
Поддержка более 60 языков. Сборки для macOS, Windows и Linux.
На macOS IDE также можно установить через Homebrew:
```bash
brew install --cask l0ng-ai/tap/openidea
```
## Сравнение производительности
Открытие проекта [freqtrade](https://github.com/freqtrade/freqtrade) (Python, около 770 файлов)
с прогретыми кешами, медиана пяти запусков:
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
| ---------------------------------------------- | ------------------- | ---------------------- |
| Появление окна с проектом | **0,9 с** | 3,1 с |
| Готовность (нагрузка на CPU стабилизировалась) | **1,1 с** | 13,2 с |
| Память (USS, все процессы) | **169 МБ** | 2011 МБ |
| Процессорное время до готовности | **2,4 с** | 47,9 с |
| Загрузка CPU в простое | **4 %** одного ядра | 7 % одного ядра |
| Завершение работы | **0,3 с** | 5,9 с |
В тесте использовались релизная сборка OpenIDEA из ветки `main` и IDEA с настройками и плагинами по умолчанию.
Окружение: Windows 11, 32-ядерный процессор AMD, 62 ГБ оперативной памяти.
IDEA глубже анализирует Python-код, поэтому к моменту готовности обе IDE выполняют разный объём работы.
Измерения обеих IDE проводились извне по одной методике: с помощью
[`perf/compare`](perf/compare) можно повторить тест на своём компьютере со своими проектами.
## Плагины
Плагины добавляют действия, автодополнение кода, быстрые исправления, окна инструментов, пользовательские редакторы,
темы оформления, значки файлов и поддержку языков. Они работают как компоненты WebAssembly в изолированной среде;
для тем оформления, тем значков и языков писать код не нужно.
Плагины можно установить в разделе «Настройки › Плагины» (Settings › Plugins) или создать собственный командой
`openidea-plugin new`. См. [руководство по созданию плагинов OpenIDEA](https://openidea.sh/en/plugins)
и [официальные плагины](plugins/official). API плагинов пока доступен в предварительной версии.
## Сообщество
- [Discord](https://discord.gg/AsZqMgxZm): вопросы, обратная связь и новости о релизах.
- Группа WeChat: отсканируйте QR-код, чтобы присоединиться.
<img src=".github/assets/wechat-group-5.png" alt="QR-код группы WeChat" width="200">
- Как внести вклад: см. [CONTRIBUTING.md](CONTRIBUTING.md) и [документацию для участников проекта](https://openidea.sh/en/contribute/setup).
## Лицензия
[Apache 2.0](LICENSE). Включённые в поставку сторонние ресурсы перечислены в [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md).
<sub>OpenIDEA не связан с JetBrains. IntelliJ IDEA — товарный знак JetBrains s.r.o.</sub>
+2 -2
Переглянути файл
@@ -10,7 +10,7 @@
</p>
<p align="center">
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · Türkçe
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · Türkçe · <a href="README.ru.md">Русский</a>
</p>
<p align="center">
@@ -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).
+2 -2
Переглянути файл
@@ -10,7 +10,7 @@
</p>
<p align="center">
<a href="README.md">English</a> · 简体中文
<a href="README.md">English</a> · 简体中文 · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a>
</p>
<p align="center">
@@ -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)。
+29 -1
Переглянути файл
@@ -4,7 +4,7 @@
`src/ui/brands/*.svg` use the unmodified logo paths from
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:odin`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
## DuckDB symbol
@@ -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`
+4 -4
Переглянути файл
@@ -24,7 +24,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
match run_once(shared, spec, prefer_stored, model).await {
Err(err)
if !prefer_stored
&& crate::provider::is_copilot_provider(&spec.id)
&& crate::provider::is_copilot_provider(spec.base_id())
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root)
&& super::auth_required(0, &err) =>
{
@@ -53,7 +53,7 @@ async fn run_once(
.await
.map_err(|e| e.to_string())??;
let cwd = dunce::canonicalize(&root).unwrap_or(root);
let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), ..Default::default() });
let updates = Arc::new(DiscoveryUpdates { provider: spec.base_id().to_owned(), ..Default::default() });
let client = Dialect::wrap(updates.clone());
let on_stderr: Box<dyn Fn(String) + Send + Sync> = Box::new(|_| {});
let peer = (shared.connector)(&launch, &cwd, client.clone(), on_stderr)
@@ -69,7 +69,7 @@ async fn run_once(
.await
.map_err(discovery_error)?;
let mut options = config::options_of(&new);
config::add_client_options(&launch.id, &mut options);
config::add_client_options(launch.base_id(), &mut options);
let model_option = options.iter().find(|o| o.category.as_deref() == Some("model"));
let mut levels = BTreeMap::new();
let has_config = new.get("configOptions").is_some_and(Value::is_array);
@@ -119,7 +119,7 @@ async fn run_once(
.commands
.lock()
.clone()
.or_else(|| new.get("availableCommands").map(|_| config::commands_of(&new, &launch.id)));
.or_else(|| new.get("availableCommands").map(|_| config::commands_of(&new, launch.base_id())));
Ok::<_, String>(Discovered { config: options, commands, levels })
};
let result = tokio::time::timeout(DISCOVER_TIMEOUT, work).await;
+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,
+1
Переглянути файл
@@ -189,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.");
+32 -11
Переглянути файл
@@ -254,7 +254,14 @@ impl AgentCatalogs {
}
let unavailable = || "The agent did not report settings for the selected model".to_owned();
let spec = shared.spec(provider).ok_or_else(unavailable)?;
let (_, flight) = self.request(shared, spec, false, Some(model));
let flight = {
let catalogs = self.clone();
let shared = shared.clone();
let model = model.to_owned();
tokio::task::spawn_blocking(move || catalogs.request(&shared, spec, false, Some(&model)).1)
.await
.map_err(|e| e.to_string())?
};
if let Some(mut ready) = flight {
while !*ready.borrow_and_update() {
if ready.changed().await.is_err() {
@@ -444,7 +451,22 @@ impl AgentCatalogs {
let flight_key = key.clone();
let task = shared.runtime.clone().spawn(async move {
let result = discover(&shared, spec, model.as_deref()).await;
coordinator.complete(&shared, flight_key, generation, model, result);
let current = {
let shared = shared.clone();
let provider_id = flight_key.2.clone();
tokio::task::spawn_blocking(move || {
shared
.paths
.provider_specs()
.into_iter()
.find(|spec| spec.id == provider_id)
.map(|spec| LaunchContext::new(spec, &shared.paths.project_root))
})
.await
.ok()
.flatten()
};
coordinator.complete(&shared, flight_key, generation, model, current, result);
let _ = done.send(true);
});
// A subscriber can re-enter and change configuration during the start event.
@@ -466,12 +488,9 @@ impl AgentCatalogs {
key: Key,
generation: u64,
model: Option<String>,
current: Option<LaunchContext>,
result: Result<Discovered, String>,
) {
let current = provider::load(shared.paths.custom_agents_dir.as_deref(), shared.env_secrets())
.into_iter()
.find(|spec| spec.id == key.2)
.map(|spec| LaunchContext::new(spec, &shared.paths.project_root));
let mut state = self.state.lock();
let Some(entry) = state.entries.get_mut(&key).filter(|e| e.generation == generation) else { return };
// Configuration may have changed without another refresh request arriving.
@@ -622,8 +641,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 +649,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'"))?;
@@ -676,7 +697,7 @@ async fn discover(
Ok(Discovered {
commands: Some(config::commands_of(
&serde_json::json!({ "availableCommands": found.commands }),
&spec.id,
spec.base_id(),
)),
config: config::options_of(&serde_json::json!({ "configOptions": found.options })),
levels: found
@@ -700,7 +721,7 @@ async fn discover(
Ok(found) => Ok(Discovered {
commands: Some(config::commands_of(
&serde_json::json!({ "availableCommands": found.commands }),
&spec.id,
spec.base_id(),
)),
config: config::options_of(&serde_json::json!({ "configOptions": found.options })),
levels: found
+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).
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
+42 -2
Переглянути файл
@@ -760,12 +760,21 @@ 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,
/// The built-in command can be owned by a global npm package.
#[serde(default)]
pub can_check_cli_update: bool,
/// The built-in agent this one is an instance of.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub base: Option<String>,
/// A built-in agent, of which another instance can be added.
#[serde(default)]
pub can_duplicate: bool,
/// Environment variables it starts with (from its agent file).
pub env: BTreeMap<String, String>,
/// Settings (models, modes…) the agent offered last time it ran; empty before its first session.
@@ -1055,6 +1064,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.
@@ -1081,6 +1098,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 {
@@ -1670,6 +1695,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,
@@ -1758,6 +1789,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>,
@@ -1845,13 +1882,16 @@ pub struct McpProbeResult {
pub error: Option<String>,
}
/// Payload for creating a custom ACP agent (always the ACP driver); the id
/// becomes the `<config>/agents/<id>.toml` file name.
/// Payload for creating a custom ACP agent, or an instance of built-in `base` (which
/// launches as its base does when `command` is empty); the id becomes the
/// `<config>/agents/<id>.toml` file name.
#[derive(Clone, Debug, Deserialize, Type)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CustomAgentInput {
pub id: String,
pub name: String,
#[serde(default)]
pub base: Option<String>,
pub command: String,
#[serde(default)]
pub args: Vec<String>,
+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,
+241 -4
Переглянути файл
@@ -125,11 +125,13 @@ 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(),
login_hint: String::new(),
source: crate::AgentSource::Builtin,
base: None,
};
let found = discover(spec, tmp.path().to_path_buf()).await.unwrap();
let models: Vec<_> = found
@@ -1019,10 +1021,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 +1166,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 +1301,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 +2276,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();
}
}
+14
Переглянути файл
@@ -881,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 {
+1 -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)
})
+168 -10
Переглянути файл
@@ -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`
@@ -16,8 +18,49 @@ pub(crate) mod codex;
pub(crate) mod copilot;
use ide_jsonrpc::{Framing, Handler, Peer};
use parking_lot::Mutex;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant, SystemTime};
const VERSION_CACHE_TTL: Duration = Duration::from_secs(60);
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct VersionCacheKey {
path: PathBuf,
modified: Option<SystemTime>,
len: Option<u64>,
#[cfg(unix)]
ino: Option<u64>,
}
impl VersionCacheKey {
fn of(real: &Path) -> Self {
let meta = std::fs::metadata(real).ok();
#[cfg(unix)]
let ino = meta.as_ref().map(std::os::unix::fs::MetadataExt::ino);
Self {
path: real.to_path_buf(),
modified: meta.as_ref().and_then(|m| m.modified().ok()),
len: meta.as_ref().map(std::fs::Metadata::len),
#[cfg(unix)]
ino,
}
}
}
struct CachedVersion {
version: Vec<u64>,
checked_at: Instant,
}
type VersionSlot = Arc<Mutex<Option<CachedVersion>>>;
fn version_cache() -> &'static Mutex<HashMap<VersionCacheKey, VersionSlot>> {
static CACHE: OnceLock<Mutex<HashMap<VersionCacheKey, VersionSlot>>> = OnceLock::new();
CACHE.get_or_init(Default::default)
}
/// The newest install of `command` on the `PATH` a child sees, by its `--version`.
/// Several installs are common (npm, Homebrew, the vendor's own installer), and the first
@@ -36,27 +79,69 @@ fn newest_install_in(command: &str, search: &std::ffi::OsStr) -> String {
let names =
ide_core::process::executable_names(command, cfg!(windows), pathext.as_deref().and_then(|p| p.to_str()));
let mut seen = Vec::new();
let candidates: Vec<PathBuf> = std::env::split_paths(search)
let candidates: Vec<(PathBuf, PathBuf)> = std::env::split_paths(search)
.filter(|d| !d.as_os_str().is_empty())
.flat_map(|dir| names.iter().map(move |n| dir.join(n)))
.filter(|p| p.is_file())
.filter(|p| {
let real = dunce::canonicalize(p).unwrap_or_else(|_| p.clone());
let new = !seen.contains(&real);
seen.push(real);
new
.filter_map(|p| {
let real = dunce::canonicalize(&p).unwrap_or_else(|_| p.clone());
if seen.contains(&real) {
return None;
}
seen.push(real.clone());
Some((p, real))
})
.collect();
if candidates.len() < 2 {
return candidates.into_iter().next().map_or_else(|| command.to_owned(), |p| p.to_string_lossy().into_owned());
return candidates
.into_iter()
.next()
.map_or_else(|| command.to_owned(), |(p, _)| p.to_string_lossy().into_owned());
}
// Probe distinct installs in parallel; per-binary cache + single-flight avoids re-spawning
// `--version` on concurrent or repeated lookups while still noticing upgraded binaries.
let versions: Vec<Option<Vec<u64>>> = std::thread::scope(|s| {
let handles: Vec<_> = candidates.iter().map(|(p, real)| s.spawn(|| cached_version_of(p, real))).collect();
handles.into_iter().map(|h| h.join().ok().flatten()).collect()
});
candidates
.into_iter()
.filter_map(|p| version_of(&p).map(|v| (v, p)))
.zip(versions)
.filter_map(|((p, _), v)| v.map(|v| (v, p)))
.max_by(|a, b| a.0.cmp(&b.0))
.map_or_else(|| command.to_owned(), |(_, p)| p.to_string_lossy().into_owned())
}
fn cached_version_of(program: &Path, real: &Path) -> Option<Vec<u64>> {
let key = VersionCacheKey::of(real);
let slot = {
let mut cache = version_cache().lock();
if cache.len() > 64 {
cache.retain(|_, slot| {
slot.try_lock()
.is_none_or(|guard| guard.as_ref().is_some_and(|c| c.checked_at.elapsed() < VERSION_CACHE_TTL))
});
}
cache.entry(key).or_default().clone()
};
let mut guard = slot.lock();
if let Some(cached) = guard.as_ref()
&& cached.checked_at.elapsed() < VERSION_CACHE_TTL
{
return Some(cached.version.clone());
}
match version_of(program) {
Some(version) => {
*guard = Some(CachedVersion { version: version.clone(), checked_at: Instant::now() });
Some(version)
}
None => {
*guard = None;
None
}
}
}
/// `x.y.z` from `<program> --version` ("codex-cli 0.164.0", "2.1.312 (Claude Code)").
fn version_of(program: &Path) -> Option<Vec<u64>> {
let mut cmd = std::process::Command::new(program);
@@ -142,4 +227,77 @@ mod tests {
assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy());
}
}
#[cfg(unix)]
#[test]
fn newest_install_caches_versions_and_invalidates_on_change() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let old = dir.path().join("old");
let new = dir.path().join("new");
let old_log = dir.path().join("old.log");
let new_log = dir.path().join("new.log");
for (path, log, version) in [(&old, &old_log, "2.9.0"), (&new, &new_log, "2.10.0")] {
std::fs::create_dir_all(path).unwrap();
let executable = path.join("agent");
std::fs::write(&executable, format!("#!/bin/sh\nprintf 'x\\n' >> '{}'\necho {version}\n", log.display()))
.unwrap();
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let search = std::env::join_paths([&old, &new]).unwrap();
assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy());
assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy());
assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 1);
assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1);
// Replacing the older binary with a newer version invalidates only its cache entry.
let upgraded = old.join("agent");
std::fs::write(&upgraded, format!("#!/bin/sh\nprintf 'x\\n' >> '{}'\necho 2.11.0\n", old_log.display()))
.unwrap();
std::fs::set_permissions(&upgraded, std::fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(newest_install_in("agent", &search), upgraded.to_string_lossy());
assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 2);
assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1);
}
#[cfg(unix)]
#[test]
fn newest_install_deduplicates_concurrent_probes() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let old = dir.path().join("old");
let new = dir.path().join("new");
let old_log = dir.path().join("old.log");
let new_log = dir.path().join("new.log");
for (path, log, version) in [(&old, &old_log, "2.9.0"), (&new, &new_log, "2.10.0")] {
std::fs::create_dir_all(path).unwrap();
let executable = path.join("agent");
std::fs::write(
&executable,
format!("#!/bin/sh\nsleep 0.05\nprintf 'x\\n' >> '{}'\necho {version}\n", log.display()),
)
.unwrap();
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let search = std::env::join_paths([&old, &new]).unwrap();
let expected = new.join("agent").to_string_lossy().into_owned();
let barrier = std::sync::Barrier::new(4);
std::thread::scope(|s| {
let handles: Vec<_> = (0..4)
.map(|_| {
s.spawn(|| {
barrier.wait();
newest_install_in("agent", &search)
})
})
.collect();
for handle in handles {
assert_eq!(handle.join().unwrap(), expected);
}
});
assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 1);
assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1);
}
}
+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,")));
}
}
+411 -27
Переглянути файл
@@ -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,
@@ -42,6 +43,8 @@ pub(crate) struct ProviderSpec {
/// How to sign in when the agent reports it needs authentication.
pub login_hint: String,
pub source: AgentSource,
/// The built-in agent an instance copies (its identity); `None` for every other agent.
pub base: Option<String>,
}
/// `(id, name, driver, command line, sign-in hint)`. npm adapters are pinned so a
@@ -90,6 +93,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,22 +104,33 @@ 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(),
login_hint: (*hint).into(),
source: AgentSource::Builtin,
base: None,
})
.collect()
}
impl ProviderSpec {
/// The built-in id this agent is an instance of, or else its own id.
pub(crate) fn base_id(&self) -> &str {
self.base.as_deref().unwrap_or(&self.id)
}
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();
}
let search = ide_core::tool_path::search_path();
let builtin = builtin_spec(&self.id);
let builtin = builtin_spec(self.base_id());
let on_path = builtin.as_ref().and_then(|b| ide_core::process::find_executable(&b.command, &search));
render_login_hint(self, program, on_path.as_deref(), cfg!(windows))
}
@@ -135,7 +150,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),
@@ -154,7 +169,7 @@ impl ProviderSpec {
cwd: &Path,
strip_ambient_tokens: bool,
) -> Result<Self, String> {
let is_copilot = is_copilot_provider(&self.id);
let is_copilot = is_copilot_provider(self.base_id());
let account = is_copilot.then(|| copilot_github_account(&self.env)).flatten();
let explicit_copilot_token =
self.env.iter().any(|(name, value)| name == "COPILOT_GITHUB_TOKEN" && !value.is_empty());
@@ -179,10 +194,12 @@ 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) {
if is_copilot_provider(self.base_id()) {
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
}
@@ -208,7 +225,7 @@ impl ProviderSpec {
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
};
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
if let Some((separate_cmd, separate_args)) = match self.base_id() {
"claude-acp" => Some(("claude", &[][..])),
"codex-acp" => Some(("codex", &["login"][..])),
"vibe" => Some(("vibe", &[][..])),
@@ -222,7 +239,9 @@ impl ProviderSpec {
});
}
if let Some(builtin) = builtin_spec(&self.id) {
if let Some(builtin) = builtin_spec(self.base_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)
@@ -230,7 +249,7 @@ impl ProviderSpec {
let resolved = self.clone().resolve_for_launch_base(cwd, true);
let program = resolve_exe(&resolved.command, &resolved.env)?;
let mut env: BTreeMap<String, String> = resolved.env.into_iter().collect();
if is_copilot_provider(&self.id) {
if is_copilot_provider(self.base_id()) {
for key in AMBIENT_COPILOT_AUTH_VARS {
env.insert(key.to_owned(), String::new());
}
@@ -521,7 +540,7 @@ pub(crate) fn sanitize_copilot_env_with(
}
fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>, windows: bool) -> String {
let Some(builtin) = builtin_spec(&spec.id) else { return spec.login_hint.clone() };
let Some(builtin) = builtin_spec(spec.base_id()) else { return spec.login_hint.clone() };
let prefix = format!("Run `{}", builtin.command);
let Some(rest) = spec.login_hint.strip_prefix(&prefix).filter(|rest| rest.starts_with([' ', '`'])) else {
return spec.login_hint.clone();
@@ -533,7 +552,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 +560,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 +608,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")
}
@@ -598,6 +628,8 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
let builtin = builtin_spec(&spec.id);
let reason = if matches!(spec.source, AgentSource::Registry { .. }) {
Some(AgentCommandReadOnlyReason::Registry)
} else if spec.base.is_some() {
Some(AgentCommandReadOnlyReason::CustomAgent)
} else if let Some(default) = &builtin {
uses_package_runner(&default.command).then_some(AgentCommandReadOnlyReason::PackageRunner)
} else {
@@ -610,22 +642,25 @@ 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(),
base: spec.base.clone(),
can_duplicate: builtin.is_some(),
env: spec.env.iter().cloned().collect(),
config: vec![],
thought_levels: BTreeMap::new(),
@@ -664,13 +699,17 @@ pub(crate) fn set_builtin_additional_args(
})
}
/// The environment built-in `id` starts with, through its agent file (empty clears it).
/// The environment built-in `id` (or an instance of one) starts with, through its agent file
/// (empty clears it).
pub(crate) fn set_builtin_env(
custom_dir: &Path,
secrets: Option<&dyn EnvSecrets>,
id: &str,
env: BTreeMap<String, String>,
) -> IdeResult<()> {
if builtin_spec(id).is_none() {
return set_instance_env(custom_dir, secrets, id, env);
}
if id == "copilot" {
let file = custom_dir.join("copilot.toml");
if file.try_exists()?
@@ -702,6 +741,26 @@ pub(crate) fn set_builtin_env(
})
}
/// An instance's environment is all its own: never merged with its base's.
fn set_instance_env(
custom_dir: &Path,
secrets: Option<&dyn EnvSecrets>,
id: &str,
env: BTreeMap<String, String>,
) -> IdeResult<()> {
let id = validated_custom_id(id)?;
let _lock = lock_custom_agents(custom_dir)?;
let file = custom_dir.join(format!("{id}.toml"));
let mut agent = match CustomAgent::read_with(&file, &id, secrets) {
Ok(agent) if agent.registry.is_none() && agent.base.as_deref().is_some_and(|b| builtin_spec(b).is_some()) => {
agent
}
_ => return Err(IdeError::invalid(format!("{id} is not a built-in agent or an instance of one"))),
};
agent.env = env;
agent.write_with(&file, &id, secrets)
}
/// Changes built-in `id`'s agent file; a file left with only the built-in's values is removed.
fn update_builtin(
custom_dir: &Path,
@@ -718,6 +777,7 @@ fn update_builtin(
} else {
CustomAgent {
name: Some(builtin.name.clone()),
base: None,
driver: builtin.driver,
command: builtin.command.clone(),
args: builtin.args.clone(),
@@ -747,9 +807,24 @@ 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.
/// a safe file stem. An instance of a built-in (`base`) may leave the command
/// empty to launch as its base does.
pub(crate) fn save_custom(
custom_dir: &Path,
secrets: Option<&dyn EnvSecrets>,
@@ -759,9 +834,20 @@ pub(crate) fn save_custom(
if builtin_spec(&id).is_some() {
return Err(IdeError::invalid(format!("{id} is a built-in agent; change its command instead")));
}
if input.command.trim().is_empty() {
let base = match input.base.as_deref() {
Some(base) => {
Some(builtin_spec(base).ok_or_else(|| IdeError::invalid(format!("{base} is not a built-in agent")))?)
}
None => None,
};
let inherits = input.command.trim().is_empty();
if inherits && base.is_none() {
return Err(IdeError::invalid("the agent command must not be empty"));
}
if inherits && !input.args.is_empty() {
return Err(IdeError::invalid("an agent without its own command takes no arguments"));
}
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()) {
@@ -773,8 +859,9 @@ pub(crate) fn save_custom(
}
CustomAgent {
name: Some(input.name.clone()),
driver: Driver::Acp,
command: input.command.clone(),
driver: base.as_ref().filter(|_| !inherits).map_or(Driver::Acp, |b| b.driver),
command: if inherits { String::new() } else { input.command.clone() },
base: base.map(|b| b.id),
args: input.args.clone(),
additional_args: Vec::new(),
env: input.env.clone(),
@@ -790,6 +877,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 +917,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);
@@ -844,6 +933,7 @@ pub(crate) fn import_acp(
} else {
CustomAgent {
name: Some(outcome.name.clone()),
base: None,
driver: Driver::Acp,
command: server.command,
args: server.args,
@@ -886,8 +976,12 @@ pub(crate) fn slugify_id(name: &str) -> String {
pub(crate) struct CustomAgent {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// The built-in agent this one is an instance of; without a `command` it launches as the base does.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub base: Option<String>,
#[serde(default, skip_serializing_if = "Driver::is_acp")]
pub driver: Driver,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub command: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub args: Vec<String>,
@@ -916,9 +1010,13 @@ impl Driver {
impl CustomAgent {
pub(crate) fn read(path: &Path) -> Result<Self, String> {
std::fs::read_to_string(path)
let agent = std::fs::read_to_string(path)
.map_err(|e| e.to_string())
.and_then(|t| toml::from_str::<CustomAgent>(&t).map_err(|e| e.to_string()))
.and_then(|t| toml::from_str::<CustomAgent>(&t).map_err(|e| e.to_string()))?;
if agent.command.is_empty() && agent.base.is_none() {
return Err("missing field `command`".into());
}
Ok(agent)
}
/// Writes the file atomically (a reader never sees half of it).
@@ -990,7 +1088,8 @@ fn forget_env(secrets: Option<&dyn EnvSecrets>, id: &str, keep: &[String]) {
}
/// Built-in agents, then the `*.toml` agents of `custom_dir`; a custom agent with a
/// built-in id replaces it.
/// built-in id replaces it. Instances of a built-in (`base`) are resolved last, against
/// the built-in as its own file left it, so file order does not matter.
pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>) -> Vec<ProviderSpec> {
let mut specs = builtins();
let mut files: Vec<PathBuf> = custom_dir
@@ -1002,6 +1101,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
.filter(|p| p.extension().is_some_and(|e| e == "toml"))
.collect();
files.sort();
let mut instances = Vec::new();
for path in files {
let Some(id) = path.file_stem().and_then(|s| s.to_str()).map(str::to_owned) else { continue };
let explicit_driver = std::fs::read_to_string(&path)
@@ -1015,6 +1115,18 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
continue;
}
};
if let Some(base) = agent.base.clone() {
if builtin_spec(&id).is_some() {
tracing::warn!("skipping agent {}: a built-in agent cannot have a base", path.display());
} else if agent.registry.is_some() {
tracing::warn!("skipping agent {}: an ACP Registry install cannot have a base", path.display());
} else if builtin_spec(&base).is_none() {
tracing::warn!("skipping agent {}: {base} is not a built-in agent", path.display());
} else {
instances.push((id, agent));
}
continue;
}
let env: Vec<(String, String)> = agent.env.into_iter().collect();
let source = match agent.registry {
Some(r) => AgentSource::Registry { version: r.version, update: None },
@@ -1024,16 +1136,20 @@ 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,
login_hint: "Sign in with the agent's own command line first.".into(),
source,
base: None,
id,
};
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
@@ -1054,6 +1170,34 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
None => specs.push(spec),
}
}
for (id, agent) in instances {
let base = agent.base.expect("instances have a base");
let Some(base_spec) = specs.iter().find(|s| s.id == base && s.base.is_none()) else { continue };
let (driver, command, args) = if agent.command.is_empty() {
(base_spec.driver, base_spec.command.clone(), base_spec.args.clone())
} else {
(agent.driver, agent.command, agent.args)
};
let login_hint = base_spec.login_hint.clone();
// Copies of one agent follow it, in the order of their file names.
let at = specs.iter().rposition(|s| s.base_id() == base).map_or(specs.len(), |i| i + 1);
specs.insert(
at,
ProviderSpec {
name: agent.name.unwrap_or_else(|| id.clone()),
driver,
command,
managed_cli: None,
args,
additional_args_len: 0,
env: agent.env.into_iter().collect(),
login_hint,
source: AgentSource::Custom,
base: Some(base),
id,
},
);
}
specs
}
@@ -1102,6 +1246,56 @@ 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()),
base: None,
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 +1348,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 +1423,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 +1475,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();
@@ -1416,6 +1611,7 @@ mod tests {
let file = dir.path().join("copilot.toml");
CustomAgent {
name: Some("GitHub Copilot".into()),
base: None,
driver: Driver::Acp,
command: "/tools/copilot".into(),
args: vec!["--acp".into()],
@@ -1473,6 +1669,7 @@ mod tests {
let path = dir.path().join("codex.toml");
CustomAgent {
name: None,
base: None,
driver: Driver::Acp,
command: "amp".into(),
args: vec![],
@@ -1499,6 +1696,7 @@ mod tests {
for field in ["name", "driver", "args", "env", "unnamed"] {
let mut agent = CustomAgent {
name: Some("Claude Code".into()),
base: None,
driver: Driver::Claude,
command: "/old/claude".into(),
args: vec![],
@@ -1553,6 +1751,7 @@ mod tests {
let path = dir.path().join("agents").join("amp-acp.toml");
let agent = CustomAgent {
name: Some("Amp".into()),
base: None,
driver: Driver::Acp,
command: "/data/agents/tools/amp-acp/0.10.0/amp-acp".into(),
args: vec!["acp".into()],
@@ -1573,6 +1772,7 @@ mod tests {
CustomAgentInput {
id: id.into(),
name: "Mine".into(),
base: None,
command: "/opt/mine".into(),
args: vec!["acp".into()],
env: BTreeMap::from([("K".to_owned(), "v".to_owned())]),
@@ -1794,4 +1994,188 @@ github.com
assert_eq!(launch.env.get("GH_TOKEN").map(String::as_str), Some(""));
assert_eq!(launch.env.get("COPILOT_GITHUB_TOKEN").map(String::as_str), Some(""));
}
fn write_agent(dir: &Path, id: &str, text: &str) {
std::fs::write(dir.join(format!("{id}.toml")), text).unwrap();
}
fn spec_of(dir: &Path, id: &str) -> Option<ProviderSpec> {
load(Some(dir), None).into_iter().find(|s| s.id == id)
}
#[test]
fn instances_inherit_the_base_launch_whatever_the_file_order() {
let dir = tempfile::tempdir().unwrap();
let instance =
"base = \"claude\"\nname = \"Claude Work\"\n[env]\nCLAUDE_CONFIG_DIR = \"/home/me/.claude-work\"\n";
// `a-claude` sorts before the base's own file, `z-claude` after it.
write_agent(dir.path(), "a-claude", instance);
write_agent(dir.path(), "z-claude", instance);
write_agent(
dir.path(),
"claude",
"name = \"Claude Code\"\ndriver = \"claude\"\ncommand = \"/opt/claude\"\n[env]\nB = \"1\"\n",
);
let builtin = builtin_spec("claude").unwrap();
for id in ["a-claude", "z-claude"] {
let spec = spec_of(dir.path(), id).unwrap();
assert_eq!((spec.driver, spec.command.as_str()), (Driver::Claude, "/opt/claude"), "{id}");
assert_eq!(spec.args, builtin.args);
assert_eq!(spec.env, [("CLAUDE_CONFIG_DIR".to_owned(), "/home/me/.claude-work".to_owned())]);
assert_eq!(spec.login_hint, builtin.login_hint);
assert_eq!(
(&spec.source, spec.base.as_deref(), spec.base_id()),
(&AgentSource::Custom, Some("claude"), "claude")
);
assert_eq!(spec.name, "Claude Work");
}
std::fs::remove_file(dir.path().join("claude.toml")).unwrap();
assert_eq!(spec_of(dir.path(), "a-claude").unwrap().command, "claude");
}
#[test]
fn instances_follow_their_base_in_the_list() {
let dir = tempfile::tempdir().unwrap();
write_agent(dir.path(), "z-claude", "base = \"claude\"\n");
write_agent(dir.path(), "a-claude", "base = \"claude\"\n");
write_agent(dir.path(), "codex-2", "base = \"codex\"\n");
write_agent(dir.path(), "mine", "command = \"/opt/mine\"\n");
let ids: Vec<String> = load(Some(dir.path()), None).into_iter().map(|s| s.id).collect();
let at = |id: &str| ids.iter().position(|i| i == id).unwrap();
assert_eq!((at("a-claude"), at("z-claude")), (at("claude") + 1, at("claude") + 2));
assert_eq!(at("codex-2"), at("codex") + 1);
assert_eq!(at("mine"), ids.len() - 1);
}
#[test]
fn an_instance_with_its_own_command_keeps_it() {
let dir = tempfile::tempdir().unwrap();
write_agent(
dir.path(),
"codex-2",
"base = \"codex\"\ndriver = \"codex\"\ncommand = \"/opt/codex2\"\nargs = [\"app-server\", \"-v\"]\n",
);
write_agent(dir.path(), "codex", "driver = \"codex\"\ncommand = \"/opt/codex\"\nargs = [\"app-server\"]\n");
let spec = spec_of(dir.path(), "codex-2").unwrap();
assert_eq!((spec.driver, spec.command.as_str()), (Driver::Codex, "/opt/codex2"));
assert_eq!(spec.args, ["app-server", "-v"]);
assert_eq!(spec.base.as_deref(), Some("codex"));
assert_eq!(spec.login_hint, builtin_spec("codex").unwrap().login_hint);
}
#[test]
fn invalid_instances_are_skipped() {
let dir = tempfile::tempdir().unwrap();
write_agent(dir.path(), "unknown-base", "base = \"nope\"\n");
write_agent(dir.path(), "first", "base = \"claude\"\n");
write_agent(dir.path(), "chained", "base = \"first\"\n");
write_agent(dir.path(), "codex", "base = \"claude\"\n");
write_agent(dir.path(), "no-command", "name = \"Nothing\"\n");
let specs = load(Some(dir.path()), None);
let ids: Vec<&str> = specs.iter().filter(|s| s.source != AgentSource::Builtin).map(|s| s.id.as_str()).collect();
assert_eq!(ids, ["first"]);
assert_eq!(specs.iter().find(|s| s.id == "codex").unwrap(), &builtin_spec("codex").unwrap());
}
#[test]
fn save_custom_writes_instances() {
let dir = tempfile::tempdir().unwrap();
let instance = |id: &str, base: &str| CustomAgentInput {
base: Some(base.into()),
command: String::new(),
args: Vec::new(),
..custom_input(id)
};
save_custom(dir.path(), None, &instance("work", "claude")).unwrap();
let text = std::fs::read_to_string(dir.path().join("work.toml")).unwrap();
assert!(text.contains("base = \"claude\"") && !text.contains("command") && !text.contains("driver"), "{text}");
let spec = spec_of(dir.path(), "work").unwrap();
assert_eq!(
(spec.driver, spec.command.as_str(), spec.base.as_deref()),
(Driver::Claude, "claude", Some("claude"))
);
save_custom(dir.path(), None, &CustomAgentInput { command: "/opt/codex".into(), ..instance("own", "codex") })
.unwrap();
let own = spec_of(dir.path(), "own").unwrap();
assert_eq!((own.driver, own.command.as_str()), (Driver::Codex, "/opt/codex"));
save_custom(dir.path(), None, &instance("work", "claude")).unwrap_err();
save_custom(dir.path(), None, &instance("other", "nope")).unwrap_err();
save_custom(dir.path(), None, &instance("other", "work")).unwrap_err();
save_custom(dir.path(), None, &instance("codex", "claude")).unwrap_err();
save_custom(dir.path(), None, &CustomAgentInput { args: vec!["x".into()], ..instance("other", "claude") })
.unwrap_err();
assert!(!dir.path().join("other.toml").exists());
}
#[test]
fn instances_describe_their_base() {
let dir = tempfile::tempdir().unwrap();
write_agent(dir.path(), "work", "base = \"claude\"\n");
save_custom(dir.path(), None, &custom_input("mine")).unwrap();
let info = |id: &str| describe(&spec_of(dir.path(), id).unwrap());
let work = info("work");
assert_eq!(work.base.as_deref(), Some("claude"));
assert!(!work.can_duplicate && !work.can_check_cli_update && !work.command_editable);
assert_eq!(work.command_read_only_reason, Some(AgentCommandReadOnlyReason::CustomAgent));
assert_eq!(work.login_hint.as_deref(), Some("Run `claude` in a terminal and sign in."));
let claude = info("claude");
assert!(claude.can_duplicate && claude.base.is_none());
let mine = info("mine");
assert!(!mine.can_duplicate && mine.base.is_none());
}
#[cfg(unix)]
#[test]
fn instances_sign_in_with_their_own_environment() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join("claude");
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
write_agent(dir.path(), "claude", &format!("driver = \"claude\"\ncommand = {:?}\n", bin.to_string_lossy()));
write_agent(dir.path(), "work", "base = \"claude\"\n[env]\nCLAUDE_CONFIG_DIR = \"/home/me/.claude-work\"\n");
let spec = spec_of(dir.path(), "work").unwrap();
assert!(spec.can_sign_in(dir.path(), None));
let launch = spec.login_launch(dir.path(), None).unwrap();
assert_eq!(launch.program, bin);
assert!(launch.args.is_empty());
assert_eq!(launch.env.get("CLAUDE_CONFIG_DIR").map(String::as_str), Some("/home/me/.claude-work"));
}
#[test]
fn instance_environment_is_set_and_forgotten_through_the_secrets() {
let dir = tempfile::tempdir().unwrap();
let secrets = MemorySecrets::default();
let s = Some(&secrets as &dyn EnvSecrets);
let instance = CustomAgentInput {
base: Some("copilot".into()),
command: String::new(),
args: Vec::new(),
env: BTreeMap::new(),
..custom_input("copilot-work")
};
save_custom(dir.path(), s, &instance).unwrap();
let env = BTreeMap::from([
(COPILOT_GITHUB_ACCOUNT_ENV.to_owned(), "octo-work".to_owned()),
("COPILOT_HOME".to_owned(), "/home/me/.copilot-work".to_owned()),
]);
set_builtin_env(dir.path(), s, "copilot-work", env.clone()).unwrap();
let text = std::fs::read_to_string(dir.path().join("copilot-work.toml")).unwrap();
assert!(text.contains("base = \"copilot\"") && !text.contains("octo-work"), "{text}");
let spec = load(Some(dir.path()), s).into_iter().find(|p| p.id == "copilot-work").unwrap();
assert_eq!(describe(&spec).env, env);
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("octo-work"));
assert!(load(Some(dir.path()), s).iter().find(|p| p.id == "copilot").unwrap().env.is_empty());
save_custom(dir.path(), s, &custom_input("mine")).unwrap();
set_builtin_env(dir.path(), s, "mine", env.clone()).unwrap_err();
write_agent(dir.path(), "bad-base", "base = \"nope\"\n");
set_builtin_env(dir.path(), s, "bad-base", env).unwrap_err();
assert!(secrets.keys("agent/bad-base/").is_empty());
remove_custom(dir.path(), s, "copilot-work").unwrap();
assert!(!dir.path().join("copilot-work.toml").exists());
assert!(secrets.keys("agent/copilot-work/").is_empty());
}
}
+3
Переглянути файл
@@ -587,6 +587,7 @@ fn install_entry_with(
}
let agent = CustomAgent {
name: Some(entry.name.clone()),
base: None,
driver: Driver::Acp,
command: exe.to_string_lossy().into_owned(),
args,
@@ -985,6 +986,7 @@ mod tests {
let entries = parse(INDEX).unwrap();
let installed = |id: &str, version: &str| CustomAgent {
name: None,
base: None,
driver: Driver::Acp,
command: "/x".into(),
args: vec![],
@@ -1222,6 +1224,7 @@ esac
CustomAgent {
name: Some("GitHub Copilot".into()),
base: None,
driver: Driver::Acp,
command: "/data/tools/copilot/1.0.104/node_modules/.bin/copilot".into(),
args: vec!["--acp".into()],
+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");
}
}
+329 -6
Переглянути файл
@@ -49,6 +49,8 @@ struct FakeAgent {
/// Hold the late mode reply until the prompt's permission request is already waiting.
hold_late_mode: bool,
empty_config: AtomicBool,
/// Text sent as an agent message when a session opens, before any prompt (pi-acp's startup info).
startup_notice: Mutex<Option<String>>,
/// Blocks `session/new` until discovery times out (see `acp::discover` test timeout).
hold_session_new: AtomicBool,
/// Sleeps this long at the start of `session/set_config_option`, after noting the time.
@@ -65,6 +67,8 @@ 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.
@@ -219,6 +223,9 @@ impl Handler for FakeAgent {
std::thread::sleep(Duration::from_millis(10));
}
}
if let Some(notice) = self.startup_notice.lock().clone() {
self.say("s1", &notice);
}
if self.empty_config.load(Ordering::Acquire) {
return Ok(json!({"sessionId": "s1"}));
}
@@ -230,7 +237,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"]));
@@ -655,6 +668,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");
@@ -674,6 +711,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.
@@ -886,6 +924,37 @@ async fn an_ephemeral_task_is_not_saved_and_asks_for_an_unsaved_session() {
}
}
#[tokio::test(flavor = "multi_thread")]
async fn text_the_agent_sends_before_the_prompt_is_not_part_of_the_reply() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.startup_notice.lock() = Some("pi v1.5.2\n---\n## Context\n- AGENTS.md\n".into());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude".into(),
isolation: Isolation::Local,
ephemeral: true,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let replies: Vec<String> = mgr
.entries(&task.id, None)
.unwrap()
.into_iter()
.filter_map(|e| match e {
AgentEntry::Agent { text } => Some(text),
_ => None,
})
.collect();
assert_eq!(replies.last().map(String::as_str), Some("second turn"));
assert!(replies.iter().any(|t| t.starts_with("pi v1.5.2")));
shut_down(&mgr, &agent).await;
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn claude_commands_share_catalog_discovery_and_persist_results() {
@@ -1362,6 +1431,31 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
assert_eq!(names(mgr_a.providers().into_iter().find(|p| p.id == "claude").unwrap().commands), ["review"]);
}
fn instance_of(id: &str, base: &str) -> crate::CustomAgentInput {
crate::CustomAgentInput {
id: id.into(),
name: id.into(),
base: Some(base.into()),
command: String::new(),
args: Vec::new(),
env: std::collections::BTreeMap::new(),
}
}
#[tokio::test(flavor = "multi_thread")]
async fn instances_offer_the_commands_of_their_base() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager_at(tmp.path(), &tmp.path().join("models.json"), agent);
mgr.save_custom_agent(instance_of("codex-work", "codex")).unwrap();
mgr.reload_providers();
assert_eq!((mgr.base_provider_id("codex-work"), mgr.base_provider_id("custom")), ("codex".into(), "custom".into()));
let names = |commands: Vec<AgentCommand>| commands.into_iter().map(|c| c.name).collect::<Vec<_>>();
let instance = names(mgr.commands("codex-work", None).await.unwrap());
assert!(instance.iter().any(|name| name == "review"), "{instance:?}");
assert_eq!(instance, names(mgr.commands("codex", None).await.unwrap()));
}
#[tokio::test(flavor = "multi_thread")]
async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metadata() {
let tmp = tempfile::tempdir().unwrap();
@@ -2239,14 +2333,25 @@ async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_ag
assert_eq!(calls(&agent), ["session/load", "session/new", "session/prompt"]);
}
/// A locked Codex recording can be forked without resuming it or moving its writer between tasks.
/// A locked Codex recording can be forked without resuming it or moving its writer between tasks,
/// also when the task runs an instance of Codex.
#[tokio::test(flavor = "multi_thread")]
async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
for provider in ["codex", "codex-work"] {
codex_writer_conflict_forks_on_a_new_connection(provider).await;
}
}
async fn codex_writer_conflict_forks_on_a_new_connection(provider: &str) {
let tmp = tempfile::tempdir().unwrap();
let task = {
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
if provider != "codex" {
mgr.save_custom_agent(instance_of(provider, "codex")).unwrap();
mgr.reload_providers();
}
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "codex".into(), ..Default::default() })
.create(NewAgentTask { prompt: text("again"), provider: provider.into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
@@ -3137,6 +3242,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,
@@ -3480,6 +3586,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();
@@ -3576,6 +3738,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();
@@ -4066,6 +4301,59 @@ async fn cursor_approval_switch_resolves_pending_and_survives_restart() {
mgr.shutdown();
}
/// Saving or dropping a Cursor instance on disk is reflected on the very first `providers()` call.
#[tokio::test(flavor = "multi_thread")]
async fn new_cursor_instance_has_approval_option_on_first_providers_call() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let _down = ShutDown(&mgr);
// Saved through the API: base_provider_id and providers() see it immediately without reload_providers().
mgr.save_custom_agent(instance_of("cursor-work", "cursor")).unwrap();
assert_eq!(mgr.base_provider_id("cursor-work"), "cursor");
// Hand-written on disk: providers() updates its cache before mapping per-provider options.
std::fs::write(tmp.path().join("agents/cursor-disk.toml"), "base = \"cursor\"\nname = \"Cursor Disk\"\n").unwrap();
let list = mgr.providers();
for id in ["cursor-work", "cursor-disk"] {
let info = list.iter().find(|p| p.id == id).unwrap_or_else(|| panic!("{id}"));
assert!(info.config.iter().any(|o| o.id == config::CURSOR_APPROVAL), "{id}: {:?}", info.config);
}
}
/// An instance of Cursor offers Cursor's client-side approval option, and a scheduled turn
/// clamps it as it clamps Cursor's own.
#[tokio::test(flavor = "multi_thread")]
async fn instances_take_the_approval_options_and_automation_clamp_of_their_base() {
for provider in ["cursor", "cursor-work"] {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let _down = ShutDown(&mgr);
mgr.save_custom_agent(instance_of("cursor-work", "cursor")).unwrap();
mgr.reload_providers();
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: provider.into(),
config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }],
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let approval = || {
let snapshot = mgr.task_snapshot(&task.id).unwrap();
snapshot.config.iter().find(|o| o.id == config::CURSOR_APPROVAL).and_then(|o| o.current.clone())
};
assert_eq!(approval().as_deref(), Some("bypass"), "{provider}");
let meta = ScheduledTurnMeta {
permissions: Some(automation::AutomationPermissionMode::Default),
..Default::default()
};
mgr.prompt_scheduled(&task.id, text("again"), meta).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(approval().as_deref(), Some("ask"), "{provider}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn bypass_approvals_keeps_both_question_dialects_pending_but_allows_permissions() {
for prompt in ["ask", "qwen ask"] {
@@ -4521,6 +4809,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,
@@ -4586,6 +4875,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,
@@ -4849,6 +5139,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,
@@ -4906,14 +5197,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")]
@@ -6354,6 +6652,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(),
@@ -6370,6 +6670,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,
},
]
}));
@@ -6676,6 +6978,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,
@@ -6799,6 +7102,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,
@@ -7449,3 +7753,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;
}
+11 -2
Переглянути файл
@@ -20,6 +20,8 @@ pub(crate) struct Timeline {
cards: HashMap<String, usize>,
/// Session messages, by message id.
messages: HashMap<String, usize>,
/// The next agent text starts an entry of its own (see [`Timeline::seal`]).
sealed: bool,
}
/// What a `session/update` changed in the timeline.
@@ -138,10 +140,17 @@ impl Timeline {
out
}
/// A prompt is being sent: text the agent sent before it (a startup notice) is not the
/// start of the reply, so the reply's text gets an entry of its own.
pub fn seal(&mut self) {
self.sealed = true;
}
fn append_text(&mut self, thought: bool, text: &str) -> usize {
let sealed = std::mem::take(&mut self.sealed);
match self.entries.last_mut() {
Some(AgentEntry::Agent { text: t }) if !thought => t.push_str(text),
Some(AgentEntry::Thought { text: t, .. }) if thought => t.push_str(text),
Some(AgentEntry::Agent { text: t }) if !thought && !sealed => t.push_str(text),
Some(AgentEntry::Thought { text: t, .. }) if thought && !sealed => t.push_str(text),
_ => {
let text = text.to_owned();
return self.push(if thought {
+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"}}
+244 -19
Переглянути файл
@@ -359,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>> {
@@ -571,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()) {
@@ -959,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.
@@ -995,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.
@@ -2062,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() {
@@ -2231,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 })
}
+75 -13
Переглянути файл
@@ -543,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).
@@ -587,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());
}
@@ -616,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
}
@@ -960,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)?;
}
}
@@ -1027,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);
@@ -1228,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;
+121 -1
Переглянути файл
@@ -416,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(&[
@@ -592,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",
@@ -607,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(&[
+56 -3
Переглянути файл
@@ -103,9 +103,19 @@ pub fn load_linked_with_jdk(
let mut m = maven::load_with_linked_jdk(root, repo, &profiles, maven_jdk_version, &settings.linked_projects);
maven::UnlinkedProjects::from_model(&m, settings).filter(&mut m);
// The user settings' profiles can be chosen too (`-P` applies to them as well).
for p in maven::user_settings_file(root, settings).map(|f| maven::settings_profiles(&f)).unwrap_or_default() {
if !m.profiles.iter().any(|x| x.id == p.id) {
m.profiles.push(p);
if let Some(settings_file) = maven::user_settings_file(root, settings) {
for p in maven::settings_profiles(&settings_file) {
if let Some(existing) = m.profiles.iter_mut().find(|x| x.id == p.id) {
existing.active_by_default |= p.active_by_default;
} else {
m.profiles.push(p);
}
}
let active_in_settings = maven::settings_active_profiles(&settings_file);
for existing in &mut m.profiles {
if active_in_settings.iter().any(|id| id == &existing.id) {
existing.active_by_default = true;
}
}
}
sync::apply_maven_cache(root, cache_dir, &mut m);
@@ -358,6 +368,49 @@ mod tests {
assert!(modules(&settings).is_empty());
}
#[test]
fn settings_xml_active_profiles_mark_pom_profiles_active_by_default() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir(root.join("child")).unwrap();
std::fs::write(
root.join("pom.xml"),
r#"<project><groupId>demo</groupId><artifactId>root</artifactId><version>1.0</version><packaging>pom</packaging>
<modules><module>child</module></modules>
<profiles>
<profile><id>test3</id></profile>
<profile><id>dev</id><activation><activeByDefault>TRUE</activeByDefault></activation></profile>
</profiles></project>"#,
)
.unwrap();
std::fs::write(
root.join("child/pom.xml"),
r#"<project><parent><groupId>demo</groupId><artifactId>root</artifactId><version>1.0</version></parent>
<artifactId>child</artifactId>
<profiles><profile><id>child-default</id><activation><activeByDefault>true</activeByDefault></activation></profile></profiles></project>"#,
)
.unwrap();
let settings_xml = root.join("settings.xml");
std::fs::write(
&settings_xml,
r#"<settings><activeProfiles><activeProfile>test3</activeProfile></activeProfiles></settings>"#,
)
.unwrap();
let cache = root.join("cache");
let settings = ide_core::settings::MavenSettings {
user_settings: settings_xml.to_string_lossy().into_owned(),
..Default::default()
};
let model = load_linked(root, &cache, None, &settings, &Default::default()).maven.unwrap();
let flags: Vec<(&str, bool)> = model.profiles.iter().map(|p| (p.id.as_str(), p.active_by_default)).collect();
assert!(
flags.contains(&("test3", true)),
"activeProfile from settings.xml marks POM profile active: {flags:?}"
);
assert!(flags.contains(&("dev", true)), "case-insensitive activeByDefault: {flags:?}");
assert!(flags.contains(&("child-default", true)), "child module activeByDefault: {flags:?}");
}
#[test]
fn detects_build_systems_and_build_files() {
let tmp = tempfile::tempdir().unwrap();
+136 -3
Переглянути файл
@@ -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 {
@@ -339,7 +437,9 @@ fn read_raw(project: &Element) -> RawPom {
for p in project.list("profiles", "profile") {
let mut profile = RawProfile {
id: p.text_of("id").unwrap_or_else(|| "default".into()),
active_by_default: p.at("activation/activeByDefault").is_some_and(|a| a.text.trim() == "true"),
active_by_default: p
.at("activation/activeByDefault")
.is_some_and(|a| a.text.trim().eq_ignore_ascii_case("true")),
activation_jdk: p.at("activation/jdk").map(|jdk| jdk.text.trim().to_owned()).filter(|jdk| !jdk.is_empty()),
modules: module_names(p),
properties: read_properties(p.child("properties")),
@@ -503,12 +603,25 @@ pub fn settings_profiles(settings: &Path) -> Vec<MavenProfile> {
if profiles.iter().any(|p| p.id == id) {
continue;
}
let by_default = profile.at("activation/activeByDefault").is_some_and(|e| e.text.trim() == "true");
let by_default =
profile.at("activation/activeByDefault").is_some_and(|e| e.text.trim().eq_ignore_ascii_case("true"));
profiles.push(MavenProfile { active_by_default: by_default || active.contains(&id), id, ..Default::default() });
}
profiles
}
/// Profile IDs listed under `<activeProfiles>` in `settings.xml` (may refer to profiles defined in POMs).
pub fn settings_active_profiles(settings: &Path) -> Vec<String> {
let Some(root) = xml::read_text(settings).as_deref().and_then(xml::parse) else {
return Vec::new();
};
root.list("activeProfiles", "activeProfile")
.iter()
.map(|e| e.text.trim().to_owned())
.filter(|id| !id.is_empty())
.collect()
}
/// `<localRepository>` of a settings file, when it names one: the repository a build
/// with `-s <file>` resolves into, which is not necessarily the user's default.
pub fn local_repository_of(settings: &Path) -> Option<PathBuf> {
@@ -1340,6 +1453,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 +1639,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)));
@@ -1592,7 +1723,9 @@ pub fn load_with_linked_jdk(
// The project can activate the profiles of its own POM and its ancestors'.
for (id, active) in &ctx.profiles {
if !model.profiles.iter().any(|x| x.id == *id) {
if let Some(existing) = model.profiles.iter_mut().find(|x| x.id == *id) {
existing.active_by_default |= *active;
} else {
model.profiles.push(MavenProfile { id: id.clone(), active_by_default: *active, ..Default::default() });
}
}
+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
Переглянути файл
@@ -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"] }
+3
Переглянути файл
@@ -86,6 +86,8 @@ pub struct EditorAppearanceSettings {
pub indent_guides: bool,
/// Colour indent guides by depth (`--syn-rainbow-*`), while `indent_guides` is on.
pub rainbow_indent_guides: bool,
/// Also tint each indent level's whitespace in its rainbow colour, while `rainbow_indent_guides` is on.
pub rainbow_indent_guides_fill: bool,
/// Right margin and visual guides from Code Style.
pub hard_wrap_guides: bool,
pub intention_bulb: bool,
@@ -114,6 +116,7 @@ impl Default for EditorAppearanceSettings {
whitespace_trailing: true,
indent_guides: true,
rainbow_indent_guides: false,
rainbow_indent_guides_fill: false,
hard_wrap_guides: true,
intention_bulb: true,
render_doc_comments: false,
+14
Переглянути файл
@@ -328,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 {
@@ -447,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)]
+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,
+60 -3
Переглянути файл
@@ -162,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")]
@@ -211,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(),
@@ -253,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 {
@@ -266,6 +278,8 @@ impl Default for AgentMcpServer {
url: None,
headers: BTreeMap::new(),
agents: Vec::new(),
registry_name: None,
registry_url: None,
}
}
}
@@ -1073,6 +1087,8 @@ pub struct GeneralSettings {
pub close_tabs_with_window: bool,
/// Where Open… puts a project while one is open: `ask` | `new` | `same` | `attach`.
pub open_project_in: String,
/// What closing a remote development window does with its backend: `ask` | `keep` | `stop`.
pub close_remote_window: String,
/// Initial folder of the Open / Clone dialogs; empty = the OS default.
pub default_project_directory: String,
/// Save all files after `idle_seconds` without input.
@@ -1086,6 +1102,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,
@@ -1101,6 +1119,7 @@ impl Default for GeneralSettings {
close_without_welcome: false,
close_tabs_with_window: false,
open_project_in: "ask".into(),
close_remote_window: "ask".into(),
default_project_directory: String::new(),
save_on_idle: false,
idle_seconds: 15,
@@ -1108,6 +1127,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(),
@@ -1347,6 +1367,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>,
@@ -1451,6 +1472,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,
@@ -1516,6 +1540,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(),
@@ -1715,6 +1740,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,
@@ -1730,6 +1757,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,
@@ -1737,6 +1765,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 {
@@ -2562,12 +2600,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);
}
@@ -2594,12 +2636,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!(
@@ -2615,6 +2657,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!({}));
}
@@ -2683,6 +2726,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();
+19
Переглянути файл
@@ -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(),
}
}
}
@@ -562,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,
}
@@ -585,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(),
}
@@ -727,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,
}
+38 -3
Переглянути файл
@@ -51,6 +51,8 @@ pub struct AdapterSpec {
pub pinned: Option<ProgramPin>,
/// See [`DebuggerConfig::resolve_lazy_variables`].
pub resolve_lazy_variables: bool,
/// Connect to the one lldb-dap server every such session shares ([`crate::lldb_server`]).
pub shared: bool,
}
/// Built-in adapters used when no language definition names `adapter`.
@@ -193,6 +195,7 @@ pub fn resolve(config: &DebuggerConfig, cwd: PathBuf) -> AdapterSpec {
connect: config.connect.clone(),
pinned: config.pinned.clone(),
resolve_lazy_variables: config.resolve_lazy_variables,
shared: false,
}
}
@@ -298,7 +301,7 @@ fn managed_dirs(root: &Path) -> Vec<PathBuf> {
/// The `PATH` an adapter runs with, unless its launch sets one: the search path language servers
/// get, so what it starts in turn (js-debug's wrapper runs `node`, Delve runs `go build`) is
/// found like Run finds it, even when the login shell's `PATH` didn't reach the app.
fn adapter_path(env: &[(String, String)], cwd: &Path) -> Option<std::ffi::OsString> {
pub(crate) fn adapter_path(env: &[(String, String)], cwd: &Path) -> Option<std::ffi::OsString> {
let own = env.iter().any(|(k, _)| if cfg!(windows) { k.eq_ignore_ascii_case("PATH") } else { k == "PATH" });
(!own).then(|| ide_core::tool_path::search_path_in(cwd))
}
@@ -613,11 +616,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);
}
@@ -735,6 +747,18 @@ impl AdapterLauncher for ProcessLauncher {
.ok_or_else(|| missing(&spec))?
}
};
#[cfg(target_os = "macos")]
if spec.shared && spec.transport == Transport::Stdio && spec.connect.is_none() && spec.args.is_empty() {
match crate::lldb_server::connect(&spec, &binary).await {
Ok(Some(io)) => return Ok(io),
Ok(None) => {}
Err(e) => tracing::warn!(
target: "ide_dap::adapter",
"no shared lldb-dap server ({}); starting one for this session",
e.message
),
}
}
let launch_after_configuration =
if spec.adapter == "gdb" { prepare_gdb(&spec, &binary).await? } else { false };
let base_args = substitute_root(&spec.args, &spec.cwd);
@@ -882,7 +906,7 @@ fn is_port_race(err: &IdeError) -> bool {
|| message.contains("exited before accepting connections")
}
fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(
pub(crate) fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(
stream: R,
name: String,
sink: Arc<parking_lot::Mutex<Vec<String>>>,
@@ -1205,6 +1229,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());
+1
Переглянути файл
@@ -103,6 +103,7 @@ pub(crate) fn bare_session_of(name: &str, request: &str) -> BareSession {
connect: None,
pinned: None,
resolve_lazy_variables: false,
shared: false,
};
let session = Session::new(
DebugSessionId(1),
+12 -1
Переглянути файл
@@ -21,6 +21,8 @@ mod js_debug;
mod jvm_memory;
pub mod kotlin;
pub mod kotlin_lsp;
#[cfg(target_os = "macos")]
mod lldb_server;
mod memory;
pub mod native;
mod session;
@@ -516,6 +518,7 @@ fn is_native(adapter: &str) -> bool {
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
/// adapter.
pub const RUN_LINK: &str = "__openideaRun";
const XCODE_ATTACH: &str = "__openideaXcodeAttach";
fn take_run_link(arguments: &mut Value) -> Option<RunId> {
let run = arguments.as_object_mut()?.remove(RUN_LINK)?;
@@ -1203,6 +1206,7 @@ impl DebugManager {
connect: None,
pinned: None,
resolve_lazy_variables: false,
shared: false,
};
let cancel = ide_core::CancellationToken::new();
self.start_session(
@@ -1269,7 +1273,7 @@ impl DebugManager {
parent: Option<DebugSessionId>,
request: String,
mut arguments: Value,
spec: AdapterSpec,
mut spec: AdapterSpec,
reuse_port: Option<u16>,
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
cancel: ide_core::CancellationToken,
@@ -1278,6 +1282,13 @@ impl DebugManager {
if request != "launch" && request != "attach" {
return Err(IdeError::invalid(format!("request must be `launch` or `attach`, got `{request}`")));
}
// Xcode Debug attaches to the app its run launched: a shared lldb-dap server keeps the
// system libraries it parsed, so the next attach skips that (#6665 E7).
let xcode_attach = arguments.as_object_mut().and_then(|args| args.remove(XCODE_ATTACH));
spec.shared = xcode_attach == Some(Value::Bool(true))
&& adapter_name == "lldb-dap"
&& request == "attach"
&& arguments.get(RUN_LINK).is_some();
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
+408
Переглянути файл
@@ -0,0 +1,408 @@
//! Cache one lldb-dap server for successive attaches to Xcode runs (#6665 E7).
//!
//! An iOS app loads about 550 system libraries before its first line runs, and a fresh lldb-dap
//! parses all of their symbol tables (about 5 million symbols) on each attach: 1.5 s on an idle
//! Mac, far more under load. A server keeps the modules it parsed, so later sessions skip that
//! and reach a breakpoint about as fast as Run reaches the same line. LLDB's own on-disk index
//! cache would serve the first session too, but Xcode 27.1's lldb crashes on cached symbols.
//!
//! The server holds about 1 GB, so it ends once no session has been connected for
//! [`IDLE_TIMEOUT`]; the next Debug then starts cold, as every Debug did before. A shell holds
//! it and ends it when its stdin closes: when the IDE quits or crashes, when the server idles
//! out, or when a server for another lldb-dap or environment replaces it.
use crate::adapter::{AdapterIo, AdapterSpec, adapter_path, pump_lines};
use ide_core::{IdeError, IdeResult};
use std::ffi::OsString;
use std::fs::Permissions;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::process::Stdio;
use std::sync::{Arc, LazyLock};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::net::UnixStream;
use tokio::process::{Child, Command};
/// What a server was started with: a session reuses it only when its own start would match.
#[derive(PartialEq)]
struct Key {
binary: PathBuf,
cwd: PathBuf,
cwd_env: Vec<(OsString, Option<OsString>)>,
}
struct Server {
key: Key,
socket: PathBuf,
/// Recent stderr for the active connection.
stderr: Arc<parking_lot::Mutex<Vec<String>>>,
idle: Arc<Idle>,
/// The shell holding the server; dropping it closes its stdin, which ends the server.
_holder: Child,
_socket_dir: tempfile::TempDir,
}
/// When the last session disconnected, or `None` while a session owns the server.
type Idle = parking_lot::Mutex<Option<Instant>>;
type Slot = tokio::sync::Mutex<Option<Server>>;
static SERVER: LazyLock<Slot> = LazyLock::new(Default::default);
/// How long a server with no session stays up.
const IDLE_TIMEOUT: Duration = Duration::from_secs(10 * 60);
/// How long a new server may take to listen.
const START_TIMEOUT: Duration = Duration::from_secs(15);
/// A connection to a running server; a server that does not take it is replaced.
const PROBE_TIMEOUT: Duration = Duration::from_millis(500);
/// Starts the server and ends it when the shell's stdin closes (`read` sees EOF) or when the
/// server exits on its own (`wait`), so a `binary` without `--connection` fails at once.
const HOLDER: &str = "exec 3<&0\n\
\"$0\" --connection \"$1\" </dev/null >/dev/null &\n\
server=$!\n\
(read _ <&3; kill \"$server\" 2>/dev/null) &\n\
watcher=$!\n\
wait \"$server\"\n\
result=$?\n\
kill \"$watcher\" 2>/dev/null\n\
wait \"$watcher\" 2>/dev/null\n\
exit \"$result\"\n";
/// A connection to the shared server of `binary`, started first when there is none.
pub async fn connect(spec: &AdapterSpec, binary: &Path) -> IdeResult<Option<AdapterIo>> {
connect_to(&SERVER, spec, binary, IDLE_TIMEOUT).await
}
async fn connect_to(
slot: &'static Slot,
spec: &AdapterSpec,
binary: &Path,
idle_timeout: Duration,
) -> IdeResult<Option<AdapterIo>> {
// The server gets the environment a per-session lldb-dap would: the project's (its Xcode's
// `DEVELOPER_DIR`, from `cwd`), the adapter's search path and the spec's own variables.
let mut cmd = Command::new("/bin/sh");
cmd.current_dir(&spec.cwd);
if let Some(path) = adapter_path(&spec.env, &spec.cwd) {
cmd.env("PATH", path);
}
cmd.envs(spec.env.iter().map(|(k, v)| (k, v)));
ide_core::process::prepare(cmd.as_std_mut());
let mut env: Vec<_> = cmd.as_std().get_envs().map(|(k, v)| (k.to_owned(), v.map(|v| v.to_owned()))).collect();
env.sort();
let key = Key { binary: binary.to_path_buf(), cwd: spec.cwd.clone(), cwd_env: env };
let mut server = slot.lock().await;
// A concurrent launch uses its own adapter. Replacing the cached process here would
// disconnect the ongoing session, and concurrent sessions would share its stderr.
if server.as_ref().is_some_and(|running| running.idle.lock().is_none()) {
return Ok(None);
}
if let Some(running) = server.as_ref().filter(|s| s.key == key)
&& let Ok(Ok(stream)) = tokio::time::timeout(PROBE_TIMEOUT, UnixStream::connect(&running.socket)).await
{
running.stderr.lock().clear();
return Ok(Some(io(stream, running.stderr.clone(), lease(&running.idle))));
}
*server = None;
let socket_dir = tempfile::Builder::new()
.permissions(Permissions::from_mode(0o700))
.tempdir()
.map_err(|e| IdeError::unavailable(format!("cannot create the lldb-dap socket directory: {e}")))?;
let socket = socket_dir.path().join("dap.sock");
let mut uri = OsString::from("accept://");
uri.push(&socket);
ide_core::process::own_group(cmd.as_std_mut());
cmd.arg("-c").arg(HOLDER).arg(binary).arg(uri).stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::piped());
let mut holder = cmd.spawn().map_err(|e| IdeError::unavailable(format!("failed to start lldb-dap: {e}")))?;
let stderr = Arc::new(parking_lot::Mutex::new(Vec::new()));
if let Some(err) = holder.stderr.take() {
pump_lines(err, spec.adapter.clone(), stderr.clone(), None);
}
let stream = connect_when_ready(&socket, &mut holder).await?;
let idle = Arc::new(Idle::default());
let first = lease(&idle);
tokio::spawn(end_when_idle(slot, idle.clone(), idle_timeout));
*server = Some(Server { key, socket, stderr: stderr.clone(), idle, _holder: holder, _socket_dir: socket_dir });
Ok(Some(io(stream, stderr, first)))
}
async fn connect_when_ready(socket: &Path, holder: &mut Child) -> IdeResult<UnixStream> {
let deadline = Instant::now() + START_TIMEOUT;
loop {
let error = match UnixStream::connect(socket).await {
Ok(stream) => return Ok(stream),
Err(error) => error,
};
if let Ok(Some(status)) = holder.try_wait() {
return Err(IdeError::unavailable(format!("debug adapter exited before accepting connections ({status})")));
}
if Instant::now() >= deadline {
return Err(IdeError::unavailable(format!("could not connect to lldb-dap: {error}")));
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
/// A session's hold on the server, released when its connection's both halves are gone.
struct Lease(Arc<Idle>);
fn lease(idle: &Arc<Idle>) -> Arc<Lease> {
*idle.lock() = None;
Arc::new(Lease(idle.clone()))
}
impl Drop for Lease {
fn drop(&mut self) {
*self.0.lock() = Some(Instant::now());
}
}
/// Ends the server in `slot` once no session has been connected to it for `timeout`; returns
/// early when another server took its place.
async fn end_when_idle(slot: &'static Slot, idle: Arc<Idle>, timeout: Duration) {
loop {
let since = *idle.lock();
let wait = since.map_or(timeout, |at| (at + timeout).saturating_duration_since(Instant::now()));
tokio::time::sleep(wait.max(Duration::from_millis(10))).await;
let mut server = slot.lock().await;
if !server.as_ref().is_some_and(|s| Arc::ptr_eq(&s.idle, &idle)) {
return;
}
if idle.lock().is_some_and(|at| at.elapsed() >= timeout) {
*server = None;
return;
}
}
}
/// One half of a session's connection, holding the session's [`Lease`].
struct Leased<T> {
inner: T,
_lease: Arc<Lease>,
}
impl<T: AsyncRead + Unpin> AsyncRead for Leased<T> {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.inner).poll_read(cx, buf)
}
}
impl<T: AsyncWrite + Unpin> AsyncWrite for Leased<T> {
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<std::io::Result<usize>> {
Pin::new(&mut self.inner).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.inner).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.inner).poll_shutdown(cx)
}
}
/// A session's streams. When the server dies the session's connection closes and the session
/// ends with the server's last stderr lines, whichever session started it.
fn io(stream: UnixStream, stderr: Arc<parking_lot::Mutex<Vec<String>>>, lease: Arc<Lease>) -> AdapterIo {
let (r, w) = stream.into_split();
AdapterIo {
launch_after_configuration: false,
reader: Box::new(Leased { inner: r, _lease: lease.clone() }),
writer: Box::new(Leased { inner: w, _lease: lease }),
// The server is not the session's to stop.
child: None,
port: None,
stderr,
program_output: None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::AsyncReadExt;
/// A stand-in for lldb-dap's server mode: it parses `--connection accept:///path`,
/// records each start in `starts`, and answers every connection with its pid and the
/// `DEVELOPER_DIR` it was started with.
fn fake_lldb_dap(dir: &Path) -> Option<PathBuf> {
use std::os::unix::fs::PermissionsExt;
std::process::Command::new("python3").arg("-c").arg("").status().ok()?.success().then_some(())?;
let path = dir.join("lldb-dap");
let log = dir.join("starts");
std::fs::write(
&path,
format!(
"#!/usr/bin/env python3\nimport os, socket, sys\n\
assert sys.argv[1] == '--connection'\n\
open({:?}, 'a').write('start\\n')\n\
path = sys.argv[2][len('accept://'):]\n\
s = socket.socket(socket.AF_UNIX)\n\
s.bind(path); s.listen()\n\
while True:\n c, _ = s.accept(); c.sendall(f\"{{os.getpid()}} {{os.environ.get('DEVELOPER_DIR', '')}}\".encode()); c.close()\n",
log.to_string_lossy(),
),
)
.unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
Some(path)
}
/// The server's pid and `DEVELOPER_DIR`; the session's connection is closed afterwards.
async fn server_of(io: AdapterIo) -> (i32, String) {
let mut reader = io.reader;
let mut text = String::new();
reader.read_to_string(&mut text).await.unwrap();
let (pid, dir) = text.split_once(' ').unwrap();
(pid.parse().unwrap(), dir.to_owned())
}
fn spec(dir: &Path) -> AdapterSpec {
AdapterSpec {
adapter: "lldb-dap".into(),
command: "lldb-dap".into(),
args: Vec::new(),
transport: crate::adapter::Transport::Stdio,
install_hint: None,
cwd: dir.to_path_buf(),
env: Vec::new(),
server_host: None,
connect: None,
pinned: None,
resolve_lazy_variables: false,
shared: true,
}
}
fn slot() -> &'static Slot {
Box::leak(Box::default())
}
fn starts(dir: &Path) -> usize {
std::fs::read_to_string(dir.join("starts")).unwrap_or_default().lines().count()
}
fn alive(pid: i32) -> bool {
unsafe { libc::kill(pid, 0) == 0 }
}
async fn until_gone(pid: i32) -> bool {
for _ in 0..150 {
if !alive(pid) {
return true;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
false
}
const LONG: Duration = Duration::from_secs(600);
/// Sessions share one server; it outlives them, and goes when its holder does (the IDE quits).
#[tokio::test]
async fn sessions_share_one_server_that_ends_with_its_holder() {
let dir = tempfile::tempdir().unwrap();
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
let slot = slot();
let first = connect_to(slot, &spec(dir.path()), &binary, LONG).await.unwrap().unwrap();
assert!(first.child.is_none(), "a session must not stop the shared server");
let first_stderr = first.stderr.clone();
let (pid, _) = server_of(first).await;
let second = connect_to(slot, &spec(dir.path()), &binary, LONG).await.unwrap().unwrap();
assert!(Arc::ptr_eq(&second.stderr, &first_stderr), "every session sees the server's errors");
assert_eq!(server_of(second).await.0, pid, "the second session reuses the server");
assert_eq!(starts(dir.path()), 1);
// Another lldb-dap (the selected Xcode changed) gets its own server; the old one ends.
let other_dir = tempfile::tempdir().unwrap();
let other = fake_lldb_dap(other_dir.path()).unwrap();
let (other_pid, _) =
server_of(connect_to(slot, &spec(other_dir.path()), &other, LONG).await.unwrap().unwrap()).await;
assert_ne!(other_pid, pid);
assert!(until_gone(pid).await, "the replaced server is still running");
*slot.lock().await = None;
assert!(until_gone(other_pid).await, "the server outlived its holder");
}
/// The server gets the session's environment, and a session with another Xcode
/// (`DEVELOPER_DIR`) does not reuse a server started for a different one.
#[tokio::test]
async fn a_server_is_reused_only_with_the_same_environment() {
let dir = tempfile::tempdir().unwrap();
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
let slot = slot();
let with = |xcode: &str| AdapterSpec { env: vec![("DEVELOPER_DIR".into(), xcode.into())], ..spec(dir.path()) };
let (a, dir_a) = server_of(connect_to(slot, &with("/Xcode-a"), &binary, LONG).await.unwrap().unwrap()).await;
assert_eq!(dir_a, "/Xcode-a");
let (b, dir_b) = server_of(connect_to(slot, &with("/Xcode-b"), &binary, LONG).await.unwrap().unwrap()).await;
assert_eq!(dir_b, "/Xcode-b");
assert_ne!(a, b);
assert_eq!(server_of(connect_to(slot, &with("/Xcode-b"), &binary, LONG).await.unwrap().unwrap()).await.0, b);
*slot.lock().await = None;
assert!(until_gone(b).await);
}
#[tokio::test]
async fn concurrent_attaches_leave_the_active_server_alone() {
let dir = tempfile::tempdir().unwrap();
let other = tempfile::tempdir().unwrap();
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
let slot = slot();
let first = connect_to(slot, &spec(dir.path()), &binary, LONG).await.unwrap().unwrap();
for cwd in [dir.path(), other.path()] {
assert!(connect_to(slot, &spec(cwd), &binary, LONG).await.unwrap().is_none());
}
assert_eq!(starts(dir.path()), 1);
let (first_pid, _) = server_of(first).await;
assert!(alive(first_pid));
let replacement = connect_to(slot, &spec(other.path()), &binary, LONG).await.unwrap().unwrap();
let (replacement_pid, _) = server_of(replacement).await;
assert_ne!(first_pid, replacement_pid, "changing only the working directory replaces an idle server");
assert!(until_gone(first_pid).await);
*slot.lock().await = None;
assert!(until_gone(replacement_pid).await);
}
/// The server ends once no session has been connected for the idle timeout; a connected
/// session, or a new one within the timeout, keeps it.
#[tokio::test]
async fn an_idle_server_ends_and_the_next_session_starts_another() {
let dir = tempfile::tempdir().unwrap();
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
let slot = slot();
let idle = Duration::from_millis(400);
let held = connect_to(slot, &spec(dir.path()), &binary, idle).await.unwrap().unwrap();
tokio::time::sleep(idle * 2).await;
let (pid, _) = server_of(held).await;
assert!(alive(pid), "a connected session keeps the server");
tokio::time::sleep(idle / 4).await;
assert_eq!(server_of(connect_to(slot, &spec(dir.path()), &binary, idle).await.unwrap().unwrap()).await.0, pid);
assert_eq!(starts(dir.path()), 1, "a session within the timeout reuses the server");
assert!(until_gone(pid).await, "the idle server is still running");
let (next, _) = server_of(connect_to(slot, &spec(dir.path()), &binary, idle).await.unwrap().unwrap()).await;
assert_ne!(next, pid);
assert_eq!(starts(dir.path()), 2);
*slot.lock().await = None;
assert!(until_gone(next).await);
}
/// An lldb-dap without server mode fails at once, so the caller can start it as before.
#[tokio::test]
async fn an_lldb_dap_without_server_mode_fails_fast() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let binary = dir.path().join("lldb-dap");
std::fs::write(&binary, "#!/bin/sh\necho \"unknown option $1\" >&2\nexit 1\n").unwrap();
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap();
let started = std::time::Instant::now();
let e = connect_to(slot(), &spec(dir.path()), &binary, LONG).await.err().unwrap();
assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed());
assert!(e.message.contains("exited before accepting connections"), "{}", e.message);
}
}
+46
Переглянути файл
@@ -4044,6 +4044,52 @@ async fn stop_ends_a_native_program_a_run_started_for_the_debugger() {
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
}
/// Xcode Debug's attach goes to the shared lldb-dap server, which keeps the system libraries
/// parsed by earlier sessions (#6665 E7); other sessions start their own adapter.
#[tokio::test]
async fn only_an_lldb_dap_attach_to_a_run_shares_the_server() {
struct CaptureLauncher {
inner: FakeLauncher,
shared: Arc<parking_lot::Mutex<Vec<bool>>>,
}
impl AdapterLauncher for CaptureLauncher {
fn launch(&self, spec: AdapterSpec, reuse: Option<u16>) -> LaunchFuture {
self.shared.lock().push(spec.shared);
self.inner.launch(spec, reuse)
}
}
let shared: Arc<parking_lot::Mutex<Vec<bool>>> = Arc::default();
let launcher = CaptureLauncher {
inner: FakeLauncher { log: Arc::default(), script: Script::default() },
shared: shared.clone(),
};
let manager = DebugManager::with_launcher(Arc::new(LanguageRegistry::from_configs(Vec::new())), Arc::new(launcher));
let session = |adapter: &str, request: &str, linked: bool, xcode: bool| LaunchConfig {
adapter: adapter.into(),
request: request.into(),
extra_json: Some(
if linked {
json!({ RUN_LINK: 7, XCODE_ATTACH: xcode, "pid": 4242 })
} else {
json!({ XCODE_ATTACH: xcode, "pid": 4242 })
}
.to_string(),
),
..config()
};
for launch in [
session("lldb-dap", "attach", true, true),
session("lldb-dap", "attach", true, false),
session("lldb-dap", "attach", false, true),
session("lldb-dap", "launch", true, true),
session("debugpy", "attach", true, true),
] {
let (owner, _) = recording_owner("main");
manager.start(launch, owner).await.unwrap();
}
assert_eq!(*shared.lock(), [true, false, false, false, false]);
}
/// LLDB leaves a breakpoint it can't bind unverified without a reason: say what may be wrong
/// (#6665 E1b: Xcode's debug info had `/tmp/…` for a project under `/private/tmp`).
#[tokio::test]
+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",
] {
+106 -5
Переглянути файл
@@ -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;
@@ -156,6 +157,15 @@ pub struct TableInfo {
pub comment: Option<String>,
}
/// Non-secret identity of an already-connected data source target.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConnectedSourceInfo {
pub source_id: String,
pub name: String,
pub driver: DbDriver,
pub database: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbColumnInfo")]
@@ -1298,15 +1308,49 @@ impl DbManager {
}
}
/// Lists non-secret metadata for every currently connected source target on this project/window.
/// Never allocates a pool, connects a source, or reads credentials.
pub fn connected_sources(&self) -> Vec<ConnectedSourceInfo> {
let connected = self.connected();
if connected.is_empty() {
return Vec::new();
}
let sources: std::collections::HashMap<String, DataSource> =
self.sources().unwrap_or_default().into_iter().map(|s| (s.id.clone(), s)).collect();
let mut out: Vec<ConnectedSourceInfo> = connected
.into_iter()
.filter_map(|source_id| {
let (base_id, db_suffix) = split_target(&source_id);
let source = sources.get(base_id)?.resolved().ok()?;
let database =
db_suffix.map(str::to_owned).or_else(|| (!source.database.is_empty()).then_some(source.database));
Some(ConnectedSourceInfo { source_id, name: source.name, driver: source.driver, database })
})
.collect();
out.sort_by(|a, b| a.source_id.cmp(&b.source_id));
out
}
/// Every schema (the Schemas tab picks the ones the tree shows); system schemas
/// only with [`DbIntrospection::show_system`].
pub async fn schemas(&self, id: &str) -> IdeResult<Vec<String>> {
let system = self.source(id)?.introspection.show_system;
let pool = self.pool(id).await?;
if let Pool::Snowflake(p) = &*pool {
Self::schemas_on(&pool, system).await
}
/// Read schemas using an existing connection only. Never opens a connection or prompts for credentials.
pub async fn connected_schemas(&self, id: &str) -> IdeResult<Vec<String>> {
let system = self.source(id)?.introspection.show_system;
let pool = self.connected_pool(id)?;
Self::schemas_on(&pool, system).await
}
async fn schemas_on(pool: &Pool, system: bool) -> IdeResult<Vec<String>> {
if let Pool::Snowflake(p) = pool {
return snowflake::meta::schemas(p, system).await;
}
let rows = match &*pool {
let rows = match pool {
Pool::Jdbc(p) => p.metadata(&["schemas"]).await?,
_ => pool.rows(sql::schemas(pool.driver(), system), MAX_META_ROWS).await?,
};
@@ -1315,10 +1359,20 @@ impl DbManager {
pub async fn tables(&self, id: &str, schema: &str) -> IdeResult<Vec<TableInfo>> {
let pool = self.pool(id).await?;
if let Pool::Snowflake(p) = &*pool {
Self::tables_on(&pool, schema).await
}
/// Read tables using an existing connection only. Never opens a connection or prompts for credentials.
pub async fn connected_tables(&self, id: &str, schema: &str) -> IdeResult<Vec<TableInfo>> {
let pool = self.connected_pool(id)?;
Self::tables_on(&pool, schema).await
}
async fn tables_on(pool: &Pool, schema: &str) -> IdeResult<Vec<TableInfo>> {
if let Pool::Snowflake(p) = pool {
return snowflake::meta::tables(p, schema).await;
}
let rows = match &*pool {
let rows = match pool {
Pool::Jdbc(p) => p.metadata(&["tables", schema]).await?,
_ => pool.rows(&sql::tables(pool.driver(), schema), MAX_META_ROWS).await?,
};
@@ -1336,6 +1390,25 @@ impl DbManager {
.collect())
}
/// Executes a SQL statement using an existing connection only (used by extension hosts).
/// Respects read-only connections and never opens a disconnected source or prompts for credentials.
pub async fn connected_execute(
&self,
id: &str,
statement: &str,
max_rows: usize,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
let pool = self.connected_pool(id)?;
if pool.transaction_read_only() {
conn::validate_pg_read_only(statement).map_err(IdeError::invalid)?;
}
if !conn::cursor_statement(statement) {
self.cursors.release_target(id);
}
pool.execute_from(statement, 0, max_rows, cancel).await
}
async fn duckdb_catalog_pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
let source = self.source(id)?;
if id != source.id || source.driver != DbDriver::Jdbc || source.vendor != "duckdb" {
@@ -2103,6 +2176,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?;
@@ -2150,6 +2225,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),
@@ -2164,6 +2240,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();
@@ -2196,6 +2281,7 @@ impl DbManager {
conn.discard().await;
return Err(IdeError::cancelled());
}
conn.release_after(statement, pool.driver()).await;
return r;
};
if pool.driver() == DbDriver::Clickhouse {
@@ -2216,6 +2302,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);
@@ -2245,7 +2337,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?;
@@ -2451,10 +2545,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(())
}
+23
Переглянути файл
@@ -26,6 +26,8 @@ pub enum Capability {
DatabaseSources,
/// Read table metadata of connected project sources; never rows or credentials.
DatabaseSchema,
/// Execute SQL statements against connected project database sources.
DatabaseQuery,
VcsRead,
VcsWrite,
/// The Maven / Gradle dependency graph the IDE resolved.
@@ -109,6 +111,7 @@ impl Capability {
// A trusted project's own files name the programs the IDE starts (its settings, its
// build scripts), so writing them is running code.
Self::ProjectWrite
| Self::DatabaseQuery
| Self::IdeCommands
| Self::Ipc(_)
| Self::Process(_)
@@ -134,6 +137,7 @@ impl Capability {
Self::ProjectWrite => "Create and change files in the open project".into(),
Self::DatabaseSources => "Manage its own database sources and store their passwords in trusted projects".into(),
Self::DatabaseSchema => "Read table structures of connected database sources in trusted projects, without rows or passwords".into(),
Self::DatabaseQuery => "Execute SQL queries and statements on connected database sources in trusted projects".into(),
Self::IdeCommands => "Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing".into(),
Self::VcsRead => "Read version control state".into(),
Self::VcsWrite => "Change version control state (commit, fetch, checkout)".into(),
@@ -294,6 +298,7 @@ impl fmt::Display for Capability {
Self::IdeCommands => f.write_str("ide.commands"),
Self::DatabaseSources => f.write_str("database.sources"),
Self::DatabaseSchema => f.write_str("database.schema"),
Self::DatabaseQuery => f.write_str("database.query"),
Self::VcsRead => f.write_str("vcs.read"),
Self::VcsWrite => f.write_str("vcs.write"),
Self::BuildRead => f.write_str("build.read"),
@@ -389,6 +394,7 @@ impl FromStr for Capability {
"ide.commands" => Self::IdeCommands,
"database.sources" => Self::DatabaseSources,
"database.schema" => Self::DatabaseSchema,
"database.query" => Self::DatabaseQuery,
"vcs.read" => Self::VcsRead,
"vcs.write" => Self::VcsWrite,
"build.read" => Self::BuildRead,
@@ -700,6 +706,23 @@ mod database_tests {
}
}
#[test]
fn database_query_is_a_separate_high_risk_grant_requiring_api21() {
let cap: Capability = "database.query".parse().unwrap();
assert_eq!(cap, Capability::DatabaseQuery);
assert_eq!(cap.to_string(), "database.query");
assert_eq!(cap.risk(), Risk::High);
assert!(!cap.auto_migrates());
for other in [Capability::ProjectRead, Capability::DatabaseSources, Capability::DatabaseSchema] {
assert!(!other.covers(&cap));
}
for (api, valid) in [("^1.20", false), ("^1.21", true)] {
let text = format!(
"id='query'\nname='Query'\nversion='1.0.0'\nengines.openidea='{api}'\n[capabilities]\nrequired=['database.query']"
);
assert_eq!(crate::Manifest::parse(&text).is_ok(), valid);
}
}
#[test]
fn database_sources_is_a_medium_risk_exact_grant_requiring_api4() {
let cap: Capability = "database.sources".parse().unwrap();
assert_eq!(cap, Capability::DatabaseSources);
+8 -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",
@@ -429,6 +430,9 @@ impl Manifest {
if matches!(cap, Capability::DatabaseSchema) {
self.needs_api(&format!("capability `{cap}`"), 20)?;
}
if matches!(cap, Capability::DatabaseQuery) {
self.needs_api(&format!("capability `{cap}`"), 21)?;
}
if matches!(cap, Capability::Agents) {
self.needs_api(&format!("capability `{cap}`"), 18)?;
}
@@ -475,6 +479,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()),
+225 -5
Переглянути файл
@@ -19,6 +19,54 @@ const BIOME_MARKERS: [&str; 3] = ["biome.json", "biome.jsonc", "node_modules/@bi
const DPRINT_MARKERS: [&str; 5] =
["dprint.json", ".dprint.json", "dprint.jsonc", ".dprint.jsonc", "node_modules/dprint/package.json"];
/// CSharpier's configuration and ignore files.
const CSHARPIER_CONFIGS: [&str; 5] =
[".csharpierrc", ".csharpierrc.json", ".csharpierrc.yaml", ".csharpierrc.yml", ".csharpierignore"];
/// The version of CSharpier in the `dotnet` tool manifest that applies to `file`: the nearest one
/// in the project that lists it, up to a manifest marked `isRoot` (as `dotnet` searches).
fn local_csharpier(file: &Path, root: &Path) -> Option<String> {
for dir in file.parent()?.ancestors().take_while(|dir| dir.starts_with(root)) {
let mut is_root = false;
// .NET 10's `dotnet new tool-manifest` writes the second location.
for manifest in [dir.join(".config").join("dotnet-tools.json"), dir.join("dotnet-tools.json")] {
let Some(json) = std::fs::read_to_string(manifest).ok().and_then(|text| {
let text = text.trim_start_matches('\u{feff}');
serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(text)).ok()
}) else {
continue;
};
let tool = json["tools"].as_object().and_then(|tools| {
tools.iter().find(|(name, _)| name.eq_ignore_ascii_case("csharpier")).map(|(_, tool)| tool)
});
if let Some(tool) = tool {
return Some(tool["version"].as_str().unwrap_or_default().to_owned());
}
is_root |= json["isRoot"] == serde_json::Value::Bool(true);
}
if is_root {
break;
}
}
None
}
/// CSharpier for a `.cs` file of a project that uses it. `None` keeps the language server: another
/// language, a project without CSharpier, or only its configuration with no CSharpier installed.
fn csharpier_for(tools: &Tools, file: &Path, root: &Path) -> Option<IdeResult<formatter::CSharpierCommand>> {
if !file.extension().is_some_and(|e| e.eq_ignore_ascii_case("cs")) {
return None;
}
let local = local_csharpier(file, root);
if local.is_none() && find_in_project(file, root, &CSHARPIER_CONFIGS).is_none() {
return None;
}
match tools.csharpier_command(file, local.as_deref()) {
Err(_) if local.is_none() => None,
command => Some(command),
}
}
/// The nearest of `names` in `file`'s folder or above, up to the project `root` (none outside it).
fn find_in_project(file: &Path, root: &Path, names: &[&str]) -> Option<PathBuf> {
file.parent()?
@@ -374,10 +422,53 @@ fn php_cs_fixer_edits(
let copy = dir.path().join(name);
std::fs::write(&copy, unsaved)?;
formatter::run_php_cs_fixer(tools.php_cs_fixer_command(php, fixer, &copy)?, &Default::default())?;
let formatted = std::fs::read_to_string(&copy)?;
fixed_edits(unsaved, &std::fs::read_to_string(&copy)?)
}
/// Where a container finds the copy PHP-CS-Fixer fixes.
const PHP_CS_FIXER_COPY: &str = "/openidea-php-cs-fixer";
/// [`php_cs_fixer_edits`] with the PHP of `target`, the container run target PHP runs in: the
/// folder of the copy is mounted for this run, the configuration and `vendor` are in the project.
fn php_cs_fixer_container_edits(
data_dir: &Path,
root: &Path,
target: &ide_core::remote_settings::RunTarget,
fixer: &formatter::PhpCsFixer,
path: &Path,
unsaved: &str,
) -> IdeResult<Vec<TextEdit>> {
let name = path.file_name().ok_or_else(|| IdeError::invalid("PHP-CS-Fixer: file has no name"))?;
let dir = tempfile::tempdir()?;
let copy = dir.path().join(name);
std::fs::write(&copy, unsaved)?;
let php = crate::ops::run::container::PhpContainer::open(data_dir, root, target)?;
let args = [
php.path(&fixer.bin)?,
"fix".into(),
"--config".into(),
php.path(&fixer.config)?,
"--using-cache=no".into(),
"--no-interaction".into(),
"--show-progress=none".into(),
format!("{PHP_CS_FIXER_COPY}/{}", name.to_string_lossy()),
];
let cwd = php.path(fixer.config.parent().unwrap_or(root))?;
let volumes = [(dir.path().to_path_buf(), PHP_CS_FIXER_COPY.to_owned())];
let (command, container) = php.command(&cwd, &volumes, &args)?;
if let Err(error) = formatter::run_php_cs_fixer(command, &Default::default()) {
// A run that timed out left its container behind.
php.remove(&container);
return Err(error);
}
fixed_edits(unsaved, &std::fs::read_to_string(&copy)?)
}
/// The edits that turn `unsaved` into `formatted`.
fn fixed_edits(unsaved: &str, formatted: &str) -> IdeResult<Vec<TextEdit>> {
let text = ide_text::Document::new(unsaved);
Ok(text
.diff(&formatted)
.diff(formatted)
.changes
.into_iter()
.map(|c| TextEdit {
@@ -756,8 +847,11 @@ async fn provider_edits(
}
let php = ide_sdk::apply::setting_path(&project.root, &settings.languages.php.interpreter);
let tools = Tools::new(&host.local_data_dir);
let edits = tokio::task::spawn_blocking(move || {
php_cs_fixer_edits(&tools, php.as_deref(), &fixer, &snap.path, &snap.text)
let container = crate::ops::run::container::php_target(&settings);
let (data_dir, root) = (host.data_dir.clone(), project.root.clone());
let edits = tokio::task::spawn_blocking(move || match container {
Some(target) => php_cs_fixer_container_edits(&data_dir, &root, &target, &fixer, &snap.path, &snap.text),
None => php_cs_fixer_edits(&tools, php.as_deref(), &fixer, &snap.path, &snap.text),
})
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
@@ -770,6 +864,39 @@ async fn provider_edits(
}
return Ok(Some(edits));
}
// CSharpier takes over Reformat Code for C# in projects that use it. It formats whole files
// only, so ranges (a selection, generated code) stay with the language server, as in Rider.
// It runs the project's tool, so Restricted Mode keeps the server too.
if options.tool.is_none()
&& range.is_none()
&& project.require_trust().is_ok()
&& let Some(command) = csharpier_for(&Tools::new(&host.local_data_dir), &snap.path, &project.root)
{
if options.on_save && !settings.editor.format_on_save {
return Ok(None);
}
if snap.read_only {
return Err(IdeError::invalid("The file is read-only"));
}
let command = command?;
let (edits, excluded) = tokio::task::spawn_blocking(move || {
let formatted = formatter::run_csharpier(command, &snap.text, &Default::default())?;
if excluded_output(&snap.text, &formatted) {
return Ok((Vec::new(), true));
}
Ok::<_, IdeError>((diff_edits(&ide_text::Document::new(&snap.text), &formatted), false))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
if excluded && !options.on_save {
project.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Info,
title: "CSharpier".into(),
body: Some("CSharpier left the file unchanged: its configuration excludes it".into()),
});
}
return Ok(Some(edits));
}
// dprint formats what its configuration covers, before the language's own formatters.
let dprint = &settings.languages.dprint;
let forced_dprint = options.tool == Some(ExternalFormatter::Dprint);
@@ -963,7 +1090,7 @@ async fn provider_edits(
}
/// The edits that turn `text` into `formatted`, one per changed region.
fn diff_edits(text: &ide_text::Document, formatted: &str) -> Vec<TextEdit> {
pub(crate) fn diff_edits(text: &ide_text::Document, formatted: &str) -> Vec<TextEdit> {
text.diff(formatted)
.changes
.into_iter()
@@ -1059,6 +1186,54 @@ mod tests {
assert_eq!(external_tool(None, None, file, &settings).unwrap(), None);
}
#[test]
fn csharpier_is_found_in_the_projects_tool_manifest() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("repo");
let file = root.join("src/App/A.cs");
let write = |path: &str, text: &str| {
let path = dir.path().join(path);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
};
let manifest = |name: &str, version: &str, is_root: bool| {
format!(r#"{{"isRoot":{is_root},"tools":{{"{name}":{{"version":"{version}"}}}}}}"#)
};
// Outside the project it is not the project's.
write("dotnet-tools.json", &manifest("csharpier", "1.0.0", true));
assert_eq!(local_csharpier(&file, &root), None);
// .NET 10 writes the manifest at the root; names are case-insensitive, a BOM is fine.
write("repo/dotnet-tools.json", &format!("\u{feff}{}", manifest("CSharpier", "1.4.2", true)));
assert_eq!(local_csharpier(&file, &root).as_deref(), Some("1.4.2"));
// A nearer manifest without it passes the search on, unless it is the root one.
write("repo/src/.config/dotnet-tools.json", &manifest("dotnet-ef", "10.0.0", false));
assert_eq!(local_csharpier(&file, &root).as_deref(), Some("1.4.2"));
write("repo/src/.config/dotnet-tools.json", &manifest("dotnet-ef", "10.0.0", true));
assert_eq!(local_csharpier(&file, &root), None);
write("repo/src/.config/dotnet-tools.json", "not json");
assert_eq!(local_csharpier(&file, &root).as_deref(), Some("1.4.2"));
}
#[test]
fn only_csharp_files_of_csharpier_projects_leave_the_language_server() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let tools = Tools::new(&root.join("data"));
let uses = |file: &str| csharpier_for(&tools, &root.join(file), root).is_some();
assert!(!uses("A.cs"));
// A configuration alone takes over only with a CSharpier installed (none on CI), else the
// language server keeps formatting.
std::fs::write(root.join(".csharpierrc"), "").unwrap();
assert_eq!(uses("A.cs"), tools.formatter_command("csharpier", &root.join("A.cs"), None).is_ok());
std::fs::write(root.join("dotnet-tools.json"), r#"{"tools":{"csharpier":{"version":"1.4.2"}}}"#).unwrap();
// `.csx`, project files and other languages keep their formatter.
for other in ["A.csx", "App.csproj", "a.fs"] {
assert!(!uses(other), "{other}");
}
// Without `dotnet` this is the "SDK is not installed" error, still CSharpier's.
assert!(uses("A.cs") && uses("B.CS"));
}
#[test]
fn ruff_is_the_python_external_formatter_and_is_opt_out() {
let file = Path::new("/project/src/example.py");
@@ -1555,6 +1730,51 @@ mod tests {
assert_eq!(formatter::php_cs_fixer(&file).unwrap().config, root.join("src/.php-cs-fixer.dist.php"));
}
/// With a real Docker daemon:
/// `cargo test -p ide-host --lib formatter::tests::php_cs_fixer_fixes_the_copy_in -- --ignored`.
#[test]
#[ignore = "requires a Docker daemon and the php:8.3-cli image"]
fn php_cs_fixer_fixes_the_copy_in_a_container_run_target() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
std::fs::create_dir_all(root.join("vendor/bin")).unwrap();
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(root.join(".php-cs-fixer.dist.php"), "<?php").unwrap();
// Stands in for PHP-CS-Fixer: it needs the configuration, runs beside it, and indents
// the file it is given.
let stand_in = r#"<?php
$file = end($argv);
if ($argv[1] !== 'fix' || !is_file($argv[3]) || getcwd() !== dirname($argv[3]) || getenv('XDEBUG_MODE') !== 'off') {
fwrite(STDERR, 'unexpected run: ' . getcwd() . ' ' . implode(' ', $argv));
exit(16);
}
file_put_contents($file, str_replace(' echo', ' echo', file_get_contents($file)));
"#;
std::fs::write(root.join("vendor/bin/php-cs-fixer"), stand_in).unwrap();
let file = root.join("src").join("Kernel.php");
let fixer = formatter::php_cs_fixer(&file).unwrap();
let target = ide_core::remote_settings::RunTarget {
kind: ide_core::remote_settings::RunTargetKind::Docker,
id: "php".into(),
name: "PHP".into(),
image: "php:8.3-cli".into(),
..Default::default()
};
let data = root.join("data");
let edits = php_cs_fixer_container_edits(&data, &root, &target, &fixer, &file, "<?php\n echo 1;\n").unwrap();
assert_eq!(edits.len(), 1);
assert_eq!(edits[0].new_text, " ");
assert!(!file.exists(), "the file on disk is left alone");
std::fs::write(
root.join("vendor/bin/php-cs-fixer"),
"<?php fwrite(STDERR, 'Configuration file is invalid'); exit(16);",
)
.unwrap();
let err = php_cs_fixer_container_edits(&data, &root, &target, &fixer, &file, "<?php\n").unwrap_err();
assert!(err.message.contains("Configuration file is invalid"), "{}", err.message);
}
#[cfg(unix)]
#[test]
fn php_cs_fixer_fixes_a_copy_of_the_unsaved_text() {
+54 -8
Переглянути файл
@@ -2,7 +2,9 @@
use ide_build::kotlin_bridge::{self, Outcome, ProjectLibraries};
use ide_core::event::NotifyLevel;
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink, TaskId};
use ide_core::{
CancellationToken, Diagnostic, IdeError, IdeEvent, IdeResult, Pos, Range, Severity, SharedSink, TaskId,
};
use ide_lsp::LspManager;
use ide_workspace::SettingsStore;
use ide_workspace::documents::DocumentObserver;
@@ -20,6 +22,10 @@ use tokio::sync::Notify;
const DELAY: Duration = Duration::from_millis(750);
const SOURCE: &str = "kotlin-bridge";
const COMMAND: &str = "openidea.kotlin.replace";
/// How long a snapshot waits for jdtls to import the project, before it is sent regardless.
const IMPORT_WAIT: Duration = Duration::from_secs(30 * 60);
/// The pauses before a snapshot jdtls did not take is sent again.
const RETRY_DELAYS: [Duration; 3] = [Duration::from_secs(5), Duration::from_secs(15), Duration::from_secs(45)];
#[derive(Default)]
struct Revision {
@@ -133,13 +139,50 @@ impl KotlinBridge {
self.revision.lock().cancel.cancel();
}
async fn replace(&self, projects: &[ProjectLibraries], cancel: &CancellationToken) -> ide_core::IdeResult<()> {
let snapshot = serde_json::to_value(projects).map_err(|e| ide_core::IdeError::internal(e.to_string()))?;
/// Hands `projects` to jdtls once it imported the project, again after a pause when it
/// timed out, refused or went away. A jdtls that was stopped is not started again.
async fn replace(&self, projects: &[ProjectLibraries], cancel: &CancellationToken) -> IdeResult<()> {
let deadline = tokio::time::Instant::now() + IMPORT_WAIT;
let mut delays = RETRY_DELAYS.iter();
loop {
let Err(error) = self.try_replace(projects, deadline, cancel).await else { return Ok(()) };
let Some(delay) = delays.next() else { return Err(error) };
if cancel.is_cancelled() || self.lsp.jdtls_stopped(&self.root) {
return Err(error);
}
tracing::info!("Kotlin libraries: {error}; trying again in {} s", delay.as_secs());
tokio::select! {
biased;
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
_ = tokio::time::sleep(*delay) => {}
}
if self.lsp.jdtls_stopped(&self.root) {
return Err(error);
}
}
}
/// [`replace`](Self::replace), with a background task while it waits for the import.
async fn publish(&self, projects: &[ProjectLibraries], cancel: &CancellationToken) -> IdeResult<()> {
let _waiting = (!self.lsp.jdtls_imported(&self.root)).then(|| {
let task = BuildTask::start(self.sink.clone(), cancel);
task.emit(Some("Waiting for jdtls to import the project".into()), None, false);
task
});
self.replace(projects, cancel).await
}
async fn try_replace(
&self,
projects: &[ProjectLibraries],
deadline: tokio::time::Instant,
cancel: &CancellationToken,
) -> IdeResult<()> {
let snapshot = serde_json::to_value(projects).map_err(|e| IdeError::internal(e.to_string()))?;
self.lsp.wait_jdtls_imported(&self.root, deadline, cancel).await?;
let response = self.lsp.jdtls_command_cancellable(&self.root, COMMAND, vec![snapshot], cancel).await?;
if response.as_u64().is_none() {
return Err(ide_core::IdeError::unavailable(
"Kotlin bridge command did not acknowledge its library snapshot",
));
return Err(IdeError::unavailable("Kotlin bridge command did not acknowledge its library snapshot"));
}
Ok(())
}
@@ -211,7 +254,7 @@ impl KotlinBridge {
};
// Clear entries persisted by an earlier incarnation only before our first build.
if !initialized {
if let Err(error) = self.replace(&[], &cancel).await {
if let Err(error) = self.publish(&[], &cancel).await {
if !cancel.is_cancelled() {
self.failure(error.message, &mut diagnostics, &mut last_failure);
}
@@ -238,7 +281,7 @@ impl KotlinBridge {
}
match result {
Ok(Ok(Outcome { success: true, projects, .. })) => {
match self.replace(&projects, &cancel).await {
match self.publish(&projects, &cancel).await {
Ok(()) => {
for old in published.drain(..) {
remove_directory(old).await;
@@ -423,6 +466,9 @@ impl DocumentObserver for KotlinBridge {
}
}
#[cfg(all(test, unix))]
mod replace_tests;
#[cfg(test)]
mod tests {
use super::*;
+305
Переглянути файл
@@ -0,0 +1,305 @@
//! The bridge against an in-memory jdtls that is still importing, refuses a snapshot or goes
//! away (#7726). Maven is a fake `mvnw` that reports a build without modules.
use super::*;
use ide_jsonrpc::{Handler, Peer};
use ide_language::{LanguageRegistry, LanguageServerConfig};
use ide_lsp::{LaunchError, Launcher};
use serde_json::{Value, json};
use std::os::unix::fs::PermissionsExt;
use std::sync::atomic::AtomicUsize;
use std::time::Instant;
/// Longer than the time a command may take once it was sent.
const LONG_IMPORT: Duration = Duration::from_secs(300);
const PAST_RETRY: Duration = Duration::from_secs(60);
#[derive(Default)]
struct Jdtls {
launches: AtomicUsize,
/// Whether each snapshot arrived after the running instance's `ServiceReady`.
replaces: Mutex<Vec<bool>>,
/// The snapshots refused from now on, by their position among all.
refused: Mutex<Vec<usize>>,
/// Requests are not answered while set.
stuck: AtomicBool,
importing: AtomicBool,
ready: AtomicBool,
peer: Mutex<Option<Peer>>,
}
impl Jdtls {
fn finish_import(&self) {
self.ready.store(true, Ordering::SeqCst);
let peer = self.peer.lock().clone().unwrap();
peer.notify("language/status", json!({ "type": "ServiceReady", "message": "ServiceReady" })).unwrap();
}
fn replaces(&self) -> Vec<bool> {
self.replaces.lock().clone()
}
}
struct Server(Arc<Jdtls>);
impl Handler for Server {
fn on_notification(&self, method: &str, _: Value) {
if method == "initialized" && !self.0.importing.load(Ordering::SeqCst) {
self.0.finish_import();
}
}
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
match method {
"initialize" => Ok(json!({ "capabilities": {} })),
"workspace/executeCommand" if params["command"] == COMMAND => {
let position = {
let mut replaces = self.0.replaces.lock();
replaces.push(self.0.ready.load(Ordering::SeqCst));
replaces.len() - 1
};
while self.0.stuck.load(Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(5));
}
if self.0.refused.lock().contains(&position) {
return Err((-32603, "Workspace is locked".into()));
}
Ok(json!(0))
}
_ => Ok(Value::Null),
}
}
}
struct Launch(Arc<Jdtls>);
impl Launcher for Launch {
fn launch(
&self,
config: &LanguageServerConfig,
_: &Path,
handler: Arc<dyn Handler>,
_: Box<dyn Fn(String) + Send + Sync>,
) -> Result<Peer, LaunchError> {
if config.name != "jdtls" {
return Err(LaunchError::Missing);
}
self.0.launches.fetch_add(1, Ordering::SeqCst);
self.0.ready.store(false, Ordering::SeqCst);
let (client, server) = tokio::io::duplex(1 << 20);
let (r, w) = tokio::io::split(server);
*self.0.peer.lock() = Some(Peer::connect(r, w, Arc::new(Server(self.0.clone()))));
let (r, w) = tokio::io::split(client);
Ok(Peer::connect(r, w, handler))
}
}
/// A background task's message (`None` when it starts or ends) and whether it is done.
type TaskUpdate = (Option<String>, bool);
struct Fixture {
_tmp: tempfile::TempDir,
jdtls: Arc<Jdtls>,
lsp: Arc<LspManager>,
bridge: Arc<KotlinBridge>,
tasks: Arc<Mutex<Vec<TaskUpdate>>>,
failures: Arc<Mutex<Vec<String>>>,
}
fn start(importing: bool, refused: &[usize]) -> Fixture {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let root = base.join("p");
std::fs::create_dir_all(root.join("src/main/kotlin")).unwrap();
std::fs::write(
root.join("pom.xml"),
"<project><groupId>g</groupId><artifactId>a</artifactId><version>1</version></project>",
)
.unwrap();
std::fs::write(root.join("src/main/kotlin/K.kt"), "class K\n").unwrap();
std::fs::write(
root.join("mvnw"),
"#!/bin/sh\nfor a; do case \"$a\" in -Dopenidea.kotlin.staging=*) echo '[]' > \"$(dirname \"${a#*=}\")/modules.json\";; esac; done\n",
)
.unwrap();
std::fs::set_permissions(root.join("mvnw"), std::fs::Permissions::from_mode(0o755)).unwrap();
let jdtls = Arc::new(Jdtls::default());
jdtls.importing.store(importing, Ordering::SeqCst);
*jdtls.refused.lock() = refused.to_vec();
let tasks: Arc<Mutex<Vec<_>>> = Arc::default();
let failures: Arc<Mutex<Vec<String>>> = Arc::default();
let sink: SharedSink = Arc::new({
let (tasks, failures) = (tasks.clone(), failures.clone());
move |e: IdeEvent| match e {
IdeEvent::Task { title, message, done, .. } if title == BuildTask::TITLE => {
tasks.lock().push((message, done))
}
IdeEvent::Notify { body, .. } => failures.lock().push(body.unwrap_or_default()),
_ => {}
}
});
let languages = Arc::new(LanguageRegistry::load(None).unwrap());
let lsp = LspManager::with_launcher(root.clone(), languages, sink.clone(), Arc::new(Launch(jdtls.clone())));
let bridge = KotlinBridge::new(
root,
base.join("cache"),
&base.join("data"),
Arc::new(SettingsStore::load(&base.join("config"), None)),
lsp.clone(),
sink,
Arc::new(AtomicBool::new(true)),
);
bridge.start(&tokio::runtime::Handle::current());
Fixture { _tmp: tmp, jdtls, lsp, bridge, tasks, failures }
}
impl Drop for Fixture {
fn drop(&mut self) {
self.jdtls.stuck.store(false, Ordering::SeqCst);
}
}
impl Fixture {
/// The bridge asked for jdtls and it was told `initialized`.
async fn until_running(&self) {
until("jdtls to run", || self.lsp.servers().iter().any(|s| s.name == "jdtls" && is_up(s.status))).await;
tokio::time::sleep(Duration::from_millis(100)).await;
}
async fn until_published(&self, replaces: usize) {
until("the libraries to be published", || self.jdtls.replaces().len() == replaces).await;
until("the task to end", || self.tasks.lock().last().is_some_and(|(_, done)| *done)).await;
}
fn jdtls_id(&self) -> ide_core::ServerId {
self.lsp.servers().iter().find(|s| s.name == "jdtls").unwrap().id
}
}
fn is_up(status: ide_core::event::ServerStatus) -> bool {
matches!(status, ide_core::event::ServerStatus::Ready | ide_core::event::ServerStatus::Busy)
}
async fn until(what: &str, done: impl Fn() -> bool) {
let deadline = Instant::now() + Duration::from_secs(30);
while !done() {
assert!(Instant::now() < deadline, "timed out waiting for {what}");
tokio::time::sleep(Duration::from_millis(20)).await;
}
}
/// Moves every timer on by `time` and lets what it wakes run.
async fn skip(time: Duration) {
tokio::time::pause();
tokio::time::advance(time).await;
tokio::time::resume();
tokio::time::sleep(Duration::from_millis(200)).await;
}
#[tokio::test]
async fn a_snapshot_waits_for_an_import_longer_than_the_command_timeout() {
let f = start(true, &[]);
f.until_running().await;
skip(LONG_IMPORT).await;
assert_eq!((f.jdtls.replaces(), f.failures.lock().clone()), (vec![], vec![]));
let waiting = f.tasks.lock().last().cloned().unwrap();
assert!(waiting.0.is_some_and(|m| m.contains("import")) && !waiting.1, "the wait shows in the status bar");
f.jdtls.finish_import();
f.until_published(2).await;
assert_eq!(f.jdtls.replaces(), [true, true], "only after ServiceReady");
assert!(f.failures.lock().is_empty());
f.bridge.shutdown().await;
}
#[tokio::test]
async fn refused_snapshots_are_sent_again() {
// The first snapshot clears earlier libraries, the third publishes the built ones.
let f = start(false, &[0, 2]);
until("the first snapshot", || f.jdtls.replaces().len() == 1).await;
skip(PAST_RETRY).await;
until("the built snapshot", || f.jdtls.replaces().len() == 3).await;
skip(PAST_RETRY).await;
f.until_published(4).await;
assert!(f.failures.lock().is_empty());
f.bridge.shutdown().await;
}
#[tokio::test]
async fn a_snapshot_that_times_out_is_sent_again() {
let f = start(false, &[]);
f.jdtls.stuck.store(true, Ordering::SeqCst);
until("the first snapshot", || f.jdtls.replaces().len() == 1).await;
skip(LONG_IMPORT).await;
f.jdtls.stuck.store(false, Ordering::SeqCst);
skip(PAST_RETRY).await;
f.until_published(3).await;
assert!(f.failures.lock().is_empty());
f.bridge.shutdown().await;
}
#[tokio::test]
async fn a_snapshot_refused_every_time_is_reported_once_and_dropped() {
let f = start(false, &[0, 1, 2, 3, 4, 5, 6, 7]);
for attempt in 1..=1 + RETRY_DELAYS.len() {
until("the next attempt", || f.jdtls.replaces().len() == attempt).await;
skip(PAST_RETRY).await;
}
until("the failure", || !f.failures.lock().is_empty()).await;
skip(LONG_IMPORT).await;
assert_eq!(f.jdtls.replaces().len(), 1 + RETRY_DELAYS.len());
assert!(matches!(&f.failures.lock()[..], [text] if text.contains("Workspace is locked")));
f.bridge.shutdown().await;
}
#[tokio::test]
async fn a_restart_during_the_import_waits_for_the_new_instance() {
let f = start(true, &[]);
f.until_running().await;
f.lsp.restart(f.jdtls_id()).await.unwrap();
skip(LONG_IMPORT).await;
assert_eq!(f.jdtls.launches.load(Ordering::SeqCst), 2);
f.jdtls.finish_import();
f.until_published(2).await;
assert_eq!(f.jdtls.replaces(), [true, true]);
assert!(f.failures.lock().is_empty());
f.bridge.shutdown().await;
}
#[tokio::test]
async fn a_server_lost_during_the_import_is_waited_for_again() {
let f = start(true, &[]);
f.until_running().await;
f.jdtls.peer.lock().take().unwrap().kill();
until("the restart after the crash", || f.jdtls.launches.load(Ordering::SeqCst) == 2).await;
f.until_running().await;
f.jdtls.finish_import();
skip(PAST_RETRY).await;
f.until_published(2).await;
assert_eq!(f.jdtls.replaces(), [true, true]);
assert!(f.failures.lock().is_empty());
f.bridge.shutdown().await;
}
#[tokio::test]
async fn stopping_jdtls_ends_the_wait_and_does_not_start_it_again() {
let f = start(true, &[]);
f.until_running().await;
f.lsp.stop(f.jdtls_id()).await.unwrap();
until("the failure", || !f.failures.lock().is_empty()).await;
skip(LONG_IMPORT).await;
assert_eq!(f.jdtls.launches.load(Ordering::SeqCst), 1);
assert!(f.jdtls.replaces().is_empty());
f.bridge.shutdown().await;
}
#[tokio::test]
async fn closing_the_project_ends_the_wait_at_once() {
let f = start(true, &[]);
f.until_running().await;
let closing = Instant::now();
f.bridge.shutdown().await;
assert!(closing.elapsed() < Duration::from_secs(5), "{:?}", closing.elapsed());
assert!(f.jdtls.replaces().is_empty());
assert!(f.failures.lock().is_empty());
assert!(f.tasks.lock().last().is_some_and(|(_, done)| *done), "the status bar task ends");
}
+5 -1
Переглянути файл
@@ -25,6 +25,8 @@ mod phpstan;
pub mod plugins;
mod project;
mod proxy;
mod python_move;
mod python_signature;
pub mod relay;
mod requests;
pub mod rpc;
@@ -514,7 +516,6 @@ impl Host {
watch.stop();
}
project.documents.clear_workspace_edit_history();
project.agents.detach_sinks();
project.flutter.stop();
project.devtools.stop();
project.widget_preview.stop();
@@ -527,8 +528,11 @@ impl Host {
let shutdown_agents = if !project.light
&& self.automations.retain_on_window_close(self, &project.root, &project.agents, agent_reason)
{
// Keep internal automation watchers/peer bridges subscribed while dropping UI sinks.
project.agents.detach_ui_sinks();
Vec::new()
} else {
project.agents.detach_sinks();
vec![project.agents.clone()]
};
let handle = self.spawn_project_shutdown(ShutdownWork {
+979
Переглянути файл
@@ -0,0 +1,979 @@
//! Built-in MCP tools for inspecting, previewing, configuring, and controlling
//! Agent Automations (`list_automations`, `preview_automation_schedule`,
//! `save_automation`, `control_automation`, and `schedule_next_run`).
//!
//! Safety invariants:
//! - Read-only tools (`list_automations`, `preview_automation_schedule`) are strictly scoped
//! to the target project (`call.root()`), never exposing `ChatOnly` or other projects' data.
//! - Project mutating tools (`save_automation`, `control_automation`) refuse recursive invocations
//! from unattended scheduled agent turns, never modify host-level login-service or
//! approval-ceiling settings, and always ask for interactive confirmation in an open trusted
//! project window (even when MCP brave mode is enabled).
//! - Self-chaining (`schedule_next_run`) requires zero human confirmation ONLY when the calling
//! session belongs to an automation whose user-configured `allowAgentSchedule` flag is `true`,
//! updates ONLY that single automation's next firing time and prompt (never creating additional
//! automations or widening workspace/permission boundaries), enforces a 60s minimum delay, and
//! respects `maxRuns` and `disableAfterMs` stop limits.
use crate::Host;
use crate::automations::SelfScheduleTime;
use crate::mcp::page::{OFFSET, Page};
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
use ide_agent::{
AgentAutomation, AgentConfigChoice, AgentPrompt, AutomationContinuity, AutomationPermissionMode, AutomationTrigger,
AutomationWorkspace, Isolation, SaveAutomationInput, export_markdown, format_trigger_timestamp,
parse_iso_timestamp_ms, parse_markdown,
};
use ide_core::settings::{AutomationMisfirePolicy, NewTaskApprovals};
use ide_core::{IdeError, IdeResult, IpcPath};
use serde_json::{Map, Value, json};
use std::path::Path;
use std::sync::Arc;
const DEFAULT_AUTOMATIONS_LIMIT: usize = 100;
const DEFAULT_RUNS_LIMIT: u32 = 20;
const MAX_RUNS_LIMIT: u32 = 200;
const PROMPT_PREVIEW_CHARS: usize = 400;
pub fn tools() -> Vec<Tool> {
vec![
list_automations(),
preview_automation_schedule(),
save_automation(),
control_automation(),
schedule_next_run(),
]
}
/// Standalone tools exposed to an internal automation `caller_task` even when its working folder
/// is not an open project window (e.g. `ChatOnly` or headless `--scheduler` runs).
pub(super) fn standalone_task_tools() -> Vec<ide_mcp::Tool> {
vec![schedule_next_run().metadata, preview_automation_schedule().metadata]
}
fn trigger_schema(description: &'static str) -> Value {
json!({
"type": "object",
"description": description,
"properties": {
"kind": {
"type": "string",
"enum": ["manual", "hourly", "daily", "weekdays", "weekly", "cron", "oneShot"],
"description": "Schedule kind"
},
"minute": {
"type": "integer",
"description": "Minute of the hour (0..=59) for `hourly`, `daily`, `weekdays`, and `weekly`"
},
"hour": {
"type": "integer",
"description": "Hour of the day in 24-hour time (0..=23) for `daily`, `weekdays`, and `weekly`"
},
"days": {
"type": "array",
"items": { "type": "integer" },
"description": "Weekdays (0 = Sunday .. 6 = Saturday) for `weekly`"
},
"expression": {
"type": "string",
"description": "5-field cron expression (`minute hour day-of-month month day-of-week`) for `cron`"
},
"timeZone": {
"type": "string",
"description": "IANA timezone name (for example `America/Los_Angeles` or `UTC`), or `local` (default)"
},
"runAtMs": {
"type": "number",
"description": "Epoch timestamp in milliseconds for `oneShot`"
}
},
"required": ["kind"]
})
}
fn parse_trigger_value(raw: &Value) -> IdeResult<AutomationTrigger> {
let mut normalized = raw.clone();
if let Some(obj) = normalized.as_object_mut() {
let needs_tz = matches!(
obj.get("kind").and_then(Value::as_str),
Some("hourly" | "daily" | "weekdays" | "weekly" | "cron")
);
if needs_tz && !obj.contains_key("timeZone") {
obj.insert("timeZone".into(), Value::String("local".into()));
}
}
serde_json::from_value::<AutomationTrigger>(normalized)
.map_err(|e| IdeError::invalid(format!("invalid `trigger`: {e}")))
}
fn ensure_not_scheduled_caller(call: &Call) -> IdeResult<()> {
if call.caller_session.as_ref().is_some_and(|c| c.in_scheduled_turn) {
return Err(IdeError::invalid(
"Unattended scheduled runs cannot create, modify, enable, delete, or trigger automations; use schedule_next_run if self-scheduling is enabled on this automation",
));
}
Ok(())
}
fn ensure_project_owns_automation(host: &Host, project_root: &Path, id: &str) -> IdeResult<AgentAutomation> {
let canon_project = dunce::canonicalize(project_root).unwrap_or_else(|_| project_root.to_path_buf());
let Some(auto) = host.automations.get(id) else {
return Err(IdeError::not_found(format!("unknown automation '{id}'")));
};
match &auto.workspace {
AutomationWorkspace::Project { root, .. } => {
let canon_auto = dunce::canonicalize(&root.0).unwrap_or_else(|_| root.0.clone());
if canon_auto != canon_project {
return Err(IdeError::not_found(format!("unknown automation '{id}'")));
}
}
AutomationWorkspace::ChatOnly => {
return Err(IdeError::not_found(format!("unknown automation '{id}'")));
}
}
Ok(auto)
}
fn format_automation_json(auto: &AgentAutomation, include_markdown: bool) -> IdeResult<Value> {
let mut val = serde_json::to_value(auto).map_err(|e| IdeError::internal(e.to_string()))?;
if let Some(obj) = val.as_object_mut() {
obj.insert("triggerSummary".into(), Value::String(auto.trigger.summary()));
if let Some(next_ms) = auto.next_run_ms
&& let Some(iso) = format_trigger_timestamp(&auto.trigger, next_ms)
{
obj.insert("nextRunIso".into(), Value::String(iso));
}
if let Some(ov_ms) = auto.next_run_override_ms
&& let Some(iso) = format_trigger_timestamp(&auto.trigger, ov_ms)
{
obj.insert("nextRunOverrideIso".into(), Value::String(iso));
}
if include_markdown {
obj.insert("markdown".into(), Value::String(export_markdown(auto)?));
}
}
Ok(val)
}
fn truncate_preview(text: &str, max_chars: usize) -> String {
let trimmed = text.trim();
let count = trimmed.chars().count();
if count <= max_chars {
trimmed.to_owned()
} else {
let mut head: String = trimmed.chars().take(max_chars).collect();
head.push('…');
head
}
}
fn describe_effective_permissions(host: &Host, requested: AutomationPermissionMode) -> String {
let ceiling = host.global_settings.effective().agents.new_task_approvals;
let req_label = match requested {
AutomationPermissionMode::Default => "default (ask before edits and commands)",
AutomationPermissionMode::Assisted => "assisted (auto-accept workspace edits, ask before commands)",
AutomationPermissionMode::AllowAll => "allowAll (auto-approve within command policy)",
};
match (requested, ceiling) {
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Ask)
| (AutomationPermissionMode::Assisted, NewTaskApprovals::Ask) => {
format!("{req_label} — capped at runtime to `ask` by Settings › Agents › New task approvals")
}
_ => req_label.to_owned(),
}
}
fn prepend_brave_mode_note(host: &Host, detail: String) -> String {
if host.global_settings.effective().mcp_server.run_without_confirmation {
format!(
"Note: automation schedules always ask first, even with \"Run tools without confirmation\" (brave mode) on.\n\n{detail}"
)
} else {
detail
}
}
fn list_automations() -> Tool {
Tool::new(
"list_automations",
"Lists the project's Agent Automations, recent run history, active in-session schedules (`Send Later` / `/loop`), and scheduler status.
Scoped strictly to the target project. Pass `automationId` to inspect one automation (and its runs), or `includeMarkdown=true` to include portable `.automation.md` definitions.",
|call| async move {
let page = Page::of(&call, DEFAULT_AUTOMATIONS_LIMIT)?;
let filter_id = call.opt_str("automationId")?;
let include_runs = call.flag("includeRuns", true)?;
let include_markdown = call.flag("includeMarkdown", false)?;
let runs_limit = match call.opt_i64("runsLimit")? {
None => DEFAULT_RUNS_LIMIT,
Some(n) if n <= 0 => return Err(IdeError::invalid("runsLimit must be > 0")),
Some(n) => (n as u32).min(MAX_RUNS_LIMIT),
};
let host = call.host();
let h = host.clone();
let project_agents = call.project.agents.clone();
let root = dunce::canonicalize(call.root()).unwrap_or_else(|_| call.root().to_path_buf());
host.blocking(move || {
let roots = [root];
let automations = if let Some(ref id) = filter_id {
vec![ensure_project_owns_automation(&h, &roots[0], id)?]
} else {
h.automations.list_scoped(Some(&roots), false)
};
let mut out = Map::new();
let paged = page.take(automations, &mut out);
let items: Vec<Value> = paged
.iter()
.map(|a| format_automation_json(a, include_markdown))
.collect::<IdeResult<_>>()?;
out.insert("automations".into(), Value::Array(items));
out.insert("availableProviders".into(), json!(project_agents.known_provider_ids()));
if include_runs {
let runs_page = h.automations.runs_scoped(
Some(&roots),
false,
filter_id.as_deref(),
None,
Some(runs_limit),
);
out.insert(
"runs".into(),
serde_json::to_value(runs_page.runs).map_err(|e| IdeError::internal(e.to_string()))?,
);
}
let session_schedules = h.automations.list_session_schedules_scoped(Some(&roots), None);
out.insert(
"sessionSchedules".into(),
serde_json::to_value(session_schedules).map_err(|e| IdeError::internal(e.to_string()))?,
);
let status = h.automations.host_status(&h, false, String::new());
let auto_start_enabled = h.global_settings.effective().agents.automations.auto_start_service;
out.insert(
"scheduler".into(),
json!({
"activeSchedules": status.active_schedules,
"runningRuns": status.running_runs,
"needsInputRuns": status.needs_input_runs,
"unreadRuns": status.unread_runs,
"nextRunMs": status.next_run_ms,
"autoStartServiceEnabled": auto_start_enabled,
"bootServiceKind": status.boot_service_kind,
"bootServiceRegistered": status.boot_service_registered,
}),
);
Output::json(Value::Object(out))
})
.await
},
)
.param(Param::optional("automationId", ParamType::String, "Optional automation ID in this project to inspect"))
.param(Param::optional("includeRuns", ParamType::Boolean, "Include recent run history (default true)"))
.param(Param::optional(
"runsLimit",
ParamType::Integer,
"Recent runs to return at most when `includeRuns` is true (default 20, max 200)",
))
.param(Param::optional(
"includeMarkdown",
ParamType::Boolean,
"Include portable `.automation.md` text on each automation (default false)",
))
.param(Param::optional("limit", ParamType::Integer, "Automations to return at most (default 100)"))
.param(Param::optional("offset", ParamType::Integer, OFFSET))
}
pub(super) fn run_preview_schedule_sync(host: &Host, args: &Value) -> IdeResult<Output> {
let raw_trigger =
args.get("trigger").ok_or_else(|| IdeError::invalid("missing or invalid argument `trigger`"))?.clone();
let trigger = parse_trigger_value(&raw_trigger)?;
let count = match args.get("count").filter(|v| !v.is_null()) {
None => 5u32,
Some(v) => {
let n = v.as_i64().ok_or_else(|| IdeError::invalid("count must be an integer"))?;
if !(1..=20).contains(&n) {
return Err(IdeError::invalid("count must be between 1 and 20"));
}
n as u32
}
};
let next_runs_ms = host.automations.preview_schedule_capped(&trigger, count, 20)?;
let next_runs_iso: Vec<String> =
next_runs_ms.iter().filter_map(|&ms| format_trigger_timestamp(&trigger, ms)).collect();
let mut out = json!({
"summary": trigger.summary(),
"nextRunsMs": next_runs_ms,
"nextRunsIso": next_runs_iso,
});
if let Some((expr, tz)) = trigger.to_cron()?
&& let Some(obj) = out.as_object_mut()
{
obj.insert("cronExpression".into(), Value::String(expr));
obj.insert("timeZone".into(), Value::String(tz));
}
Output::json(out)
}
fn preview_automation_schedule() -> Tool {
Tool::new(
"preview_automation_schedule",
"Validates an automation schedule `trigger` (5-field cron, preset schedule, or one-shot timestamp) and previews the next `count` firing times in both epoch milliseconds and zoned ISO-8601 timestamps.
Call this before `save_automation` to verify cron syntax and timezone behavior.",
|call| async move {
let host = call.host();
let h = host.clone();
let args = call.args.clone();
host.blocking(move || run_preview_schedule_sync(&h, &args)).await
},
)
.schema_param(
"trigger",
true,
trigger_schema("Schedule trigger to validate and preview (`manual`, `hourly`, `daily`, `weekdays`, `weekly`, `cron`, or `oneShot`)."),
)
.param(Param::optional("count", ParamType::Integer, "Upcoming firing times to preview (1..=20, default 5)"))
}
fn parse_isolation(raw: Option<&str>, fallback: Isolation) -> IdeResult<Isolation> {
match raw {
None => Ok(fallback),
Some("local") => Ok(Isolation::Local),
Some("worktree") => Ok(Isolation::Worktree),
Some(other) => Err(IdeError::invalid(format!("invalid `isolation` '{other}'; expected `local` or `worktree`"))),
}
}
fn parse_continuity(raw: Option<&str>, fallback: AutomationContinuity) -> IdeResult<AutomationContinuity> {
match raw {
None => Ok(fallback),
Some("newTask") => Ok(AutomationContinuity::NewTask),
Some("sameTask") => Ok(AutomationContinuity::SameTask),
Some(other) => {
Err(IdeError::invalid(format!("invalid `continuity` '{other}'; expected `newTask` or `sameTask`")))
}
}
}
fn parse_permissions(raw: Option<&str>, fallback: AutomationPermissionMode) -> IdeResult<AutomationPermissionMode> {
match raw {
None => Ok(fallback),
Some("default") => Ok(AutomationPermissionMode::Default),
Some("assisted") => Ok(AutomationPermissionMode::Assisted),
Some("allowAll") => Ok(AutomationPermissionMode::AllowAll),
Some(other) => Err(IdeError::invalid(format!(
"invalid `permissions` '{other}'; expected `default`, `assisted`, or `allowAll`"
))),
}
}
fn parse_misfire_policy(
raw: Option<&str>,
present: bool,
fallback: Option<AutomationMisfirePolicy>,
) -> IdeResult<Option<AutomationMisfirePolicy>> {
if !present {
return Ok(fallback);
}
match raw {
None | Some("inherit") => Ok(None),
Some("runOnce") => Ok(Some(AutomationMisfirePolicy::RunOnce)),
Some("skip") => Ok(Some(AutomationMisfirePolicy::Skip)),
Some(other) => Err(IdeError::invalid(format!(
"invalid `misfirePolicy` '{other}'; expected `runOnce`, `skip`, or `inherit`"
))),
}
}
fn parse_config_choices(raw: Option<&Value>, fallback: Vec<AgentConfigChoice>) -> IdeResult<Vec<AgentConfigChoice>> {
let Some(val) = raw.filter(|v| !v.is_null()) else {
return Ok(fallback);
};
serde_json::from_value::<Vec<AgentConfigChoice>>(val.clone())
.map_err(|e| IdeError::invalid(format!("invalid `config`: {e}")))
}
fn save_automation() -> Tool {
Tool::new(
"save_automation",
"Creates or updates a project-scoped Agent Automation in the target project (or imports a portable `.automation.md` template via `markdown`).
Validates the trigger, workspace trust, and provider first, then always asks the user for confirmation in an open project window (even in MCP brave mode).
Never modifies OS login-service settings (`autoStartService`) or global approval ceilings, and refuses calls from unattended scheduled runs.",
|call| async move {
ensure_not_scheduled_caller(&call)?;
call.project.require_trust()?;
let host = call.host();
let root = dunce::canonicalize(call.root()).unwrap_or_else(|_| call.root().to_path_buf());
let id = call.opt_str("id")?;
let existing = match id.as_deref() {
Some(existing_id) => Some(ensure_project_owns_automation(&host, &root, existing_id)?),
None => None,
};
let parsed_md = match call.opt_str("markdown")? {
Some(md) => Some(parse_markdown(&md)?),
None => None,
};
let name = call
.opt_str("name")?
.or_else(|| parsed_md.as_ref().map(|p| p.name.clone()))
.or_else(|| existing.as_ref().map(|e| e.name.clone()))
.map(|s| s.trim().to_owned())
.filter(|s| !s.is_empty())
.ok_or_else(|| IdeError::invalid("missing or empty `name`"))?;
let prompt_text = call
.opt_str("prompt")?
.or_else(|| parsed_md.as_ref().map(|p| p.prompt.clone()))
.or_else(|| existing.as_ref().map(|e| e.prompt.text.clone()))
.map(|s| s.trim().to_owned())
.filter(|s| !s.is_empty())
.ok_or_else(|| IdeError::invalid("missing or empty `prompt`"))?;
let provider = call
.opt_str("provider")?
.or_else(|| existing.as_ref().map(|e| e.provider.clone()))
.map(|s| s.trim().to_owned())
.filter(|s| !s.is_empty())
.ok_or_else(|| {
IdeError::invalid("missing or empty `provider` (for example `claude`, `codex`, or `copilot`)")
})?;
{
let agents = call.project.agents.clone();
let candidate = provider.clone();
let ok = host.blocking(move || Ok(agents.has_provider(&candidate))).await?;
if !ok {
let known = call.project.agents.known_provider_ids().join(", ");
return Err(IdeError::invalid(format!(
"unknown `provider` '{provider}'; available providers: {known}"
)));
}
}
let trigger = match call.args.get("trigger").filter(|v| !v.is_null()) {
Some(raw) => parse_trigger_value(raw)?,
None => parsed_md
.as_ref()
.map(|p| p.trigger.clone())
.or_else(|| existing.as_ref().map(|e| e.trigger.clone()))
.unwrap_or(AutomationTrigger::Manual),
};
let default_enabled = if parsed_md.is_some() || matches!(trigger, AutomationTrigger::Manual) {
false
} else {
existing.as_ref().is_none_or(|e| e.enabled)
};
let enabled = call.flag("enabled", default_enabled)?;
let (existing_isolation, existing_base, existing_auto_clean) = match existing.as_ref().map(|e| &e.workspace)
{
Some(AutomationWorkspace::Project { isolation, base, auto_clean_worktree, .. }) => {
(*isolation, base.clone(), *auto_clean_worktree)
}
_ => (Isolation::Local, None, true),
};
let isolation = parse_isolation(call.opt_str("isolation")?.as_deref(), existing_isolation)?;
let base = if call.args.get("base").is_some() {
call.opt_str("base")?.map(|b| b.trim().to_owned()).filter(|b| !b.is_empty())
} else {
existing_base
};
let auto_clean_worktree = call.flag("autoCleanWorktree", existing_auto_clean)?;
let continuity = parse_continuity(
call.opt_str("continuity")?.as_deref(),
existing.as_ref().map_or(AutomationContinuity::NewTask, |e| e.continuity),
)?;
let permissions = parse_permissions(
call.opt_str("permissions")?.as_deref(),
existing.as_ref().map_or(AutomationPermissionMode::Assisted, |e| e.permissions),
)?;
let config = parse_config_choices(
call.args.get("config"),
existing.as_ref().map(|e| e.config.clone()).unwrap_or_default(),
)?;
let misfire_policy = parse_misfire_policy(
call.opt_str("misfirePolicy")?.as_deref(),
call.args.get("misfirePolicy").is_some(),
existing.as_ref().and_then(|e| e.misfire_policy),
)?;
let disable_after_ms = match call.args.get("disableAfterMs") {
Some(Value::Null) => None,
Some(v) => {
let n = v.as_f64().ok_or_else(|| IdeError::invalid("disableAfterMs must be a number"))?;
if !n.is_finite() || n < 0.0 {
return Err(IdeError::invalid("disableAfterMs must be >= 0"));
}
(n > 0.0).then_some(n)
}
None => {
parsed_md.as_ref().and_then(|p| p.disable_after_ms).or(existing.as_ref().and_then(|e| e.disable_after_ms))
}
};
let max_runs = match call.opt_i64("maxRuns")? {
Some(n) if n < 0 => return Err(IdeError::invalid("maxRuns must be >= 0")),
Some(0) => None,
Some(n) => Some(n as u32),
None if call.args.get("maxRuns").is_some_and(Value::is_null) => None,
None => parsed_md.as_ref().and_then(|p| p.max_runs).or(existing.as_ref().and_then(|e| e.max_runs)),
};
let default_allow_self_schedule = parsed_md
.as_ref()
.map(|p| p.allow_agent_schedule)
.or_else(|| existing.as_ref().map(|e| e.allow_agent_schedule))
.unwrap_or(false);
let allow_agent_schedule = call.flag("allowAgentSchedule", default_allow_self_schedule)?;
let clear_override = call.flag("clearOverride", false)?;
let workspace = AutomationWorkspace::Project {
root: IpcPath(root),
isolation,
base: base.clone(),
auto_clean_worktree,
};
// Pre-validate workspace trust (including parent Git repository trust for worktrees)
// and trigger syntax BEFORE showing the UI confirmation dialog.
crate::automations::check_workspace_trust(&host, &workspace).map_err(IdeError::invalid)?;
let now = host.automations.now_ms();
let next_ms = trigger.next_run_after(now)?;
let preserves_future_override = existing.as_ref().is_some_and(|e| {
enabled
&& allow_agent_schedule
&& !clear_override
&& e.trigger == trigger
&& max_runs.is_none_or(|max| e.run_count < max)
&& e.next_run_override_ms.is_some_and(|ms| ms > now && disable_after_ms.is_none_or(|exp| ms < exp))
});
if enabled && matches!(trigger, AutomationTrigger::OneShot { .. }) && next_ms.is_none() && !preserves_future_override {
return Err(IdeError::invalid("one-shot timestamp must be in the future when enabled"));
}
let subject = match &existing {
Some(_) => format!("update automation `{name}`"),
None => format!("create automation `{name}`"),
};
let isolation_desc = match (&isolation, &base) {
(Isolation::Worktree, Some(b)) => format!("worktree (base: {b})"),
(Isolation::Worktree, None) => "worktree".to_owned(),
(Isolation::Local, _) => "local checkout".to_owned(),
};
let continuity_desc = match continuity {
AutomationContinuity::NewTask => "newTask",
AutomationContinuity::SameTask => "sameTask",
};
let self_sched_line = if allow_agent_schedule {
"\nSelf-scheduling: ALLOWED (runs can call schedule_next_run without confirmation)"
} else {
""
};
let mut detail = format!(
"Name: {name}\nSchedule: {} (enabled: {enabled}){self_sched_line}\nProvider: {provider}\nIsolation: {isolation_desc}\nContinuity: {continuity_desc}\nPermissions: {}\nPrompt:\n{}",
trigger.summary(),
describe_effective_permissions(&host, permissions),
truncate_preview(&prompt_text, PROMPT_PREVIEW_CHARS),
);
if let Some(existing) = &existing {
detail = format!("ID: {}\n{detail}", existing.id);
}
let detail = prepend_brave_mode_note(&host, detail);
call.confirm_always(&subject, Some(detail)).await?;
let prompt = AgentPrompt {
text: prompt_text,
files: existing.as_ref().map(|e| e.prompt.files.clone()).unwrap_or_default(),
images: existing.as_ref().map(|e| e.prompt.images.clone()).unwrap_or_default(),
};
let input = SaveAutomationInput {
id,
name,
enabled,
prompt,
workspace,
continuity,
provider,
config,
permissions,
mcp_overrides: existing.as_ref().map(|e| e.mcp_overrides.clone()).unwrap_or_default(),
skill_overrides: existing.as_ref().map(|e| e.skill_overrides.clone()).unwrap_or_default(),
memory_overrides: existing.as_ref().and_then(|e| e.memory_overrides.clone()),
trigger,
allow_agent_schedule,
clear_override,
misfire_policy,
disable_after_ms,
max_runs,
};
let h = host.clone();
let saved = host.blocking(move || h.automations.save(&h, input)).await?;
Output::json(json!({ "automation": format_automation_json(&saved, false)? }))
},
)
.write()
.param(Param::optional("id", ParamType::String, "Existing automation ID in this project to update; omit to create"))
.param(Param::optional(
"markdown",
ParamType::String,
"Optional `.automation.md` template (YAML frontmatter + prompt body); explicit fields override parsed values",
))
.param(Param::optional("name", ParamType::String, "Automation name (required when creating without `markdown`)"))
.param(Param::optional("prompt", ParamType::String, "Prompt sent to the agent on each run"))
.param(Param::optional(
"provider",
ParamType::String,
"Agent provider ID (for example `claude`, `codex`, `copilot`, `cursor`, or a custom ACP agent ID)",
))
.schema_param(
"trigger",
false,
trigger_schema("Schedule trigger (`manual`, `hourly`, `daily`, `weekdays`, `weekly`, `cron`, or `oneShot`). Defaults to `manual` on create."),
)
.param(Param::optional(
"enabled",
ParamType::Boolean,
"Whether the schedule is active (defaults to false for `manual` and `markdown` imports, true for new schedules)",
))
.param(Param::optional(
"allowAgentSchedule",
ParamType::Boolean,
"Allow runs of this automation to call `schedule_next_run` to set their own next firing time and prompt without interactive confirmation (default false)",
))
.param(Param::optional(
"clearOverride",
ParamType::Boolean,
"On updates, explicitly clear any pending agent-scheduled `nextRunOverrideMs` and `nextPromptOverride` (default false; non-schedule edits otherwise preserve a valid future override)",
))
.schema_param(
"isolation",
false,
json!({
"type": "string",
"enum": ["local", "worktree"],
"description": "Where runs execute: `local` (project checkout, default) or `worktree` (fresh Git worktree; recommended for unattended code edits)"
}),
)
.param(Param::optional("base", ParamType::String, "Optional base Git branch/ref when `isolation` is `worktree`"))
.param(Param::optional(
"autoCleanWorktree",
ParamType::Boolean,
"Automatically remove zero-diff worktrees after `newTask` worktree runs (default true)",
))
.schema_param(
"continuity",
false,
json!({
"type": "string",
"enum": ["newTask", "sameTask"],
"description": "`newTask` starts a fresh session each run (default); `sameTask` continues the previous session"
}),
)
.schema_param(
"permissions",
false,
json!({
"type": "string",
"enum": ["default", "assisted", "allowAll"],
"description": "Unattended approval level (`assisted` default); capped at runtime by Settings › Agents › New task approvals"
}),
)
.schema_param(
"config",
false,
json!({
"type": "array",
"description": "Optional session configuration choices (for example model, reasoning effort, or context window)",
"items": {
"type": "object",
"properties": {
"id": { "type": "string" },
"value": { "type": "string" }
},
"required": ["id", "value"]
}
}),
)
.schema_param(
"misfirePolicy",
false,
json!({
"type": "string",
"enum": ["runOnce", "skip", "inherit"],
"description": "Behavior after missed scheduled windows while asleep (`runOnce`, `skip`, or `inherit` host default)"
}),
)
.schema_param(
"disableAfterMs",
false,
json!({
"type": ["number", "null"],
"description": "Optional epoch timestamp (ms) after which the schedule disables automatically (`0` or `null` clears)"
}),
)
.param(Param::optional(
"maxRuns",
ParamType::Integer,
"Optional maximum run count before the schedule disables automatically (`0` clears)",
))
}
fn control_automation() -> Tool {
Tool::new(
"control_automation",
"Enables, pauses, runs immediately, or deletes an Agent Automation of the target project, or pauses all active schedules of the target project (`pause_all`).
Always asks for confirmation in an open project window first (even in MCP brave mode), and refuses calls from unattended scheduled runs.",
|call| async move {
ensure_not_scheduled_caller(&call)?;
call.project.require_trust()?;
let action = call.str("action")?;
let host = call.host();
let root = dunce::canonicalize(call.root()).unwrap_or_else(|_| call.root().to_path_buf());
match action.as_str() {
"pause_all" => {
let detail = prepend_brave_mode_note(
&host,
format!("Pause all enabled automations and session schedules in {}", root.display()),
);
call.confirm_always("pause all project automations", Some(detail)).await?;
let h = host.clone();
let roots = vec![root];
let paused_count =
host.blocking(move || h.automations.pause_all_scoped(&h, Some(&roots), false)).await?;
Output::json(json!({
"action": "pause_all",
"pausedCount": paused_count,
}))
}
"enable" | "pause" | "run_now" | "delete" => {
let id = call.str("id")?;
let auto = ensure_project_owns_automation(&host, &root, &id)?;
if matches!(action.as_str(), "enable" | "run_now") {
crate::automations::check_workspace_trust(&host, &auto.workspace)
.map_err(IdeError::invalid)?;
}
if action == "enable" {
let now = host.automations.now_ms();
let next = auto.trigger.next_run_after(now)?;
let has_future_override = auto.next_run_override_ms.is_some_and(|ms| ms > now);
if matches!(auto.trigger, AutomationTrigger::OneShot { .. })
&& next.is_none()
&& !has_future_override
{
return Err(IdeError::invalid(
"one-shot timestamp is in the past; update its schedule before enabling",
));
}
}
let verb = match action.as_str() {
"enable" => "enable",
"pause" => "pause",
"run_now" => "run now",
"delete" => "delete",
_ => unreachable!(),
};
let subject = format!("{verb} automation `{}`", auto.name);
let detail = prepend_brave_mode_note(
&host,
format!(
"Action: {action}\nID: {}\nName: {}\nSchedule: {}\nProvider: {}\nPrompt:\n{}",
auto.id,
auto.name,
auto.trigger.summary(),
auto.provider,
truncate_preview(&auto.prompt.text, PROMPT_PREVIEW_CHARS),
),
);
call.confirm_always(&subject, Some(detail)).await?;
match action.as_str() {
"enable" | "pause" => {
let enabled = action == "enable";
let h = host.clone();
let updated = host.blocking(move || h.automations.set_enabled(&h, &id, enabled)).await?;
Output::json(json!({
"action": action,
"automation": format_automation_json(&updated, false)?,
}))
}
"run_now" => {
let run = host.automations.clone().run_now(&host, &id).await?;
Output::json(json!({
"action": "run_now",
"run": run,
}))
}
"delete" => {
let h = host.clone();
let target_id = id.clone();
host.blocking(move || h.automations.delete(&h, &target_id)).await?;
Output::json(json!({
"action": "delete",
"deletedId": id,
}))
}
_ => unreachable!(),
}
}
other => Err(IdeError::invalid(format!(
"invalid `action` '{other}'; expected `enable`, `pause`, `pause_all`, `run_now`, or `delete`"
))),
}
},
)
.write()
.schema_param(
"action",
true,
json!({
"type": "string",
"enum": ["enable", "pause", "pause_all", "run_now", "delete"],
"description": "Action to perform on this project's automations"
}),
)
.param(Param::optional(
"id",
ParamType::String,
"Automation ID in this project (required for `enable`, `pause`, `run_now`, and `delete`)",
))
}
pub(super) fn run_schedule_next_run_sync(
host: &Arc<Host>,
caller_session: Option<&ide_agent::McpCallerSession>,
args: &Value,
) -> IdeResult<Output> {
let Some(caller) = caller_session else {
return Err(IdeError::invalid(
"schedule_next_run can only be called from an active Agent Automation run inside OpenIDEA; use save_automation to create a new automation",
));
};
let done = match args.get("done").filter(|v| !v.is_null()) {
Some(v) => v.as_bool().ok_or_else(|| IdeError::invalid("done must be a boolean"))?,
None => false,
};
let prompt = match args.get("prompt").filter(|v| !v.is_null()) {
Some(v) => Some(v.as_str().map(str::to_owned).ok_or_else(|| IdeError::invalid("prompt must be a string"))?),
None => None,
};
let opt_f64 = |key: &str| -> IdeResult<Option<f64>> {
match args.get(key).filter(|v| !v.is_null()) {
None => Ok(None),
Some(v) => {
let n = v.as_f64().ok_or_else(|| IdeError::invalid(format!("{key} must be a number")))?;
if !n.is_finite() || n <= 0.0 {
return Err(IdeError::invalid(format!("{key} must be > 0")));
}
Ok(Some(n))
}
}
};
let delay_minutes = opt_f64("delayMinutes")?;
let delay_seconds = opt_f64("delaySeconds")?;
let run_at_ms = opt_f64("runAtMs")?;
let run_at_iso = match args.get("runAtIso").filter(|v| !v.is_null()) {
None => None,
Some(v) => {
let s = v.as_str().ok_or_else(|| IdeError::invalid("runAtIso must be a string"))?;
Some(parse_iso_timestamp_ms(s)?)
}
};
let provided_timing = [delay_minutes.is_some(), delay_seconds.is_some(), run_at_ms.is_some(), run_at_iso.is_some()]
.into_iter()
.filter(|&b| b)
.count();
if done && (provided_timing > 0 || prompt.is_some()) {
return Err(IdeError::invalid(
"cannot combine `done: true` with `prompt`, `delayMinutes`, `delaySeconds`, `runAtIso`, or `runAtMs`",
));
}
if !done && provided_timing != 1 {
return Err(IdeError::invalid(
"specify exactly one of `delayMinutes`, `delaySeconds`, `runAtIso`, or `runAtMs` (or `done: true` to clear override)",
));
}
let schedule = delay_minutes
.map(|mins| SelfScheduleTime::After(mins * 60_000.0))
.or_else(|| delay_seconds.map(|secs| SelfScheduleTime::After(secs * 1_000.0)))
.or_else(|| run_at_ms.or(run_at_iso).map(SelfScheduleTime::At));
let updated = host.automations.schedule_next_run_from_agent(host, caller, schedule, prompt)?;
let next_iso = updated.next_run_ms.and_then(|ms| format_trigger_timestamp(&updated.trigger, ms));
Output::json(json!({
"scheduled": !done,
"nextRunMs": updated.next_run_ms,
"nextRunIso": next_iso,
"nextRunOverrideMs": updated.next_run_override_ms,
"nextPromptOverride": updated.next_prompt_override,
"automation": format_automation_json(&updated, false)?,
}))
}
fn schedule_next_run() -> Tool {
Tool::new(
"schedule_next_run",
"Schedules a one-time next-run override (`nextRunOverrideMs` and optional `nextPromptOverride`) for the currently executing Agent Automation without human confirmation, or clears any pending override (`done: true`) so the regular schedule continues (leaving `manual` automations idle and disabling elapsed `oneShot` automations).
Keeps the automation's configured `trigger` and base `prompt` intact, works only during an active scheduled run of an automation with `allowAgentSchedule` enabled (including `oneShot` seed runs, which auto-disable once a run completes without scheduling a follow-up), enforces a 60-second minimum delay, and respects `maxRuns` and `disableAfterMs` limits.",
|call| async move {
let host = call.host();
let h = host.clone();
let caller_session = call.caller_session.clone();
let args = call.args.clone();
host.blocking(move || run_schedule_next_run_sync(&h, caller_session.as_ref(), &args)).await
},
)
.write()
.schema_param(
"delayMinutes",
false,
json!({
"type": "number",
"description": "Minutes from now until the next run (>= 1; supports fractional minutes)"
}),
)
.schema_param(
"delaySeconds",
false,
json!({
"type": "number",
"description": "Seconds from now until the next run (>= 60)"
}),
)
.param(Param::optional(
"runAtIso",
ParamType::String,
"ISO-8601 / RFC-3339 timestamp with timezone offset for the next run (for example `2026-12-01T23:30:00-08:00`)",
))
.schema_param(
"runAtMs",
false,
json!({
"type": "number",
"description": "Epoch timestamp in milliseconds for the next run"
}),
)
.param(Param::optional(
"prompt",
ParamType::String,
"Optional updated prompt instructions for the next run; omit to keep the automation's current prompt",
))
.param(Param::optional(
"done",
ParamType::Boolean,
"Set `true` to clear the pending override and resume the configured schedule",
))
}
+81
Переглянути файл
@@ -1,4 +1,5 @@
//! Built-in IDE tools. Transport and discovery live in `ide-mcp`.
mod automations;
mod background;
mod check;
mod debug;
@@ -57,6 +58,7 @@ fn tools(local_desktop: bool) -> Vec<tool::Tool> {
if local_desktop {
tools.extend(devcontainer::tools());
}
tools.extend(automations::tools());
tools
}
@@ -194,6 +196,63 @@ impl ToolRegistry for Registry {
fn tools_without_project(&self) -> Vec<ide_mcp::Tool> {
tools_for(&self.0, Path::new(""), true)
}
fn tools_for_session_nonce(&self, session_nonce: &str) -> Option<Vec<ide_mcp::Tool>> {
let caller = self.0.automations.resolve_mcp_caller(&self.0, session_nonce)?;
Some(if caller.is_automation_session {
automations::standalone_task_tools()
} else {
self.tools_without_project()
})
}
fn call_for_session_nonce(
&self,
session_nonce: &str,
name: &str,
arguments: &str,
cancel: CancellationToken,
_client: &str,
) -> Option<Result<String, ToolCallError>> {
let Some(caller) = self.0.automations.resolve_mcp_caller(&self.0, session_nonce) else {
return Some(Err(ToolCallError::Failed("invalid or expired MCP session nonce".into())));
};
match name {
"schedule_next_run" => {
if cancel.is_cancelled() {
return Some(Err(ToolCallError::Failed(IdeError::cancelled().message)));
}
let args: serde_json::Value = match serde_json::from_str(arguments) {
Ok(v) => v,
Err(e) => return Some(Err(ToolCallError::Failed(e.to_string()))),
};
Some(
automations::run_schedule_next_run_sync(&self.0, Some(&caller), &args)
.map(|o| o.0)
.map_err(|e| ToolCallError::Failed(e.message)),
)
}
"preview_automation_schedule" if caller.active_automation_id.is_some() => {
if cancel.is_cancelled() {
return Some(Err(ToolCallError::Failed(IdeError::cancelled().message)));
}
let args: serde_json::Value = match serde_json::from_str(arguments) {
Ok(v) => v,
Err(e) => return Some(Err(ToolCallError::Failed(e.to_string()))),
};
Some(
automations::run_preview_schedule_sync(&self.0, &args)
.map(|o| o.0)
.map_err(|e| ToolCallError::Failed(e.message)),
)
}
"save_automation" | "control_automation" if caller.in_scheduled_turn => {
Some(Err(ToolCallError::Failed(
"Unattended scheduled runs cannot create, modify, enable, delete, or trigger automations; use schedule_next_run if self-scheduling is enabled on this automation"
.into(),
)))
}
_ => None,
}
}
fn call(
&self,
root: &Path,
@@ -211,6 +270,26 @@ impl ToolRegistry for Registry {
cancel: CancellationToken,
client: &str,
) -> Result<String, ToolCallError> {
self.call_from(root, name, arguments, cancel, client, None)
}
fn call_from(
&self,
root: &Path,
name: &str,
arguments: &str,
cancel: CancellationToken,
client: &str,
session_nonce: Option<&str>,
) -> Result<String, ToolCallError> {
let caller_session = match session_nonce {
Some(nonce) => Some(
self.0
.automations
.resolve_mcp_caller(&self.0, nonce)
.ok_or_else(|| ToolCallError::Failed("invalid or expired MCP session nonce".into()))?,
),
None => None,
};
let unknown = || ToolCallError::UnknownTool(format!("unknown tool: {name}"));
// Before the project loads, so the refusal neither loads a background project nor
// unloads an idle one at the limit to make room.
@@ -240,6 +319,7 @@ impl ToolRegistry for Registry {
args,
cancel: cancel.clone(),
client: client.to_owned(),
caller_session,
tool: name.to_owned(),
};
if cancel.is_cancelled() {
@@ -285,6 +365,7 @@ impl Registry {
args,
cancel: cancel.clone(),
client: client.into(),
caller_session: None,
tool: metadata.name,
};
if cancel.is_cancelled() {
+1
Переглянути файл
@@ -237,6 +237,7 @@ mod tests {
let window = BackgroundProjects::key(&self.inventory);
Call {
client: "test-client".into(),
caller_session: None,
tool: "build_project".into(),
host: self.host.clone(),
project: self.host.open_project(&window, &self.inventory).unwrap(),
+10 -1
Переглянути файл
@@ -803,6 +803,10 @@ fn shell_invocation(shell: Option<&str>, line: &str) -> (String, Vec<String>) {
"cmd" => (line.to_owned(), Vec::new()),
"pwsh" | "powershell" => {
args.retain(|a| a != "-l");
// As in the terminal: script shims such as npm.ps1 run under the default policy.
if cfg!(windows) {
args.extend(["-ExecutionPolicy".to_owned(), "Bypass".to_owned()]);
}
args.extend(["-NoLogo".to_owned(), "-Command".to_owned(), line.to_owned()]);
(program, args)
}
@@ -1141,7 +1145,12 @@ mod tests {
assert_eq!(shell_invocation(Some("/bin/zsh"), "ls -a").1, ["-l", "-c", "ls -a"]);
assert_eq!(shell_invocation(Some("/bin/bash --norc"), "ls").1, ["--norc", "-c", "ls"]);
assert_eq!(shell_invocation(Some("/bin/tcsh"), "ls").1, ["-c", "ls"]);
assert_eq!(shell_invocation(Some("/usr/bin/pwsh"), "ls").1, ["-NoLogo", "-Command", "ls"]);
let pwsh: &[&str] = if cfg!(windows) {
&["-ExecutionPolicy", "Bypass", "-NoLogo", "-Command", "ls"]
} else {
&["-NoLogo", "-Command", "ls"]
};
assert_eq!(shell_invocation(Some("/usr/bin/pwsh"), "ls").1, pwsh);
assert_eq!(shell_invocation(Some("cmd.exe"), "dir /b"), ("dir /b".to_owned(), Vec::new()));
}
+3 -1
Переглянути файл
@@ -939,8 +939,10 @@ impl Walk {
continue;
}
let Ok(in_base) = entry.path.strip_prefix(base) else { continue };
let in_base = in_base.to_string_lossy().replace('\\', "/");
let mask = self.excludes.iter().find(|(b, _)| b == base).map(|(_, m)| m);
if mask.is_some_and(|m| !m.matches(&in_base.to_string_lossy().replace('\\', "/"))) {
if mask.is_some_and(|m| !m.matches(&in_base) || (entry.kind == EntryKind::Dir && m.excludes_dir(&in_base)))
{
continue;
}
match entry.kind {
+15
Переглянути файл
@@ -15,6 +15,7 @@ pub(crate) fn project_path() -> Value {
pub struct Call {
pub client: String,
pub caller_session: Option<ide_agent::McpCallerSession>,
pub tool: String,
pub host: Arc<Host>,
pub project: Arc<Project>,
@@ -92,6 +93,13 @@ impl Call {
if self.host.global_settings.effective().mcp_server.run_without_confirmation {
return self.project.require_trust();
}
self.confirm_always(subject, detail).await
}
/// Always asks the user in an open trusted project window, even when brave mode
/// (`mcpServer.runWithoutConfirmation`) is enabled. Used for persistent schedule mutations
/// and unattended-automation actions so prompt injection cannot silently install schedules.
pub async fn confirm_always(&self, subject: &str, detail: Option<String>) -> IdeResult<()> {
self.project.require_trust()?;
self.ask(ide_core::event::McpUiRequest::Confirm {
client: self.client.clone(),
tool: self.tool.clone(),
@@ -286,6 +294,13 @@ impl Tool {
}
self
}
pub fn schema_param(mut self, name: &'static str, required: bool, schema: Value) -> Self {
self.metadata.input_schema["properties"][name] = schema;
if required {
self.metadata.input_schema["required"].as_array_mut().unwrap().push(name.into());
}
self
}
pub fn output(mut self, schema: Value) -> Self {
self.metadata.output_schema = Some(schema);
self
+8
Переглянути файл
@@ -763,11 +763,19 @@ pub fn spec(os: Os) -> Vec<Entry> {
"Subversion",
vec![
act("svn.merge", "Merge From…"),
act("svn.updateOptions", "Update Directory…"),
act("svn.browseRepository", "Browse Repository…"),
act("svn.export", "Export…"),
act("svn.switchUrl", "Switch to URL…"),
act("svn.compareWithBranch", "Compare with Branch…"),
act("svn.configureBranches", "Configure Branches…"),
SEP,
act("svn.cleanup", "Cleanup"),
act("svn.lock", "Lock…"),
act("svn.unlock", "Unlock"),
act("svn.relocate", "Relocate…"),
act("svn.properties", "Properties…"),
act("svn.copyUrl", "Copy URL"),
],
),
SEP,
+216 -48
Переглянути файл
@@ -5,17 +5,17 @@ use crate::Host;
use crate::agent_secrets::{AgentSecrets, Kept};
use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentAutomation, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent,
AgentMarketplaceBrowseResult, AgentMemoryCatalog, AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemoryOverrides,
AgentMemorySettings, AgentModelCatalog, AgentPluginCatalog, AgentPluginPreview, AgentPluginSettings, AgentProbe,
AgentPrompt, AgentProvider, AgentProviderMemoryPolicy, AgentQueued, AgentRecoveryReport, AgentSkillMode,
AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode, AutomationRun, AutomationRunsPage,
AutomationSnapshot, AutomationTrigger, AutomationWorkspace, CopilotAuthStatus, CreateAgentMemoryInput,
CreateSessionScheduleInput, CustomAgentInput, ExternalSession, InstallAgentPluginRequest,
InstallRemoteSkillRequest, Isolation, LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult, McpScope,
McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput, RemoteSkillBrowseResult,
RemoteSkillPreview, SaveAutomationInput, SessionSchedule, SkillsPolicy,
AcpImportOutcome, AgentAcceptOutcome, AgentAutomation, AgentChange, AgentChanges, AgentChangesView,
AgentCliInstallResult, AgentCliOffer, AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry,
AgentEvent, AgentLoginEvent, AgentMarketplaceBrowseResult, AgentMemoryCatalog, AgentMemoryEntryPolicy,
AgentMemoryMode, AgentMemoryOverrides, AgentMemorySettings, AgentModelCatalog, AgentPluginCatalog,
AgentPluginPreview, AgentPluginSettings, AgentProbe, AgentPrompt, AgentProvider, AgentProviderMemoryPolicy,
AgentQueued, AgentRecoveryReport, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode,
AutomationRun, AutomationRunsPage, AutomationSnapshot, AutomationTrigger, AutomationWorkspace, CopilotAuthStatus,
CreateAgentMemoryInput, CreateSessionScheduleInput, CustomAgentInput, ExternalSession, InstallAgentPluginRequest,
InstallRemoteSkillRequest, Isolation, LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult,
McpRegistryPage, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput,
RemoteSkillBrowseResult, RemoteSkillPreview, SaveAutomationInput, SessionSchedule, SkillsPolicy,
};
use ide_command::command;
use ide_core::error::ErrorKind;
@@ -101,8 +101,10 @@ pub async fn agent_hermes_profiles(host: &Host, window: &str) -> IdeResult<Vec<i
}
/// Refreshes the model catalog; force bypasses freshness, not the cooldown.
/// Reads provider config and resolves the agent executable on PATH, so it runs on the
/// blocking pool.
#[command(trust = trusted)]
pub fn agent_refresh_models(
pub async fn agent_refresh_models(
host: &Host,
window: &str,
provider: String,
@@ -111,7 +113,8 @@ pub fn agent_refresh_models(
) -> IdeResult<AgentModelCatalog> {
// Refreshes the selected agent's model catalog without sending a prompt.
host.require_trust(window)?;
host.project(window)?.agents.refresh_models(&provider, force, model.as_deref())
let agents = host.project(window)?.agents.clone();
host.blocking(move || agents.refresh_models(&provider, force, model.as_deref())).await
}
/// Probes Copilot's model catalog for a staged GitHub account without persisting until Apply.
@@ -142,8 +145,8 @@ pub fn agent_set_additional_args(host: &Host, window: &str, id: String, args: Ve
host.project(window)?.agents.set_builtin_additional_args(&id, args)
}
/// Environment variables built-in agent `id` starts with (saved in its agent file);
/// an empty map clears them.
/// Environment variables built-in agent `id`, or an instance of one, starts with (saved in
/// its agent file); an empty map clears them.
#[command(trust = trusted)]
pub fn agent_set_env(
host: &Host,
@@ -201,6 +204,14 @@ fn prepare_login_launch_env(
}
}
/// `codex login` waits for the browser redirect on a loopback port of this host, which a browser on
/// the user's machine can't reach, and ignores the remote markers above.
fn use_device_auth(is_remote: bool, id: &str, args: &mut Vec<String>) {
if is_remote && matches!(id, "codex" | "codex-acp") && *args == ["login"] {
args.push("--device-auth".into());
}
}
fn apply_remote_login_env(host: &Host, cwd: &std::path::Path, target_is_gh: bool, launch: &mut LoginLaunch) {
let cwd = if cwd.is_dir() { cwd.to_path_buf() } else { dirs::home_dir().unwrap_or_else(std::env::temp_dir) };
prepare_login_launch_env(host.environment.is_remote(), target_is_gh, &mut launch.env, |key| {
@@ -242,6 +253,42 @@ fn spawn_login_pty(
)
}
async fn resolve_login_launch(
host: &Host,
window: &str,
id: &str,
) -> IdeResult<(std::path::PathBuf, LoginLaunch, String)> {
let agent = id.to_owned();
match host.project(window) {
Ok(project) => {
let root = project.root.clone();
let agents = project.agents.clone();
let base = agents.base_provider_id(&agent);
let launch = host.blocking(move || agents.login_launch(&agent)).await?;
Ok((root, launch, base))
}
Err(_) => {
let custom_dir = host.config_dir.join("agents");
let secrets = host.agent_secrets.clone();
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
let cwd_for_lookup = cwd.clone();
let (launch, base) = host
.blocking(move || {
let base = ide_agent::base_provider_id_without_project(Some(&custom_dir), &agent);
ide_agent::login_launch_without_project(
Some(&custom_dir),
Some(secrets.as_ref()),
&cwd_for_lookup,
&agent,
)
.map(|launch| (launch, base))
})
.await?;
Ok((cwd, launch, base))
}
}
}
/// Starts agent `id`'s interactive sign-in flow in an IDE-managed PTY and streams its output and exit code.
#[command(trust = outside_restricted)]
pub async fn agent_login_spawn(
@@ -253,26 +300,9 @@ pub async fn agent_login_spawn(
on_event: Channel<AgentLoginEvent>,
) -> IdeResult<ide_terminal::TerminalInfo> {
host.require_trust_if_project(window)?;
let (cwd, mut launch) = match host.project(window) {
Ok(project) => {
let root = project.root.clone();
let agents = project.agents.clone();
let launch = host.blocking(move || agents.login_launch(&id)).await?;
(root, launch)
}
Err(_) => {
let custom_dir = host.config_dir.join("agents");
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
let cwd_for_lookup = cwd.clone();
let launch = host
.blocking(move || {
ide_agent::login_launch_without_project(Some(&custom_dir), None, &cwd_for_lookup, &id)
})
.await?;
(cwd, launch)
}
};
let (cwd, mut launch, base) = resolve_login_launch(host, window, &id).await?;
apply_remote_login_env(host, &cwd, false, &mut launch);
use_device_auth(host.environment.is_remote(), &base, &mut launch.args);
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
}
@@ -296,22 +326,29 @@ pub async fn agent_gh_login_spawn(
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
}
/// Saves a new custom ACP agent through its agent file.
pub fn save_custom_agent(host: &Host, window: &str, input: CustomAgentInput) -> IdeResult<()> {
/// Saves a new custom ACP agent, or an instance of a built-in agent, through its agent
/// file; refuses built-in and ACP Registry ids and taken ids.
#[command(trust = trusted)]
pub async fn agent_custom_save(host: &Host, window: &str, input: CustomAgentInput) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.save_custom_agent(input)
let agents = host.project(window)?.agents.clone();
host.blocking(move || agents.save_custom_agent(input)).await
}
/// Removes a custom agent's file (registry installs go through `registry_remove`).
pub fn remove_custom_agent(host: &Host, window: &str, id: String) -> IdeResult<()> {
/// Removes a custom agent's file (registry installs go through `agent_registry_remove`).
#[command(trust = trusted)]
pub async fn agent_custom_remove(host: &Host, window: &str, id: String) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.remove_custom_agent(&id)
let agents = host.project(window)?.agents.clone();
host.blocking(move || agents.remove_custom_agent(&id)).await
}
/// Imports a JetBrains `acp.json` file's `agent_servers` entries as custom agents.
pub fn import_acp_agents(host: &Host, window: &str, text: String) -> IdeResult<Vec<AcpImportOutcome>> {
#[command(trust = trusted)]
pub async fn agent_custom_import(host: &Host, window: &str, text: String) -> IdeResult<Vec<AcpImportOutcome>> {
host.require_trust(window)?;
host.project(window)?.agents.import_acp_agents(&text)
let agents = host.project(window)?.agents.clone();
host.blocking(move || agents.import_acp_agents(&text)).await
}
/// Where ACP Registry agents are saved (`<config>/agents`, like the user's own) and installed.
@@ -596,6 +633,35 @@ pub async fn agent_cli_update_check(
cli_update(host, window, provider, None, request).await
}
/// Installs a missing built-in CLI on the project host using the command shown in Agent Setup.
#[command(trust = trusted)]
pub async fn agent_cli_install(
host: &Host,
window: &str,
provider: String,
approved_command: String,
request: RequestId,
) -> IdeResult<AgentCliInstallResult> {
host.require_trust(window)?;
let project = host.project(window)?;
let installing = Installing::begin(&provider)?;
let cancel = host.begin_project_request(window, request);
let projects = host.projects();
let result = blocking(move || {
let _installing = installing;
let result = project.agents.cli_install(&provider, &approved_command, &cancel)?;
if result == AgentCliInstallResult::Installed {
for project in projects {
project.agents.reload_providers();
}
}
Ok(result)
})
.await;
host.end_request(request);
result
}
/// Installs the exact version offered if the selected installation still matches.
#[command(trust = trusted)]
pub async fn agent_cli_update(
@@ -1159,6 +1225,42 @@ pub async fn agent_mcp_import_selected(
})
}
/// Searches or lists MCP servers from an open MCP Registry (`v0.1` / `v0`).
/// When `registry_url` is omitted or blank, uses `agents.mcpRegistryUrl` or GitHub's MCP Registry.
#[command(trust = always)]
pub async fn agent_mcp_registry_search(
host: &Host,
registry_url: Option<String>,
query: Option<String>,
cursor: Option<String>,
limit: Option<u32>,
request: RequestId,
) -> IdeResult<McpRegistryPage> {
let effective_url =
registry_url.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).or_else(|| {
let configured = host.global_settings.effective().agents.mcp_registry_url;
let trimmed = configured.trim();
(!trimmed.is_empty()).then(|| trimmed.to_owned())
});
let cancel = host.begin_request(request);
let search_path = ide_core::tool_path::search_path();
let res = blocking(move || {
let fetcher = ide_agent::mcp_registry::HttpMcpRegistryFetcher::new(&search_path)?;
ide_agent::mcp_registry::search_registry(
&fetcher,
effective_url.as_deref(),
query.as_deref(),
cursor.as_deref(),
limit,
&search_path,
&cancel,
)
})
.await;
host.end_request(request);
res
}
/// Tests an MCP server by connecting (`initialize`) and listing its tools (`tools/list`).
#[command(trust = trusted)]
pub async fn agent_mcp_test(host: &Host, window: &str, id: String) -> IdeResult<McpProbeResult> {
@@ -1394,11 +1496,12 @@ fn resolve_skills_with_host_plugins(
);
let projected = ide_agent::plugins::projected_skill_roots(&plug_states, None);
ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_agent_plugins(
ide_agent::skills::discover_skills_with_indexed_files(
&policy.workspace_roots,
home,
&policy.plugin_dirs,
&projected,
&policy.indexed_skill_files,
),
None,
&policy.workspace,
@@ -1618,6 +1721,13 @@ pub(crate) fn workspace_skill_roots(root: &std::path::Path) -> Vec<std::path::Pa
roots
}
/// Non-ignored `SKILL.md` files currently known to `index`, used to discover deeply nested
/// workspace skills without walking the filesystem again.
pub(crate) fn indexed_skill_files(index: &ide_index::ProjectIndex) -> Vec<std::path::PathBuf> {
let names = std::collections::HashSet::from([std::ffi::OsStr::new("SKILL.md")]);
index.files_with_names(&names)
}
/// The skill policies a session of `project` (or global Settings without a project) resolves against.
fn host_skills_policy(host: &Host, project: Option<&crate::Project>) -> SkillsPolicy {
match project {
@@ -1638,6 +1748,7 @@ fn host_skills_policy(host: &Host, project: Option<&crate::Project>) -> SkillsPo
workspace_trusted,
workspace_roots: workspace_skill_roots(&project.root),
plugin_dirs,
indexed_skill_files: indexed_skill_files(&project.index),
}
}
None => {
@@ -1648,6 +1759,7 @@ fn host_skills_policy(host: &Host, project: Option<&crate::Project>) -> SkillsPo
workspace_trusted: true,
workspace_roots: Vec::new(),
plugin_dirs,
indexed_skill_files: Vec::new(),
}
}
}
@@ -1798,11 +1910,10 @@ pub async fn agent_memory_set_auto(
) -> IdeResult<AgentMemoryCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
let (mut user, mut workspace) = memory_settings_layers(host, project.as_ref());
let prov_key = provider
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(|s| ide_agent::memory::normalize_provider_id(s).to_owned());
let prov_key = provider.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(|s| {
let base = project.as_ref().map(|p| p.agents.base_provider_id(s));
ide_agent::memory::normalize_provider_id(base.as_deref().unwrap_or(s)).to_owned()
});
let apply = |layer: &mut AgentMemorySettings| -> bool {
match &prov_key {
None => {
@@ -2749,6 +2860,19 @@ mod tests {
assert!(!reloaded.approved(&tmp.path().join("other"), "extra", &extra));
}
#[test]
fn codex_signs_in_with_a_device_code_only_on_a_remote_host() {
let args = |is_remote, id, args: &[&str]| {
let mut args = args.iter().map(|a| (*a).to_owned()).collect();
use_device_auth(is_remote, id, &mut args);
args
};
assert_eq!(args(true, "codex", &["login"]), ["login", "--device-auth"]);
assert_eq!(args(true, "codex-acp", &["login"]), ["login", "--device-auth"]);
assert_eq!(args(false, "codex", &["login"]), ["login"]);
assert_eq!(args(true, "copilot", &["login"]), ["login"]);
}
#[test]
fn prepare_login_launch_env_marks_remote_sessions_for_device_code_auth() {
let mut desktop_agent_env = std::collections::BTreeMap::new();
@@ -2782,6 +2906,45 @@ mod tests {
assert!(!ssh_env.contains_key("GH_BROWSER"));
assert!(!ssh_env.contains_key("GLAMOUR_STYLE"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn resolve_login_launch_without_project_reads_instance_env_from_secrets() {
ide_ssh::secrets::testing::use_memory_store();
let tmp = tempfile::tempdir().unwrap();
let host = Host::new(crate::HostConfig {
config_dir: tmp.path().join("config"),
data_dir: tmp.path().join("data"),
local_data_dir: tmp.path().join("data"),
languages: std::sync::Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: std::sync::Arc::default(),
sink_for: Box::new(|_| std::sync::Arc::new(ide_core::NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
let bin = tmp.path().join(if cfg!(windows) { "claude.cmd" } else { "claude" });
std::fs::write(&bin, if cfg!(windows) { "@echo off\r\n" } else { "#!/bin/sh\n" }).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let agents_dir = host.config_dir.join("agents");
std::fs::create_dir_all(&agents_dir).unwrap();
std::fs::write(
agents_dir.join("claude.toml"),
format!("driver = \"claude\"\ncommand = {:?}\n", bin.to_string_lossy()),
)
.unwrap();
std::fs::write(agents_dir.join("claude-work.toml"), "base = \"claude\"\n[env]\nCLAUDE_CONFIG_DIR = \"\"\n")
.unwrap();
host.agent_secrets.set("agent/claude-work/env/CLAUDE_CONFIG_DIR", "/home/me/.claude-work").unwrap();
let (_, launch, base) = resolve_login_launch(&host, "no-project", "claude-work").await.unwrap();
assert_eq!(base, "claude");
assert_eq!(launch.program, bin);
assert_eq!(launch.env.get("CLAUDE_CONFIG_DIR").map(String::as_str), Some("/home/me/.claude-work"));
}
}
ide_command::domain!(
@@ -2793,6 +2956,7 @@ ide_command::domain!(
agent_cancel,
agent_context_usage,
agent_changes,
agent_cli_install,
agent_cli_update,
agent_automation_delete,
agent_automation_export_markdown,
@@ -2809,6 +2973,9 @@ ide_command::domain!(
agent_commands,
agent_copilot_auth_status,
agent_create,
agent_custom_import,
agent_custom_remove,
agent_custom_save,
agent_delete,
agent_dismiss_interrupted,
agent_entries,
@@ -2825,6 +2992,7 @@ ide_command::domain!(
agent_mcp_import,
agent_mcp_import_selected,
agent_mcp_list,
agent_mcp_registry_search,
agent_mcp_remove,
agent_mcp_save,
agent_mcp_save_json,
+260 -33
Переглянути файл
@@ -12,7 +12,9 @@ use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
use ide_build::jbuild::Target;
use ide_build::maven::completion::{PomCompletion, PomCompletionOption};
use ide_build::maven::sources;
use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions};
use ide_build::maven::{
PomGoto, PomManagedDeclaration, PomNavigationOptions, default_local_repo, local_repository_of, user_settings_file,
};
use ide_build::pom_edit::{ArtifactKey, Exclusion};
use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress};
use ide_core::settings::Settings;
@@ -74,14 +76,7 @@ fn maven_modules(
/// the Maven home and options from Settings › Maven.
pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
let jdk = ide_sdk::apply::project_jdk(root, settings);
let mut model = ide_build::load_linked_with_jdk(
root,
cache,
ide_sdk::apply::maven_local_repository(root, settings),
&settings.languages.java.maven,
&settings.languages.java.gradle,
ide_sdk::apply::maven_jdk(root, settings, None).map(|jdk| jdk.major),
);
let mut model = load_synced(root, cache, settings);
if let Some(m) = &mut model.maven {
let mvn = ide_sdk::apply::maven_command(root, settings);
let options = ide_sdk::apply::maven_options(root, settings);
@@ -127,6 +122,49 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
model
}
/// The build model as [`sync_options`] syncs it: a load that differs in the JDK or the linked
/// projects finds its own last sync out of date.
fn load_synced(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
ide_build::load_linked_with_jdk(
root,
cache,
ide_sdk::apply::maven_local_repository(root, settings),
&settings.languages.java.maven,
&settings.languages.java.gradle,
maven_jdk_version(root, settings),
)
}
/// The JDK `<activation><jdk>` profiles are matched against.
fn maven_jdk_version(root: &Path, settings: &Settings) -> Option<u32> {
ide_sdk::apply::maven_jdk(root, settings, None).map(|jdk| jdk.major)
}
fn sync_options(
root: &Path,
settings: &Settings,
current: &BuildModel,
offline: bool,
profiles: &[String],
) -> SyncOptions {
let env = current
.maven
.as_ref()
.and_then(|m| m.projects.iter().find(|p| !p.env.is_empty()))
.map(|p| p.env.clone())
.unwrap_or_default();
SyncOptions {
offline,
profiles: profiles.to_vec(),
env,
jdk_version: maven_jdk_version(root, settings),
maven_command: ide_sdk::apply::maven_command(root, settings).map(|p| p.to_string_lossy().into_owned()),
maven_options: ide_sdk::apply::maven_options(root, settings),
maven_settings: settings.languages.java.maven.clone(),
gradle_command: None,
}
}
/// POM navigation follows the same profile choices as the last Maven sync and
/// resolves JDK-activated profiles with the project's selected Maven runtime.
fn pom_navigation_options(project: &Project, settings: &Settings) -> PomNavigationOptions {
@@ -140,7 +178,7 @@ fn pom_navigation_options(project: &Project, settings: &Settings) -> PomNavigati
local_repo: ide_sdk::apply::maven_local_repository(&project.root, settings)
.or_else(ide_build::maven::default_local_repo),
profiles,
jdk_version: ide_sdk::apply::maven_jdk(&project.root, settings, None).map(|jdk| jdk.major),
jdk_version: maven_jdk_version(&project.root, settings),
}
}
@@ -201,6 +239,57 @@ pub async fn build_model(host: &Host, window: &str) -> IdeResult<BuildModel> {
blocking(move || workspace::load_project(&project, &config)).await
}
/// Settings › Build Tools › Maven: the local repository the field's placeholder shows —
/// 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`. Reads files only; `home` may name `bin` or the `mvn` executable.
#[command(trust = always)]
pub async fn maven_local_repository(
host: &Host,
window: &str,
home: Option<String>,
user_settings: Option<String>,
) -> IdeResult<Option<String>> {
let root = host.project(window)?.root.clone();
let settings =
ide_core::settings::MavenSettings { user_settings: user_settings.unwrap_or_default(), ..Default::default() };
blocking(move || {
let user = user_settings_file(&root, &settings);
let global = home
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(maven_installation_root)
.map(|h| h.join("conf").join("settings.xml"));
let repository = user
.and_then(|settings| local_repository_of(&settings))
.or_else(|| global.and_then(|settings| local_repository_of(&settings)))
.or_else(default_local_repo);
Ok(repository.map(|p| ide_core::ipc_path::to_ipc(&p)))
})
.await
}
/// The Maven installation `home` names: a path to `bin`, `bin/mvn(.cmd|.bat)` or `mvn`
/// itself is reduced to the installation root. Either separator is accepted, so a Windows
/// path is reduced on any host.
fn maven_installation_root(home: &str) -> PathBuf {
let mut root = home.trim().trim_end_matches(['/', '\\']);
fn last(s: &str) -> String {
s.rsplit(['/', '\\']).next().unwrap_or(s).to_ascii_lowercase()
}
fn parent(s: &str) -> &str {
s.rfind(['/', '\\']).map_or("", |i| &s[..i])
}
if matches!(last(root).as_str(), "bin" | "mvn" | "mvn.cmd" | "mvn.bat") {
root = parent(root);
if last(root) == "bin" {
root = parent(root);
}
}
PathBuf::from(root)
}
/// Settings › CMake and the toolbar switcher: every profile, saved ones then presets (with
/// whether each is enabled), and why the presets file cannot be read, if it cannot.
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
@@ -524,21 +613,7 @@ pub async fn build_sync(
false
});
}
let env = current
.maven
.as_ref()
.and_then(|m| m.projects.iter().find(|p| !p.env.is_empty()))
.map(|p| p.env.clone())
.unwrap_or_default();
let options = SyncOptions {
offline,
profiles: profiles.clone(),
env,
maven_command: ide_sdk::apply::maven_command(root, settings).map(|p| p.to_string_lossy().into_owned()),
maven_options: ide_sdk::apply::maven_options(root, settings),
maven_settings: settings.languages.java.maven.clone(),
gradle_command: None,
};
let options = sync_options(root, settings, &current, offline, &profiles);
let progress = |p: SyncProgress| {
let _ = on_progress.send(p);
};
@@ -808,14 +883,7 @@ pub(crate) fn analyzed_dependencies(
) -> IdeResult<crate::plugins::BuildGraph> {
let mut graph = crate::plugins::BuildGraph::default();
for scope in workspace::scopes(project, config)?.iter().filter(|s| root == project.root || s.root == root) {
let settings = &scope.settings;
let model = ide_build::load_linked(
&scope.root,
&scope.cache,
ide_sdk::apply::maven_local_repository(&scope.root, settings),
&settings.languages.java.maven,
&settings.languages.java.gradle,
);
let model = load_synced(&scope.root, &scope.cache, &scope.settings);
graph.maven.extend(model.maven.into_iter().flat_map(|m| m.projects));
for build in &model.gradle {
let reports =
@@ -1502,6 +1570,92 @@ pub async fn build_compile_file(
Ok(outcome)
}
/// Run dotnet format: `dotnet format` on a solution or project file (`verify`:
/// `--verify-no-changes`), streaming like a build; cancellable with `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn build_dotnet_format(
host: &Host,
window: &str,
file: std::path::PathBuf,
verify: bool,
request: RequestId,
clear: Vec<std::path::PathBuf>,
on_event: Channel<BuildEvent>,
) -> IdeResult<BuildResult> {
let plan = move |file: &Path| compile::dotnet_format_plan(file, verify);
run_dotnet_plan(host, window, file, plan, request, clear, on_event).await
}
/// Publish a .NET project: `dotnet publish <file> <options>`, streaming like a build;
/// cancellable with `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn build_dotnet_publish(
host: &Host,
window: &str,
file: std::path::PathBuf,
options: Vec<String>,
request: RequestId,
clear: Vec<std::path::PathBuf>,
on_event: Channel<BuildEvent>,
) -> IdeResult<BuildResult> {
let plan = move |file: &Path| compile::dotnet_publish_plan(file, &options);
run_dotnet_plan(host, window, file, plan, request, clear, on_event).await
}
/// `dotnet build` / `clean` / `restore` of a solution or project from the .NET tool window,
/// streaming like a build; cancellable with `cancel_request(request)`.
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
pub async fn build_dotnet_command(
host: &Host,
window: &str,
file: std::path::PathBuf,
command: compile::DotnetCommand,
options: Vec<String>,
request: RequestId,
clear: Vec<std::path::PathBuf>,
on_event: Channel<BuildEvent>,
) -> IdeResult<BuildResult> {
let plan = move |file: &Path| compile::dotnet_command_plan(file, command, &options);
run_dotnet_plan(host, window, file, plan, request, clear, on_event).await
}
async fn run_dotnet_plan(
host: &Host,
window: &str,
file: std::path::PathBuf,
plan: impl FnOnce(&Path) -> IdeResult<compile::BuildPlan> + Send + 'static,
request: RequestId,
clear: Vec<std::path::PathBuf>,
on_event: Channel<BuildEvent>,
) -> IdeResult<BuildResult> {
host.require_trust(window)?;
let project = host.project(window)?;
let (root, sink) = (project.root.clone(), project.sink.clone());
let file = ide_core::project_roots::resolve(&root, &file);
let token = host.begin_project_request(window, request);
let result = blocking(move || {
for path in clear {
sink.emit(IdeEvent::Diagnostics {
path: path.into(),
source: compile::DIAGNOSTICS_SOURCE.into(),
items: Vec::new(),
});
}
let plan = plan(&file)?;
let result = compile::run(&root, &plan, &token, &|e| {
let _ = on_event.send(e);
})?;
for (path, items) in compile::diagnostics(&result.messages) {
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: compile::DIAGNOSTICS_SOURCE.into(), items });
}
Ok::<_, IdeError>(result)
})
.await;
host.end_request(request);
result
}
#[cfg(test)]
mod build_tool_settings_tests {
use super::*;
@@ -1701,6 +1855,58 @@ mod build_tool_settings_tests {
}
}
/// Each root (a project, or a member of a workspace) with its own JDK and a linked reactor.
#[cfg(unix)]
#[test]
fn a_maven_sync_is_current_for_the_jdk_of_its_root() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let mvn = base.join("maven/bin/mvn");
std::fs::create_dir_all(mvn.parent().unwrap()).unwrap();
std::fs::write(&mvn, "#!/bin/sh\n").unwrap();
std::fs::set_permissions(&mvn, std::fs::Permissions::from_mode(0o755)).unwrap();
for (name, version) in [("jdk8", "1.8"), ("jdk17", "17"), ("jdk21", "21")] {
let home = base.join(name);
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::write(home.join("bin/java"), "").unwrap();
std::fs::write(home.join("release"), format!("JAVA_VERSION=\"{version}\"\n")).unwrap();
}
let reactor = |dir: &Path, jdk: &str| {
std::fs::create_dir_all(dir.join("extra")).unwrap();
let pom = format!(
"<project><groupId>g</groupId><artifactId>a</artifactId><version>1</version><packaging>pom</packaging>\
<profiles><profile><id>p</id><activation><jdk>{jdk}</jdk></activation>\
<modules><module>extra</module></modules></profile></profiles></project>"
);
std::fs::write(dir.join("pom.xml"), pom).unwrap();
let module = "<project><groupId>g</groupId><artifactId>extra</artifactId><version>1</version></project>";
std::fs::write(dir.join("extra/pom.xml"), module).unwrap();
};
let scope = |name: &str, jdk: &str| {
let mut settings = Settings::default();
settings.languages.java.jdk = base.join(jdk).to_string_lossy().into_owned();
settings.languages.java.maven.home = base.join("maven").to_string_lossy().into_owned();
settings.languages.java.maven.linked_projects = vec!["linked/pom.xml".into()];
(base.join(name), base.join(name).join("cache"), settings)
};
let maven = |(root, cache, settings): &(PathBuf, PathBuf, Settings)| {
load(root, cache, settings).maven.map(|m| (m.projects.len(), m.stale)).unwrap()
};
let scopes = [scope("first", "jdk8"), scope("second", "jdk17"), scope("third", "jdk21")];
for scope in &scopes {
let (root, cache, settings) = scope;
reactor(root, "[11,)");
reactor(&root.join("linked"), "[21,)");
let current = load(root, cache, settings);
let options = sync_options(root, settings, &current, false, &[]);
ide_build::sync_maven(root, cache, &options, &ide_core::CancellationToken::new(), &|_| {}).unwrap();
}
assert_eq!(scopes.each_ref().map(maven), [(2, false), (3, false), (4, false)]);
assert_eq!(maven(&scope("second", "jdk8")), (2, true));
assert_eq!(maven(&scope("second", "jdk21")), (4, true));
}
#[test]
fn model_for_sync_tasks_and_compile_uses_gradle_settings() {
let tmp = tempfile::tempdir().unwrap();
@@ -1892,6 +2098,9 @@ mod maven_completion_tests {
ide_command::domain!(
build:
build_compile_file,
build_dotnet_command,
build_dotnet_format,
build_dotnet_publish,
build_model,
build_run,
build_sync,
@@ -1906,11 +2115,29 @@ ide_command::domain!(
maven_dependency_declaration,
maven_exclude_dependency,
maven_goto_declaration,
maven_local_repository,
maven_managed_declarations,
toolchain_check,
toolchains_detect,
);
#[cfg(test)]
mod maven_installation_root_tests {
use super::maven_installation_root;
#[test]
fn reduces_bin_and_mvn_paths_to_the_installation_root() {
assert_eq!(maven_installation_root("/opt/maven-3.9"), std::path::PathBuf::from("/opt/maven-3.9"));
assert_eq!(maven_installation_root("/opt/maven-3.9/bin"), std::path::PathBuf::from("/opt/maven-3.9"));
assert_eq!(maven_installation_root("/opt/maven-3.9/bin/mvn"), std::path::PathBuf::from("/opt/maven-3.9"));
assert_eq!(
maven_installation_root("C:\\tools\\maven\\bin\\mvn.cmd"),
std::path::PathBuf::from("C:\\tools\\maven")
);
assert_eq!(maven_installation_root(" /opt/maven-3.9/ "), std::path::PathBuf::from("/opt/maven-3.9"));
}
}
#[cfg(test)]
mod cmake_reset_tests {
use super::reset_cmake_cache;
+2 -2
Переглянути файл
@@ -236,8 +236,8 @@ pub async fn doc_python_facts(host: &Host, window: &str, doc: DocId) -> IdeResul
blocking(move || Ok(syntax.python_facts(&snap.language, &snap.text))).await
}
/// Rearrange Code: the edits that put the document's class members in arrangement order (Python
/// for now); none when they already are or the language has no arrangement.
/// Rearrange Code: the edits that put the document's class members in arrangement order (Python,
/// TypeScript and JavaScript); none when they already are or the language has no arrangement.
#[command(trust = always)]
pub async fn doc_rearrange(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<TextEdit>> {
let project = host.project(window)?;
+4
Переглянути файл
@@ -126,6 +126,10 @@ async fn save_as_copies_the_current_buffer_and_leaves_the_source_on_disk() {
.unwrap();
let target = f.outside.with_extension("copy.txt");
std::fs::write(&target, "old\n").unwrap();
let error = doc_copy_as(&f.host, "main", original.id, target.clone()).await.unwrap_err();
assert_eq!(error.kind, ide_core::error::ErrorKind::AlreadyExists);
assert_eq!(std::fs::read_to_string(&target).unwrap(), "old\n");
std::fs::remove_file(&target).unwrap();
assert!(doc_copy_as(&f.host, "main", original.id, target.clone()).await.unwrap());
+48 -13
Переглянути файл
@@ -230,6 +230,18 @@ pub async fn fs_read_dir(host: &Host, window: &str, path: PathBuf) -> IdeResult<
.await
}
fn notify_vcs_of_created_file(project: &Project, path: &Path) {
let paths = &[path.to_path_buf()];
let result = project.with_backend_of(path, |backend| match super::svn::as_svn(backend) {
// New SVN paths go through the same frontend confirmation as Git's.
Some(wc) => wc.restore_recreated_files(paths),
None => backend.files_added(paths),
});
if let Err(e) = result {
tracing::debug!("vcs files_added for {}: {e}", path.display());
}
}
/// Creates an empty file; inside a project, honours the EditorConfig
/// `charset` (writes the BOM for `utf-8-bom` / UTF-16).
#[command(trust = always)]
@@ -248,10 +260,7 @@ pub fn fs_create_file(host: &Host, window: &str, path: PathBuf) -> IdeResult<()>
if empty && !bom.is_empty() {
std::fs::write(&path, bom)?;
}
// A checkout backend opens the file for add; Git's hook is a no-op.
if let Err(e) = p.with_backend_of(&path, |r| r.files_added(std::slice::from_ref(&path))) {
tracing::debug!("vcs files_added for {}: {e}", path.display());
}
notify_vcs_of_created_file(&p, &path);
Ok(())
}
Err(_) => ide_vfs::create_file(&path),
@@ -263,10 +272,8 @@ pub async fn fs_create_file_bytes(host: &Host, window: &str, path: PathBuf, data
let project = host.project(window).ok();
host.blocking(move || {
ide_vfs::create_file_bytes(&path, &data)?;
if let Some(p) = project
&& let Err(e) = p.with_backend_of(&path, |r| r.files_added(std::slice::from_ref(&path)))
{
tracing::debug!("vcs files_added for {}: {e}", path.display());
if let Some(p) = project {
notify_vcs_of_created_file(&p, &path);
}
Ok(())
})
@@ -399,17 +406,20 @@ pub async fn fs_copy(host: &Host, window: &str, from: PathBuf, to: PathBuf) -> I
let project = host.project(window).ok();
host.blocking(move || {
ide_workspace::file_ops::copy(&from, &to)?;
// A copy is an add at the destination; Git's hook is a no-op.
if let Some(p) = project
&& let Err(e) = p.with_backend_of(&to, |r| r.files_added(std::slice::from_ref(&to)))
{
tracing::debug!("vcs files_added for {}: {e}", to.display());
if let Some(p) = project {
notify_vcs_of_created_file(&p, &to);
}
Ok(())
})
.await
}
/// Whether both paths reach the same file, however they are spelled; fails when either is missing.
#[command(trust = always)]
pub async fn fs_same_file(host: &Host, a: PathBuf, b: PathBuf) -> IdeResult<bool> {
host.blocking(move || ide_vfs::same_file(&a, &b)).await
}
#[command(trust = always)]
pub async fn fs_rename(host: &Host, window: &str, from: PathBuf, to: PathBuf) -> IdeResult<()> {
let project = host.project(window).ok();
@@ -439,6 +449,29 @@ pub async fn fs_read_text(host: &Host, window: &str, path: PathBuf) -> IdeResult
.await
}
/// Reads many text files in one call, as `fs_read_text` does each (usage lists show a line from
/// each of hundreds of files): `None` for one that can't be read.
#[command(trust = always)]
pub async fn fs_read_texts(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<Vec<Option<String>>> {
let project = host.project(window).ok();
host.blocking(move || {
let read = |path: &PathBuf| match &project {
Some(p) => p.text_of(path).ok(),
None => ide_vfs::load_text(path).ok().map(|t| t.text),
};
let workers = std::thread::available_parallelism().map_or(4, |n| n.get().min(8));
let chunk = paths.len().div_ceil(workers).max(1);
Ok(std::thread::scope(|scope| {
let parts: Vec<_> = paths
.chunks(chunk)
.map(|part| (part.len(), scope.spawn(move || part.iter().map(read).collect::<Vec<_>>())))
.collect();
parts.into_iter().flat_map(|(len, h)| h.join().unwrap_or_else(|_| vec![None; len])).collect()
}))
})
.await
}
/// The file `window` may hand to the OS's default application: `path` itself, resolved, when it is a
/// file inside the window's project (its folder or a content root). The window must be trusted and
/// open locally; a remote window's files live on its own machine and are not launched here.
@@ -550,7 +583,9 @@ ide_command::domain!(
fs_entry_kind,
fs_read_dir,
fs_read_text,
fs_read_texts,
fs_rename,
fs_same_file,
fs_scratches_dir,
fs_set_writable,
fs_synchronize_directories,
+4 -2
Переглянути файл
@@ -102,16 +102,18 @@ pub async fn http_environment_file(host: &Host, window: &str, path: IpcPath, is_
}
/// Where `{{name}}` is defined in the environment files that apply to request file `path`
/// (Navigate › Declaration on a variable), private file first.
/// (Navigate › Declaration on a variable), private file first. With `env`, only the key a request
/// run in that environment reads.
#[command(trust = trusted)]
pub async fn http_variable_definitions(
host: &Host,
window: &str,
path: IpcPath,
name: String,
env: Option<String>,
) -> IdeResult<Vec<Location>> {
let root = root(host, window);
blocking(move || Ok(ide_http::env::variable_definitions(&path, root.as_deref(), &name))).await
blocking(move || Ok(ide_http::env::variable_definitions(&path, root.as_deref(), &name, env.as_deref()))).await
}
ide_command::domain!(
Loaded 100 of 1591 files, more files were not shown because too many files have changed in this diff. Show more