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

...
Автор SHA1 Повідомлення Дата
l0ng-ai e6e2bdb80d fix(agents): add scheduling to the new task composer 2026-12-03 23:28:49 +08:00
l0ng-ai 6e5f91f7fd feat(agents): add a New Agent Task button to the main toolbar (#7718)
The main toolbar shows New Agent Task by default, between the Run widget and Search. It carries the selected agent's icon and runs agents.newTask; its menu lists the installed agents to start a task with another one, and ends with More Agents. Customize Main Toolbar can remove it. Below 480px the button is hidden so the toolbar keeps fitting the window.

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

Closes #7817

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

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

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

Closes #7810

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

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

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

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

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

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

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

Closes #7784

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

Closes #7795

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

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

Closes #7665
Closes #7734

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

Part of #7688.

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

Part of #7688.

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

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

Part of #7688.

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

Part of #7688.

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

Part of #7688.

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

Part of #7688.

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

Part of #7688.

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

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

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

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

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

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

Closes #7729

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

Refs #7140

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

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

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

Closes #7758

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

Refs #7433

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

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

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

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

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

Closes #7777

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

Closes #7754

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

Closes #7765

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

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

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

Closes #7726

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

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

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

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

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

Closes #7728

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

Closes #7704

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

Closes #7725

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

Closes #7749

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

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

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

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

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

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

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

Closes #7712

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

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

Refs #901

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

Refs #901

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

Refs #4968

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

Closes #7656

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

Closes #7637

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

Closes #7626

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

Closes #7646

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

Closes #7631

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

Refs #7619

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

Part of #4968

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

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

Closes #7664

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

Refs #7675

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

Refs #4582

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

Refs #4582

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

Refs #4582

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

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

Closes #7678

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

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

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

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

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

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

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

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

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

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

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

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

Closes #7644

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

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

Closes #7630

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

Closes #7635

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

Closes #7672

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

Refs #7651

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

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

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

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

Closes #7668

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

Closes #7628

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

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

Closes #7531

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

Closes #7639

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

Closes #7614

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

Closes #7609

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

Refs #7433

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

Refs #4582

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Closes #7554

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Refs #7419

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

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

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

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

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

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

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

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

Fixes #7178

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

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

Closes #7555

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

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

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

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

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

Closes #7334

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

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

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

Closes #7483

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

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

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

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

Closes #7543

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

Fixes #7438

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

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

Closes #7528

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

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

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

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

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

Closes #7467

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

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

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

Closes #7439

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

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

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

Fixes #7450

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

Fixes #7458

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

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

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

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

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

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

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

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

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

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

Closes #7293

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

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

Closes #7506

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

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

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

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

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

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

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

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

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

Refs #7444

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

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

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

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

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

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

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

Closes #7453

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Closes #7337

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

Closes #615

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

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

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

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

Closes #7410

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

Closes #7369

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

Closes #7335

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

Closes #7333

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

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

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

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

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

Closes #7348

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

Closes #7326

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

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

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

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

Closes #7393

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

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

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

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

Closes #7387

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

Closes #7383

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

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

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

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

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

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

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

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

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

Covered by valueHint.test.ts.

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

Covered by Dialog and Search Everywhere tests.

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

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

Covered by navigationInterfaceMark.test.ts.

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

Covered by max_depth_counts_the_levels_below_the_directory.

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

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

Fixes #7367

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

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

Fixes #7354

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

Covered by e2e/usagesPopupLayout.spec.ts.

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

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

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

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

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

Closes #7324

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

Closes #7332

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

Closes #7330

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

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

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

Closes #7312

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

Closes #7311

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

Closes #7273

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

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

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

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

Closes #6872

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

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

Closes #6942

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

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

Closes #6876

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

Closes #7306

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

Closes #7313

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

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

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

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

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

Closes #7295

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

Closes #7297

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

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

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

Fixes #7169

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

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

Closes #7274

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

Closes #7289

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

Closes #7267

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

Closes #7270

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

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

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

Closes #7277

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

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

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

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

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

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

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

Fixes #7246

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

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

Fixes #7264

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

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

Fixes #7261

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

Closes #7250

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

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

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

Closes #7247

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

Closes #178

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

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

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

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

---------

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

Fixes #7236
Fixes #7237

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

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

Fixes #7240

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

Fixes #7232

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

Fixes #7228

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

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

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

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

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

Fixes #7213

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

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

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

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

Fixes #7208

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

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

Fixes #7206

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

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

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

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

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

Fixes #7197

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

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

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

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

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

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

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

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

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

Fixes #7179

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

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

Refs #6289

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

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

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

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

Fixes #6911

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

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

Fixes #7170

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

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

Fixes #7156

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

Fixes #7155

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

Fixes #7154

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

Fixes #7152

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

Fixes #7144

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

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

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

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

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

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

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

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

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

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

Fixes #7083
2026-12-01 08:02:01 +08:00
l0ng-ai b2d03ac5f0 fix(debugger): fall back to CodeLLDB or GDB when a C/C++ host has no lldb-dap (#7125)
CMake targets (and Swift packages) always launched lldb-dap. Most Linux hosts, remote ones included, have no lldb-dap on PATH, so Debug failed with a macOS-oriented install hint although GDB or an installable CodeLLDB would have worked.

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

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

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

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

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

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

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

Fixes #6806

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

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

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

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

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

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

Closes #7035

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

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

Closes #7105, closes #7106, closes #7107

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

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

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

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

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

Closes #7039

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

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

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

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

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

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

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

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

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

Fixes #6938

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

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

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

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

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

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

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

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

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

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

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

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

Refs #6938

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

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

Refs #6938

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

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

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

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

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

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

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

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

Closes #7051

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Closes #7028

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

Closes #7022

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

Closes #7026

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

Closes #7018

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

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

Fixes #7014
2026-11-30 21:16:47 +08:00
2190 змінених файлів з 198741 додано та 15053 видалено

No files matched your search

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

До

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

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

Після

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

+14 -5
Переглянути файл
@@ -7,11 +7,20 @@
## How it was verified
<!-- Required. Commands you actually ran and their results; what else this could
affect and how you checked it still works.
Visible UI changes: before/after screenshots (not for removed UI or copy-only
changes). Multi-step interactions: a recording.
Backend changes: logs or command output. -->
<!-- Required, from the final version of this branch. Commands you actually ran and
their results; what else this could affect and how you checked it still works.
Then the evidence for each kind of change this PR makes (AGENTS.md § Issues & PRs):
- Bug fix: a test that fails on main and passes here, or exact repro steps
- Visible UI: before/after screenshots, same state and size; each theme touched
- Interaction (multi-step, drag, keyboard, focus): a recording
- Code intelligence / run / debug: language_smoke or smoke output on a fixture
- Performance: before/after numbers on the same machine, and the results unchanged
- Windows/Linux only: CI job plus a screenshot or log from a real machine
- Settings / persisted data: starting from the previous version's data
- Copy, docs, refactor, no UI change: write "No visible change"
Drag screenshots and recordings in here; don't commit them. -->
## Review focus
+20 -3
Переглянути файл
@@ -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:
@@ -150,8 +151,18 @@ jobs:
- name: Linux deps
if: runner.os == 'Linux'
run: |
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf)
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf subversion sqlite3)
dpkg -s "${pkgs[@]}" >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y "${pkgs[@]}"; }
# The Subversion tests run the real svn, svnadmin and svnserve (and sqlite3, to write a
# working copy's database); with CI set they fail instead of skipping when these are
# missing. Linux gets them with the deps above; macOS has sqlite3. Windows runners skip them.
- name: Subversion (macOS)
if: runner.os == 'macOS'
run: command -v svnadmin >/dev/null || brew install subversion
- name: Subversion version
if: runner.os != 'Windows'
shell: bash
run: svn --version --quiet && svnadmin --version --quiet && svnserve --version --quiet && sqlite3 --version
# tauri-build checks that frontendDist exists.
- run: pnpm install --frozen-lockfile && mkdir -p dist
shell: bash
@@ -360,6 +371,12 @@ jobs:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
# src/features/dotnet/edit.test.ts and *.cli.test.ts run the real `dotnet` CLI; with CI set they fail, not skip, when it is missing.
- uses: actions/setup-dotnet@v5
with:
dotnet-version: |
10.0.x
11.0.x
- run: pnpm install --frozen-lockfile
- run: pnpm typecheck
- run: pnpm lint
+4 -2
Переглянути файл
@@ -34,7 +34,9 @@ on:
- "src/editor/relatedProviders.ts"
- "src/editor/core/cm/cornerInset.ts"
- "src/editor/core/cm/iconArea.ts"
- "src/editor/core/cm/inlineBg.ts"
- "src/editor/core/cm/localAppearance.ts"
- "src/editor/core/cm/lineNumberOptions.ts"
- "src/editor/lsp/availability.ts"
- "src/editor/lsp/diagnostics.ts"
- "src/editor/lsp/files.ts"
@@ -45,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"
@@ -109,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|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|lineNumberOptions|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src/assets/openidea-logo\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
+20 -2
Переглянути файл
@@ -1,9 +1,9 @@
name: PR check
on:
# pull_request_target so the check can label PRs from forks. It never checks out
# or runs PR code: it only reads the PR title and description.
# or runs PR code: it only reads the PR title, description and changed file names.
pull_request_target:
types: [opened, edited, reopened, ready_for_review]
types: [opened, edited, reopened, ready_for_review, synchronize]
permissions:
issues: write
@@ -34,6 +34,24 @@ jobs:
const { owner, repo } = context.repo;
const issue_number = pr.number;
if (verified && verified[1].trim()) {
const section = verified[1];
const hasMedia =
/!\[[^\]]*\]\(|<img\b|<video\b|github\.com\/user-attachments\/|https?:\/\/\S+\.(png|jpe?g|gif|webp|mp4|mov|webm)\b/i.test(section);
const optedOut = /no visible change/i.test(section);
if (!hasMedia && !optedOut) {
const files = await github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number: issue_number, per_page: 100 });
const ui = files
.filter(f => f.status !== 'removed')
.map(f => f.filename)
.filter(name => /^src\/.*\.(tsx|css)$/.test(name) && !/\.(test|spec)\.tsx$/.test(name));
if (ui.length) {
const shown = ui.slice(0, 3).map(n => `\`${n}\``).join(', ') + (ui.length > 3 ? ', …' : '');
problems.push(`This PR changes UI files (${shown}). Add before/after screenshots, or a recording for interactions, to **How it was verified**; if nothing users see changed, write "No visible change" and say what you checked.`);
}
}
}
const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number });
const existing = comments.find(c => c.user.type === 'Bot' && c.body.includes(MARKER));
const labeled = pr.labels.some(l => l.name === LABEL);
+4 -2
Переглянути файл
@@ -284,6 +284,8 @@ jobs:
return;
}
// Bundle suffix → updater platform keys, as tauri-action names them.
// Nightly builds skip RPM because RPM rejects `-` in SemVer prerelease versions.
const nightly = tag.includes("-nightly.");
const windows = (arch, msi, nsis) => [
[msi, [`windows-${arch}`, `windows-${arch}-msi`]],
[nsis, [`windows-${arch}-nsis`]],
@@ -291,10 +293,10 @@ jobs:
const kinds = [
[/_aarch64\.AppImage$/, ["linux-aarch64", "linux-aarch64-appimage"]],
[/_arm64\.deb$/, ["linux-aarch64-deb"]],
[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]],
...(nightly ? [] : [[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]]]),
[/_amd64\.AppImage$/, ["linux-x86_64", "linux-x86_64-appimage"]],
[/_amd64\.deb$/, ["linux-x86_64-deb"]],
[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]],
...(nightly ? [] : [[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]]]),
[/_aarch64\.app\.tar\.gz$/, ["darwin-aarch64", "darwin-aarch64-app"]],
[/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]],
...windows("aarch64", /_arm64_en-US\.msi$/, /_arm64-setup\.exe$/),
+6 -5
Переглянути файл
@@ -33,12 +33,13 @@ target/
test-results/
playwright-report/
# Local AI agent files
AGENTS.md
CLAUDE.md
# Local AI agent files. Shared skills live in .agents/skills; .claude/skills links to them.
CLAUDE.local.md
.agents/
.claude/
.claude/*
!.claude/skills/
.claude/skills/*
!.claude/skills/pr
!.claude/skills/verify
# Local reference screenshots
pycharm-screenshots/
+2
Переглянути файл
@@ -15,10 +15,12 @@
"src/editor/core/cm/jsp/parser*.ts",
"src/editor/core/cm/astro/parser*.ts",
"src/editor/core/cm/django/parser*.ts",
"src/editor/core/cm/freemarker/parser*.ts",
"plugins/themes.md",
"pnpm-lock.yaml",
"**/*.toml",
"fixtures",
"vendor",
"plugins/*/web",
"plugins/official/*/web",
"crates/**/tests/fixtures"
+5 -1
Переглянути файл
@@ -16,6 +16,7 @@
"src/editor/core/cm/angular/parser*.ts",
"src/editor/core/cm/astro/parser*.ts",
"fixtures",
"vendor",
"plugins",
"test-results",
"playwright-report",
@@ -152,7 +153,10 @@
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
"excludeFiles": ["e2e/**"],
"rules": {
"no-await-in-loop": "error"
"no-await-in-loop": "error",
"react/no-array-index-key": "error",
"react/jsx-no-constructed-context-values": "error",
"react/no-object-type-as-default-prop": "error"
}
}
]
+197
Переглянути файл
@@ -0,0 +1,197 @@
# OpenIDEA — contributor guide
Rust + Tauri 2 desktop IDE with full-featured, multi-language code intelligence.
Visual style: rounded content islands on a grey frame, low-contrast greys, one cool accent;
Islands Light is the default theme. `src/styles/tokens.css` is the source of truth for colours
and metrics; `DESIGN.md` and `PRODUCT.md` describe the design system and who the product is for.
## Layout
- `crates/ide-*` — backend crates; one domain each. Depend on `ide-core` for shared
types; never reach into another crate's internals.
- `src-tauri/` — glue only: `state.rs` (AppState / Project), `commands/<domain>.rs`
(desktop-only commands; the adapters of `ide-host` commands are derived), `events.rs`.
No domain logic here.
- `src/bindings.ts` — generated by tauri-specta (`pnpm gen:bindings`). Never edit.
- `src/platform/` — ipc (`call`, `onIdeEvent`, `nextRequestId`), actions registry,
keymap + dispatcher, context keys / `when` clauses, project store.
- `src/workbench/contributions.ts` — extension points (tool windows, status items,
overlays, editor kinds) and cross-feature services (editor, tool windows, notifications).
- `src/ui/` — design-system primitives. `src/features/<name>/` — one feature each,
exporting `activate()` registered in `src/features/index.ts`.
- `languages/<id>.toml` — language definitions (detection, comments, LSP, DAP).
- `crates/ide-host` — the `openidea-server` binary for remote development and the
`openidea-plugin` CLI (plugin starter templates live in its `templates.rs`).
- `wit/` — plugin interface definitions; `plugins/` — sample and bundled plugins.
Plugin docs: `plugins/README.md`, `plugins/themes.md`.
- `java/` — JDT LS extension bundles (`java-usages`, `kotlin-bridge`) and the patched
Lombok agent, embedded into the app by `ide-sdk` / `ide-tools`.
- `e2e/` — Playwright UI tests (`pnpm e2e`). `evals/` — code-intelligence evals (`pnpm eval`).
`fixtures/` — sample projects per language for manual and automated testing.
- `docs/` — the Mintlify documentation site (`docs.json` navigation, `en/` and `zh/` pages);
preview with `npx mint dev` in `docs/`.
## Rules
- IPC coordinates: 0-based lines, **UTF-16** columns/offsets everywhere (`ide-core::text`).
- Every command returns `IdeResult<T>`; convert internal errors at the crate edge.
- Declare a command once, on its implementation: `#[command(trust = …)]` in `ide-host::ops`
plus its module's `domain!` list (Tauri adapter, server handler and bindings are derived);
desktop-only commands use `#[desktop_command(trust = …)]` and `desktop_domain!`.
- Streaming → `tauri::ipc::Channel<T>`; cancellable → UI-allocated `RequestId` +
`cancel_request`. Backend → UI notifications → `IdeEvent` via `EventSink`.
- Long work never blocks the UI thread or a Tauri command thread: use
`spawn_blocking`/rayon, honour `CancellationToken`.
- Frontend features never import each other; communicate via actions, contributions
and services. All user-invocable behaviour is an action with a stable id; default
shortcuts live in `src/platform/keymaps/`.
- Styling: CSS Modules + tokens only (no hex literals in components). Inline SVG
icons from `src/ui/icons.tsx`, never emoji. Real `<button>`/`<input>`; `aria-label` on icon buttons.
`gap` uses the `--space-*` scale (`src/styles/tokens.css`, 4px grid) where a value is on it.
- User-visible text goes through the text catalog: add every new string to both
`src/platform/locales/text/en.json` and `zh.json` (`textCatalog.test.ts` enforces it).
Other locales may lack entries; their UI shows the English text until a translator adds it.
- Keep comments sparse and purposeful; match surrounding style.
- New regular expressions in frontend code must run on WebKit (no lookbehind):
`src/platform/webkitCompatibility.test.ts` checks them.
- For GUI verification, prefer Tauri MCP; use Computer Use only when Tauri MCP is
unavailable or cannot cover the required checks.
## UX changes
A change to what users see or how they interact must look and behave like the rest of the IDE.
- `DESIGN.md` (colours, type, layout, components, Do's and Don'ts) and `PRODUCT.md`
(users, principles, accessibility) are the reference; `docs/en/contribute/guidelines/ui.mdx`
has the code-level rules. Build from `src/ui/` primitives and workbench contributions;
don't create a one-off control, colour or spacing when an existing one fits.
- Check every theme the change touches (at least Islands Light and Islands Dark) and narrow
sizes (e.g. the Commit tool window at its default width, a small window). Long translated
strings must not break the layout.
- Everything works from the keyboard; focus is visible and lands somewhere sensible when a
popup or dialog closes. Icon-only buttons have an `aria-label` and a tooltip.
- Follow the conventions users of this kind of IDE already know: the same action keeps the
same name, place and shortcut across views. Don't invent a new pattern for an existing one.
- Agent and MCP features follow good agent-tool practice: restrained, predictable, reversible.
- Restructuring a page layout or navigation, or changing a default behaviour, needs a
maintainer's decision first: ask in the issue and label it `needs-decision`.
- The Impeccable design skills may be used for design critique and polish; they read
`DESIGN.md`, `PRODUCT.md` and `.impeccable/`. A detector exception goes in
`.impeccable/config.json` with a reason.
## Issues & PRs
Follow `CONTRIBUTING.md` and `.github/pull_request_template.md`: one problem per PR
(`Closes #<n>` when it resolves an issue), reproduce first, keep the diff focused, short plain
description. Unclear product decisions → `needs-decision` and stop.
Every PR carries evidence a reviewer can accept without re-running everything, in
**How it was verified**. It must come from the final version of the branch:
| Change | Evidence |
| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| Bug fix | A test that fails before the fix and passes after, or exact reproduction steps with before/after result |
| Visible UI | Before/after screenshots at the same state and window size; each theme the change touches |
| Interaction (multi-step, drag, keyboard, focus) | A short recording or numbered screenshots |
| Code intelligence / language support | The fixture used and `language_smoke` output; `pnpm eval` numbers for Java |
| Run / debug | `pnpm smoke smoke/run.test.ts` / `smoke/debug.test.ts -t <language>` output |
| Performance | Before/after numbers on the same machine (`pnpm perf`, `pnpm perf:rust` or a stated measurement), plus proof the results are unchanged |
| Windows / Linux only | The platform's CI job, and a screenshot or log from a real machine |
| Backend / IPC | Test output; regenerated `src/bindings.ts` when types changed |
| Remote development | The flow against a real `openidea-server` host |
| Plugin API / `wit/` | `plugins/build.sh` run and `dist/` committed; a sample plugin using the change |
| Settings / persisted data | Behaviour when starting from data written by the previous version |
| Copy, docs, refactor | The commands run; "No visible change" when nothing users see changed |
Attach screenshots and recordings to the PR description; never commit them. The `pr` skill
has the full checklist.
## Skills
Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
`pr` prepares a pull request — checks to run, evidence for the kind of change, description;
`verify` drives the running app through Tauri MCP and captures screenshot evidence.
## Commands
- Optional: `mise install` provisions the contributor toolchain; `mise tasks` lists the task aliases.
See [Development setup](docs/en/contribute/setup.mdx). The direct commands below still work without mise.
- `pnpm tauri dev` — run the app with worktree isolation. Use Node 22.22.2 or later on the 22.x line.
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
this worktree's running MCP bridges and actual ports.
- `pnpm build` — typecheck + bundle frontend.
- `pnpm dogfood:local [--build-only]` (or `mise run dogfood:local`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
- `pnpm dogfood:all <remote_name> [--restart | --no-restart]` (or `mise run dogfood:all <remote_name>`) — run `dogfood:local` and `dogfood:remote <remote_name>` in parallel.
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
- `pnpm smoke smoke/run.test.ts -t <language>` — run and test that language's fixture through the
run store and a real `openidea-server` (build it first: `cargo build -p ide-host --bin openidea-server`).
- `pnpm smoke smoke/debug.test.ts -t <language>` — debug that fixture's entry point the same way, with
the debugger the IDE installs (on macOS, CodeLLDB and Delve may need Developer Mode:
`sudo DevToolsSecurity -enable`).
- `pnpm test`, `pnpm e2e`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm typecheck`,
`pnpm gen:bindings`.
- `pnpm perf` (UI interaction latency / frames / leaks), `pnpm perf:rust` (criterion
benches vs budgets). Budgets: `perf/budgets.json`.
- `pnpm eval [--only <id>] [--runs n] [--save-baseline]` — Java code intelligence (navigation,
usages, gutter markers) in the production workbench against a release `openidea-server` and
jdtls: time to feedback / first result / complete, results vs `evals/<language>/golden/`.
Report: `target/eval/report.json`. Goldens and `evals/budgets.json` are changed by people only.
Tool versions: `.github/tool-versions.env` (shared with Language smoke).
- `pnpm release:prepare <version>` — the release commit's changes: app version everywhere,
`Cargo.lock`, and the plugin API snapshot when `wit/` moved to a new version.
## Before opening a PR
Run what CI runs for the parts you touched:
- Rust: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,
`cargo nextest run --workspace`. After changing IPC types, run `pnpm gen:bindings` and
commit `src/bindings.ts`; CI fails if it differs.
- Frontend: `pnpm typecheck` (vitest does not type-check), `pnpm lint`, `pnpm format:check`,
`pnpm knip`, `pnpm test`, `pnpm build`, and every `e2e/` spec of the feature you touched.
- New text keys: `src/platform/locales/textCatalog.test.ts` and `src/platform/i18n.test.ts`.
New or renamed tokens: `pnpm gen:theme-docs`.
- Changed a `pub fn` signature in a crate: run that crate's whole `cargo test`, not one test.
- UI or runtime behaviour: verify in the running app (`.agents/skills/verify`) and collect
the evidence above (`.agents/skills/pr`).
## Pitfalls
- Run a subset of frontend tests with `pnpm vitest run <path>`. `pnpm test -- <path>` ignores
the filter and runs the whole suite, which takes several minutes.
- Don't run clippy while iterating: `pnpm tauri dev` compiles anyway. Run
`cargo fmt --all` + `cargo clippy -p <crate> --all-targets -- -D warnings` once, right
before committing. A cold build cache can take around 5 minutes. Run long checks one at
a time, not chained in one shell call that may hit the 10-minute tool timeout.
- `pnpm tauri dev` does a full debug build. Clippy only checks the code, so a passing clippy
doesn't make the first launch fast.
## Parallel worktrees
Several worktrees can be developed and run side by side.
- Create one per task: `git worktree add ../<name> -b <branch> origin/main`, then
`pnpm install` in it.
- Launch with `pnpm tauri dev` / `pnpm dev:app`, not the raw `pnpm exec tauri dev` CLI. The
wrapper starts Vite on a worktree-derived port (advancing if occupied), passes its actual
URL to Tauri, and reports an existing launcher instead of starting another for the same
worktree. HMR uses the Vite port.
- Debug app identity, data, settings, logs and single-instance scope follow the canonical
worktree path captured at build time, independent of launch cwd. Launching the same debug
binary again focuses its existing instance and forwards its path argument. Different
worktrees and the installed release can coexist. `--release` uses normal release identity
and bypasses the development wrapper.
- MCP bridge ports are dynamic (9223–9322). Use `pnpm dev:status`, connect to the reported
port, verify identifier/cwd, and pass `appIdentifier: <port>` explicitly. Do not assume the
default MCP session belongs to this worktree.
- Keep each worktree's Cargo output directory separate; do not point `CARGO_TARGET_DIR` or
`target` symlinks at a shared directory.
- Each worktree's first build is cold (several minutes) and `cargo build` output takes
around 9 GB; tests, clippy and incremental builds add more. Avoid running several heavy builds on one machine at the same time.
- Stop only processes started for the current worktree/session. Never use broad
process-name kills such as `pkill openidea`.
- When done: stop that worktree's app and dev session, delete its build output, then
`git worktree remove ../<name>`.
Symlink
+1
Переглянути файл
@@ -0,0 +1 @@
AGENTS.md
+8 -2
Переглянути файл
@@ -1,6 +1,7 @@
# Contributing to OpenIDEA
These rules apply to everyone, and to any coding agent working on their behalf.
Project layout, coding rules, commands, checks and the evidence a PR needs are in [AGENTS.md](AGENTS.md).
## Issues
@@ -26,7 +27,12 @@ These rules apply to everyone, and to any coding agent working on their behalf.
- **How it was verified** is required: the commands you ran and their results,
and what else the change could affect. Changes to what users see need before/after
screenshots; multi-step interactions need a recording. UI that goes away with a removed
feature, copy-only and non-visual changes don't; say what you checked instead.
feature, copy-only and non-visual changes don't; write "No visible change" and say what
you checked instead. [AGENTS.md](AGENTS.md#issues--prs) lists the evidence for each kind of
change (tests, smoke output, perf numbers, real-machine logs…).
- Changes to what users see follow [DESIGN.md](DESIGN.md) and the existing UI: tokens,
`src/ui/` primitives, both themes, keyboard access. Restructuring a layout or navigation
needs a maintainer's decision first.
- If a change needs a product decision you can't make, ask in the issue and stop
rather than guessing.
@@ -35,4 +41,4 @@ and the plugin API. Community plugins live in their authors' repositories and
are listed through [l0ng-ai/openidea-plugins](https://github.com/l0ng-ai/openidea-plugins);
see [`plugins/README.md`](plugins/README.md) § 8.1.
A check on each PR adds `needs-info` when the verification section is missing, and removes it once it's filled in.
A check on each PR adds `needs-info` when the verification section is missing, or when the PR changes UI files and the section has neither a screenshot nor a recording nor "No visible change". It removes the label once that's fixed.
Створено
+320 -410
File diff suppressed because it is too large. Load diff
+10 -2
Переглянути файл
@@ -2,10 +2,10 @@
resolver = "3"
members = ["crates/*", "src-tauri"]
# Plugins and the guest SDK build for wasm32-wasip2 in their own workspaces.
exclude = ["sdk", "plugins"]
exclude = ["sdk", "plugins", "vendor"]
[workspace.package]
version = "0.1.56"
version = "0.1.57"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
@@ -24,6 +24,7 @@ ide-jsonrpc = { path = "crates/ide-jsonrpc" }
ide-lsp = { path = "crates/ide-lsp" }
ide-dap = { path = "crates/ide-dap" }
ide-vcs = { path = "crates/ide-vcs" }
ide-svn = { path = "crates/ide-svn" }
ide-github = { path = "crates/ide-github" }
ide-terminal = { path = "crates/ide-terminal" }
ide-run = { path = "crates/ide-run" }
@@ -90,6 +91,7 @@ trash = "5"
blake3 = "1"
dunce = "1"
dirs = "6"
jiff = "0.2"
memmap2 = "0.9"
zip = { version = "9.2.3", default-features = false, features = ["deflate"] }
flate2 = "1"
@@ -99,6 +101,7 @@ tar = "0.4"
grep-searcher = "0.1"
grep-regex = "0.1"
regex-syntax = "0.8"
regex = "1"
grep-matcher = "0.1"
nucleo-matcher = "0.3"
redb = "4"
@@ -158,3 +161,8 @@ opt-level = 3
panic = "unwind"
# Keep the symbol table: crash reports and logged backtraces name functions.
strip = "debuginfo"
# tauri-plugin-mcp-bridge 0.13.2 (debug-only E2E bridge) pins `tauri ~2.12`; this copy only widens
# that requirement to 2.13. Drop it once a release supporting tauri 2.13 is published.
[patch.crates-io]
tauri-plugin-mcp-bridge = { path = "vendor/tauri-plugin-mcp-bridge" }
+5
Переглянути файл
@@ -6,6 +6,11 @@ contributors as part of the IntelliJ Platform (https://github.com/JetBrains/inte
https://github.com/JetBrains/intellij-plugins), licensed under the Apache License 2.0.
Copyright 2000-2026 JetBrains s.r.o. and contributors.
The Subversion tests (crates/ide-svn/tests/matrix.rs) take the tree-conflict scenarios,
their names and file contents from IntelliJ's svn4idea TreeConflictData
(plugins/svn4idea/testSource/org/jetbrains/idea/svn/), Apache License 2.0, Copyright
2000-2026 JetBrains s.r.o. and contributors.
Some Simplified Chinese UI terms follow the Visual Studio Code Simplified Chinese
language pack (https://github.com/microsoft/vscode-loc), Copyright (c) Microsoft
Corporation, licensed under the MIT License.
+2 -2
Переглянути файл
@@ -71,10 +71,10 @@ the [official plugins](plugins/official). The plugin API is still a preview.
## Community
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
- [Discord](https://discord.gg/AsZqMgxZm) — questions, feedback and release news.
- WeChat group — scan to join:
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
<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).
+2 -2
Переглянути файл
@@ -71,10 +71,10 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
## Topluluk
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
- [Discord](https://discord.gg/AsZqMgxZm): sorular, geri bildirim ve sürüm haberleri.
- WeChat grubu, katılmak için kodu okut:
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
<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
Переглянути файл
@@ -69,10 +69,10 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
## 社区
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
- [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:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
## DuckDB symbol
@@ -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`
+3 -1
Переглянути файл
@@ -18,14 +18,16 @@ ide-tools = { path = "../ide-tools" }
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
sqlx.workspace = true
tokio.workspace = true
toml.workspace = true
toml_edit.workspace = true
tracing.workspace = true
parking_lot.workspace = true
dunce.workspace = true
jiff.workspace = true
uuid.workspace = true
tempfile.workspace = true
which = "8"
semver = "1"
sha1 = "0.10"
+1
Переглянути файл
@@ -105,6 +105,7 @@ fn manager(dir: &Path, agent: Arc<FakeV2Agent>) -> AgentManager {
store_dir: dir.join("store"),
worktrees_dir: dir.join("worktrees"),
models_file: dir.join("models.json"),
cli_dir: dir.join("agent-cli"),
custom_agents_dir: None,
home_dir: None,
env_secrets: None,
+18
Переглянути файл
@@ -53,6 +53,24 @@ pub(crate) fn auth_required(code: i64, message: &str) -> bool {
.any(|w| w == ["logged", "out"] || w == ["sign", "in"] || w == ["log", "in"] || w == ["login", "required"])
}
/// Whether a failed request only means the agent hasn't finished starting up: OpenCode
/// rejects session opens until the location's plugins and MCP servers finish activating
/// (`ServiceUnavailableError`, "Location plugins did not finish activating") and reports
/// an unavailable server as `ServerUnavailable`. Both arrive as internal errors naming
/// the cause in `data.errorName`; retrying them once activation completes succeeds.
pub(crate) fn service_warming_up(error: &RpcError) -> bool {
let RpcError::Server { code: codes::INTERNAL_ERROR, message, data } = error else {
return false;
};
if let Some(name) = data.as_ref().and_then(|d| d.get("errorName")).and_then(Value::as_str)
&& matches!(name, "ServiceUnavailableError" | "ServerUnavailable")
{
return true;
}
let lower = message.to_lowercase();
lower.contains("did not finish activating") || lower.contains("opencode server is unavailable")
}
/// The capabilities this client offers, in v1 form.
fn client_capabilities() -> Value {
json!({
+35
Переглянути файл
@@ -52,6 +52,40 @@ fn auth_required_matches_authentication_words_and_sign_in_phrases() {
}
}
#[test]
fn service_warming_up_matches_opencode_startup_races_only() {
for (code, message, data, expected) in [
(
codes::INTERNAL_ERROR,
"Internal error: Internal service failure",
Some(json!({"errorName": "ServiceUnavailableError"})),
true,
),
(
codes::INTERNAL_ERROR,
"Internal error: OpenCode server is unavailable",
Some(json!({"errorName": "ServerUnavailable"})),
true,
),
(codes::INTERNAL_ERROR, "Location plugins did not finish activating", None, true),
(
codes::INTERNAL_ERROR,
"Internal error: Internal service failure",
Some(json!({"errorName": "SQLiteError"})),
false,
),
(codes::INTERNAL_ERROR, "Internal error: Internal service failure", None, false),
(codes::INTERNAL_ERROR, "boom", None, false),
(AUTH_REQUIRED, "Authentication required", None, false),
] {
assert_eq!(
service_warming_up(&RpcError::Server { code, message: message.into(), data: data.clone() }),
expected,
"code={code}, message={message:?}, data={data:?}"
);
}
}
/// The messages of a fixture going `dir` (`in` or `out`).
pub(crate) fn frames(fixture: &str, dir: &str) -> Vec<Value> {
fixture
@@ -155,6 +189,7 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
store_dir: tmp.path().join("store"),
worktrees_dir: tmp.path().join("worktrees"),
models_file: tmp.path().join("models.json"),
cli_dir: tmp.path().join("agent-cli"),
custom_agents_dir: None,
home_dir: None,
env_secrets: None,
File diff suppressed because it is too large. Load diff
+8 -4
Переглянути файл
@@ -468,7 +468,9 @@ impl AgentCatalogs {
model: Option<String>,
result: Result<Discovered, String>,
) {
let current = provider::load(shared.paths.custom_agents_dir.as_deref(), shared.env_secrets())
let current = shared
.paths
.provider_specs()
.into_iter()
.find(|spec| spec.id == key.2)
.map(|spec| LaunchContext::new(spec, &shared.paths.project_root));
@@ -622,8 +624,7 @@ impl crate::AgentManager {
/// Return cached choices immediately and schedule discovery when eligible.
pub fn refresh_models(&self, provider: &str, force: bool, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
// Settings and environment secrets can change while this window is open.
*self.shared.providers.write() =
provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
*self.shared.providers.write() = self.shared.paths.provider_specs();
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force, model).0)
}
@@ -631,7 +632,10 @@ impl crate::AgentManager {
/// Probes Copilot's model catalog for a staged `account` selection (`""` = Copilot CLI
/// default) without mutating `models.json` or broadcasting to active sessions before Apply.
pub async fn preview_copilot_models(&self, account: &str, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
let mut spec = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets())
let mut spec = self
.shared
.paths
.provider_specs()
.into_iter()
.find(|p| p.id == "copilot")
.ok_or_else(|| IdeError::not_found("unknown agent 'copilot'"))?;
+1
Переглянути файл
@@ -157,6 +157,7 @@ fn make_manager_at(root: &Path, models_file: &Path, catalogs: Arc<AgentCatalogs>
store_dir: root.join("store"),
worktrees_dir: root.join("worktrees"),
models_file: models_file.to_path_buf(),
cli_dir: root.join("agent-cli"),
catalogs,
custom_agents_dir: Some(root.join("agents")),
home_dir: Some(root.to_path_buf()),
+151 -53
Переглянути файл
@@ -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,
@@ -58,15 +124,53 @@ impl AgentManager {
if spec.source != AgentSource::Builtin {
return Ok(AgentCliUpdateResult::Unmanaged);
}
let Ok(npm) = which::which("npm") else { return Ok(AgentCliUpdateResult::Unmanaged) };
let Some(npm) = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path()) else {
return Ok(AgentCliUpdateResult::Unmanaged);
};
let 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,
@@ -149,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"));
}
@@ -210,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::*;
@@ -312,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") };
@@ -349,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();
@@ -375,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));
+338 -1
Переглянути файл
@@ -131,7 +131,263 @@ fn is_bypass_mode(mode: &str) -> bool {
let lower = mode.to_lowercase();
let m: String =
lower.rsplit(['#', '/']).next().unwrap_or_default().chars().filter(char::is_ascii_lowercase).collect();
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous"
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous" || m == "autopilot"
}
fn upsert_choice(wanted: &mut Vec<crate::model::AgentConfigChoice>, id: &str, value: &str) {
if let Some(existing) = wanted.iter_mut().find(|c| c.id == id) {
existing.value = value.to_owned();
} else {
wanted.push(crate::model::AgentConfigChoice { id: id.to_owned(), value: value.to_owned() });
}
}
pub(crate) fn is_approval_option(opt: &AgentConfigOption) -> bool {
opt.id == CURSOR_APPROVAL || matches!(opt.category.as_deref(), Some("mode" | "permissions" | "approval"))
}
fn wanted_val(wanted: &[crate::model::AgentConfigChoice], id: &str) -> Option<String> {
wanted.iter().find(|c| c.id == id).map(|c| c.value.clone())
}
/// Applies an automation's permission policy (`mode`) to `config` and `wanted`, enforcing the
/// user's interactive approval setting (`interactive`) as a strict ceiling. When `mode` is `None`
/// (an in-session `/loop` or `Send Later` turn), clamps any bypass options down when `interactive`
/// is [`ide_core::settings::NewTaskApprovals::Ask`].
pub(crate) fn clamp_automation_permissions(
provider: &str,
mode: Option<crate::automation::AutomationPermissionMode>,
interactive: ide_core::settings::NewTaskApprovals,
config: &mut [AgentConfigOption],
wanted: &mut Vec<crate::model::AgentConfigChoice>,
) {
use crate::automation::AutomationPermissionMode;
use ide_core::settings::NewTaskApprovals;
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
return;
}
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
if !allow_bypass {
// Strip any explicit bypass choices from `wanted` first so they cannot re-elevate later.
wanted.retain(|c| match c.id.as_str() {
"mode" => !is_bypass_mode(&c.value),
"allow_all" | "permissions" => !matches!(c.value.to_ascii_lowercase().as_str(), "on" | "true"),
"approval" | CURSOR_APPROVAL => !c.value.eq_ignore_ascii_case("bypass"),
"approval_policy" => !c.value.eq_ignore_ascii_case("never"),
_ => true,
});
ask_for_approvals(config);
}
match provider {
"claude" | "claude-acp" => {
let cur_wanted = wanted_val(wanted, "mode");
let target = if allow_bypass {
match cur_wanted.as_deref() {
Some("default" | "plan" | "acceptEdits") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "bypassPermissions".to_owned(),
}
} else if interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::Assisted) {
match cur_wanted.as_deref() {
Some("default" | "plan") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "acceptEdits".to_owned(),
}
} else {
// Either Default mode or interactive policy is Ask (where interactive Claude starts in `default`).
match cur_wanted.as_deref() {
Some("plan") => "plan".to_owned(),
_ => "default".to_owned(),
}
};
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
&& opt.values.iter().any(|v| v.value == target)
{
let id = opt.id.clone();
opt.current = Some(target.clone());
upsert_choice(wanted, &id, &target);
} else if mode.is_some() || cur_wanted.is_some() {
upsert_choice(wanted, "mode", &target);
}
}
"codex" | "codex-acp" => {
let cur_wanted = wanted_val(wanted, "mode");
let target = if allow_bypass {
match cur_wanted.as_deref() {
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "full-access".to_owned(),
}
} else if mode == Some(AutomationPermissionMode::Default) {
"read-only".to_owned()
} else if mode.is_some() {
// Assisted, or AllowAll clamped by interactive Ask (`ask_for_approvals` maps full-access -> ask).
match cur_wanted.as_deref() {
Some("read-only") => "read-only".to_owned(),
_ => "ask".to_owned(),
}
} else {
// Scheduled /loop or Send Later under interactive Ask: never full-access.
match cur_wanted.as_deref() {
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "ask".to_owned(),
}
};
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
&& opt.values.iter().any(|v| v.value == target)
{
let id = opt.id.clone();
opt.current = Some(target.clone());
upsert_choice(wanted, &id, &target);
} else if mode.is_some() || cur_wanted.is_some() {
upsert_choice(wanted, "mode", &target);
}
}
"copilot" => {
if allow_bypass {
if !matches!(wanted_val(wanted, "allow_all").as_deref(), Some("off" | "false")) {
upsert_choice(wanted, "allow_all", "on");
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
opt.current = Some("on".into());
}
}
} else {
upsert_choice(wanted, "allow_all", "off");
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
opt.current = Some("off".into());
}
let non_auto = match wanted_val(wanted, "mode").as_deref() {
Some("plan") => "plan",
_ => "agent",
};
if mode.is_some() || config.iter().any(|o| o.id == "mode" && o.current.as_deref() == Some("autopilot"))
{
upsert_choice(wanted, "mode", non_auto);
}
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode")
&& (mode.is_some() || opt.current.as_deref() == Some("autopilot"))
&& opt.values.iter().any(|v| v.value == non_auto)
{
opt.current = Some(non_auto.into());
}
}
}
"cursor" => {
let target = if allow_bypass && wanted_val(wanted, CURSOR_APPROVAL).as_deref() != Some("ask") {
"bypass"
} else {
"ask"
};
upsert_choice(wanted, CURSOR_APPROVAL, target);
if let Some(opt) = config.iter_mut().find(|o| o.id == CURSOR_APPROVAL) {
opt.current = Some(target.into());
}
}
_ => {
if allow_bypass {
let user_chose_non_bypass = config.iter().any(|o| {
is_approval_option(o)
&& wanted.iter().any(|c| {
c.id == o.id && o.category.as_deref().and_then(bypass_value).is_some_and(|b| !b(&c.value))
})
});
if !user_chose_non_bypass {
apply_bypass_approvals(config);
}
}
}
}
// Ensure every approval-bearing option in `config` has its enforced value mirrored in `wanted`
// so `open_session` actively configures the live session even if the CLI's own config differs.
for opt in config.iter().filter(|o| is_approval_option(o)) {
if let Some(cur) = opt.current.as_deref() {
upsert_choice(wanted, &opt.id, cur);
}
}
}
/// Verifies that the session's reported `config` options do not exceed the required automation
/// permission ceiling (`min(mode, interactive)`). Returns `Err(reason)` if the provider remained
/// in a more permissive mode than allowed.
pub(crate) fn verify_automation_ceiling(
provider: &str,
mode: Option<crate::automation::AutomationPermissionMode>,
interactive: ide_core::settings::NewTaskApprovals,
config: &[AgentConfigOption],
) -> Result<(), String> {
use crate::automation::AutomationPermissionMode;
use ide_core::settings::NewTaskApprovals;
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
return Ok(());
}
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
if !allow_bypass && bypass_approvals(config) {
return Err("Agent did not confirm the required approval ceiling (session remained in bypass mode).".into());
}
let cur_of = |id: &str| config.iter().find(|o| o.id == id).and_then(|o| o.current.as_deref());
let mode_cur = config
.iter()
.find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
.and_then(|o| o.current.as_deref());
if !allow_bypass {
match provider {
"claude" | "claude-acp" => {
if let Some(cur) = mode_cur {
let allowed = if interactive == NewTaskApprovals::Bypass
&& mode == Some(AutomationPermissionMode::Assisted)
{
matches!(cur, "default" | "plan" | "acceptEdits")
} else {
matches!(cur, "default" | "plan")
};
if !allowed {
return Err(format!(
"Claude session remained in mode '{cur}', exceeding the required approval ceiling."
));
}
}
}
"codex" | "codex-acp" => {
if let Some(cur) = mode_cur {
let allowed = if mode == Some(AutomationPermissionMode::Default) {
cur == "read-only"
} else if mode.is_some() {
matches!(cur, "read-only" | "ask")
} else {
matches!(cur, "read-only" | "ask" | "auto")
};
if !allowed {
return Err(format!(
"Codex session remained in mode '{cur}', exceeding the required approval ceiling."
));
}
}
}
"copilot" => {
if let Some(cur) = cur_of("allow_all")
&& matches!(cur.to_ascii_lowercase().as_str(), "on" | "true")
{
return Err("Copilot session kept allow_all enabled above the approval ceiling.".into());
}
if let Some(cur) = mode_cur
&& cur.eq_ignore_ascii_case("autopilot")
{
return Err("Copilot session remained in autopilot mode above the approval ceiling.".into());
}
}
"cursor" if cur_of(CURSOR_APPROVAL).is_some_and(|cur| cur.eq_ignore_ascii_case("bypass")) => {
return Err("Cursor session remained in bypass mode above the approval ceiling.".into());
}
_ => {}
}
}
Ok(())
}
/// The settings in a `session/new` or `session/load` result: its select `configOptions`,
@@ -669,6 +925,87 @@ mod tests {
);
}
#[test]
fn automation_permissions_respect_interactive_approval_ceiling() {
use crate::automation::AutomationPermissionMode;
use crate::model::AgentConfigChoice;
use ide_core::settings::NewTaskApprovals;
let claude_opts = || {
options_of(&json!({"configOptions": [{
"id": "mode", "category": "mode", "type": "select", "currentValue": "bypassPermissions",
"defaultValue": "default",
"options": [
{"value": "default"}, {"value": "acceptEdits"}, {"value": "plan"}, {"value": "bypassPermissions"}
]
}]}))
};
// Claude Assisted under interactive Bypass -> acceptEdits; under interactive Ask -> default!
let mut c = claude_opts();
let mut wanted = Vec::new();
clamp_automation_permissions(
"claude",
Some(AutomationPermissionMode::Assisted),
NewTaskApprovals::Bypass,
&mut c,
&mut wanted,
);
assert_eq!(c[0].current.as_deref(), Some("acceptEdits"));
assert!(wanted.iter().any(|w| w.id == "mode" && w.value == "acceptEdits"));
let mut c_ask = claude_opts();
let mut wanted_ask = vec![AgentConfigChoice { id: "mode".into(), value: "bypassPermissions".into() }];
clamp_automation_permissions(
"claude",
Some(AutomationPermissionMode::AllowAll),
NewTaskApprovals::Ask,
&mut c_ask,
&mut wanted_ask,
);
assert_eq!(c_ask[0].current.as_deref(), Some("default"));
assert_eq!(wanted_ask, vec![AgentConfigChoice { id: "mode".into(), value: "default".into() }]);
// Copilot AllowAll under interactive Ask clamps allow_all -> off and autopilot -> agent.
let mut copilot = options_of(&json!({"configOptions": [
{"id": "mode", "category": "mode", "type": "select", "currentValue": "autopilot",
"options": [{"value": "agent"}, {"value": "plan"}, {"value": "autopilot"}]},
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "on",
"options": [{"value": "off"}, {"value": "on"}]}
]}));
let mut copilot_wanted = vec![AgentConfigChoice { id: "allow_all".into(), value: "on".into() }];
clamp_automation_permissions(
"copilot",
Some(AutomationPermissionMode::AllowAll),
NewTaskApprovals::Ask,
&mut copilot,
&mut copilot_wanted,
);
assert_eq!(ids(&copilot), [("mode", Some("agent")), ("allow_all", Some("off"))]);
assert!(!bypass_approvals(&copilot));
// Codex Default -> read-only, Assisted -> ask, AllowAll + Ask -> ask, AllowAll + Bypass -> full-access.
let codex_opts = || {
options_of(&json!({"configOptions": [{
"id": "mode", "category": "mode", "type": "select", "currentValue": "full-access",
"defaultValue": "ask",
"options": [{"value": "read-only"}, {"value": "ask"}, {"value": "auto"}, {"value": "full-access"}]
}]}))
};
for (perm, interactive, expected) in [
(AutomationPermissionMode::Default, NewTaskApprovals::Bypass, "read-only"),
(AutomationPermissionMode::Assisted, NewTaskApprovals::Bypass, "ask"),
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Ask, "ask"),
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Bypass, "full-access"),
] {
let mut opts = codex_opts();
let mut w = Vec::new();
clamp_automation_permissions("codex", Some(perm), interactive, &mut opts, &mut w);
assert_eq!(opts[0].current.as_deref(), Some(expected), "{perm:?} + {interactive:?}");
assert!(w.iter().any(|c| c.id == "mode" && c.value == expected));
}
}
#[test]
fn command_sources_in_updates_and_stored_tasks() {
let update = json!({"availableCommands": [
+182 -1
Переглянути файл
@@ -1,7 +1,10 @@
//! ACP elicitation in form mode: the agent's restricted JSON Schema as form fields, and the
//! user's answer as the `elicitation/create` response.
use crate::model::{AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption};
use crate::model::{
AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption, AgentQuestion,
AgentQuestionOption,
};
use serde::Deserialize;
use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
use serde_json::{Map, Value, json};
@@ -10,6 +13,9 @@ use serde_json::{Map, Value, json};
/// anything else cancels it.
const DECLINE: &str = "decline";
/// What the question card sends for Skip.
const SKIP: &str = "reject";
/// The form `elicitation/create` asks for; `Err` when it asks for something else.
pub(crate) fn form_of(params: &Value) -> Result<AgentForm, String> {
if params.get("mode").and_then(Value::as_str) != Some("form") {
@@ -148,6 +154,97 @@ fn scalar(value: &Value) -> Option<String> {
}
}
/// The questions a form asks when it is an agent's question tool in form shape: every field
/// a choice, each followed by its own text field for a typed answer, named after it
/// (`question_0` + `question_0_custom` from claude-agent-acp's `AskUserQuestion`, `q0` +
/// `q0__other` from OMP's `ask`). They are shown and answered as the agent's questions, one
/// at a time like a native `AskUserQuestion` (#7359); [`answer_questions`] turns the answers
/// back into the form's values. `None` for any other form.
pub(crate) fn questions_of(form: &AgentForm, params: &Value, message: &str) -> Option<Vec<AgentQuestion>> {
let choices = form.fields.len() / 2;
if choices == 0 || form.fields.len() % 2 == 1 {
return None;
}
let properties = params.pointer("/requestedSchema/properties");
form.fields
.chunks(2)
.map(|pair| {
let [choice, text] = pair else { return None };
let asks = matches!(choice.kind, AgentFormFieldKind::Choice | AgentFormFieldKind::Choices)
&& !choice.options.is_empty()
&& text.kind == AgentFormFieldKind::Text
&& text.name.len() > choice.name.len()
&& text.name.starts_with(&choice.name);
if !asks {
return None;
}
let (title, description) = (choice.title.trim(), choice.description.trim());
let (header, question) = if choices == 1 && !message.is_empty() {
(if title == message || title == choice.name { "" } else { title }, message)
} else if description.is_empty() {
("", title)
} else {
(if title == choice.name { "" } else { title }, description)
};
let schema = properties.and_then(|p| p.get(&choice.name));
let options = choice
.options
.iter()
.map(|option| AgentQuestionOption {
label: option.label.clone(),
description: option.description.clone(),
preview: schema.and_then(|s| option_preview(s, &option.value)),
})
.collect();
Some(AgentQuestion {
answer_key: Some(choice.name.clone()),
header: header.to_owned(),
question: question.to_owned(),
multi_select: choice.kind == AgentFormFieldKind::Choices,
options,
})
})
.collect()
}
/// The preview claude-agent-acp forwards beside an option (`_meta["_claude/askUserQuestionOption"]`).
fn option_preview(schema: &Value, value: &str) -> Option<String> {
let listed = schema.get("oneOf").or_else(|| schema.get("anyOf")).or_else(|| schema.pointer("/items/anyOf"));
listed?
.as_array()?
.iter()
.find(|o| o.get("const").and_then(Value::as_str) == Some(value))?
.pointer("/_meta/_claude~1askUserQuestionOption/preview")?
.as_str()
.map(str::to_owned)
}
/// The form reply to the answers of [`questions_of`]'s questions (question key to the picked
/// labels and the typed text): picked options as the choice's values, the text in the field
/// beside it. The question card's Skip declines the form; nothing passes through.
pub(crate) fn answer_questions(form: &AgentForm, reply: Option<&str>) -> Option<String> {
let reply = reply?;
if reply == SKIP {
return Some(DECLINE.to_owned());
}
let Ok(answers) = serde_json::from_str::<Map<String, Value>>(reply) else { return Some(reply.to_owned()) };
let mut values = Map::new();
for pair in form.fields.chunks(2) {
let [choice, text] = pair else { continue };
let items = answers.get(&choice.name).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str);
let (mut picked, mut typed) = (Vec::new(), Vec::new());
for item in items {
match choice.options.iter().find(|o| o.label == item) {
Some(option) => picked.push(json!(option.value)),
None => typed.push(item),
}
}
values.insert(choice.name.clone(), Value::Array(picked));
values.insert(text.name.clone(), json!([typed.join("\n")]));
}
Some(Value::Object(values).to_string())
}
/// A form is submitted from its own card; this option only names a declined form.
pub(crate) fn options() -> Vec<AgentPermissionOption> {
vec![AgentPermissionOption { id: DECLINE.to_owned(), name: "Decline".to_owned(), kind: "reject_once".to_owned() }]
@@ -295,6 +392,90 @@ mod tests {
assert_eq!(chosen, "count: 3; ok: no; size: Small; tags: a, b");
}
/// What claude-agent-acp sends for `AskUserQuestion` with two questions.
fn claude_questions() -> Value {
json!({
"sessionId": "s", "mode": "form", "message": "Please answer the following questions.",
"requestedSchema": { "type": "object", "properties": {
"question_0": { "type": "string", "title": "Delivery", "description": "How should it ship?",
"oneOf": [{ "const": "Util + table (Recommended)", "title": "Util + table (Recommended)",
"description": "Tracks tasks",
"_meta": { "_claude/askUserQuestionOption": { "preview": "```\nUtil\n```" } } },
{ "const": "Util only", "title": "Util only" }] },
"question_0_custom": { "type": "string", "title": "Other" },
"question_1": { "type": "array", "title": "Targets", "description": "Who receives it?",
"items": { "anyOf": [{ "const": "Members", "title": "Members" },
{ "const": "Tags", "title": "Tags" }] } },
"question_1_custom": { "type": "string", "title": "Other" }
} }
})
}
fn in_order(params: &Value, names: &[&str]) -> AgentForm {
let mut form = form_of(params).unwrap();
form.fields.sort_by_key(|f| names.iter().position(|n| *n == f.name));
form
}
#[test]
fn a_question_tool_form_is_asked_as_questions() {
let params = claude_questions();
let form = in_order(&params, &["question_0", "question_0_custom", "question_1", "question_1_custom"]);
let questions = questions_of(&form, &params, "Please answer the following questions.").unwrap();
let [delivery, targets] = questions.as_slice() else { panic!("{questions:?}") };
assert_eq!(
(
delivery.answer_key.as_deref(),
delivery.header.as_str(),
delivery.question.as_str(),
delivery.multi_select
),
(Some("question_0"), "Delivery", "How should it ship?", false)
);
assert_eq!(delivery.options[0].description, "Tracks tasks");
assert_eq!(delivery.options[0].preview.as_deref(), Some("```\nUtil\n```"));
assert_eq!(delivery.options[1].preview, None);
assert_eq!((targets.question.as_str(), targets.multi_select), ("Who receives it?", true));
let reply = json!({ "question_0": ["Util only", "keep it small"], "question_1": ["Members", "Tags"] });
let reply = answer_questions(&form, Some(&reply.to_string()));
let (response, chosen) = answer(&form, reply.as_deref());
assert_eq!(
response,
json!({ "action": "accept", "content": {
"question_0": "Util only", "question_0_custom": "keep it small", "question_1": ["Members", "Tags"]
} })
);
assert_eq!(chosen, "Delivery: Util only; Other: keep it small; Targets: Members, Tags");
assert_eq!(answer_questions(&form, Some(SKIP)).as_deref(), Some(DECLINE));
assert_eq!(answer_questions(&form, None), None);
}
#[test]
fn a_single_question_reads_from_the_message() {
let params = ask();
let form = in_order(&params, &["q0", "q0__other"]);
let questions = questions_of(&form, &params, "Which database?").unwrap();
assert_eq!((questions[0].header.as_str(), questions[0].question.as_str()), ("", "Which database?"));
assert_eq!(questions[0].options[0].label, "Postgres");
let reply = answer_questions(&form, Some(&json!({ "q0": ["SQLite"] }).to_string()));
assert_eq!(answer(&form, reply.as_deref()).0, json!({ "action": "accept", "content": { "q0": "sqlite" } }));
}
#[test]
fn other_forms_stay_forms() {
let only_choices = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
"size": { "type": "string", "enum": ["s", "l"] }, "env": { "type": "string", "enum": ["dev"] }
} } }))
.unwrap();
assert_eq!(questions_of(&only_choices, &json!({}), "Pick"), None);
let unrelated_text = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
"size": { "type": "string", "enum": ["s", "l"] }, "note": { "type": "string" }
} } }))
.unwrap();
assert_eq!(questions_of(&unrelated_text, &json!({}), "Pick"), None);
}
#[test]
fn declining_and_dismissing_send_no_content() {
let form = form_of(&ask()).unwrap();
+397 -3
Переглянути файл
@@ -2,9 +2,10 @@
//! scanned so they can be listed and imported as tasks instead of re-explained (#312).
//!
//! Only the native providers keep transcripts on disk in a readable form: Claude Code
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`) and Codex
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`), Codex
//! (`<home>/.codex/sessions/**`, rollout files with a `session_meta` line, named in
//! `<home>/.codex/session_index.jsonl`).
//! `<home>/.codex/session_index.jsonl`), and Copilot
//! (`<config>/session-state/<id>/workspace.yaml` plus `events.jsonl`).
use super::native::claude::history;
use serde::Serialize;
@@ -17,7 +18,7 @@ use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExternalSession {
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`).
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`, `copilot`).
pub provider: String,
/// The id resuming it names (`--resume`, `thread/resume`).
pub session_id: String,
@@ -26,6 +27,9 @@ pub struct ExternalSession {
pub cwd: Option<String>,
/// File modification time, ms since the epoch.
pub updated_ms: f64,
/// Another live process (VS Code, a terminal Copilot CLI) has it open: importing would let two
/// apps write the same session, so forking a copy is the safe choice.
pub in_use: bool,
}
/// Modification time of `path` in ms, else 0.
@@ -123,6 +127,7 @@ pub fn claude_sessions(config_dir: &Path, root: &Path) -> Vec<ExternalSession> {
title,
cwd,
updated_ms: mtime(&path),
in_use: false,
});
}
}
@@ -193,6 +198,7 @@ fn codex_file(path: &Path) -> Option<ExternalSession> {
session_id,
cwd,
updated_ms: mtime(path),
in_use: false,
})
}
@@ -246,6 +252,289 @@ pub fn codex_sessions(codex_home: &Path, root: &Path) -> Vec<ExternalSession> {
sessions
}
/// Whether `raw` is a YAML block-scalar header (`|`, `|-`, `|+`, `>`, `>-`, `>+`, with optional indent digit).
fn is_yaml_block_header(raw: &str) -> bool {
let mut chars = raw.chars();
matches!(chars.next(), Some('|' | '>')) && chars.all(|c| matches!(c, '-' | '+') || c.is_ascii_digit())
}
/// Unquotes a single-line YAML scalar value from Copilot's `workspace.yaml`.
fn parse_yaml_inline_value(raw: &str) -> String {
if raw.starts_with('"') {
serde_json::from_str(raw).unwrap_or_else(|_| raw.trim_matches('"').to_owned())
} else if raw.starts_with('\'') && raw.ends_with('\'') && raw.len() >= 2 {
raw[1..raw.len() - 1].replace("''", "'")
} else {
raw.to_owned()
}
}
/// Metadata for one Copilot session, read without opening its potentially multi-gigabyte event log.
/// Supports both inline scalars (`name: "Fix\nbug"`) and block scalars (`name: |-\n Fix\n bug`).
fn copilot_metadata(path: &Path) -> Option<HashMap<String, String>> {
let file = std::fs::File::open(path).ok()?;
let mut lines = std::io::BufReader::new(file).lines().map_while(Result::ok).peekable();
let mut metadata = HashMap::new();
while let Some(line) = lines.next() {
if line.is_empty() || line.starts_with(char::is_whitespace) || line.trim_start().starts_with('#') {
continue;
}
let Some((key, raw)) = line.split_once(':') else { continue };
let key = key.trim();
let raw = raw.trim();
if key.is_empty() {
continue;
}
if is_yaml_block_header(raw) {
let folded = raw.starts_with('>');
let mut block = Vec::new();
while let Some(next) = lines.peek() {
if next.is_empty() || next.starts_with(' ') || next.starts_with('\t') {
block.push(lines.next().unwrap_or_default());
} else {
break;
}
}
while block.last().is_some_and(|l| l.trim().is_empty()) {
block.pop();
}
let indent = block
.iter()
.filter(|l| !l.trim().is_empty())
.map(|l| l.bytes().take_while(|&b| b == b' ').count())
.min()
.unwrap_or(0);
let sep = if folded { " " } else { "\n" };
let joined = block
.iter()
.map(|l| if l.len() >= indent { &l[indent..] } else { l.trim_start() })
.collect::<Vec<_>>()
.join(sep);
if !joined.trim().is_empty() {
metadata.insert(key.to_owned(), joined);
}
} else if !raw.is_empty() {
metadata.insert(key.to_owned(), parse_yaml_inline_value(raw));
}
}
(!metadata.is_empty()).then_some(metadata)
}
/// The first real prompt in a Copilot event log, used when an old or unnamed session has no title.
fn copilot_prompt(path: &Path) -> Option<String> {
let file = std::fs::File::open(path).ok()?;
std::io::BufReader::new(file)
.lines()
.take(400)
.filter_map(|line| line.ok())
.filter_map(|line| serde_json::from_str::<serde_json::Value>(&line).ok())
.find_map(|event| {
(event.get("type").and_then(serde_json::Value::as_str) == Some("user.message"))
.then(|| event.pointer("/data/content").and_then(serde_json::Value::as_str).map(str::trim))
.flatten()
.filter(|text| !text.is_empty())
.map(short)
})
}
/// Candidate VS Code Agent Host SQLite databases (`<user>/globalStorage/agent-host.db`),
/// ordered oldest-first so a newer database wins when two editions share a session.
fn vscode_agent_host_dbs(home: &Path) -> Vec<PathBuf> {
let mut bases = vec![home.join("Library/Application Support"), home.join(".config"), home.join("AppData/Roaming")];
let real_home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));
if real_home.as_deref().is_some_and(|h| Path::new(h) == home) {
for var in ["XDG_CONFIG_HOME", "APPDATA"] {
if let Some(dir) = std::env::var_os(var).filter(|v| !v.is_empty()).map(PathBuf::from)
&& !bases.contains(&dir)
{
bases.push(dir);
}
}
}
let mut dbs = Vec::new();
for base in bases {
for app in ["Code", "Code - Insiders"] {
dbs.push(base.join(app).join("User/globalStorage/agent-host.db"));
}
}
for server in [".vscode-server", ".vscode-server-insiders"] {
dbs.push(home.join(server).join("data/User/globalStorage/agent-host.db"));
}
dbs.retain(|p| p.is_file());
dbs.sort_by(|a, b| mtime(a).total_cmp(&mtime(b)));
dbs
}
fn is_generic_vscode_placeholder(title: &str, source: Option<&str>) -> bool {
source != Some("user") && (title.eq_ignore_ascii_case("new session") || title.eq_ignore_ascii_case("new chat"))
}
fn pick_vscode_chat_title(
scs_title: Option<&str>,
scs_source: Option<&str>,
metadata_json: Option<&str>,
payload_json: Option<&str>,
) -> Option<String> {
if let Some(t) = scs_title.map(str::trim).filter(|t| !t.is_empty())
&& !is_generic_vscode_placeholder(t, scs_source)
{
return Some(t.to_owned());
}
for blob in [metadata_json, payload_json].into_iter().flatten() {
let Ok(v) = serde_json::from_str::<serde_json::Value>(blob) else { continue };
let summary = v.pointer("/data/summary").and_then(serde_json::Value::as_str).map(str::trim);
let source = v.pointer("/data/titleSource").and_then(serde_json::Value::as_str);
if let Some(t) = summary.filter(|t| !t.is_empty())
&& !is_generic_vscode_placeholder(t, source)
{
return Some(t.to_owned());
}
}
None
}
/// The rows of one `agent-host.db` that map a backing Copilot session (`sdkSessionId`) to its
/// title. Read through a read-only connection that sets no `journal_mode` or other write pragma,
/// so VS Code's database is never changed. An unknown schema (a newer VS Code) reads nothing.
async fn read_vscode_chat_rows(path: &Path) -> Vec<[Option<String>; 5]> {
use sqlx::{Connection, Row};
const FULL_QUERY: &str = "\
SELECT c.provider_data, scs.title, scs.title_source, c.metadata, s.payload \
FROM chats_v2 c \
LEFT JOIN session_chat_state scs \
ON scs.session_uri = c.owner_session_uri AND scs.chat_uri = c.chat_uri \
LEFT JOIN sessions_v2 s \
ON s.session_uri = c.owner_session_uri \
WHERE c.tombstoned = 0 \
ORDER BY COALESCE(s.modified_time, 0) ASC, COALESCE(c.chat_order, 0) ASC";
const FALLBACK_QUERY: &str = "SELECT provider_data, NULL, NULL, metadata, NULL FROM chats_v2 WHERE tombstoned = 0";
let options = sqlx::sqlite::SqliteConnectOptions::new()
.filename(path)
.read_only(true)
.create_if_missing(false)
.busy_timeout(std::time::Duration::from_millis(200));
let Ok(mut conn) = sqlx::SqliteConnection::connect_with(&options).await else { return Vec::new() };
let rows = match sqlx::query(FULL_QUERY).fetch_all(&mut conn).await {
Ok(rows) => rows,
Err(_) => sqlx::query(FALLBACK_QUERY).fetch_all(&mut conn).await.unwrap_or_default(),
};
let _ = conn.close().await;
rows.iter().map(|row| std::array::from_fn(|i| row.try_get::<Option<String>, _>(i).ok().flatten())).collect()
}
/// Session titles VS Code's Agent Host (`vscode-agent-host`) assigns to backing Copilot CLI
/// sessions (`sdkSessionId` → summary or user rename). VS Code keeps these in its own
/// `agent-host.db` rather than in Copilot's `workspace.yaml`, so without them a renamed chat
/// would be listed under its first prompt. Best-effort: any failure leaves the CLI titles.
fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
let Some(home) = home else { return HashMap::new() };
let dbs = vscode_agent_host_dbs(home);
if dbs.is_empty() {
return HashMap::new();
}
// Callers are sync and may run on a runtime thread or none: a private runtime on its own
// thread works from either without blocking a runtime worker.
let rows: Vec<[Option<String>; 5]> = std::thread::scope(|scope| {
scope
.spawn(|| {
let Ok(rt) = tokio::runtime::Builder::new_current_thread().enable_all().build() else {
return Vec::new();
};
rt.block_on(async {
let mut all = Vec::new();
for path in &dbs {
all.extend(read_vscode_chat_rows(path).await);
}
all
})
})
.join()
.unwrap_or_default()
});
let mut titles = HashMap::new();
for [pdata, scs_title, scs_source, metadata, payload] in rows {
let Some(pdata) = pdata else { continue };
let Ok(pv) = serde_json::from_str::<serde_json::Value>(&pdata) else { continue };
let Some(sdk_id) = pv.get("sdkSessionId").and_then(serde_json::Value::as_str).filter(|s| !s.is_empty()) else {
continue;
};
if let Some(title) =
pick_vscode_chat_title(scs_title.as_deref(), scs_source.as_deref(), metadata.as_deref(), payload.as_deref())
{
titles.insert(sdk_id.to_owned(), title);
}
}
titles
}
/// Whether a live process holds the Copilot session in `dir`. Copilot writes `inuse.<pid>.lock`
/// while a CLI or SDK host (such as VS Code) has the session open; a crash leaves a stale one,
/// so only a lock whose process still runs counts.
fn copilot_session_in_use(dir: &Path) -> bool {
std::fs::read_dir(dir).into_iter().flatten().flatten().any(|entry| {
let name = entry.file_name();
let Some(pid) = name
.to_str()
.and_then(|n| n.strip_prefix("inuse."))
.and_then(|n| n.strip_suffix(".lock"))
.and_then(|n| n.parse::<u32>().ok())
else {
return false;
};
ide_core::process::process_alive(pid)
})
}
/// Copilot sessions of the project at `root`: `<config>/session-state/<id>`, titled by VS Code's
/// Agent Host summary/rename (when started from VS Code), their recorded CLI name, or first prompt.
/// Directories without an event log are unfinished sessions and are not listed.
pub fn copilot_sessions(copilot_home: &Path, home: Option<&Path>, root: &Path) -> Vec<ExternalSession> {
let mut pending: Vec<(ExternalSession, bool)> = std::fs::read_dir(copilot_home.join("session-state"))
.into_iter()
.flatten()
.flatten()
.filter_map(|entry| {
let dir = entry.path();
let events = dir.join("events.jsonl");
if !events.is_file() {
return None;
}
let metadata = copilot_metadata(&dir.join("workspace.yaml"))?;
let session_id = metadata.get("id").cloned().or_else(|| entry.file_name().to_str().map(str::to_owned))?;
let cwd = metadata.get("cwd").cloned().or_else(|| metadata.get("git_root").cloned());
if !in_project(cwd.as_deref(), root) {
return None;
}
let raw_name = metadata.get("name").map(String::as_str).map(str::trim).filter(|name| !name.is_empty());
let cli_user_named = metadata.get("user_named").is_some_and(|v| v == "true")
&& raw_name.is_some_and(|n| !n.eq_ignore_ascii_case("new session"));
let title = raw_name
.map(short)
.or_else(|| copilot_prompt(&events))
.unwrap_or_else(|| format!("Copilot session {}", &session_id[..session_id.len().min(8)]));
let session = ExternalSession {
provider: "copilot".to_owned(),
session_id,
title,
cwd,
updated_ms: mtime(&events),
in_use: copilot_session_in_use(&dir),
};
Some((session, cli_user_named))
})
.collect();
if !pending.is_empty() {
let vscode_titles = vscode_copilot_titles(home);
for (session, cli_user_named) in &mut pending {
if !*cli_user_named && let Some(title) = vscode_titles.get(&session.session_id) {
session.title = short(title);
}
}
}
pending.into_iter().map(|(s, _)| s).collect()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -344,6 +633,111 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
assert!(claude_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
assert!(codex_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
assert!(copilot_sessions(&tmp.path().join("nope"), None, Path::new("/work")).is_empty());
}
fn exec_sqlite(path: &Path, sql: &'static str) {
use sqlx::Connection;
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
rt.block_on(async {
let options = sqlx::sqlite::SqliteConnectOptions::new().filename(path).create_if_missing(true);
let mut conn = sqlx::SqliteConnection::connect_with(&options).await.unwrap();
sqlx::raw_sql(sql).execute(&mut conn).await.unwrap();
conn.close().await.unwrap();
});
}
#[test]
fn lists_copilot_sessions_with_names_block_scalars_vscode_titles_and_prompt_fallbacks() {
let tmp = tempfile::tempdir().unwrap();
let copilot_home = tmp.path().join(".copilot");
let session = copilot_home.join("session-state/copilot-1");
write(
&session.join("events.jsonl"),
&[
json!({"type": "session.start", "data": {}}),
json!({"type": "user.message", "data": {"content": "fix the parser"}}),
],
);
std::fs::write(
session.join("workspace.yaml"),
"id: copilot-1\ncwd: /work/app/api\nname: \"Fix parser\\nand tests\"\n",
)
.unwrap();
let block_scalar = copilot_home.join("session-state/copilot-block");
write(&block_scalar.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
std::fs::write(
block_scalar.join("workspace.yaml"),
"id: copilot-block\ncwd: /work/app\nname: |-\n check why excalidraw font\n is not displayed\nuser_named: false\n",
)
.unwrap();
let vscode_renamed = copilot_home.join("session-state/copilot-vscode");
write(
&vscode_renamed.join("events.jsonl"),
&[json!({"type": "user.message", "data": {"content": "create a branch deng/session add Create Session"}})],
);
std::fs::write(
vscode_renamed.join("workspace.yaml"),
"id: copilot-vscode\ncwd: /work/app\nclient_name: vscode-agent-host\nname: create a branch deng/session add Create Session\nuser_named: false\n",
)
.unwrap();
let vscode_placeholder = copilot_home.join("session-state/copilot-placeholder");
write(&vscode_placeholder.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
std::fs::write(
vscode_placeholder.join("workspace.yaml"),
"id: copilot-placeholder\ncwd: /work/app\nname: Greeting exchange\nuser_named: false\n",
)
.unwrap();
let unnamed = copilot_home.join("session-state/copilot-2");
write(
&unnamed.join("events.jsonl"),
&[json!({"type": "user.message", "data": {"content": "add a regression test"}})],
);
std::fs::write(unnamed.join("workspace.yaml"), "id: copilot-2\ncwd: /work/app\n").unwrap();
// A live holder marks the session in use; a lock left by a process that exited does not.
std::fs::write(session.join(format!("inuse.{}.lock", std::process::id())), "").unwrap();
std::fs::write(unnamed.join("inuse.2147483646.lock"), "").unwrap();
let empty = copilot_home.join("session-state/copilot-empty");
std::fs::create_dir_all(&empty).unwrap();
std::fs::write(empty.join("workspace.yaml"), "id: copilot-empty\ncwd: /work/app\n").unwrap();
let other = copilot_home.join("session-state/copilot-other");
write(
&other.join("events.jsonl"),
&[json!({"type": "user.message", "data": {"content": "unrelated project"}})],
);
std::fs::write(other.join("workspace.yaml"), "id: copilot-other\ncwd: /other\n").unwrap();
exec_sqlite(
&tmp.path().join(".config/Code/User/globalStorage/agent-host.db"),
"CREATE TABLE sessions_v2 (session_uri TEXT PRIMARY KEY, payload TEXT, modified_time INTEGER);
CREATE TABLE session_chat_state (session_uri TEXT, chat_uri TEXT, title TEXT, title_source TEXT);
CREATE TABLE chats_v2 (chat_uri TEXT PRIMARY KEY, owner_session_uri TEXT, chat_order INTEGER, provider_data TEXT, metadata TEXT, tombstoned INTEGER);
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs1', '{}', 100);
INSERT INTO chats_v2 VALUES ('chat:/vs1', 'copilotcli:/vs1', 0, '{\"sdkSessionId\":\"copilot-vscode\"}', '{\"data\":{\"summary\":\"Session\",\"titleSource\":\"user\"}}', 0);
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs2', '{}', 100);
INSERT INTO chats_v2 VALUES ('chat:/vs2', 'copilotcli:/vs2', 0, '{\"sdkSessionId\":\"copilot-placeholder\"}', '{\"data\":{\"summary\":\"New session\",\"titleSource\":\"auto\"}}', 0);",
);
let sessions = copilot_sessions(&copilot_home, Some(tmp.path()), Path::new("/work"));
assert_eq!(sessions.len(), 5);
let mut by_id: HashMap<_, _> = sessions.into_iter().map(|s| (s.session_id.clone(), s)).collect();
let named = by_id.remove("copilot-1").unwrap();
assert_eq!((named.provider.as_str(), named.title.as_str()), ("copilot", "Fix parser and tests"));
assert_eq!(named.cwd.as_deref(), Some("/work/app/api"));
assert!(named.in_use);
assert_eq!(by_id.remove("copilot-block").unwrap().title, "check why excalidraw font is not displayed");
assert_eq!(by_id.remove("copilot-vscode").unwrap().title, "Session");
assert_eq!(by_id.remove("copilot-placeholder").unwrap().title, "Greeting exchange");
let unnamed = by_id.remove("copilot-2").unwrap();
assert_eq!(unnamed.title, "add a regression test");
assert!(!unnamed.in_use);
}
#[test]
+9 -2
Переглянути файл
@@ -16,14 +16,19 @@ pub(crate) fn from_content(content: &Value) -> Option<AgentImage> {
if let (Some(data), Some(mime)) = (str_of(content, "data"), str_of(content, "mimeType"))
&& mime.starts_with("image/")
{
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None, inline_number: None });
}
from_uri(str_of(content, "uri")?)
}
"resource" => {
let resource = content.get("resource")?;
let (data, mime) = (str_of(resource, "blob")?, str_of(resource, "mimeType")?);
mime.starts_with("image/").then(|| AgentImage { mime_type: mime.into(), data: data.into(), name: None })
mime.starts_with("image/").then(|| AgentImage {
mime_type: mime.into(),
data: data.into(),
name: None,
inline_number: None,
})
}
"resource_link" => {
let uri = str_of(content, "uri")?;
@@ -51,6 +56,7 @@ pub(crate) fn from_uri(uri: &str) -> Option<AgentImage> {
mime_type: mime.into(),
data: data.into(),
name: None,
inline_number: None,
});
}
uri.starts_with("file://").then(|| from_file(Path::new(&uri_path(uri))))?
@@ -67,6 +73,7 @@ pub(crate) fn from_file(path: &Path) -> Option<AgentImage> {
mime_type: mime.into(),
data: base64::engine::general_purpose::STANDARD.encode(bytes),
name: path.file_name().and_then(|n| n.to_str()).map(str::to_owned),
inline_number: None,
})
}
File diff suppressed because it is too large. Load diff
+67 -16
Переглянути файл
@@ -68,9 +68,27 @@ fn to_mcp_server(scope: McpScope, name: &str, cfg: &AgentMcpServer) -> McpServer
headers: cfg.headers.iter().map(|(k, v)| McpKeyValue { name: k.clone(), value: v.clone() }).collect(),
agents: cfg.agents.clone(),
unapproved: false,
plugin_id: None,
plugin_name: None,
registry_name: cfg.registry_name.clone(),
registry_url: cfg.registry_url.clone(),
}
}
/// Merges `projected` MCP servers from enabled agent plugins behind `configured` User and
/// Workspace servers so standalone settings entries always take precedence on name clashes.
pub fn merge_projected_servers(mut configured: Vec<McpServer>, projected: Vec<McpServer>) -> Vec<McpServer> {
let existing: HashSet<String> = configured.iter().map(|s| s.name.clone()).collect();
// Same-named servers from different bundles are distinct rows (ids are `plugin:<bundle>:<server>`).
let mut seen_projected: HashSet<String> = HashSet::new();
for srv in projected {
if !existing.contains(&srv.name) && seen_projected.insert(srv.id.clone()) {
configured.push(srv);
}
}
configured
}
fn normalize_provider(id: &str) -> &str {
id.strip_suffix("-acp").unwrap_or(id)
}
@@ -238,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();
@@ -261,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 => {
@@ -285,6 +327,8 @@ pub fn apply_save(
url: Some(url.to_owned()),
headers,
agents: normalize_agents_list(input.agents),
registry_name,
registry_url,
}
}
};
@@ -399,13 +443,8 @@ pub fn apply_save_json(
Ok(saved_names)
}
const COPILOT_PLUGIN_MANIFESTS: &[&str] = &[
".github/plugin/plugin.json",
".plugin/plugin.json",
".claude-plugin/plugin.json",
".cursor-plugin/plugin.json",
"plugin.json",
];
const COPILOT_PLUGIN_MANIFESTS: &[&str] =
&[".github/plugin/plugin.json", ".plugin/plugin.json", ".claude-plugin/plugin.json", "plugin.json"];
#[derive(Clone, PartialEq, Eq)]
enum SourceFormat {
@@ -1007,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,
})
}
@@ -1051,6 +1092,14 @@ fn extract_servers_from_root(root: &Value, fallback_name: Option<&str>) -> BTree
out
}
pub(crate) fn read_external_mcp_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
read_external_file(path)
}
pub(crate) fn parse_mcp_value(root: &Value) -> Result<BTreeMap<String, AgentMcpServer>, String> {
Ok(extract_servers_from_root(root, None))
}
fn read_external_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
let Ok(text) = std::fs::read_to_string(path) else {
return BTreeMap::new();
@@ -1088,15 +1137,7 @@ pub async fn probe_stdio_server(server: &AgentMcpServer, cwd: &Path) -> McpProbe
env.push((k.clone(), v.clone()));
}
}
let search_path = env
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
.map(|(_, v)| std::ffi::OsString::from(v))
.or_else(|| ide_core::process::host_var_os("PATH"))
.unwrap_or_default();
let program = ide_core::process::find_executable(raw_cmd, &search_path)
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|| raw_cmd.to_owned());
let program = ide_jsonrpc::resolve_spawn_program(raw_cmd, &env).to_string_lossy().into_owned();
let stderr_lines = std::sync::Arc::new(parking_lot::Mutex::new(Vec::<String>::new()));
let stderr_capture = stderr_lines.clone();
@@ -1259,6 +1300,10 @@ mod tests {
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
plugin_id: None,
plugin_name: None,
registry_name: None,
registry_url: None,
}
}
@@ -1314,6 +1359,8 @@ mod tests {
url: None,
headers: Vec::new(),
agents: Vec::new(),
registry_name: None,
registry_url: None,
},
)
.unwrap();
@@ -1334,6 +1381,8 @@ mod tests {
url: None,
headers: Vec::new(),
agents: Vec::new(),
registry_name: None,
registry_url: None,
},
)
.unwrap();
@@ -1354,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
+24
Переглянути файл
@@ -453,6 +453,26 @@ pub fn discover_memories(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Age
out
}
/// Discovers all standalone memory entries across `workspaces` and `home`, then appends
/// projected rule/context entries from enabled agent plugins (deduplicated by canonical path).
pub fn discover_memories_with_plugins(
workspaces: &[PathBuf],
home: Option<&Path>,
projected: Vec<AgentMemoryEntry>,
) -> Vec<AgentMemoryEntry> {
let mut out = discover_memories(workspaces, home);
let mut seen: HashSet<PathBuf> =
out.iter().map(|e| dunce::canonicalize(&e.path.0).unwrap_or_else(|_| e.path.0.clone())).collect();
for mut entry in projected {
let canon = dunce::canonicalize(&entry.path.0).unwrap_or_else(|_| entry.path.0.clone());
entry.path = canon.clone().into();
if seen.insert(canon) {
out.push(entry);
}
}
out
}
/// Resolves the full [`AgentMemoryCatalog`] (entries + per-provider auto-memory statuses)
/// against `policy` and optional per-session `session_overrides`.
pub fn resolve_catalog(
@@ -1412,6 +1432,8 @@ fn parse_cursor_mdc(path: &Path, rel: &str) -> Option<AgentMemoryEntry> {
writable: false,
valid: true,
warnings,
plugin_id: None,
plugin_name: None,
})
}
@@ -1482,6 +1504,8 @@ fn parse_entry(
writable,
valid: true,
warnings,
plugin_id: None,
plugin_name: None,
})
}
+452 -3
Переглянути файл
@@ -71,6 +71,7 @@ pub enum InterruptionReason {
BackendStop,
UnexpectedExit,
NetworkTimeout,
CursorCapacity,
}
impl From<AgentShutdownReason> for InterruptionReason {
@@ -199,6 +200,10 @@ pub struct AgentTask {
/// Per-session recovery / network auto-retry window override in minutes (`0` = Off; `None` = inherit global).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recovery_window_mins: Option<u32>,
/// Provenance metadata when this task was created or continued by an [`crate::automation::AgentAutomation`].
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub automation: Option<Box<crate::automation::AgentTaskAutomation>>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
@@ -427,6 +432,9 @@ pub struct AgentImage {
/// Base64, without a `data:` prefix.
pub data: String,
pub name: Option<String>,
/// The `[Image #n]` label in the prompt text for an inline attachment.
#[specta(optional)]
pub inline_number: Option<u32>,
}
impl AgentImage {
@@ -454,11 +462,29 @@ pub struct AgentPrompt {
pub images: Vec<AgentImage>,
}
/// Provenance carried with a scheduled turn (`SameTask`, `Send Later`, or `/loop`), including
/// while queued behind a busy turn, so trust and approval ceilings are re-checked at dispatch.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduledTurnMeta {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub permissions: Option<crate::automation::AutomationPermissionMode>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub extra_choices: Vec<AgentConfigChoice>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub automation_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_schedule_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentQueued {
pub id: String,
pub prompt: AgentPrompt,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(skip)]
pub scheduled: Option<ScheduledTurnMeta>,
}
/// A setting chosen for a new task, by [`AgentConfigOption::id`].
@@ -616,6 +642,9 @@ pub enum AgentEntry {
/// Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn.
#[serde(default)]
recovery: Option<InterruptionReason>,
/// One-based automatic retry number for this continuation.
#[serde(default)]
retry_attempt: Option<u32>,
},
Agent {
text: String,
@@ -731,6 +760,9 @@ pub struct AgentProvider {
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
/// Whether the command was found (on `PATH`).
pub installed: bool,
/// Command the project host can run to install this missing built-in CLI.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cli_install_command: Option<String>,
/// Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal.
#[serde(default)]
pub can_sign_in: bool,
@@ -920,7 +952,7 @@ pub struct AgentModelCatalog {
}
/// Streamed to the window that subscribed (`AgentManager::subscribe_as`).
#[derive(Clone, Debug, Serialize, Type)]
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum AgentEvent {
/// A task was created or its metadata changed.
@@ -1018,6 +1050,22 @@ pub struct McpServer {
/// True when this Workspace server was added outside OpenIDEA and has not been approved yet.
#[serde(default)]
pub unapproved: bool,
/// Parent agent plugin ID when this server is live-projected from an enabled agent plugin bundle.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_id: Option<String>,
/// Display name of the parent agent plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_name: Option<String>,
/// 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.
@@ -1044,6 +1092,14 @@ pub struct McpServerInput {
/// Agent provider ids this server is enabled for; empty means enabled for all agents.
#[serde(default)]
pub agents: Vec<String>,
/// Canonical MCP registry server identifier when installed from an MCP registry.
#[serde(default)]
#[specta(optional)]
pub registry_name: Option<String>,
/// Normalized MCP registry base URL when installed from an MCP registry.
#[serde(default)]
#[specta(optional)]
pub registry_url: Option<String>,
}
fn default_true() -> bool {
@@ -1051,8 +1107,8 @@ fn default_true() -> bool {
}
pub use ide_core::settings::{
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentProviderMemoryPolicy, AgentSkillMode,
AgentSkillPolicy, AutoMemoryMode,
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings,
AgentProviderMemoryPolicy, AgentSkillMode, AgentSkillPolicy, AutoMemoryMode,
};
/// Kind of discovered agent memory entry.
@@ -1165,6 +1221,14 @@ pub struct AgentMemoryEntry {
pub valid: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
/// Parent agent plugin ID when this rule/instruction is live-projected from an enabled agent plugin bundle.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_id: Option<String>,
/// Display name of the parent agent plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_name: Option<String>,
}
/// A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin.
@@ -1337,6 +1401,14 @@ pub struct AgentSkill {
pub valid: bool,
/// What validation found (`name` mismatch, missing or over-long description…).
pub warnings: Vec<String>,
/// Parent agent plugin ID when this skill comes from an agent plugin bundle.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_id: Option<String>,
/// Display name of the parent agent plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_name: Option<String>,
}
/// A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
@@ -1398,6 +1470,383 @@ pub struct McpDiscoveredServer {
pub header_keys: Vec<String>,
}
/// Which workspace, user, or CLI store an agent plugin bundle was discovered in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginSource {
/// `~/.copilot/installed-plugins/{<marketplace>,_direct}/*`.
#[default]
CopilotUser,
/// `~/.claude/plugins/installed_plugins.json` & `~/.claude/plugins/cache/*`.
ClaudeUser,
/// `~/.codex/plugins/cache/*`.
CodexUser,
/// `~/.gemini/extensions/*`.
GeminiUser,
}
/// Manifest format(s) recognized inside an agent plugin directory.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginFormat {
/// Vendor-neutral Agent Plugins 1.0 / 1.1 (`plugin.json` with `$schema`).
#[default]
AgentPluginsV1,
/// `.openidea/plugin.json`.
OpenIdea,
/// `.claude-plugin/plugin.json`.
Claude,
/// `.plugin/plugin.json`, `.github/plugin/plugin.json`, or legacy root `plugin.json`.
Copilot,
/// `.codex-plugin/plugin.json`.
Codex,
/// `gemini-extension.json`.
GeminiExtension,
}
/// Which policy layer decided an [`AgentPluginState::enabled`] status.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginOrigin {
/// Native harness configuration owns the enabled state.
#[default]
None,
/// Locked `Off` because the workspace is untrusted.
Trust,
/// Locked `Off` until executable capabilities (stdio MCP / lifecycle hooks) are approved.
Consent,
}
/// Data type of a plugin `userConfig` / `variables` / `settings` option.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginConfigFieldKind {
#[default]
String,
Number,
Boolean,
Secret,
}
/// One configurable option declared by an agent plugin (`userConfig`, `variables`, or Gemini `settings`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginConfigField {
pub key: String,
pub title: String,
#[serde(default)]
pub description: String,
pub kind: AgentPluginConfigFieldKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub default_value: Option<String>,
#[serde(default)]
pub required: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub env_var: Option<String>,
/// Current non-sensitive value (always empty when `kind == Secret`).
#[serde(default)]
pub value: String,
/// True when a secret is stored in OS Keychain for this field.
#[serde(default)]
pub has_secret: bool,
}
/// Summary of components and executable capabilities bundled inside an agent plugin.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginCapabilities {
pub skill_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub skill_names: Vec<String>,
pub mcp_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub mcp_names: Vec<String>,
pub rule_count: u32,
pub subagent_count: u32,
pub command_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub hook_files: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub stdio_commands: Vec<String>,
#[serde(default)]
pub has_lsp: bool,
#[serde(default)]
pub has_canvas_or_app: bool,
/// Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub native_harnesses: Vec<String>,
/// Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands` + `hook_files` contents).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub capability_hash: Option<String>,
#[serde(default)]
pub requires_consent: bool,
}
/// One discovered agent plugin bundle on disk (or built-in).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPlugin {
pub id: String,
pub name: String,
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub version: Option<String>,
pub description: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub author: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub homepage: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub repository: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub license: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace: Option<String>,
pub source: AgentPluginSource,
/// Scope this bundle is installed in. Native plugin folders and enablement config are
/// resolved relative to this scope.
pub scope: McpScope,
/// Workspace whose native configuration owns this row's enablement (workspace scope only).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub workspace_root: Option<IpcPath>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub also_in: Vec<AgentPluginSource>,
pub formats: Vec<AgentPluginFormat>,
pub root_path: IpcPath,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub manifest_path: Option<IpcPath>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub readme_path: Option<IpcPath>,
pub default_enabled: bool,
pub approx_tokens: u32,
pub capabilities: AgentPluginCapabilities,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub config_fields: Vec<AgentPluginConfigField>,
pub valid: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
}
/// Resolved agent plugin state paired with its policy origin and consent status.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginState {
pub plugin: AgentPlugin,
pub enabled: bool,
pub origin: AgentPluginOrigin,
/// True when executable stdio MCP / hook capabilities require user approval before enabling.
pub consent_required: bool,
}
/// Summary of a configured or repository-discovered plugin marketplace.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMarketplaceInfo {
pub id: String,
pub name: String,
pub source: String,
pub scope: McpScope,
/// True when discovered from a harness-native marketplace/configuration file.
pub discovered: bool,
}
/// Full catalog returned to Settings › Agents › Plugins.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginCatalog {
pub plugins: Vec<AgentPluginState>,
pub marketplaces: Vec<AgentMarketplaceInfo>,
pub projected_skills: u32,
pub projected_mcp_servers: u32,
pub projected_rules: u32,
}
/// One installable plugin entry listed inside a marketplace or repository.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMarketplaceCandidate {
pub name: String,
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub version: Option<String>,
pub description: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub author: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace: Option<String>,
#[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,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub keywords: Vec<String>,
pub already_installed_user: bool,
pub already_installed_workspace: bool,
}
/// Result of browsing a marketplace (`owner/repo`, local marketplace path, or direct plugin repo).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMarketplaceBrowseResult {
pub source: String,
pub marketplace_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub owner: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub repo: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub git_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub tree_sha: Option<String>,
pub candidates: Vec<AgentMarketplaceCandidate>,
}
/// Whether a previewed plugin can be installed for one harness, and where it is already installed.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginInstallTarget {
pub harness: String,
pub supported: bool,
/// Why the harness cannot install this plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub reason: Option<String>,
/// Whether this harness can enable the plugin for just one workspace.
pub workspace_supported: bool,
/// This harness already records the plugin for the user / for the current workspace.
pub installed_user: bool,
pub installed_workspace: bool,
/// The harness store already holds this plugin version's folder, so installing replaces it.
pub overwrite_required: bool,
}
/// Security and capability preview of an agent plugin bundle before installation.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginPreview {
/// `"github"` or `"local"`.
pub source_kind: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub owner: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub repo: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub git_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub tree_sha: Option<String>,
/// Pinned commit SHA from preview when `source_kind == "github"`.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub commit_sha: Option<String>,
#[serde(default)]
pub subpath: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub local_path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace_source: Option<String>,
pub name: String,
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub version: Option<String>,
pub description: String,
#[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>,
pub scan_warnings: Vec<crate::skill_installer::SkillScanWarning>,
/// Per-harness install eligibility and existing installs for this plugin and marketplace.
pub targets: Vec<AgentPluginInstallTarget>,
}
/// Request payload to install a previewed agent plugin into a selected harness's native plugin directory.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct InstallAgentPluginRequest {
/// `"github"` or `"local"`.
pub source_kind: String,
#[serde(default)]
#[specta(optional)]
pub owner: Option<String>,
#[serde(default)]
#[specta(optional)]
pub repo: Option<String>,
#[serde(default)]
#[specta(optional)]
pub git_ref: Option<String>,
/// Pinned root tree SHA from preview when `source_kind == "github"`.
#[serde(default)]
#[specta(optional)]
pub tree_sha: Option<String>,
/// Pinned commit SHA from preview when `source_kind == "github"`.
#[serde(default)]
#[specta(optional)]
pub commit_sha: Option<String>,
#[serde(default)]
pub subpath: String,
#[serde(default)]
#[specta(optional)]
pub local_path: Option<String>,
#[serde(default)]
#[specta(optional)]
pub marketplace: Option<String>,
#[serde(default)]
#[specta(optional)]
pub marketplace_source: Option<String>,
pub scope: McpScope,
/// Native harness the plugin is installed for (`claude`, `copilot`, `codex`, or `gemini`).
pub harness: String,
#[serde(default)]
pub approve_capabilities: bool,
/// The preview's `capabilityHash` the user approved; the install is refused if the installed
/// folder resolves to different executable capabilities.
#[serde(default)]
#[specta(optional)]
pub approved_capability_hash: Option<String>,
#[serde(default)]
pub confirm_warnings: bool,
#[serde(default)]
pub overwrite: bool,
}
/// Selection of one server from an external MCP configuration source to import.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+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")?;
+142 -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);
}
}
@@ -1484,3 +1593,34 @@ async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env()
"claude-md-and-agents-md"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn session_merges_memory_settings_without_plugin_dir_or_plugin_config_injection() {
let cli = replay_cli(load_fixture("simple"));
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
let h =
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
let params = json!({
"cwd": h.cwd,
"mcpServers": [],
"_meta": {
"openidea": {
"memory": {
"claudeInstructionFiles": "claude-md-and-agents-md"
},
"plugins": { "activePlugins": ["azure", "linear@mkt"] }
}
}
});
h.request("session/new", params).await.unwrap();
let args = cli.launched.lock()[0].clone();
assert!(!args.iter().any(|a| a == "--plugin-dir"), "{args:?}");
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
assert_eq!(
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
"claude-md-and-agents-md"
);
assert!(parsed["pluginConfigs"]["azure"].is_null());
}
+188 -3
Переглянути файл
@@ -34,6 +34,14 @@ const OUTPUT_EVERY: Duration = Duration::from_millis(200);
const EARLY_CANCEL: Duration = Duration::from_secs(1);
/// How long the client's connection outlives codex.
const EXIT_GRACE: Duration = Duration::from_millis(100);
/// How often running background terminals are listed again: codex announces neither a
/// terminal that outlives its turn nor its end.
#[cfg(not(test))]
const TERMINAL_POLL: Duration = Duration::from_secs(3);
#[cfg(test)]
const TERMINAL_POLL: Duration = Duration::from_millis(20);
/// How long closing the connection waits for codex to stop the background terminals.
const TERMINAL_CLEAN: Duration = Duration::from_secs(3);
/// What a thread's name is asked for with, after its first turn.
const NAME_PROMPT: &str = "Name this conversation for a list of tasks: a short title of at most six words, in the \
language the user writes in. Reply with the title only, without quotes or a closing period.";
@@ -66,7 +74,7 @@ pub(crate) fn connect(
on_stderr: Box<dyn Fn(String) + Send + Sync>,
) -> std::io::Result<Peer> {
attach(client, |events| {
let command = super::newest_install(&spec.command);
let command = super::newest_install(spec.executable());
Peer::spawn_framed(&command, &spec.args, cwd, &spec.env, events, on_stderr, Framing::Lines)
})
}
@@ -187,6 +195,10 @@ fn attach(
}
tokio::spawn(async move {
to_client.closed().await;
// Background terminals run in process groups of their own: stopping codex alone
// would leave them running with nothing left to report or stop them.
let threads: Vec<String> = shim.state.lock().threads.keys().cloned().collect();
shim.clean_terminals(&threads).await;
codex.kill();
});
Ok(ours)
@@ -248,6 +260,14 @@ struct Thread {
token_usage: Option<Value>,
/// The thread has a name.
named: bool,
/// Running background terminals of this session and its subagents, by task id:
/// `(thread, processId)`.
terminals: HashMap<String, (String, String)>,
/// The background tasks reported last.
shown_tasks: Vec<Value>,
/// The background terminals are being followed; `relist` asks for another listing.
watching: bool,
relist: bool,
/// A name is being asked for.
naming: bool,
}
@@ -416,6 +436,7 @@ impl CodexShim {
"session/prompt" => self.prompt(&params).await,
"_openidea/steer" => self.steer(&params).await,
"_openidea/rollback" => self.rollback(&params).await,
"_openidea/stop_task" => self.stop_task(&params).await,
"session/close" => self.close(&params).await,
_ => Err(error(codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))),
}
@@ -439,7 +460,7 @@ impl CodexShim {
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
"mcpCapabilities": { "http": false, "sse": false, "stdio": true },
"sessionCapabilities": { "fork": {}, "close": {}, "additionalDirectories": {} },
"_meta": { "openidea": { "rollback": true, "steer": true } },
"_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true } },
},
"agentInfo": { "name": "codex", "title": "Codex", "version": version },
"authMethods": [],
@@ -568,9 +589,26 @@ impl CodexShim {
}
let result = self.call("thread/fork", request).await?;
let (id, options) = self.open_thread(&result, &models, settings);
// Cut by what the fork holds: a turn the source runs now may or may not be in it.
let wanted = params.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64);
let held = result.pointer("/thread/turns").and_then(Value::as_array).map(|t| t.len() as u64);
let mut kept = None;
if let (Some(turns), Some(held)) = (wanted, held)
&& turns <= held
{
let dropped = held - turns;
if dropped > 0 {
self.rollback(&json!({ "sessionId": id, "turns": dropped })).await?;
}
kept = Some(turns);
}
self.apply_skill_roots(&id, params).await;
self.publish_skills(&id).await;
Ok(json!({ "sessionId": id, "configOptions": options }))
let mut reply = json!({ "sessionId": id, "configOptions": options });
if let Some(turns) = kept {
reply["_meta"] = json!({ "openidea": { "forkTurns": turns } });
}
Ok(reply)
}
async fn set_config(&self, params: &Value) -> Result<Value, ResponseError> {
@@ -915,6 +953,16 @@ impl CodexShim {
/// Stops following the session's thread (codex unloads it once nothing follows it).
async fn close(&self, params: &Value) -> Result<Value, ResponseError> {
let session = str_param(params, "sessionId")?;
let threads: Vec<String> = {
let state = self.state.lock();
state
.threads
.iter()
.filter(|(id, t)| *id == session || t.parent.as_deref() == Some(session))
.map(|(id, _)| id.clone())
.collect()
};
self.clean_terminals(&threads).await;
let known = self.state.lock().threads.remove(session).is_some();
if known && let Err(e) = self.call("thread/unsubscribe", json!({ "threadId": session })).await {
tracing::debug!("codex: unsubscribing from {session}: {}", e.message);
@@ -922,6 +970,129 @@ impl CodexShim {
Ok(json!({}))
}
/// Follows the background terminals of `session` and its subagents until none runs:
/// codex keeps them running after the turn that started them.
fn watch_terminals(self: &Arc<Self>, session: &str) {
{
let mut state = self.state.lock();
if state.gone {
return;
}
let Some(t) = state.threads.get_mut(session) else { return };
if t.watching {
t.relist = true;
return;
}
t.watching = true;
}
let (shim, session) = (self.clone(), session.to_owned());
self.runtime.spawn(async move {
loop {
let running = shim.list_terminals(&session).await;
let relist = {
let mut state = shim.state.lock();
let Some(t) = state.threads.get_mut(&session) else { return };
let relist = std::mem::take(&mut t.relist);
if !relist && !running {
t.watching = false;
return;
}
relist
};
if !relist {
tokio::time::sleep(TERMINAL_POLL).await;
}
}
});
}
/// Reports the running background terminals of `session` and its subagents as the
/// session's background tasks; whether any runs. A codex without the (experimental)
/// listing has none to report.
async fn list_terminals(&self, session: &str) -> bool {
let threads: Vec<String> = {
let state = self.state.lock();
let children = state.threads.iter().filter(|(_, t)| t.parent.as_deref() == Some(session));
std::iter::once(session.to_owned()).chain(children.map(|(id, _)| id.clone())).collect()
};
let mut terminals = HashMap::new();
let mut tasks = Vec::new();
for thread in &threads {
let listed = match self.terminals_of(thread).await {
Ok(listed) => listed,
Err(e) => {
tracing::debug!("codex: listing the background terminals of {thread}: {}", e.message);
continue;
}
};
for (process, description) in listed {
let id = if thread == session { process.clone() } else { format!("{thread}:{process}") };
tasks.push(json!({ "task_id": id, "task_type": "local_bash", "description": description }));
terminals.insert(id, (thread.clone(), process));
}
}
let running = !tasks.is_empty();
let changed = {
let mut state = self.state.lock();
let Some(t) = state.threads.get_mut(session) else { return false };
t.terminals = terminals;
let changed = t.shown_tasks != tasks;
if changed {
t.shown_tasks = tasks.clone();
}
changed
};
if changed {
self.emit(session, json!({ "sessionUpdate": crate::BACKGROUND_TASKS_UPDATE, "tasks": tasks }));
}
running
}
/// The running background terminals of `thread`, as `(processId, description)`.
async fn terminals_of(&self, thread: &str) -> Result<Vec<(String, String)>, ResponseError> {
let mut all = Vec::new();
let mut cursor = Value::Null;
let mut seen = HashSet::new();
loop {
let page =
self.call("thread/backgroundTerminals/list", json!({ "threadId": thread, "cursor": cursor })).await?;
all.extend(translate::background_terminals(&page));
match page.get("nextCursor").and_then(Value::as_str) {
Some(next) if !next.is_empty() && seen.insert(next.to_owned()) => cursor = json!(next),
_ => return Ok(all),
}
}
}
/// `_openidea/stop_task`: stops one background terminal.
async fn stop_task(&self, params: &Value) -> Result<Value, ResponseError> {
let session = str_param(params, "sessionId")?;
let task = str_param(params, "taskId")?;
let known = self.state.lock().threads.get(session).and_then(|t| t.terminals.get(task).cloned());
let (thread, process) = known.unwrap_or_else(|| (session.to_owned(), task.to_owned()));
self.call("thread/backgroundTerminals/terminate", json!({ "threadId": thread, "processId": process })).await?;
self.list_terminals(session).await;
Ok(json!({}))
}
/// Stops the background terminals of `threads`; a codex without the (experimental)
/// method has none.
async fn clean_terminals(&self, threads: &[String]) {
if threads.is_empty() || self.state.lock().gone {
return;
}
let clean = async {
for thread in threads {
if let Err(e) = self.call("thread/backgroundTerminals/clean", json!({ "threadId": thread })).await {
tracing::debug!("codex: stopping the background terminals of {thread}: {}", e.message);
}
}
};
if tokio::time::timeout(TERMINAL_CLEAN, clean).await.is_err() {
tracing::warn!("codex: stopping the background terminals timed out");
}
}
/// `session/cancel`: interrupts the session's turn, or the one about to start.
fn cancel(&self, session: &str) {
let mut state = self.state.lock();
@@ -1261,6 +1432,19 @@ impl CodexShim {
t.turn = None;
}
t.completed = Some(id.to_owned());
// A command still open when its turn completed goes on in the background (a
// background terminal): its call returned, so it didn't fail with the turn. Its
// own completion reports how it ended. Sent before the prompt's answer settles the
// turn.
if completed {
let commands = t.items.values().filter(|i| i["type"] == "commandExecution");
for id in commands.filter_map(|i| i["id"].as_str()) {
self.emit(
thread,
json!({ "sessionUpdate": "tool_call_update", "toolCallId": id, "status": "completed" }),
);
}
}
t.items.clear();
t.last_chunk = None;
let error = t.error.take();
@@ -1275,6 +1459,7 @@ impl CodexShim {
t.naming |= name;
(t.parent.clone(), (answer, error), name)
};
self.watch_terminals(parent.as_deref().unwrap_or(thread));
if name {
let (shim, thread, turn) = (self.clone(), thread.to_owned(), id.to_owned());
self.runtime.spawn(async move { shim.name_thread(&thread, &turn).await });
+1
Переглянути файл
@@ -66,6 +66,7 @@ fn manager(dir: &Path, runtime: Arc<Runtime>) -> AgentManager {
store_dir: dir.join("store"),
worktrees_dir: dir.join("worktrees"),
models_file: dir.join("models.json"),
cli_dir: dir.join("agent-cli"),
custom_agents_dir: Some(agents),
home_dir: Some(dir.into()),
env_secrets: None,
+240 -4
Переглянути файл
@@ -125,6 +125,7 @@ for line in sys.stdin:
name: "Codex".into(),
driver: crate::provider::Driver::Codex,
command: script.to_string_lossy().into_owned(),
managed_cli: None,
args: Vec::new(),
additional_args_len: 0,
env: Vec::new(),
@@ -1019,10 +1020,12 @@ async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
.unwrap()
.unwrap_or_else(|| panic!("the shim closed before {frame}"));
let actual: Value = serde_json::from_str(&line).unwrap();
// Older recordings predate config inspection, skill discovery and thread naming; play an
// unsupported server.
// Older recordings predate config inspection, skill discovery, thread naming and
// background terminals; play an unsupported server.
let method = actual["method"].as_str().unwrap_or_default();
if matches!(method, "config/read" | "skills/list" | "thread/sample") && frame["method"] != method {
let unrecorded = matches!(method, "config/read" | "skills/list" | "thread/sample")
|| method.starts_with("thread/backgroundTerminals/");
if unrecorded && frame["method"] != method {
let reply = json!({ "id": actual["id"], "error": { "code": -32601, "message": "unsupported" } });
write.write_all(format!("{reply}\n").as_bytes()).await.unwrap();
continue;
@@ -1162,6 +1165,60 @@ impl Handler for TrustServer {
}
}
/// Forks a thread holding two finished turns and one cut off by the fork.
#[derive(Default)]
struct ForkServer {
calls: Mutex<Vec<(String, Value)>>,
}
impl Handler for ForkServer {
fn on_notification(&self, _: &str, _: Value) {}
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
self.calls.lock().push((method.to_owned(), params));
match method {
"initialize" | "thread/rollback" => Ok(json!({})),
"model/list" | "skills/list" => Ok(json!({"data": []})),
"config/read" => Ok(json!({"layers": []})),
"thread/fork" => Ok(json!({"thread": {"id": "copy", "turns": [
{"id": "t1", "status": "completed"},
{"id": "t2", "status": "completed"},
{"id": "t3", "status": "interrupted"},
]}})),
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
}
}
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_keeps_the_asked_turns_of_what_the_fork_holds() {
for (turns, rolled_back, kept) in [(Some(2), Some(1), Some(2)), (Some(3), None, Some(3)), (Some(4), None, None)] {
let server = Arc::new(ForkServer::default());
let (ours, theirs) = tokio::io::duplex(1 << 16);
let (read, write) = tokio::io::split(theirs);
let native = Peer::connect_framed(read, write, server.clone(), Framing::Lines);
let acp = attach(Arc::new(Client::default()), |events| {
let (read, write) = tokio::io::split(ours);
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
})
.unwrap();
request(&acp, "initialize", json!({})).await.unwrap();
let params = json!({"cwd": "/tmp", "sessionId": "source", "mcpServers": [],
"_meta": {"openidea": {"forkTurns": turns}}});
let reply = request(&acp, "session/fork", params).await.unwrap();
assert_eq!(reply["sessionId"], "copy");
assert_eq!(reply.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64), kept);
let rollbacks: Vec<Value> =
server.calls.lock().iter().filter(|(m, _)| m == "thread/rollback").map(|(_, p)| p.clone()).collect();
assert_eq!(
rollbacks,
rolled_back.map(|n| json!({"threadId": "copy", "numTurns": n})).into_iter().collect::<Vec<_>>()
);
acp.kill();
native.kill();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn project_trust_is_confirmed_before_new_resumed_and_forked_sessions() {
for method in ["session/new", "session/load", "session/fork"] {
@@ -1243,7 +1300,10 @@ async fn auth_failure_names_auth() {
let (results, _client, frames, _) = replay(Scenario::AuthFailure).await;
let init = result(&results, "initialize").as_ref().unwrap();
assert_eq!(init["agentCapabilities"]["loadSession"], true);
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"], json!({"rollback": true, "steer": true}));
assert_eq!(
init["agentCapabilities"]["_meta"]["openidea"],
json!({"rollback": true, "steer": true, "backgroundTasks": true})
);
assert!(init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object());
let new = result(&results, "new").as_ref().unwrap();
let categories: Vec<&str> =
@@ -2215,3 +2275,179 @@ async fn an_ephemeral_session_starts_an_ephemeral_thread() {
native.kill();
}
}
/// A codex whose background terminals listings come from `pages` (an empty list after
/// them); `None` answers like a codex without the method.
struct TerminalServer {
pages: Mutex<VecDeque<Value>>,
supported: bool,
calls: Mutex<Vec<(String, Value)>>,
}
impl TerminalServer {
fn new(pages: Vec<Value>, supported: bool) -> Arc<Self> {
Arc::new(Self { pages: Mutex::new(pages.into()), supported, calls: Mutex::default() })
}
fn calls_of(&self, method: &str) -> Vec<Value> {
self.calls.lock().iter().filter(|(m, _)| m == method).map(|(_, p)| p.clone()).collect()
}
}
impl Handler for TerminalServer {
fn on_notification(&self, _: &str, _: Value) {}
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
self.calls.lock().push((method.to_owned(), params));
match method {
"initialize" => Ok(json!({})),
"model/list" => Ok(json!({"data": []})),
"config/read" => Ok(json!({"layers": []})),
"thread/start" => Ok(json!({"thread": {"id": "s", "turns": []}, "cwd": "/w"})),
"skills/list" => Ok(json!({"data": []})),
"thread/unsubscribe" => Ok(json!({})),
m if m.starts_with("thread/backgroundTerminals/") && !self.supported => {
Err((codes::INVALID_REQUEST, format!("Invalid request: unknown variant `{m}`")))
}
"thread/backgroundTerminals/list" => {
Ok(self.pages.lock().pop_front().unwrap_or_else(|| json!({"data": [], "nextCursor": null})))
}
"thread/backgroundTerminals/terminate" => Ok(json!({"terminated": true})),
"thread/backgroundTerminals/clean" => Ok(json!({})),
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
}
}
}
fn terminal(process: &str, command: &str) -> Value {
json!({"itemId": format!("item-{process}"), "processId": process, "command": command, "cwd": "/w", "osPid": 4242})
}
/// A session over a codex playing `server`; the codex peer and the ACP peer.
async fn terminal_session(server: Arc<TerminalServer>, client: Arc<Client>) -> (Peer, Peer) {
let (ours, theirs) = tokio::io::duplex(1 << 16);
let (read, write) = tokio::io::split(theirs);
let native = Peer::connect_framed(read, write, server, Framing::Lines);
let acp = attach(client, |events| {
let (read, write) = tokio::io::split(ours);
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
})
.unwrap();
let init = request(&acp, "initialize", json!({})).await.unwrap();
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"]["backgroundTasks"], true);
request(&acp, "session/new", json!({"cwd": "/w", "mcpServers": []})).await.unwrap();
(native, acp)
}
fn shown_tasks(client: &Client) -> Vec<Value> {
client
.of("s")
.into_iter()
.filter(|u| u["sessionUpdate"] == crate::BACKGROUND_TASKS_UPDATE)
.map(|u| u["tasks"].clone())
.collect()
}
async fn until(what: &str, mut done: impl FnMut() -> bool) {
for _ in 0..200 {
if done() {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("timed out waiting for {what}");
}
#[tokio::test(flavor = "multi_thread")]
async fn background_terminals_outlive_their_turn_as_background_tasks_until_they_end() {
let running = json!({"data": [terminal("p1", "/bin/zsh -lc 'sleep 600; echo done'")], "nextCursor": null});
let server = TerminalServer::new(vec![running.clone(), running.clone(), running], true);
let client = Arc::new(Client::default());
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
until("the terminal to end", || shown_tasks(&client).len() == 2).await;
assert_eq!(
shown_tasks(&client),
[json!([{"task_id": "p1", "task_type": "local_bash", "description": "sleep 600; echo done"}]), json!([])]
);
let listed = server.calls_of("thread/backgroundTerminals/list").len();
assert!(listed >= 4, "listed until none ran, got {listed}");
tokio::time::sleep(Duration::from_millis(100)).await;
assert_eq!(server.calls_of("thread/backgroundTerminals/list").len(), listed, "stops listing once none runs");
acp.kill();
native.kill();
}
#[tokio::test(flavor = "multi_thread")]
async fn a_background_terminal_stops_on_request_and_all_stop_with_the_connection() {
let running = json!({"data": [terminal("p1", "cargo nextest run")], "nextCursor": null});
let server = TerminalServer::new(vec![running; 1000], true);
let client = Arc::new(Client::default());
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
until("the terminal to show", || !shown_tasks(&client).is_empty()).await;
request(&acp, "_openidea/stop_task", json!({"sessionId": "s", "taskId": "p1"})).await.unwrap();
assert_eq!(server.calls_of("thread/backgroundTerminals/terminate"), [json!({"threadId": "s", "processId": "p1"})]);
assert!(server.calls_of("thread/backgroundTerminals/clean").is_empty());
acp.kill();
until("the terminals to be cleaned", || !server.calls_of("thread/backgroundTerminals/clean").is_empty()).await;
assert_eq!(server.calls_of("thread/backgroundTerminals/clean"), [json!({"threadId": "s"})]);
native.kill();
}
#[tokio::test(flavor = "multi_thread")]
async fn closing_a_session_stops_its_background_terminals() {
let server = TerminalServer::new(Vec::new(), true);
let client = Arc::new(Client::default());
let (native, acp) = terminal_session(server.clone(), client).await;
request(&acp, "session/close", json!({"sessionId": "s"})).await.unwrap();
let calls: Vec<String> = server.calls.lock().iter().map(|(m, _)| m.clone()).collect();
let clean = calls.iter().position(|m| m == "thread/backgroundTerminals/clean").expect("cleaned");
let unsubscribe = calls.iter().position(|m| m == "thread/unsubscribe").expect("unsubscribed");
assert!(clean < unsubscribe);
acp.kill();
native.kill();
}
#[tokio::test(flavor = "multi_thread")]
async fn a_codex_without_background_terminals_reports_none() {
let server = TerminalServer::new(Vec::new(), false);
let client = Arc::new(Client::default());
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
until("the listing", || !server.calls_of("thread/backgroundTerminals/list").is_empty()).await;
tokio::time::sleep(Duration::from_millis(100)).await;
assert_eq!(server.calls_of("thread/backgroundTerminals/list").len(), 1);
assert!(shown_tasks(&client).is_empty());
assert!(request(&acp, "_openidea/stop_task", json!({"sessionId": "s", "taskId": "p1"})).await.is_err());
acp.kill();
native.kill();
}
#[tokio::test(flavor = "multi_thread")]
async fn a_command_left_running_by_a_completed_turn_is_not_a_failure() {
for (status, settled) in [("completed", true), ("interrupted", false)] {
let server = TerminalServer::new(Vec::new(), true);
let client = Arc::new(Client::default());
let (native, acp) = terminal_session(server, client.clone()).await;
let item = json!({"type": "commandExecution", "id": "call_1", "command": "/bin/zsh -lc 'sleep 240'",
"cwd": "/w", "status": "inProgress", "commandActions": []});
native.notify("item/started", json!({"threadId": "s", "turnId": "t1", "item": item})).unwrap();
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": status}})).unwrap();
until("the command card", || client.of("s").iter().any(|u| u["sessionUpdate"] == "tool_call")).await;
tokio::time::sleep(Duration::from_millis(50)).await;
let updates: Vec<Value> = client
.of("s")
.into_iter()
.filter(|u| u["sessionUpdate"] == "tool_call_update" && u["toolCallId"] == "call_1")
.collect();
let expected = if settled {
vec![json!({"sessionUpdate": "tool_call_update", "toolCallId": "call_1", "status": "completed"})]
} else {
Vec::new()
};
assert_eq!(updates, expected, "turn {status}");
acp.kill();
native.kill();
}
}
+20 -1
Переглянути файл
@@ -553,7 +553,12 @@ fn image_content(image: &crate::model::AgentImage) -> Value {
/// A generated image: inline (base64 PNG) or, when codex saved it, the file.
fn generated_image(item: &Value) -> Option<crate::model::AgentImage> {
if let Some(data) = item.get("result").and_then(Value::as_str).filter(|d| !d.is_empty()) {
let image = crate::model::AgentImage { mime_type: "image/png".into(), data: data.into(), name: None };
let image = crate::model::AgentImage {
mime_type: "image/png".into(),
data: data.into(),
name: None,
inline_number: None,
};
return Some(crate::model::AgentImage { mime_type: image.media_type().into(), ..image });
}
crate::images::from_file(std::path::Path::new(item.get("savedPath")?.as_str()?))
@@ -876,6 +881,20 @@ pub(super) fn decisions(params: &Value, command: bool) -> Vec<Choice> {
out
}
/// One page of `thread/backgroundTerminals/list`: the running terminals as
/// `(processId, description)`.
pub(super) fn background_terminals(page: &Value) -> Vec<(String, String)> {
let data = page.get("data").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
data.iter()
.filter_map(|t| {
let process = t.get("processId").and_then(Value::as_str).filter(|p| !p.is_empty())?;
let command = t.get("command").and_then(Value::as_str).unwrap_or_default();
let description = crate::shell_script(command).unwrap_or_else(|| command.to_owned());
Some((process.to_owned(), description))
})
.collect()
}
/// A command prefix as typed: the script of a `<shell> -lc <script>` wrapper, else the words.
fn shell_unwrapped(argv: &[&str]) -> String {
match argv {
+59 -4
Переглянути файл
@@ -37,6 +37,15 @@ const DISCOVER_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(5) } else
const EARLY_CANCEL: Duration = Duration::from_secs(2);
const EXIT_GRACE: Duration = Duration::from_millis(100);
/// Copilot's configuration directory (`COPILOT_HOME`, otherwise `<home>/.copilot`).
pub(crate) fn config_dir(env: &[(String, String)], home: Option<&Path>) -> Option<PathBuf> {
env.iter()
.find(|(key, _)| key == "COPILOT_HOME")
.map(|(_, value)| PathBuf::from(value))
.or_else(|| std::env::var_os("COPILOT_HOME").map(PathBuf::from))
.or_else(|| home.map(|home| home.join(".copilot")))
}
/// Pre-session discovery result for `Shared::fetch_settings`.
pub(crate) struct Discovered {
pub commands: Vec<Value>,
@@ -59,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)
})
@@ -551,6 +560,7 @@ impl CopilotShim {
"initialize" => self.initialize().await,
"session/new" => self.new_session(&params).await,
"session/load" => self.load_session(&params).await,
"session/fork" => self.fork_session(&params).await,
"session/set_config_option" => self.set_config(&params).await,
"session/prompt" => self.prompt(&params, false).await,
"_openidea/steer" => self.prompt(&params, true).await,
@@ -569,7 +579,7 @@ impl CopilotShim {
"loadSession": true,
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
"mcpCapabilities": { "http": true, "sse": true, "stdio": true },
"sessionCapabilities": { "close": {}, "list": {} },
"sessionCapabilities": { "fork": {}, "close": {}, "list": {} },
"_meta": { "openidea": { "steer": true, "backgroundTasks": true, "contextUsage": true } },
},
"agentInfo": {
@@ -649,6 +659,25 @@ impl CopilotShim {
async fn load_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
let session_id = str_param(params, "sessionId")?.to_owned();
let loaded = self.resume_session(params, &session_id).await?;
let actual_id = loaded.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
self.replay_history(&actual_id).await;
Ok(loaded)
}
async fn fork_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
let source = str_param(params, "sessionId")?;
let forked = self.call("sessions.fork", json!({ "sessionId": source })).await?;
let target = forked
.get("sessionId")
.and_then(Value::as_str)
.filter(|id| !id.is_empty())
.ok_or_else(|| error(codes::INTERNAL_ERROR, "Copilot fork returned no sessionId"))?
.to_owned();
self.resume_session(params, &target).await
}
async fn resume_session(self: &Arc<Self>, params: &Value, session_id: &str) -> Result<Value, ResponseError> {
let cwd = str_param(params, "cwd")?;
let catalog = self.models().await?;
let defaults = fetch_user_defaults(self.copilot(), &self.args).await;
@@ -675,7 +704,8 @@ impl CopilotShim {
apply_memory(params, &mut req);
let resumed = self.call("session.resume", req).await?;
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(session_id).to_owned();
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": actual_id })).await {
if let Some(model_id) = current.get("modelId").or_else(|| current.get("model")).and_then(Value::as_str) {
let _ = settings.set(&catalog, MODEL, model_id);
}
@@ -686,7 +716,6 @@ impl CopilotShim {
let _ = settings.set(&catalog, CONTEXT_TIER, tier);
}
}
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
let options = models::config_options(&catalog, &settings);
self.state.lock().sessions.insert(actual_id.clone(), SessionEntry::new(settings));
self.publish_commands(&actual_id, cwd);
@@ -697,6 +726,28 @@ impl CopilotShim {
}))
}
async fn replay_history(&self, session_id: &str) {
let history = match self.call("session.getMessages", json!({ "sessionId": session_id })).await {
Ok(history) => history,
Err(error) => {
tracing::warn!("copilot session {session_id}: could not load history: {}", error.message);
return;
}
};
let events = history.get("events").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
let updates = {
let mut state = self.state.lock();
let Some(entry) = state.sessions.get_mut(session_id) else { return };
events
.iter()
.flat_map(|event| entry.translator.translate_history(session_id, event, None).updates)
.collect::<Vec<_>>()
};
for (target_session, update) in updates {
self.send_update(&target_session, update);
}
}
fn sync_usage_metrics(self: &Arc<Self>, session_id: &str) {
let shim = self.clone();
let sid = session_id.to_owned();
@@ -1321,6 +1372,10 @@ fn build_prompt_payload(session_id: &str, blocks: &[Value]) -> (String, Vec<Valu
{
let path_str = saved.to_string_lossy().into_owned();
let name = saved.file_name().and_then(|n| n.to_str()).unwrap_or("image").to_owned();
// Copilot takes one text prompt and a separate attachments array.
if let Some(number) = block.pointer("/_meta/openideaImageNumber").and_then(Value::as_u64) {
text_parts.push(format!("[Image #{number}: {name}]"));
}
attachments.push(json!({ "type": "file", "path": path_str, "displayName": name }));
temp_files.push(saved);
}
+120
Переглянути файл
@@ -115,6 +115,18 @@ fn sample_price_units() -> Value {
})
}
#[test]
fn resolves_copilot_home_from_agent_env_or_user_home() {
let home = std::path::Path::new("/home/test");
assert_eq!(
super::config_dir(&[("COPILOT_HOME".into(), "/custom/copilot".into())], Some(home)).as_deref(),
Some(std::path::Path::new("/custom/copilot"))
);
if std::env::var_os("COPILOT_HOME").is_none() {
assert_eq!(super::config_dir(&[], Some(home)), Some(home.join(".copilot")));
}
}
#[test]
fn parses_an_enabled_auto_only_catalog() {
let list = json!({
@@ -434,6 +446,39 @@ impl Handler for FakeCopilotServer {
"skills.discover" => Ok(json!({ "skills": [] })),
"session.create" => Ok(json!({ "sessionId": "cop-sess-1" })),
"session.resume" => Ok(json!({ "sessionId": params["sessionId"] })),
"sessions.fork" => Ok(json!({ "sessionId": "cop-sess-fork" })),
"session.getMessages" => Ok(json!({
"events": [
{
"type": "user.message",
"data": { "content": "Fix the parser" }
},
{
"type": "assistant.message",
"data": {
"messageId": "history-message",
"reasoningText": "Inspect the grammar first.",
"content": "I fixed the parser."
}
},
{
"type": "tool.execution_start",
"data": {
"toolCallId": "history-tool",
"toolName": "view",
"arguments": { "path": "/tmp/parser.rs" }
}
},
{
"type": "tool.execution_complete",
"data": {
"toolCallId": "history-tool",
"success": true,
"result": { "content": "fn parse() {}" }
}
}
]
})),
"session.model.getCurrent" => Ok(json!({ "modelId": "gemini-4-carbon" })),
"session.model.switchTo" => Ok(json!({ "modelId": params["modelId"] })),
"session.mode.set" => Ok(json!({})),
@@ -674,6 +719,81 @@ async fn shim_creates_session_with_copilot_defaults_switches_tiers_and_streams_t
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shim_loads_and_replays_copilot_history() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates.clone(), move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let init: Value = client.request("initialize", json!({}), None).await.unwrap();
assert!(init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object());
let loaded: Value = client
.request("session/load", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
.await
.unwrap();
assert_eq!(loaded["sessionId"], "cop-sess-1");
assert!(
server
.calls
.lock()
.iter()
.any(|(method, params)| { method == "session.getMessages" && params["sessionId"] == "cop-sess-1" })
);
let seen = updates.0.lock();
assert!(
seen.iter().any(|u| u["sessionUpdate"] == "user_message_chunk" && u["content"]["text"] == "Fix the parser")
);
assert!(
seen.iter().any(
|u| u["sessionUpdate"] == "agent_thought_chunk" && u["content"]["text"] == "Inspect the grammar first."
)
);
assert!(
seen.iter()
.any(|u| u["sessionUpdate"] == "agent_message_chunk" && u["content"]["text"] == "I fixed the parser.")
);
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call" && u["toolCallId"] == "history-tool"));
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call_update" && u["toolCallId"] == "history-tool"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shim_forks_copilot_sessions_and_resumes_the_new_id() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates, move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
let forked: Value = client
.request("session/fork", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
.await
.unwrap();
assert_eq!(forked["sessionId"], "cop-sess-fork");
let calls = server.calls.lock();
assert!(calls.iter().any(|(method, params)| method == "sessions.fork" && params["sessionId"] == "cop-sess-1"));
assert!(calls.iter().any(|(method, params)| method == "session.resume" && params["sessionId"] == "cop-sess-fork"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shim_forwards_disabled_mcp_servers_on_create_and_resume() {
let server =
+49
Переглянути файл
@@ -370,6 +370,55 @@ impl EventTranslator {
}
out
}
/// Translates one persisted Copilot event returned by `session.getMessages`. The live
/// event stream omits historical user messages and emits reasoning deltas, while the
/// persisted form has complete user and assistant messages.
pub fn translate_history(&mut self, main_session: &str, event: &Value, fallback_limit: Option<u32>) -> Translated {
let event_type = str_of(event, "type").unwrap_or_default();
let data = event.get("data").unwrap_or(&Value::Null);
if event_type == "user.message" {
let Some(text) = str_of(data, "content").map(str::trim).filter(|text| !text.is_empty()) else {
return Translated { updates: Vec::new(), terminal: None };
};
let target_session = str_of(event, "agentId")
.filter(|id| !id.is_empty())
.map(|id| format!("{main_session}:sub:{id}"))
.unwrap_or_else(|| main_session.to_owned());
return Translated {
updates: vec![(
target_session,
json!({
"sessionUpdate": "user_message_chunk",
"content": { "type": "text", "text": text },
}),
)],
terminal: None,
};
}
let mut translated = self.translate(main_session, event, fallback_limit);
if event_type == "assistant.message"
&& !(data.get("parentToolCallId").and_then(Value::as_str).is_some() && str_of(event, "agentId").is_none())
&& let Some(reasoning) = str_of(data, "reasoningText").map(str::trim).filter(|text| !text.is_empty())
{
let target_session = str_of(event, "agentId")
.filter(|id| !id.is_empty())
.map(|id| format!("{main_session}:sub:{id}"))
.unwrap_or_else(|| main_session.to_owned());
translated.updates.insert(
0,
(
target_session,
json!({
"sessionUpdate": "agent_thought_chunk",
"content": { "type": "text", "text": reasoning },
}),
),
);
}
translated
}
}
fn describe_tool(name: &str, args: &Value) -> ToolInfo {
+4 -6
Переглянути файл
@@ -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`
@@ -25,11 +27,7 @@ use std::sync::Arc;
/// A path, or a name not found on `PATH`, is used as it is; a single match returns its
/// resolved path so Windows `PATHEXT` shims (`claude.cmd`, `codex.cmd`) start.
pub(crate) fn newest_install(command: &str) -> String {
let path = ide_core::process::host_var_os("PATH")
.or_else(|| ide_core::process::shell_env().find(|(k, _)| *k == "PATH").map(|(_, v)| v.to_owned()))
.unwrap_or_default();
// Windows: read afresh, so a tool the user installed since the IDE started is found too.
newest_install_in(command, &ide_core::process::with_user_path(&path))
newest_install_in(command, &ide_core::tool_path::search_path())
}
fn newest_install_in(command: &str, search: &std::ffi::OsStr) -> String {
File diff suppressed because it is too large. Load diff
+136 -23
Переглянути файл
@@ -35,6 +35,7 @@ pub(crate) struct ProviderSpec {
pub name: String,
pub driver: Driver,
pub command: String,
pub managed_cli: Option<String>,
pub args: Vec<String>,
/// Number of trailing arguments added by the built-in agent's settings.
pub additional_args_len: usize,
@@ -90,6 +91,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
("vibe", "Mistral Vibe", Driver::Acp, &["vibe-acp"], "Run `vibe` in a terminal and sign in."),
("omp", "OMP", Driver::Acp, &["omp", "acp"], "Run `omp` in a terminal and sign in."),
("hermes", "Hermes Agent", Driver::Acp, &["hermes", "acp"], "Run `hermes model` in a terminal."),
("antigravity-acp", "Google Antigravity", Driver::Acp, &["agy", "acp"], "Run `agy acp --login` in a terminal."),
];
fn builtins() -> Vec<ProviderSpec> {
@@ -100,6 +102,7 @@ fn builtins() -> Vec<ProviderSpec> {
name: (*name).into(),
driver: *driver,
command: cmd[0].into(),
managed_cli: None,
args: cmd[1..].iter().map(|a| (*a).to_owned()).collect(),
additional_args_len: 0,
env: Vec::new(),
@@ -110,11 +113,15 @@ fn builtins() -> Vec<ProviderSpec> {
}
impl ProviderSpec {
pub(crate) fn executable(&self) -> &str {
self.managed_cli.as_deref().unwrap_or(&self.command)
}
pub(crate) fn login_hint(&self, program: &Path) -> String {
if !program.is_absolute() {
return self.login_hint.clone();
}
let search = ide_core::process::host_var_os("PATH").unwrap_or_default();
let search = ide_core::tool_path::search_path();
let builtin = builtin_spec(&self.id);
let on_path = builtin.as_ref().and_then(|b| ide_core::process::find_executable(&b.command, &search));
render_login_hint(self, program, on_path.as_deref(), cfg!(windows))
@@ -135,7 +142,7 @@ impl ProviderSpec {
.flatten();
let hint = match terminal_args {
Some(args) => {
let command = render_login_command(program, args, cfg!(windows));
let command = render_shell_command(program, args, cfg!(windows));
format!("Run `{command}` in a terminal.")
}
None => self.login_hint(program),
@@ -179,7 +186,9 @@ impl ProviderSpec {
}
fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
if self.driver != Driver::Acp {
if let Some(program) = self.managed_cli.take() {
self.command = program;
} else if self.driver != Driver::Acp {
self.command = crate::native::newest_install(&self.command);
}
if is_copilot_provider(&self.id) {
@@ -222,7 +231,9 @@ impl ProviderSpec {
});
}
if let Some(builtin) = builtin_spec(&self.id) {
if let Some(builtin) = builtin_spec(&self.id)
&& !(matches!(self.source, AgentSource::Registry { .. }) && registry_uses_separate_binary(&self.id))
{
let args = terminal_auth_args
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
.map(<[String]>::to_vec)
@@ -533,7 +544,7 @@ fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>
return spec.login_hint.clone();
}
let (args, suffix) = rest.split_once('`').expect("built-in login hints delimit their command");
let command = render_login_command(program, args.split_whitespace(), windows);
let command = render_shell_command(program, args.split_whitespace(), windows);
match suffix {
" in a terminal." => format!("Run `{command}` in a terminal."),
" in a terminal and sign in." => format!("Run `{command}` in a terminal and sign in."),
@@ -541,7 +552,11 @@ fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>
}
}
fn render_login_command<'a>(program: &Path, args: impl IntoIterator<Item = &'a str>, windows: bool) -> String {
pub(crate) fn render_shell_command<'a>(
program: &Path,
args: impl IntoIterator<Item = &'a str>,
windows: bool,
) -> String {
let quote = |word: &str| {
if windows { format!("'{}'", word.replace('\'', "''")) } else { format!("'{}'", word.replace('\'', "'\\''")) }
};
@@ -585,6 +600,13 @@ pub(crate) fn is_unlisted(spec: &ProviderSpec) -> bool {
UNLISTED.contains(&spec.id.as_str()) && builtin_spec(&spec.id).as_ref() == Some(spec)
}
/// Built-in CLI agents whose ACP Registry archive ships a separate ACP server binary
/// rather than the CLI itself, so the built-in CLI's login subcommand does not apply
/// to a registry install.
fn registry_uses_separate_binary(id: &str) -> bool {
id == "antigravity-acp"
}
fn uses_package_runner(command: &str) -> bool {
matches!(command, "npx" | "bunx" | "uvx")
}
@@ -610,20 +632,21 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
AgentProvider {
id: spec.id.clone(),
name: spec.name.clone(),
command: std::iter::once(spec.command.as_str())
command: std::iter::once(spec.executable())
.chain(spec.args.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" "),
program: spec.command.clone(),
program: spec.executable().to_owned(),
args: spec.args.clone(),
additional_args,
default_program: builtin.as_ref().map(|b| b.command.clone()),
default_args: builtin.as_ref().map(|b| b.args.clone()).unwrap_or_default(),
login_hint: Some(spec.login_hint(&ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env))),
login_hint: Some(spec.login_hint(&ide_jsonrpc::resolve_spawn_program(spec.executable(), &spec.env))),
command_overridden: builtin.as_ref().is_some_and(|b| b.command != spec.command),
command_editable: reason.is_none(),
command_read_only_reason: reason,
installed: installed(&spec.command),
installed: installed_with_env(spec.executable(), &spec.env),
cli_install_command: None,
can_sign_in: spec.can_sign_in(Path::new("."), None),
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
env: spec.env.iter().cloned().collect(),
@@ -747,6 +770,20 @@ fn update_builtin(
agent.write_with(&file, id, secrets)
}
/// Project backends can share a config directory. Keep the ID check, credential
/// changes and file write in the same critical section.
fn lock_custom_agents(custom_dir: &Path) -> std::io::Result<std::fs::File> {
std::fs::create_dir_all(custom_dir)?;
let lock = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(custom_dir.join(".custom-agents.lock"))?;
lock.lock()?;
Ok(lock)
}
/// Saves a new custom agent; refuses built-in and ACP Registry ids, taken ids
/// and an empty command. The id is also the agent file's name, so it must be
/// a safe file stem.
@@ -762,6 +799,7 @@ pub(crate) fn save_custom(
if input.command.trim().is_empty() {
return Err(IdeError::invalid("the agent command must not be empty"));
}
let _lock = lock_custom_agents(custom_dir)?;
let file = custom_dir.join(format!("{id}.toml"));
if file.try_exists()? {
if CustomAgent::read(&file).is_ok_and(|a| a.registry.is_some()) {
@@ -790,6 +828,7 @@ pub(crate) fn remove_custom(custom_dir: &Path, secrets: Option<&dyn EnvSecrets>,
if builtin_spec(id).is_some() {
return Err(IdeError::invalid(format!("{id} is a built-in agent and cannot be removed")));
}
let _lock = lock_custom_agents(custom_dir)?;
let file = custom_dir.join(format!("{id}.toml"));
let agent =
CustomAgent::read(&file).map_err(|_| IdeError::not_found(format!("there is no custom agent '{id}'")))?;
@@ -829,6 +868,7 @@ pub(crate) fn import_acp(
}
let parsed: AcpJson =
serde_json::from_str(text).map_err(|e| IdeError::invalid(format!("not an acp.json file: {e}")))?;
let _lock = lock_custom_agents(custom_dir)?;
let mut outcomes = Vec::with_capacity(parsed.agent_servers.len());
for (name, server) in parsed.agent_servers {
let id = slugify_id(&name);
@@ -1024,6 +1064,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
name: agent.name.unwrap_or_else(|| id.clone()),
driver: agent.driver,
command: agent.command,
managed_cli: None,
args: agent.args,
additional_args_len: 0,
env,
@@ -1033,7 +1074,9 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
};
match specs.iter_mut().find(|s| s.id == spec.id) {
Some(existing) => {
spec.login_hint = existing.login_hint.clone();
if !(matches!(spec.source, AgentSource::Registry { .. }) && registry_uses_separate_binary(&spec.id)) {
spec.login_hint = existing.login_hint.clone();
}
if !explicit_driver && existing.driver == Driver::Copilot && spec.driver == Driver::Acp {
// Registry installs (`github-copilot-cli`) record `args = ["--acp"]` with no
// `driver`; upgrade them in place to the native headless driver (which
@@ -1057,19 +1100,23 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
specs
}
/// Whether `command` resolves to an executable (a path, or a name on `PATH`).
/// Whether `command` resolves to an executable (a path, or a name on [`ide_core::tool_path::search_path`]).
#[cfg(test)]
pub(crate) fn installed(command: &str) -> bool {
installed_with_env(command, &[])
}
pub(crate) fn installed_with_env(command: &str, env: &[(String, String)]) -> bool {
let p = Path::new(command);
if p.components().count() > 1 {
if p.components().count() > 1 || p.is_absolute() {
return is_executable(p);
}
let exts: &[&str] = if cfg!(windows) { &["exe", "cmd", "bat"] } else { &[] };
std::env::var_os("PATH").is_some_and(|path| {
std::env::split_paths(&path).any(|dir| {
let c = dir.join(command);
is_executable(&c) || exts.iter().any(|e| is_executable(&c.with_extension(e)))
})
})
if let Some((_, path)) = env.iter().find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
&& ide_core::process::find_executable(command, std::ffi::OsStr::new(path)).is_some()
{
return true;
}
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
}
fn is_executable(p: &Path) -> bool {
@@ -1098,6 +1145,55 @@ mod tests {
assert_eq!(info.login_hint.as_deref(), Some("Run `hermes model` in a terminal."));
}
#[test]
fn antigravity_is_built_in_over_acp() {
let spec = builtin_spec("antigravity-acp").unwrap();
assert_eq!(spec.driver, Driver::Acp);
assert!(!is_builtin("antigravity-acp"));
let info = describe(&spec);
assert_eq!((info.name.as_str(), info.command.as_str()), ("Google Antigravity", "agy acp"));
assert_eq!(info.login_hint.as_deref(), Some("Run `agy acp --login` in a terminal."));
assert!(info.command_editable);
assert_eq!(info.additional_args, Some(vec![]));
}
#[test]
fn registry_antigravity_does_not_inherit_cli_login_subcommand() {
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join(if cfg!(windows) { "agy_acp_server.exe" } else { "agy_acp_server.par" });
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
}
CustomAgent {
name: Some("Google Antigravity".into()),
driver: Driver::Acp,
command: bin.to_string_lossy().into_owned(),
args: Vec::new(),
additional_args: Vec::new(),
env: BTreeMap::new(),
registry: Some(RegistryRef { id: "antigravity-acp".into(), version: "1.5.2".into() }),
}
.write(&dir.path().join("antigravity-acp.toml"))
.unwrap();
let reg = load(Some(dir.path()), None).into_iter().find(|s| s.id == "antigravity-acp").unwrap();
assert_eq!(reg.source, AgentSource::Registry { version: "1.5.2".into(), update: None });
assert_eq!(reg.login_hint, "Sign in with the agent's own command line first.");
assert_eq!(describe(&reg).login_hint.as_deref(), Some("Sign in with the agent's own command line first."));
assert!(reg.login_launch(dir.path(), None).is_none());
let terminal_launch = reg.login_launch(dir.path(), Some(&["--login".into()])).unwrap();
assert_eq!(terminal_launch.program, bin);
assert_eq!(terminal_launch.args, ["--login"]);
std::fs::remove_file(dir.path().join("antigravity-acp.toml")).unwrap();
let builtin = load(Some(dir.path()), None).into_iter().find(|s| s.id == "antigravity-acp").unwrap();
assert_eq!(builtin.source, AgentSource::Builtin);
assert_eq!((builtin.command.as_str(), builtin.args.as_slice()), ("agy", &["acp".to_owned()][..]));
}
#[test]
fn qoder_global_and_cn_editions_are_both_built_in() {
let info = |id: &str| describe(&load(None, None).into_iter().find(|s| s.id == id).unwrap());
@@ -1150,6 +1246,7 @@ mod tests {
assert_eq!(args("copilot"), ["login"]);
assert_eq!(args("goose"), ["configure"]);
assert_eq!(args("hermes"), ["model"]);
assert_eq!(args("antigravity-acp"), ["acp", "--login"]);
assert!(args("qwen").is_empty());
}
@@ -1224,7 +1321,7 @@ mod tests {
(true, "& '/agent''s tools/$cli' auth login --account 'user name' 'a''b' '$token' ''"),
] {
assert_eq!(
render_login_command(
render_shell_command(
Path::new("/agent's tools/$cli"),
["auth", "login", "--account", "user name", "a'b", "$token", ""],
windows
@@ -1276,10 +1373,10 @@ mod tests {
for p in &defaults {
assert_eq!(p.source, AgentSource::Builtin);
assert!(p.default_program.is_some());
assert_eq!(p.command_editable, !p.id.ends_with("-acp"));
assert_eq!(p.command_editable, !uses_package_runner(&p.program));
assert_eq!(
p.command_read_only_reason,
p.id.ends_with("-acp").then_some(AgentCommandReadOnlyReason::PackageRunner)
uses_package_runner(&p.program).then_some(AgentCommandReadOnlyReason::PackageRunner)
);
}
set_builtin_command(dir.path(), None, "codex", Some("/path with spaces/codex")).unwrap();
@@ -1326,6 +1423,22 @@ mod tests {
assert!(installed("sh"));
}
#[test]
fn installed_with_env_resolves_executables_on_provider_path() {
let dir = tempfile::tempdir().unwrap();
let name = if cfg!(windows) { "fake-agent.cmd" } else { "fake-agent" };
let exe = dir.path().join(name);
std::fs::write(&exe, "").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
}
assert!(!installed("fake-agent"));
let env = vec![("PATH".to_owned(), dir.path().to_string_lossy().into_owned())];
assert!(installed_with_env("fake-agent", &env));
}
#[test]
fn set_builtin_env_writes_and_clears_the_environment() {
let dir = tempfile::tempdir().unwrap();
+5 -3
Переглянути файл
@@ -320,7 +320,7 @@ fn is_builtin(id: &str) -> bool {
}
fn on_path(command: &str) -> bool {
which::which(command).is_ok()
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
}
/// `1.10.0` > `1.9.2`; a release is newer than its pre-releases.
@@ -708,7 +708,8 @@ fn install_npm(
emit: Emit,
) -> IdeResult<PathBuf> {
let (name, _) = split_npm_spec(&p.package);
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
let npm = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path())
.ok_or_else(|| IdeError::unavailable(format!("npm is required to install {name}")))?;
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
}
@@ -789,7 +790,8 @@ fn install_uv(
_ => format!("{name}=={}", entry.version),
};
check_spec(&spec)?;
let uv = which::which("uv").map_err(|_| IdeError::unavailable(format!("uv is required to install {name}")))?;
let uv = ide_core::process::find_executable("uv", &ide_core::tool_path::search_path())
.ok_or_else(|| IdeError::unavailable(format!("uv is required to install {name}")))?;
let bin = dir.join("bin");
let mut cmd = Command::new(uv);
cmd.args(["tool", "install", "--force"])
+1 -16
Переглянути файл
@@ -185,22 +185,7 @@ pub(crate) fn recorder(out: PathBuf) -> Connector {
let file = Arc::new(Mutex::new(String::new()));
let connections = Arc::new(Mutex::new(0u32));
Arc::new(move |spec, cwd, client, on_stderr| {
let program = {
let path = Path::new(&spec.command);
if path.components().count() > 1 || path.is_absolute() {
path.to_path_buf()
} else {
let search = spec
.env
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
.map(|(_, v)| std::ffi::OsString::from(v))
.or_else(|| ide_core::process::shell_env().find(|(k, _)| k == "PATH").map(|(_, v)| v))
.or_else(|| ide_core::process::host_var_os("PATH"))
.unwrap_or_default();
ide_core::process::find_executable(&spec.command, &search).unwrap_or_else(|| path.to_path_buf())
}
};
let program = ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env);
let mut cmd = tokio::process::Command::new(&program);
ide_core::process::prepare(cmd.as_std_mut());
let mut child = cmd
+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,
+517 -47
Переглянути файл
@@ -163,6 +163,15 @@ pub struct RepoRef<'a> {
pub trait SkillSourceFetcher: Send + Sync {
fn default_branch(&self, owner: &str, repo: &str, cancel: &CancellationToken) -> IdeResult<String>;
fn git_commit_sha(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<String>;
/// The root tree SHA recorded in commit `commit_sha`.
fn git_commit_tree_sha(
&self,
owner: &str,
repo: &str,
commit_sha: &str,
cancel: &CancellationToken,
) -> IdeResult<String>;
fn git_tree(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<GitTree>;
fn read_blob(
&self,
@@ -238,6 +247,63 @@ impl SkillSourceFetcher for GitHubHttpFetcher {
.map_err(|e| IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{git_ref}: invalid Git tree: {e}")))
}
fn git_commit_sha(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<String> {
#[derive(Deserialize)]
struct CommitMeta {
sha: String,
}
let RepoRef { owner, repo, git_ref } = target;
validate_repo_coord(owner, "owner")?;
validate_repo_coord(repo, "repository")?;
validate_git_ref(git_ref)?;
let encoded_ref = encode_url_segment(git_ref);
let url = format!("https://api.github.com/repos/{owner}/{repo}/commits/{encoded_ref}");
let body = self.get_github_json(&url, MAX_REPO_META_BYTES, cancel)?;
let meta: CommitMeta = serde_json::from_str(&body).map_err(|e| {
IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{git_ref}: invalid GitHub commit: {e}"))
})?;
if !is_git_object_id(&meta.sha) {
return Err(IdeError::new(
ErrorKind::Protocol,
format!("{owner}/{repo}@{git_ref}: invalid GitHub commit SHA"),
));
}
Ok(meta.sha)
}
fn git_commit_tree_sha(
&self,
owner: &str,
repo: &str,
commit_sha: &str,
cancel: &CancellationToken,
) -> IdeResult<String> {
#[derive(Deserialize)]
struct TreeRef {
sha: String,
}
#[derive(Deserialize)]
struct GitCommit {
tree: TreeRef,
}
validate_repo_coord(owner, "owner")?;
validate_repo_coord(repo, "repository")?;
if !is_git_object_id(commit_sha) {
return Err(IdeError::invalid("Invalid commit SHA"));
}
let url = format!("https://api.github.com/repos/{owner}/{repo}/git/commits/{commit_sha}");
let body = self.get_github_json(&url, MAX_REPO_META_BYTES, cancel)?;
let commit: GitCommit = serde_json::from_str(&body).map_err(|e| {
IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{commit_sha}: invalid Git commit: {e}"))
})?;
if !is_git_object_id(&commit.tree.sha) {
return Err(IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{commit_sha}: invalid tree SHA")));
}
Ok(commit.tree.sha)
}
fn read_blob(
&self,
target: RepoRef<'_>,
@@ -616,6 +682,17 @@ fn sanitize_repo_as_skill_name(repo: &str) -> String {
out.trim_matches('-').to_owned()
}
pub(crate) struct FetchedSubtree {
pub tree_sha: String,
pub normalized_subpath: String,
pub files: Vec<RemoteSkillFile>,
pub scan_warnings: Vec<SkillScanWarning>,
/// `(relative_path, bytes, executable)` for safe non-symlink files to write on disk.
pub regular_files: Vec<(PathBuf, Vec<u8>, bool)>,
/// `(relative_path, relative_target)` for safe internal symlinks.
pub in_root_symlinks: Vec<(PathBuf, PathBuf)>,
}
struct PreparedSkillBundle {
tree_sha: String,
skill_name: String,
@@ -629,14 +706,19 @@ struct PreparedSkillBundle {
in_root_symlinks: Vec<(PathBuf, PathBuf)>,
}
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
fn fetch_and_scan_bundle(
/// Fetches `target`'s tree (or exactly `pinned_tree_sha` when set) and scans `subpath` with hardened
/// symlink-graph, executable-script, and hidden-Unicode checks.
#[allow(clippy::too_many_arguments)]
pub(crate) fn fetch_and_scan_subtree(
fetcher: &dyn SkillSourceFetcher,
target: RepoRef<'_>,
subpath: &str,
pinned_tree_sha: Option<&str>,
max_files: usize,
max_subtree_bytes: u64,
noun: &str,
cancel: &CancellationToken,
) -> IdeResult<PreparedSkillBundle> {
) -> IdeResult<FetchedSubtree> {
let RepoRef { owner, repo, git_ref } = target;
validate_repo_coord(owner, "owner")?;
validate_repo_coord(repo, "repository")?;
@@ -646,9 +728,8 @@ fn fetch_and_scan_bundle(
let tree = match pinned_tree_sha {
Some(sha) => {
if !is_git_object_id(sha) {
return Err(IdeError::invalid("Preview the skill again before installing it"));
return Err(IdeError::invalid(format!("Preview the {noun} again before installing it")));
}
// The Git trees API accepts a tree SHA in place of a ref.
let tree = fetcher.git_tree(RepoRef { owner, repo, git_ref: sha }, cancel)?;
if !tree.sha.eq_ignore_ascii_case(sha) {
return Err(IdeError::new(
@@ -660,6 +741,14 @@ fn fetch_and_scan_bundle(
}
None => fetcher.git_tree(target, cancel)?,
};
if tree.truncated {
return Err(IdeError::new(
ErrorKind::Protocol,
format!(
"{owner}/{repo}@{git_ref}: GitHub returned a truncated file listing; the {noun} cannot be verified"
),
));
}
let prefix = if normalized_subpath.is_empty() { String::new() } else { format!("{normalized_subpath}/") };
let subtree_entries: Vec<&GitTreeEntry> = tree
@@ -672,27 +761,32 @@ fn fetch_and_scan_bundle(
if subtree_entries.is_empty() {
return Err(IdeError::not_found(format!(
"Skill path {:?} was not found in {owner}/{repo}@{git_ref}",
"{} path {:?} was not found in {owner}/{repo}@{git_ref}",
capitalize(noun),
normalized_subpath
)));
}
if subtree_entries.len() > MAX_SKILL_FILES {
if subtree_entries.len() > max_files {
return Err(IdeError::invalid(format!(
"Skill exceeds maximum of {MAX_SKILL_FILES} files ({} found)",
"{} exceeds maximum of {max_files} files ({} found)",
capitalize(noun),
subtree_entries.len()
)));
}
let declared_total: u64 = subtree_entries.iter().map(|e| e.size.unwrap_or(0)).sum();
if declared_total > MAX_SKILL_SUBTREE_BYTES {
return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20)));
if declared_total > max_subtree_bytes {
return Err(IdeError::invalid(format!(
"{} exceeds {} MiB size cap",
capitalize(noun),
max_subtree_bytes >> 20
)));
}
let mut files = Vec::with_capacity(subtree_entries.len());
let mut scan_warnings = Vec::new();
let mut regular_files = Vec::new();
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
let mut skill_markdown: Option<String> = None;
let mut actual_total = 0u64;
for entry in subtree_entries {
@@ -709,12 +803,16 @@ fn fetch_and_scan_bundle(
target,
&entry.path,
&entry.sha,
MAX_SINGLE_BLOB_BYTES.min(MAX_SKILL_SUBTREE_BYTES - actual_total),
MAX_SINGLE_BLOB_BYTES.min(max_subtree_bytes - actual_total),
cancel,
)?;
actual_total = actual_total.saturating_add(bytes.len() as u64);
if actual_total > MAX_SKILL_SUBTREE_BYTES {
return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20)));
if actual_total > max_subtree_bytes {
return Err(IdeError::invalid(format!(
"{} exceeds {} MiB size cap",
capitalize(noun),
max_subtree_bytes >> 20
)));
}
if is_symlink {
@@ -748,11 +846,15 @@ fn fetch_and_scan_bundle(
if let Ok(text) = std::str::from_utf8(&bytes) {
scan_hidden_unicode(rel_str, text, &mut scan_warnings);
if rel_str == "SKILL.md" {
skill_markdown = Some(text.to_owned());
if rel_str == "SKILL.md" || rel_str.ends_with("/SKILL.md") {
for tool in frontmatter_shell_tools(text) {
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::AllowedToolsShell,
file: rel_str.to_owned(),
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
});
}
}
} else if rel_str == "SKILL.md" {
return Err(IdeError::invalid("SKILL.md is not valid UTF-8 text"));
}
files.push(RemoteSkillFile {
@@ -767,13 +869,12 @@ fn fetch_and_scan_bundle(
files.sort_by(|a, b| a.path.cmp(&b.path));
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
// Symlinks are judged together: one link may point through another, and an entry placed beneath
// a symlink would be written wherever that link points.
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
if let Some(link) = graph.symlink_ancestor(path) {
return Err(IdeError::invalid(format!(
"Skill entry {:?} is inside symlink {link:?}; the repository tree is malformed",
"{} entry {:?} is inside symlink {link:?}; the repository tree is malformed",
capitalize(noun),
path.display().to_string()
)));
}
@@ -786,26 +887,65 @@ fn fetch_and_scan_bundle(
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::OutOfRootSymlink,
file: rel_str,
message: format!("Symlink target {target_raw:?} leaves the skill folder (omitted on install)"),
message: format!("Symlink target {target_raw:?} leaves the {noun} folder (omitted on install)"),
});
}
}
in_root_symlinks.sort();
let Some(skill_markdown) = skill_markdown else {
return Err(IdeError::invalid("Selected folder does not contain a regular SKILL.md file"));
};
Ok(FetchedSubtree { tree_sha: tree.sha, normalized_subpath, files, scan_warnings, regular_files, in_root_symlinks })
}
let folder_hint = normalized_subpath
fn capitalize(s: &str) -> String {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
}
}
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
fn fetch_and_scan_bundle(
fetcher: &dyn SkillSourceFetcher,
target: RepoRef<'_>,
subpath: &str,
pinned_tree_sha: Option<&str>,
cancel: &CancellationToken,
) -> IdeResult<PreparedSkillBundle> {
let RepoRef { repo, .. } = target;
let mut sub = fetch_and_scan_subtree(
fetcher,
target,
subpath,
pinned_tree_sha,
MAX_SKILL_FILES,
MAX_SKILL_SUBTREE_BYTES,
"skill",
cancel,
)?;
let skill_bytes = sub
.regular_files
.iter()
.find(|(p, _, _)| p == Path::new("SKILL.md"))
.map(|(_, b, _)| b.as_slice())
.ok_or_else(|| IdeError::invalid("Selected folder does not contain a regular SKILL.md file"))?;
let skill_markdown =
std::str::from_utf8(skill_bytes).map_err(|_| IdeError::invalid("SKILL.md is not valid UTF-8 text"))?.to_owned();
let folder_hint = sub
.normalized_subpath
.rsplit('/')
.next()
.filter(|s| !s.is_empty())
.map(str::to_owned)
.unwrap_or_else(|| sanitize_repo_as_skill_name(repo));
// Strip any `SKILL.md` shell-tool warnings already collected so `parse_skill_markdown_metadata` emits them in order.
sub.scan_warnings.retain(|w| !(w.kind == SkillScanWarningKind::AllowedToolsShell && w.file == "SKILL.md"));
let parsed_meta = parse_skill_markdown_metadata(&folder_hint, &skill_markdown)?;
for tool in &parsed_meta.shell_tools {
scan_warnings.push(SkillScanWarning {
sub.scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::AllowedToolsShell,
file: "SKILL.md".into(),
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
@@ -813,14 +953,14 @@ fn fetch_and_scan_bundle(
}
Ok(PreparedSkillBundle {
tree_sha: tree.sha,
tree_sha: sub.tree_sha,
skill_name: parsed_meta.name,
description: parsed_meta.description,
skill_markdown,
files,
scan_warnings,
regular_files,
in_root_symlinks,
files: sub.files,
scan_warnings: sub.scan_warnings,
regular_files: sub.regular_files,
in_root_symlinks: sub.in_root_symlinks,
})
}
@@ -1140,6 +1280,33 @@ fn create_parent_dirs_no_follow(root: &Path, rel: &Path) -> IdeResult<()> {
Ok(())
}
/// Creates `target` below the existing `anchor` (the home or project folder) without following a
/// symlink in any directory between them, the harness store root included.
fn create_dirs_below_anchor(anchor: &Path, target: &Path) -> IdeResult<()> {
if !anchor.is_dir() {
return Err(IdeError::not_found(format!("{} does not exist", anchor.display())));
}
let rel = target
.strip_prefix(anchor)
.map_err(|_| IdeError::invalid(format!("{} is outside {}", target.display(), anchor.display())))?;
let mut dir = anchor.to_path_buf();
for component in rel.components() {
if !matches!(component, Component::Normal(_)) {
return Err(IdeError::invalid(format!("{} is not a plain path below the store", target.display())));
}
dir.push(component);
match std::fs::symlink_metadata(&dir) {
Ok(meta) if meta.is_dir() => {}
Ok(_) => {
return Err(IdeError::invalid(format!("{} passes through a symlink or file", dir.display())));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => std::fs::create_dir(&dir)?,
Err(e) => return Err(e.into()),
}
}
Ok(())
}
/// Whether the symlink at `link` resolves strictly inside `root` (canonical), following links on disk.
/// Components that do not exist are resolved lexically.
#[cfg(unix)]
@@ -1220,15 +1387,16 @@ pub fn install_skill(
workspace_root: Option<&Path>,
cancel: &CancellationToken,
) -> IdeResult<PathBuf> {
let target_root = match req.scope {
// Anchored at the home or project folder: nothing below it may be a symlink, store included.
let (anchor, target_root) = match req.scope {
McpScope::User => {
let home = user_home.ok_or_else(|| IdeError::unavailable("Cannot locate user home directory"))?;
home.join(".agents").join("skills")
(home.to_path_buf(), home.join(".agents").join("skills"))
}
McpScope::Workspace => {
let ws = workspace_root
.ok_or_else(|| IdeError::invalid("Open a trusted project to install workspace skills"))?;
ws.join(".agents").join("skills")
(ws.to_path_buf(), ws.join(".agents").join("skills"))
}
};
@@ -1245,20 +1413,60 @@ pub fn install_skill(
));
}
std::fs::create_dir_all(&target_root)?;
let final_dir = target_root.join(&bundle.skill_name);
if final_dir.exists() && !req.overwrite {
write_staged_subtree(
&anchor,
&target_root,
&bundle.skill_name,
req.overwrite,
"Skill",
&bundle.regular_files,
&bundle.in_root_symlinks,
&[],
)
}
/// Atomically writes `regular_files`, `in_root_symlinks`, and `extra_files` into a staging folder
/// under `target_root`, verifies created symlinks stay inside the folder, and swaps into `<target_root>/<folder_name>`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn write_staged_subtree(
anchor: &Path,
target_root: &Path,
folder_name: &str,
overwrite: bool,
noun_cap: &str,
regular_files: &[(PathBuf, Vec<u8>, bool)],
in_root_symlinks: &[(PathBuf, PathBuf)],
extra_files: &[(&str, &[u8])],
) -> IdeResult<PathBuf> {
create_dirs_below_anchor(anchor, target_root)?;
if folder_name.is_empty() || !Path::new(folder_name).components().all(|c| matches!(c, Component::Normal(_))) {
return Err(IdeError::invalid(format!("Invalid {} folder name", noun_cap.to_ascii_lowercase())));
}
let final_dir = target_root.join(folder_name);
let existing = match std::fs::symlink_metadata(&final_dir) {
Ok(meta) if meta.is_dir() => true,
Ok(_) => {
return Err(IdeError::invalid(format!(
"{} is a symlink or file, not a {} folder",
final_dir.display(),
noun_cap.to_ascii_lowercase()
)));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
Err(e) => return Err(e.into()),
};
if existing && !overwrite {
return Err(IdeError::new(
ErrorKind::AlreadyExists,
format!("Skill `{}` is already installed in {}", bundle.skill_name, target_root.display()),
format!("{noun_cap} `{folder_name}` is already installed in {}", target_root.display()),
));
}
let nonce = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();
let staging = target_root.join(format!(".staging-{}-{nonce}-{}", bundle.skill_name, std::process::id()));
let staging = target_root.join(format!(".staging-{folder_name}-{nonce}-{}", std::process::id()));
let write_res = (|| -> IdeResult<()> {
std::fs::create_dir_all(&staging)?;
for (rel_path, bytes, is_exec) in &bundle.regular_files {
for (rel_path, bytes, is_exec) in regular_files {
create_parent_dirs_no_follow(&staging, rel_path)?;
let dest = staging.join(rel_path);
std::fs::write(&dest, bytes)?;
@@ -1270,7 +1478,12 @@ pub fn install_skill(
#[cfg(not(unix))]
let _ = is_exec;
}
for (rel_link, target) in &bundle.in_root_symlinks {
for (rel_str, bytes) in extra_files {
let rel_path = validate_rel_skill_file(rel_str)?;
create_parent_dirs_no_follow(&staging, &rel_path)?;
std::fs::write(staging.join(&rel_path), bytes)?;
}
for (rel_link, target) in in_root_symlinks {
create_parent_dirs_no_follow(&staging, rel_link)?;
let dest = staging.join(rel_link);
#[cfg(unix)]
@@ -1288,17 +1501,18 @@ pub fn install_skill(
#[cfg(unix)]
{
let root = std::fs::canonicalize(&staging)?;
for (rel_link, _) in &bundle.in_root_symlinks {
for (rel_link, _) in in_root_symlinks {
if !link_resolves_inside(&root, &staging.join(rel_link)) {
return Err(IdeError::invalid(format!(
"Symlink {:?} leaves the skill folder",
rel_link.display().to_string()
"Symlink {:?} leaves the {} folder",
rel_link.display().to_string(),
noun_cap.to_ascii_lowercase()
)));
}
}
}
let backup = if final_dir.exists() {
let bak = target_root.join(format!(".old-{}-{nonce}", bundle.skill_name));
let backup = if existing {
let bak = target_root.join(format!(".old-{folder_name}-{nonce}"));
std::fs::rename(&final_dir, &bak)?;
Some(bak)
} else {
@@ -1323,6 +1537,179 @@ pub fn install_skill(
Ok(final_dir)
}
/// Scans a local directory on disk with the same symlink-graph, executable-script, and hidden-Unicode
/// checks used for remote GitHub subtrees.
/// Content digest of a scanned local folder, used to pin a local preview to its install.
fn local_subtree_digest(regular_files: &[(PathBuf, Vec<u8>, bool)], symlinks: &[(PathBuf, PathBuf)]) -> String {
let mut hasher = blake3::Hasher::new();
hasher.update(b"openidea-local-subtree-v1\0");
for (path, bytes, executable) in regular_files {
hasher.update(b"f\0");
hasher.update(path.to_string_lossy().replace('\\', "/").as_bytes());
hasher.update(&[0, u8::from(*executable)]);
hasher.update(&(bytes.len() as u64).to_le_bytes());
hasher.update(bytes);
}
for (path, target) in symlinks {
hasher.update(b"l\0");
hasher.update(path.to_string_lossy().replace('\\', "/").as_bytes());
hasher.update(b"\0");
hasher.update(target.to_string_lossy().replace('\\', "/").as_bytes());
hasher.update(b"\0");
}
format!("local-blake3:{}", hasher.finalize().to_hex())
}
pub(crate) fn scan_local_subtree(
dir: &Path,
max_files: usize,
max_subtree_bytes: u64,
noun: &str,
) -> IdeResult<FetchedSubtree> {
if !dir.is_dir() {
return Err(IdeError::not_found(format!("Directory {} does not exist", dir.display())));
}
let mut files = Vec::new();
let mut scan_warnings = Vec::new();
let mut regular_files = Vec::new();
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
let mut actual_total = 0u64;
let mut stack = vec![(dir.to_path_buf(), String::new())];
while let Some((cur_dir, rel_prefix)) = stack.pop() {
let mut entries: Vec<_> = std::fs::read_dir(&cur_dir)?.filter_map(Result::ok).collect();
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let name = entry.file_name();
let Some(name_str) = name.to_str() else {
return Err(IdeError::invalid(format!(
"{} contains a file name that is not valid UTF-8: {}",
capitalize(noun),
entry.path().display()
)));
};
if name_str == ".git" || name_str == "node_modules" || name_str == "target" {
continue;
}
let rel_str = if rel_prefix.is_empty() { name_str.to_owned() } else { format!("{rel_prefix}/{name_str}") };
let rel_path = validate_rel_skill_file(&rel_str)?;
let full = entry.path();
let meta = std::fs::symlink_metadata(&full)?;
if (meta.file_type().is_symlink() || meta.file_type().is_file())
&& regular_files.len() + symlinks.len() >= max_files
{
return Err(IdeError::invalid(format!("{} exceeds maximum of {max_files} files", capitalize(noun))));
}
if meta.file_type().is_symlink() {
let target_raw = std::fs::read_link(&full)?.to_string_lossy().replace('\\', "/");
symlinks.push((rel_path, rel_str.clone(), target_raw));
files.push(RemoteSkillFile { path: rel_str, size: 0, executable: false, symlink: true });
continue;
}
if meta.file_type().is_dir() {
stack.push((full, rel_str));
continue;
}
if !meta.file_type().is_file() {
continue;
}
if meta.len() > MAX_SINGLE_BLOB_BYTES {
return Err(IdeError::invalid(format!(
"File {rel_str:?} exceeds {} MiB size cap",
MAX_SINGLE_BLOB_BYTES >> 20
)));
}
let bytes = std::fs::read(&full)?;
actual_total = actual_total.saturating_add(bytes.len() as u64);
if actual_total > max_subtree_bytes {
return Err(IdeError::invalid(format!(
"{} exceeds {} MiB size cap",
capitalize(noun),
max_subtree_bytes >> 20
)));
}
#[cfg(unix)]
let is_exec_mode = {
use std::os::unix::fs::PermissionsExt;
meta.permissions().mode() & 0o111 != 0
};
#[cfg(not(unix))]
let is_exec_mode = false;
let has_shebang = bytes.starts_with(b"#!");
let is_script_path = is_executable_or_script_path(&rel_path);
if is_exec_mode || has_shebang || is_script_path {
let reason = if is_exec_mode {
"executable file mode"
} else if has_shebang {
"script with `#!` interpreter header"
} else {
"bundled script or native binary"
};
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::ExecutableScript,
file: rel_str.clone(),
message: format!("Contains {reason}"),
});
}
if let Ok(text) = std::str::from_utf8(&bytes) {
scan_hidden_unicode(&rel_str, text, &mut scan_warnings);
if rel_str == "SKILL.md" || rel_str.ends_with("/SKILL.md") {
for tool in frontmatter_shell_tools(text) {
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::AllowedToolsShell,
file: rel_str.clone(),
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
});
}
}
}
files.push(RemoteSkillFile {
path: rel_str,
size: bytes.len() as u64,
executable: is_exec_mode || has_shebang,
symlink: false,
});
regular_files.push((rel_path, bytes, is_exec_mode));
}
}
files.sort_by(|a, b| a.path.cmp(&b.path));
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
if let Some(link) = graph.symlink_ancestor(path) {
return Err(IdeError::invalid(format!(
"{} entry {:?} is inside symlink {link:?}",
capitalize(noun),
path.display().to_string()
)));
}
}
let mut in_root_symlinks = Vec::new();
for (rel_path, rel_str, target_raw) in symlinks {
if graph.stays_inside(&rel_path, &target_raw) {
in_root_symlinks.push((rel_path, PathBuf::from(target_raw)));
} else {
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::OutOfRootSymlink,
file: rel_str,
message: format!("Symlink target {target_raw:?} leaves the {noun} folder (omitted on install)"),
});
}
}
in_root_symlinks.sort();
Ok(FetchedSubtree {
tree_sha: local_subtree_digest(&regular_files, &in_root_symlinks),
normalized_subpath: String::new(),
files,
scan_warnings,
regular_files,
in_root_symlinks,
})
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1374,6 +1761,25 @@ mod tests {
.cloned()
.ok_or_else(|| IdeError::not_found(format!("unknown ref {}", target.git_ref)))
}
fn git_commit_sha(&self, target: RepoRef<'_>, _cancel: &CancellationToken) -> IdeResult<String> {
self.trees
.get(target.git_ref)
.map(|_| git_blob_id(format!("commit:{}", target.git_ref).as_bytes()))
.ok_or_else(|| IdeError::not_found(format!("unknown ref {}", target.git_ref)))
}
fn git_commit_tree_sha(
&self,
_owner: &str,
_repo: &str,
commit_sha: &str,
_cancel: &CancellationToken,
) -> IdeResult<String> {
self.trees
.iter()
.find(|(git_ref, _)| git_blob_id(format!("commit:{git_ref}").as_bytes()) == commit_sha)
.map(|(_, tree)| tree.sha.clone())
.ok_or_else(|| IdeError::not_found(format!("unknown commit {commit_sha}")))
}
fn read_blob(
&self,
@@ -1440,7 +1846,9 @@ mod tests {
let cancel = CancellationToken::new();
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
std::fs::create_dir_all(&home).unwrap();
let ws = tmp.path().join("ws");
std::fs::create_dir_all(&ws).unwrap();
// Bare `owner/repo` lists both skills; `owner/repo@clean-skill` falls back from ref lookup to skill filter!
let all = browse_skills(&fetcher, "acme/skills", &cancel).unwrap();
@@ -1796,4 +2204,66 @@ mod tests {
.unwrap();
assert!(dest.join("SKILL.md").is_file());
}
#[cfg(unix)]
#[test]
fn local_scan_counts_symlinks_toward_the_file_cap() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("SKILL.md"), "x").unwrap();
for i in 0..3 {
std::os::unix::fs::symlink("SKILL.md", tmp.path().join(format!("link-{i}"))).unwrap();
}
let Err(err) = scan_local_subtree(tmp.path(), 3, 1 << 20, "plugin") else { panic!("symlinks must count") };
assert!(err.to_string().contains("maximum of 3 files"), "{err}");
}
#[test]
fn truncated_tree_listings_are_rejected() {
let mut fetcher = FakeFetcher::new();
fetcher.add_tree("main", vec![("skills/a/SKILL.md", "100644", b"---\nname: a\ndescription: a\n---\n")]);
fetcher.trees.get_mut("main").unwrap().truncated = true;
let cancel = CancellationToken::new();
let target = RepoRef { owner: "o", repo: "r", git_ref: "main" };
let Err(err) = fetch_and_scan_subtree(&fetcher, target, "skills/a", None, 10, 1 << 20, "skill", &cancel) else {
panic!("a truncated listing cannot be verified")
};
assert!(err.to_string().contains("truncated"), "{err}");
}
#[cfg(unix)]
#[test]
fn staged_installs_do_not_follow_symlinks_below_the_store() {
let tmp = tempfile::tempdir().unwrap();
let store = tmp.path().join("store");
let outside = tmp.path().join("outside");
std::fs::create_dir_all(&store).unwrap();
std::fs::create_dir_all(&outside).unwrap();
std::os::unix::fs::symlink(&outside, store.join("mkt")).unwrap();
let files = vec![(PathBuf::from("plugin.json"), b"{}".to_vec(), false)];
let Err(err) = write_staged_subtree(&store, &store.join("mkt"), "plugin", false, "Plugin", &files, &[], &[])
else {
panic!("a symlinked marketplace folder must not be written through")
};
assert!(err.to_string().contains("symlink"), "{err}");
assert!(std::fs::read_dir(&outside).unwrap().next().is_none(), "nothing was written outside the store");
// The store root itself (`<home>/.claude/plugins` → elsewhere) is checked as well.
let home = tmp.path().join("home");
std::fs::create_dir_all(home.join(".claude")).unwrap();
std::os::unix::fs::symlink(&outside, home.join(".claude/plugins")).unwrap();
let store_root = home.join(".claude/plugins/cache/mkt");
let Err(err) = write_staged_subtree(&home, &store_root, "plugin", false, "Plugin", &files, &[], &[]) else {
panic!("a symlinked store root must not be written through")
};
assert!(err.to_string().contains("symlink"), "{err}");
assert!(std::fs::read_dir(&outside).unwrap().next().is_none());
std::fs::create_dir_all(store.join("real")).unwrap();
std::os::unix::fs::symlink(&outside, store.join("real/plugin")).unwrap();
let Err(err) = write_staged_subtree(&store, &store.join("real"), "plugin", true, "Plugin", &files, &[], &[])
else {
panic!("an existing symlinked plugin folder must not be replaced through")
};
assert!(err.to_string().contains("symlink"), "{err}");
}
}
+179 -73
Переглянути файл
@@ -275,12 +275,45 @@ pub fn discover_skills_in(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Ag
}
/// [`discover_skills_in`] plus the `<dir>` skill folders contributed by enabled OpenIDEA
/// plugins (`[[contributes.skills]]`). Workspace and user skills take precedence on a name
/// clash; a plugin skill is never silently renamed.
/// plugins (`[[contributes.skills]]`) and unified agent plugin bundles (`plugins.rs`).
/// Workspace and user skills take precedence on a name clash; a plugin skill is never silently renamed.
pub fn discover_skills_with_plugins(
workspaces: &[PathBuf],
home: Option<&Path>,
plugin_skill_dirs: &[PathBuf],
) -> Vec<AgentSkill> {
let default_policy = crate::plugins::PluginsPolicy { workspace_roots: workspaces.to_vec(), ..Default::default() };
let states =
crate::plugins::resolve_plugins(crate::plugins::discover_plugins(workspaces, home), &default_policy, None);
let projected = crate::plugins::projected_skill_roots(&states, None);
discover_skills_with_agent_plugins(workspaces, home, plugin_skill_dirs, &projected)
}
/// Discovers skills across `workspaces`, `home`, OpenIDEA IDE-plugin skill folders (`plugin_skill_dirs`),
/// and resolved agent plugin bundle roots (`agent_plugin_roots`).
pub fn discover_skills_with_agent_plugins(
workspaces: &[PathBuf],
home: Option<&Path>,
plugin_skill_dirs: &[PathBuf],
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
) -> Vec<AgentSkill> {
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();
@@ -306,6 +339,13 @@ pub fn discover_skills_with_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)));
}
@@ -338,9 +378,19 @@ pub fn discover_skills_with_plugins(
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
push_skill(parse_skill_file(dir, &folder, &text, AgentSkillSource::Plugin));
}
if let Some(home) = home {
for (root, source) in copilot_installed_plugin_roots(&home.join(".copilot")) {
for skill in skills_of(&root, source) {
for proj in agent_plugin_roots {
if proj.dir.join("SKILL.md").is_file() && proj.dir.file_name().and_then(|s| s.to_str()) != Some("skills") {
let Some(folder) = file_name(&proj.dir) else { continue };
if let Ok(text) = std::fs::read_to_string(proj.dir.join("SKILL.md")) {
let mut skill = parse_skill_file(&proj.dir, &folder, &text, proj.source);
skill.plugin_id = Some(proj.plugin_id.clone());
skill.plugin_name = Some(proj.plugin_name.clone());
push_skill(skill);
}
} else {
for mut skill in skills_of(&proj.dir, proj.source) {
skill.plugin_id = Some(proj.plugin_id.clone());
skill.plugin_name = Some(proj.plugin_name.clone());
push_skill(skill);
}
}
@@ -388,81 +438,72 @@ fn monorepo_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
out
}
/// Discovers skill roots inside `~/.copilot/installed-plugins`, supporting both Copilot CLI's
/// 2-level `<marketplace-or-_direct>/<plugin>` layout (and `config.json` `installedPlugins`
/// enablement) and flat 1-level `<plugin>` folders.
fn copilot_installed_plugin_roots(copilot_dir: &Path) -> Vec<(PathBuf, AgentSkillSource)> {
let mut disabled_paths: HashSet<PathBuf> = HashSet::new();
let mut plugin_dirs: Vec<PathBuf> = Vec::new();
let mut seen_dirs: HashSet<PathBuf> = HashSet::new();
let mut push_plugin = |dir: PathBuf, disabled: &HashSet<PathBuf>| {
if !dir.is_dir() {
return;
}
let canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
if disabled.contains(&canon) || !seen_dirs.insert(canon) {
return;
}
plugin_dirs.push(dir);
};
if let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json"))
&& let Ok(root) = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text))
&& let Some(installed) = root.get("installedPlugins").and_then(serde_json::Value::as_array)
{
for entry in installed {
let Some(raw_cache) = entry.get("cache_path").and_then(serde_json::Value::as_str).map(str::trim) else {
continue;
};
if raw_cache.is_empty() {
continue;
}
let dir =
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
if entry.get("enabled").and_then(serde_json::Value::as_bool) == Some(false) {
disabled_paths.insert(dunce::canonicalize(&dir).unwrap_or(dir));
} else {
push_plugin(dir, &disabled_paths);
}
}
/// 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 plugins_root = copilot_dir.join("installed-plugins");
for entry in sorted(&plugins_root) {
if !entry.is_dir() {
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 looks_like_plugin_dir(&entry) {
push_plugin(entry, &disabled_paths);
} else {
// 2-level `<marketplace>/<plugin>` or `_direct/<plugin>`.
for sub in sorted(&entry) {
if sub.is_dir() {
push_plugin(sub, &disabled_paths);
}
}
if !pkg_root.is_dir() {
continue;
}
candidates.push((rel.components().count(), pkg_root));
}
let mut roots = Vec::new();
for plugin in plugin_dirs {
let skills_sub = plugin.join("skills");
if skills_sub.is_dir() {
roots.push((skills_sub, AgentSkillSource::CopilotUser));
} else {
roots.push((plugin, AgentSkillSource::CopilotUser));
}
}
roots
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()
}
fn looks_like_plugin_dir(dir: &Path) -> bool {
dir.join("skills").is_dir()
|| dir.join("plugin.json").is_file()
|| dir.join(".plugin").is_dir()
|| dir.join(".claude-plugin").is_dir()
|| dir.join(".cursor-plugin").is_dir()
|| dir.join("SKILL.md").is_file()
/// 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`
@@ -544,6 +585,8 @@ fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSour
paths,
valid: warnings.is_empty(),
warnings,
plugin_id: None,
plugin_name: None,
}
}
@@ -1070,6 +1113,8 @@ mod tests {
paths: Vec::new(),
valid: true,
warnings: Vec::new(),
plugin_id: None,
plugin_name: None,
}
}
@@ -1517,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");
}
}
+683 -7
Переглянути файл
@@ -65,10 +65,16 @@ struct FakeAgent {
mcp_calls: Mutex<Vec<(String, Vec<String>)>>,
/// The params of every `session/fork`, in order.
forks: Mutex<Vec<Value>>,
/// Cuts a fork at `_meta.openidea.forkTurns` itself, as the native agents do.
cuts_forks: bool,
/// The content blocks of each `session/prompt`.
prompts: Mutex<Vec<Value>>,
/// Queued errors returned on the next `session/prompt` calls before succeeding.
prompt_errors: Mutex<VecDeque<(i64, String)>>,
/// Number of prompts that stream Cursor's capacity diagnostic before returning end_turn.
capacity_errors: Mutex<u32>,
/// Queued errors returned on the next session-open calls before succeeding.
open_errors: Mutex<VecDeque<(i64, String, Option<Value>)>>,
/// Recorded `(method, _meta.openidea.memory)` payloads across `session/new`, `session/load`, and `session/fork`.
memory_calls: Mutex<Vec<(String, Option<Value>)>>,
}
@@ -150,6 +156,12 @@ impl Handler for FakeAgent {
let data = json!({"openidea": {"usageLimit": {"resetsAtMs": 1234.0}}});
return Err((codes::INTERNAL_ERROR, "You've hit your usage limit".into(), Some(data)));
}
if matches!(method, "session/new" | "session/load" | "session/fork")
&& let Some(err) = self.open_errors.lock().pop_front()
{
self.calls.lock().push(method.to_owned());
return Err(err);
}
self.on_request(method, params).map_err(|(code, message)| (code, message, None))
}
@@ -220,7 +232,13 @@ impl Handler for FakeAgent {
"session/fork" => {
self.forks.lock().push(params.clone());
let requested = params.pointer("/_meta/openidea/forkSessionId").and_then(Value::as_str);
Ok(json!({ "sessionId": requested.unwrap_or("s2") }))
let mut reply = json!({ "sessionId": requested.unwrap_or("s2") });
if self.cuts_forks
&& let Some(turns) = params.pointer("/_meta/openidea/forkTurns")
{
reply["_meta"] = json!({ "openidea": { "forkTurns": turns } });
}
Ok(reply)
}
"_openidea/stop_task" => {
self.calls.lock().push(format!("{method} {}", params["taskId"]));
@@ -289,6 +307,22 @@ impl Handler for FakeAgent {
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
{
let mut remaining = self.capacity_errors.lock();
if *remaining > 0 {
*remaining -= 1;
if text == "edit once" {
self.update(
&session,
json!({"sessionUpdate": "tool_call", "toolCallId": "edit",
"title": "Edit file", "kind": "edit", "status": "completed"}),
);
}
self.say(&session, "\n\nError: RetriableError: ");
self.say(&session, "[resource_exhausted] Error");
return Ok(json!({"stopReason": "end_turn"}));
}
}
if text.starts_with("The previous turn was interrupted because ") {
self.say(&session, "resumed cleanly");
return Ok(json!({"stopReason": "end_turn"}));
@@ -426,6 +460,28 @@ impl Handler for FakeAgent {
self.say(&session, &format!("form {answer}"));
return Ok(json!({ "stopReason": "end_turn" }));
}
if text == "question form" {
// claude-agent-acp's `AskUserQuestion`, sent as a form.
let peer = self.latest();
let answer: Value = tokio::runtime::Handle::current()
.block_on(peer.request(
"elicitation/create",
json!({"sessionId": session, "mode": "form",
"message": "Please answer the following questions.",
"requestedSchema": {"type": "object", "properties": {
"question_0": {"type": "string", "title": "Layout", "description": "Which layout?",
"oneOf": [{"const": "List", "title": "List"}, {"const": "Grid", "title": "Grid"}]},
"question_0_custom": {"type": "string", "title": "Other"},
"question_1": {"type": "array", "title": "Checks", "description": "Which checks?",
"items": {"anyOf": [{"const": "Disk", "title": "Disk"},
{"const": "GPU", "title": "GPU"}]}},
"question_1_custom": {"type": "string", "title": "Other"}}}}),
None,
))
.unwrap();
self.say(&session, &format!("form {answer}"));
return Ok(json!({ "stopReason": "end_turn" }));
}
if text == "ask" {
let peer = self.latest();
let answer: Value = tokio::runtime::Handle::current()
@@ -626,6 +682,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.
@@ -2191,6 +2248,210 @@ async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_ag
assert_eq!(calls(&agent), ["session/load", "session/new", "session/prompt"]);
}
/// A locked Codex recording can be forked without resuming it or moving its writer between tasks.
#[tokio::test(flavor = "multi_thread")]
async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
let tmp = tempfile::tempdir().unwrap();
let task = {
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "codex".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.shutdown();
task
};
let agent = Arc::new(FakeAgent {
load_error: Some((codes::INVALID_PARAMS, "thread s1 already has an active writer".into())),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
for _ in 0..2 {
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
}
assert!(!agent.calls.lock().iter().any(|c| c == "session/new"));
let copy = mgr.fork(&task.id, None).await.unwrap();
assert_eq!(agent.forks.lock().last().unwrap()["sessionId"], "s1");
let copy_handle = mgr.task(&copy.id).unwrap();
assert_eq!(copy_handle.live.lock().as_ref().unwrap().session, "s2");
let loads = agent.calls.lock().iter().filter(|c| *c == "session/load").count();
mgr.prompt(&copy.id, text("again"), false).await.unwrap();
wait_for(&mgr, &copy.id, AgentStatus::Ready).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/load").count(), loads);
mgr.shutdown();
}
fn warming_up_error() -> (i64, String, Option<Value>) {
(
codes::INTERNAL_ERROR,
"Internal error: Internal service failure".to_owned(),
Some(json!({"errorName": "ServiceUnavailableError"})),
)
}
#[tokio::test(flavor = "multi_thread")]
async fn session_open_retries_while_the_agent_finishes_starting_up() {
// OpenCode rejects session opens until its plugins and MCP servers finish activating.
let tmp = tempfile::tempdir().unwrap();
let agent =
Arc::new(FakeAgent { open_errors: Mutex::new(VecDeque::from([warming_up_error()])), ..Default::default() });
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/new").count(), 2, "retried the startup race");
let saved = mgr.task(&task.id).unwrap().state.lock().session_id.clone().expect("a session");
mgr.shutdown();
// The same race when reopening a saved session.
let agent =
Arc::new(FakeAgent { open_errors: Mutex::new(VecDeque::from([warming_up_error()])), ..Default::default() });
let mgr = manager(tmp.path(), agent.clone());
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/load").count(), 2, "retried the startup race");
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some(saved.as_str()));
mgr.shutdown();
}
async fn wait_for_session_open_attempts(agent: &FakeAgent, method: &str, attempts: usize) {
tokio::time::timeout(Duration::from_secs(5), async {
while agent.calls.lock().iter().filter(|call| call.as_str() == method).count() < attempts {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("agent received the session-open requests");
}
#[tokio::test]
async fn retry_after_warmup_expires_loads_the_saved_session_again() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let saved = mgr.task(&task.id).unwrap().state.lock().session_id.clone().unwrap();
mgr.shutdown();
let agent = Arc::new(FakeAgent {
open_errors: Mutex::new(std::iter::repeat_with(warming_up_error).take(16).collect()),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for_session_open_attempts(&agent, "session/load", 2).await;
tokio::time::pause();
tokio::time::advance(WARMUP_WINDOW - WARMUP_DELAY * 2).await;
tokio::time::resume();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
assert!(mgr.entries(&task.id, None).unwrap().iter().any(|entry| matches!(
entry, AgentEntry::Error { message } if message.contains("Try again") && !message.contains("new session")
)));
agent.open_errors.lock().clear();
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert!(!agent.calls.lock().iter().any(|call| call == "session/new"));
let handle = mgr.task(&task.id).unwrap();
assert_eq!(handle.live.lock().as_ref().unwrap().session, saved);
mgr.shutdown();
}
#[tokio::test]
async fn a_stalled_warmup_retry_times_out_and_closes_the_connection() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent {
open_errors: Mutex::new(VecDeque::from([warming_up_error()])),
hold_session_new: AtomicBool::new(true),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for_session_open_attempts(&agent, "session/new", 2).await;
tokio::time::pause();
tokio::time::advance(WARMUP_WINDOW).await;
tokio::time::resume();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
assert!(mgr.entries(&task.id, None).unwrap().iter().any(|entry| matches!(
entry, AgentEntry::Error { message } if message.contains("timed out")
)));
tokio::time::timeout(Duration::from_secs(5), agent.latest().closed())
.await
.expect("the timed-out connection closes");
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn session_open_authenticates_after_a_warmup_reply() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent {
open_errors: Mutex::new(VecDeque::from([warming_up_error()])),
auth_on_new: true,
authenticate_method: Some("agent_login".into()),
auth_methods: vec![json!({"id": "agent_login", "name": "Sign in"})],
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let calls = agent.calls.lock();
let setup: Vec<_> = calls
.iter()
.map(String::as_str)
.filter(|call| call.starts_with("session/") || call.starts_with("authenticate"))
.collect();
assert_eq!(
setup,
["session/new", "session/new", "authenticate", "authenticate agent_login", "session/new", "session/prompt"]
);
drop(calls);
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn session_open_does_not_retry_unrelated_internal_errors() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent {
open_errors: Mutex::new(VecDeque::from([(
codes::INTERNAL_ERROR,
"Internal error: Internal service failure".into(),
Some(json!({"errorName": "SQLiteError"})),
)])),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/new").count(), 1, "no retry on a real failure");
mgr.shutdown();
}
fn text(t: &str) -> AgentPrompt {
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
}
@@ -2571,7 +2832,12 @@ async fn subagents_get_their_own_conversation() {
#[test]
fn image_blocks_declare_the_type_of_their_bytes() {
let image = |mime: &str, data: &str| AgentImage { mime_type: mime.into(), data: data.into(), name: None };
let image = |mime: &str, data: &str| AgentImage {
mime_type: mime.into(),
data: data.into(),
name: None,
inline_number: None,
};
let cases = [
// A browser's JPEG pasted as PNG.
(image("image/png", "/9j/4AAQSkZJRgABAQ"), "image/jpeg"),
@@ -2593,7 +2859,7 @@ fn prompts_become_acp_content_blocks() {
let p = AgentPrompt {
text: "look".into(),
files: vec![IpcPath(PathBuf::from("/p/my file.rs"))],
images: vec![AgentImage { mime_type: "image/png".into(), data: "AAA".into(), name: None }],
images: vec![AgentImage { mime_type: "image/png".into(), data: "AAA".into(), name: None, inline_number: None }],
};
assert_eq!(
blocks(&p, &[]),
@@ -2625,6 +2891,32 @@ fn prompts_become_acp_content_blocks() {
assert!(clean(text(" ")).is_none());
}
#[test]
fn inline_images_are_distinct_content_blocks_in_text_order() {
let older: AgentImage = serde_json::from_value(json!({"mimeType":"image/png", "data":"AAA", "name":null})).unwrap();
assert!(older.inline_number.is_none());
let image = |number, data: &str| AgentImage {
mime_type: "image/png".into(),
data: data.into(),
name: None,
inline_number: Some(number),
};
let prompt = AgentPrompt {
text: "😀 [Image #2] then [Image #1] and [Image #99]".into(),
images: vec![image(1, "AAA"), image(2, "BBB"), image(3, "CCC")],
..Default::default()
};
let content = blocks(&prompt, &[]);
assert_eq!(content.len(), 5);
assert_eq!(content[0], json!({"type": "text", "text": "😀 "}));
assert_eq!(content[1]["type"], "image");
assert_eq!(content[1]["data"], "BBB");
assert_eq!(content[2], json!({"type": "text", "text": " then "}));
assert_eq!(content[3]["type"], "image");
assert_eq!(content[3]["data"], "AAA");
assert_eq!(content[4], json!({"type": "text", "text": " and [Image #99]"}));
}
#[tokio::test(flavor = "multi_thread")]
async fn claude_questions_keep_the_answer_object_as_the_option_id() {
let tmp = tempfile::tempdir().unwrap();
@@ -2854,6 +3146,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,
@@ -3197,6 +3490,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();
@@ -3241,6 +3590,131 @@ fn plant_codex_session(root: &Path, session_id: &str) {
.unwrap();
}
/// Plants a recorded Copilot session below the test home.
fn plant_copilot_session(root: &Path, session_id: &str) {
let dir = root.join(".copilot").join("session-state").join(session_id);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("workspace.yaml"),
format!("id: {session_id}\ncwd: {}\nname: Fix the Copilot parser\n", root.to_string_lossy()),
)
.unwrap();
std::fs::write(
dir.join("events.jsonl"),
format!(
"{}\n",
json!({
"type": "user.message",
"data": {"content": "fix the Copilot parser"}
})
),
)
.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn imports_copilot_sessions_and_loads_their_history() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
plant_copilot_session(tmp.path(), NATIVE_SOURCE);
let sessions = mgr.external_sessions();
assert!(sessions.iter().any(|session| session.provider == "copilot" && session.session_id == NATIVE_SOURCE));
let task = mgr.import_session("copilot", NATIVE_SOURCE).unwrap();
assert_eq!(task.provider, "copilot");
for _ in 0..200 {
if agent.calls.lock().iter().any(|call| call == "session/load")
&& mgr.entries(&task.id, None).unwrap().len() >= 2
{
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert!(agent.calls.lock().iter().any(|call| call == "session/load"));
assert!(
mgr.entries(&task.id, None)
.unwrap()
.iter()
.any(|entry| matches!(entry, AgentEntry::User { text, .. } if text == "earlier question"))
);
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();
@@ -3261,6 +3735,28 @@ async fn fork_session_uses_the_id_codex_assigns() {
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_uses_the_id_copilot_assigns() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
plant_copilot_session(tmp.path(), NATIVE_SOURCE);
let task = mgr.fork_session("copilot", NATIVE_SOURCE, tmp.path()).unwrap();
for _ in 0..200 {
if !agent.forks.lock().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let forks = agent.forks.lock().clone();
assert_eq!(forks.len(), 1);
assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE);
assert!(forks[0].pointer("/_meta/openidea/forkSessionId").is_none(), "copilot names its own fork");
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some("s2"));
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_rejects_invalid_input_before_starting() {
let tmp = tempfile::tempdir().unwrap();
@@ -3821,6 +4317,54 @@ async fn an_agent_form_is_answered_declined_or_cancelled_even_when_approvals_are
}
}
/// claude-agent-acp asks `AskUserQuestion` as a form: it is shown as the question card, one
/// question at a time, and the card's answers fill the form (#7359).
#[tokio::test(flavor = "multi_thread")]
async fn a_question_tool_form_is_asked_as_questions() {
let answers = json!({"question_0": ["Grid", "with thumbnails"], "question_1": ["Disk", "GPU"]}).to_string();
for (reply, said) in [
(
answers.as_str(),
r#"form {"action":"accept","content":{"question_0":"Grid","question_0_custom":"with thumbnails","question_1":["Disk","GPU"]}}"#,
),
("reject", r#"form {"action":"decline"}"#),
] {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("question form"),
provider: "cursor".into(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
let (id, questions) = mgr
.entries(&task.id, None)
.unwrap()
.into_iter()
.find_map(|entry| match entry {
AgentEntry::Permission { id, questions, form: None, chosen: None, .. } if !questions.is_empty() => {
Some((id, questions))
}
_ => None,
})
.unwrap();
let asked: Vec<_> =
questions.iter().map(|q| (q.answer_key.as_deref(), q.question.as_str(), q.multi_select)).collect();
assert_eq!(asked, [(Some("question_0"), "Which layout?", false), (Some("question_1"), "Which checks?", true)]);
mgr.respond(&task.id, id, Some(reply.to_owned())).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let entries = mgr.entries(&task.id, None).unwrap();
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == said)), "{entries:?}");
mgr.shutdown();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_approval_choice_applies_before_first_prompt() {
let tmp = tempfile::tempdir().unwrap();
@@ -4116,6 +4660,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,
@@ -4181,6 +4726,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,
@@ -4444,6 +4990,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,
@@ -4501,14 +5048,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")]
@@ -4773,7 +5327,7 @@ fn a_running_tools_output_is_sent_as_appends() {
// An image the tool returned is not part of the appended text: it goes with the whole entry.
let mut shown = titled.clone();
if let AgentEntry::Tool { images, output, .. } = &mut shown {
images.push(AgentImage { mime_type: "image/png".into(), data: "AAAA".into(), name: None });
images.push(AgentImage { mime_type: "image/png".into(), data: "AAAA".into(), name: None, inline_number: None });
output.as_mut().unwrap().push('!');
}
let imaged = event(&mut streamed, None, 2, &shown).unwrap();
@@ -5947,6 +6501,10 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
plugin_id: None,
plugin_name: None,
registry_name: None,
registry_url: None,
},
McpServer {
id: "user::slack".into(),
@@ -5961,6 +6519,10 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
plugin_id: None,
plugin_name: None,
registry_name: None,
registry_url: None,
},
]
}));
@@ -6267,6 +6829,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,
@@ -6390,6 +6953,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,
@@ -6872,6 +7436,85 @@ async fn transient_network_outage_probes_with_zero_prompts_and_auto_resumes_when
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_capacity_retry_pauses_after_three_continuations_and_resumes_on_request() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.capacity_errors.lock() = 4;
let mgr = manager(tmp.path(), agent.clone());
let _down = ShutDown(&mgr);
let task = mgr
.create(NewAgentTask { provider: "cursor".into(), prompt: text("edit once"), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let handle = mgr.task(&task.id).unwrap();
let snap = handle.state.lock().snapshot();
assert_eq!(snap.interrupted.unwrap().reason, InterruptionReason::CursorCapacity);
assert!(snap.retry.is_none());
let entries = mgr.entries(&task.id, None).unwrap();
let attempts: Vec<_> = entries
.iter()
.filter_map(|e| match e {
AgentEntry::User { retry_attempt, .. } => *retry_attempt,
_ => None,
})
.collect();
assert_eq!(attempts, [1, 2, 3]);
assert_eq!(entries.iter().filter(|e| matches!(e, AgentEntry::Tool { .. })).count(), 1);
assert_eq!(agent.prompts.lock().len(), 4);
mgr.resume(&task.id).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert!(handle.state.lock().task.interrupted.is_none());
assert_eq!(agent.prompts.lock().len(), 5);
assert!(
agent
.prompts
.lock()
.iter()
.skip(1)
.all(|p| p[0]["text"].as_str().unwrap().contains("Inspect the current workspace"))
);
assert!(
matches!(mgr.entries(&task.id, None).unwrap().last(), Some(AgentEntry::Agent { text }) if text == "resumed cleanly")
);
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_capacity_retry_can_be_stopped_or_replaced_during_backoff() {
for send_now in [false, true] {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.capacity_errors.lock() = 1;
let mgr = manager(tmp.path(), agent.clone());
let _down = ShutDown(&mgr);
let task = mgr
.create(NewAgentTask { provider: "cursor".into(), prompt: text("edit once"), ..Default::default() })
.await
.unwrap();
let handle = mgr.task(&task.id).unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
while handle.state.lock().task.retry.is_none() {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.unwrap();
let retry = handle.state.lock().task.retry.clone().unwrap();
assert_eq!((retry.attempt, retry.max_retries, retry.deadline_ms), (1, Some(3), None));
if !send_now {
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.prompts.lock().len(), 1);
assert!(handle.state.lock().task.retry.is_none());
}
mgr.prompt(&task.id, text("again"), send_now).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(agent.prompts.lock().len(), 2);
assert_eq!(agent.prompts.lock()[1][0]["text"], "again");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn network_outage_window_off_or_expired_degrades_to_interrupted_and_auth_errors_fail_fast() {
use ide_core::settings::{NetworkRetryWindow, ResumeInterruptedPolicy};
@@ -6928,3 +7571,36 @@ async fn network_outage_window_off_or_expired_degrades_to_interrupted_and_auth_e
mgr2.shutdown();
mgr3.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn metadata_edits_do_not_bump_updated_ms() {
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;
let handle = mgr.task(&task.id).unwrap();
let fixed_ms = 1_234.0;
handle.state.lock().task.updated_ms = fixed_ms;
mgr.rename(&task.id, "Custom Title").unwrap();
assert_eq!(handle.state.lock().task.updated_ms, fixed_ms);
let after_mcp = mgr.set_mcp_overrides(&task.id, BTreeMap::from([("github".into(), false)])).unwrap();
assert_eq!(after_mcp.updated_ms, fixed_ms);
let after_skill =
mgr.set_skill_overrides(&task.id, BTreeMap::from([("triage".into(), AgentSkillMode::Off)])).unwrap();
assert_eq!(after_skill.updated_ms, fixed_ms);
let after_memory = mgr
.set_memory_overrides(
&task.id,
AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off), entries: BTreeMap::new() },
)
.unwrap();
assert_eq!(after_memory.updated_ms, fixed_ms);
}
+3 -1
Переглянути файл
@@ -523,7 +523,7 @@ mod tests {
t.apply(&update);
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "status": "completed"}));
let AgentEntry::Tool { images, output, status, .. } = &t.entries[0] else { panic!() };
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None }]);
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None, inline_number: None }]);
assert!(output.as_ref().unwrap().len() < MAX_OUTPUT + 100);
assert_eq!(*status, AgentToolStatus::Completed);
let saved = serde_json::to_string(&t.entries[0]).unwrap();
@@ -646,6 +646,7 @@ mod tests {
done_ms: None,
steered: false,
recovery: None,
retry_attempt: None,
};
let mut t = Timeline::default();
t.push(user(1.0));
@@ -668,6 +669,7 @@ mod tests {
done_ms: None,
steered,
recovery: None,
retry_attempt: None,
};
let mut t = Timeline::default();
t.push(user(1.0, false));
+377 -7
Переглянути файл
@@ -9,12 +9,34 @@ use std::path::{Path, PathBuf};
use std::time::{Duration, UNIX_EPOCH};
pub(crate) struct Created {
#[cfg_attr(not(test), allow(dead_code))]
pub path: PathBuf,
pub cwd: PathBuf,
pub branch: String,
pub base: String,
pub base_commit: String,
}
const OWNERSHIP_MARKER: &str = "openidea-worktree.json";
const OWNERSHIP_TAG: &str = "openidea-agent";
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct WorktreeOwnership {
owner: String,
task_id: String,
worktree_root: PathBuf,
repo_root: PathBuf,
}
/// Returns the canonical root of the Git repository containing `project_root`, if any.
pub fn canonical_repo_root(project_root: &Path) -> IdeResult<Option<PathBuf>> {
match Repo::discover(project_root)? {
Some(repo) => Ok(Some(dunce::canonicalize(repo.root())?)),
None => Ok(None),
}
}
/// The repository of `path`, free to execute: the host runs every agent command that
/// reaches a repository only in a trusted project.
fn discover(path: &Path) -> IdeResult<Option<Repo>> {
@@ -157,9 +179,38 @@ pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
}
}
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
#[cfg(test)]
pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, base: Option<&str>) -> IdeResult<Created> {
create_for_task(project_root, worktrees_dir, "", title, base)
}
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
/// Records an ownership marker in the linked worktree's private `git_dir` and preserves any
/// project-relative subdirectory inside `project_root` when `project_root` is below `repo.root()`.
pub(crate) fn create_for_task(
project_root: &Path,
worktrees_dir: &Path,
task_id: &str,
title: &str,
base: Option<&str>,
) -> IdeResult<Created> {
let repo = repo_at(project_root)?;
let canon_repo = dunce::canonicalize(repo.root())?;
let canon_proj = dunce::canonicalize(project_root)?;
let rel_subdir = if canon_proj != canon_repo {
canon_proj
.strip_prefix(&canon_repo)
.map_err(|_| {
IdeError::invalid(format!(
"{} is outside git repository {}",
canon_proj.display(),
canon_repo.display()
))
})?
.to_path_buf()
} else {
PathBuf::new()
};
let (base, base_commit) = match base.map(str::trim).filter(|b| !b.is_empty()) {
Some(b) => {
let commit =
@@ -177,7 +228,125 @@ pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, bas
let path = worktrees_dir.join(&slug);
let branch = format!("agent/{slug}");
repo.add_worktree(&path, &base_commit, Some(&branch))?;
Ok(Created { path, branch, base, base_commit })
let canon_wt = match dunce::canonicalize(&path) {
Ok(p) => p,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e.into());
}
};
let wt_repo = match repo_at(&canon_wt) {
Ok(r) => r,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
};
let [git_dir, common_dir] = match wt_repo.metadata_dirs() {
Ok(dirs) => dirs,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
};
if dunce::canonicalize(&git_dir).ok() == dunce::canonicalize(&common_dir).ok() {
let _ = repo.remove_worktree(&path, false);
return Err(IdeError::internal("linked worktree did not receive a separate git metadata directory"));
}
let marker = WorktreeOwnership {
owner: OWNERSHIP_TAG.to_owned(),
task_id: task_id.to_owned(),
worktree_root: canon_wt.clone(),
repo_root: canon_repo,
};
if let Err(e) = serde_json::to_vec_pretty(&marker)
.map_err(|e| IdeError::internal(e.to_string()))
.and_then(|bytes| ide_vfs::write_atomic(&git_dir.join(OWNERSHIP_MARKER), &bytes))
{
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
let raw_cwd = if rel_subdir.as_os_str().is_empty() { canon_wt.clone() } else { canon_wt.join(&rel_subdir) };
if !raw_cwd.is_dir() {
let _ = repo.remove_worktree(&path, false);
return Err(IdeError::invalid(format!(
"project folder {} does not exist in base revision {}",
rel_subdir.display(),
base
)));
}
let canon_cwd = match verify_confined_worktree_subdir(&canon_wt, &raw_cwd) {
Ok(c) => c,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
};
Ok(Created { path, cwd: canon_cwd, branch, base, base_commit })
}
fn verify_confined_worktree_subdir(canon_wt_root: &Path, target_cwd: &Path) -> IdeResult<PathBuf> {
let canon_cwd = dunce::canonicalize(target_cwd)?;
let real_wt = ide_core::real_path::resolve_real(canon_wt_root);
let real_cwd = ide_core::real_path::resolve_real(target_cwd);
if !canon_cwd.starts_with(canon_wt_root)
|| !real_cwd.starts_with(&real_wt)
|| ide_core::real_path::reaches_git_dir(&real_wt, &real_cwd)
{
return Err(IdeError::invalid(format!(
"worktree working directory {} resolves outside worktree {}",
target_cwd.display(),
canon_wt_root.display()
)));
}
Ok(canon_cwd)
}
/// Canonicalizes `cwd` of an existing `Isolation::Worktree` task and verifies that it still
/// resolves strictly inside its own worktree checkout root under `worktrees_dir` (preventing
/// symlink escapes on reused sessions/turns).
pub(crate) fn verify_confined_worktree_cwd(worktrees_dir: &Path, cwd: &Path) -> IdeResult<PathBuf> {
let (wt_root, wt_base) = worktree_checkout_root(worktrees_dir, cwd);
if !wt_root.starts_with(&wt_base) || wt_root == wt_base {
return Err(IdeError::invalid(format!(
"worktree working directory {} is outside managed worktrees directory {}",
cwd.display(),
worktrees_dir.display()
)));
}
let canon_wt_root = dunce::canonicalize(&wt_root)?;
let canon_wt_dir = dunce::canonicalize(worktrees_dir)?;
if !canon_wt_root.starts_with(&canon_wt_dir)
|| canon_wt_root == canon_wt_dir
|| canon_wt_root.parent() != Some(canon_wt_dir.as_path())
{
return Err(IdeError::invalid("worktree checkout root escaped managed worktrees directory"));
}
verify_confined_worktree_subdir(&canon_wt_root, cwd)
}
fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) {
if let Ok(rel) = path.strip_prefix(worktrees_dir)
&& let Some(first) = rel.components().next()
{
return (worktrees_dir.join(first), worktrees_dir.to_path_buf());
}
if let Ok(canon_wt_dir) = dunce::canonicalize(worktrees_dir) {
if let Ok(rel) = path.strip_prefix(&canon_wt_dir)
&& let Some(first) = rel.components().next()
{
return (canon_wt_dir.join(first), canon_wt_dir);
}
if let Ok(canon_path) = dunce::canonicalize(path)
&& let Ok(rel) = canon_path.strip_prefix(&canon_wt_dir)
&& let Some(first) = rel.components().next()
{
return (canon_wt_dir.join(first), canon_wt_dir);
}
}
(path.to_path_buf(), worktrees_dir.to_path_buf())
}
/// `git worktree remove --force -- <path>`. When git no longer recognizes the
@@ -186,19 +355,94 @@ pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, bas
/// ours, so it is removed directly to keep the task deletable (a stale
/// registration prunes later); anything else keeps git's error.
pub(crate) fn remove(project_root: &Path, worktrees_dir: &Path, path: &Path) -> IdeResult<()> {
let (target, wt_base) = worktree_checkout_root(worktrees_dir, path);
let repo = repo_at(project_root)?;
let err = match repo.remove_worktree(path, true) {
let err = match repo.remove_worktree(&target, true) {
Ok(()) => return Ok(()),
Err(e) => e,
};
if !path.exists() {
if !target.exists() {
return Ok(());
}
if !path.starts_with(worktrees_dir) || path == worktrees_dir {
if !target.starts_with(&wt_base) || target == wt_base {
return Err(err);
}
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(path))
.map_err(|e| IdeError::internal(format!("{}: {e}", path.display())))
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(&target))
.map_err(|e| IdeError::internal(format!("{}: {e}", target.display())))
}
/// Safely removes an automation worktree ONLY after verifying its private `git_dir` ownership
/// marker (`openidea-worktree.json`) matches `task_id` and `worktrees_dir`.
///
/// - When `require_clean` is `true` (zero-diff GC): verifies `HEAD == base_commit` and both the
/// Git index (staged) and working tree (unstaged + untracked) are completely clean right before
/// running **non-forced** `git worktree remove` (`force = false`). Returns `Ok(false)` without
/// modifying disk if the worktree has any commits, staged changes, unstaged edits, or untracked
/// files.
/// - Never falls back to `remove_dir_all` on any ownership or Git error: any error keeps the
/// checkout intact.
pub(crate) fn remove_owned_automation_worktree(
project_root: &Path,
worktrees_dir: &Path,
cwd: &Path,
task_id: &str,
base_commit: Option<&str>,
require_clean: bool,
) -> IdeResult<bool> {
if !cwd.exists() || !worktrees_dir.exists() {
return Ok(false);
}
let canon_worktrees = dunce::canonicalize(worktrees_dir)?;
let canon_cwd = dunce::canonicalize(cwd)?;
if !canon_cwd.starts_with(&canon_worktrees) || canon_cwd == canon_worktrees {
return Err(IdeError::invalid("refusing to clean worktree outside managed worktrees directory"));
}
let main_repo = repo_at(project_root)?;
let wt_repo = repo_at(&canon_cwd)?;
let canon_wt_root = dunce::canonicalize(wt_repo.root())?;
if !canon_wt_root.starts_with(&canon_worktrees)
|| canon_wt_root == canon_worktrees
|| canon_wt_root.parent() != Some(canon_worktrees.as_path())
{
return Err(IdeError::invalid("worktree root does not match managed worktrees directory"));
}
let [git_dir, wt_common] = wt_repo.metadata_dirs()?;
let [_, main_common] = main_repo.metadata_dirs()?;
let canon_git_dir = dunce::canonicalize(&git_dir)?;
let canon_wt_common = dunce::canonicalize(&wt_common)?;
let canon_main_common = dunce::canonicalize(&main_common)?;
if canon_git_dir == canon_wt_common || canon_wt_common != canon_main_common {
return Err(IdeError::invalid("target checkout is not a linked worktree of this repository"));
}
let marker_bytes = std::fs::read(canon_git_dir.join(OWNERSHIP_MARKER))
.map_err(|_| IdeError::invalid("refusing to remove worktree without OpenIDEA ownership marker"))?;
let marker: WorktreeOwnership = serde_json::from_slice(&marker_bytes)
.map_err(|_| IdeError::invalid("corrupt OpenIDEA worktree ownership marker"))?;
let marker_root = dunce::canonicalize(&marker.worktree_root).unwrap_or(marker.worktree_root);
if marker.owner != OWNERSHIP_TAG || marker.task_id != task_id || marker_root != canon_wt_root {
return Err(IdeError::invalid("worktree ownership marker does not match task"));
}
if require_clean {
let Some(base) = base_commit else {
return Ok(false);
};
if wt_repo.head()?.1.as_deref() != Some(base) {
return Ok(false);
}
// `status()` checks BOTH HEAD↔index (staged) and index↔worktree (unstaged + untracked).
if !wt_repo.status()?.is_empty() {
return Ok(false);
}
if !wt_repo.diff_with_worktree(base)?.is_empty() {
return Ok(false);
}
main_repo.remove_worktree(&canon_wt_root, false)?;
return Ok(true);
}
main_repo.remove_worktree(&canon_wt_root, true)?;
Ok(true)
}
/// On Windows a folder can't be deleted while a process still has a file in it open
@@ -1944,4 +2188,130 @@ mod tests {
changed.sort();
assert_eq!(changed, ["edited", "new", "reverted"]);
}
#[test]
fn owned_worktree_cleanup_preserves_subproject_cwd_catches_staged_changes_and_verifies_ownership() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
let sub = repo.join("packages").join("subapp");
std::fs::create_dir_all(&sub).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
git(&repo, &["config", "core.autocrlf", "false"]);
std::fs::write(repo.join("root.txt"), "root\n").unwrap();
std::fs::write(sub.join("index.ts"), "export const x = 1;\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
let wt_dir = tmp.path().join("wt");
let created = create_for_task(&sub, &wt_dir, "task-1", "Sub Audit", None).unwrap();
assert_eq!(
dunce::canonicalize(&created.cwd).unwrap(),
dunce::canonicalize(&created.path).unwrap().join("packages").join("subapp"),
"project-relative cwd inside parent repo must be preserved inside worktree"
);
// Wrong task_id is refused and keeps the checkout untouched.
assert!(
remove_owned_automation_worktree(
&sub,
&wt_dir,
&created.cwd,
"wrong-task",
Some(&created.base_commit),
true,
)
.is_err()
);
assert!(created.path.exists());
// Staged-only change (index differs from HEAD while working tree matches HEAD!) is NOT clean!
std::fs::write(created.cwd.join("index.ts"), "export const x = 2;\n").unwrap();
git(&created.path, &["add", "packages/subapp/index.ts"]);
std::fs::write(created.cwd.join("index.ts"), "export const x = 1;\n").unwrap();
let removed_staged =
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
.unwrap();
assert!(!removed_staged, "staged-only index change must prevent zero-diff worktree GC");
assert!(created.path.exists());
// Reset index back to HEAD -> zero-diff GC removes the worktree via non-forced `git worktree remove`.
git(&created.path, &["reset", "-q", "HEAD", "--", "packages/subapp/index.ts"]);
let removed_clean =
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
.unwrap();
assert!(removed_clean);
assert!(!created.path.exists());
// Foreign / manually created git worktree inside `wt_dir` without ownership marker is NEVER deleted.
let manual_wt = wt_dir.join("foreign");
git(&repo, &["worktree", "add", "-q", "-b", "manual-branch", manual_wt.to_str().unwrap(), "HEAD"]);
assert!(
remove_owned_automation_worktree(&repo, &wt_dir, &manual_wt, "task-2", Some(&created.base_commit), false,)
.is_err()
);
assert!(manual_wt.exists(), "worktree without OpenIDEA ownership marker must never be deleted");
}
#[cfg(unix)]
#[test]
fn symlinked_subproject_cwd_escaping_worktree_is_rejected_on_create_and_reuse() {
let tmp = tempfile::tempdir().unwrap();
let outside = tmp.path().join("outside");
std::fs::create_dir_all(&outside).unwrap();
std::fs::write(outside.join("secret.txt"), "nope\n").unwrap();
let repo = tmp.path().join("repo");
let packages = repo.join("packages");
std::fs::create_dir_all(&packages).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
git(&repo, &["config", "core.autocrlf", "false"]);
// 1a. Direct symlink pointing outside git is rejected immediately.
let escape_link = packages.join("escape");
std::os::unix::fs::symlink(&outside, &escape_link).unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "symlink escape"]);
let wt_dir = tmp.path().join("wt");
assert!(create_for_task(&escape_link, &wt_dir, "task-escape-direct", "Escape", None).is_err());
// 1b. Committed symlink in `HEAD` (`packages/tricky -> ../../outside`) while the main
// checkout temporarily has a real directory at `packages/tricky`: `git worktree add`
// checks out `HEAD`'s symlink inside the worktree, and `verify_confined_worktree_subdir`
// must catch the escape and clean up the worktree!
let tricky = packages.join("tricky");
std::os::unix::fs::symlink(&outside, &tricky).unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "committed tricky symlink"]);
std::fs::remove_file(&tricky).unwrap();
std::fs::create_dir_all(&tricky).unwrap();
let Err(err) = create_for_task(&tricky, &wt_dir, "task-escape-head", "Tricky", None) else {
panic!("expected committed symlink escaping worktree root to be rejected");
};
assert!(
err.to_string().contains("outside worktree") || err.to_string().contains("escapes worktree root"),
"unexpected error for committed symlink cwd: {err}"
);
// 2. Normal directory at creation time, later replaced with an escaping symlink before reuse,
// must be rejected by `verify_confined_worktree_cwd`!
let legit_sub = packages.join("legit");
std::fs::create_dir_all(&legit_sub).unwrap();
std::fs::write(legit_sub.join("ok.txt"), "ok\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "legit sub"]);
let created = create_for_task(&legit_sub, &wt_dir, "task-reuse", "Legit", None).unwrap();
let verified = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap();
assert!(verified.starts_with(dunce::canonicalize(&created.path).unwrap()));
std::fs::remove_dir_all(&created.cwd).unwrap();
std::os::unix::fs::symlink(&outside, &created.cwd).unwrap();
let reuse_err = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap_err();
assert!(
reuse_err.to_string().contains("outside worktree") || reuse_err.to_string().contains("escapes"),
"symlink swap on worktree reuse must be rejected: {reuse_err}"
);
}
}
+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"}}
+24
Переглянути файл
@@ -0,0 +1,24 @@
{
"version": 2,
"plugins": {
"evidence-plugin@evidence-mkt": [
{
"scope": "user",
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
"version": "1.2.3",
"installedAt": "2026-11-30T21:50:25.665Z",
"lastUpdated": "2026-11-30T21:50:25.665Z",
"gitCommitSha": "1111111111111111111111111111111111111111"
},
{
"scope": "project",
"projectPath": "$WORKSPACE",
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
"version": "1.2.3",
"installedAt": "2026-11-30T21:50:25.665Z",
"lastUpdated": "2026-11-30T21:50:25.665Z",
"gitCommitSha": "1111111111111111111111111111111111111111"
}
]
}
}
+6
Переглянути файл
@@ -0,0 +1,6 @@
[marketplaces.evidence-mkt]
source_type = "local"
source = "$HOME/.codex/.tmp/marketplaces/evidence-mkt"
[plugins."evidence-plugin@evidence-mkt"]
enabled = false
+19
Переглянути файл
@@ -0,0 +1,19 @@
// This file is managed automatically.
{
"installedPlugins": [
{
"name": "evidence-plugin",
"marketplace": "evidence-mkt",
"installed_at": "2026-11-30T21:50:25.665Z",
"enabled": true,
"version": "1.2.3",
"cache_path": "$HOME/.copilot/installed-plugins/evidence-mkt/evidence-plugin",
"source": {
"source": "github",
"repo": "acme/plugins",
"sha": "1111111111111111111111111111111111111111",
"path": "plugins/evidence-plugin"
}
}
]
}
+8
Переглянути файл
@@ -0,0 +1,8 @@
{
"evidence-extension": {
"overrides": [
"$HOME/*",
"!$WORKSPACE/*"
]
}
}
+1 -1
Переглянути файл
@@ -63,7 +63,7 @@ pub(crate) fn stream_batched<T>(
}
}
flush(&mut batch, on_batch);
Ok((lines.finish(cancel)?, stderr_tail))
Ok((lines.finish(cancel)?.success(), stderr_tail))
}
#[cfg(all(test, unix))]
+194 -32
Переглянути файл
@@ -17,12 +17,13 @@ pub use launch_resources::process_launch_resources;
pub use modules::record_module_build;
pub use single::{
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
has_gradle_file_target, javac_step, module_classpath, module_classpath_without_build, module_classpaths,
single_file_classpath, single_file_target,
has_gradle_file_target, javac_step, maven_system_classpath, module_classpath, module_classpath_without_build,
module_classpaths, single_file_classpath, single_file_target,
};
pub use structure::{
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
StructureBuildContext, StructureJdk, StructureRoots, artifact_file, artifact_output, language_release,
structure_build, structure_build_war, structure_compile_file_plan, structure_outputs, structure_plan,
structure_war_plan, structure_web_artifacts,
};
pub use tsc_watch::{tsc_watch, tsc_watch_roots};
pub use up_to_date::{menu_up_to_date, record_menu_build};
@@ -358,16 +359,14 @@ pub(super) fn maven_steps(
};
// The reactor root containing the module builds it with what it depends on (`-pl … -am`).
let rel = rel_str(root, module);
if !m.projects.iter().any(|p| p.dir == rel) {
let Some(target) = m.projects.iter().find(|p| p.dir == rel) else {
return Err(IdeError::not_found("no linked Maven project found for module"));
}
};
let top = maven_reactor(m, &rel).ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
let top_dir = subdir(root, &top.dir);
if module == top_dir {
return Ok(vec![step(top, &[])]);
if let Some(pl) = maven::module_selector(root, top, target) {
return Ok(vec![step(top, &["-pl".into(), pl, "-am".into()])]);
}
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or(rel);
Ok(vec![step(top, &["-pl".into(), pl, "-am".into()])])
Ok(vec![step(top, &[])])
}
fn gradle_steps(root: &Path, model: &BuildModel, kind: BuildKind, module: Option<&Path>) -> IdeResult<Vec<BuildStep>> {
@@ -421,13 +420,14 @@ fn cargo_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
}
/// CLion's Build Project for a CMake project: configures the build directory when it has no
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild), one job per
/// `CMakeCache.txt` or no File API reply yet, then `cmake --build` (`--clean-first` to rebuild), one job per
/// logical CPU unless the profile's build arguments choose a count. The directory and
/// options come from the CMake profile; without one, a configured directory of the project
/// (the first by name), else `build`, as the generated run configurations use.
fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> Vec<BuildStep> {
let build_dir = match profile {
Some(p) if !p.build_dir.trim().is_empty() => p.build_dir.trim().to_owned(),
Some(p) if p.build_type.is_empty() => "cmake-build-default".into(),
Some(p) => format!("cmake-build-{}", p.build_type.to_lowercase()),
None => {
let mut configured: Vec<String> = std::fs::read_dir(dir)
@@ -444,18 +444,49 @@ fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> V
let build_type = profile.map_or("Debug", |p| p.build_type.as_str());
let env = profile.map(|p| p.env.clone()).unwrap_or_default();
let mut steps = Vec::new();
if !dir.join(&build_dir).join("CMakeCache.txt").is_file() {
let mut configure = BuildStep::new("cmake", &["-S", ".", "-B", &build_dir], dir, Format::Gcc);
if let Some(p) = profile.filter(|p| !p.generator.trim().is_empty()) {
configure.args.extend(["-G".into(), p.generator.clone()]);
}
configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}"));
let preset = profile.and_then(|p| p.preset.as_ref());
// The profile's toolchain may bring its own cmake.
let cmake = profile.and_then(|p| p.cmake_program.as_ref()).map_or("cmake".into(), |c| c.to_string_lossy());
let cmake = cmake.as_ref();
let build_path = dir.join(&build_dir);
// Configured without the File API queries (by another tool, or before they were written):
// configure again so the targets, and their run configurations, become known.
let fresh = !build_path.join("CMakeCache.txt").is_file();
if fresh || !build_path.join(ide_core::cmake_file_api::REPLY).is_dir() {
// Best effort: without the queries the build still runs, only the targets stay unknown.
let _ = ide_core::cmake_file_api::write_queries(&build_path);
let mut configure = match preset {
// The preset sets the generator and cache variables.
Some(preset) => BuildStep::new(cmake, &["--preset", &preset.configure], dir, Format::Gcc),
None => {
let mut configure = BuildStep::new(cmake, &["-S", ".", "-B", &build_dir], dir, Format::Gcc);
// A configured directory keeps its generator (CMake refuses another one) and,
// without a profile, its build type.
if let Some(p) = profile.filter(|p| fresh && !p.generator.trim().is_empty()) {
configure.args.extend(["-G".into(), p.generator.clone()]);
}
if fresh || profile.is_some() {
configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}"));
}
configure
}
};
configure.args.push("-DCMAKE_EXPORT_COMPILE_COMMANDS=ON".into());
configure.args.extend(profile.map(|p| p.cmake_args.clone()).unwrap_or_default());
configure.env = env.clone();
steps.push(configure);
}
let mut build = BuildStep::new("cmake", &["--build", &build_dir, "--config", build_type], dir, Format::Gcc);
let mut build = match preset.and_then(|p| p.build.as_deref()) {
Some(build) => BuildStep::new(cmake, &["--build", "--preset", build], dir, Format::Gcc),
None => {
let mut build = BuildStep::new(cmake, &["--build", &build_dir], dir, Format::Gcc);
// CLion's "Default" build type: no configuration at all.
if !build_type.is_empty() {
build.args.extend(["--config".into(), build_type.into()]);
}
build
}
};
if kind == BuildKind::Rebuild {
build.args.push("--clean-first".into());
}
@@ -538,6 +569,27 @@ fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
Ok(vec![step])
}
/// `dotnet format` of a solution or C# / VB project file; `verify` only reports what it would
/// change and fails when there is anything.
pub fn dotnet_format_plan(file: &Path, verify: bool) -> IdeResult<BuildPlan> {
let ext = file.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
let (Some(dir), Some(name), true) =
(file.parent(), file.file_name(), matches!(ext.as_str(), "sln" | "slnx" | "csproj" | "vbproj"))
else {
return Err(IdeError::invalid("dotnet format needs a solution or a C# / VB project"));
};
if !file.is_file() {
return Err(IdeError::not_found(format!("{} does not exist", file.display())));
}
let name = name.to_string_lossy();
// Verbose output names the files it changed; verifying changes none.
let options: &[&str] = if verify { &["--verify-no-changes"] } else { &["--verbosity", "normal"] };
let mut step = BuildStep::new("dotnet", &["format", &name], dir, Format::Msbuild);
step.args.extend(options.iter().map(|o| (*o).to_owned()));
step.env.insert("MSBUILDTERMINALLOGGER".into(), "off".into());
Ok(BuildPlan { system: BuildSystem::Dotnet, title: format!("dotnet format {name}"), steps: vec![step] })
}
fn ts_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
let script = has_build_script(dir);
if script && (kind == BuildKind::Artifacts || !dir.join("tsconfig.json").is_file()) {
@@ -926,17 +978,7 @@ pub fn has_non_java_sources(module: &Path) -> bool {
}
fn reactor_projects<'a>(m: &'a maven::MavenModel, top: &'a maven::MavenProject) -> Vec<&'a maven::MavenProject> {
let mut projects = Vec::new();
let mut pending = vec![top];
let mut seen = HashSet::new();
while let Some(p) = pending.pop() {
if !seen.insert(&p.pom) {
continue;
}
projects.push(p);
pending.extend(m.projects.iter().filter(|child| p.modules.contains(&child.pom)));
}
projects
maven::reactor_projects(m, top)
}
/// A step running Maven, its output parsed as Maven's.
@@ -962,7 +1004,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.
@@ -986,7 +1028,7 @@ fn maven_launch_projects<'a>(
}
projects.push(p);
for dep in &p.dependencies {
if !dep.resolved() || (dep.scope == "test" && (!test || p.pom != start.pom)) {
if !dep.resolved() || dep.scope == "system" || (dep.scope == "test" && (!test || p.pom != start.pom)) {
continue;
}
if let Some(upstream) = reactor.iter().find(|u| {
@@ -1659,6 +1701,15 @@ mod tests {
"an unconfigured project is configured first"
);
write(&cm, "cmake-build-release/CMakeCache.txt", "");
let p =
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(
p.steps[0].args,
["-S", ".", "-B", "cmake-build-release", "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"],
"configured again, as it was, when it has no File API reply"
);
assert!(cm.join("cmake-build-release/.cmake/api/v1/query/client-openidea/codemodel-v2").is_file());
std::fs::create_dir_all(cm.join("cmake-build-release").join(ide_core::cmake_file_api::REPLY)).unwrap();
let p =
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(
@@ -1694,6 +1745,33 @@ mod tests {
)
.unwrap();
assert_eq!(p.steps[0].args[..4], ["-S", ".", "-B", "cmake-build-debug"]);
let preset = CMakeProfile {
build_dir: "out/dev".into(),
preset: Some(ide_core::settings::CMakePresetRef {
configure: "dev".into(),
build: Some("dev-build".into()),
..Default::default()
}),
..CMakeProfile::default()
};
let p = plan(
&cm,
&BuildModel::default(),
BuildKind::Build,
None,
Some(std::slice::from_ref(&preset)),
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(
args(&p),
[
"--preset dev -DCMAKE_EXPORT_COMPILE_COMMANDS=ON".to_owned(),
format!("--build --preset dev-build {jobs}")
],
"a preset profile configures and builds with its presets"
);
let siblings = tmp.path().join("siblings");
write(&siblings, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
@@ -1993,6 +2071,34 @@ mod tests {
);
}
#[test]
fn sibling_reactor_launch_uses_relative_module_selector() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(
root,
"parent/pom.xml",
"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>",
);
write(
root,
"common/pom.xml",
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
);
write(
root,
"app/pom.xml",
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId></project>",
);
let model = BuildModel { maven: Some(maven::load(root)), ..Default::default() };
let plan =
launch_plan(root, &model, &root.join("app"), false, BuildKind::Build, &CancellationToken::new()).unwrap();
assert_eq!(plan.steps.len(), 1);
assert_eq!(plan.steps[0].cwd, root.join("parent"));
let pl = plan.steps[0].args.iter().position(|a| a == "-pl").unwrap();
assert_eq!(&plan.steps[0].args[pl..pl + 3], &["-pl", "../app", "-am"]);
}
#[cfg(unix)]
#[test]
fn external_launch_returns_upstream_outputs_and_blocks_failure_or_cancellation() {
@@ -2162,4 +2268,60 @@ 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}");
}
}
}
+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()));
}
}
+89 -8
Переглянути файл
@@ -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 })
}
@@ -180,6 +178,30 @@ pub fn find_javac(env: &BTreeMap<String, String>) -> String {
exe.to_owned()
}
/// Existing system-scope dependencies of this module. Maven resolves these from
/// their local files and does not pass them transitively to reactor dependents.
pub fn maven_system_classpath(root: &Path, model: &BuildModel, module: &Path) -> Vec<PathBuf> {
let Some(maven) = &model.maven else { return Vec::new() };
let module = root.join(module);
maven
.projects
.iter()
.find(|p| root.join(&p.dir) == module)
.into_iter()
.flat_map(|p| &p.system_paths)
.filter(|p| p.is_file())
.cloned()
.collect()
}
fn with_system_classpath(root: &Path, model: &BuildModel, module: &Path, classpath: String) -> String {
let system = maven_system_classpath(root, model, module);
if system.is_empty() {
return classpath;
}
join_classpath(std::env::split_paths(&classpath).chain(system).map(|p| p.to_string_lossy().into_owned()))
}
/// Dependency classpath of the module: existing reactor class directories plus
/// `mvn dependency:build-classpath` (which resolves without compiling anything,
/// so `-am` stays cheap). Entries are platform-separated (`;` on Windows).
@@ -233,7 +255,7 @@ pub fn module_classpath_without_build(
&& cached.version == CLASSPATH_CACHE_VERSION
&& classpath_entries_exist(root, &cached.classpath)
{
return Ok(cached.classpath);
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
}
classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel)
}
@@ -270,7 +292,7 @@ pub fn module_classpaths(
&& classpath_entries_exist(root, &cached.classpath)
{
if i == 0 {
return Ok(cached.classpath);
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
}
continue;
}
@@ -298,7 +320,7 @@ pub fn module_classpaths(
}
}
}
Ok(classpaths.into_iter().next().unwrap())
Ok(with_system_classpath(root, model, &modules[0], classpaths.into_iter().next().unwrap()))
}
/// A module whose classpath the Maven probe resolves, with its cache key and file.
@@ -346,7 +368,8 @@ fn classpath(
compile_first: bool,
cancel: &CancellationToken,
) -> IdeResult<String> {
Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
let classpath = classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap();
Ok(with_system_classpath(root, model, &target.module, classpath))
}
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
@@ -912,6 +935,64 @@ mod tests {
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
}
#[cfg(unix)]
#[test]
fn system_jars_augment_maven_javac_and_launch_classpaths() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
write(
&root,
"pom.xml",
r#"<project><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version>
<packaging>pom</packaging><modules><module>app</module></modules>
<properties><lib.dir>src/main/resources/lib</lib.dir></properties></project>"#,
);
write(
&root,
"app/pom.xml",
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
<artifactId>app</artifactId>
<properties><lib.file>${lib.dir}/offline.jar</lib.file></properties>
<dependencies>
<dependency><groupId>local</groupId><artifactId>offline</artifactId><version>1</version>
<scope>system</scope><systemPath>${pom.basedir}/${lib.file}</systemPath></dependency>
<dependency><groupId>local</groupId><artifactId>late</artifactId><version>1</version>
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}/late.jar</systemPath></dependency>
<dependency><groupId>local</groupId><artifactId>directory</artifactId><version>1</version>
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}</systemPath></dependency>
</dependencies></project>"#,
);
let jars = "app/src/main/resources/lib";
write(&root, &format!("{jars}/offline.jar"), "");
write(&root, "app/src/main/java/demo/Main.java", "class Main {}");
// The scope-filtered Maven classpath can contain no dependencies.
write(&root, "mvnw", "#!/bin/sh\nmkdir -p app/target\n: > app/target/ide-compile-cp.txt\n");
fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap();
let cache = root.join("cache");
let model = crate::load(&root, &cache, None);
let module = root.join("app");
let file = module.join("src/main/java/demo/Main.java");
let jar = root.join(jars).join("offline.jar");
let plan = compile_file_plan(&root, &model, &file).unwrap();
assert!(plan.steps[0].args.windows(2).any(|arg| arg[0] == "-cp" && Path::new(&arg[1]) == jar));
let cancel = CancellationToken::new();
let cp = module_classpath(&root, &model, &module, false, None, &cache, &cancel).unwrap();
let paths: Vec<_> = std::env::split_paths(&cp).collect();
assert_eq!(paths, [module.join("target/classes"), jar.clone()]);
assert!(maven_system_classpath(&root, &model, &root).is_empty());
// Adding a previously absent jar or deleting an old one updates a no-build launch.
fs::remove_file(jar).unwrap();
write(&root, &format!("{jars}/late.jar"), "");
fs::remove_file(root.join("mvnw")).unwrap();
let cp = module_classpath_without_build(&root, &model, &module, false, &cache, &cancel).unwrap();
let paths: Vec<_> = std::env::split_paths(&cp).collect();
assert_eq!(paths, [module.join("target/classes"), root.join(jars).join("late.jar")]);
}
/// Modules launched together resolve their classpaths in one Maven probe and leave
/// the others' cached; a probe another module breaks still resolves the first one.
#[cfg(unix)]
File diff suppressed because it is too large. Load diff
+19 -4
Переглянути файл
@@ -234,9 +234,7 @@ fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Ve
Some(out)
}
/// Parses a class file; `None` when it isn't a well-formed one.
pub fn parse(data: &[u8]) -> Option<ClassFile> {
let mut r = Bytes { data, pos: 0 };
fn read_pool(r: &mut Bytes<'_>) -> Option<Pool> {
if r.u4()? != 0xCAFE_BABE {
return None;
}
@@ -283,11 +281,28 @@ pub fn parse(data: &[u8]) -> Option<ClassFile> {
entries.push(entry);
i += 1;
if wide {
if i == count {
return None;
}
entries.push(Entry::Empty);
i += 1;
}
}
let pool = Pool(entries);
Some(Pool(entries))
}
/// Reads the internal class name (e.g. `com/acme/Order$Line`) from `this_class`.
pub fn class_file_name(data: &[u8]) -> Option<String> {
let mut r = Bytes { data, pos: 0 };
let pool = read_pool(&mut r)?;
r.u2()?; // access_flags
Some(pool.class(r.u2()?)?.to_owned())
}
/// Parses a class file; `None` when it isn't a well-formed one.
pub fn parse(data: &[u8]) -> Option<ClassFile> {
let mut r = Bytes { data, pos: 0 };
let pool = read_pool(&mut r)?;
let mut refs = BTreeSet::new();
for entry in &pool.0 {
match entry {
+404 -243
Переглянути файл
@@ -22,7 +22,7 @@ mod incremental;
mod javac;
mod model;
pub use classfile::ClassFile;
pub use classfile::{ClassFile, class_file_name};
pub use javac::{JavacPool, Reply, ServerKey};
use incremental::{ClassRecord, SetStamp, SetState};
@@ -64,9 +64,300 @@ pub struct JavaBuildService {
}
impl JavaBuildService {
fn lock(&self, dir: &Path) -> Arc<Mutex<()>> {
pub(crate) fn lock(&self, dir: &Path) -> Arc<Mutex<()>> {
self.locks.lock().unwrap().entry(dir.to_path_buf()).or_default().clone()
}
/// Compiles what changed in one source set (see [`incremental`]).
pub fn compile_incremental(
&self,
set: &IncrementalSet<'_>,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
messages: &mut Vec<BuildMessage>,
) -> IdeResult<IncrementalOutcome> {
if set.clean {
remove_classes(&set.output);
let _ = std::fs::remove_dir_all(&set.generated_dir);
let _ = std::fs::remove_file(&set.state_file);
}
let source_stamps: BTreeMap<PathBuf, FileStamp> =
set.sources.iter().filter_map(|s| Some((s.clone(), file_stamp(s)?))).collect();
let previous = incremental::load_state(&set.state_file);
let reactor: Vec<PathBuf> = set.upstream_states.iter().map(|(o, _)| o.clone()).collect();
let stamp = SetStamp {
options: set.options.clone(),
libraries: set.libraries.iter().map(|e| (e.clone(), file_stamp(e))).collect(),
reactor,
processor_path: set.processor_path.iter().map(|p| (p.clone(), file_stamp(p))).collect(),
java_home: set.java_home.clone(),
};
// What the upstream outputs it compiles against changed since it last compiled.
let mut upstream = BTreeMap::new();
let mut upstream_changed = BTreeSet::new();
let mut upstream_all = false;
for (entry, up_state_file) in &set.upstream_states {
let state = incremental::load_state(up_state_file);
let generation = state.as_ref().map_or(0, |s| s.generation);
upstream.insert(entry.clone(), generation);
let recorded = previous.as_ref().and_then(|p| p.upstream.get(entry)).copied();
if recorded == Some(generation) {
continue;
}
match (recorded, state.and_then(|s| s.changes_since(recorded?))) {
(Some(_), Some(changed)) => upstream_changed.extend(changed),
_ => upstream_all = true,
}
}
let had_state = previous.is_some();
let previous = previous.unwrap_or_default();
let mut changed: BTreeSet<PathBuf> = source_stamps
.iter()
.filter(|(path, stamp)| {
previous.sources.get(*path) != Some(*stamp)
|| previous.dirty.contains(*path)
|| set.force.contains(*path)
})
.map(|(path, _)| path.clone())
.collect();
let removed: BTreeSet<PathBuf> =
previous.sources.keys().filter(|p| !source_stamps.contains_key(*p)).cloned().collect();
let mut from_scratch = !had_state
|| previous.stamp != stamp
|| upstream_all
|| !set.output.is_dir()
|| (!previous.success && previous.dirty.is_empty());
if had_state && !from_scratch {
for record in previous.classes.values() {
if !record.file.is_file() {
match &record.source {
Some(src) if source_stamps.contains_key(src) => {
changed.insert(src.clone());
}
Some(src) if removed.contains(src) => {}
_ => {
from_scratch = true;
break;
}
}
}
}
}
if !from_scratch && changed.is_empty() && removed.is_empty() && upstream_changed.is_empty() {
return Ok(IncrementalOutcome { failed: false, compiled_files: 0, outputs_changed: false });
}
// Processors that aggregate (or name no originating source) can't be followed class by class.
let has_changes = !changed.is_empty() || !removed.is_empty() || !upstream_changed.is_empty();
let from_scratch =
from_scratch || ((!previous.generated.is_empty() || !previous.unowned.is_empty()) && has_changes);
let mut state = SetState {
stamp,
sources: source_stamps.clone(),
generation: previous.generation,
upstream,
classes: previous.classes,
changes: previous.changes,
..Default::default()
};
let mut api_changed = BTreeSet::new();
let mut constants_changed = false;
// Classes of removed sources go first, and count as changed.
let gone: Vec<String> = state
.classes
.iter()
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| removed.contains(s)))
.map(|(n, _)| n.clone())
.collect();
let gone_empty = gone.is_empty();
for name in gone {
let record = state.classes.remove(&name).expect("listed");
let _ = std::fs::remove_file(&record.file);
constants_changed |= record.constants != incremental::NO_CONSTANTS;
api_changed.insert(name);
}
let mut to_compile: BTreeSet<PathBuf> = if from_scratch || constants_changed {
remove_classes(&set.output);
for file in previous.generated.iter().chain(&previous.unowned) {
let _ = std::fs::remove_file(file);
}
let _ = std::fs::remove_dir_all(&set.generated_dir);
state.classes.retain(|_, r| r.source.is_some());
source_stamps.keys().cloned().collect()
} else {
let affected =
incremental::with_subclasses(&state.classes, &upstream_changed.union(&api_changed).cloned().collect());
changed.iter().cloned().chain(incremental::dependent_sources(&state.classes, &affected)).collect()
};
std::fs::create_dir_all(&set.output)?;
std::fs::create_dir_all(&set.generated_dir)?;
let total = source_stamps.len();
let mut compiled: BTreeSet<PathBuf> = BTreeSet::new();
let mut server = None;
loop {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let batch: BTreeSet<PathBuf> = to_compile
.iter()
.filter(|s| !compiled.contains(*s) && source_stamps.contains_key(*s))
.cloned()
.collect();
if batch.is_empty() {
break;
}
// The classes the batch replaces: their files go first, so nothing stale is left.
let replaced: BTreeMap<String, ClassRecord> = state
.classes
.iter()
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| batch.contains(s)))
.map(|(n, r)| (n.clone(), r.clone()))
.collect();
for (name, record) in &replaced {
let _ = std::fs::remove_file(&record.file);
state.classes.remove(name);
}
let files: Vec<PathBuf> = batch.iter().cloned().collect();
let noun = if total == 1 { "file" } else { "files" };
let count = if files.len() == total {
format!("{total} {noun}")
} else {
format!("{} of {total} {noun}", files.len())
};
on_event(BuildEvent::Step {
command: format!("javac {} ({}, {count})", set.module_name, set.set_name),
cwd: set.cwd.clone().into(),
});
if server.is_none() {
let key = ServerKey { java_home: set.java_home.clone(), jvm_args: set.jvm_args.clone() };
server = Some(self.servers.server(set.jar, &key)?);
}
let mut written: Vec<(PathBuf, Option<PathBuf>)> = Vec::new();
let result =
server.as_ref().expect("started").compile(&set.options, &files, set.encoding, cancel, |reply| {
match reply {
Reply::Output { path, source } => written.push((path.clone(), source.clone())),
Reply::Generated { path, .. } => state.generated.push(path.clone()),
Reply::OutputText { text } => {
on_event(BuildEvent::Output { text: text.clone(), stderr: false })
}
Reply::Diagnostic { .. } => {
if let Some(m) = diagnostic(reply) {
on_event(BuildEvent::Output {
text: message_text(&m),
stderr: m.severity == Severity::Error,
});
on_event(BuildEvent::Message { message: m.clone() });
messages.push(m);
}
}
Reply::Done { .. } => {}
}
});
if !matches!(result, Ok(true)) {
for (path, _) in &written {
let _ = std::fs::remove_file(path);
}
// The next build starts from the state this one started from, with whatever this
// one had to compile still to compile. Its earlier rounds' classes are not the
// baseline: compared with them, the API and constant changes those rounds found
// would never reach this set's dependents or the sets compiled against it.
let mut retry = incremental::load_state(&set.state_file).unwrap_or_default();
retry.dirty.extend(to_compile.union(&compiled).filter(|s| source_stamps.contains_key(*s)).cloned());
retry.success = false;
let _ = model::write_json(&set.state_file, &retry);
return result.map(|_| IncrementalOutcome {
failed: true,
compiled_files: compiled.len(),
outputs_changed: false,
});
}
// javac names sources as they were passed; other spellings are matched canonically,
// and classes of sources outside the set (processors' output) are unowned.
let canonical: HashMap<PathBuf, &PathBuf> =
batch.iter().filter_map(|s| Some((dunce::canonicalize(s).ok()?, s))).collect();
let own = |source: PathBuf| -> Option<PathBuf> {
if source_stamps.contains_key(&source) {
return Some(source);
}
canonical.get(&dunce::canonicalize(&source).ok()?).map(|s| (*s).clone())
};
let mut fresh = BTreeMap::new();
for (path, source) in written {
let source = source.and_then(own);
let class = (path.extension().is_some_and(|e| e == "class"))
.then(|| std::fs::read(&path).ok())
.flatten()
.and_then(|bytes| classfile::parse(&bytes));
match (class, source) {
(Some(class), Some(source)) => {
let (name, record) = ClassRecord::new(class, path, Some(source));
fresh.insert(name, record);
}
_ => state.unowned.push(path),
}
}
let round = incremental::diff(&replaced, &fresh);
constants_changed |= round.constants;
api_changed.extend(round.api.iter().cloned());
state.classes.extend(fresh);
compiled.extend(batch);
if constants_changed {
// Constants are copied into the classes that use them: compile the rest too.
to_compile.extend(source_stamps.keys().cloned());
continue;
}
let affected =
incremental::with_subclasses(&state.classes, &round.api.union(&upstream_changed).cloned().collect());
to_compile.extend(incremental::dependent_sources(&state.classes, &affected));
to_compile.extend(incremental::shadowed_sources(&state.classes, &round.added));
}
state.success = true;
if !compiled.is_empty() || !api_changed.is_empty() {
let changed =
incremental::with_subclasses(&state.classes, &api_changed.union(&upstream_changed).cloned().collect());
state.log(now_generation(), changed, !had_state || constants_changed);
}
model::write_json(&set.state_file, &state)?;
Ok(IncrementalOutcome {
failed: false,
compiled_files: compiled.len(),
outputs_changed: !compiled.is_empty() || !gone_empty,
})
}
}
/// Inputs for compiling one source set incrementally with the resident `javac` server.
pub struct IncrementalSet<'a> {
pub module_name: String,
pub set_name: &'static str,
pub cwd: PathBuf,
pub sources: Vec<PathBuf>,
pub output: PathBuf,
pub options: Vec<String>,
pub libraries: Vec<PathBuf>,
/// Upstream `(output_dir, state_file)` pairs this set compiles against.
pub upstream_states: Vec<(PathBuf, PathBuf)>,
pub processor_path: Vec<PathBuf>,
pub java_home: PathBuf,
pub jvm_args: Vec<String>,
pub encoding: Option<&'a str>,
pub state_file: PathBuf,
pub generated_dir: PathBuf,
pub force: &'a BTreeSet<PathBuf>,
pub jar: &'a Path,
pub clean: bool,
}
/// Result of compiling one source set incrementally.
#[derive(Debug, Default)]
pub struct IncrementalOutcome {
pub failed: bool,
pub compiled_files: usize,
pub outputs_changed: bool,
}
/// One build of the IDE's Java build service.
@@ -79,6 +370,8 @@ pub struct JavaBuild<'a> {
/// Changes when the jar does, so models recorded by an older extension are prepared again.
pub jar_version: &'a str,
pub local_repo: Option<PathBuf>,
/// Explicit Maven goals the project's settings allow the IDE to skip in compile phases.
pub ignored_maven_compile_goals: &'a [String],
pub service: &'a JavaBuildService,
/// The JDK home that compiles for a release, when Maven's environment names none.
pub jdk: &'a (dyn Fn(Option<u32>) -> Option<PathBuf> + Sync),
@@ -250,15 +543,11 @@ fn java_sources(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<Vec<Pa
Ok(out)
}
/// `-g`, `-g:lines,vars` or `-g:none`, as maven-compiler-plugin passes them.
fn debug_args(c: &CompilerConfig) -> Vec<String> {
if c.debug == Some(false) {
return vec!["-g:none".into()];
}
match c.debuglevel.as_deref().map(str::trim).filter(|l| !l.is_empty()) {
Some(level) => vec![format!("-g:{level}")],
None => vec!["-g".into()],
}
/// A javac debug-info option (`-g`, `-g:none`, `-g:lines,vars`). The IDE's build always
/// compiles with `-g`: breakpoints need line numbers and local variables, whatever
/// maven-compiler-plugin's `<debug>` / `<debuglevel>` ask of Maven's own build (#7786).
fn is_debug_option(arg: &str) -> bool {
arg == "-g" || arg.starts_with("-g:")
}
/// The JDK feature version of `release` / `source` (`1.8` → 8).
@@ -294,7 +583,7 @@ fn javac_options(set: &SourceSet, classpath: &[PathBuf], generated: &Path, jdk_m
if let Some(proc) = c.proc.as_deref().filter(|p| !p.is_empty()) {
args.push(format!("-proc:{proc}"));
}
args.extend(debug_args(&c));
args.push("-g".into());
if c.parameters == Some(true) {
args.push("-parameters".into());
}
@@ -323,15 +612,19 @@ fn javac_options(set: &SourceSet, classpath: &[PathBuf], generated: &Path, jdk_m
}
}
for (key, value) in &c.compiler_arguments {
args.push(if key.starts_with('-') { key.clone() } else { format!("-{key}") });
let key = if key.starts_with('-') { key.clone() } else { format!("-{key}") };
if is_debug_option(&key) {
continue;
}
args.push(key);
if let Some(value) = value.as_ref().filter(|v| !v.is_empty()) {
args.push(value.clone());
}
}
if let Some(argument) = &c.compiler_argument {
args.extend(argument.split_whitespace().map(str::to_owned));
args.extend(argument.split_whitespace().filter(|a| !is_debug_option(a)).map(str::to_owned));
}
args.extend(c.compiler_args.iter().filter(|a| !a.is_empty()).cloned());
args.extend(c.compiler_args.iter().filter(|a| !a.is_empty() && !is_debug_option(a)).cloned());
args
}
@@ -558,7 +851,7 @@ impl JavaBuild<'_> {
}
};
for (project, test) in &projects {
if let Some(reason) = project.unsupported(*test) {
if let Some(reason) = project.unsupported(*test, self.ignored_maven_compile_goals) {
return Ok(Built::Unsupported(reason));
}
// A launch of a Java module runs it from the module path, which the language server reports.
@@ -667,6 +960,7 @@ impl JavaBuild<'_> {
for project in &reactor_model.projects {
for test in [false, true] {
let stamp = resource_stamp(project.set(test), cancel)?;
self.prune_resources(dir, project, test, cancel)?;
model::write_json(&state_path(dir, project, test, "resources"), &stamp)?;
}
}
@@ -702,7 +996,11 @@ impl JavaBuild<'_> {
let step = match top {
Reactor::Maven(top) => {
let selection = maven_project_selection(changed.iter().map(|(p, _, _)| *p));
let mut extra = vec!["-q".to_owned(), "-pl".to_owned(), selection];
// The resources plugin copies a file only when it is newer than the copy; content
// replaced without moving the mtime (a sync tool, PowerShell `Copy-Item`) would stay
// stale while its stamp is recorded as processed.
let mut extra =
vec!["-q".to_owned(), "-pl".to_owned(), selection, "-Dmaven.resources.overwrite=true".to_owned()];
extra.push("resources:resources".into());
if changed.iter().any(|(_, test, _)| *test) {
extra.push("resources:testResources".into());
@@ -730,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);
@@ -758,244 +1087,46 @@ impl JavaBuild<'_> {
return Ok(false);
}
let sources = java_sources(set, cancel)?;
let source_stamps: BTreeMap<PathBuf, FileStamp> =
sources.iter().filter_map(|s| Some((s.clone(), file_stamp(s)?))).collect();
let state_file = state_path(dir, project, test, "compile");
let previous = incremental::load_state(&state_file);
let config = set.compiler.clone().unwrap_or_default();
let release = config.release.as_deref().or(config.source.as_deref()).and_then(feature);
let java_home = self.java_home(top, &config, release)?;
let generated = generated_dir(dir, project, test);
let generated_dir = generated_dir(dir, project, test);
let classpath: Vec<PathBuf> = if test {
std::iter::once(project.main.output.clone()).chain(set.classpath.iter().cloned()).collect()
} else {
set.classpath.clone()
};
let options = javac_options(set, &classpath, &generated, jdk_major(&java_home));
let reactor: Vec<PathBuf> =
classpath.iter().filter(|e| **e != set.output && outputs.contains_key(*e)).cloned().collect();
let stamp = SetStamp {
options: options.clone(),
libraries: classpath
.iter()
.filter(|e| **e != set.output && !outputs.contains_key(*e))
.map(|e| (e.clone(), file_stamp(e)))
.collect(),
reactor: reactor.clone(),
processor_path: config.processor_path.iter().flatten().map(|p| (p.clone(), file_stamp(p))).collect(),
java_home: java_home.clone(),
};
// What the reactor outputs it compiles against changed since it last compiled.
let mut upstream = BTreeMap::new();
let mut upstream_changed = BTreeSet::new();
let mut upstream_all = false;
for entry in &reactor {
let (key, entry_test) = &outputs[entry];
let state = incremental::load_state(&state_path_of(dir, key, *entry_test, "compile"));
let generation = state.as_ref().map_or(0, |s| s.generation);
upstream.insert(entry.clone(), generation);
let recorded = previous.as_ref().and_then(|p| p.upstream.get(entry)).copied();
if recorded == Some(generation) {
continue;
}
match (recorded, state.and_then(|s| s.changes_since(recorded?))) {
(Some(_), Some(changed)) => upstream_changed.extend(changed),
_ => upstream_all = true,
}
}
let had_state = previous.is_some();
let previous = previous.unwrap_or_default();
let changed: BTreeSet<PathBuf> = source_stamps
let options = javac_options(set, &classpath, &generated_dir, jdk_major(&java_home));
let upstream_states: Vec<(PathBuf, PathBuf)> = classpath
.iter()
.filter(|(path, stamp)| {
previous.sources.get(*path) != Some(*stamp) || previous.dirty.contains(*path) || force.contains(*path)
.filter(|e| **e != set.output)
.filter_map(|e| {
outputs.get(e).map(|(key, entry_test)| (e.clone(), state_path_of(dir, key, *entry_test, "compile")))
})
.map(|(path, _)| path.clone())
.collect();
let removed: BTreeSet<PathBuf> =
previous.sources.keys().filter(|p| !source_stamps.contains_key(*p)).cloned().collect();
let from_scratch = !had_state
|| previous.stamp != stamp
|| upstream_all
|| !set.output.is_dir()
|| (!previous.success && previous.dirty.is_empty());
if !from_scratch && changed.is_empty() && removed.is_empty() && upstream_changed.is_empty() {
return Ok(false);
}
// Processors that aggregate (or name no originating source) can't be followed class by class.
let from_scratch = from_scratch
|| (!previous.generated.is_empty() || !previous.unowned.is_empty())
&& !(changed.is_empty() && removed.is_empty() && upstream_changed.is_empty());
let mut state = SetState {
stamp,
sources: source_stamps.clone(),
generation: previous.generation,
upstream,
classes: previous.classes,
changes: previous.changes,
..Default::default()
let libraries: Vec<PathBuf> =
classpath.iter().filter(|e| **e != set.output && !outputs.contains_key(*e)).cloned().collect();
let incremental_set = IncrementalSet {
module_name: project.artifact_id.clone(),
set_name: if test { "tests" } else { "main" },
cwd: project.dir.clone(),
sources,
output: set.output.clone(),
options,
libraries,
upstream_states,
processor_path: config.processor_path.unwrap_or_default(),
jvm_args: jvm_config(top, &subdir(self.root, top.rel_dir())),
java_home,
encoding: config.encoding.as_deref(),
state_file: state_path(dir, project, test, "compile"),
generated_dir,
force,
jar: self.jar,
clean: false,
};
let mut api_changed = BTreeSet::new();
let mut constants_changed = false;
// Classes of removed sources go first, and count as changed.
let gone: Vec<String> = state
.classes
.iter()
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| removed.contains(s)))
.map(|(n, _)| n.clone())
.collect();
for name in gone {
let record = state.classes.remove(&name).expect("listed");
let _ = std::fs::remove_file(&record.file);
constants_changed |= record.constants != incremental::NO_CONSTANTS;
api_changed.insert(name);
}
let mut to_compile: BTreeSet<PathBuf> = if from_scratch || constants_changed {
remove_classes(&set.output);
for file in previous.generated.iter().chain(&previous.unowned) {
let _ = std::fs::remove_file(file);
}
let _ = std::fs::remove_dir_all(&generated);
state.classes.retain(|_, r| r.source.is_some());
source_stamps.keys().cloned().collect()
} else {
let affected =
incremental::with_subclasses(&state.classes, &upstream_changed.union(&api_changed).cloned().collect());
changed.iter().cloned().chain(incremental::dependent_sources(&state.classes, &affected)).collect()
};
std::fs::create_dir_all(&set.output)?;
std::fs::create_dir_all(&generated)?;
let set_name = if test { "tests" } else { "main" };
let total = source_stamps.len();
let mut compiled: BTreeSet<PathBuf> = BTreeSet::new();
let mut server = None;
loop {
let batch: BTreeSet<PathBuf> = to_compile
.iter()
.filter(|s| !compiled.contains(*s) && source_stamps.contains_key(*s))
.cloned()
.collect();
if batch.is_empty() {
break;
}
// The classes the batch replaces: their files go first, so nothing stale is left.
let replaced: BTreeMap<String, ClassRecord> = state
.classes
.iter()
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| batch.contains(s)))
.map(|(n, r)| (n.clone(), r.clone()))
.collect();
for (name, record) in &replaced {
let _ = std::fs::remove_file(&record.file);
state.classes.remove(name);
}
let files: Vec<PathBuf> = batch.iter().cloned().collect();
let noun = if total == 1 { "file" } else { "files" };
let count = if files.len() == total {
format!("{total} {noun}")
} else {
format!("{} of {total} {noun}", files.len())
};
on_event(BuildEvent::Step {
command: format!("javac {} ({set_name}, {count})", project.artifact_id),
cwd: project.dir.clone().into(),
});
if server.is_none() {
let key = ServerKey {
java_home: java_home.clone(),
jvm_args: jvm_config(top, &subdir(self.root, top.rel_dir())),
};
server = Some(self.service.servers.server(self.jar, &key)?);
}
let mut written: Vec<(PathBuf, Option<PathBuf>)> = Vec::new();
let result = server.as_ref().expect("started").compile(
&options,
&files,
config.encoding.as_deref(),
cancel,
|reply| match reply {
Reply::Output { path, source } => written.push((path.clone(), source.clone())),
Reply::Generated { path, .. } => state.generated.push(path.clone()),
Reply::OutputText { text } => on_event(BuildEvent::Output { text: text.clone(), stderr: false }),
Reply::Diagnostic { .. } => {
if let Some(m) = diagnostic(reply) {
on_event(BuildEvent::Output {
text: message_text(&m),
stderr: m.severity == Severity::Error,
});
on_event(BuildEvent::Message { message: m.clone() });
messages.push(m);
}
}
Reply::Done { .. } => {}
},
);
if !matches!(result, Ok(true)) {
for (path, _) in &written {
let _ = std::fs::remove_file(path);
}
// The next build starts from the state this one started from, with whatever this
// one had to compile still to compile. Its earlier rounds' classes are not the
// baseline: compared with them, the API and constant changes those rounds found
// would never reach this set's dependents or the sets compiled against it.
let mut retry = incremental::load_state(&state_file).unwrap_or_default();
retry.dirty.extend(to_compile.union(&compiled).filter(|s| source_stamps.contains_key(*s)).cloned());
retry.success = false;
let _ = model::write_json(&state_file, &retry);
return result.map(|_| true);
}
// javac names sources as they were passed; other spellings are matched canonically,
// and classes of sources outside the set (processors' output) are unowned.
let canonical: HashMap<PathBuf, &PathBuf> =
batch.iter().filter_map(|s| Some((dunce::canonicalize(s).ok()?, s))).collect();
let own = |source: PathBuf| -> Option<PathBuf> {
if source_stamps.contains_key(&source) {
return Some(source);
}
canonical.get(&dunce::canonicalize(&source).ok()?).map(|s| (*s).clone())
};
let mut fresh = BTreeMap::new();
for (path, source) in written {
let source = source.and_then(own);
let class = (path.extension().is_some_and(|e| e == "class"))
.then(|| std::fs::read(&path).ok())
.flatten()
.and_then(|bytes| classfile::parse(&bytes));
match (class, source) {
(Some(class), Some(source)) => {
let (name, record) = ClassRecord::new(class, path, Some(source));
fresh.insert(name, record);
}
_ => state.unowned.push(path),
}
}
let round = incremental::diff(&replaced, &fresh);
constants_changed |= round.constants;
api_changed.extend(round.api.iter().cloned());
state.classes.extend(fresh);
compiled.extend(batch);
if constants_changed {
// Constants are copied into the classes that use them: compile the rest too.
to_compile.extend(source_stamps.keys().cloned());
continue;
}
let affected =
incremental::with_subclasses(&state.classes, &round.api.union(&upstream_changed).cloned().collect());
to_compile.extend(incremental::dependent_sources(&state.classes, &affected));
to_compile.extend(incremental::shadowed_sources(&state.classes, &round.added));
}
state.success = true;
if !compiled.is_empty() || !api_changed.is_empty() {
let changed =
incremental::with_subclasses(&state.classes, &api_changed.union(&upstream_changed).cloned().collect());
state.log(now_generation(), changed, !had_state || constants_changed);
}
model::write_json(&state_file, &state)?;
Ok(false)
let outcome = self.service.compile_incremental(&incremental_set, cancel, on_event, messages)?;
Ok(outcome.failed)
}
/// The JDK compiling a source set: the compiler plugin's forked `executable`, else Maven's
@@ -1129,5 +1260,35 @@ fn resource_stamp(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTre
Ok(out)
}
/// Where `process-resources` puts each file of a source set's resource folders: the output folder,
/// the root's target path, then the path under the root, filtered by its includes and excludes.
fn resource_outputs(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTreeSet<PathBuf>> {
let mut out = BTreeSet::new();
for root in &set.resources {
let mut pending = vec![root.directory.clone()];
while let Some(dir) = pending.pop() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
for entry in entries.flatten() {
let path = entry.path();
if entry.file_type().is_ok_and(|t| t.is_dir()) {
pending.push(path);
continue;
}
let rel = path.strip_prefix(&root.directory).unwrap_or(&path).to_string_lossy().replace('\\', "/");
let included = root.includes.is_empty() || root.includes.iter().any(|p| ant_match(p, &rel));
if !included || root.excludes.iter().any(|p| ant_match(p, &rel)) {
continue;
}
let target = root.target_path.as_deref().unwrap_or("").replace('\\', "/");
out.insert(set.output.join(target.trim_matches('/')).join(&rel));
}
}
}
Ok(out)
}
#[cfg(test)]
mod tests;
+16 -3
Переглянути файл
@@ -105,13 +105,26 @@ impl ProjectModel {
}
/// Why the IDE can't compile this project with javac itself, if it can't.
pub fn unsupported(&self, test: bool) -> Option<String> {
pub fn unsupported(&self, test: bool, ignored_maven_compile_goals: &[String]) -> Option<String> {
// What the build tool couldn't resolve or read: the model would be incomplete.
if let Some(problem) = self.problems.first() {
return Some(format!("{}: {problem}", self.artifact_id));
}
if !self.other_compilers.is_empty() {
return Some(format!("{} also compiles with {}", self.artifact_id, self.other_compilers.join(", ")));
// Keep the recorded model intact: adding or removing a project override must also
// affect an already prepared model. Gradle tasks never use Maven overrides.
let other_compilers: Vec<&str> = self
.other_compilers
.iter()
.filter(|execution| {
!(self.gradle_path.is_none()
&& execution.split_once('@').is_some_and(|(goal, _)| {
ignored_maven_compile_goals.iter().any(|ignored| ignored.trim() == goal)
}))
})
.map(String::as_str)
.collect();
if !other_compilers.is_empty() {
return Some(format!("{} also compiles with {}", self.artifact_id, other_compilers.join(", ")));
}
if test && !self.test_generators.is_empty() {
return Some(format!(
+237 -9
Переглянути файл
@@ -55,6 +55,75 @@ fn maven_resources_select_projects_by_coordinates_not_by_basedir() {
assert_eq!(maven_project_selection(projects.iter()), "org.starry:cloud,org.starry:organ");
}
#[test]
fn maven_compile_goal_overrides_apply_to_cached_models_and_can_be_removed() {
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
let project = ProjectModel {
artifact_id: "app".into(),
other_compilers: vec![format!("{goal}@default-jar"), format!("{goal}@extra-jar")],
..Default::default()
};
let cached: ProjectModel = serde_json::from_str(&serde_json::to_string(&project).unwrap()).unwrap();
assert!(cached.unsupported(false, &[]).unwrap().contains(goal));
assert_eq!(cached.unsupported(false, &[goal.into()]), None);
assert_eq!(cached.unsupported(false, &[format!(" {goal} ")]), None);
assert!(cached.unsupported(false, &[]).unwrap().contains(goal));
assert_eq!(cached.other_compilers, project.other_compilers);
}
#[test]
fn maven_compile_goal_overrides_match_exact_goals_and_keep_other_executions() {
let jar = "org.apache.maven.plugins:maven-jar-plugin:jar";
let kotlin = "org.jetbrains.kotlin:kotlin-maven-plugin:compile";
let mut project = ProjectModel {
artifact_id: "app".into(),
other_compilers: vec![format!("{jar}@default-jar")],
..Default::default()
};
for unmatched in [
"",
"*",
"org.apache.maven.plugins:maven-jar-plugin",
"maven-jar-plugin:jar",
"org.apache.maven.plugins:maven-jar-plugin:test-jar",
"org.apache.maven.plugins:*:jar",
] {
assert!(project.unsupported(false, &[unmatched.into()]).is_some(), "{unmatched}");
}
project.other_compilers.push(format!("{kotlin}@compile"));
let reason = project.unsupported(false, &[jar.into()]).unwrap();
assert!(reason.contains(kotlin));
assert!(!reason.contains(jar));
}
#[test]
fn maven_compile_goal_overrides_do_not_affect_gradle_or_other_safety_checks() {
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
let ignored = [goal.into()];
let mut project = ProjectModel {
artifact_id: "app".into(),
other_compilers: vec![format!("{goal}@default-jar")],
..Default::default()
};
project.gradle_path = Some(":app".into());
assert!(project.unsupported(false, &ignored).is_some());
project.gradle_path = None;
project.problems.push("unresolved dependency".into());
assert!(project.unsupported(false, &ignored).unwrap().contains("unresolved dependency"));
project.problems.clear();
project.test_generators.push("org.example:generator:test@tests".into());
assert_eq!(project.unsupported(false, &ignored), None);
assert!(project.unsupported(true, &ignored).unwrap().contains("generates test sources"));
project.test_generators.clear();
project.main.compiler = Some(CompilerConfig { compiler_id: Some("eclipse".into()), ..Default::default() });
assert!(project.unsupported(false, &ignored).unwrap().contains("eclipse"));
project.main.compiler = Some(CompilerConfig { multi_release_output: Some(true), ..Default::default() });
assert!(project.unsupported(false, &ignored).unwrap().contains("multi-release"));
project.main.compiler =
Some(CompilerConfig { processor_path_error: Some("missing processor".into()), ..Default::default() });
assert!(project.unsupported(false, &ignored).unwrap().contains("missing processor"));
}
/// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped).
fn tools() -> Option<(PathBuf, PathBuf)> {
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?;
@@ -169,6 +238,17 @@ impl Fixture {
}
fn build(&self, target: Target) -> LaunchOutputs {
match self.try_build(target, &[]) {
Ok(Built::Done(outputs)) => outputs,
Ok(Built::Unsupported(reason)) => {
let output = build_output_tail(&self.events.lock().unwrap());
panic!("unsupported: {reason}\n{output}");
}
Err(e) => panic!("{e:?}"),
}
}
fn try_build(&self, target: Target, ignored_maven_compile_goals: &[String]) -> IdeResult<Built> {
let jdk = |_: Option<u32>| None;
let build = JavaBuild {
root: &self.root,
@@ -177,18 +257,12 @@ impl Fixture {
jar: Path::new(JAR),
jar_version: "test",
local_repo: None,
ignored_maven_compile_goals,
service: &self.service,
jdk: &jdk,
};
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) {
Ok(Built::Done(outputs)) => outputs,
Ok(Built::Unsupported(reason)) => {
let output = build_output_tail(&self.events.lock().unwrap());
panic!("unsupported: {reason}\n{output}");
}
Err(e) => panic!("{e:?}"),
}
build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event)
}
/// The steps of the launch builds since the last call.
@@ -213,6 +287,37 @@ impl Fixture {
}
}
#[test]
fn a_real_maven_compile_goal_can_be_skipped_with_a_cached_reactor() {
let pom = APP_POM.replace(
"</build>",
concat!(
"<plugins><plugin><groupId>org.apache.maven.plugins</groupId>",
"<artifactId>maven-jar-plugin</artifactId><version>3.4.1</version>",
"<executions><execution><id>early-jar</id><phase>compile</phase>",
"<goals><goal>jar</goal></goals></execution></executions></plugin></plugins></build>",
),
);
let Some(f) = Fixture::new(&[
("app/pom.xml", &pom),
("lib/src/main/java/l/L.java", "package l; public class L {}"),
("app/src/main/java/a/A.java", "package a; public class A { l.L dependency; }"),
]) else {
return;
};
let module = f.root.join("app");
let go = |ignored: &[String]| f.try_build(Target::Launch { module: &module, test: false }, ignored).unwrap();
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
assert!(matches!(go(&[]), Built::Unsupported(reason) if reason.contains(goal)));
f.steps();
let Built::Done(output) = go(&[goal.into()]) else { panic!("expected the configured build to use javac") };
assert!(output.failure.is_none(), "{:?}", output.messages);
assert!(f.out("t.app/classes/a/A.class").is_file());
assert!(!f.root.join("app/target/app-1.jar").exists());
assert!(f.steps().iter().all(|step| step.starts_with("javac")), "the prepared model was reused");
assert!(matches!(go(&[]), Built::Unsupported(reason) if reason.contains(goal)));
}
#[test]
fn builds_maven_modules_with_javac_and_only_what_changed() {
let Some(f) = Fixture::new(&[
@@ -258,6 +363,8 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl t:app"), "{steps:?}");
// #7340: content replaced without a newer mtime is copied too.
assert!(steps[0].contains("-Dmaven.resources.overwrite=true"), "{steps:?}");
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nmore=1\n");
// A deleted source leaves no class behind.
@@ -309,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(&[
@@ -485,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",
@@ -500,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(&[
@@ -581,6 +808,7 @@ fn leaves_gradle_projects_with_other_compilers_to_gradle() {
jar: Path::new(JAR),
jar_version: "test",
local_repo: None,
ignored_maven_compile_goals: &[],
service: &f.service,
jdk: &jdk,
};
+139 -2
Переглянути файл
@@ -69,6 +69,9 @@ pub struct MavenProject {
pub aggregated: bool,
pub plugins: Vec<MavenPlugin>,
pub dependencies: Vec<MavenDependency>,
/// Local classpath entries from the POM. The synced dependency tree has coordinates only.
#[serde(skip)]
pub system_paths: Vec<PathBuf>,
/// Profile ids declared in this POM.
pub profiles: Vec<String>,
/// Java feature version the project compiles for (`maven.compiler.release`, `java.version`…).
@@ -89,6 +92,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 {
@@ -176,6 +273,7 @@ struct RawDep {
kind: Option<String>,
classifier: Option<String>,
scope: Option<String>,
system_path: Option<String>,
optional: bool,
}
@@ -248,6 +346,7 @@ fn read_dep(e: &Element) -> Option<RawDep> {
kind: e.text_of("type"),
classifier: e.text_of("classifier"),
scope: e.text_of("scope"),
system_path: e.text_of("systemPath"),
optional: e.text_of("optional").is_some_and(|o| o == "true"),
})
}
@@ -1335,6 +1434,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 {
@@ -1519,7 +1634,13 @@ pub fn load_with_linked_jdk(
let packaging = i(pom.packaging.as_deref().unwrap_or("jar"));
let managed: HashMap<String, &RawDep> = ctx.managed.iter().map(|m| (m.key(), m)).collect();
let managed_version = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.version.clone());
let managed_scope = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.scope.clone());
let scope = |d: &RawDep| {
d.scope
.as_deref()
.or_else(|| managed.get(&d.key()).and_then(|m| m.scope.as_deref()))
.map(i)
.unwrap_or_else(|| "compile".into())
};
let dependencies = ctx
.deps
.iter()
@@ -1529,11 +1650,26 @@ pub fn load_with_linked_jdk(
version: d.version.clone().or_else(|| managed_version(d)).map(|v| i(&v)),
kind: d.kind.clone().unwrap_or_else(|| "jar".into()),
classifier: d.classifier.clone(),
scope: d.scope.clone().or_else(|| managed_scope(d)).unwrap_or_else(|| "compile".into()),
scope: scope(d),
optional: d.optional,
..MavenDependency::default()
})
.collect();
let system_paths = ctx
.deps
.iter()
.filter(|d| scope(d) == "system")
.filter_map(|d| {
let path = d
.system_path
.as_deref()
.or_else(|| managed.get(&d.key()).and_then(|m| m.system_path.as_deref()))?;
let path = i(path);
// Rebuilt from its components: `${pom.basedir}/lib/x.jar` on Windows mixes `\\` and `/`.
(!path.contains("${") && Path::new(&path).is_absolute())
.then(|| Path::new(&path).components().collect::<PathBuf>())
})
.collect();
let mut plugins: Vec<RawPlugin> = ctx.plugins.clone();
for a in lifecycle_plugins(&packaging) {
@@ -1592,6 +1728,7 @@ pub fn load_with_linked_jdk(
aggregated,
plugins,
dependencies,
system_paths,
profiles: ctx.profiles.iter().map(|(id, _)| id.clone()).collect(),
java_version: jv,
command: wrapper(&canonical_root, &dir_canon),
+93 -19
Переглянути файл
@@ -110,27 +110,15 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
}
fs::write(cache.join("artifact-id.txt"), id)?;
if let Some(pom) = id.strip_prefix("maven:") {
let p = model
.maven
.as_ref()
.and_then(|m| m.projects.iter().find(|p| p.pom == pom && p.packaging == "war"))
.ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
let projects = &model.maven.as_ref().unwrap().projects;
let top = projects
let maven = model.maven.as_ref().ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
let p = maven
.projects
.iter()
.filter(|t| {
!t.aggregated && (t.dir.is_empty() || p.dir == t.dir || p.dir.starts_with(&format!("{}/", t.dir)))
})
.max_by_key(|t| t.dir.len())
.unwrap_or(p);
.find(|p| p.pom == pom && p.packaging == "war")
.ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
let top = crate::maven::reactor_for_pom(maven, &p.pom).unwrap_or(p);
let mut args = top.options.clone();
if top.pom != p.pom {
let module = root
.join(&p.dir)
.strip_prefix(root.join(&top.dir))
.map_err(|e| IdeError::invalid(e.to_string()))?
.to_string_lossy()
.replace('\\', "/");
if let Some(module) = crate::maven::module_selector(root, top, p) {
args.extend(["-pl".into(), module, "-am".into()]);
}
// help:evaluate runs once, in the reactor's first project. Query the selected
@@ -316,4 +304,90 @@ mod tests {
assert!(!action.contains("p.") && !action.contains("war."), "{action}");
}
}
#[test]
fn maven_sibling_reactor_builds_war_through_aggregator_with_relative_pl() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
for dir in ["parent", "common", "app"] {
fs::create_dir_all(root.join(dir)).unwrap();
}
fs::write(
root.join("parent/pom.xml"),
"<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>",
)
.unwrap();
fs::write(
root.join("common/pom.xml"),
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
)
.unwrap();
fs::write(
root.join("app/pom.xml"),
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId><packaging>war</packaging><dependencies><dependency><groupId>test</groupId><artifactId>common</artifactId><version>1</version></dependency></dependencies></project>",
)
.unwrap();
let model = crate::load(root, &root.join("cache"), None);
let a = artifacts(root, &model);
assert_eq!(a.len(), 1);
assert_eq!(a[0].id, "maven:app/pom.xml");
let plan = build(root, &model, &a[0].id, &root.join("base")).unwrap();
assert_eq!(plan.cwd, "parent");
assert_eq!(&plan.args[..3], &["-pl", "../app", "-am"]);
let (probe, _) = plan.maven_project.as_ref().unwrap();
assert!(probe.contains(&root.join("app/pom.xml").to_string_lossy().into_owned()));
}
#[test]
fn maven_subfolder_aggregator_builds_root_war_with_parent_pl() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
for dir in ["parent", "common"] {
fs::create_dir_all(root.join(dir)).unwrap();
}
fs::write(
root.join("pom.xml"),
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>parent/pom.xml</relativePath></parent><artifactId>app</artifactId><packaging>war</packaging></project>",
)
.unwrap();
fs::write(
root.join("parent/pom.xml"),
"<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../</module><module>../common</module></modules></project>",
)
.unwrap();
fs::write(
root.join("common/pom.xml"),
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
)
.unwrap();
let settings =
ide_core::settings::MavenSettings { linked_projects: vec!["parent/pom.xml".into()], ..Default::default() };
let model = crate::load_linked(root, &root.join("cache"), None, &settings, &Default::default());
let plan = build(root, &model, "maven:pom.xml", &root.join("base")).unwrap();
assert_eq!(plan.cwd, "parent");
assert_eq!(&plan.args[..3], &["-pl", "..", "-am"]);
}
#[test]
fn maven_independent_sibling_wars_keep_own_reactor() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
for dir in ["a", "b"] {
fs::create_dir_all(root.join(dir)).unwrap();
fs::write(
root.join(dir).join("pom.xml"),
format!("<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>{dir}</artifactId><version>1</version><packaging>war</packaging></project>"),
)
.unwrap();
}
let model = crate::load(root, &root.join("cache"), None);
for dir in ["a", "b"] {
let plan = build(root, &model, &format!("maven:{dir}/pom.xml"), &root.join("base")).unwrap();
assert_eq!(plan.cwd, dir);
assert!(!plan.args.contains(&"-pl".into()));
}
}
}
+1 -1
Переглянути файл
@@ -16,7 +16,7 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["std",
png = "0.18"
[target.'cfg(target_os = "linux")'.dependencies]
gtk = "0.18"
gtk = "0.19"
[dev-dependencies]
png = "0.18"
+5 -5
Переглянути файл
@@ -175,7 +175,7 @@ impl CliTool {
Poll::Finished => break,
}
}
Ok((lines.finish(cancel)?, stderr_tail))
Ok((lines.finish(cancel)?.success(), stderr_tail))
}
/// Starts `cmd` with a reader thread per pipe, for a caller that drives the loop itself
@@ -301,9 +301,9 @@ impl Lines {
}
}
/// Waits for the child to exit and returns whether it did so successfully. Fails, after
/// killing it, when `cancel` fires first.
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<bool> {
/// Waits for the child to exit and returns how it exited. Fails, after killing it, when
/// `cancel` fires first.
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<std::process::ExitStatus> {
let status = loop {
if let Some(status) = self.child.try_wait()? {
break status;
@@ -314,6 +314,6 @@ impl Lines {
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(status.success())
Ok(status)
}
}
+20
Переглянути файл
@@ -0,0 +1,20 @@
//! The CMake File API queries the IDE writes into a build directory, shared by the run
//! configurations (which read the replies) and Build Project (which configures).
use std::path::Path;
/// The objects asked for: targets, cache, toolchains and the CMake files.
pub const QUERIES: [&str; 4] = ["codemodel-v2", "cache-v2", "toolchains-v1", "cmakeFiles-v1"];
const QUERY: &str = ".cmake/api/v1/query/client-openidea";
/// Where CMake writes its replies, relative to the build directory.
pub const REPLY: &str = ".cmake/api/v1/reply";
/// Asks CMake to answer [`QUERIES`] on the next configure of `build`.
pub fn write_queries(build: &Path) -> std::io::Result<()> {
let query = build.join(QUERY);
std::fs::create_dir_all(&query)?;
for name in QUERIES {
std::fs::write(query.join(name), "")?;
}
Ok(())
}
+41
Переглянути файл
@@ -314,6 +314,30 @@ pub struct SmartKeysSettings {
pub insert_doc_stub: bool,
/// Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`.
pub backspace_unindent: String,
/// The styles Cycle Identifier Case goes through.
pub cycle_case: CycleCaseSettings,
}
/// Editor › General › Smart Keys › Cycle Identifier Case: the styles the action goes through.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CycleCaseSettings {
/// `snake_case`
pub snake: bool,
/// `SCREAMING_SNAKE_CASE`
pub screaming: bool,
/// `kebab-case`
pub kebab: bool,
/// `camelCase`
pub camel: bool,
/// `PascalCase`
pub pascal: bool,
}
impl Default for CycleCaseSettings {
fn default() -> Self {
Self { snake: true, screaming: true, kebab: true, camel: true, pascal: true }
}
}
impl Default for SmartKeysSettings {
@@ -335,6 +359,7 @@ impl Default for SmartKeysSettings {
smart_indent: true,
insert_doc_stub: true,
backspace_unindent: "autoindent".into(),
cycle_case: CycleCaseSettings::default(),
}
}
}
@@ -376,6 +401,8 @@ impl Default for CodeEditingSettings {
#[serde(default, rename_all = "camelCase")]
pub struct InlayHintsSettings {
pub types: bool,
/// Inferred variable and field types from the JavaScript and TypeScript servers (on, as in WebStorm).
pub js_ts_types: bool,
pub parameters: bool,
/// Hints of other kinds (chaining, closing labels…).
pub other: bool,
@@ -411,6 +438,7 @@ impl Default for InlayHintsSettings {
fn default() -> Self {
Self {
types: true,
js_ts_types: true,
parameters: true,
other: true,
closing_labels: true,
@@ -685,6 +713,19 @@ mod folding_tests {
}
}
#[cfg(test)]
mod inlay_hints_tests {
use super::InlayHintsSettings;
#[test]
fn existing_settings_enable_js_ts_type_hints_by_default() {
let settings: InlayHintsSettings = serde_json::from_str(r#"{"parameters":false}"#).unwrap();
assert!(settings.types);
assert!(settings.js_ts_types);
assert!(!settings.parameters);
}
}
#[cfg(test)]
mod sticky_lines_tests {
use super::CodeEditingSettings;
+25
Переглянути файл
@@ -11,6 +11,14 @@ use specta::Type;
use std::collections::BTreeMap;
use std::sync::Arc;
/// The execution target recorded with an MCP agent run.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum McpAgentRunTarget {
Host,
Container { id: String },
}
/// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
@@ -27,6 +35,10 @@ pub enum McpUiRequest {
subject: String,
project: String,
detail: Option<String>,
/// The project is served without a window: the request shows in another project's window,
/// which names it and keeps the keyboard focus where it is.
#[serde(default)]
background: bool,
},
OpenFile {
path: crate::IpcPath,
@@ -38,6 +50,7 @@ pub enum McpUiRequest {
command: String,
cwd: crate::IpcPath,
env: BTreeMap<String, String>,
target: McpAgentRunTarget,
},
RunConfiguration {
#[specta(type = specta_typescript::Unknown)]
@@ -95,6 +108,8 @@ pub enum IdeEvent {
WindowGroupsChanged,
/// A project was loaded or unloaded for the MCP server without a window of its own.
McpBackgroundProjectsChanged,
/// Agent automations, run history, or session schedules changed on the host.
AutomationsChanged,
/// A window entered or left full screen, itself or as a member of a full-screen window group.
WindowFullscreenChanged,
/// This remote window's connection ended or another window took over the session.
@@ -102,6 +117,14 @@ pub enum IdeEvent {
host: String,
#[serde(default)]
taken_over: bool,
/// Plain-language explanation when a dev container exited from the OOM killer (`OOMKilled` / exit 137).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
oom_message: Option<String>,
/// Local configuration file (`devcontainer.json` or Compose file) that sets the container's limit.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
oom_config_path: Option<String>,
},
ProjectTrustChanged {
root: crate::IpcPath,
@@ -424,6 +447,8 @@ pub enum LspRefreshKind {
Inheritance,
/// The Dart server published a document's Flutter outline.
FlutterOutline,
/// Spring bean markers of open documents may have changed.
SpringBeanMarkers,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
+1
Переглянути файл
@@ -6,6 +6,7 @@
pub mod build_jobs;
pub mod cli_process;
pub mod cmake_file_api;
pub mod editor_settings;
pub mod error;
pub mod event;
+72
Переглянути файл
@@ -1,5 +1,35 @@
//! Returning freed heap pages to the OS.
use std::sync::Mutex;
use std::time::{Duration, Instant};
/// Like [`release_free_pages`], on a background thread once 2 s pass without another call:
/// closing a project or a batch of tabs frees memory in bursts, released once.
pub fn release_free_pages_soon() {
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
debounce(&DUE, Duration::from_secs(2), release_free_pages);
}
/// Runs `run` on a background thread once `delay` passes after the last call.
fn debounce(due: &'static Mutex<Option<Instant>>, delay: Duration, run: fn()) {
let idle = due.lock().unwrap().replace(Instant::now() + delay).is_none();
if idle {
std::thread::spawn(move || {
loop {
let mut slot = due.lock().unwrap();
let left = slot.map_or(Duration::ZERO, |at| at.saturating_duration_since(Instant::now()));
if left.is_zero() {
*slot = None;
drop(slot);
return run();
}
drop(slot);
std::thread::sleep(left);
}
});
}
}
/// Hands pages the allocator has freed but kept back to the OS. Call after a burst of
/// short-lived allocations (a full index scan); until then they still count towards the
/// process's memory footprint.
@@ -18,3 +48,45 @@ pub fn release_free_pages() {
libc::malloc_trim(0);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
static RUNS: AtomicUsize = AtomicUsize::new(0);
fn count() {
RUNS.fetch_add(1, SeqCst);
}
#[test]
fn a_burst_of_calls_runs_once_after_the_delay() {
// Timing-based: a loaded CI machine can oversleep, so each check allows for that.
let delay = Duration::from_millis(500);
let (mut last, mut widest_gap) = (None::<Instant>, Duration::ZERO);
for _ in 0..5 {
debounce(&DUE, delay, count);
let now = Instant::now();
widest_gap = widest_gap.max(last.map_or(Duration::ZERO, |l| now - l));
last = Some(now);
std::thread::sleep(Duration::from_millis(20));
}
if last.unwrap().elapsed() < delay {
assert_eq!(RUNS.load(SeqCst), 0, "ran before the delay passed");
}
let deadline = Instant::now() + Duration::from_secs(10);
while RUNS.load(SeqCst) == 0 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
// A second run would come within another delay.
std::thread::sleep(delay);
if widest_gap < delay {
assert_eq!(RUNS.load(SeqCst), 1);
} else {
assert!(RUNS.load(SeqCst) >= 1);
}
release_free_pages_soon();
}
}
+93
Переглянути файл
@@ -83,6 +83,24 @@ pub fn own_group(cmd: &mut Command) -> &mut Command {
cmd
}
/// Starts the child as the leader of a session of its own on Unix. Like [`own_group`] it leads
/// its process group, so [`kill_tree`] and [`terminate_tree`] reach what it starts; unlike it,
/// the child has no controlling terminal, so a tool that would ask on `/dev/tty` (and be
/// stopped there as a background job when the app was started from a shell) falls back to
/// its pipes. Use it in place of `own_group`: a group leader cannot start a session. A no-op
/// elsewhere.
pub fn own_session(cmd: &mut Command) -> &mut Command {
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// SAFETY: `setsid` is async-signal-safe and touches none of the parent's memory.
unsafe {
cmd.pre_exec(|| if libc::setsid() == -1 { Err(std::io::Error::last_os_error()) } else { Ok(()) });
}
}
cmd
}
/// Kills the child and everything it started, then reaps it.
///
/// - Unix: `SIGKILL` to its process group, so spawn it with [`own_group`].
@@ -622,6 +640,30 @@ pub fn host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
apply_changes(std::env::vars_os().collect(), &child_env_changes(Some(dir))).into_iter()
}
/// Whether `(key, value)` can go into a Windows environment block (`KEY=VALUE\0`
/// entries, then a final `\0`). `CreateProcessW` / `NtCreateUserProcess` returns
/// `ERROR_INVALID_PARAMETER` (os error 87) when an entry has an empty name or an
/// interior NUL. That happens when a `REG_MULTI_SZ` user environment value is
/// loaded into the process or re-read from the registry (#6806): the extra NUL
/// is treated as an entry separator and leaves a fragment with no `=`.
pub fn is_spawnable_env_pair(key: &OsStr, value: &OsStr) -> bool {
!key.is_empty() && !contains_ascii(key, 0) && !contains_ascii(key, b'=') && !contains_ascii(value, 0)
}
fn contains_ascii(s: &OsStr, byte: u8) -> bool {
s.as_encoded_bytes().contains(&byte)
}
/// [`host_vars`] without pairs that a Windows PTY spawn would reject.
pub fn spawnable_host_vars() -> impl Iterator<Item = (OsString, OsString)> {
host_vars().filter(|(k, v)| is_spawnable_env_pair(k, v))
}
/// [`host_vars_in`] without pairs that a Windows PTY spawn would reject.
pub fn spawnable_host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
host_vars_in(dir).filter(|(k, v)| is_spawnable_env_pair(k, v))
}
/// [`std::env::var_os`] as a child should see it (see [`host_env`]), the login shell's value
/// included when this process lacks the variable.
pub fn host_var_os(key: impl AsRef<OsStr>) -> Option<OsString> {
@@ -946,6 +988,28 @@ fn append_path_entries(path: &OsStr, extra: &OsStr) -> OsString {
mod tests {
use super::*;
#[cfg(unix)]
#[test]
fn own_session_leaves_the_controlling_terminal_behind() {
// `ps` prints `?` (Linux) or `??` (macOS) for a process without a controlling terminal.
let mut cmd = Command::new("sh");
cmd.args(["-c", "ps -o tty= -p $$"]);
let out = own_session(&mut cmd).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert!(String::from_utf8_lossy(&out.stdout).trim().chars().all(|c| c == '?'), "{:?}", out.stdout);
// Without a terminal (CI) the line above holds anyway: the child must lead a session
// of its own, which only `setsid` makes it.
let mut cmd = Command::new("sleep");
cmd.arg("5");
let mut child = own_session(&mut cmd).spawn().unwrap();
let pid = libc::pid_t::try_from(child.id()).unwrap();
// SAFETY: plain syscall on a child not reaped yet.
let session = unsafe { libc::getsid(pid) };
let _ = child.kill();
let _ = child.wait();
assert_eq!(session, pid, "the child leads its own session");
}
#[test]
fn process_alive_tells_live_from_dead_pids() {
assert!(process_alive(std::process::id()));
@@ -1240,6 +1304,35 @@ mod tests {
assert!(host_vars_in(root).all(|(k, _)| k != "OPENIDEA_PROJECT_VAR"));
}
fn os_from_bytes(bytes: &[u8]) -> OsString {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStringExt;
OsString::from_vec(bytes.to_vec())
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStringExt;
OsString::from_wide(&bytes.iter().copied().map(u16::from).collect::<Vec<_>>())
}
}
#[test]
fn spawnable_env_pairs_reject_empty_keys_equals_and_interior_nuls() {
let ok_key = OsString::from("PATH");
let ok_val = OsString::from("/bin");
assert!(is_spawnable_env_pair(&ok_key, &ok_val));
assert!(!is_spawnable_env_pair(OsStr::new(""), &ok_val));
assert!(!is_spawnable_env_pair(OsStr::new("FOO=BAR"), &ok_val));
// A REG_MULTI_SZ value's interior NUL would split the environment block,
// leaving a fragment with no `=` (#6806). An empty name is also rejected.
assert!(!is_spawnable_env_pair(&os_from_bytes(b""), &os_from_bytes(b"132786")));
assert!(!is_spawnable_env_pair(&ok_key, &os_from_bytes(b"1788051509\x00132786")));
assert!(!is_spawnable_env_pair(&os_from_bytes(b"132786\x00"), &ok_val));
assert!(spawnable_host_vars().all(|(k, v)| is_spawnable_env_pair(&k, &v)));
assert!(spawnable_host_vars().any(|(k, _)| k == "PATH" || k == "Path"));
}
#[test]
fn changes_apply_in_order() {
let vars = apply_changes(
+24 -7
Переглянути файл
@@ -5,6 +5,29 @@ use std::path::{Component, Path, PathBuf};
pub const SEARCH_DEPTH: usize = 3;
/// Folders that hold dependencies or build output rather than the project's own builds: hidden
/// folders (`.build`, `.git`), package checkouts (`node_modules`, `SourcePackages`, `Pods`,
/// `Carthage`) and build products (`target`, `build`, `DerivedData`, …).
pub fn is_skipped_dir(name: &str) -> bool {
name.starts_with('.')
|| matches!(
name,
"node_modules"
| "target"
| "build"
| "dist"
| "vendor"
| "out"
| "bin"
| "obj"
| "venv"
| "SourcePackages"
| "Pods"
| "Carthage"
| "DerivedData"
)
}
pub fn children(dir: &Path) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
let mut dirs: Vec<_> = entries
@@ -13,13 +36,7 @@ pub fn children(dir: &Path) -> Vec<PathBuf> {
if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
return false;
}
let name = entry.file_name();
let name = name.to_string_lossy();
!name.starts_with('.')
&& !matches!(
name.as_ref(),
"node_modules" | "target" | "build" | "dist" | "vendor" | "out" | "bin" | "obj" | "venv"
)
!is_skipped_dir(&entry.file_name().to_string_lossy())
})
.map(|entry| entry.path())
.collect();
+8 -1
Переглянути файл
@@ -203,6 +203,9 @@ pub enum RunTargetKind {
Docker,
/// A new container of a Compose service (`docker compose run --rm`).
Compose,
/// A WSL distribution on this Windows machine (`wsl.exe -d <distro>`), the project read
/// through `/mnt/<drive>`.
Wsl,
}
/// Build, Execution, Deployment › Run Targets: run configurations on another machine
@@ -215,7 +218,8 @@ pub struct RunTarget {
pub name: String,
/// [`SshConfiguration::id`] (SSH).
pub ssh_config: String,
/// Remote folder the project is synchronised to and run from (SSH).
/// Remote folder the project is synchronised to and run from (SSH); the project's Linux
/// path, empty = its `/mnt/<drive>` path (WSL).
pub project_root: String,
/// Upload changed project files before each run (SSH).
pub sync_before_run: bool,
@@ -223,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,
@@ -241,6 +246,8 @@ pub struct RunTarget {
pub run_options: String,
/// Run as the image's user instead of the project folder's owner (Linux).
pub image_user: bool,
/// Distribution name, as `wsl.exe -l -q` lists it (WSL).
pub distro: String,
}
/// A plugin-owned argv wrapper for project runs (API 1.4).
+271 -3
Переглянути файл
@@ -68,6 +68,8 @@ pub struct Settings {
/// Build, Execution, Deployment › Run Targets.
pub run_targets: Vec<RunTarget>,
pub cmake: CMakeSettings,
/// Build, Execution, Deployment › Toolchains; the first is the default.
pub toolchains: Vec<Toolchain>,
/// Settings › Agents.
pub agents: AgentSettings,
/// Agents › MCP Server (global only).
@@ -160,6 +162,9 @@ pub struct AgentSettings {
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, AgentMcpServer>)]
pub mcp_servers: BTreeMap<String, AgentMcpServer>,
/// Custom MCP Registry base URL (`agents.mcpRegistryUrl`); empty = GitHub MCP Registry.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub mcp_registry_url: String,
/// How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
/// files on disk are never modified.
#[serde(deserialize_with = "or_default")]
@@ -170,6 +175,15 @@ pub struct AgentSettings {
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentMemorySettings)]
pub memory: AgentMemorySettings,
/// Agent plugin bundle policies (`[agents.plugins]`): registered marketplaces and non-sensitive
/// config. Enablement lives in each harness's native config; capability consent is stored per machine.
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentPluginSettings)]
pub plugins: AgentPluginSettings,
/// Scheduled agent automations and headless scheduler host policies (`[agents.automations]`).
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentAutomationSettings)]
pub automations: AgentAutomationSettings,
}
impl Default for AgentSettings {
@@ -200,8 +214,11 @@ 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(),
automations: AgentAutomationSettings::default(),
}
}
}
@@ -240,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 {
@@ -253,6 +278,8 @@ impl Default for AgentMcpServer {
url: None,
headers: BTreeMap::new(),
agents: Vec::new(),
registry_name: None,
registry_url: None,
}
}
}
@@ -358,6 +385,96 @@ pub struct AgentMemorySettings {
pub entries: BTreeMap<String, AgentMemoryEntryPolicy>,
}
/// One agent plugin bundle's policy in Settings › Agents › Plugins
/// (`[agents.plugins.entries."<harness>:<plugin>@<marketplace>"]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentPluginEntryPolicy {
/// Non-sensitive `userConfig` / `variables` key-value pairs; sensitive values live in OS Keychain.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub config: BTreeMap<String, String>,
}
/// Agent plugin bundle settings (`[agents.plugins]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentPluginSettings {
/// Registered plugin marketplaces (`owner/repo[#ref]`, GitHub URL, or local directory/manifest path).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub marketplaces: Vec<String>,
/// Per-plugin non-sensitive native option hints, keyed by `<harness>:<plugin>@<marketplace>`.
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
#[specta(type = BTreeMap<String, AgentPluginEntryPolicy>)]
pub entries: BTreeMap<String, AgentPluginEntryPolicy>,
}
/// When OpenIDEA holds an OS idle-sleep assertion during active automation turns.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AutomationPreventSleep {
/// Prevent idle sleep while plugged into AC power.
#[default]
Ac,
/// Prevent idle sleep whenever an automated turn is running.
Always,
/// Never hold an idle-sleep assertion.
Never,
}
/// What the scheduler does when one or more scheduled occurrences fell due while asleep or offline.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AutomationMisfirePolicy {
/// Coalesce all missed occurrences into at most one catch-up run once awake and online.
#[default]
RunOnce,
/// Skip missed occurrences and advance to the next future slot.
Skip,
}
/// Agent automation and headless scheduler settings (`[agents.automations]`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentAutomationSettings {
/// Automatically register the headless login/boot scheduler service while at least one
/// automation is enabled, and unregister it when none remain enabled.
pub auto_start_service: bool,
/// Keep the local OpenIDEA host alive in the background when windows close while local
/// automations are enabled.
pub keep_alive_in_background: bool,
/// Prevent system idle sleep while an automated turn is running.
#[serde(deserialize_with = "or_default")]
#[specta(type = AutomationPreventSleep)]
pub prevent_sleep: AutomationPreventSleep,
/// Default policy for scheduled occurrences missed during sleep, offline downtime, or reboot.
#[serde(deserialize_with = "or_default")]
#[specta(type = AutomationMisfirePolicy)]
pub misfire_policy: AutomationMisfirePolicy,
/// Keep `openidea-server --daemon` alive across disconnects while the remote host has
/// enabled scheduled automations.
pub keep_remote_daemon_alive: bool,
/// Automatically remove temporary automation worktrees when a run finishes with zero diff
/// and zero commits.
pub auto_clean_worktrees: bool,
/// Maximum retained non-clean automation worktrees per automation before pruning oldest
/// finished ones.
pub max_dirty_worktrees: u32,
}
impl Default for AgentAutomationSettings {
fn default() -> Self {
Self {
auto_start_service: false,
keep_alive_in_background: true,
prevent_sleep: AutomationPreventSleep::Ac,
misfire_policy: AutomationMisfirePolicy::RunOnce,
keep_remote_daemon_alive: true,
auto_clean_worktrees: true,
max_dirty_worktrees: 5,
}
}
}
/// A hand-edited value these settings don't know reads as the default, rather than
/// failing the whole settings file.
fn or_default<'de, D, T>(d: D) -> Result<T, D::Error>
@@ -602,6 +719,8 @@ pub struct ToolDownloadSettings {
/// Maven Central, dependency version completion from Maven Central, npm, PyPI and
/// crates.io). Off by default.
pub configured_registries_only: bool,
/// The managed Vue Language Server release. Empty selects it from the project's Vue dependency.
pub vue_language_server_version: String,
}
/// Settings › Settings Sync: the Git repository the IDE settings sync through, and what syncs.
@@ -649,9 +768,42 @@ impl Default for SettingsSyncSettings {
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CMakeSettings {
#[serde(skip_serializing_if = "Option::is_none")]
/// Serialized as `null` when absent, so `cmake.profiles` stays a known settings key.
#[specta(optional)]
pub profiles: Option<Vec<CMakeProfile>>,
/// `true` ignores `CMakePresets.json` / `CMakeUserPresets.json`; otherwise every visible
/// configure preset whose condition holds is listed after the explicit profiles.
pub ignore_presets: bool,
/// Configure presets (by name) enabled as profiles. As in CLion, a preset is listed but
/// disabled until enabled here.
pub enabled_presets: Vec<String>,
/// The profile (by name) that build, run and debug use, as CLion's toolbar switcher;
/// empty or unknown = the first enabled one.
pub active_profile: String,
}
/// The presets a profile made from `CMakePresets.json` runs with.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CMakePresetRef {
pub configure: String,
/// The first build preset of `configure`, used by `cmake --build --preset`.
#[serde(skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub build: Option<String>,
/// The first test preset of `configure`, used by `ctest --preset`.
#[serde(skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub test: Option<String>,
/// Cache variables the resolved preset sets itself, read when presets are loaded (never
/// saved): a toolchain does not override them.
#[serde(skip)]
#[specta(skip)]
pub cache_variables: Vec<String>,
/// The preset names a toolchain file, which picks the compilers.
#[serde(skip)]
#[specta(skip)]
pub toolchain_file: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -665,6 +817,23 @@ pub struct CMakeProfile {
pub build_dir: String,
pub build_args: Vec<String>,
pub env: BTreeMap<String, String>,
/// `false` keeps the profile listed but unused (CLion's "Enable profile").
pub enabled: bool,
/// Toolchain name (Settings › Toolchains); empty = the default (first) toolchain.
pub toolchain: String,
/// Set only on the profiles made from presets: configure with `cmake --preset`, and the
/// generator and cache variables come from the preset.
#[serde(skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub preset: Option<CMakePresetRef>,
/// Resolved from the toolchain when profiles are put to use (never saved): the `cmake`
/// to run (`ctest` next to it) and the debugger to prefer.
#[serde(skip)]
#[specta(skip)]
pub cmake_program: Option<std::path::PathBuf>,
#[serde(skip)]
#[specta(skip)]
pub debugger: Option<std::path::PathBuf>,
}
impl Default for CMakeProfile {
@@ -677,10 +846,44 @@ impl Default for CMakeProfile {
build_dir: String::new(),
build_args: Vec::new(),
env: BTreeMap::new(),
enabled: true,
toolchain: String::new(),
preset: None,
cmake_program: None,
debugger: None,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum ToolchainKind {
/// Tools from the chosen paths, else from `PATH`.
#[default]
System,
/// A MinGW / MSYS2 directory: its `bin` goes first on `PATH`, with gcc, g++,
/// mingw32-make and gdb from there.
#[serde(rename = "mingw")]
MinGw,
}
/// Build, Execution, Deployment › Toolchains (IDE-wide, as in CLion). Empty fields are
/// detected: from the MinGW directory, else from `PATH`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct Toolchain {
pub name: String,
pub kind: ToolchainKind,
/// The MinGW directory (the one holding `bin`).
pub path: String,
pub cmake: String,
/// `CMAKE_MAKE_PROGRAM`: make, mingw32-make or ninja.
pub build_tool: String,
pub c_compiler: String,
pub cxx_compiler: String,
pub debugger: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ToolSettings {
@@ -792,6 +995,7 @@ impl Default for Settings {
deployment: DeploymentSettings::default(),
run_targets: Vec::new(),
cmake: CMakeSettings::default(),
toolchains: Vec::new(),
agents: AgentSettings::default(),
mcp_server: McpServerSettings::default(),
agent_security: AgentSecuritySettings::default(),
@@ -1157,6 +1361,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>,
@@ -1240,6 +1445,10 @@ pub struct CustomColorScheme {
pub struct EditorSettings {
pub font_family: String,
pub font_size: f32,
/// Largest document (in MiB) eligible for syntax analysis and language-server features.
#[serde(deserialize_with = "code_insight_limit_mb")]
#[specta(type = u8)]
pub max_code_insight_file_size_mb: u8,
pub line_height: f32,
pub tab_size: u32,
pub insert_spaces: bool,
@@ -1293,11 +1502,23 @@ pub struct EditorSettings {
pub encodings: EncodingSettings,
}
pub const DEFAULT_CODE_INSIGHT_LIMIT_MB: u8 = 5;
pub const MAX_CODE_INSIGHT_LIMIT_MB: u8 = 50;
fn code_insight_limit_mb<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u8, D::Error> {
Ok(serde_json::Value::deserialize(d)?
.as_u64()
.and_then(|n| u8::try_from(n).ok())
.filter(|n| (1..=MAX_CODE_INSIGHT_LIMIT_MB).contains(n))
.unwrap_or(DEFAULT_CODE_INSIGHT_LIMIT_MB))
}
impl Default for EditorSettings {
fn default() -> Self {
Self {
font_family: "JetBrains Mono".into(),
font_size: 13.0,
max_code_insight_file_size_mb: DEFAULT_CODE_INSIGHT_LIMIT_MB,
line_height: 22.0,
tab_size: 4,
insert_spaces: true,
@@ -1509,6 +1730,9 @@ pub struct MarkdownSettings {
pub preview_layout: MarkdownPreviewLayout,
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
pub preview_font_size: Option<u32>,
/// Whether `.mdx` previews ask before running JSX components/imports, run automatically in
/// trusted projects, or stay in static safe mode.
pub mdx_execution: MdxExecutionPolicy,
/// "Detect commands that can be run right from Markdown files": gutter run icons on
/// shell code blocks and on command lines in code blocks.
pub run_commands: bool,
@@ -1521,12 +1745,22 @@ impl Default for MarkdownSettings {
Self {
preview_layout: MarkdownPreviewLayout::default(),
preview_font_size: None,
mdx_execution: MdxExecutionPolicy::default(),
run_commands: true,
command_directory: None,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MdxExecutionPolicy {
#[default]
Ask,
Trusted,
Off,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MarkdownPreviewLayout {
@@ -1935,6 +2169,8 @@ pub struct MavenSettings {
pub active_profiles: String,
/// Delegate IDE build/run actions to Maven: launches build with Maven (`javac`) instead of jdtls (ECJ).
pub delegate_build: bool,
/// Maven goals (`groupId:artifactId:goal`) the IDE may skip in compile phases. Empty by default.
pub ignored_compile_goals: Vec<String>,
/// Download `-sources.jar` of dependencies when the Java language server imports the
/// project (jdtls `java.maven.downloadSources`). Off: sources are fetched on demand
/// from a library class's Download Sources banner.
@@ -2054,6 +2290,37 @@ pub struct ProjectLibrary {
pub scope: DependencyScope,
}
/// A library class entry written as a jar glob: `dir/*.jar` → `(dir, false)`, `dir/**/*.jar` → `(dir, true)`.
pub fn split_jar_glob(entry: &str) -> Option<(&str, bool)> {
let entry = entry.trim();
if let Some(base) = entry.strip_suffix("/**/*.jar").or_else(|| entry.strip_suffix(r"\**\*.jar")) {
return Some((base, true));
}
entry.strip_suffix("/*.jar").or_else(|| entry.strip_suffix(r"\*.jar")).map(|base| (base, false))
}
/// The `.jar` files in `dir` (and its subfolders when `recursive`), sorted by name per folder.
pub fn jar_files(dir: &std::path::Path, recursive: bool) -> Vec<std::path::PathBuf> {
fn walk(dir: &std::path::Path, recursive: bool, out: &mut Vec<std::path::PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
let mut entries: Vec<_> = entries.flatten().collect();
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let path = entry.path();
match entry.file_type() {
Ok(t) if t.is_dir() && recursive => walk(&path, true, out),
Ok(t) if t.is_file() && path.extension().is_some_and(|x| x.eq_ignore_ascii_case("jar")) => {
out.push(path)
}
_ => {}
}
}
}
let mut out = Vec::new();
walk(dir, recursive, &mut out);
out
}
/// Dependency entry of a module (Project Structure › Modules › Dependencies).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -2342,12 +2609,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!(
@@ -2363,6 +2630,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!({}));
}
+8
Переглянути файл
@@ -296,6 +296,14 @@ pub struct OutlineItem {
#[serde(default)]
#[specta(optional)]
pub visibility: Option<Visibility>,
/// Rust `impl Trait for Type`: the trait's name in the header (its last path segment, where go-to-definition lands), from the syntax tree.
#[serde(default)]
#[specta(optional)]
pub implements: Option<Range>,
/// Rust `impl [Trait for] Type`: the implementing type's name (its last path segment), from the syntax tree.
#[serde(default)]
#[specta(optional)]
pub self_type: Option<Range>,
}
/// Fuzzy-match highlight: indices (in chars of the displayed string) that matched.
+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]
+60 -3
Переглянути файл
@@ -27,6 +27,35 @@ pub struct VcsSettings {
pub mappings: VcsMappings,
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
pub github: GithubSettings,
/// Settings › Version Control › Subversion.
pub svn: SvnSettings,
}
/// Settings › Version Control › Subversion (`vcs.svn`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct SvnSettings {
/// Path to the svn executable; empty = auto-detect.
pub executable: String,
/// Run svn as if in a terminal: its password, passphrase and certificate prompts open
/// dialogs. Off, svn runs with `--non-interactive` and a rejected login asks once.
pub interactive: bool,
/// Pass `--config-dir config_dir` to every svn command.
pub use_custom_config_dir: bool,
pub config_dir: String,
}
impl Default for SvnSettings {
/// Interactive except on Windows: svn there asks on the console, which an IDE's child
/// process has hidden, so a prompt could not be answered (not verified on Windows yet).
fn default() -> Self {
Self {
executable: String::new(),
interactive: !cfg!(windows),
use_custom_config_dir: false,
config_dir: String::new(),
}
}
}
/// Settings › Version Control › GitHub (`vcs.github`).
@@ -80,6 +109,7 @@ impl Default for VcsSettings {
issue_navigation: Vec::new(),
mappings: VcsMappings::default(),
github: GithubSettings::default(),
svn: SvnSettings::default(),
}
}
}
@@ -447,12 +477,15 @@ pub struct BuildSettings {
pub open_tool_window: String,
/// When to focus the Build tool window: `always` | `onError` | `never`.
pub focus_tool_window: String,
/// Build an Xcode project in the background when xcode-build-server has no build log to read
/// yet, so cross-file code insight works before the first Run.
pub xcode_index_build: bool,
}
impl Default for BuildSettings {
fn default() -> Self {
// Builds open the tool window without taking focus.
Self { open_tool_window: "always".into(), focus_tool_window: "never".into() }
Self { open_tool_window: "always".into(), focus_tool_window: "never".into(), xcode_index_build: true }
}
}
@@ -530,6 +563,7 @@ pub struct DebuggerSettings {
/// Java: whether to reload changed classes into running debug sessions after compilation.
pub hot_swap_after_compile: HotSwapPolicy,
pub python: PythonDebuggerSettings,
pub cpp: CppDebuggerSettings,
}
impl Default for DebuggerSettings {
@@ -552,6 +586,7 @@ impl Default for DebuggerSettings {
flutter_hot_reload_on_save: true,
hot_swap_after_compile: HotSwapPolicy::Ask,
python: PythonDebuggerSettings::default(),
cpp: CppDebuggerSettings::default(),
}
}
}
@@ -570,6 +605,14 @@ impl Default for PythonDebuggerSettings {
}
}
/// C/C++ debugger executables. Empty paths use automatic discovery.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CppDebuggerSettings {
pub gdb_executable: String,
pub lldb_dap_executable: String,
}
/// Run/Debug configuration behaviour.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -616,13 +659,14 @@ pub struct TerminalSettings {
pub close_on_exit: bool,
pub mouse_reporting: bool,
pub copy_on_selection: bool,
/// Programs may set the clipboard with OSC 52 (tmux, Neovim, TUIs over SSH); never read it.
pub osc52_clipboard: bool,
pub paste_on_middle_click: bool,
/// Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it).
pub right_click_paste: bool,
pub override_ide_shortcuts: bool,
pub shell_integration: bool,
pub highlight_hyperlinks: bool,
pub highlight_selection: bool,
/// Highlights typed commands the IDE recognises; Run Highlighted Command runs them with it.
pub run_commands_using_ide: bool,
pub option_as_meta: bool,
@@ -656,12 +700,12 @@ impl Default for TerminalSettings {
close_on_exit: true,
mouse_reporting: true,
copy_on_selection: false,
osc52_clipboard: true,
paste_on_middle_click: true,
right_click_paste: false,
override_ide_shortcuts: true,
shell_integration: true,
highlight_hyperlinks: true,
highlight_selection: true,
run_commands_using_ide: true,
option_as_meta: false,
escape_to_editor: false,
@@ -800,4 +844,17 @@ mod tests {
assert_eq!(serialized["hotSwapAfterCompile"], raw);
}
}
#[test]
fn cpp_debugger_paths_default_to_empty_and_roundtrip() {
let missing: DebuggerSettings = serde_json::from_str("{}").unwrap();
assert!(missing.cpp.gdb_executable.is_empty());
assert!(missing.cpp.lldb_dap_executable.is_empty());
let cpp = serde_json::json!({"gdbExecutable": "tools/gdb-16", "lldbDapExecutable": "/opt/llvm/bin/lldb-dap"});
let settings: DebuggerSettings = serde_json::from_value(serde_json::json!({"cpp": cpp})).unwrap();
assert_eq!(settings.cpp.gdb_executable, "tools/gdb-16");
assert_eq!(settings.cpp.lldb_dap_executable, "/opt/llvm/bin/lldb-dap");
assert_eq!(serde_json::to_value(&settings).unwrap()["cpp"], cpp);
}
}
+92
Переглянути файл
@@ -35,6 +35,24 @@ pub fn parse(path: &Path) -> Option<WslPath> {
Some(WslPath { distro: distro.to_owned(), path: format!("/{}", tail.trim_end_matches('/')) })
}
/// The Linux path of a Windows path seen from `distro`: `C:\a` → `/mnt/c/a` (WSL's default
/// automount root), `\\wsl.localhost\<distro>\a` → `/a`. `None` for another distro's share,
/// other network shares and relative paths.
pub fn linux_path(path: &Path, distro: &str) -> Option<String> {
if let Some(w) = parse(path) {
return w.distro.eq_ignore_ascii_case(distro).then_some(w.path);
}
let s = path.to_string_lossy().replace('\\', "/");
let s = s.strip_prefix("//?/").unwrap_or(&s);
let mut chars = s.chars();
let drive = chars.next().filter(char::is_ascii_alphabetic)?;
let rest = chars.as_str().strip_prefix(':')?;
if !(rest.is_empty() || rest.starts_with('/')) {
return None;
}
Some(format!("/mnt/{}{}", drive.to_ascii_lowercase(), rest.trim_end_matches('/')))
}
/// A distro name `wsl.exe -d` can be given safely: Windows creates them from letters, digits,
/// `.`, `_` and `-`. A leading `-` would be read as an option, so it is refused too.
pub fn is_valid_distro(name: &str) -> bool {
@@ -86,6 +104,57 @@ pub fn list_distros() -> Vec<String> {
Vec::new()
}
/// Where this machine reads `distro`'s file system.
pub fn share_root(distro: &str) -> std::path::PathBuf {
format!(r"\\wsl.localhost\{distro}").into()
}
/// The names of a Linux path, `.` dropped and `..` taking the name before it.
pub fn path_parts(linux: &str) -> Vec<&str> {
let mut parts: Vec<&str> = Vec::new();
for c in linux.split('/').filter(|c| !c.is_empty() && *c != ".") {
if c == ".." {
parts.pop();
} else {
parts.push(c);
}
}
parts
}
/// Where this machine reads the absolute path `linux` of `distro`: a drive mounted at
/// `/mnt/<drive>` is read directly, anything else through [`share_root`]. `..` goes up
/// within `linux`, never above the drive or the share.
pub fn windows_path(linux: &str, distro: &str) -> std::path::PathBuf {
let parts = path_parts(linux);
let base = match parts.as_slice() {
["mnt", drive, ..] if drive.len() == 1 && drive.chars().all(|c| c.is_ascii_alphabetic()) => {
let base = std::path::PathBuf::from(format!("{}:\\", drive.to_ascii_uppercase()));
return parts[2..].iter().fold(base, |p, c| p.join(c));
}
_ => share_root(distro),
};
parts.iter().fold(base, |p, c| p.join(c))
}
/// Runs `args` in `distro` without its shell and returns the standard output; a failed
/// run is an error with its output. `wsl.exe`'s own messages are UTF-16: their NULs go.
pub fn exec(distro: &str, args: &[&str], timeout: std::time::Duration) -> crate::IdeResult<String> {
use crate::cli_process::{CliTool, Decoding};
if !is_valid_distro(distro) {
return Err(crate::IdeError::invalid(format!("'{distro}' is not a WSL distribution name")));
}
let mut cmd = std::process::Command::new(EXE);
cmd.args(["-d", distro, "--exec"]).args(args);
let out = CliTool::new(EXE, Decoding::Utf8Lossy).run(cmd, timeout, None)?;
let (stdout, stderr) = (out.stdout.replace('\0', ""), out.stderr.replace('\0', ""));
if out.success {
return Ok(stdout);
}
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
Err(crate::IdeError::internal(format!("{EXE} -d {distro} --exec {}: {detail}", args.first().unwrap_or(&""))))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -103,6 +172,21 @@ mod tests {
assert_eq!(p(r"\\?\UNC\WSL.LOCALHOST\Ubuntu-24.04\home\me\app"), want);
}
#[test]
fn windows_paths_map_onto_the_distro() {
let l = |s: &str| linux_path(Path::new(s), "Ubuntu");
assert_eq!(l(r"C:\Users\me\app"), Some("/mnt/c/Users/me/app".into()));
assert_eq!(l(r"D:\"), Some("/mnt/d".into()));
assert_eq!(l("e:/work/x/"), Some("/mnt/e/work/x".into()));
assert_eq!(l(r"\\?\C:\proj"), Some("/mnt/c/proj".into()));
assert_eq!(l(r"\\wsl.localhost\ubuntu\home\me"), Some("/home/me".into()));
assert_eq!(l(r"\\wsl$\Debian\home\me"), None);
assert_eq!(l(r"\\server\share\a"), None);
assert_eq!(l(r"C:relative"), None);
assert_eq!(l("app"), None);
assert_eq!(l("/home/me"), None);
}
#[test]
fn distro_root_and_foreign_paths() {
assert_eq!(p(r"\\wsl.localhost\Debian"), Some(("Debian".to_owned(), "/".to_owned())));
@@ -127,6 +211,14 @@ mod tests {
assert!(parse_distro_list(b"").is_empty());
}
#[test]
fn linux_paths_are_read_on_their_drive_or_through_the_share() {
use std::path::PathBuf;
assert_eq!(windows_path("/mnt/d/lib/../x.py", "U"), PathBuf::from("D:\\").join("x.py"));
assert_eq!(windows_path("/usr/lib/a.py", "U"), share_root("U").join("usr").join("lib").join("a.py"));
assert_eq!(windows_path("/mnt/wsl/x", "U"), share_root("U").join("mnt").join("wsl").join("x"));
}
#[test]
fn distro_names_cannot_smuggle_options_or_paths() {
for bad in ["", "-d", "--exec", "a b", "a/b", r"a\b", "a;b", "a$(x)", "a\"b"] {
+116 -11
Переглянути файл
@@ -360,9 +360,46 @@ fn find_binary_in(
}
/// [`find_binary`], plus Xcode's toolchain on macOS (`xcrun -f lldb-dap`): Xcode ships
/// lldb-dap without putting it on `PATH`.
/// lldb-dap without putting it on `PATH`. Elsewhere lldb-dap may carry its LLVM version.
pub fn resolve_binary(command: &str, cwd: &Path) -> Option<PathBuf> {
find_binary(command, cwd).or_else(|| xcrun_tool(command, cwd))
find_binary(command, cwd).or_else(|| xcrun_tool(command, cwd)).or_else(|| {
(command == "lldb-dap" && !cfg!(windows))
.then(|| versioned_lldb_dap(&search_dirs(cwd), Path::new("/usr/lib")))
.flatten()
})
}
/// Debian and Ubuntu install LLVM's lldb-dap as `lldb-dap-18` (`lldb-vscode-14` before
/// LLVM 18 renamed it; same protocol) on `PATH`, or only as `/usr/lib/llvm-18/bin/lldb-dap`.
/// The newest LLVM wins.
fn versioned_lldb_dap(dirs: &[PathBuf], lib: &Path) -> Option<PathBuf> {
let version = |name: &str| -> Option<u32> {
let v = name.strip_prefix("lldb-dap-").or_else(|| name.strip_prefix("lldb-vscode-"))?;
v.parse().ok()
};
let mut found: Vec<(u32, PathBuf)> = Vec::new();
for dir in dirs {
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
let path = entry.path();
if let Some(v) = path.file_name().and_then(|n| n.to_str()).and_then(version)
&& is_executable(&path, false)
{
found.push((v, path));
}
}
}
for entry in std::fs::read_dir(lib).into_iter().flatten().flatten() {
let Some(v) = entry.file_name().to_str().and_then(|n| n.strip_prefix("llvm-")?.parse::<u32>().ok()) else {
continue;
};
for name in ["lldb-dap", "lldb-vscode"] {
let path = entry.path().join("bin").join(name);
if is_executable(&path, false) {
found.push((v, path));
}
}
}
found.into_iter().max_by_key(|(v, _)| *v).map(|(_, p)| p)
}
/// `cwd`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
@@ -472,7 +509,7 @@ fn is_app_execution_alias(path: &Path) -> bool {
/// GDB's DAP interpreter (`-i dap`) shipped in GDB 14; older ones exit with
/// "Interpreter `dap' unrecognized".
const GDB_MIN_MAJOR: u32 = 14;
pub(crate) const GDB_MIN_MAJOR: u32 = 14;
/// `(major, minor)` of the first version number in the output of `gdb --version`
/// (`GNU gdb (GDB) 14.2`, `GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1`, `GNU gdb
@@ -513,24 +550,29 @@ pub fn parse_gdb_version(output: &str) -> Option<(u32, u32)> {
/// Probe the already resolved and verified executable with its launch environment.
async fn gdb_version(binary: &Path, spec: &AdapterSpec) -> IdeResult<Option<(u32, u32)>> {
Ok(probe_gdb_version(binary, &spec.cwd, &spec.env).await)
}
/// `(major, minor)` of `binary --version`, run in `cwd` with `env`; `None` when it doesn't say.
pub(crate) async fn probe_gdb_version(binary: &Path, cwd: &Path, env: &[(String, String)]) -> Option<(u32, u32)> {
let mut probe = Command::new(binary);
if let Some(path) = adapter_path(&spec.env, &spec.cwd) {
if let Some(path) = adapter_path(env, cwd) {
probe.env("PATH", path);
}
probe.current_dir(&spec.cwd);
probe.current_dir(cwd);
ide_core::process::prepare(probe.as_std_mut());
let probe = probe
.arg("--version")
.envs(spec.env.iter().cloned())
.envs(env.iter().cloned())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.output();
let Ok(Ok(out)) = tokio::time::timeout(Duration::from_secs(15), probe).await else {
return Ok(None);
return None;
};
Ok(parse_gdb_version(&String::from_utf8_lossy(&out.stdout)))
parse_gdb_version(&String::from_utf8_lossy(&out.stdout))
}
/// Refuse old GDB versions and report whether launch must follow configurationDone.
@@ -543,8 +585,9 @@ async fn prepare_gdb(spec: &AdapterSpec, binary: &Path) -> IdeResult<bool> {
return Ok(major == 15);
}
let mut msg = format!(
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor}): \
this one has no DAP interpreter (`gdb -i dap`)"
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor} at {}): \
this one has no DAP interpreter (`gdb -i dap`)",
binary.display(),
);
if let Some(hint) = &spec.install_hint {
msg.push_str(". ");
@@ -570,11 +613,20 @@ pub fn not_standalone(spec: &AdapterSpec) -> IdeError {
}
pub fn missing(spec: &AdapterSpec) -> IdeError {
let no_prebuilt = ide_core::tool_path::netcoredbg_no_prebuilt(
cfg!(all(target_os = "macos", target_arch = "x86_64")),
cfg!(all(windows, target_arch = "aarch64")),
)
.filter(|_| spec.adapter == "netcoredbg");
missing_with(spec, no_prebuilt.as_deref().or(spec.install_hint.as_deref()))
}
fn missing_with(spec: &AdapterSpec, hint: Option<&str>) -> IdeError {
let mut msg = format!(
"debug adapter `{}` not found (`{}` is neither installed by OpenIDEA nor on PATH)",
spec.adapter, spec.command
);
if let Some(hint) = &spec.install_hint {
if let Some(hint) = hint {
msg.push_str(". ");
msg.push_str(hint);
}
@@ -1026,6 +1078,48 @@ mod tests {
assert!(builtin("nope").is_none());
}
#[cfg(unix)]
#[tokio::test]
async fn gdb_version_check_probes_the_adapter_command() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let binary = dir.path().join("custom gdb");
std::fs::write(&binary, "#!/bin/sh\n[ \"$1\" = --version ] && echo 'GNU gdb (GDB) 13.2'\n").unwrap();
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut spec = resolve(&builtin("gdb").unwrap(), dir.path().to_path_buf());
spec.command = binary.to_str().unwrap().to_owned();
let Err(error) = ProcessLauncher.launch(spec, None).await else {
panic!("GDB 13 was started as a DAP adapter");
};
assert_eq!(error.kind, ide_core::error::ErrorKind::Unavailable);
assert!(error.message.contains("needs GDB 14 or newer (found 13.2 at "), "{}", error.message);
assert!(error.message.contains(binary.to_str().unwrap()), "{}", error.message);
}
/// Debian/Ubuntu's versioned lldb-dap (and lldb-vscode before LLVM 18): the newest LLVM wins.
#[cfg(unix)]
#[test]
fn finds_versioned_lldb_dap() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let exe = |p: &Path| {
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, "").unwrap();
std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o755)).unwrap();
};
let (bin, lib) = (tmp.path().join("bin"), tmp.path().join("lib"));
exe(&bin.join("lldb-vscode-14"));
std::fs::write(bin.join("lldb-dap-99"), "").unwrap(); // not executable
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(bin.join("lldb-vscode-14")));
exe(&lib.join("llvm-18/bin/lldb-dap"));
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(lib.join("llvm-18/bin/lldb-dap")));
exe(&bin.join("lldb-dap-19"));
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(bin.join("lldb-dap-19")));
assert_eq!(versioned_lldb_dap(&[], &tmp.path().join("none")), None);
}
/// The first version number of `gdb --version`'s first line, however the distro decorates it.
#[test]
fn parses_gdb_versions() {
@@ -1120,6 +1214,17 @@ mod tests {
assert!(err.message.contains("Settings › Languages & Frameworks › Language Servers"));
}
#[test]
fn missing_netcoredbg_without_a_build_says_how_to_get_one() {
let spec = resolve(&builtin("netcoredbg").unwrap(), std::env::temp_dir());
let hint = ide_core::tool_path::netcoredbg_no_prebuilt(true, false).unwrap();
let message = missing_with(&spec, Some(&hint)).message;
assert!(message.starts_with("debug adapter `netcoredbg` not found"), "{message}");
assert!(message.contains("no prebuilt netcoredbg for Intel Macs"), "{message}");
assert!(message.contains("on PATH"), "{message}");
assert_eq!(ide_core::tool_path::netcoredbg_no_prebuilt(false, false), None);
}
#[tokio::test]
async fn process_launcher_reports_missing_binary() {
let mut spec = resolve(&builtin("netcoredbg").unwrap(), std::env::temp_dir());
+23 -2
Переглянути файл
@@ -22,6 +22,7 @@ mod jvm_memory;
pub mod kotlin;
pub mod kotlin_lsp;
mod memory;
pub mod native;
mod session;
mod stream_trace;
mod swiftpm;
@@ -507,6 +508,11 @@ fn child_name(configuration: &Value, parent: &str) -> String {
}
}
/// LLDB-based adapters, which debug native programs (and Swift on Apple platforms).
fn is_native(adapter: &str) -> bool {
matches!(adapter, "lldb-dap" | "codelldb")
}
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
/// adapter.
pub const RUN_LINK: &str = "__openideaRun";
@@ -1049,6 +1055,15 @@ impl DebugManager {
if let Some(command) = custom_command(&spec.command) {
spec.command = command;
}
// The debugger of the run configuration's toolchain (a MinGW gdb), over every other choice.
if let Some(command) = arguments
.as_object_mut()
.and_then(|o| o.remove(native::ADAPTER_COMMAND))
.and_then(|v| v.as_str().map(str::to_owned))
{
spec.command = command;
spec.pinned = None;
}
// debugpy: run the adapter with the debuggee's interpreter (venvs carry their own debugpy),
// or with the launcher's when the debuggee runs through a manager (`uv run python`).
if config.adapter == "debugpy" {
@@ -1637,11 +1652,16 @@ impl DebugManager {
let _ = s.conn.request_timeout("terminate", json!({ "restart": false }), SHUTDOWN_TIMEOUT).await;
}
if !graceful && (!own_terminate || killed) {
// A native attach to a program a run started for the debugger (an Xcode app launched
// with `simctl launch --wait-for-debugger`) ends it too: detached, the app can be
// left stopped with the SIGTERM the run's Stop sent while it was traced, and the
// simulator then holds its launch (and the next one) forever.
let ends_debuggee = s.request == "launch" || (terminate && s.run.is_some() && is_native(&s.adapter));
let _ = s
.conn
.request_timeout(
"disconnect",
json!({ "restart": false, "terminateDebuggee": s.request == "launch" }),
json!({ "restart": false, "terminateDebuggee": ends_debuggee }),
SHUTDOWN_TIMEOUT,
)
.await;
@@ -1785,7 +1805,8 @@ impl DebugManager {
let mut states = self.states.lock();
let Some(slot) = states.get_mut(path).and_then(|v| v.get_mut(index)) else { return false };
let next = session::state_from(bp, slot.line);
let next = BreakpointState { message: next.message.or_else(|| slot.message.clone()), ..next };
let kept = slot.message.clone().filter(|m| !(next.verified && m == session::UNBOUND_NATIVE));
let next = BreakpointState { message: next.message.or(kept), ..next };
let changed = *slot != next;
*slot = next;
changed
+232
Переглянути файл
@@ -0,0 +1,232 @@
//! C/C++ launches made for lldb-dap (CMake, Swift packages) fall back to CodeLLDB, then to
//! GDB 14 or newer, when the host has no lldb-dap: Linux hosts rarely put one on `PATH`, and
//! CodeLLDB is the debugger OpenIDEA can install itself.
use crate::LaunchConfig;
use crate::adapter::{GDB_MIN_MAJOR, probe_gdb_version};
use ide_core::{IdeError, IdeResult};
use serde_json::{Map, Value, json};
use std::path::{Path, PathBuf};
/// Launch argument naming the debugger to run (a toolchain's gdb or lldb-dap), which replaces
/// the search: lldb-dap if its name says so, else GDB.
pub const ADAPTER_COMMAND: &str = "__adapterCommand";
/// Prefix of the error when none of them is there; the UI offers to install CodeLLDB on it.
pub const NO_NATIVE_DEBUGGER: &str = "No C/C++ debugger found";
/// `config` for the first of lldb-dap, CodeLLDB and GDB 14+ that `lookup` finds (it resolves a
/// debugger command: a configured tool path, else the search path). Other launches pass through.
pub async fn choose(
mut config: LaunchConfig,
lookup: impl Fn(&str) -> Option<PathBuf> + Send + 'static,
) -> IdeResult<LaunchConfig> {
if config.adapter != "lldb-dap" || config.request != "launch" {
return Ok(config);
}
let chosen = config
.extra_json
.as_deref()
.and_then(|e| serde_json::from_str::<Value>(e).ok())
.and_then(|e| e[ADAPTER_COMMAND].as_str().map(PathBuf::from));
let found = tokio::task::spawn_blocking(move || {
if let Some(chosen) = chosen {
let name = chosen.file_stem().map(|s| s.to_string_lossy().to_lowercase()).unwrap_or_default();
return if name.contains("lldb-dap") { Found::LldbDap } else { Found::Gdb(chosen) };
}
if lookup("lldb-dap").is_some() {
return Found::LldbDap;
}
if lookup("codelldb").is_some() {
return Found::CodeLldb;
}
lookup("gdb").map_or(Found::Nothing, Found::Gdb)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
let cwd = config.cwd.clone().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"));
match found {
Found::LldbDap => {}
Found::CodeLldb => convert(&mut config, "codelldb")?,
Found::Gdb(gdb) => match probe_gdb_version(&gdb, &cwd, &[]).await {
Some((major, minor)) if major < GDB_MIN_MAJOR => return Err(missing(Some((&gdb, major, minor)))),
// Unknown versions are left to GDB itself, as a GDB launch does.
_ => convert(&mut config, "gdb")?,
},
Found::Nothing => return Err(missing(None)),
}
Ok(config)
}
enum Found {
LldbDap,
CodeLldb,
Gdb(PathBuf),
Nothing,
}
fn missing(gdb: Option<(&Path, u32, u32)>) -> IdeError {
let found = match gdb {
Some((path, major, minor)) => format!(
"lldb-dap and CodeLLDB are not installed, and GDB {major}.{minor} at {} cannot debug through DAP \
(it needs GDB {GDB_MIN_MAJOR} or newer)",
path.display(),
),
None => "lldb-dap, CodeLLDB and GDB are not installed".to_owned(),
};
IdeError::unavailable(format!(
"{NO_NATIVE_DEBUGGER}: {found}. Install CodeLLDB, or install lldb-dap or GDB {GDB_MIN_MAJOR} or newer on this host"
))
}
/// Rewrites an lldb-dap launch for `to` (`codelldb` or `gdb`). lldb-dap takes the environment as
/// `KEY=VALUE` strings and the source map as pairs; the others take the run configuration's
/// environment map (`config.env`), CodeLLDB its source map as an object, GDB none.
fn convert(config: &mut LaunchConfig, to: &str) -> IdeResult<()> {
let mut extra = match config.extra_json.as_deref().filter(|e| !e.trim().is_empty()).map(serde_json::from_str) {
None => Map::new(),
Some(Ok(Value::Object(extra))) => extra,
Some(Ok(other)) => return Err(IdeError::invalid(format!("launch arguments are not an object: {other}"))),
Some(Err(e)) => return Err(IdeError::invalid(format!("invalid launch JSON: {e}"))),
};
extra.remove("env");
let source_map = extra.remove("sourceMap");
if to == "codelldb" {
if let Some(Value::Array(pairs)) = source_map {
let map: Map<String, Value> = pairs
.iter()
.filter_map(|pair| match pair.as_array().map(Vec::as_slice) {
Some([Value::String(from), to]) => Some((from.clone(), to.clone())),
_ => None,
})
.collect();
if !map.is_empty() {
extra.insert("sourceMap".into(), Value::Object(map));
}
}
// CodeLLDB evaluates as Rust unless told otherwise (ide-dap's default for it).
let language = if extra.contains_key("swiftpm") { "swift" } else { "cpp" };
extra.entry("sourceLanguages").or_insert_with(|| json!([language]));
}
config.adapter = to.to_owned();
config.extra_json = (!extra.is_empty()).then(|| Value::Object(extra).to_string());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
fn cmake_launch() -> LaunchConfig {
LaunchConfig {
name: "hello".into(),
adapter: "lldb-dap".into(),
request: "launch".into(),
program: Some("/home/dev/hello/build/hello".into()),
args: vec![],
cwd: Some(std::path::PathBuf::from("/").into()),
env: BTreeMap::from([("A".into(), "1".into())]),
extra_json: Some(json!({"env": ["A=1"], "sourceMap": [["/src", "/real/src"]]}).to_string()),
}
}
fn extra(config: &LaunchConfig) -> Value {
config.extra_json.as_deref().map_or(Value::Null, |e| serde_json::from_str(e).unwrap())
}
fn only(names: &'static [&'static str]) -> impl Fn(&str) -> Option<PathBuf> + Send + 'static {
move |c| names.contains(&c).then(|| PathBuf::from(format!("/usr/bin/{c}")))
}
#[tokio::test]
async fn keeps_lldb_dap_when_it_is_there() {
let config = choose(cmake_launch(), only(&["lldb-dap", "codelldb", "gdb"])).await.unwrap();
assert_eq!(config.adapter, "lldb-dap");
assert_eq!(config.extra_json, cmake_launch().extra_json);
}
#[tokio::test]
async fn falls_back_to_codelldb_with_its_launch_shape() {
let config = choose(cmake_launch(), only(&["codelldb", "gdb"])).await.unwrap();
assert_eq!(config.adapter, "codelldb");
assert_eq!(config.env, cmake_launch().env, "the environment comes from the run configuration's map");
assert_eq!(
extra(&config),
json!({"sourceMap": {"/src": "/real/src"}, "sourceLanguages": ["cpp"]}),
"no KEY=VALUE env strings; the source map as an object; C++ evaluation"
);
}
#[tokio::test]
async fn a_swift_package_evaluates_swift_under_codelldb() {
let mut launch = cmake_launch();
launch.extra_json = Some(json!({"env": [], "swiftpm": {"product": "app", "buildArgs": []}}).to_string());
let config = choose(launch, only(&["codelldb"])).await.unwrap();
assert_eq!(extra(&config)["sourceLanguages"], json!(["swift"]));
assert_eq!(extra(&config)["swiftpm"]["product"], "app");
}
#[tokio::test]
async fn a_toolchain_debugger_replaces_the_search() {
let mut launch = cmake_launch();
launch.extra_json = Some(json!({"env": ["A=1"], ADAPTER_COMMAND: "/opt/mingw/bin/gdb.exe"}).to_string());
// lldb-dap is there, but the toolchain names its GDB (an unknown version is left to GDB).
let config = choose(launch, only(&["lldb-dap"])).await.unwrap();
assert_eq!(config.adapter, "gdb");
assert_eq!(extra(&config)[ADAPTER_COMMAND], "/opt/mingw/bin/gdb.exe", "kept for the adapter launch");
let mut launch = cmake_launch();
launch.extra_json = Some(json!({ADAPTER_COMMAND: "/opt/llvm/bin/lldb-dap"}).to_string());
assert_eq!(choose(launch, only(&[])).await.unwrap().adapter, "lldb-dap");
}
#[tokio::test]
async fn without_any_debugger_says_what_to_install() {
let e = choose(cmake_launch(), only(&[])).await.unwrap_err();
assert_eq!(e.kind, ide_core::error::ErrorKind::Unavailable);
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
assert!(e.message.contains("Install CodeLLDB"), "{}", e.message);
}
#[tokio::test]
async fn other_launches_pass_through() {
let mut attach = cmake_launch();
attach.request = "attach".into();
assert_eq!(choose(attach, only(&[])).await.unwrap().adapter, "lldb-dap");
let mut rust = cmake_launch();
rust.adapter = "codelldb".into();
assert_eq!(choose(rust, only(&[])).await.unwrap().adapter, "codelldb");
}
#[cfg(unix)]
fn fake_gdb(dir: &Path, version: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let gdb = dir.join("gdb");
std::fs::write(&gdb, format!("#!/bin/sh\necho '{version}'\n")).unwrap();
std::fs::set_permissions(&gdb, std::fs::Permissions::from_mode(0o755)).unwrap();
gdb
}
/// Ubuntu 22.04's GDB 12 has no DAP interpreter: the error names its version (#7001).
#[cfg(unix)]
#[tokio::test]
async fn an_old_gdb_is_named_in_the_error() {
let dir = tempfile::tempdir().unwrap();
let gdb = fake_gdb(dir.path(), "GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1");
let path = gdb.clone();
let e = choose(cmake_launch(), move |c| (c == "gdb").then(|| path.clone())).await.unwrap_err();
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
assert!(e.message.contains("GDB 12.1"), "{}", e.message);
assert!(e.message.contains(gdb.to_str().unwrap()), "{}", e.message);
}
#[cfg(unix)]
#[tokio::test]
async fn falls_back_to_a_gdb_with_dap() {
let dir = tempfile::tempdir().unwrap();
let gdb = fake_gdb(dir.path(), "GNU gdb (GDB) 14.2");
let config = choose(cmake_launch(), move |c| (c == "gdb").then(|| gdb.clone())).await.unwrap();
assert_eq!(config.adapter, "gdb");
assert_eq!(extra(&config), Value::Null, "GDB takes the environment map and has no source map");
}
}
+21 -7
Переглянути файл
@@ -293,6 +293,11 @@ impl Suspension {
/// symlinked path (`/tmp/game` while the editor has `/private/tmp/game`).
const RESOLVES_PATHS: &[&str] = &["godot"];
/// LLDB answers a breakpoint it can't bind yet with no reason: the code may simply not be loaded.
const NATIVE_ADAPTERS: &[&str] = &["lldb-dap", "codelldb"];
/// One literal: the UI looks it up in the text catalogs to translate it.
pub(crate) const UNBOUND_NATIVE: &str = "No loaded code at this line yet. If it stays unbound after its module loads, the debug info may record this file under another path (through a symlink, or /tmp for /private/tmp): set a source map from that path to this one";
impl Session {
#[allow(clippy::too_many_arguments)]
pub fn new(
@@ -514,6 +519,9 @@ impl Session {
ids.insert(id, (path.to_path_buf(), i));
}
states[i] = state_from(r, breakpoints[i].line);
if !states[i].verified && states[i].message.is_none() && NATIVE_ADAPTERS.contains(&self.adapter.as_str()) {
states[i].message = Some(UNBOUND_NATIVE.to_owned());
}
}
Ok(states)
}
@@ -1134,21 +1142,27 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
// CodeLLDB's launcher clears the terminal first; the console keeps the session's earlier output.
cmd.args(rest.iter().filter(|a| *a != "--clear-screen"));
let cwd = args.get("cwd").and_then(Value::as_str).filter(|c| !c.is_empty()).map_or(s.spec.cwd.as_path(), Path::new);
for (k, v) in ide_core::process::host_env_fixes_in(cwd) {
match v {
Some(v) => cmd.env(k, v),
None => cmd.env_remove(k),
}
// See #6806: do not inherit portable-pty's registry-built Windows env block.
cmd.env_clear();
for (k, v) in ide_core::process::spawnable_host_vars_in(cwd) {
cmd.env(k, v);
}
for (k, v) in ide_core::process::shell_env_in(cwd) {
cmd.env(k, v);
if ide_core::process::is_spawnable_env_pair(&k, &v) {
cmd.env(k, v);
}
}
cmd.env("TERM", "xterm-256color");
cmd.cwd(cwd);
if let Some(env) = args.get("env").and_then(Value::as_object) {
for (k, v) in env {
match v.as_str() {
Some(v) => cmd.env(k, v),
Some(v)
if ide_core::process::is_spawnable_env_pair(std::ffi::OsStr::new(k), std::ffi::OsStr::new(v)) =>
{
cmd.env(k, v)
}
Some(_) => {}
None => cmd.env_remove(k),
};
}
+48 -1
Переглянути файл
@@ -138,6 +138,8 @@ struct Script {
output_after_terminate: bool,
/// Advertise `supportsTerminateRequest` (java-debug does not, so Stop signals the program).
supports_terminate: bool,
/// Answer `setBreakpoints` with unverified breakpoints and no reason (LLDB before the code loads).
unbound_breakpoints: bool,
/// Answer `setBreakpoints` only once this many are waiting (a client that waits for each never gets one).
hold_set_breakpoints: usize,
/// Send a `continued` event right after the first `stopped` one.
@@ -220,6 +222,7 @@ impl Default for Script {
fn default() -> Self {
Self {
run_in_terminal: None,
unbound_breakpoints: false,
start_debugging: false,
child_request: None,
ignore_configuration_done: false,
@@ -414,7 +417,7 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
.unwrap()
.iter()
.enumerate()
.map(|(i, b)| json!({"id": i + 1, "verified": true, "line": b["line"]}))
.map(|(i, b)| json!({"id": i + 1, "verified": !script.unbound_breakpoints, "line": b["line"]}))
.collect();
ok!(msg, json!({"breakpoints": bps}));
}
@@ -4019,6 +4022,50 @@ async fn stop_detaches_from_an_attached_program() {
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
}
/// Xcode Debug: lldb-dap attaches to the app a run launched suspended. Stop ends the app through
/// the debugger; detaching would leave it stopped with the run's SIGTERM, holding the simulator.
#[tokio::test]
async fn stop_ends_a_native_program_a_run_started_for_the_debugger() {
let h = harness(Script::default());
let linked = |adapter: &str| LaunchConfig {
adapter: adapter.into(),
request: "attach".into(),
extra_json: Some(json!({ RUN_LINK: 7, "pid": 4242 }).to_string()),
..config()
};
let id = h.start(linked("lldb-dap")).await.unwrap();
h.manager.stop(id).await.unwrap();
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], true);
// Another adapter's attach to a run (a Gradle test worker JVM) still only detaches.
let h = harness(Script::default());
let id = h.start(linked("debugpy")).await.unwrap();
h.manager.stop(id).await.unwrap();
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
}
/// LLDB leaves a breakpoint it can't bind unverified without a reason: say what may be wrong
/// (#6665 E1b: Xcode's debug info had `/tmp/…` for a project under `/private/tmp`).
#[tokio::test]
async fn an_unbound_native_breakpoint_says_why() {
for (adapter, hint) in [("lldb-dap", true), ("codelldb", true), ("debugpy", false)] {
let h = harness(Script { unbound_breakpoints: true, ..Script::default() });
h.start(LaunchConfig { adapter: adapter.into(), ..config() }).await.unwrap();
let path = PathBuf::from("/private/tmp/app/Counter.swift");
let states = h.manager.set_breakpoints(&h.owner.key, path, vec![bp(6)]).await.unwrap();
assert!(!states[0].verified);
assert_eq!(states[0].message.as_deref() == Some(crate::session::UNBOUND_NATIVE), hint, "{adapter}");
}
// Bound once the module loads (lldb-dap's `breakpoint` event has no message): the hint goes.
let path = PathBuf::from("/private/tmp/app/Counter.swift");
let h = harness(Script { unbound_breakpoints: true, ..Script::default() });
h.start(LaunchConfig { adapter: "lldb-dap".into(), ..config() }).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(6)]).await.unwrap();
assert!(h.manager.update_breakpoint_state(&path, 0, &json!({"id": 1, "verified": true, "line": 7})));
assert_eq!(h.manager.breakpoint_states(&path)[0].message, None);
}
#[tokio::test]
async fn cell_breakpoints_go_only_to_their_notebooks_kernel_session() {
use crate::jvm_memory::test_support::bare_session_of;
Loaded 100 of 2190 files, more files were not shown because too many files have changed in this diff. Show more