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

...
Автор SHA1 Повідомлення Дата
l0ng-ai c00016db8a fix(plugins): load precompiled plugin components in the signed macOS app
compile_cached loaded the cached .cwasm with Component::deserialize_file,
which maps the file and makes its pages executable. The hardened runtime
of the signed app refuses that ("unable to make memory executable:
Permission denied"), so every activation logged "discarding precompiled
... failed to load code", deleted the cache file and compiled the plugin
again. The file is now read into memory and deserialized from the bytes,
which wasmtime copies into memory the app may make executable.

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

Closes #6925

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

Fixes #6940

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

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

Fixes #6930

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

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

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

Fixes #5586

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

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

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

Closes #6960

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

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

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

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

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

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

Closes #6975

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

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

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

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

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

Closes #6947

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

Closes #6943

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

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

Closes #6927

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

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

Closes #6901

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

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

Closes #6900

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

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

Closes #6907

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

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

Closes #6913

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

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

Closes #6915

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

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

Closes #6910

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

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

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

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

Closes #6897

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

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

Closes #6887

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fixes #4733

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

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

Fixes #5570

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

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

Refs #6142, #6701

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

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

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

Closes #6810

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

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

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

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

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

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

Fixes #5514

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

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

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

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

Closes #6842

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

Closes #6845

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

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

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

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

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

Refs #404

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

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

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

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

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

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

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

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

Closes #6801

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

Closes #6797

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

Closes #6795

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

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

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

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

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

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

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

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

Closes #6177

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

Part of #334

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

Part of #6306

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

Closes #6521

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

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

Part of #5922

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

Closes #5921

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

Closes #6295

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

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

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

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

Closes #6761

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

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

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

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

Closes #6758

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

Closes #6796

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

Closes #6785

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

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

Closes #6788

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

Closes #6787

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

Closes #6786

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

Closes #6789

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

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

Closes #6750

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

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

Closes #6744

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

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

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

Closes #6713

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

Closes #6695

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

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

Closes #6681

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

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

Closes #6526

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

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

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

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

Closes #6716

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

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

Closes #6715

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

Closes #6714

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

Closes #6712

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

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

Closes #6773


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

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

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

Closes #6719

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

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

Closes #6682

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

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

Closes #6679

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

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

Closes #6533

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

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

Closes #6646

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

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

Closes #6532

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

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

Closes #6644

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

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

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

Closes #6743

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

Closes #6732

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

Closes #6664

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

Closes #6723

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

Closes #6690

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

Closes #6687

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

Closes #6672

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

Closes #6726

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

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

Closes #6737

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

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

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

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

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

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

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

Closes #6762

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

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

Closes #6774

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fixes #6751

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

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

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

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

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

Refs #4658

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

Fixes #6717

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

Closes #6710.

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

Closes #6685.

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

Closes #6631.

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

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

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

Closes #6727.

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

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

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

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

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

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

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

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

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

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

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

Closes #6666.

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

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

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

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

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

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

Closes #6699.

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

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

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

Closes #5538

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

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

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

Refs #6514

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

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

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

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

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

Closes #6652

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

Co-authored-by: HandsomeXi <[email protected]>
2026-11-28 14:36:10 +08:00
1290 змінених файлів з 79432 додано та 5402 видалено

No files matched your search

+9
Переглянути файл
@@ -0,0 +1,9 @@
# Keeps the commit SHAs the workflows pin their actions to current (the trailing comment names
# the release each SHA comes from).
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule: { interval: weekly }
groups:
actions: { patterns: ["*"] }
+1 -1
Переглянути файл
@@ -12,7 +12,7 @@ jobs:
cancel:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v8
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
script: |
// A merged or closed PR's remaining CI only holds runners other PRs wait for.
+42 -34
Переглянути файл
@@ -106,7 +106,8 @@ jobs:
if: needs.changes.outputs.rust == 'true'
permissions:
contents: read
timeout-minutes: 60
# A Windows build that misses the Rust cache spends ~50 minutes compiling before the tests run.
timeout-minutes: ${{ matrix.os == 'windows-latest' && 75 || 60 }}
strategy:
fail-fast: false
matrix:
@@ -115,22 +116,24 @@ jobs:
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { components: "clippy, rustfmt" }
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
# (only main saves it because saving takes minutes on Windows; PRs restore main's).
- uses: Swatinem/rust-cache@v2
# A failing test run on main still saves it, so the next PR doesn't compile from scratch.
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: runner.environment != 'self-hosted'
with:
save-if: ${{ github.ref == 'refs/heads/main' }}
cache-on-failure: true
# The persistent target dir makes incremental builds pay off; cap its size so it can't fill the disk.
- name: Persistent Cargo target dir
if: runner.environment == 'self-hosted'
@@ -142,7 +145,8 @@ jobs:
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
rm -rf "$CARGO_TARGET_DIR"
fi
- uses: taiki-e/install-action@nextest
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
with: { tool: nextest }
- name: Linux deps
if: runner.os == 'Linux'
run: |
@@ -159,10 +163,10 @@ jobs:
- name: Restore Maven artifacts for Java build tests
id: jbuild-maven-cache
if: runner.environment == 'github-hosted'
uses: actions/cache/restore@v5
uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: jbuild-maven-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
key: jbuild-maven-v2-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
- name: Prepare Maven artifacts for Java build tests
id: jbuild-maven
if: runner.environment == 'github-hosted'
@@ -179,10 +183,13 @@ jobs:
if [[ "$CACHE_HIT" == true ]]; then
exit 0
fi
# The IDE also reads the compiler plugin descriptor when it builds the Maven model.
# The Java tests read the compiler descriptor and run Maven launch and rebuild.
for delay in 0 10 30; do
sleep "$delay"
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml resources:resources compiler:compile; then
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml \
clean resources:resources compiler:compile \
org.apache.maven.plugins:maven-dependency-plugin:3.8.1:get \
-Dartifact=org.slf4j:slf4j-api:1.7.36; then
echo "prepared=true" >> "$GITHUB_OUTPUT"
exit 0
fi
@@ -190,7 +197,7 @@ jobs:
exit 1
- name: Save Maven artifacts for Java build tests
if: steps.jbuild-maven.outputs.prepared == 'true'
uses: actions/cache/save@v5
uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
@@ -235,10 +242,10 @@ jobs:
timeout-minutes: 40
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: x86_64-unknown-linux-musl }
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: runner.environment != 'self-hosted'
with: { key: server-musl }
- name: Persistent Cargo target dir
@@ -264,13 +271,13 @@ jobs:
timeout-minutes: 30
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: wasm32-wasip2, components: "clippy, rustfmt" }
- if: runner.environment != 'self-hosted'
shell: bash
run: echo "CARGO_TARGET_DIR=$GITHUB_WORKSPACE/target-plugins" >> "$GITHUB_ENV"
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: runner.environment != 'self-hosted'
with:
key: plugins
@@ -300,9 +307,9 @@ jobs:
cargo test --locked --manifest-path "$dir/Cargo.toml"
echo "::endgroup::"
done
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with: { node-version: 22, package-manager-cache: false }
# Plugin web pages (`web-src/`, their own pnpm projects): typecheck and test.
- name: Web pages typecheck and test
@@ -329,9 +336,10 @@ jobs:
timeout-minutes: 15
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: taiki-e/install-action@cargo-deny
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
with: { tool: cargo-deny }
- run: cargo deny check
frontend:
@@ -341,13 +349,13 @@ jobs:
timeout-minutes: 30
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
# scripts/smoke-paths.test.ts runs `cargo metadata`, which is not preinstalled in the runner container.
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
if: runner.environment == 'self-hosted'
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -368,10 +376,10 @@ jobs:
timeout-minutes: 15
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -390,10 +398,10 @@ jobs:
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -401,7 +409,7 @@ jobs:
- run: pnpm install --frozen-lockfile
- run: pnpm exec playwright install --with-deps chromium
- run: pnpm e2e --shard=${{ matrix.shard }}/4
- uses: actions/upload-artifact@v6
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
if: failure()
with:
name: playwright-report-${{ matrix.shard }}
+3 -2
Переглянути файл
@@ -21,6 +21,7 @@ concurrency:
jobs:
mirror:
environment: release
runs-on: ubuntu-latest
timeout-minutes: 120
env:
@@ -35,10 +36,10 @@ jobs:
echo "::notice::CNB_TOKEN unset: not mirroring $TAG"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.token.outputs.skip != 'true'
with: { sparse-checkout: scripts }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.token.outputs.skip != 'true'
with: { node-version: 22 }
- name: Download release
+4 -3
Переглянути файл
@@ -23,6 +23,7 @@ concurrency:
jobs:
cask:
environment: release
runs-on: ubuntu-latest
timeout-minutes: 30
env:
@@ -41,16 +42,16 @@ jobs:
echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.check.outputs.skip != 'true'
with: { sparse-checkout: scripts }
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.check.outputs.skip != 'true'
with:
repository: ${{ env.TAP }}
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
path: tap
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.check.outputs.skip != 'true'
with: { node-version: 22 }
- name: Download DMGs
+21 -16
Переглянути файл
@@ -34,6 +34,7 @@ on:
- "src/editor/relatedProviders.ts"
- "src/editor/core/cm/cornerInset.ts"
- "src/editor/core/cm/iconArea.ts"
- "src/editor/core/cm/localAppearance.ts"
- "src/editor/lsp/availability.ts"
- "src/editor/lsp/diagnostics.ts"
- "src/editor/lsp/files.ts"
@@ -106,9 +107,9 @@ jobs:
# SDKs, build tools, the project model, Find Usages candidates, debug stream traces):
# cargo metadata, ide-host's direct deps ide-search/ide-streams and the deps of
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea)|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|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
@@ -154,9 +155,9 @@ jobs:
# stripping local-variable debuginfo from fixtures debugged in the smoke job (CodeLLDB).
CARGO_PROFILE_DEV_DEBUG: line-tables-only
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: runner.environment != 'self-hosted'
with:
shared-key: language-smoke
@@ -183,7 +184,7 @@ jobs:
test -x smoke-bin/language_smoke && test -x smoke-bin/project_smoke
# A tar keeps the executable bits, which artifacts drop.
tar -cf smoke-bin.tar smoke-bin
- uses: actions/upload-artifact@v6
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
smoke:
@@ -202,20 +203,20 @@ jobs:
env:
CARGO_MANIFEST_DIR: ${{ github.workspace }}/crates/ide-host
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
# Tool versions, shared with the evals (pnpm eval).
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { components: "rust-analyzer, rustfmt" }
- uses: actions/download-artifact@v6
- uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0
with: { name: smoke-bin }
- run: |
tar -xf smoke-bin.tar && rm smoke-bin.tar
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -241,19 +242,19 @@ jobs:
fi
- if: matrix.language == 'python'
uses: actions/setup-python@v5
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
with: { python-version: "3.12" }
- if: matrix.language == 'python'
run: pip install "basedpyright==$BASEDPYRIGHT" "ruff==$RUFF"
- if: matrix.language == 'go'
uses: actions/setup-go@v5
uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
with: { go-version: "1.27", cache: false }
- if: matrix.language == 'go'
run: go install "golang.org/x/tools/gopls@$GOPLS"
- if: matrix.language == 'java' || matrix.language == 'kotlin'
uses: actions/setup-java@v4
uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
- if: matrix.language == 'java'
run: |
@@ -265,7 +266,7 @@ jobs:
# The Kotlin fixture has no Gradle wrapper: the server imports it with the Gradle on PATH.
- if: matrix.language == 'kotlin'
uses: gradle/actions/setup-gradle@v4
uses: gradle/actions/setup-gradle@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
with: { gradle-version: "${{ env.GRADLE }}" }
- if: matrix.language == 'kotlin'
run: |
@@ -277,7 +278,7 @@ jobs:
# Xdebug for the debug smoke; Composer installs the fixture's Pest for the run smoke.
- if: matrix.language == 'php'
uses: shivammathur/setup-php@v2
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
with: { php-version: "8.5", coverage: xdebug, tools: composer }
- if: matrix.language == 'php'
run: npm install --global "intelephense@$INTELEPHENSE"
@@ -285,6 +286,10 @@ jobs:
# The binaries from the build job, run from the crate directory as `cargo test` does.
- working-directory: crates/ide-host
run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }}
# Problems › TypeScript Project Errors runs the project's own tsc: the global install stands in.
- if: matrix.language == 'typescript'
working-directory: crates/ide-host
run: ../../smoke-bin/language_smoke --ignored --exact typescript_project_errors typescript_import_style
- if: matrix.language == 'java'
working-directory: crates/ide-host
run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
+104
Переглянути файл
@@ -0,0 +1,104 @@
name: Nightly
# Builds main every night, when it has moved since the last nightly, into a prerelease
# v<next patch>-nightly.<date> (scripts/nightly-prepare.ts: the tag points at a commit on top of
# main that only sets the version). Nightly apps update from the rolling `nightly` release, which
# holds the newest nightly's latest.json; stable apps read releases/latest, which is never a
# prerelease, so they never see a nightly. The newest 14 nightlies are kept.
on:
schedule:
- cron: "0 18 * * *" # 02:00 Beijing
workflow_dispatch:
inputs:
force:
description: "Build even when main has not changed since the last nightly"
type: boolean
default: false
permissions:
contents: read
concurrency:
group: nightly
jobs:
prepare:
if: github.repository == 'l0ng-ai/openidea'
permissions:
contents: write
runs-on: ubuntu-latest
outputs:
tag: ${{ steps.tag.outputs.tag }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with: { ref: main, fetch-depth: 0 }
- id: changed
env:
FORCE: ${{ inputs.force == true }}
run: |
last="$(git tag --list 'v*-nightly.*' --sort=-creatordate | head -1)"
if [ "$FORCE" != true ] && [ -n "$last" ] && [ "$(git rev-parse "$last^")" = "$(git rev-parse HEAD)" ]; then
echo "::notice::main has not changed since $last"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.changed.outputs.skip != 'true'
with: { node-version: 22 }
- name: Version commit and tag
id: tag
if: steps.changed.outputs.skip != 'true'
env:
BUILD: ${{ github.run_number }}
run: |
version="$(node scripts/nightly-prepare.ts --date "$(date -u +%Y%m%d)" --build "$BUILD" | tail -1)"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add -A
git commit -q -m "chore: v$version"
git tag "v$version"
# Pushed with GITHUB_TOKEN, the tag does not start release.yml: the job below calls it.
git push origin "refs/tags/v$version"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
release:
needs: prepare
if: needs.prepare.outputs.tag != ''
permissions:
contents: write
uses: ./.github/workflows/release.yml
with:
tag: ${{ needs.prepare.outputs.tag }}
nightly: true
secrets: inherit
# Points the nightly channel at the new nightly and drops the old ones.
channel:
needs: [prepare, release]
permissions:
contents: write
runs-on: ubuntu-latest
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
TAG: ${{ needs.prepare.outputs.tag }}
steps:
- name: Nightly manifest
run: |
if ! gh release download "$TAG" -p latest.json -D "$RUNNER_TEMP/manifest"; then
echo "::warning::$TAG has no latest.json (unsigned build): the nightly channel stays where it was"
exit 0
fi
notes="The update channel of the [nightly builds](https://github.com/$GH_REPO/releases?q=nightly&expanded=true): its latest.json is the newest nightly's, [$TAG](https://github.com/$GH_REPO/releases/tag/$TAG)."
if gh release view nightly >/dev/null 2>&1; then
gh release edit nightly --notes "$notes"
else
gh release create nightly --prerelease --target main --title "OpenIDEA Nightly" --notes "$notes"
fi
gh release upload nightly "$RUNNER_TEMP/manifest/latest.json" --clobber
- name: Drop old nightlies
run: |
gh release list --limit 200 --json tagName,createdAt \
--jq '[.[] | select(.tagName | test("^v.*-nightly\\."))] | sort_by(.createdAt) | reverse | .[14:][] | .tagName' |
while read -r old; do
gh release delete "$old" --cleanup-tag --yes
done
+1 -1
Переглянути файл
@@ -18,7 +18,7 @@ jobs:
if: github.event.pull_request.user.type != 'Bot' && !github.event.pull_request.draft
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v8
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
script: |
const pr = context.payload.pull_request;
+84 -24
Переглянути файл
@@ -19,6 +19,7 @@ env:
jobs:
plugin-keys:
permissions: {}
environment: release
runs-on: ubuntu-latest
outputs:
keys: ${{ steps.keys.outputs.keys }}
@@ -43,6 +44,7 @@ jobs:
contents: write
needs: plugin-keys
name: Build (${{ matrix.name }})
environment: release
env:
OPENIDEA_OFFICIAL_PLUGIN_KEYS: ${{ needs.plugin-keys.outputs.keys }}
strategy:
@@ -69,15 +71,15 @@ jobs:
target: x86_64-pc-windows-msvc
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with: { ref: "${{ env.TAG }}" }
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with: { node-version: 22, cache: pnpm }
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: "${{ matrix.target }}" }
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with: { key: "${{ matrix.target }}", cache-on-failure: true }
- name: Linux deps
if: runner.os == 'Linux'
@@ -85,40 +87,57 @@ jobs:
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf
- run: pnpm install --frozen-lockfile
# Signing is optional: only secrets that are set get exported, so forks and
# unconfigured repos produce unsigned builds instead of failing.
- name: Signing env
# Signing is optional: forks and unconfigured repos produce unsigned builds instead of
# failing. The secrets go only into the steps that sign (never $GITHUB_ENV), so the other
# steps and the actions' post steps never see them. Tauri treats a set-but-empty key as a
# key, so the unsigned build is a separate step without the secrets.
- name: Signing configured
id: signing
shell: bash
env:
UPDATER_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
APPLE_ID: ${{ runner.os == 'macOS' && secrets.APPLE_ID || '' }}
run: |
echo "updater=$([ -n "$UPDATER_KEY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
echo "apple=$([ -n "$APPLE_ID" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
- name: Build (signed)
if: steps.signing.outputs.updater == 'true'
uses: tauri-apps/tauri-action@84b9d35b5fc46c1e45415bdb6144030364f7ebc5 # v0.6.2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
APPLE_CERTIFICATE: ${{ runner.os == 'macOS' && secrets.APPLE_CERTIFICATE || '' }}
APPLE_CERTIFICATE_PASSWORD: ${{ runner.os == 'macOS' && secrets.APPLE_CERTIFICATE_PASSWORD || '' }}
APPLE_SIGNING_IDENTITY: ${{ runner.os == 'macOS' && secrets.APPLE_SIGNING_IDENTITY || '' }}
APPLE_ID: ${{ runner.os == 'macOS' && secrets.APPLE_ID || '' }}
APPLE_PASSWORD: ${{ runner.os == 'macOS' && secrets.APPLE_PASSWORD || '' }}
APPLE_TEAM_ID: ${{ runner.os == 'macOS' && secrets.APPLE_TEAM_ID || '' }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: |
for v in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD APPLE_SIGNING_IDENTITY APPLE_ID \
APPLE_PASSWORD APPLE_TEAM_ID TAURI_SIGNING_PRIVATE_KEY TAURI_SIGNING_PRIVATE_KEY_PASSWORD; do
[ -n "${!v}" ] && { echo "$v<<__EOF__"; echo "${!v}"; echo "__EOF__"; } >> "$GITHUB_ENV"
done
true
- uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
releaseId: ${{ inputs.release_id }}
tagName: ${{ env.TAG }}
args: --target ${{ matrix.target }}
# The parallel builds would race on one latest.json; `updater-manifest` writes it once.
uploadUpdaterJson: false
- name: Build (unsigned)
if: steps.signing.outputs.updater != 'true'
uses: tauri-apps/tauri-action@84b9d35b5fc46c1e45415bdb6144030364f7ebc5 # v0.6.2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
releaseId: ${{ inputs.release_id }}
tagName: ${{ env.TAG }}
args: --target ${{ matrix.target }}
uploadUpdaterJson: false
# tauri-action notarizes the .app but not the DMG around it; notarize and
# staple the DMG too, then replace the uploaded asset.
- name: Notarize DMG
if: runner.os == 'macOS' && env.APPLE_ID != ''
if: runner.os == 'macOS' && steps.signing.outputs.apple == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: |
for dmg in target/${{ matrix.target }}/release/bundle/dmg/*.dmg; do
xcrun notarytool submit "$dmg" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \
@@ -137,6 +156,8 @@ jobs:
shell: pwsh
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: |
$target = "${{ matrix.target }}"
$arch = if ($target -like "x86_64*") { "x64" } else { "arm64" }
@@ -176,11 +197,11 @@ jobs:
- { runner: macos-latest, target: x86_64-apple-darwin, os: macos, arch: x86_64 }
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with: { ref: "${{ env.TAG }}" }
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: "${{ matrix.target }}" }
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with: { key: "server-${{ matrix.target }}", cache-on-failure: true }
- name: musl toolchain
if: runner.os == 'Linux'
@@ -201,6 +222,45 @@ jobs:
if command -v sha256sum >/dev/null; then sha256sum "$ASSET"; else shasum -a 256 "$ASSET"; fi > "$ASSET.sha256"
gh release upload "$TAG" "$ASSET" "$ASSET.sha256" --clobber
# Signs every server archive with the updater key (`<asset>.sig`), so the app verifies a
# server from the CNB mirror as it does from GitHub (ide-tools `server::fetch`). Only this job
# gets the key; without it the archives keep only their .sha256.
server-signatures:
permissions:
contents: write
needs: server
environment: release
runs-on: ubuntu-latest
steps:
- name: Signing configured
id: signing
env:
UPDATER_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
run: echo "updater=$([ -n "$UPDATER_KEY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.signing.outputs.updater == 'true'
with: { ref: "${{ env.TAG }}" }
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
if: steps.signing.outputs.updater == 'true'
with: { version: 11 }
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.signing.outputs.updater == 'true'
with: { node-version: 22, cache: pnpm }
- if: steps.signing.outputs.updater == 'true'
run: pnpm install --frozen-lockfile
- name: Sign server archives
if: steps.signing.outputs.updater == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: |
gh release download "$TAG" -p 'openidea-server-*.gz' -D "$RUNNER_TEMP/server"
for asset in "$RUNNER_TEMP"/server/*.gz; do
pnpm exec tauri signer sign "$asset"
done
gh release upload "$TAG" "$RUNNER_TEMP"/server/*.gz.sig --clobber
# The updater manifest (latest.json), built once from the signed bundles every build uploaded.
# Fails when a platform is missing, so a release never ships a manifest without it.
updater-manifest:
@@ -209,7 +269,7 @@ jobs:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v8
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
RELEASE_ID: ${{ inputs.release_id }}
with:
+38 -16
Переглянути файл
@@ -7,19 +7,27 @@ on:
tag:
description: "Tag to release (e.g. v0.1.0); must already exist"
required: true
# nightly.yml: a nightly is a prerelease whose notes start at the previous nightly, without the
# official plugins, the CNB mirror or the Homebrew cask.
workflow_call:
inputs:
tag: { type: string, required: true }
nightly: { type: boolean, default: false }
permissions:
contents: read
concurrency:
group: release-${{ github.event.inputs.tag || github.ref_name }}
group: release-${{ inputs.tag || github.ref_name }}
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
TAG: ${{ github.event.inputs.tag || github.ref_name }}
TAG: ${{ inputs.tag || github.ref_name }}
COMMUNITY_PLUGINS_INDEX: https://github.com/l0ng-ai/openidea-plugins/releases/download/index/index.json
# The jobs that read a signing key or token, here and in the workflows called below, run in
# the `release` environment, which holds those secrets.
jobs:
# Creates (or reuses) one draft release that every platform build uploads into.
create-release:
@@ -29,7 +37,7 @@ jobs:
outputs:
release_id: ${{ steps.release.outputs.id }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with: { ref: "${{ env.TAG }}" }
- name: Tag matches app version
run: |
@@ -49,7 +57,9 @@ jobs:
exit 1
fi
- id: release
uses: actions/github-script@v8
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
NIGHTLY: ${{ inputs.nightly == true }}
with:
script: |
const tag = process.env.TAG;
@@ -61,8 +71,13 @@ jobs:
core.setOutput("id", existing.id);
return;
}
// Prereleases are skipped: the notes span stable release to stable release.
const previous = releases.find((r) => !r.draft && !r.prerelease);
// Prereleases are skipped: the notes span stable release to stable release. A
// nightly's span from the newest published release, nightly or stable (not the
// rolling `nightly` release, which only holds the channel's manifest).
const nightly = process.env.NIGHTLY === "true";
const previous = releases.find(
(r) => !r.draft && r.tag_name !== "nightly" && (nightly || !r.prerelease),
);
const { data: notes } = await github.rest.repos.generateReleaseNotes({
owner, repo, tag_name: tag, previous_tag_name: previous?.tag_name,
});
@@ -78,7 +93,7 @@ jobs:
needs: create-release
uses: ./.github/workflows/release-build.yml
with:
tag: ${{ github.event.inputs.tag || github.ref_name }}
tag: ${{ inputs.tag || github.ref_name }}
release_id: ${{ needs.create-release.outputs.release_id }}
secrets: inherit
@@ -96,29 +111,34 @@ jobs:
contents: write
needs: create-release
name: Official plugins
environment: release
runs-on: ubuntu-22.04
env:
SIGNING_KEY: ${{ secrets.PLUGIN_SIGNING_KEY }}
NIGHTLY: ${{ inputs.nightly == true }}
steps:
- id: key
run: |
if [ -z "$SIGNING_KEY" ]; then
if [ "$NIGHTLY" = true ]; then
echo "a nightly does not publish the official plugins"
echo "skip=true" >> "$GITHUB_OUTPUT"
elif [ -z "$SIGNING_KEY" ]; then
echo "::warning::PLUGIN_SIGNING_KEY is not set: the official plugins are not published"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.key.outputs.skip != 'true'
with: { ref: "${{ env.TAG }}" }
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
if: steps.key.outputs.skip != 'true'
with: { targets: wasm32-wasip2 }
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: steps.key.outputs.skip != 'true'
with: { key: release-plugins }
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
if: steps.key.outputs.skip != 'true'
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.key.outputs.skip != 'true'
with: { node-version: 22 }
# Builds the web pages; fails when a checked-in component isn't built from these sources.
@@ -163,7 +183,7 @@ jobs:
needs: [create-release, binaries, plugins]
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v8
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
with:
@@ -175,13 +195,15 @@ jobs:
# The China mirror the updater's CNB source reads; a failure here leaves the GitHub release as is.
cnb-mirror:
needs: publish
if: ${{ !inputs.nightly }}
uses: ./.github/workflows/cnb-mirror.yml
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
with: { tag: "${{ inputs.tag || github.ref_name }}" }
secrets: inherit
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
homebrew:
needs: publish
if: ${{ !inputs.nightly }}
uses: ./.github/workflows/homebrew.yml
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
with: { tag: "${{ inputs.tag || github.ref_name }}" }
secrets: inherit
Створено
+78 -54
Переглянути файл
@@ -252,9 +252,9 @@ dependencies = [
[[package]]
name = "async-executor"
version = "1.14.0"
version = "1.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
dependencies = [
"async-task",
"concurrent-queue",
@@ -1552,9 +1552,9 @@ dependencies = [
[[package]]
name = "curve25519-dalek"
version = "5.0.0"
version = "5.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"
checksum = "94c1aa5a9b7626ed65ac0cf5ea9d4f1547af89017fbac20bd4de40022fff516f"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
@@ -4154,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4171,6 +4171,7 @@ dependencies = [
"semver",
"serde",
"serde_json",
"sha1 0.10.7",
"specta",
"tempfile",
"tokio",
@@ -4182,7 +4183,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4194,10 +4195,11 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"serde",
"serde_json",
"specta",
"tempfile",
"which",
@@ -4205,7 +4207,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"blake3",
"chardetng",
@@ -4223,7 +4225,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4237,7 +4239,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4248,7 +4250,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -4259,7 +4261,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4281,7 +4283,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-run",
@@ -4294,7 +4296,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4305,6 +4307,7 @@ dependencies = [
"ide-jvm-attach",
"ide-jvm-inspect",
"ide-language",
"ide-run",
"libc",
"memchr",
"parking_lot 0.12.5",
@@ -4323,7 +4326,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4362,7 +4365,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"serde",
@@ -4375,7 +4378,7 @@ dependencies = [
[[package]]
name = "ide-drag-out"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4389,7 +4392,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4409,7 +4412,7 @@ dependencies = [
[[package]]
name = "ide-flutter"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-android",
"ide-core",
@@ -4420,7 +4423,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4432,7 +4435,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4444,7 +4447,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"criterion",
"ide-core",
@@ -4463,7 +4466,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4490,6 +4493,7 @@ dependencies = [
"ide-docker",
"ide-extension",
"ide-flutter",
"ide-github",
"ide-heap",
"ide-http",
"ide-index",
@@ -4545,11 +4549,15 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"http",
"hyper-util",
"ide-core",
"ide-vfs",
"objc2-cf-network",
"objc2-core-foundation",
"parking_lot 0.12.5",
"reqwest",
"rustls",
@@ -4564,7 +4572,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"blake3",
"criterion",
@@ -4587,7 +4595,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4599,7 +4607,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4615,7 +4623,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"libc",
"tempfile",
@@ -4624,7 +4632,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"futures",
"serde",
@@ -4635,7 +4643,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"blake3",
"criterion",
@@ -4694,7 +4702,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"criterion",
"dunce",
@@ -4724,7 +4732,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"bytes",
"dunce",
@@ -4743,20 +4751,24 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"futures",
"ide-core",
"ide-http",
"ide-vfs",
"jupyter-protocol",
"jupyter-zmq-client",
"libc",
"parking_lot 0.12.5",
"reqwest",
"serde",
"serde_json",
"specta",
"specta-typescript",
"tempfile",
"tokio",
"tokio-tungstenite",
"uuid",
"windows-sys 0.61.2",
"zeromq",
@@ -4764,7 +4776,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"blake3",
"dunce",
@@ -4786,7 +4798,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4800,7 +4812,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"dunce",
"futures",
@@ -4820,8 +4832,9 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"blake3",
"dunce",
"encoding_rs",
"ide-build",
@@ -4845,7 +4858,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-tools",
@@ -4861,7 +4874,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4887,7 +4900,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"criterion",
"encoding_rs",
@@ -4908,7 +4921,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"parking_lot 0.12.5",
@@ -4921,7 +4934,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4946,7 +4959,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-language",
@@ -4959,7 +4972,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"ide-language",
@@ -4974,7 +4987,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"ide-core",
"libc",
@@ -4988,7 +5001,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"criterion",
"ide-core",
@@ -5001,16 +5014,19 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"blake3",
"flate2",
"hex",
"http",
"hyper-util",
"ide-core",
"ide-http",
"ide-language",
"libc",
"minisign-verify",
"parking_lot 0.12.5",
"serde",
"serde_json",
@@ -5025,7 +5041,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"blake3",
"dunce",
@@ -5047,7 +5063,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"chardetng",
"dunce",
@@ -5074,7 +5090,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5090,7 +5106,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"blake3",
"dunce",
@@ -6321,6 +6337,15 @@ dependencies = [
"objc2-quartz-core 0.3.2",
]
[[package]]
name = "objc2-cf-network"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b4c9e30e636e2cd7d7414f320af2e0aa86f686adfc6f1bbe50b92366e4309c8"
dependencies = [
"objc2-core-foundation",
]
[[package]]
name = "objc2-cloud-kit"
version = "0.2.2"
@@ -6729,7 +6754,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.55"
version = "0.1.56"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -6749,7 +6774,6 @@ dependencies = [
"ide-drag-out",
"ide-extension",
"ide-fonts",
"ide-github",
"ide-host",
"ide-http",
"ide-jsonrpc",
@@ -9836,7 +9860,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"getrandom 0.3.4",
"once_cell",
"rustix",
"windows-sys 0.61.2",
+2 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.55"
version = "0.1.56"
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-github = { path = "crates/ide-github" }
ide-terminal = { path = "crates/ide-terminal" }
ide-run = { path = "crates/ide-run" }
ide-workspace = { path = "crates/ide-workspace" }
+1
Переглянути файл
@@ -27,6 +27,7 @@ uuid.workspace = true
tempfile.workspace = true
which = "8"
semver = "1"
sha1 = "0.10"
[target.'cfg(unix)'.dependencies]
rustix = { version = "1", features = ["fs"] }
+15
Переглянути файл
@@ -54,6 +54,21 @@ pub(crate) fn bypass_approvals(config: &[AgentConfigOption]) -> bool {
.any(|category| selected(category).zip(bypass_value(category)).is_some_and(|(value, bypass)| bypass(value)))
}
/// Canonical snapshot of approval-bearing config options (`mode`, `permissions`, `approval`)
/// so auto-resume can refuse to run silently if permission policy drifted while closed.
pub(crate) fn approval_fingerprint(config: &[AgentConfigOption]) -> Option<String> {
let mut parts: Vec<String> = config
.iter()
.filter(|o| matches!(o.category.as_deref(), Some("mode" | "permissions" | "approval")))
.filter_map(|o| Some(format!("{}={}", o.id, o.current.as_deref()?)))
.collect();
if parts.is_empty() {
return None;
}
parts.sort();
Some(parts.join(";"))
}
/// For an option of `category` that can approve everything, what tells its approving values.
fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
match category {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+310 -2
Переглянути файл
@@ -49,6 +49,74 @@ pub struct AgentCapabilities {
pub context_usage: bool,
}
/// Why `AgentManager` is shutting down its live tasks.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AgentShutdownReason {
WindowClose,
#[default]
Quit,
Restart,
BackendUpgrade,
BackendStop,
}
/// Why an in-flight turn stopped before completing.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum InterruptionReason {
WindowClose,
Quit,
Restart,
BackendUpgrade,
BackendStop,
UnexpectedExit,
NetworkTimeout,
}
impl From<AgentShutdownReason> for InterruptionReason {
fn from(reason: AgentShutdownReason) -> Self {
match reason {
AgentShutdownReason::WindowClose => Self::WindowClose,
AgentShutdownReason::Quit => Self::Quit,
AgentShutdownReason::Restart => Self::Restart,
AgentShutdownReason::BackendUpgrade => Self::BackendUpgrade,
AgentShutdownReason::BackendStop => Self::BackendStop,
}
}
}
/// Recovery metadata recorded when an active turn was interrupted before finishing.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentInterrupted {
pub reason: InterruptionReason,
pub at_ms: f64,
#[serde(default, skip_serializing_if = "is_false")]
pub was_waiting_for_input: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub approval_mode: Option<String>,
#[serde(default, skip_serializing_if = "is_false")]
pub auto_resume_once: bool,
}
/// Summary returned when reconciling interrupted tasks for a connected project window.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentRecoveryReport {
/// Unique identifier of this `AgentManager` process incarnation.
pub instance_id: String,
/// `true` on the first reconciliation of this `AgentManager` incarnation.
pub first_reconcile: bool,
/// Task IDs automatically resumed during this reconciliation.
pub auto_resumed: Vec<String>,
/// Task IDs remaining in `Interrupted` (`Ask to resume`).
pub interrupted: Vec<String>,
}
fn is_false(b: &bool) -> bool {
!*b
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum Isolation {
@@ -113,10 +181,24 @@ pub struct AgentTask {
/// Per-session skill modes (`skill name` -> mode), on top of the settings' policies.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
/// Per-session memory overrides (auto-memory mode and per-entry modes), boxed to keep `AgentEvent::Task` small.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub memory_overrides: Option<Box<AgentMemoryOverrides>>,
/// Token counts of the last turn and context compressions, when the agent reports them.
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
#[serde(default)]
pub stats: Box<AgentSessionStats>,
/// Set when the task's last active turn was interrupted (window close, restart, crash, or
/// expired network retry window) and has not been resumed or dismissed yet.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub interrupted: Option<Box<AgentInterrupted>>,
/// Persisted unseen reply / input / failure state across window closes and remote reattaches.
#[serde(default, skip_serializing_if = "is_false")]
pub unread: bool,
/// Per-session recovery / network auto-retry window override in minutes (`0` = Off; `None` = inherit global).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recovery_window_mins: Option<u32>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
@@ -159,6 +241,9 @@ pub struct AgentRetry {
/// When the next attempt starts (ms since the epoch).
pub retry_at_ms: f64,
pub error: Option<String>,
/// Set when OpenIDEA holds an active turn in `Waiting for network` until `deadline_ms`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deadline_ms: Option<f64>,
}
/// Token pricing (Credits per 1M tokens) and context window capacity for one tier.
@@ -528,6 +613,9 @@ pub enum AgentEntry {
/// Sent into a running turn rather than starting one.
#[serde(default)]
steered: bool,
/// Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn.
#[serde(default)]
recovery: Option<InterruptionReason>,
},
Agent {
text: String,
@@ -750,6 +838,10 @@ pub struct NewAgentTask {
/// Per-session skill modes (`skill name` -> mode).
#[serde(default)]
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
/// Per-session memory overrides (auto-memory mode and per-entry modes).
#[serde(default)]
#[specta(optional)]
pub memory_overrides: Option<AgentMemoryOverrides>,
/// Creates the task without sending `prompt` (it only names the task): the composer's
/// `!` command runs in it first.
#[serde(default)]
@@ -891,7 +983,7 @@ pub enum AgentEvent {
pub use ide_core::settings::{AgentMcpServer, McpTransport};
/// Where an MCP server configuration is stored (`settings.toml` vs `.openidea/settings.toml`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum McpScope {
User,
@@ -958,7 +1050,223 @@ fn default_true() -> bool {
true
}
pub use ide_core::settings::{AgentSkillMode, AgentSkillPolicy};
pub use ide_core::settings::{
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentProviderMemoryPolicy, AgentSkillMode,
AgentSkillPolicy, AutoMemoryMode,
};
/// Kind of discovered agent memory entry.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemoryKind {
/// Always-loaded instruction document (`AGENTS.md`, `CLAUDE.md`, `copilot-instructions.md`, `GEMINI.md`).
#[default]
Instruction,
/// Path-scoped or conditional rule (`.claude/rules/*.md`, `*.instructions.md`, `.cursor/rules/*.mdc`).
Rule,
/// Agent-authored cross-session memory note (`MEMORY.md`, Claude topic files, Codex summaries, Hermes `USER.md`).
AutoNote,
}
/// Which workspace, user, or CLI store a memory entry was discovered in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemorySource {
/// Portable workspace instructions: `AGENTS.md`, `AGENTS.override.md`.
#[default]
Workspace,
/// `CLAUDE.md`, `.claude/CLAUDE.md`, `CLAUDE.local.md`, `.claude/rules/**`.
ClaudeWorkspace,
/// `~/.claude/CLAUDE.md`, `~/.claude/rules/**`.
ClaudeUser,
/// `~/.claude/projects/<repo>/memory/**` (or custom `autoMemoryDirectory`).
ClaudeAuto,
/// `.github/copilot-instructions.md`, `.github/instructions/**/*.instructions.md`.
GithubWorkspace,
/// `~/.copilot/copilot-instructions.md`, `~/.copilot/instructions/**/*.instructions.md`.
CopilotUser,
/// `~/.codex/AGENTS.md`, `~/.codex/AGENTS.override.md`.
CodexUser,
/// `~/.codex/memories/**` / `~/.codex/memories_v2/**`.
CodexAuto,
/// `.cursor/rules/**/*.mdc`, `.cursorrules`.
CursorWorkspace,
/// `GEMINI.md`.
GeminiWorkspace,
/// `~/.gemini/GEMINI.md`.
GeminiUser,
/// `<hermes_profile>/memories/{MEMORY.md,USER.md}`.
HermesAuto,
}
impl AgentMemorySource {
/// True when the entry lives inside the current workspace and requires Workspace Trust.
pub fn is_workspace(self) -> bool {
matches!(
self,
Self::Workspace
| Self::ClaudeWorkspace
| Self::GithubWorkspace
| Self::CursorWorkspace
| Self::GeminiWorkspace
)
}
/// True when the entry is an agent's learned cross-session auto-memory store.
pub fn is_auto(self) -> bool {
matches!(self, Self::ClaudeAuto | Self::CodexAuto | Self::HermesAuto)
}
}
/// Which layer decided an [`AgentMemoryState::mode`] or [`AutoMemoryMode`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemoryOrigin {
#[default]
None,
Session,
Workspace,
User,
/// Locked `Off` because the workspace is untrusted.
Trust,
}
/// One discovered instruction file, rule file, or learned auto-memory note.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMemoryEntry {
/// Stable identifier (`"<source>::<rel_key>"`).
pub id: String,
pub title: String,
pub description: String,
pub kind: AgentMemoryKind,
pub source: AgentMemorySource,
/// Secondary sources whose symlink or `@AGENTS.md` import resolved to this same canonical file.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub also_in: Vec<AgentMemorySource>,
/// Canonical file path on disk.
pub path: IpcPath,
/// Normalized path-scoping globs (`paths:` in Claude, `applyTo:` in Copilot, `globs:` in Cursor).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub paths: Vec<String>,
/// Optional memory category (`user`, `feedback`, `project`, `reference`, `profile`).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub category: Option<String>,
/// Approximate prompt token cost (~4 chars/token).
pub approx_tokens: u32,
pub line_count: u32,
pub byte_len: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub modified_ms: Option<f64>,
/// True when OpenIDEA allows deleting or promoting-and-removing this file (auto-memory notes).
pub writable: bool,
pub valid: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
}
/// A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMemoryState {
pub entry: AgentMemoryEntry,
pub mode: AgentMemoryMode,
/// Optional provider filter from `[agents.memory.entries.<id>]`; empty means all agents.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub agents: Vec<String>,
pub origin: AgentMemoryOrigin,
}
/// Live auto-memory status and capability summary for one agent family.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentAutoMemoryStatus {
pub provider: String,
pub label: String,
pub mode: AutoMemoryMode,
pub origin: AgentMemoryOrigin,
pub note_count: u32,
pub rollout_count: u32,
pub approx_tokens: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub storage_path: Option<IpcPath>,
pub supports_auto_control: bool,
pub supports_file_exclusion: bool,
pub supports_reset: bool,
}
/// Full catalog returned to Settings › Agents › Memory and the Composer `MemoryPicker`.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMemoryCatalog {
pub entries: Vec<AgentMemoryState>,
pub providers: Vec<AgentAutoMemoryStatus>,
pub auto_memory: AutoMemoryMode,
pub auto_memory_origin: AgentMemoryOrigin,
}
/// Per-session memory overrides stored on an [`AgentTask`].
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentMemoryOverrides {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub auto_memory: Option<AutoMemoryMode>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub entries: BTreeMap<String, AgentMemoryMode>,
}
impl AgentMemoryOverrides {
pub fn is_empty(&self) -> bool {
self.auto_memory.is_none() && self.entries.is_empty()
}
}
/// Target format when creating a new memory or instruction file from Settings › Agents › Memory.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemoryCreateTarget {
/// `<workspace>/AGENTS.md` (or `~/.codex/AGENTS.md` in User scope).
#[default]
AgentsMd,
/// `<workspace>/.claude/rules/<slug>.md` or `~/.claude/rules/<slug>.md`.
ClaudeRule,
/// `<workspace>/.github/instructions/<slug>.instructions.md` or `~/.copilot/instructions/<slug>.instructions.md`.
CopilotInstruction,
/// `<workspace>/.cursor/rules/<slug>.mdc`.
CursorRule,
}
/// Payload for creating a new instruction or rule file.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CreateAgentMemoryInput {
pub scope: McpScope,
pub target: AgentMemoryCreateTarget,
#[serde(default)]
pub name: String,
#[serde(default)]
#[specta(optional)]
pub description: Option<String>,
#[serde(default)]
pub paths: Vec<String>,
pub content: String,
}
/// Payload for promoting an auto-memory note into `AGENTS.md`.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PromoteAgentMemoryInput {
pub source_id: String,
#[serde(default)]
#[specta(optional)]
pub heading: Option<String>,
#[serde(default)]
pub remove_source: bool,
}
/// Which CLI's own folders a skill was discovered in (Settings › Agents › Skills groups by it).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
+62 -6
Переглянути файл
@@ -174,10 +174,14 @@ struct Session {
mcp_off: Vec<String>,
/// The staged skills folder passed as `--add-dir` (its `.claude/skills` holds the copies).
skills_add_dir: Option<PathBuf>,
/// The staged memory rules folder passed as `--add-dir` (its `.claude/rules` holds shared rules).
memory_add_dir: Option<PathBuf>,
/// Load `.claude/rules` from `--add-dir` folders (`CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`).
additional_dirs_claude_md: bool,
/// The workspace's other roots, each passed as `--add-dir`.
additional_dirs: Vec<String>,
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
skills_settings: Option<String>,
/// Combined `--settings` JSON (`skillOverrides`, `autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`).
cli_settings: Option<String>,
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
ephemeral: bool,
shim: Weak<Shim>,
@@ -371,13 +375,20 @@ impl Shim {
}
});
let skills = params.pointer("/_meta/openidea/skills");
let memory = params.pointer("/_meta/openidea/memory");
let cli_settings = build_cli_settings(skills, memory);
let session = Arc::new(Session {
id: id.to_owned(),
mcp_config,
mcp_off,
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
memory_add_dir: memory.and_then(|m| m.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
additional_dirs_claude_md: memory
.and_then(|m| m.get("claudeAdditionalDirsClaudeMd"))
.and_then(Value::as_bool)
.unwrap_or(false),
additional_dirs: additional_dirs(params),
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
cli_settings,
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
shim: Arc::downgrade(self),
st: Mutex::new(State {
@@ -728,18 +739,28 @@ impl Session {
if let Some(dir) = &self.skills_add_dir {
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
}
if let Some(dir) = &self.memory_add_dir
&& self.skills_add_dir.as_ref() != Some(dir)
{
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
}
for dir in &self.additional_dirs {
args.extend(["--add-dir".to_owned(), dir.clone()]);
}
if let Some(settings) = &self.skills_settings {
if let Some(settings) = &self.cli_settings {
args.extend(["--settings".to_owned(), settings.clone()]);
}
if self.ephemeral {
args.push("--no-session-persistence".to_owned());
}
args.extend(start.args());
let launch =
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
let mut env = shim.config.env.clone();
if self.additional_dirs_claude_md
&& !env.iter().any(|(k, _)| k == "CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD")
{
env.push(("CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD".to_owned(), "1".to_owned()));
}
let launch = Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env };
let io = shim
.cli
.launch(&launch, shim.on_stderr.clone())
@@ -1601,6 +1622,41 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
/// Claude Code's own configuration stays off too.
/// Combines `skillOverrides` from `_meta.openidea.skills.claudeSettings` with memory
/// settings (`autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`) into one `--settings` JSON.
fn build_cli_settings(skills: Option<&Value>, memory: Option<&Value>) -> Option<String> {
let mut root = skills
.and_then(|s| s.get("claudeSettings"))
.and_then(Value::as_str)
.and_then(|raw| serde_json::from_str::<serde_json::Map<String, Value>>(raw).ok())
.unwrap_or_default();
if let Some(mem) = memory {
if let Some(auto) = mem.get("claudeAutoMemory").and_then(Value::as_bool) {
root.insert("autoMemoryEnabled".into(), json!(auto));
}
if let Some(excludes) = mem.get("claudeMdExcludes").and_then(Value::as_array) {
let clean: Vec<Value> =
excludes.iter().filter_map(Value::as_str).filter(|s| !s.is_empty()).map(|s| json!(s)).collect();
if !clean.is_empty() {
root.insert("claudeMdExcludes".into(), Value::Array(clean));
}
}
if let Some(inst) = mem.get("claudeInstructionFiles").and_then(Value::as_str).filter(|s| !s.is_empty()) {
root.insert(
"pluginConfigs".into(),
json!({
"cc-plugin-agents-md@builtin": {
"options": { "instructionFiles": inst }
}
}),
);
}
}
(!root.is_empty()).then(|| serde_json::to_string(&Value::Object(root)).expect("settings serialize"))
}
/// The session's `additionalDirectories`: the workspace's other roots.
fn additional_dirs(params: &Value) -> Vec<String> {
let dirs = params.get("additionalDirectories").and_then(Value::as_array);
+42
Переглянути файл
@@ -1442,3 +1442,45 @@ async fn an_ephemeral_session_is_not_saved() {
let args = cli.launched.lock()[0].clone();
assert!(args.contains(&"--no-session-persistence".to_owned()), "{args:?}");
}
#[tokio::test(flavor = "multi_thread")]
async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env() {
let cli = replay_cli(load_fixture("simple"));
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
let h =
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
let params = json!({
"cwd": h.cwd,
"mcpServers": [],
"_meta": {
"openidea": {
"skills": {
"claudeAddDir": "/tmp/farm-skills",
"claudeSettings": "{\"skillOverrides\":{\"tdd\":\"user-invocable-only\"}}"
},
"memory": {
"autoMemory": "readOnly",
"claudeAutoMemory": false,
"claudeMdExcludes": ["/repo/CLAUDE.local.md"],
"claudeInstructionFiles": "claude-md-and-agents-md",
"claudeAddDir": "/tmp/farm-memory",
"claudeAdditionalDirsClaudeMd": true
}
}
}
});
h.request("session/new", params).await.unwrap();
let args = cli.launched.lock()[0].clone();
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-skills"]), "{args:?}");
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-memory"]), "{args:?}");
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
assert_eq!(parsed["skillOverrides"]["tdd"], "user-invocable-only");
assert_eq!(parsed["autoMemoryEnabled"], false);
assert_eq!(parsed["claudeMdExcludes"], json!(["/repo/CLAUDE.local.md"]));
assert_eq!(
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
"claude-md-and-agents-md"
);
}
+14
Переглянути файл
@@ -20,6 +20,17 @@ pub(crate) const BUILTIN_COMMANDS: &[BuiltinCommandSpec] = &[
choices: &[("reconnect", "Reload and reconnect MCP servers.")],
},
BuiltinCommandSpec { name: "skills", description: "List available skills.", hint: None, choices: &[] },
BuiltinCommandSpec {
name: "memories",
description: "Show, enable, disable, or reset cross-session Codex memories.",
hint: Some("[show|on|off|reset]"),
choices: &[
("show", "Show consolidated memory summary for this thread."),
("on", "Enable memory generation for this thread."),
("off", "Disable memory generation for this thread."),
("reset", "Clear local Codex memory files and summaries."),
],
},
BuiltinCommandSpec {
name: "status",
description: "Display session configuration and token usage.",
@@ -79,6 +90,7 @@ pub(super) enum BuiltinCommand {
Plan,
Mcp,
Skills,
Memories,
Status,
Review,
ReviewBranch,
@@ -95,6 +107,7 @@ impl BuiltinCommand {
"plan" => Self::Plan,
"mcp" => Self::Mcp,
"skills" => Self::Skills,
"memories" => Self::Memories,
"status" => Self::Status,
"review" => Self::Review,
"review-branch" => Self::ReviewBranch,
@@ -150,6 +163,7 @@ mod tests {
"plan",
"mcp",
"skills",
"memories",
"status",
"review",
"review-branch",
+49
Переглянути файл
@@ -362,6 +362,23 @@ fn apply_thread_config(params: &Value, request: &mut Value) {
{
map.insert("skills".into(), json!({ "config": off }));
}
if let Some(mem) = params.pointer("/_meta/openidea/memory")
&& let Some(map) = config.as_object_mut()
{
let mut mem_cfg = serde_json::Map::new();
if let Some(use_m) = mem.get("codexUseMemories").and_then(Value::as_bool) {
mem_cfg.insert("use_memories".into(), json!(use_m));
}
if let Some(gen_m) = mem.get("codexGenerateMemories").and_then(Value::as_bool) {
mem_cfg.insert("generate_memories".into(), json!(gen_m));
}
if !mem_cfg.is_empty() {
map.insert("memories".into(), Value::Object(mem_cfg));
}
if let Some(dev) = mem.get("codexDeveloperInstructions").and_then(Value::as_str).filter(|s| !s.is_empty()) {
map.insert("developer_instructions".into(), json!(dev));
}
}
if !config.as_object().is_some_and(|m| m.is_empty()) {
request["config"] = config;
}
@@ -708,6 +725,7 @@ impl CodexShim {
let found = self.call("skills/list", json!({ "cwds": [cwd] })).await?;
self.say(session, skills_text(&found));
}
BuiltinCommand::Memories => self.memories_command(session, &command.rest).await?,
BuiltinCommand::Mcp => match command.rest.as_str() {
"" => self.say(session, self.mcp_text(session).await?),
rest if rest.eq_ignore_ascii_case("reconnect") => {
@@ -747,6 +765,36 @@ impl CodexShim {
Ok(json!({ "stopReason": "end_turn" }))
}
async fn memories_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
let arg = rest.trim().to_ascii_lowercase();
match arg.as_str() {
"" | "show" => {
let res = self.call("thread/memory/read", json!({ "threadId": session })).await?;
let summary = res
.get("summary")
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.unwrap_or("No consolidated memories for this thread yet.");
self.say(session, summary);
}
"on" => {
self.call("thread/memoryMode/set", json!({ "threadId": session, "mode": "enabled" })).await?;
self.say(session, "Memory generation enabled for this thread.");
}
"off" => {
self.call("thread/memoryMode/set", json!({ "threadId": session, "mode": "disabled" })).await?;
self.say(session, "Memory generation disabled for this thread.");
}
"reset" => {
self.call("memory/reset", Value::Null).await?;
self.say(session, "Reset local Codex memories.");
}
_ => self.say(session, command_usage(BuiltinCommand::Memories)),
}
Ok(())
}
async fn goal_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
let argument = rest.trim();
if argument.is_empty() {
@@ -1518,6 +1566,7 @@ fn command_usage(command: BuiltinCommand) -> String {
match command {
BuiltinCommand::Plan => "Command \"/plan\" accepts no arguments.".to_owned(),
BuiltinCommand::Mcp => "Command \"/mcp\" accepts no arguments, or `reconnect`.".to_owned(),
BuiltinCommand::Memories => "Command \"/memories\" accepts `[show|on|off|reset]`.".to_owned(),
BuiltinCommand::ReviewBranch => "Command \"/review-branch\" requires branch name.".to_owned(),
BuiltinCommand::ReviewCommit => "Command \"/review-commit\" requires commit sha.".to_owned(),
BuiltinCommand::Goal => "Command \"/goal\" requires [<objective>|clear|pause|resume].".to_owned(),
+75
Переглянути файл
@@ -1695,6 +1695,57 @@ async fn goal_commands_set_pause_resume_and_clear_through_app_server() {
}
}
#[tokio::test(flavor = "multi_thread")]
async fn memories_commands_read_toggle_and_reset_through_app_server() {
for (prompt, method, has_thread_id, expected_params, result, expected_text) in [
(
"/memories",
"thread/memory/read",
true,
json!({ "threadId": "s" }),
json!({ "summary": "Remembered: run targeted tests first." }),
"Remembered: run targeted tests first.",
),
(
"/memories show",
"thread/memory/read",
true,
json!({ "threadId": "s" }),
json!({ "summary": null }),
"No consolidated memories for this thread yet.",
),
(
"/memories on",
"thread/memoryMode/set",
true,
json!({ "threadId": "s", "mode": "enabled" }),
json!({}),
"Memory generation enabled for this thread.",
),
(
"/memories off",
"thread/memoryMode/set",
true,
json!({ "threadId": "s", "mode": "disabled" }),
json!({}),
"Memory generation disabled for this thread.",
),
("/memories reset", "memory/reset", false, Value::Null, json!({}), "Reset local Codex memories."),
] {
let (results, client, frames, _meta, _codex) =
replay_transcript(Scenario::Command(prompt), command_transcript(&[(method, result)])).await;
let session = session_of(&results, "new");
let sent = sent(&frames, method);
assert_eq!(sent.len(), 1, "{prompt}");
let mut expected = expected_params;
if has_thread_id {
expected["threadId"] = json!(session);
assert_eq!(sent[0]["params"], expected, "{prompt}");
}
assert_eq!(client.text(&session, "agent_message_chunk"), expected_text, "{prompt}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn missing_review_arguments_print_usage_without_starting_a_turn() {
for prompt in ["/review-branch", "/review-commit", "/rename", "/goal"] {
@@ -2087,6 +2138,8 @@ fn skills_become_commands_with_their_invocation_names() {
let builtins = builtin_commands();
let goal = builtins.iter().find(|c| c.name == "goal").unwrap();
assert_eq!(goal.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["clear", "pause", "resume"]);
let memories = builtins.iter().find(|c| c.name == "memories").unwrap();
assert_eq!(memories.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["show", "on", "off", "reset"]);
let mcp = builtins.iter().find(|c| c.name == "mcp").unwrap();
assert_eq!(mcp.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["reconnect"]);
assert!(skill_commands(&json!({"data": []})).unwrap()["availableCommands"].as_array().unwrap().is_empty());
@@ -2102,6 +2155,28 @@ fn workspace_roots_join_the_thread_roots() {
let mut request = json!({});
apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request);
assert!(request.get("runtimeWorkspaceRoots").is_none());
let mut mem_req = json!({});
apply_thread_config(
&json!({
"cwd": "/w/api",
"mcpServers": [],
"_meta": {
"openidea": {
"skills": { "codexOff": [["noisy", "/repo/.agents/skills/noisy/SKILL.md"]] },
"memory": {
"codexUseMemories": true,
"codexGenerateMemories": false,
"codexDeveloperInstructions": "## Memory (style)\nUse targeted selectors."
}
}
}
}),
&mut mem_req,
);
assert_eq!(mem_req["config"]["memories"], json!({ "use_memories": true, "generate_memories": false }));
assert_eq!(mem_req["config"]["developer_instructions"], "## Memory (style)\nUse targeted selectors.");
assert_eq!(mem_req["config"]["skills"]["config"][0]["enabled"], false);
}
#[tokio::test(flavor = "multi_thread")]
+34
Переглянути файл
@@ -462,6 +462,38 @@ fn apply_skills(params: &Value, req: &mut Value) {
}
}
/// Applies `_meta.openidea.memory` to Copilot's `session.create` / `session.resume` payload:
/// gates `store_memory` when auto-memory is `ReadOnly` or `Off`, disables custom instructions
/// when all workspace/user instructions are muted, and appends shared OpenIDEA memories.
fn apply_memory(params: &Value, req: &mut Value) {
let Some(mem) = params.pointer("/_meta/openidea/memory") else {
return;
};
if mem.get("copilotExcludeStoreMemory").and_then(Value::as_bool) == Some(true) {
let mut excluded: Vec<String> = req
.get("excludedTools")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
if !excluded.iter().any(|t| t == "store_memory") {
excluded.push("store_memory".into());
}
req["excludedTools"] = json!(excluded);
}
if mem.get("copilotDisableCustomInstructions").and_then(Value::as_bool) == Some(true) {
req["customInstructions"] = json!(false);
}
if let Some(sys) = mem.get("copilotSystemMessage").and_then(Value::as_str).filter(|s| !s.is_empty()) {
req["systemMessage"] = json!({
"mode": "append",
"content": sys,
});
}
}
fn invalid(message: impl Into<String>) -> ResponseError {
error(codes::INVALID_PARAMS, message)
}
@@ -588,6 +620,7 @@ impl CopilotShim {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
apply_memory(params, &mut req);
let created = self.call("session.create", req).await?;
let session_id = created
@@ -639,6 +672,7 @@ impl CopilotShim {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
apply_memory(params, &mut req);
let resumed = self.call("session.resume", req).await?;
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
+50
Переглянути файл
@@ -833,6 +833,56 @@ async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skil
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn session_new_and_load_apply_copilot_memory_gating_and_system_message() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates, move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
let meta = json!({
"openidea": {
"memory": {
"autoMemory": "readOnly",
"copilotExcludeStoreMemory": true,
"copilotDisableCustomInstructions": true,
"copilotSystemMessage": "## Memory (shared)\nRun targeted tests."
}
}
});
let _: Value =
client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [], "_meta": meta }), None).await.unwrap();
let _: Value = client
.request(
"session/load",
json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [], "_meta": meta }),
None,
)
.await
.unwrap();
let calls = server.calls.lock();
for method in ["session.create", "session.resume"] {
let params = calls.iter().find_map(|(m, p)| (m == method).then_some(p)).expect(method);
assert_eq!(params["excludedTools"], json!(["store_memory"]), "{method}: {params}");
assert_eq!(params["customInstructions"], json!(false), "{method}: {params}");
assert_eq!(
params["systemMessage"],
json!({ "mode": "append", "content": "## Memory (shared)\nRun targeted tests." }),
"{method}: {params}"
);
}
}
#[test]
fn translates_context_attribution_without_double_counting_parent_rollups() {
let payload = json!({
+511 -96
Переглянути файл
@@ -15,6 +15,7 @@ use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_tools::Http;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::{HashMap, VecDeque};
use std::path::{Component, Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
@@ -106,6 +107,9 @@ pub struct InstallRemoteSkillRequest {
pub owner: String,
pub repo: String,
pub git_ref: String,
/// Root tree SHA returned by the preview. The install reads exactly this tree, so commits pushed
/// to `git_ref` after the user reviewed the preview are never installed.
pub tree_sha: String,
pub subpath: String,
pub scope: McpScope,
/// Must be `true` when the static security scan produces any warnings.
@@ -246,13 +250,13 @@ impl SkillSourceFetcher for GitHubHttpFetcher {
validate_repo_coord(owner, "owner")?;
validate_repo_coord(repo, "repository")?;
validate_git_ref(git_ref)?;
if blob_sha.is_empty() || !blob_sha.bytes().all(|b| b.is_ascii_hexdigit()) {
if !is_git_object_id(blob_sha) {
return Err(IdeError::invalid("invalid Git blob SHA"));
}
// Base64 expands by ~4/3 plus JSON wrapper.
let json_limit = max_bytes.saturating_mul(2).saturating_add(4096);
let blob_url = format!("https://api.github.com/repos/{owner}/{repo}/git/blobs/{blob_sha}");
match self.get_github_json(&blob_url, json_limit, cancel) {
let bytes = match self.get_github_json(&blob_url, json_limit, cancel) {
Ok(text) => {
let parsed: BlobResponse = serde_json::from_str(&text)
.map_err(|e| IdeError::new(ErrorKind::Protocol, format!("invalid Git blob JSON: {e}")))?;
@@ -269,7 +273,7 @@ impl SkillSourceFetcher for GitHubHttpFetcher {
if bytes.len() as u64 > max_bytes {
return Err(IdeError::invalid(format!("{repo_path}: exceeds {} KiB limit", max_bytes >> 10)));
}
Ok(bytes)
bytes
}
Err(api_err) => {
if cancel.is_cancelled() {
@@ -286,12 +290,34 @@ impl SkillSourceFetcher for GitHubHttpFetcher {
if bytes.len() as u64 > max_bytes {
return Err(IdeError::invalid(format!("{repo_path}: exceeds {} KiB limit", max_bytes >> 10)));
}
Ok(bytes)
bytes
}
};
// The raw fallback reads `git_ref`, which may have moved since the tree was listed.
if !git_blob_id(&bytes).eq_ignore_ascii_case(blob_sha) {
return Err(IdeError::new(
ErrorKind::Protocol,
format!("{repo_path}: downloaded content does not match Git blob {blob_sha}"),
));
}
Ok(bytes)
}
}
/// A 40-digit hex SHA-1 Git object id (GitHub does not host SHA-256 repositories).
fn is_git_object_id(id: &str) -> bool {
id.len() == 40 && id.bytes().all(|b| b.is_ascii_hexdigit())
}
/// Git's object id for a blob holding `bytes`.
fn git_blob_id(bytes: &[u8]) -> String {
use sha1::Digest as _;
let mut hasher = sha1::Sha1::new();
hasher.update(format!("blob {}\0", bytes.len()).as_bytes());
hasher.update(bytes);
hasher.finalize().iter().map(|b| format!("{b:02x}")).collect()
}
fn encode_url_segment(seg: &str) -> String {
let mut out = String::with_capacity(seg.len());
for b in seg.bytes() {
@@ -603,10 +629,12 @@ 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(
fetcher: &dyn SkillSourceFetcher,
target: RepoRef<'_>,
subpath: &str,
pinned_tree_sha: Option<&str>,
cancel: &CancellationToken,
) -> IdeResult<PreparedSkillBundle> {
let RepoRef { owner, repo, git_ref } = target;
@@ -615,7 +643,23 @@ fn fetch_and_scan_bundle(
validate_git_ref(git_ref)?;
let normalized_subpath = normalize_subpath(subpath)?.unwrap_or_default();
let tree = fetcher.git_tree(target, cancel)?;
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"));
}
// 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(
ErrorKind::Protocol,
format!("{owner}/{repo}: GitHub returned tree {} instead of the previewed tree {sha}", tree.sha),
));
}
tree
}
None => fetcher.git_tree(target, cancel)?,
};
let prefix = if normalized_subpath.is_empty() { String::new() } else { format!("{normalized_subpath}/") };
let subtree_entries: Vec<&GitTreeEntry> = tree
@@ -647,7 +691,7 @@ fn fetch_and_scan_bundle(
let mut files = Vec::with_capacity(subtree_entries.len());
let mut scan_warnings = Vec::new();
let mut regular_files = Vec::new();
let mut in_root_symlinks = Vec::new();
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
let mut skill_markdown: Option<String> = None;
let mut actual_total = 0u64;
@@ -675,18 +719,7 @@ fn fetch_and_scan_bundle(
if is_symlink {
let target_raw = String::from_utf8_lossy(&bytes).trim().to_owned();
match resolve_in_root_symlink(&rel_path, &target_raw) {
Some(safe_target) => {
in_root_symlinks.push((rel_path.clone(), safe_target));
}
None => {
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::OutOfRootSymlink,
file: rel_str.to_owned(),
message: format!("Symlink target {target_raw:?} leaves the skill folder (omitted on install)"),
});
}
}
symlinks.push((rel_path, rel_str.to_owned(), target_raw));
files.push(RemoteSkillFile {
path: rel_str.to_owned(),
size: bytes.len() as u64,
@@ -734,6 +767,31 @@ 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",
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 skill 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"));
};
@@ -775,50 +833,30 @@ struct ParsedSkillMetadata {
fn parse_skill_markdown_metadata(folder_hint: &str, markdown: &str) -> IdeResult<ParsedSkillMetadata> {
let mut name: Option<String> = None;
let mut description: Option<String> = None;
let mut allowed_tools_raw: Vec<String> = Vec::new();
let normalized = markdown.strip_prefix('\u{feff}').unwrap_or(markdown);
if let Some(after_open) = normalized.strip_prefix("---\n").or_else(|| normalized.strip_prefix("---\r\n")) {
let mut current_list_key: Option<String> = None;
for raw_line in after_open.lines() {
let trimmed_end = raw_line.trim_end_matches('\r');
if matches!(trimmed_end.trim(), "---" | "...") {
break;
}
let trimmed = trimmed_end.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
if (trimmed_end.starts_with(' ') || trimmed_end.starts_with('\t'))
&& let Some(item) = trimmed.strip_prefix('-')
if trimmed.is_empty()
|| trimmed.starts_with('#')
|| trimmed_end.starts_with(' ')
|| trimmed_end.starts_with('\t')
{
if matches!(current_list_key.as_deref(), Some("allowed-tools" | "allowed_tools")) {
let val = unquote(item.trim());
if !val.is_empty() {
allowed_tools_raw.push(val.to_owned());
}
}
continue;
}
current_list_key = None;
if let Some((k, v)) = trimmed.split_once(':') {
let key = k.trim().to_ascii_lowercase();
let val = unquote(v.trim());
match key.as_str() {
"name" if !val.is_empty() => name = Some(val.to_owned()),
"description" if !val.is_empty() && !matches!(val, ">" | "|" | ">-" | "|-") => {
"description" if !val.is_empty() && !is_block_scalar_header(val) => {
description = Some(val.to_owned());
}
"allowed-tools" | "allowed_tools" => {
if val.is_empty() {
current_list_key = Some(key);
} else {
let inner = val.strip_prefix('[').and_then(|s| s.strip_suffix(']')).unwrap_or(val);
for token in split_allowed_tools(inner) {
allowed_tools_raw.push(token);
}
}
}
_ => {}
}
}
@@ -832,15 +870,86 @@ fn parse_skill_markdown_metadata(folder_hint: &str, markdown: &str) -> IdeResult
)));
}
let description = description.unwrap_or_default();
let shell_tools = allowed_tools_raw.into_iter().filter(|t| is_shell_tool_entry(t)).collect();
Ok(ParsedSkillMetadata { name: skill_name, description, shell_tools })
Ok(ParsedSkillMetadata { name: skill_name, description, shell_tools: frontmatter_shell_tools(markdown) })
}
fn split_allowed_tools(raw: &str) -> Vec<String> {
/// `|`, `>`, and their chomping/indentation variants (`>-`, `|+`, `|2-`, ...).
fn is_block_scalar_header(val: &str) -> bool {
let mut chars = val.chars();
matches!(chars.next(), Some('|' | '>')) && chars.all(|c| matches!(c, '+' | '-' | '1'..='9'))
}
/// Shell-capable entries granted by `allowed-tools` in the frontmatter.
///
/// This deliberately over-approximates YAML instead of parsing it: every token of the value — inline,
/// block scalar, flow or block sequence, continuation lines — is checked, and tokens a YAML loader could
/// turn into something else (aliases, escape sequences) count as grants. A false positive only adds a
/// warning; a missed grant hides one.
fn frontmatter_shell_tools(markdown: &str) -> Vec<String> {
let text = markdown.strip_prefix('\u{feff}').unwrap_or(markdown);
let mut lines = text.lines().skip_while(|l| l.trim().is_empty());
if lines.next().map(str::trim) != Some("---") {
return Vec::new();
}
let lines: Vec<&str> = lines.take_while(|l| !matches!(l.trim(), "---" | "...")).collect();
let mut tools: Vec<String> = Vec::new();
let mut i = 0;
while i < lines.len() {
let Some(rest) = after_allowed_tools_key(lines[i]) else {
i += 1;
continue;
};
let mut value = rest.to_owned();
i += 1;
while i < lines.len() && !is_plain_top_level_key(lines[i]) {
value.push('\n');
value.push_str(lines[i]);
i += 1;
}
for token in value_tokens(&value) {
let grants_shell = is_shell_tool_entry(&token) || token.starts_with('*') || token.contains('\\');
if grants_shell && !tools.contains(&token) {
tools.push(token);
}
}
}
tools
}
/// The text after an `allowed-tools` / `allowed_tools` / `allowedTools` key anywhere on `line`
/// (quoted keys and flow mappings included).
fn after_allowed_tools_key(line: &str) -> Option<&str> {
let lower = line.to_ascii_lowercase();
["allowed-tools", "allowed_tools", "allowedtools", "allowed tools"]
.iter()
.filter_map(|key| lower.find(key).map(|pos| pos + key.len()))
.min()
.map(|end| &line[end..])
}
/// An unindented `key:` line whose key is a plain word, which ends the previous key's value.
fn is_plain_top_level_key(line: &str) -> bool {
if !line.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_') {
return false;
}
let Some((key, rest)) = line.split_once(':') else { return false };
key.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | ' '))
&& (rest.is_empty() || rest.starts_with([' ', '\t']))
}
/// Splits a YAML value into candidate tool entries, keeping `Tool(args with spaces, commas)` whole.
fn value_tokens(value: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cur = String::new();
let mut depth = 0usize;
for ch in raw.chars() {
let mut flush = |cur: &mut String| {
let tok = cur.trim_start_matches([':', '-', '?', '&', '!', '|', '>']);
if !tok.is_empty() && !is_block_scalar_header(tok) {
out.push(tok.to_owned());
}
cur.clear();
};
for ch in value.chars() {
match ch {
'(' => {
depth += 1;
@@ -850,20 +959,13 @@ fn split_allowed_tools(raw: &str) -> Vec<String> {
depth = depth.saturating_sub(1);
cur.push(ch);
}
',' | ' ' if depth == 0 => {
let tok = unquote(cur.trim());
if !tok.is_empty() {
out.push(tok.to_owned());
}
cur.clear();
c if depth == 0 && (c.is_whitespace() || matches!(c, ',' | '[' | ']' | '{' | '}' | '"' | '\'')) => {
flush(&mut cur)
}
_ => cur.push(ch),
}
}
let tok = unquote(cur.trim());
if !tok.is_empty() {
out.push(tok.to_owned());
}
flush(&mut cur);
out
}
@@ -905,8 +1007,68 @@ fn validate_rel_skill_file(rel: &str) -> IdeResult<PathBuf> {
Ok(path.to_path_buf())
}
/// Returns `Some(target_path)` only when `target_raw` is a relative link that stays strictly inside the skill root.
fn resolve_in_root_symlink(link_rel: &Path, target_raw: &str) -> Option<PathBuf> {
/// The symlinks of one skill bundle, keyed by case-folded path so a link named `Dir` is also found as
/// `dir` (macOS and Windows file systems ignore case).
struct SymlinkGraph {
links: HashMap<Vec<String>, String>,
}
/// Maximum symlinks followed while resolving one target (Linux's `MAXSYMLINKS`).
const MAX_SYMLINK_HOPS: usize = 40;
impl SymlinkGraph {
fn new<'a>(links: impl Iterator<Item = (&'a Path, &'a str)>) -> Self {
Self { links: links.map(|(path, target)| (fold_path(path), target.to_owned())).collect() }
}
/// The nearest symlink among `path`'s ancestors, if any.
fn symlink_ancestor(&self, path: &Path) -> Option<String> {
let folded = fold_path(path);
(1..folded.len()).find(|&len| self.links.contains_key(&folded[..len])).map(|len| folded[..len].join("/"))
}
/// Whether `target_raw`, read from the link at `link_rel`, resolves strictly inside the skill root,
/// following every other symlink of the bundle it passes through.
fn stays_inside(&self, link_rel: &Path, target_raw: &str) -> bool {
let mut dir = fold_path(link_rel);
dir.pop();
let Some(mut pending) = relative_link_segments(target_raw) else { return false };
let mut hops = 0;
while let Some(seg) = pending.pop_front() {
if seg == ".." {
if dir.pop().is_none() {
return false;
}
continue;
}
dir.push(seg);
if let Some(next) = self.links.get(&dir) {
hops += 1;
let Some(mut next_segments) = relative_link_segments(next) else { return false };
if hops > MAX_SYMLINK_HOPS {
return false;
}
dir.pop();
next_segments.extend(pending);
pending = next_segments;
}
}
!dir.is_empty()
}
}
/// Case-folded normal components of a validated relative path.
fn fold_path(path: &Path) -> Vec<String> {
path.components()
.filter_map(|c| match c {
Component::Normal(s) => Some(s.to_string_lossy().to_lowercase()),
_ => None,
})
.collect()
}
/// Case-folded segments of a relative symlink target without `.`; `None` for absolute or Windows-style targets.
fn relative_link_segments(target_raw: &str) -> Option<VecDeque<String>> {
if target_raw.is_empty()
|| target_raw.starts_with('/')
|| target_raw.starts_with('~')
@@ -915,30 +1077,7 @@ fn resolve_in_root_symlink(link_rel: &Path, target_raw: &str) -> Option<PathBuf>
{
return None;
}
let mut stack: Vec<&std::ffi::OsStr> = link_rel
.parent()
.map(|p| {
p.components()
.filter_map(|c| match c {
Component::Normal(s) => Some(s),
_ => None,
})
.collect()
})
.unwrap_or_default();
for seg in target_raw.split('/') {
match seg {
"" | "." => {}
".." => {
stack.pop()?;
}
_ => stack.push(std::ffi::OsStr::new(seg)),
}
}
if stack.is_empty() {
return None;
}
Some(PathBuf::from(target_raw))
Some(target_raw.split('/').filter(|s| !s.is_empty() && *s != ".").map(str::to_lowercase).collect())
}
fn is_executable_or_script_path(rel: &Path) -> bool {
@@ -979,6 +1118,69 @@ fn scan_hidden_unicode(file: &str, text: &str, warnings: &mut Vec<SkillScanWarni
}
}
/// Creates the missing parent directories of `rel` under `root`, refusing to pass through a symlink or
/// anything else that is not a real directory.
fn create_parent_dirs_no_follow(root: &Path, rel: &Path) -> IdeResult<()> {
let mut dir = root.to_path_buf();
let Some(parent) = rel.parent() else { return Ok(()) };
for component in parent.components() {
dir.push(component);
match std::fs::symlink_metadata(&dir) {
Ok(meta) if meta.is_dir() => {}
Ok(_) => {
return Err(IdeError::invalid(format!(
"Skill path {:?} passes through a symlink or file",
rel.display().to_string()
)));
}
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)]
fn link_resolves_inside(root: &Path, link: &Path) -> bool {
let (Some(parent), Ok(target)) = (link.parent(), std::fs::read_link(link)) else { return false };
let Ok(mut dir) = std::fs::canonicalize(parent) else { return false };
if !dir.starts_with(root) || target.is_absolute() {
return false;
}
let mut pending: VecDeque<PathBuf> = target.components().map(|c| PathBuf::from(c.as_os_str())).collect();
let mut hops = 0;
while let Some(seg) = pending.pop_front() {
match seg.to_str() {
Some(".") => continue,
Some("..") => {
if dir == root {
return false;
}
dir.pop();
continue;
}
_ => {}
}
let next = dir.join(&seg);
match std::fs::symlink_metadata(&next) {
Ok(meta) if meta.file_type().is_symlink() => {
hops += 1;
let Ok(next_target) = std::fs::read_link(&next) else { return false };
if hops > MAX_SYMLINK_HOPS || next_target.is_absolute() {
return false;
}
for c in next_target.components().rev() {
pending.push_front(PathBuf::from(c.as_os_str()));
}
}
_ => dir = next,
}
}
dir != root
}
/// Previews a single skill from `target` (`subpath`) and runs the static security scan.
pub fn preview_skill(
fetcher: &dyn SkillSourceFetcher,
@@ -989,7 +1191,7 @@ pub fn preview_skill(
cancel: &CancellationToken,
) -> IdeResult<RemoteSkillPreview> {
let RepoRef { owner, repo, git_ref } = target;
let bundle = fetch_and_scan_bundle(fetcher, target, subpath, cancel)?;
let bundle = fetch_and_scan_bundle(fetcher, target, subpath, None, cancel)?;
let already_installed_user = user_home.is_some_and(|h| h.join(".agents/skills").join(&bundle.skill_name).exists());
let already_installed_workspace =
workspace_root.is_some_and(|w| w.join(".agents/skills").join(&bundle.skill_name).exists());
@@ -1034,6 +1236,7 @@ pub fn install_skill(
fetcher,
RepoRef { owner: &req.owner, repo: &req.repo, git_ref: &req.git_ref },
&req.subpath,
Some(&req.tree_sha),
cancel,
)?;
if !bundle.scan_warnings.is_empty() && !req.confirm_warnings {
@@ -1056,10 +1259,8 @@ pub fn install_skill(
let write_res = (|| -> IdeResult<()> {
std::fs::create_dir_all(&staging)?;
for (rel_path, bytes, is_exec) in &bundle.regular_files {
create_parent_dirs_no_follow(&staging, rel_path)?;
let dest = staging.join(rel_path);
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&dest, bytes)?;
#[cfg(unix)]
if *is_exec {
@@ -1070,10 +1271,8 @@ pub fn install_skill(
let _ = is_exec;
}
for (rel_link, target) in &bundle.in_root_symlinks {
create_parent_dirs_no_follow(&staging, rel_link)?;
let dest = staging.join(rel_link);
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
#[cfg(unix)]
std::os::unix::fs::symlink(target, &dest)?;
#[cfg(not(unix))]
@@ -1084,6 +1283,20 @@ pub fn install_skill(
}
}
}
// Backstop for the scan's graph check: resolve every created link on disk, where the file
// system's own case and Unicode folding apply.
#[cfg(unix)]
{
let root = std::fs::canonicalize(&staging)?;
for (rel_link, _) in &bundle.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()
)));
}
}
}
let backup = if final_dir.exists() {
let bak = target_root.join(format!(".old-{}-{nonce}", bundle.skill_name));
std::fs::rename(&final_dir, &bak)?;
@@ -1128,8 +1341,8 @@ mod tests {
fn add_tree(&mut self, git_ref: &str, entries: Vec<(&str, &str, &[u8])>) {
let mut tree_entries = Vec::new();
for (idx, (path, mode, content)) in entries.into_iter().enumerate() {
let sha = format!("{idx:040x}");
for (path, mode, content) in entries {
let sha = git_blob_id(content);
self.blobs.insert(sha.clone(), content.to_vec());
tree_entries.push(GitTreeEntry {
path: path.to_owned(),
@@ -1139,10 +1352,14 @@ mod tests {
size: Some(content.len() as u64),
});
}
self.trees.insert(
git_ref.to_owned(),
GitTree { sha: "deadbeef".repeat(5), truncated: false, tree: tree_entries },
);
let sha = git_blob_id(format!("{git_ref}:{}", self.trees.len()).as_bytes());
let tree = GitTree { sha: sha.clone(), truncated: false, tree: tree_entries };
self.trees.insert(sha.clone(), tree.clone());
self.trees.insert(git_ref.to_owned(), tree);
}
fn tree_sha(&self, git_ref: &str) -> String {
self.trees[git_ref].sha.clone()
}
}
@@ -1251,6 +1468,7 @@ mod tests {
owner: "acme".into(),
repo: "skills".into(),
git_ref: "main".into(),
tree_sha: fetcher.tree_sha("main"),
subpath: "skills/clean-skill".into(),
scope: McpScope::User,
confirm_warnings: false,
@@ -1273,6 +1491,7 @@ mod tests {
owner: "acme".into(),
repo: "skills".into(),
git_ref: "main".into(),
tree_sha: fetcher.tree_sha("main"),
subpath: "skills/clean-skill".into(),
scope: McpScope::User,
confirm_warnings: false,
@@ -1307,6 +1526,7 @@ mod tests {
owner: "acme".into(),
repo: "skills".into(),
git_ref: "main".into(),
tree_sha: fetcher.tree_sha("main"),
subpath: "skills/risky-skill".into(),
scope: McpScope::Workspace,
confirm_warnings: false,
@@ -1325,6 +1545,7 @@ mod tests {
owner: "acme".into(),
repo: "skills".into(),
git_ref: "main".into(),
tree_sha: fetcher.tree_sha("main"),
subpath: "skills/risky-skill".into(),
scope: McpScope::Workspace,
confirm_warnings: true,
@@ -1341,6 +1562,199 @@ mod tests {
assert!(!ws_installed.join("escape-link").exists(), "out-of-root symlink omitted on disk");
}
fn install_req(fetcher: &FakeFetcher, git_ref: &str, tree_sha: Option<String>) -> InstallRemoteSkillRequest {
InstallRemoteSkillRequest {
owner: "acme".into(),
repo: "skills".into(),
git_ref: git_ref.into(),
tree_sha: tree_sha.unwrap_or_else(|| fetcher.tree_sha(git_ref)),
subpath: String::new(),
scope: McpScope::User,
confirm_warnings: true,
overwrite: false,
}
}
fn preview_main(fetcher: &FakeFetcher, home: &Path) -> IdeResult<RemoteSkillPreview> {
preview_skill(
fetcher,
RepoRef { owner: "acme", repo: "skills", git_ref: "main" },
"",
Some(home),
None,
&CancellationToken::new(),
)
}
const SKILL_MD: &[u8] = b"---\nname: linky\ndescription: Links\n---\nBody\n";
#[test]
fn rejects_entries_nested_under_a_symlink() {
let mut fetcher = FakeFetcher::new();
fetcher.add_tree(
"main",
vec![
("SKILL.md", "100644", SKILL_MD),
("sub2/keep.md", "100644", b"x"),
("d1/d2/d3/sub", "120000", b"../../../sub2"),
("d1/d2/d3/sub/escape", "120000", b"../../../outside"),
("d1/d2/d3/sub/escape/deeper", "120000", b"x"),
],
);
let tmp = tempfile::tempdir().unwrap();
let err = preview_main(&fetcher, tmp.path()).unwrap_err();
assert!(err.message.contains("inside symlink"), "{err:?}");
let err = install_skill(
&fetcher,
&install_req(&fetcher, "main", None),
Some(tmp.path()),
None,
&CancellationToken::new(),
)
.unwrap_err();
assert!(err.message.contains("inside symlink"), "{err:?}");
assert!(!tmp.path().join(".agents/outside").exists());
// Case-only differences still count on case-insensitive file systems.
let mut fetcher = FakeFetcher::new();
fetcher.add_tree(
"main",
vec![("SKILL.md", "100644", SKILL_MD), ("Link", "120000", b"refs"), ("link/x", "120000", b"../..")],
);
assert!(preview_main(&fetcher, tmp.path()).unwrap_err().message.contains("inside symlink"));
}
#[test]
fn symlink_targets_are_resolved_through_other_links() {
let mut fetcher = FakeFetcher::new();
fetcher.add_tree(
"main",
vec![
("SKILL.md", "100644", SKILL_MD),
("a/b/doc.md", "100644", b"doc"),
("a/b/up", "120000", b".."),
("a/b/Up2", "120000", b".."),
("ok", "120000", b"a/b/up/b/doc.md"),
("escape", "120000", b"a/b/up/x/../../.."),
("escape-case", "120000", b"a/b/up2/x/../../.."),
("loop1", "120000", b"loop2/x"),
("loop2", "120000", b"loop1"),
],
);
let tmp = tempfile::tempdir().unwrap();
let preview = preview_main(&fetcher, tmp.path()).unwrap();
let mut flagged: Vec<&str> = preview
.scan_warnings
.iter()
.filter(|w| w.kind == SkillScanWarningKind::OutOfRootSymlink)
.map(|w| w.file.as_str())
.collect();
flagged.sort();
assert_eq!(flagged, ["escape", "escape-case", "loop1", "loop2"]);
let dir = install_skill(
&fetcher,
&install_req(&fetcher, "main", None),
Some(tmp.path()),
None,
&CancellationToken::new(),
)
.unwrap();
#[cfg(unix)]
assert_eq!(std::fs::read_to_string(dir.join("ok")).unwrap(), "doc");
for omitted in ["escape", "escape-case", "loop1", "loop2"] {
assert!(std::fs::symlink_metadata(dir.join(omitted)).is_err(), "{omitted}");
}
}
#[cfg(unix)]
#[test]
fn install_writes_refuse_to_pass_through_symlinks_on_disk() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
std::fs::create_dir_all(&root).unwrap();
std::os::unix::fs::symlink(tmp.path(), root.join("out")).unwrap();
let err = create_parent_dirs_no_follow(&root, Path::new("out/escaped/file")).unwrap_err();
assert!(err.message.contains("symlink"), "{err:?}");
assert!(!tmp.path().join("escaped").exists());
let canonical = std::fs::canonicalize(&root).unwrap();
std::fs::create_dir_all(root.join("a")).unwrap();
std::os::unix::fs::symlink("..", root.join("a/up")).unwrap();
std::os::unix::fs::symlink("up/a", root.join("a/ok")).unwrap();
std::os::unix::fs::symlink("up/a/up/..", root.join("a/bad")).unwrap();
assert!(link_resolves_inside(&canonical, &root.join("a/ok")));
assert!(!link_resolves_inside(&canonical, &root.join("a/up")), "link to the root itself");
assert!(!link_resolves_inside(&canonical, &root.join("a/bad")));
}
#[test]
fn allowed_tools_shell_grants_are_found_in_any_yaml_form() {
let shell = |fm: &str| frontmatter_shell_tools(&format!("---\nname: x\n{fm}\n---\nbody\n"));
for fm in [
"allowed-tools: >\n Bash",
"allowed-tools: |-\n Read\n Bash(git:*)",
"allowed-tools: >2+\n Bash",
"allowed-tools: Read\n Bash",
"allowed-tools: [Read,\n Bash]",
"allowed-tools:\n- Read\n- Bash",
"allowed-tools:\n - Read\n - \"Bash(git commit:*)\"",
"\"allowed-tools\": Bash",
"'allowed_tools':Bash",
"allowedTools: Read, Bash",
"allowed-tools: Read # comment\n Bash",
"tools: &t Bash\nallowed-tools: *t",
"allowed-tools: \"\\x42ash\"",
"allowed-tools: '*'",
] {
assert!(!shell(fm).is_empty(), "missed shell grant in {fm:?}");
}
for fm in ["allowed-tools: Read Grep", "allowed-tools:\n - Read\n - Edit\ndescription: >\n Bash in prose"] {
assert!(shell(fm).is_empty(), "false positive for {fm:?}: {:?}", shell(fm));
}
// Leniently opened fences still count.
assert!(!frontmatter_shell_tools("\n--- \nallowed-tools: >\n Bash\n---\n").is_empty());
let mut fetcher = FakeFetcher::new();
fetcher.add_tree(
"main",
vec![("SKILL.md", "100644", b"---\nname: benign\ndescription: x\nallowed-tools: >\n Bash\n---\n")],
);
let tmp = tempfile::tempdir().unwrap();
let preview = preview_main(&fetcher, tmp.path()).unwrap();
assert!(preview.scan_warnings.iter().any(|w| w.kind == SkillScanWarningKind::AllowedToolsShell));
}
#[test]
fn install_uses_the_previewed_tree_even_after_the_ref_moves() {
let mut fetcher = FakeFetcher::new();
fetcher.add_tree("main", vec![("SKILL.md", "100644", SKILL_MD)]);
let tmp = tempfile::tempdir().unwrap();
let preview = preview_main(&fetcher, tmp.path()).unwrap();
assert!(preview.scan_warnings.is_empty());
// `main` moves to a tree with a script after the user reviewed the preview.
fetcher.add_tree(
"main",
vec![("SKILL.md", "100644", SKILL_MD), ("scripts/payload.sh", "100755", b"#!/bin/sh\nid\n")],
);
assert_ne!(fetcher.tree_sha("main"), preview.tree_sha);
let mut req = install_req(&fetcher, "main", Some(preview.tree_sha.clone()));
req.confirm_warnings = false;
let dir = install_skill(&fetcher, &req, Some(tmp.path()), None, &CancellationToken::new()).unwrap();
assert!(dir.join("SKILL.md").is_file());
assert!(!dir.join("scripts").exists());
let bad = install_req(&fetcher, "main", Some("not-a-sha".into()));
assert!(install_skill(&fetcher, &bad, Some(tmp.path()), None, &CancellationToken::new()).is_err());
}
#[test]
fn git_blob_id_matches_git() {
assert_eq!(git_blob_id(b""), "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391");
assert_eq!(git_blob_id(b"hello\n"), "ce013625030ba8dba906f756967f9e9ca394464a");
}
#[test]
#[ignore = "hits live GitHub API"]
fn live_github_browse_preview_and_install_smoke() {
@@ -1369,6 +1783,7 @@ mod tests {
owner: browsed.owner,
repo: browsed.repo,
git_ref: browsed.git_ref,
tree_sha: preview.tree_sha,
subpath: browsed.skills[0].subpath.clone(),
scope: McpScope::User,
confirm_warnings: true,
+657 -15
Переглянути файл
@@ -67,6 +67,10 @@ struct FakeAgent {
forks: Mutex<Vec<Value>>,
/// 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)>>,
/// Recorded `(method, _meta.openidea.memory)` payloads across `session/new`, `session/load`, and `session/fork`.
memory_calls: Mutex<Vec<(String, Option<Value>)>>,
}
impl FakeAgent {
@@ -177,6 +181,7 @@ impl Handler for FakeAgent {
})
.unwrap_or_default();
self.mcp_calls.lock().push((method.to_owned(), names));
self.memory_calls.lock().push((method.to_owned(), params.pointer("/_meta/openidea/memory").cloned()));
if params.pointer("/_meta/openidea/ephemeral") == Some(&json!(true)) {
self.calls.lock().push("ephemeral".into());
}
@@ -271,6 +276,9 @@ impl Handler for FakeAgent {
}
"session/prompt" => {
self.prompts.lock().push(params.get("prompt").cloned().unwrap_or(Value::Null));
if let Some(err) = self.prompt_errors.lock().pop_front() {
return Err(err);
}
// `!` commands run since the last message come first; the message follows.
let first = match params.pointer("/prompt/0/text").and_then(Value::as_str) {
Some(t) if t.starts_with("<bash-input>") => 1,
@@ -281,6 +289,10 @@ impl Handler for FakeAgent {
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
if text.starts_with("The previous turn was interrupted because ") {
self.say(&session, "resumed cleanly");
return Ok(json!({"stopReason": "end_turn"}));
}
if text.starts_with("<send_user_message_question_reply>") {
self.say(&session, "answer received");
return Ok(json!({"stopReason": "end_turn"}));
@@ -644,7 +656,7 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.shutdown();
shut_down(&mgr, &agent).await;
let restored_agent = Arc::new(FakeAgent::default());
let restored = manager(tmp.path(), restored_agent.clone());
// Listing the tasks leaves the conversation on disk until something asks for it.
@@ -663,7 +675,8 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
#[tokio::test(flavor = "multi_thread")]
async fn an_archived_task_keeps_no_command_list_and_completes_the_known_one() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
project_root: None,
@@ -684,7 +697,7 @@ async fn an_archived_task_keeps_no_command_list_and_completes_the_known_one() {
mgr.archive(&task.id).unwrap();
assert!(snapshot(&mgr).commands.is_empty());
assert!(names(mgr.commands("claude", Some(&task.id)).await.unwrap()).contains(&"review".to_owned()));
mgr.shutdown();
shut_down(&mgr, &agent).await;
// A list saved with an archived task (by an earlier version) isn't read back.
let other = tempfile::tempdir().unwrap();
@@ -704,13 +717,27 @@ async fn an_archived_task_keeps_no_command_list_and_completes_the_known_one() {
async fn archiving_a_task_keeps_the_permission_answer_that_is_settling() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let shut_down = ShutDown(&mgr);
let (published, mut requests) = tokio::sync::mpsc::unbounded_channel();
mgr.subscribe_as(
"",
Arc::new(move |event| {
if let AgentEvent::Entry { task, entry: AgentEntry::Permission { id, chosen: None, .. }, .. } = event {
let _ = published.send((task, id));
}
}),
);
let task = mgr
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
// The status becomes visible before the request has enqueued its initial delivery.
let (owner, permission) = tokio::time::timeout(Duration::from_secs(5), requests.recv())
.await
.expect("permission request was never published")
.unwrap();
assert_eq!(owner, task.id);
let handle = mgr.task(&task.id).unwrap();
let permission = *handle.permissions.lock().keys().next().unwrap();
let answered = |e: &AgentEntry| matches!(e, AgentEntry::Permission { chosen: Some(name), .. } if name == "Allow");
let status_at_answer = tokio::task::block_in_place(|| {
@@ -737,7 +764,7 @@ async fn archiving_a_task_keeps_the_permission_answer_that_is_settling() {
})
.await
.expect("the archived turn did not finish");
mgr.shutdown();
drop(shut_down);
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
assert_eq!(restored.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Archived);
@@ -764,7 +791,7 @@ async fn a_conversation_that_cannot_be_read_is_never_saved_over() {
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.shutdown();
shut_down(&mgr, &agent).await;
// In a store of its own: a late save of the first manager can't touch it.
let name = format!("{}.json", task.id);
let mut file: Value =
@@ -803,7 +830,7 @@ async fn an_ephemeral_task_is_not_saved_and_asks_for_an_unsaved_session() {
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
assert_eq!(agent.calls.lock().iter().any(|c| c == "ephemeral"), ephemeral);
mgr.shutdown();
shut_down(&mgr, &agent).await;
// The caller never deleted it (its window closed): only a saved task comes back.
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
assert_eq!(restored.task(&task.id).is_ok(), !ephemeral);
@@ -1262,6 +1289,7 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
"plan",
"mcp",
"skills",
"memories",
"status",
"review",
"review-branch",
@@ -1301,6 +1329,7 @@ async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metada
"plan",
"mcp",
"skills",
"memories",
"status",
"review",
"review-branch",
@@ -1365,6 +1394,19 @@ async fn wait_for(mgr: &AgentManager, id: &str, status: AgentStatus) {
panic!("task never reached {status:?} (is {s:?})");
}
/// Shuts `mgr` down and waits until `agent` has seen each of its connections end. A fake still
/// waiting for an answer holds a blocking thread until its side reads that end; a test that
/// returned first would drop the runtime, and the drop waits for that thread forever.
async fn shut_down(mgr: &AgentManager, agent: &FakeAgent) {
mgr.shutdown();
let servers = agent.servers.lock().clone();
for server in servers {
tokio::time::timeout(Duration::from_secs(5), server.closed())
.await
.expect("the agent's side of the connection closes");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
let tmp = tempfile::tempdir().unwrap();
@@ -1945,7 +1987,8 @@ async fn shutdown_during_session_open_kills_connecting_peer_without_failing() {
#[tokio::test(flavor = "multi_thread")]
async fn shutdown_during_permission_request_settles_without_failing() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("decide"),
@@ -1957,7 +2000,7 @@ async fn shutdown_during_permission_request_settles_without_failing() {
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.shutdown();
shut_down(&mgr, &agent).await;
tokio::time::sleep(TURN_GRACE * 3).await;
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
@@ -3602,7 +3645,7 @@ fn retry_updates_become_a_countdown() {
json!({"sessionUpdate": RETRY_UPDATE, "attempt": 2, "maxRetries": 10, "retryDelayMs": 1500, "error": ""});
assert_eq!(
retry_of(&update, 1000.0),
Some(AgentRetry { attempt: 2, max_retries: Some(10), retry_at_ms: 2500.0, error: None })
Some(AgentRetry { attempt: 2, max_retries: Some(10), retry_at_ms: 2500.0, error: None, deadline_ms: None })
);
assert_eq!(retry_of(&json!({"sessionUpdate": RETRY_UPDATE}), 0.0), None, "no attempt");
}
@@ -5933,6 +5976,7 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
idle: false,
skill_overrides: BTreeMap::new(),
memory_overrides: None,
ephemeral: false,
})
.await
@@ -5961,6 +6005,127 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cursor_and_hermes() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::write(root.join("AGENTS.md"), "# Workspace Rules\nRun vitest first.\n").unwrap();
std::fs::write(root.join("CLAUDE.local.md"), "Noisy local draft\n").unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(root, agent.clone());
mgr.set_memory_policy_hook(Box::new({
let root = root.to_path_buf();
move || memory::MemoryPolicy {
user: AgentMemorySettings { auto_memory: AutoMemoryMode::ReadWrite, ..Default::default() },
workspace: AgentMemorySettings::default(),
workspace_trusted: true,
workspace_roots: vec![root.clone()],
}
}));
// 1. Claude task with initial `ReadOnly` + muted `CLAUDE.local.md`, then updated while idle, forked, and deleted.
let claude_task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
memory_overrides: Some(AgentMemoryOverrides {
auto_memory: Some(AutoMemoryMode::ReadOnly),
entries: BTreeMap::from([("claudeWorkspace::CLAUDE.local.md".into(), AgentMemoryMode::Off)]),
}),
idle: false,
ephemeral: false,
})
.await
.unwrap();
wait_for(&mgr, &claude_task.id, AgentStatus::Ready).await;
{
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
assert_eq!(method, "session/new");
let mem = payload.unwrap();
assert_eq!(mem["autoMemory"], "readOnly");
assert_eq!(mem["claudeAutoMemory"], false);
assert!(
mem["claudeMdExcludes"]
.as_array()
.unwrap()
.iter()
.any(|v| v.as_str().is_some_and(|s| s.ends_with("CLAUDE.local.md")))
);
}
// Updating `set_memory_overrides` while idle recycles the session so the next turn reloads (`session/load`) with `Off`.
let updated = mgr
.set_memory_overrides(
&claude_task.id,
AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off), entries: BTreeMap::new() },
)
.unwrap();
assert_eq!(updated.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::Off));
mgr.prompt(&claude_task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &claude_task.id, AgentStatus::Ready).await;
{
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
assert_eq!(method, "session/load");
assert_eq!(payload.unwrap()["autoMemory"], "off");
}
// Forking carries `memory_overrides` onto the forked task and sends `_meta.openidea.memory` on `session/fork`.
let forked = mgr.fork(&claude_task.id, None).await.unwrap();
assert_eq!(forked.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::Off));
{
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
assert_eq!(method, "session/fork");
assert_eq!(payload.unwrap()["autoMemory"], "off");
}
mgr.delete(&claude_task.id, false).await.unwrap();
assert!(!memory::farm_dir(&mgr.shared.paths.store_dir, &claude_task.id).exists());
// 2. Codex, Copilot, Cursor (ACP), and Hermes (ACP) each receive their normalized `_meta.openidea.memory`.
for (provider, expected_field) in [
("codex", Some("codexUseMemories")),
("copilot", Some("copilotEnableMemory")),
("cursor", None),
("hermes", None),
] {
let t = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: provider.into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
memory_overrides: Some(AgentMemoryOverrides {
auto_memory: Some(AutoMemoryMode::ReadOnly),
entries: BTreeMap::new(),
}),
idle: false,
ephemeral: false,
})
.await
.unwrap();
wait_for(&mgr, &t.id, AgentStatus::Ready).await;
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
assert_eq!(method, "session/new", "provider {provider}");
let mem = payload.expect("memory delivery present");
assert_eq!(mem["autoMemory"], "readOnly", "provider {provider}");
if let Some(field) = expected_field {
assert!(mem.get(field).is_some(), "provider {provider} missing {field}: {mem}");
}
}
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idle() {
let tmp = tempfile::tempdir().unwrap();
@@ -5996,6 +6161,7 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl
("tdd".into(), AgentSkillMode::Auto),
("noisy".into(), AgentSkillMode::Off),
]),
memory_overrides: None,
ephemeral: false,
})
.await
@@ -6140,6 +6306,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
memory_overrides: None,
ephemeral: false,
})
.await
@@ -6167,6 +6334,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
memory_overrides: None,
ephemeral: false,
})
.await
@@ -6246,20 +6414,20 @@ done
#[test]
fn session_params_name_the_servers_off() {
let mcp = McpForSession { servers: vec![json!({ "name": "docs" })], off: vec!["github".into()] };
let params = session_params("/p", &mcp, None, &[]);
let params = session_params("/p", &mcp, None, None, &[]);
assert_eq!(params["cwd"], "/p");
assert_eq!(params["mcpServers"][0]["name"], "docs");
assert_eq!(params["_meta"]["openidea"]["mcpServersOff"], json!(["github"]));
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
assert!(session_params("/p", &none, None, &[]).get("_meta").is_none());
assert!(session_params("/p", &none, None, None, &[]).get("_meta").is_none());
}
#[test]
fn session_params_offer_the_workspace_roots() {
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
let params = session_params("/w/api", &none, None, &["/w/web".to_owned()]);
let params = session_params("/w/api", &none, None, None, &["/w/web".to_owned()]);
assert_eq!(params["additionalDirectories"], json!(["/w/web"]));
assert!(session_params("/w/api", &none, None, &[]).get("additionalDirectories").is_none());
assert!(session_params("/w/api", &none, None, None, &[]).get("additionalDirectories").is_none());
}
#[tokio::test]
@@ -6286,3 +6454,477 @@ async fn workspace_roots_go_to_agents_that_take_them() {
assert_eq!(mgr.shared.additional_directories(&takes, &worktree, Some(&api)), vec![web]);
assert!(mgr.shared.additional_directories(&init(json!({})), &api, None).is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn shutdown_reasons_mark_only_in_flight_tasks_interrupted_and_keep_idle_tasks_clean() {
for (shutdown_reason, expected) in [
(AgentShutdownReason::WindowClose, InterruptionReason::WindowClose),
(AgentShutdownReason::Quit, InterruptionReason::Quit),
(AgentShutdownReason::Restart, InterruptionReason::Restart),
(AgentShutdownReason::BackendUpgrade, InterruptionReason::BackendUpgrade),
(AgentShutdownReason::BackendStop, InterruptionReason::BackendStop),
] {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let idle = mgr
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &idle.id, AgentStatus::Ready).await;
mgr.mark_read(&idle.id).unwrap();
let active = mgr
.create(NewAgentTask { prompt: text("wait"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &active.id, AgentStatus::Running).await;
mgr.shutdown_with(shutdown_reason);
let reopened = manager(tmp.path(), Arc::new(FakeAgent::default()));
let tasks = reopened.subscribe_as("", Arc::new(|_| {}));
let restored_idle = tasks.iter().find(|t| t.id == idle.id).unwrap();
assert_eq!(restored_idle.status, AgentStatus::Ready);
assert!(restored_idle.interrupted.is_none(), "idle keepalive task must not become interrupted");
assert!(!restored_idle.unread);
let restored_active = tasks.iter().find(|t| t.id == active.id).unwrap();
assert_eq!(restored_active.status, AgentStatus::Ready);
assert!(restored_active.unread);
let intr = restored_active.interrupted.as_deref().expect("active task marked interrupted");
assert_eq!(intr.reason, expected);
assert!(!intr.was_waiting_for_input);
reopened.shutdown();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn unexpected_exit_on_disk_tags_interrupted_lazily_without_rewriting_untouched_files() {
let tmp = tempfile::tempdir().unwrap();
let store = tmp.path().join("store");
std::fs::create_dir_all(&store).unwrap();
let crashed_running = json!({
"task": {
"id": "crash-run",
"title": "Refactor auth",
"provider": "claude",
"model": "big",
"status": "running",
"isolation": "local",
"cwd": tmp.path(),
"branch": null,
"base": null,
"baseCommit": null,
"error": null,
"createdMs": 100.0,
"updatedMs": 250.0,
"config": [{"id": "mode", "name": "Mode", "category": "mode", "current": "ask", "via": "mode", "values": []}],
"commands": [],
"usage": null,
"queue": [],
"capabilities": {},
"resetsMs": null,
"retry": null
},
"sessionId": "s1",
"entries": [
{"type": "user", "text": "refactor", "attachments": [], "sentMs": 100.0, "doneMs": null, "steered": false},
{"type": "tool", "id": "t1", "title": "cargo check", "kind": "execute", "status": "running", "locations": [], "output": null, "diffs": []}
],
"wanted": []
});
let crashed_input = json!({
"task": {
"id": "crash-input",
"title": "Needs approval",
"provider": "claude",
"model": "big",
"status": "needsInput",
"isolation": "local",
"cwd": tmp.path(),
"branch": null,
"base": null,
"baseCommit": null,
"error": null,
"createdMs": 100.0,
"updatedMs": 300.0,
"config": [],
"commands": [],
"usage": null,
"queue": [],
"capabilities": {},
"resetsMs": null,
"retry": null
},
"sessionId": "s2",
"entries": [],
"wanted": []
});
let run_path = store.join("crash-run.json");
let input_path = store.join("crash-input.json");
let raw_run = serde_json::to_vec(&crashed_running).unwrap();
std::fs::write(&run_path, &raw_run).unwrap();
std::fs::write(&input_path, serde_json::to_vec(&crashed_input).unwrap()).unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
// Conversations stay lazy on disk during startup.
assert!(!mgr.task("crash-run").unwrap().state.lock().history.is_loaded());
let tasks = mgr.subscribe_as("", Arc::new(|_| {}));
let r = tasks.iter().find(|t| t.id == "crash-run").unwrap();
assert_eq!(r.status, AgentStatus::Ready);
assert!(r.unread);
assert_eq!(r.interrupted.as_ref().unwrap().reason, InterruptionReason::UnexpectedExit);
assert!(!r.interrupted.as_ref().unwrap().was_waiting_for_input);
assert_eq!(r.interrupted.as_ref().unwrap().approval_mode.as_deref(), Some("mode=ask"));
let inp = tasks.iter().find(|t| t.id == "crash-input").unwrap();
assert_eq!(inp.interrupted.as_ref().unwrap().reason, InterruptionReason::UnexpectedExit);
assert!(inp.interrupted.as_ref().unwrap().was_waiting_for_input);
// Shutting down without touching the task does not eagerly load or rewrite its conversation file.
mgr.shutdown();
assert_eq!(std::fs::read(&run_path).unwrap(), raw_run);
}
#[tokio::test(flavor = "multi_thread")]
async fn manual_resume_appends_recovery_turn_drains_queue_and_dismiss_clears_state() {
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(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Running).await;
// Queue a follow-up message before window close.
mgr.prompt(&task.id, text("again"), false).await.unwrap();
mgr.shutdown_with(AgentShutdownReason::WindowClose);
let agent2 = Arc::new(FakeAgent::default());
let mgr2 = manager(tmp.path(), agent2.clone());
let resumed = mgr2.resume_all_interrupted().unwrap();
assert_eq!(resumed, vec![task.id.clone()]);
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
let snap = mgr2.task(&task.id).unwrap().state.lock().snapshot();
assert!(snap.interrupted.is_none());
assert!(snap.queue.is_empty(), "queued message drained after continuation turn");
let entries = mgr2.entries(&task.id, None).unwrap();
assert!(entries.iter().any(|e| matches!(
e,
AgentEntry::User { steered: false, recovery: Some(InterruptionReason::WindowClose), .. }
)));
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "resumed cleanly")));
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "second turn")));
// Dismissing an interrupted task clears its interrupted & unread state without sending a prompt.
let task2 = mgr2
.create(NewAgentTask { prompt: text("wait"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr2, &task2.id, AgentStatus::Running).await;
mgr2.shutdown_with(AgentShutdownReason::Quit);
let mgr3 = manager(tmp.path(), Arc::new(FakeAgent::default()));
mgr3.dismiss_interrupted(&task2.id).unwrap();
let snap2 = mgr3.task(&task2.id).unwrap().state.lock().snapshot();
assert!(snap2.interrupted.is_none());
assert!(!snap2.unread);
mgr3.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn interrupted_during_starting_before_session_new_resumes_original_prompt_without_duplicate() {
let tmp = tempfile::tempdir().unwrap();
let slow_agent = Arc::new(FakeAgent::default());
slow_agent.hold_session_new.store(true, Ordering::Release);
let mgr = manager(tmp.path(), slow_agent);
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Starting).await;
mgr.shutdown_with(AgentShutdownReason::Restart);
let fast_agent = Arc::new(FakeAgent::default());
let mgr2 = manager(tmp.path(), fast_agent.clone());
mgr2.resume(&task.id).unwrap();
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
let entries = mgr2.entries(&task.id, None).unwrap();
let user_entries: Vec<_> = entries.iter().filter(|e| matches!(e, AgentEntry::User { .. })).collect();
assert_eq!(user_entries.len(), 1, "original unsent prompt replayed without duplicating user entries");
assert!(matches!(user_entries[0], AgentEntry::User { text, recovery: None, .. } if text == "again"));
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "second turn")));
mgr2.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn explicit_user_cancel_settles_to_plain_ready_without_interrupted_marker() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("wait"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Running).await;
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let snap = mgr.task(&task.id).unwrap().state.lock().snapshot();
assert!(snap.interrupted.is_none());
assert!(!snap.unread);
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn reconcile_interrupted_enforces_policies_one_shot_flag_and_all_safety_guardrails() {
use ide_core::settings::{NetworkRetryWindow, ResumeInterruptedPolicy};
// 1. Ask policy leaves regular interrupted tasks waiting, except one-shot auto_resume_once.
let tmp = tempfile::tempdir().unwrap();
// Initialize git repo so worktree isolation works cleanly.
std::process::Command::new("git").args(["init", "-b", "main"]).current_dir(tmp.path()).output().unwrap();
std::fs::write(tmp.path().join("README.md"), "hi\n").unwrap();
std::process::Command::new("git").args(["add", "."]).current_dir(tmp.path()).output().unwrap();
std::process::Command::new("git")
.args(["-c", "user.name=Test", "-c", "[email protected]", "commit", "-m", "init"])
.current_dir(tmp.path())
.output()
.unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let wt_one_shot = mgr
.create(NewAgentTask {
prompt: text("wait"),
provider: "claude".into(),
isolation: Isolation::Worktree,
..Default::default()
})
.await
.unwrap();
let wt_manual = mgr
.create(NewAgentTask {
prompt: text("wait"),
provider: "claude".into(),
isolation: Isolation::Worktree,
..Default::default()
})
.await
.unwrap();
let needs_perm = mgr
.create(NewAgentTask {
prompt: text("decide"),
provider: "claude".into(),
isolation: Isolation::Worktree,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &wt_one_shot.id, AgentStatus::Running).await;
wait_for(&mgr, &wt_manual.id, AgentStatus::Running).await;
wait_for(&mgr, &needs_perm.id, AgentStatus::NeedsInput).await;
// Arm one-shot auto-resume on BOTH wt_one_shot and needs_perm; needs_perm must STILL refuse auto-resume!
mgr.set_auto_resume_once(&[wt_one_shot.id.clone(), needs_perm.id.clone()], true);
mgr.shutdown_with(AgentShutdownReason::WindowClose);
let mgr2 = manager(tmp.path(), Arc::new(FakeAgent::default()));
mgr2.set_recovery_settings_hook(Arc::new(|| (NetworkRetryWindow::Hour1, ResumeInterruptedPolicy::Ask)));
let report = mgr2.reconcile_interrupted();
assert!(report.first_reconcile);
assert_eq!(report.auto_resumed, vec![wt_one_shot.id.clone()]);
assert!(report.interrupted.contains(&wt_manual.id));
assert!(report.interrupted.contains(&needs_perm.id), "NeedsInput task must never auto-resume");
// Second call on the same AgentManager instance is idempotent.
let second = mgr2.reconcile_interrupted();
assert!(!second.first_reconcile);
assert!(second.auto_resumed.is_empty());
wait_for(&mgr2, &wt_one_shot.id, AgentStatus::Ready).await;
mgr2.shutdown();
// 2. Shared Local checkout contention: two interrupted Local tasks sharing cwd refuse auto-resume
// even under Window policy, while isolated Worktree tasks auto-resume.
let mgr3 = manager(tmp.path(), Arc::new(FakeAgent::default()));
let local_a = mgr3
.create(NewAgentTask {
prompt: text("wait"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
let local_b = mgr3
.create(NewAgentTask {
prompt: text("wait"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr3, &local_a.id, AgentStatus::Running).await;
wait_for(&mgr3, &local_b.id, AgentStatus::Running).await;
mgr3.shutdown_with(AgentShutdownReason::Restart);
let mgr4 = manager(tmp.path(), Arc::new(FakeAgent::default()));
mgr4.set_recovery_settings_hook(Arc::new(|| (NetworkRetryWindow::Hour1, ResumeInterruptedPolicy::Restart)));
let contention_report = mgr4.reconcile_interrupted();
assert!(
!contention_report.auto_resumed.contains(&local_a.id) && !contention_report.auto_resumed.contains(&local_b.id),
"two local tasks sharing a checkout must not race via auto-resume"
);
assert!(contention_report.interrupted.contains(&local_a.id));
assert!(contention_report.interrupted.contains(&local_b.id));
// 3. Permission-mode drift exclusion: changing approval config blocks silent auto-resume.
mgr4.dismiss_interrupted(&local_b.id).unwrap();
{
let handle = mgr4.task(&local_a.id).unwrap();
{
let mut s = handle.state.lock();
if let Some(mode) = s.task.config.iter_mut().find(|o| o.category.as_deref() == Some("mode")) {
mode.current = Some("bypass".into());
} else {
s.task.config.push(AgentConfigOption {
id: "mode".into(),
name: "Mode".into(),
description: None,
category: Some("mode".into()),
current: Some("bypass".into()),
default_value: None,
via: AgentConfigVia::Mode,
values: Vec::new(),
});
}
}
handle.persist();
}
mgr4.shutdown();
let mgr5 = manager(tmp.path(), Arc::new(FakeAgent::default()));
mgr5.set_recovery_settings_hook(Arc::new(|| (NetworkRetryWindow::Hour1, ResumeInterruptedPolicy::Window)));
let drift_report = mgr5.reconcile_interrupted();
assert!(!drift_report.auto_resumed.contains(&local_a.id), "drifted approval mode must not auto-resume silently");
mgr5.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn transient_network_outage_probes_with_zero_prompts_and_auto_resumes_when_online() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
agent.prompt_errors.lock().push_back((codes::INTERNAL_ERROR, "network error: connection reset by peer".into()));
let online = Arc::new(AtomicBool::new(false));
let probe_calls = Arc::new(AtomicU32::new(0));
let mgr = manager(tmp.path(), agent.clone());
mgr.set_network_probe_delays(40, 80);
mgr.set_network_probe({
let online = online.clone();
let probe_calls = probe_calls.clone();
move |_| {
probe_calls.fetch_add(1, Ordering::SeqCst);
online.load(Ordering::SeqCst)
}
});
let task = mgr
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
// Wait until the task enters `Waiting for network` (`retry.deadline_ms.is_some()`).
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
loop {
let snap = mgr.task(&task.id).unwrap().state.lock().snapshot();
if snap.retry.as_ref().is_some_and(|r| r.deadline_ms.is_some()) {
assert_eq!(snap.status, AgentStatus::Running);
assert!(mgr.has_live_work(), "remote daemon must treat network-retry wait as live work");
break;
}
assert!(tokio::time::Instant::now() < deadline, "did not enter network wait: {snap:?}");
tokio::time::sleep(Duration::from_millis(15)).await;
}
// Let several offline probes run: zero extra `session/prompt` calls may happen while offline.
while probe_calls.load(Ordering::SeqCst) < 2 {
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert_eq!(agent.prompts.lock().len(), 1, "must not spend tokens or send prompts while offline");
// Restore connectivity and poke network (simulating browser `online` event).
online.store(true, Ordering::SeqCst);
mgr.poke_network();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let snap = mgr.task(&task.id).unwrap().state.lock().snapshot();
assert!(snap.interrupted.is_none());
assert!(snap.retry.is_none());
assert_eq!(agent.prompts.lock().len(), 2);
let entries = mgr.entries(&task.id, None).unwrap();
assert!(entries.iter().any(|e| matches!(
e,
AgentEntry::User { steered: false, recovery: Some(InterruptionReason::NetworkTimeout), .. }
)));
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "resumed cleanly")));
mgr.shutdown();
}
#[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};
// 1. Turning per-session recovery window to Off (`Some(0)`) during a network wait degrades immediately to Interrupted.
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
agent.prompt_errors.lock().push_back((codes::INTERNAL_ERROR, "ENOTFOUND api.anthropic.com".into()));
let mgr = manager(tmp.path(), agent);
mgr.set_network_probe_delays(500, 1000);
mgr.set_network_probe(|_| false);
let task = mgr
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
while !mgr.task(&task.id).unwrap().state.lock().snapshot().retry.as_ref().is_some_and(|r| r.deadline_ms.is_some()) {
assert!(tokio::time::Instant::now() < deadline);
tokio::time::sleep(Duration::from_millis(15)).await;
}
mgr.set_recovery_window(&task.id, Some(0)).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let snap = mgr.task(&task.id).unwrap().state.lock().snapshot();
assert_eq!(snap.interrupted.as_ref().unwrap().reason, InterruptionReason::NetworkTimeout);
// 2. Global `NetworkRetryWindow::Off` skips waiting and immediately marks NetworkTimeout Interrupted.
let agent2 = Arc::new(FakeAgent::default());
agent2.prompt_errors.lock().push_back((codes::INTERNAL_ERROR, "503 Service Unavailable".into()));
let mgr2 = manager(tmp.path(), agent2);
mgr2.set_recovery_settings_hook(Arc::new(|| (NetworkRetryWindow::Off, ResumeInterruptedPolicy::Ask)));
let task2 = mgr2
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr2, &task2.id, AgentStatus::Ready).await;
let snap2 = mgr2.task(&task2.id).unwrap().state.lock().snapshot();
assert_eq!(snap2.interrupted.as_ref().unwrap().reason, InterruptionReason::NetworkTimeout);
// 3. Non-network 401/400 errors fail fast to Failed without entering network retry.
let agent3 = Arc::new(FakeAgent::default());
agent3.prompt_errors.lock().push_back((codes::INTERNAL_ERROR, "400 Bad Request: invalid model parameter".into()));
let mgr3 = manager(tmp.path(), agent3);
let task3 = mgr3
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr3, &task3.id, AgentStatus::Failed).await;
let snap3 = mgr3.task(&task3.id).unwrap().state.lock().snapshot();
assert!(snap3.interrupted.is_none());
mgr.shutdown();
mgr2.shutdown();
mgr3.shutdown();
}
+2
Переглянути файл
@@ -645,6 +645,7 @@ mod tests {
sent_ms: Some(sent),
done_ms: None,
steered: false,
recovery: None,
};
let mut t = Timeline::default();
t.push(user(1.0));
@@ -666,6 +667,7 @@ mod tests {
sent_ms: Some(sent),
done_ms: None,
steered,
recovery: None,
};
let mut t = Timeline::default();
t.push(user(1.0, false));
+2 -1
Переглянути файл
@@ -1,6 +1,6 @@
[package]
name = "ide-android"
description = "Android devices and logcat for the Logcat tool window, driven through the adb CLI"
description = "Android devices and iOS Simulators and their logs for the Logcat tool window, driven through adb and simctl"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -8,6 +8,7 @@ license.workspace = true
[dependencies]
ide-core.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
which = "8"
+199
Переглянути файл
@@ -0,0 +1,199 @@
//! iOS Simulators and their unified log, driven through `xcrun simctl` (macOS only).
//!
//! A simulator's log is followed with `simctl spawn <udid> log stream --style ndjson`
//! and parsed into the same [`LogcatLine`] the Android log uses, so the Logcat tool
//! window shows both with one level filter and one filter language.
use crate::model::{LogcatLevel, LogcatLine};
use crate::process;
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::process::Command;
use std::time::Duration;
const LIST: Duration = Duration::from_secs(20);
const BATCH_IDLE: Duration = Duration::from_millis(60);
const BATCH_MAX: usize = 300;
/// A booted simulator, as `simctl list devices booted -j` reports it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct BootedSimulator {
pub udid: String,
pub name: String,
/// e.g. `iOS 27.0`.
pub runtime: String,
}
/// Booted simulators; empty off macOS or without Xcode, so nothing iOS-related shows there.
pub fn booted_simulators() -> IdeResult<Vec<BootedSimulator>> {
if !cfg!(target_os = "macos") {
return Ok(Vec::new());
}
let mut cmd = Command::new("xcrun");
cmd.args(["simctl", "list", "devices", "booted", "-j"]);
match process::run(cmd, LIST, None) {
Ok(out) if out.success => Ok(parse_simulators(&out.stdout)),
// No Xcode (only the Command Line Tools, or none): there are no simulators.
_ => Ok(Vec::new()),
}
}
/// Parses `simctl list devices -j`, keeping booted devices.
pub fn parse_simulators(json: &str) -> Vec<BootedSimulator> {
#[derive(Deserialize)]
struct List {
devices: std::collections::BTreeMap<String, Vec<Device>>,
}
#[derive(Deserialize)]
struct Device {
udid: String,
name: String,
state: String,
}
let Ok(list) = serde_json::from_str::<List>(json) else {
return Vec::new();
};
let mut out = Vec::new();
for (runtime, devices) in list.devices {
// "com.apple.CoreSimulator.SimRuntime.iOS-27-0" → "iOS 27.0"
let short = runtime.rsplit('.').next().unwrap_or(&runtime);
let runtime = short.split_once('-').map_or(short.to_owned(), |(os, v)| format!("{os} {}", v.replace('-', ".")));
for d in devices.into_iter().filter(|d| d.state == "Booted") {
out.push(BootedSimulator { udid: d.udid, name: d.name, runtime: runtime.clone() });
}
}
out
}
/// Message type of the unified log → the logcat level the window filters and colors by.
fn level(message_type: &str) -> LogcatLevel {
match message_type {
"Debug" => LogcatLevel::Debug,
"Info" | "Default" => LogcatLevel::Info,
"Error" => LogcatLevel::Error,
"Fault" => LogcatLevel::Fatal,
_ => LogcatLevel::Verbose,
}
}
/// One NDJSON entry of `log stream --style ndjson`; `None` for anything that is not a
/// log message (activities, the trailing "terminated" notice). Unknown fields are ignored.
pub fn parse_ndjson(line: &str) -> Option<LogcatLine> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Entry {
event_type: String,
#[serde(default)]
message_type: String,
#[serde(default)]
timestamp: String,
#[serde(default)]
process_image_path: String,
#[serde(rename = "processID", default)]
pid: i64,
#[serde(rename = "threadID", default)]
tid: i64,
#[serde(default)]
subsystem: String,
#[serde(default)]
category: String,
#[serde(default)]
event_message: String,
}
let e: Entry = serde_json::from_str(line).ok()?;
if e.event_type != "logEvent" {
return None;
}
let process = e.process_image_path.rsplit('/').next().unwrap_or_default();
let tag = match (e.subsystem.is_empty(), e.category.is_empty()) {
(true, _) => process.to_owned(),
(false, true) => format!("{process} ({})", e.subsystem),
(false, false) => format!("{process} ({}:{})", e.subsystem, e.category),
};
// "2026-11-29 14:39:31.696480+0900" → "11-29 14:39:31.696", logcat's shape.
let time = e.timestamp.get(5..23).unwrap_or(&e.timestamp).to_owned();
Some(LogcatLine {
time,
pid: e.pid as i32,
tid: e.tid as i32,
level: level(&e.message_type),
tag,
message: e.event_message,
})
}
/// Follows simulator `udid`'s log until `cancel` fires or the simulator shuts down.
pub fn simulator_log(
udid: &str,
cancel: &CancellationToken,
on_batch: &mut dyn FnMut(Vec<LogcatLine>),
) -> IdeResult<()> {
let mut cmd = Command::new("xcrun");
cmd.args(["simctl", "spawn", udid, "log", "stream", "--style", "ndjson", "--level", "debug"]);
match process::stream_batched(cmd, cancel, BATCH_IDLE, BATCH_MAX, parse_ndjson, on_batch) {
Ok((ok, _)) if ok || cancel.is_cancelled() => Ok(()),
// `log stream` is killed when the simulator shuts down: that is an end, not a failure.
Ok((_, stderr)) if stderr.iter().any(|l| l.contains("terminated with signal")) => Ok(()),
Ok((_, stderr)) => Err(IdeError::unavailable(format!("log stream on {udid} stopped: {}", stderr.join("\n")))),
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => Ok(()),
Err(e) => Err(e),
}
}
#[cfg(test)]
mod tests {
use super::*;
const ENTRY: &str = r#"{"timezoneName":"","messageType":"Error","eventType":"logEvent","source":null,"subsystem":"com.apple.network","category":"endpoint","threadID":90176044,"processImagePath":"\/usr\/libexec\/remindd","timestamp":"2026-11-29 14:39:31.696480+0900","eventMessage":"endpoint has nothing to cleanup","processID":64339,"someFutureField":{"x":[1,2]}}"#;
#[test]
fn parses_an_entry_and_ignores_unknown_fields() {
let line = parse_ndjson(ENTRY).unwrap();
assert_eq!(line.time, "11-29 14:39:31.696");
assert_eq!(line.pid, 64339);
assert_eq!(line.tid, 90176044);
assert_eq!(line.level, LogcatLevel::Error);
assert_eq!(line.tag, "remindd (com.apple.network:endpoint)");
assert_eq!(line.message, "endpoint has nothing to cleanup");
}
#[test]
fn keeps_a_multi_line_message_whole() {
let entry = r#"{"eventType":"logEvent","messageType":"Default","processImagePath":"/a/MyApp","processID":7,"eventMessage":"first\nsecond"}"#;
let line = parse_ndjson(entry).unwrap();
assert_eq!(line.message, "first\nsecond");
assert_eq!(line.tag, "MyApp");
assert_eq!(line.level, LogcatLevel::Info);
}
#[test]
fn skips_what_is_not_a_log_message() {
assert!(parse_ndjson(r#"{"eventType":"activityCreateEvent","eventMessage":"x"}"#).is_none());
assert!(parse_ndjson("Child process terminated with signal 15: Terminated").is_none());
assert!(parse_ndjson("").is_none());
}
#[test]
fn maps_message_types_to_levels() {
assert_eq!(level("Debug"), LogcatLevel::Debug);
assert_eq!(level("Info"), LogcatLevel::Info);
assert_eq!(level("Default"), LogcatLevel::Info);
assert_eq!(level("Error"), LogcatLevel::Error);
assert_eq!(level("Fault"), LogcatLevel::Fatal);
assert_eq!(level("Signpost"), LogcatLevel::Verbose);
}
#[test]
fn reads_booted_simulators() {
let json = r#"{"devices":{"com.apple.CoreSimulator.SimRuntime.iOS-27-0":[
{"udid":"A","name":"iPhone Air","state":"Booted","isAvailable":true},
{"udid":"B","name":"iPhone 18","state":"Shutdown"}]}}"#;
assert_eq!(
parse_simulators(json),
vec![BootedSimulator { udid: "A".into(), name: "iPhone Air".into(), runtime: "iOS 27.0".into() }]
);
assert!(parse_simulators("not json").is_empty());
}
}
+2
Переглянути файл
@@ -7,9 +7,11 @@
//!
//! Every function blocks; callers run them off the UI / command threads.
mod ios;
mod model;
mod process;
pub use ios::{BootedSimulator, booted_simulators, parse_ndjson, parse_simulators, simulator_log};
pub use model::*;
use ide_core::process::{own_group, prepare};
+143 -4
Переглянути файл
@@ -29,6 +29,7 @@ pub use up_to_date::{menu_up_to_date, record_menu_build};
use crate::process::{self, Stream};
use crate::{BuildModel, maven};
use ide_core::build_jobs::append_default_jobs;
use ide_core::settings::CMakeProfile;
use ide_core::{CancellationToken, Diagnostic, IdeError, IdeResult, Pos, Range, Severity};
use parse::{ColUnit, Format, OutputParser, RawMessage};
@@ -420,7 +421,8 @@ fn cargo_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
}
/// CLion's Build Project for a CMake project: configures the build directory when it has no
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild). The directory and
/// `CMakeCache.txt` 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> {
@@ -458,6 +460,7 @@ fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> V
build.args.push("--clean-first".into());
}
build.args.extend(profile.map(|p| p.build_args.clone()).unwrap_or_default());
append_default_jobs(&mut build.args);
build.env = env;
steps.push(build);
steps
@@ -812,6 +815,74 @@ pub fn run(
})
}
/// Messages of an `xcodebuild` whose output arrives line by line (an Xcode run configuration),
/// each reported once: xcodebuild prints a message for every architecture and again on retries.
pub struct XcodebuildMessages {
parser: OutputParser,
cwd: PathBuf,
paths: PathMap,
lines: Lines,
seen: HashSet<(Option<PathBuf>, Option<Range>, String)>,
/// xcodebuild printed its result (`** BUILD SUCCEEDED **`); what follows is the app's console.
done: bool,
}
impl XcodebuildMessages {
/// Relative paths resolve against `cwd`; paths under `root`'s canonical form map back to `root`.
pub fn new(root: &Path, cwd: &Path) -> Self {
XcodebuildMessages {
parser: OutputParser::new(Format::Xcode),
cwd: cwd.to_path_buf(),
paths: PathMap::new(root),
lines: Lines::default(),
seen: HashSet::new(),
done: false,
}
}
/// Messages completed by `line` (without its line break).
pub fn feed(&mut self, line: &str) -> Vec<BuildMessage> {
if self.done {
return Vec::new();
}
let result = parse::strip_ansi(line);
let result = result.trim();
if result.len() > 6 && result.starts_with("** ") && result.ends_with(" **") {
self.done = true;
return self.finish();
}
let raws = self.parser.feed(line).messages;
self.resolve(raws)
}
/// The message still waiting for detail lines.
pub fn finish(&mut self) -> Vec<BuildMessage> {
let raws = self.parser.finish();
self.resolve(raws)
}
fn resolve(&mut self, raws: Vec<RawMessage>) -> Vec<BuildMessage> {
raws.into_iter()
.map(|raw| {
let mut m = resolve(raw, &self.cwd, &self.paths, &mut self.lines);
// xcodebuild prints the folder it was started in, which may be a symlink to the project.
if let Some(path) = m.path.clone().map(PathBuf::from)
&& !path.starts_with(&self.paths.root)
&& let Ok(real) = dunce::canonicalize(&path)
&& let Some(real) = real.to_str()
{
let mapped = self.paths.resolve(real, &self.cwd, None);
if mapped.starts_with(&self.paths.root) {
m.path = Some(mapped.into());
}
}
m
})
.filter(|m| self.seen.insert((m.path.clone().map(Into::into), m.range, m.text.clone())))
.collect()
}
}
/// Per-file editor / Problems diagnostics of the messages that have a position.
pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
diagnostics_from(messages, DIAGNOSTICS_SOURCE)
@@ -1333,6 +1404,73 @@ mod tests {
}
use super::*;
#[test]
fn xcodebuild_messages_once_per_build() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("Warn.swift");
std::fs::write(&file, "func f() -> Int {\n var count = 1\n return count\n}\n").unwrap();
let mut x = XcodebuildMessages::new(tmp.path(), tmp.path());
let warning = format!("{}:2:9: warning: variable 'count' was never mutated", file.display());
let mut out = Vec::new();
// One copy per architecture, then the linker's per-architecture lists.
for line in [
warning.as_str(),
"SwiftCompile normal arm64 Compiling\\ Warn.swift",
warning.as_str(),
"Undefined symbols for architecture x86_64:",
" \"_sym\", referenced from:",
"ld: symbol(s) not found for architecture x86_64",
"Undefined symbols for architecture arm64:",
" \"_sym\", referenced from:",
] {
out.extend(x.feed(line));
}
out.extend(x.finish());
assert_eq!(out.len(), 2, "{out:?}");
assert_eq!(out[0].path.clone().map(PathBuf::from), Some(file));
// `count`, 0-based, underlined.
assert_eq!(out[0].range, Some(Range::new(Pos::new(1, 8), Pos::new(1, 13))));
assert_eq!(
(out[1].path.is_none(), out[1].text.as_str()),
(true, "Undefined symbols\n\"_sym\", referenced from:")
);
}
#[test]
fn xcodebuild_messages_stop_at_the_build_result() {
let tmp = tempfile::tempdir().unwrap();
let mut x = XcodebuildMessages::new(tmp.path(), tmp.path());
let mut out = Vec::new();
// An Xcode run configuration's output: the build, then the app's own console.
for line in [
"/p/Demo/Demo.xcodeproj: Demo: ld: warning: Could not find or use auto-linked framework 'UIUtilities'",
"** BUILD SUCCEEDED **",
"error: request failed",
"warning: low memory",
"Demo/ContentView.swift:12: Fatal error: Unexpectedly found nil while unwrapping an Optional value",
] {
out.extend(x.feed(line));
}
out.extend(x.finish());
let texts: Vec<_> = out.iter().map(|m| m.text.as_str()).collect();
assert_eq!(texts, ["Could not find or use auto-linked framework 'UIUtilities'"]);
}
#[cfg(unix)]
#[test]
fn xcodebuild_paths_through_a_symlink_map_to_the_project() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("Demo");
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join("A.swift"), "let x = y\n").unwrap();
let link = tmp.path().join("link");
std::os::unix::fs::symlink(&root, &link).unwrap();
let mut x = XcodebuildMessages::new(&root, &root);
x.feed(&format!("{}/A.swift:1:9: error: cannot find 'y' in scope", link.display()));
let out = x.finish();
assert_eq!(out[0].path.clone().map(PathBuf::from), Some(root.join("A.swift")));
}
/// Launch outputs use the platform separator throughout, so they compare equal to
/// the same directories as JDT LS reports them.
#[test]
@@ -1508,14 +1646,15 @@ mod tests {
let cm = tmp.path().join("cm");
write(&cm, "CMakeLists.txt", "project(app)");
let args = |p: &BuildPlan| p.steps.iter().map(|s| s.args.join(" ")).collect::<Vec<_>>();
let jobs = format!("-j {}", ide_core::build_jobs::default_jobs());
let p =
plan(&cm, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(p.system, BuildSystem::CMake);
assert_eq!(
args(&p),
[
"-S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON",
"--build build --config Debug"
"-S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON".to_owned(),
format!("--build build --config Debug {jobs}"),
],
"an unconfigured project is configured first"
);
@@ -1524,7 +1663,7 @@ mod tests {
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(
args(&p),
["--build cmake-build-release --config Debug --clean-first"],
[format!("--build cmake-build-release --config Debug --clean-first {jobs}")],
"a configured directory is reused"
);
let profile = CMakeProfile {
+158
Переглянути файл
@@ -27,6 +27,10 @@ pub(crate) enum Format {
Gcc,
/// MSBuild (`dotnet build`): `C:\p\A.cs(12,5): error CS1002: msg [C:\p\App.csproj]`.
Msbuild,
/// `xcodebuild`: swiftc / clang lines like [`Format::Gcc`], their notes (`path:3:6: note:` or
/// Swift's `` `- note: `` in the code excerpt), `App.xcodeproj: App: ld: warning: msg` and
/// `Undefined symbols for architecture arm64:` with its indented details.
Xcode,
}
/// What a printed column counts.
@@ -331,6 +335,59 @@ fn gcc_line(line: &str) -> Option<RawMessage> {
(!msg.is_empty()).then(|| RawMessage::new(severity, msg, ColUnit::Byte).at(path, ln, col))
}
const UNDEFINED_SYMBOLS: &str = "Undefined symbols";
/// An `xcodebuild` message: a compiler line, a linker / build-system line without a location, or
/// the start of an undefined symbols list. Its architecture is dropped: every one prints the same.
fn xcode_line(line: &str) -> Option<RawMessage> {
if let Some(m) = gcc_line(line) {
return Some(m);
}
if line.starts_with("Undefined symbols for architecture ") {
return Some(RawMessage::new(Severity::Error, UNDEFINED_SYMBOLS, ColUnit::Byte));
}
// `/p/App.xcodeproj: App: ld: warning: msg`, `error: msg`, `xcodebuild: error: msg`.
let rest = [".xcodeproj: ", ".xcworkspace: "]
.into_iter()
.find_map(|c| line.find(c).map(|i| &line[i + c.len()..]))
.or_else(|| (!line.starts_with(char::is_whitespace)).then_some(line))?;
let (severity, msg) =
[("error: ", Severity::Error), ("warning: ", Severity::Warning)].into_iter().find_map(|(word, severity)| {
let at = rest.match_indices(word).map(|(i, _)| i).find(|&i| i == 0 || rest[..i].ends_with(": "))?;
// Only `tool: ` / `target: ` words may come before the severity, not a sentence.
rest[..at].split(": ").all(|w| !w.contains(' ')).then(|| (severity, rest[at + word.len()..].trim()))
})?;
(!msg.is_empty()).then(|| RawMessage::new(severity, msg, ColUnit::Byte))
}
/// Whether `line` belongs to the pending `xcodebuild` message (and is folded into it).
fn xcode_detail(msg: &mut RawMessage, line: &str) -> bool {
let t = line.trim_start();
// A `note:` with a location, as clang and `-diagnostic-style llvm` print it.
if let Some((_, _, _, rest)) = path_line_col(line)
&& let Some(note) = rest.strip_prefix(':').and_then(|r| r.trim_start().strip_prefix("note:"))
{
msg.text.push_str("\nnote: ");
msg.text.push_str(note.trim());
return true;
}
// The code excerpt: ` 9 | switch s {`, ` | `- note: add missing case`.
let excerpt = t.trim_start_matches(|c: char| c.is_ascii_digit()).trim_start().starts_with('|');
if excerpt {
if let Some(i) = t.find("- note: ") {
msg.text.push_str("\nnote: ");
msg.text.push_str(t[i + "- note: ".len()..].trim());
}
return true;
}
if msg.text.starts_with(UNDEFINED_SYMBOLS) && t.len() < line.len() && !t.is_empty() {
msg.text.push('\n');
msg.text.push_str(t);
return true;
}
false
}
/// rustc's JSON diagnostic (`reason: compiler-message`) → message and its rendered text.
fn cargo_json(v: &Value) -> Option<(Option<RawMessage>, String)> {
if v.get("reason")?.as_str()? != "compiler-message" {
@@ -412,6 +469,9 @@ impl OutputParser {
.map_or(line, |r| r.strip_prefix(' ').unwrap_or(r)),
_ => line,
};
if format == Format::Xcode {
return xcode_detail(&mut p.msg, line);
}
if matches!(format, Format::Maven | Format::Gradle | Format::Tsc)
&& body.starts_with(" ")
&& !body.trim().is_empty()
@@ -447,6 +507,7 @@ impl OutputParser {
Format::Go => go_line(&line),
Format::Gcc => gcc_line(&line),
Format::Msbuild => msbuild_line(&line),
Format::Xcode => xcode_line(&line),
Format::Cargo => None,
};
if let Some(msg) = parsed {
@@ -678,6 +739,103 @@ mod tests {
assert_eq!(out[2].text, "'missing.h' file not found");
}
// Real `xcodebuild build` output (Xcode 27.1, iOS Simulator, two architectures), paths shortened.
#[test]
fn xcodebuild_swift_error_warning_and_note() {
let out = parse(
Format::Xcode,
"SwiftCompile normal x86_64 Compiling\\ Warn.swift /p/Demo/Warn.swift (in target 'Demo' from project 'Demo')\n\
/p/Demo/Warn.swift:2:9: warning: variable 'count' was never mutated; consider changing to 'let' constant [#VariableNeverMutated]\n\
\x201 | func warnMe() -> Int {\n\
\x202 | var count = 1\n\
\x20 | `- warning: variable 'count' was never mutated; consider changing to 'let' constant [#VariableNeverMutated]\n\
\x203 | return count\n\
\x204 | }\n\
\n\
/p/Demo/Warn.swift:9:5: error: switch must be exhaustive\n\
\x207 | \n\
\x208 | func name(_ s: Shade) -> String {\n\
\x209 | switch s {\n\
\x20 | |- error: switch must be exhaustive\n\
\x20 | `- note: add missing case: '.dark'\n\
10 | case .light: return \"light\"\n\
11 | }\n\
\n\
[#VariableNeverMutated]: <https://docs.swift.org/compiler/documentation/diagnostics/variable-never-mutated>\n\
Failed frontend command:\n\
note: Removed stale file '/p/dd/Demo.swiftmodule'\n",
);
assert_eq!(out.len(), 2, "{out:?}");
assert_eq!(out[0].severity, Severity::Warning);
assert_eq!((out[0].path.as_deref(), out[0].line, out[0].col), (Some("/p/Demo/Warn.swift"), Some(2), Some(9)));
assert!(out[0].text.starts_with("variable 'count' was never mutated"), "{}", out[0].text);
assert_eq!(out[1].severity, Severity::Error);
assert_eq!(out[1].text, "switch must be exhaustive\nnote: add missing case: '.dark'");
assert_eq!((out[1].line, out[1].col), (Some(9), Some(5)));
}
#[test]
fn xcodebuild_clang_errors_with_note() {
let out = parse(
Format::Xcode,
"/p/Demo/Legacy.m:2:29: error: use of undeclared identifier 'undeclared_thing'\n\
\x20 2 | void legacy(void) { int x = undeclared_thing; }\n\
\x20 | ^~~~~~~~~~~~~~~~\n\
/p/Demo/Legacy.m:4:6: error: redefinition of 'twice'\n\
\x20 4 | void twice(void) {}\n\
\x20 | ^\n\
/p/Demo/Legacy.m:3:6: note: previous definition is here\n\
\x20 3 | void twice(void) {}\n\
\x20 | ^\n\
2 errors generated.\n",
);
assert_eq!(out.len(), 2, "{out:?}");
assert_eq!(out[0].text, "use of undeclared identifier 'undeclared_thing'");
assert_eq!((out[0].line, out[0].col), (Some(2), Some(29)));
assert_eq!(out[1].text, "redefinition of 'twice'\nnote: previous definition is here");
assert_eq!((out[1].line, out[1].col), (Some(4), Some(6)));
}
#[test]
fn xcodebuild_linker_errors_without_location() {
let out = parse(
Format::Xcode,
"Ld /p/dd/Demo.debug.dylib normal arm64 (in target 'Demo' from project 'Demo')\n\
\x20 cd /p/Demo\n\
\x20 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -Xlinker -reproducible -target arm64-apple-ios16.0-simulator -ferror-limit 19\n\
/p/Demo/Demo.xcodeproj: Demo: ld: warning: Could not find or use auto-linked framework 'UIUtilities': framework 'UIUtilities' not found\n\
Undefined symbols for architecture arm64:\n\
\x20 \"_missing_symbol_xyz\", referenced from:\n\
\x20 Demo.callMissing() -> () in Missing.o\n\
ld: symbol(s) not found for architecture arm64\n\
/p/Demo/Demo.xcodeproj: Demo: clang: error: linker command failed with exit code 1 (use -v to see invocation)\n\
\n\
** BUILD FAILED **\n\
\n\
The following build commands failed:\n\
\tLd /p/dd/Demo.debug.dylib normal arm64 (in target 'Demo' from project 'Demo')\n\
xcodebuild: error: Unable to find a destination matching the provided destination specifier\n",
);
let found: Vec<_> = out.iter().map(|m| (m.severity, m.text.as_str(), m.path.is_none())).collect();
assert_eq!(
found,
[
(
Severity::Warning,
"Could not find or use auto-linked framework 'UIUtilities': framework 'UIUtilities' not found",
true
),
(
Severity::Error,
"Undefined symbols\n\"_missing_symbol_xyz\", referenced from:\nDemo.callMissing() -> () in Missing.o",
true
),
(Severity::Error, "linker command failed with exit code 1 (use -v to see invocation)", true),
(Severity::Error, "Unable to find a destination matching the provided destination specifier", true),
]
);
}
#[test]
fn go_errors() {
let out = parse(
+72 -4
Переглянути файл
@@ -5,8 +5,10 @@
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::BTreeMap;
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{Duration, Instant};
pub const SETTINGS_FILES: &[&str] = &["settings.gradle.kts", "settings.gradle"];
pub const BUILD_FILES: &[&str] = &["build.gradle.kts", "build.gradle"];
@@ -227,9 +229,41 @@ pub fn build_dir(root: &Path) -> Option<PathBuf> {
build_dirs(root).into_iter().next()
}
/// How long [`cached_build_dirs`] reuses a walk. Project roots, content roots and the index
/// ask for the builds many times while a project opens; on a network share each walk is
/// thousands of round trips. A build file changing in a project calls [`forget_build_dirs`].
const BUILD_DIRS_TTL: Duration = Duration::from_secs(30);
type BuildDirsCache = HashMap<PathBuf, (Instant, Vec<PathBuf>)>;
static BUILD_DIRS: Mutex<Option<BuildDirsCache>> = Mutex::new(None);
/// Walks for builds now; the result also refreshes [`cached_build_dirs`].
fn build_dirs(root: &Path) -> Vec<PathBuf> {
let markers: Vec<_> = SETTINGS_FILES.iter().chain(BUILD_FILES).copied().collect();
ide_core::project_roots::discover(root, &markers)
let dirs = ide_core::project_roots::discover(root, &markers);
let now = Instant::now();
let mut guard = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner());
let map = guard.get_or_insert_with(HashMap::new);
map.retain(|_, (at, _)| now.duration_since(*at) < BUILD_DIRS_TTL);
map.insert(root.to_path_buf(), (now, dirs.clone()));
dirs
}
fn cached_build_dirs(root: &Path) -> Vec<PathBuf> {
let cached = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|m| m.get(root)).cloned();
match cached {
Some((at, dirs)) if at.elapsed() < BUILD_DIRS_TTL => dirs,
_ => build_dirs(root),
}
}
/// Forgets the discovered Gradle builds of `root`, and of folders above or below it
/// (after a build or settings script appeared, changed or was removed there).
pub fn forget_build_dirs(root: &Path) {
if let Some(map) = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
map.retain(|dir, _| !dir.starts_with(root) && !root.starts_with(dir));
}
}
fn wrapper(dir: &Path) -> String {
@@ -506,10 +540,23 @@ pub fn linked_project_key(root: &Path, dir: &str) -> String {
}
}
/// Linked build identities without reading their scripts (also used by index hot paths).
/// Linked build identities without reading their scripts, as of now (a sync, a build).
pub(crate) fn linked_dirs(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
linked_dirs_from(root, settings, build_dirs)
}
/// [`linked_dirs`] for hot paths (project and index roots): discovered builds are reused for a while.
pub(crate) fn linked_dirs_cached(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
linked_dirs_from(root, settings, cached_build_dirs)
}
fn linked_dirs_from(
root: &Path,
settings: &ide_core::settings::GradleSettings,
discover: fn(&Path) -> Vec<PathBuf>,
) -> Vec<String> {
match &settings.linked_projects {
None => build_dirs(root).iter().map(|dir| rel(root, dir)).collect(),
None => discover(root).iter().map(|dir| rel(root, dir)).collect(),
Some(dirs) => {
let mut out = Vec::new();
for dir in dirs {
@@ -1047,6 +1094,27 @@ pub(crate) fn has_war_plugin(script: &str) -> bool {
#[cfg(test)]
mod tests {
#[test]
fn discovered_builds_are_reused_until_forgotten() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
std::fs::create_dir_all(root.join("a")).unwrap();
std::fs::write(root.join("a/settings.gradle"), "").unwrap();
assert_eq!(super::cached_build_dirs(root), vec![root.join("a")]);
std::fs::create_dir_all(root.join("b")).unwrap();
std::fs::write(root.join("b/build.gradle"), "").unwrap();
// A walk per call is thousands of round trips on a network share.
assert_eq!(super::cached_build_dirs(root), vec![root.join("a")]);
super::forget_build_dirs(&root.join("b"));
assert_eq!(super::cached_build_dirs(root), vec![root.join("a"), root.join("b")]);
// A sync sees a new build at once, and so does every later lookup.
std::fs::create_dir_all(root.join("c")).unwrap();
std::fs::write(root.join("c/build.gradle"), "").unwrap();
let all = vec![root.join("a"), root.join("b"), root.join("c")];
assert_eq!(super::build_dirs(root), all);
assert_eq!(super::cached_build_dirs(root), all);
}
#[test]
fn default_linkage_discovers_all_shallow_builds() {
let temp = tempfile::tempdir().unwrap();
+2 -2
Переглянути файл
@@ -129,7 +129,7 @@ pub fn gradle_external_roots(
cache_dir: &Path,
settings: &ide_core::settings::GradleSettings,
) -> Vec<PathBuf> {
let builds = gradle::linked_dirs(root, settings);
let builds = gradle::linked_dirs_cached(root, settings);
let dirs: Vec<String> = builds
.iter()
.flat_map(|dir| {
@@ -171,7 +171,7 @@ pub fn gradle_source_roots(
cache_dir: &Path,
settings: &ide_core::settings::GradleSettings,
) -> Vec<(PathBuf, gradle::ReportedRoot, PathBuf)> {
let reported = gradle::linked_dirs(root, settings)
let reported = gradle::linked_dirs_cached(root, settings)
.iter()
.flat_map(|dir| sync::reported_gradle_projects(&gradle::cache_dir(cache_dir, dir)).as_ref().clone())
.collect::<Vec<_>>();
+54
Переглянути файл
@@ -4461,4 +4461,58 @@ mod linkage_tests {
assert_eq!(poms, expected.map(|e| e.iter().map(|s| s.to_string()).collect::<Vec<_>>()), "{unlinked:?}");
}
}
#[test]
fn child_module_inherits_parent_declared_plugin_prefix_and_coordinates() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("child")).unwrap();
std::fs::write(
root.join("pom.xml"),
r#"<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules><module>child</module></modules>
<build>
<plugins>
<plugin>
<groupId>io.spring.javaformat</groupId>
<artifactId>spring-javaformat-maven-plugin</artifactId>
<version>0.0.38</version>
</plugin>
</plugins>
</build>
</project>"#,
)
.unwrap();
std::fs::write(
root.join("child/pom.xml"),
r#"<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example</groupId>
<artifactId>parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>child</artifactId>
</project>"#,
)
.unwrap();
let model = load_with_repo(root, None);
for pom in ["pom.xml", "child/pom.xml"] {
let proj = model.projects.iter().find(|p| p.pom == pom).expect(pom);
let plugin = proj
.plugins
.iter()
.find(|p| p.prefix == "spring-javaformat")
.unwrap_or_else(|| panic!("spring-javaformat plugin missing on {pom}: {:?}", proj.plugins));
assert_eq!(plugin.group_id, "io.spring.javaformat");
assert_eq!(plugin.artifact_id, "spring-javaformat-maven-plugin");
assert_eq!(plugin.version.as_deref(), Some("0.0.38"));
}
}
}
+1 -1
Переглянути файл
@@ -27,4 +27,4 @@ libc = "0.2"
[target.'cfg(windows)'.dependencies]
dirs.workspace = true
tracing.workspace = true
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }
+74
Переглянути файл
@@ -0,0 +1,74 @@
//! Parallelism for build tools whose default is one compiler process at a time.
//!
//! `cmake --build` with a Makefile generator (the default) compiles one file at a
//! time unless it is given `-j N`; the IDE asks for one job per logical CPU. A count
//! the user wrote into the build arguments is left alone.
/// Jobs a native build tool gets when the user did not choose a count.
pub fn default_jobs() -> usize {
std::thread::available_parallelism().map_or(1, |jobs| jobs.get())
}
/// Appends `-j <jobs>` unless `args` already carries the user's own count. The count
/// goes before a `--` separator, so cmake's own options stay cmake's and the native
/// build tool's options stay last.
pub fn append_default_jobs(args: &mut Vec<String>) {
if args.iter().any(|arg| is_jobs_flag(arg)) {
return;
}
let jobs = default_jobs().to_string();
let at = args.iter().position(|arg| arg == "--").unwrap_or(args.len());
args.splice(at..at, ["-j".to_owned(), jobs]);
}
/// `-j`, `-j8`, `--parallel`, `--parallel=8`, `--jobs`, `--jobs=8`.
fn is_jobs_flag(arg: &str) -> bool {
let count = |rest: &str| rest.chars().all(|c| c.is_ascii_digit());
arg.strip_prefix("-j").is_some_and(count)
|| arg.strip_prefix("--parallel=").is_some_and(count)
|| arg.strip_prefix("--jobs=").is_some_and(count)
|| arg == "--parallel"
|| arg == "--jobs"
}
#[cfg(test)]
mod tests {
use super::*;
fn args_of(values: &[&str]) -> Vec<String> {
values.iter().map(|value| (*value).to_owned()).collect()
}
#[test]
fn the_default_is_one_job_per_logical_cpu() {
let expected = std::thread::available_parallelism().map_or(1, |jobs| jobs.get());
assert_eq!(default_jobs(), expected);
}
#[test]
fn a_build_without_a_count_gets_one() {
let mut argv = args_of(&["--build", "build", "--config", "Debug"]);
append_default_jobs(&mut argv);
assert_eq!(argv, args_of(&["--build", "build", "--config", "Debug", "-j", &default_jobs().to_string()]));
}
#[test]
fn a_count_the_user_chose_is_left_alone() {
let own: [&[&str]; 6] =
[&["-j", "2"], &["-j8"], &["-j", "2"], &["--parallel", "2"], &["--parallel=2"], &["--jobs=2"]];
for flags in own {
let mut argv = args_of(&["--build", "build"]);
argv.extend(flags.iter().map(|value| (*value).to_owned()));
let expected = argv.clone();
append_default_jobs(&mut argv);
assert_eq!(argv, expected, "the build arguments set the count");
}
}
#[test]
fn the_count_stays_before_native_build_tool_options() {
let mut argv = args_of(&["--build", "build", "--", "VERBOSE=1"]);
append_default_jobs(&mut argv);
assert_eq!(argv, args_of(&["--build", "build", "-j", &default_jobs().to_string(), "--", "VERBOSE=1"]));
}
}
+9
Переглянути файл
@@ -302,6 +302,12 @@ pub struct SmartKeysSettings {
pub simultaneous_tag_editing: bool,
/// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
pub reformat_on_paste: String,
/// Advanced Settings: Copy/Cut without a selection copies the whole caret lines.
pub copy_line_when_no_selection: bool,
/// Advanced Settings: Copy selects the lines copied without a selection.
pub select_copied_line: bool,
/// Advanced Settings: linewise paste `above` the caret | `caret` | `trim` at mid-line.
pub line_paste_mode: String,
pub escape_on_paste: bool,
pub smart_indent: bool,
/// Enter › Insert documentation comment stub: Enter after `/**` closes the comment.
@@ -322,6 +328,9 @@ impl Default for SmartKeysSettings {
semicolon_at_statement_end: true,
simultaneous_tag_editing: true,
reformat_on_paste: "indentEachLine".into(),
copy_line_when_no_selection: true,
select_copied_line: true,
line_paste_mode: "above".into(),
escape_on_paste: true,
smart_indent: true,
insert_doc_stub: true,
+53 -1
Переглянути файл
@@ -15,7 +15,9 @@ use std::sync::Arc;
/// 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
/// `RunConfig`, its before launch tasks already done) in the Run tool window as the user's
/// Run would, answered the same way.
/// Run would, answered the same way. `DebugConfiguration` does the same in Debug mode, so
/// the window's own Debug action builds the launch. `Breakpoints` replaces the window's
/// breakpoints, which the editor owns, persists and mirrors to the backend.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum McpUiRequest {
@@ -41,6 +43,36 @@ pub enum McpUiRequest {
#[specta(type = specta_typescript::Unknown)]
config: serde_json::Value,
},
/// Start a run configuration in Debug mode as the IDE's Debug action would.
DebugConfiguration {
#[specta(type = specta_typescript::Unknown)]
config: serde_json::Value,
},
/// Sets one line breakpoint in the window's own list, by absolute editor path. The window
/// applies the edit to its current list, so a user's pending edit is not overwritten.
SetBreakpoint {
path: String,
breakpoint: McpBreakpoint,
},
/// Removes breakpoints from the window's own list. With no path, removes every line
/// breakpoint; with a path but no line, removes all of that file's breakpoints.
RemoveBreakpoints {
path: Option<String>,
line: Option<u32>,
},
/// Flushes the editor's pending breakpoint syncs before an agent reads the backend list.
FlushBreakpoints,
}
/// A line breakpoint in an MCP request, with a 1-based line like every other MCP tool.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct McpBreakpoint {
pub line: u32,
pub enabled: bool,
pub condition: Option<String>,
pub hit_condition: Option<String>,
pub log_message: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -123,6 +155,8 @@ pub enum IdeEvent {
DocDiskConflict {
doc: DocId,
path: String,
/// The file no longer exists: saving recreates it, and there is nothing to load.
deleted: bool,
},
/// A complete workspace edit can be undone as one operation.
WorkspaceEditApplied {
@@ -142,6 +176,15 @@ pub enum IdeEvent {
/// See `DocumentInfo::ui_mode`.
ui_mode: Option<String>,
},
/// A reload from disk changed an open document's encoding, BOM or line ending (the file
/// was rewritten by another program), which the editor only learns when it opens.
DocEncoding {
doc: DocId,
encoding: String,
has_bom: bool,
/// A `LineEnding` in its serialized form: `lf`, `crLf` or `cr`.
line_ending: String,
},
/// Full replacement of diagnostics for one file from one producer.
Diagnostics {
path: crate::IpcPath,
@@ -204,6 +247,15 @@ pub enum IdeEvent {
message: String,
actions: Vec<String>,
},
/// A language server asked to show a document (`window/showDocument`), e.g. the
/// expansion file of sourcekit-lsp's Expand Macro. `path` is set for a file to open in
/// an editor, at `selection` when given; without it `uri` is a web link for the browser.
LspShowDocument {
uri: String,
path: Option<crate::IpcPath>,
selection: Option<crate::Range>,
take_focus: bool,
},
/// The request was answered or timed out; every window drops its dialog.
LspMessageRequestDone {
id: u32,
+2
Переглянути файл
@@ -4,6 +4,7 @@
//! feature crates depend on `ide-core` and never on each other's internals.
//! All IPC-facing types derive `specta::Type`, which generates `src/bindings.ts`.
pub mod build_jobs;
pub mod cli_process;
pub mod editor_settings;
pub mod error;
@@ -18,6 +19,7 @@ pub mod ipc_path;
pub mod java_runtime;
pub mod jsonc;
pub mod memory;
pub mod network_path;
pub mod output_encoding;
pub mod output_rate;
pub mod platform;
+53
Переглянути файл
@@ -0,0 +1,53 @@
//! Whether a path is on a network file system, where every stat is a round trip to a server.
use std::path::{Component, Path, Prefix};
/// A UNC path (`\\server\share`, `\\wsl.localhost\…`) or a drive letter mapped to a network
/// share (`Z:\`). Always `false` off Windows: there a mount point is not visible in the path.
pub fn is_network_path(path: &Path) -> bool {
match path.components().next() {
Some(Component::Prefix(prefix)) => match prefix.kind() {
Prefix::UNC(..) | Prefix::VerbatimUNC(..) => true,
Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => is_remote_drive(letter),
_ => false,
},
_ => false,
}
}
#[cfg(windows)]
fn is_remote_drive(letter: u8) -> bool {
use windows_sys::Win32::Storage::FileSystem::GetDriveTypeW;
/// `DRIVE_REMOTE` (WindowsProgramming).
const DRIVE_REMOTE: u32 = 4;
let root = [u16::from(letter), u16::from(b':'), u16::from(b'\\'), 0];
// SAFETY: `root` is a NUL-terminated wide string that outlives the call.
unsafe { GetDriveTypeW(root.as_ptr()) == DRIVE_REMOTE }
}
#[cfg(not(windows))]
fn is_remote_drive(_letter: u8) -> bool {
false
}
#[cfg(test)]
mod tests {
use super::is_network_path;
use std::path::Path;
#[test]
fn unc_paths_are_on_the_network() {
if cfg!(windows) {
assert!(is_network_path(Path::new(r"\\server\share\repo")));
assert!(is_network_path(Path::new(r"\\?\UNC\server\share\repo")));
assert!(is_network_path(Path::new(r"\\wsl.localhost\Ubuntu\home")));
}
assert!(!is_network_path(Path::new("relative/path")));
}
#[test]
fn a_local_directory_is_not() {
let dir = std::env::temp_dir();
assert!(!is_network_path(&dir), "{}", dir.display());
}
}
+214
Переглянути файл
@@ -52,6 +52,8 @@ pub struct Settings {
/// Per language server, by name (`rust-analyzer`): launch and protocol
/// options on top of the language definition, or a server defined here.
pub language_servers: BTreeMap<String, LanguageServerSettings>,
/// Languages & Frameworks › JSON Schema Mappings: schemas for JSON and YAML files.
pub json_schemas: Vec<JsonSchemaMapping>,
/// Tools › Download sources: a mirror prefix for the release archives the installer fetches.
pub tool_downloads: ToolDownloadSettings,
/// Editor › Inspections profiles.
@@ -78,6 +80,8 @@ pub struct Settings {
pub file_colors: FileColorSettings,
/// Database › Query Execution, Languages & Frameworks › SQL Resolution Scopes.
pub database: DatabaseSettings,
/// Settings › Settings Sync (global only, never synced itself).
pub settings_sync: SettingsSyncSettings,
/// Plugin settings (`[contributes.settings]`): plugin id → its values by key.
#[specta(type = BTreeMap<String, BTreeMap<String, specta_typescript::Unknown>>)]
pub plugins: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
@@ -134,6 +138,19 @@ pub struct AgentSettings {
#[serde(deserialize_with = "or_default")]
#[specta(type = NewTaskApprovals)]
pub new_task_approvals: NewTaskApprovals,
/// How long an in-flight turn hit by a transient network outage waits and probes for
/// connectivity before degrading to a manual Resume prompt.
#[serde(deserialize_with = "or_default")]
#[specta(type = NetworkRetryWindow)]
pub network_retry_window: NetworkRetryWindow,
/// What opening a project does with tasks interrupted when OpenIDEA closed or restarted.
/// User settings only.
#[serde(deserialize_with = "or_default")]
#[specta(type = ResumeInterruptedPolicy)]
pub resume_interrupted: ResumeInterruptedPolicy,
/// Warn before closing a local window whose project still has running agent tasks.
/// User settings only.
pub confirm_terminate_on_close: bool,
/// Settings new tasks of an agent start with: agent id → option id → value.
#[serde(deserialize_with = "agent_defaults")]
#[specta(type = BTreeMap<String, BTreeMap<String, String>>)]
@@ -148,6 +165,11 @@ pub struct AgentSettings {
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, AgentSkillPolicy>)]
pub skills: BTreeMap<String, AgentSkillPolicy>,
/// Agent memory policies (`[agents.memory]`): cross-session auto-memory mode, built-in
/// MCP memory bridge, and per-entry modes; tracked files on disk are never modified.
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentMemorySettings)]
pub memory: AgentMemorySettings,
}
impl Default for AgentSettings {
@@ -173,9 +195,13 @@ impl Default for AgentSettings {
send_with: SendKey::Enter,
while_running: WhileRunning::Queue,
new_task_approvals: NewTaskApprovals::Bypass,
network_retry_window: NetworkRetryWindow::Hour1,
resume_interrupted: ResumeInterruptedPolicy::Ask,
confirm_terminate_on_close: true,
defaults: BTreeMap::new(),
mcp_servers: BTreeMap::new(),
skills: BTreeMap::new(),
memory: AgentMemorySettings::default(),
}
}
}
@@ -259,6 +285,79 @@ impl Default for AgentSkillPolicy {
}
}
/// How an agent instruction, rule, or memory entry may load (`[agents.memory.entries.<id>] mode = …`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentMemoryMode {
/// Load according to its native rules (always for instructions, matching files for path-scoped rules).
#[default]
Auto,
/// Force-load into every session regardless of path scoping.
Always,
/// Exclude from sessions where the harness supports it.
Off,
}
/// How an agent's automatic cross-session memory runs (`[agents.memory] autoMemory = …`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AutoMemoryMode {
/// Leave the agent's own configuration untouched.
#[default]
Inherit,
/// Read past memories and record new ones.
ReadWrite,
/// Read past memories without recording new ones.
ReadOnly,
/// Neither read nor record cross-session auto-memories.
Off,
}
/// One memory or instruction entry's policy in Settings › Agents › Memory.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentMemoryEntryPolicy {
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentMemoryMode)]
pub mode: AgentMemoryMode,
/// Agent provider ids this entry applies to; empty means all agents.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub agents: Vec<String>,
}
impl Default for AgentMemoryEntryPolicy {
fn default() -> Self {
Self { mode: AgentMemoryMode::Auto, agents: Vec::new() }
}
}
/// Per-provider auto-memory policy (`[agents.memory.providers.<id>]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentProviderMemoryPolicy {
#[serde(deserialize_with = "or_default")]
#[specta(type = AutoMemoryMode)]
pub auto_memory: AutoMemoryMode,
}
/// Agent memory settings (`[agents.memory]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentMemorySettings {
/// Default cross-session auto-memory policy across agents.
#[serde(deserialize_with = "or_default")]
#[specta(type = AutoMemoryMode)]
pub auto_memory: AutoMemoryMode,
/// Optional per-provider auto-memory overrides (`[agents.memory.providers.<provider>]`).
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
#[specta(type = BTreeMap<String, AgentProviderMemoryPolicy>)]
pub providers: BTreeMap<String, AgentProviderMemoryPolicy>,
/// Per-entry modes (`[agents.memory.entries.<id>]`).
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
#[specta(type = BTreeMap<String, AgentMemoryEntryPolicy>)]
pub entries: BTreeMap<String, AgentMemoryEntryPolicy>,
}
/// 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>
@@ -360,6 +459,49 @@ pub enum NewTaskApprovals {
Ask,
}
/// Default auto-retry window for transient network outages during an active agent turn.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
pub enum NetworkRetryWindow {
#[serde(rename = "off")]
Off,
#[serde(rename = "15m")]
Minutes15,
#[default]
#[serde(rename = "1h")]
Hour1,
#[serde(rename = "4h")]
Hours4,
#[serde(rename = "24h")]
Hours24,
}
impl NetworkRetryWindow {
pub fn minutes(self) -> u32 {
match self {
Self::Off => 0,
Self::Minutes15 => 15,
Self::Hour1 => 60,
Self::Hours4 => 240,
Self::Hours24 => 1440,
}
}
}
/// How interrupted agent tasks are handled when a project reopens.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum ResumeInterruptedPolicy {
/// Show Interrupted markers, banner and balloon; wait for the user to click Resume.
#[default]
Ask,
/// Auto-resume tasks interrupted by an IDE restart or backend upgrade within 15 minutes.
Restart,
/// Auto-resume tasks interrupted by close, quit or restart within the session recovery window.
Window,
/// Settle quietly to Ready with no Interrupted markers or balloons.
Off,
}
/// Which folders without an open window the MCP server still serves tools for.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -462,6 +604,47 @@ pub struct ToolDownloadSettings {
pub configured_registries_only: bool,
}
/// Settings › Settings Sync: the Git repository the IDE settings sync through, and what syncs.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct SettingsSyncSettings {
/// Clone URL (a secret GitHub Gist's works too, though anyone with its link can read it);
/// empty = sync off.
pub repository: String,
/// Sync on startup and after the settings change, besides Sync Now.
pub auto: bool,
pub appearance: bool,
/// Editor settings, color schemes, code style, inspections and spelling.
pub editor: bool,
pub keymaps: bool,
/// Every other setting that is not machine-specific.
pub other: bool,
/// Live, file and postfix templates.
pub templates: bool,
pub macros: bool,
/// Tool window layouts and view options.
pub ui: bool,
/// The list of installed plugins: missing ones are offered, never installed or removed.
pub plugins: bool,
}
impl Default for SettingsSyncSettings {
fn default() -> Self {
Self {
repository: String::new(),
auto: true,
appearance: true,
editor: true,
keymaps: true,
other: true,
templates: true,
macros: true,
ui: true,
plugins: true,
}
}
}
/// Absent profiles retain automatic discovery for existing projects.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -613,8 +796,10 @@ impl Default for Settings {
mcp_server: McpServerSettings::default(),
agent_security: AgentSecuritySettings::default(),
scopes: Vec::new(),
json_schemas: Vec::new(),
file_colors: FileColorSettings::default(),
database: DatabaseSettings::default(),
settings_sync: SettingsSyncSettings::default(),
plugins: BTreeMap::new(),
}
}
@@ -634,6 +819,17 @@ pub struct NamedScope {
pub pattern: String,
}
/// A schema for the JSON and YAML files matching `files`; wins over a built-in SchemaStore mapping.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct JsonSchemaMapping {
pub name: String,
/// A URL, or a file path relative to the project.
pub schema: String,
/// Project-relative paths or glob patterns (`config/*.json`, `**/*.app.yaml`).
pub files: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct FileColorSettings {
@@ -882,6 +1078,8 @@ pub struct AppearanceSettings {
pub widescreen_tool_windows: bool,
/// Each tool window keeps its own size; off, the windows of a side share one.
pub remember_tool_window_sizes: bool,
/// Tool window shortcuts hide an open unfocused window right away instead of focusing it first.
pub toggle_tool_windows_on_shortcut: bool,
/// View › Appearance › Toolbar; hidden leaves IDEA's compact window header.
pub show_main_toolbar: bool,
pub show_status_bar: bool,
@@ -1016,6 +1214,7 @@ impl Default for AppearanceSettings {
show_tool_window_badges: true,
widescreen_tool_windows: false,
remember_tool_window_sizes: false,
toggle_tool_windows_on_shortcut: false,
show_main_toolbar: true,
show_status_bar: true,
navigation_bar: NavigationBarPosition::StatusBar,
@@ -2176,6 +2375,21 @@ mod tests {
}
}
#[test]
fn toggle_tool_windows_on_shortcut_defaults_off_and_round_trips() {
let old: Settings = serde_json::from_str(r#"{"appearance":{"showToolWindowNames":true}}"#).unwrap();
assert!(!old.appearance.toggle_tool_windows_on_shortcut);
assert!(!Settings::default().appearance.toggle_tool_windows_on_shortcut);
for enabled in [true, false] {
let mut settings = Settings::default();
settings.appearance.toggle_tool_windows_on_shortcut = enabled;
let json = serde_json::to_value(&settings).unwrap();
assert_eq!(json["appearance"]["toggleToolWindowsOnShortcut"], enabled);
let restored: Settings = serde_json::from_value(json).unwrap();
assert_eq!(restored.appearance.toggle_tool_windows_on_shortcut, enabled);
}
}
#[test]
fn double_click_opens_diff_is_unset_by_default_and_round_trips() {
let old: Settings = serde_json::from_str(r#"{"vcs":{"commit":{"nonModal":true}}}"#).unwrap();
+18
Переглянути файл
@@ -143,6 +143,9 @@ impl Default for GitAnnotateSettings {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GitSettings {
/// Git integration on: off, the IDE finds no repositories and runs no git at all
/// (no status, log, blame, fetch, clone or agent worktrees), and hides its Git UI.
pub enabled: bool,
pub annotate: GitAnnotateSettings,
/// Show blame after the current editor line.
pub inline_blame: bool,
@@ -201,6 +204,7 @@ pub struct GitSettings {
impl Default for GitSettings {
fn default() -> Self {
Self {
enabled: true,
annotate: GitAnnotateSettings::default(),
inline_blame: false,
inline_blame_clickable: true,
@@ -613,10 +617,14 @@ pub struct TerminalSettings {
pub mouse_reporting: bool,
pub copy_on_selection: bool,
pub paste_on_middle_click: bool,
/// Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it).
pub right_click_paste: bool,
pub override_ide_shortcuts: bool,
pub shell_integration: bool,
pub highlight_hyperlinks: bool,
pub highlight_selection: bool,
/// Highlights typed commands the IDE recognises; Run Highlighted Command runs them with it.
pub run_commands_using_ide: bool,
pub option_as_meta: bool,
/// Escape moves focus to the editor instead of reaching the shell.
pub escape_to_editor: bool,
@@ -649,10 +657,12 @@ impl Default for TerminalSettings {
mouse_reporting: true,
copy_on_selection: false,
paste_on_middle_click: true,
right_click_paste: false,
override_ide_shortcuts: true,
shell_integration: true,
highlight_hyperlinks: true,
highlight_selection: true,
run_commands_using_ide: true,
option_as_meta: false,
escape_to_editor: false,
cursor_shape: "block".into(),
@@ -752,6 +762,14 @@ mod tests {
assert_eq!(serde_json::to_value(&on).unwrap()["fixOnCommit"], true);
}
#[test]
fn git_defaults_enabled_and_can_be_disabled() {
let missing: GitSettings = serde_json::from_str("{}").unwrap();
let off: GitSettings = serde_json::from_str(r#"{"enabled":false}"#).unwrap();
assert!(missing.enabled);
assert!(!off.enabled);
}
#[test]
fn clone_submodules_defaults_on_and_can_be_disabled() {
let missing: GitSettings = serde_json::from_str("{}").unwrap();
+1
Переглянути файл
@@ -17,6 +17,7 @@ ide-jvm-attach.workspace = true
ide-jvm-inspect.workspace = true
ide-jdwp.workspace = true
ide-heap.workspace = true
ide-run.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
+55 -1
Переглянути файл
@@ -391,9 +391,10 @@ pub const DEBUGPY_MISSING: &str = "debugpy is not installed";
/// `PYTHONPATH`. Neither: an `unavailable` error naming the interpreter.
pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
let (command, cwd) = (spec.command.clone(), spec.cwd.clone());
let Some(python) = tokio::task::spawn_blocking(move || resolve_binary(&command, &cwd)).await.ok().flatten() else {
let Some(python) = tokio::task::spawn_blocking(move || debugpy_python(&command, &cwd)).await.ok().flatten() else {
return Ok(()); // Reported as a missing adapter when it is started.
};
spec.command = python.to_string_lossy().into_owned();
let mut probe = Command::new(&python);
probe.current_dir(&spec.cwd);
ide_core::process::prepare(probe.as_std_mut());
@@ -426,6 +427,46 @@ pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
)))
}
/// The interpreter `<python> -m debugpy.adapter` runs with. On Windows a bare `python3` (the
/// built-in `python.toml`'s) or `python` may name an App Execution Alias in `WindowsApps`,
/// which only opens the Store unless the Store's Python is installed: every match on `PATH`
/// of the command, then `python`, then the `py` launcher, the first that is no alias or runs.
fn debugpy_python(command: &str, cwd: &Path) -> Option<PathBuf> {
let found = resolve_binary(command, cwd);
if !cfg!(windows) || !matches!(command, "python3" | "python") {
return found;
}
let pathext = std::env::var("PATHEXT").ok();
let dirs = search_dirs(cwd);
let mut candidates: Vec<PathBuf> = Vec::new();
for name in [command, "python", "py"] {
for dir in &dirs {
if let Some(p) = find_binary_in(name, cwd, std::slice::from_ref(dir), true, pathext.as_deref())
&& !candidates.contains(&p)
{
candidates.push(p);
}
}
}
let runs = |p: &Path| {
let mut c = std::process::Command::new(p);
ide_core::process::prepare(&mut c);
c.arg("--version").stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
c.status().is_ok_and(|s| s.success())
};
pick_python(candidates, runs).or(found)
}
/// The first candidate that is no App Execution Alias, or is one that `runs`.
fn pick_python(candidates: Vec<PathBuf>, runs: impl Fn(&Path) -> bool) -> Option<PathBuf> {
candidates.into_iter().find(|p| !is_app_execution_alias(p) || runs(p))
}
/// A Windows App Execution Alias (`%LOCALAPPDATA%\Microsoft\WindowsApps\python3.exe`).
fn is_app_execution_alias(path: &Path) -> bool {
path.parent().and_then(Path::file_name).is_some_and(|d| d.eq_ignore_ascii_case("WindowsApps"))
}
/// GDB's DAP interpreter (`-i dap`) shipped in GDB 14; older ones exit with
/// "Interpreter `dap' unrecognized".
const GDB_MIN_MAJOR: u32 = 14;
@@ -859,6 +900,19 @@ async fn connect_with_retries(
mod tests {
use super::*;
/// Windows: a Store alias on `PATH` before the real interpreter is skipped unless it runs
/// (the Store's Python is installed), so the Python Debug Server starts the real one.
#[test]
fn debugpy_skips_store_aliases_that_do_not_run() {
let alias = PathBuf::from("C:/Users/me/AppData/Local/Microsoft/WindowsApps/python3.exe");
let real = PathBuf::from("C:/Program Files/Python313/python.exe");
assert!(is_app_execution_alias(&alias) && !is_app_execution_alias(&real));
let both = vec![alias.clone(), real.clone()];
assert_eq!(pick_python(both.clone(), |_| false), Some(real.clone()));
assert_eq!(pick_python(both, |_| true), Some(alias.clone()));
assert_eq!(pick_python(vec![alias], |_| false), None);
}
/// A user's `languages/python.toml` `[debugger]` is the one debugpy runs with: no other
/// language (a template one) declares debugpy before Python.
#[test]
+115
Переглянути файл
@@ -0,0 +1,115 @@
//! Machine code of a native program (DAP `disassemble`), for the Disassembly view.
use serde::{Deserialize, Serialize};
use serde_json::Value;
use specta::Type;
/// The most instructions one request asks for.
pub const MAX_INSTRUCTIONS: u32 = 1000;
/// One disassembled instruction.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct Instruction {
/// Address as the adapter writes it (`0x5555…`); also a memory reference for the next request.
pub address: String,
/// The instruction in the adapter's syntax (`mov -0x28(%rbp),%rax`).
pub instruction: String,
/// Its machine code as hex (`488b45d8`), when the adapter sends it.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub bytes: Option<String>,
/// The function it belongs to, when the adapter names it (often on the first instruction only).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub symbol: Option<String>,
}
/// `disassemble`'s instructions in order; `None` for the padding adapters put where there is no
/// code (`presentationHint: "invalid"`, or no address).
pub(crate) fn instructions(body: &Value) -> Vec<Option<Instruction>> {
let text = |i: &Value, k: &str| i.get(k).and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_owned);
let Some(list) = body.get("instructions").and_then(Value::as_array) else { return Vec::new() };
list.iter()
.map(|i| {
if i.get("presentationHint").and_then(Value::as_str) == Some("invalid") {
return None;
}
Some(Instruction {
address: text(i, "address")?,
instruction: text(i, "instruction").unwrap_or_default(),
bytes: text(i, "instructionBytes"),
symbol: text(i, "symbol"),
})
})
.collect()
}
/// A memory reference or address as a number (`0x7ffd…` or decimal).
pub(crate) fn address(reference: &str) -> Option<u128> {
let r = reference.trim();
match r.strip_prefix("0x").or_else(|| r.strip_prefix("0X")) {
Some(hex) => u128::from_str_radix(hex, 16).ok(),
None => r.parse().ok(),
}
}
/// Whether the instruction at `index` is the one at `reference`. References that are not
/// addresses cannot be checked and pass.
pub(crate) fn at_index(instructions: &[Option<Instruction>], reference: &str, index: usize) -> bool {
let Some(want) = address(reference) else { return instructions.len() > index };
instructions.get(index).and_then(Option::as_ref).and_then(|i| address(&i.address)) == Some(want)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn reads_gdbs_instructions() {
// GDB 17.1 at the reporter-style C fixture's loop line.
let body = json!({"instructions": [
{"address": "0x5555555551f5", "instruction": "mov -0x2c(%rbp),%eax", "instructionBytes": "8b45d4", "line": 14},
{"address": "0x5555555551f8", "instruction": "cltq", "instructionBytes": "4898", "symbol": "sum"},
]});
let got = instructions(&body);
assert_eq!(
got[0],
Some(Instruction {
address: "0x5555555551f5".into(),
instruction: "mov -0x2c(%rbp),%eax".into(),
bytes: Some("8b45d4".into()),
symbol: None,
})
);
assert_eq!(got[1].as_ref().unwrap().symbol.as_deref(), Some("sum"));
}
#[test]
fn padding_is_not_an_instruction() {
let body = json!({"instructions": [
{"address": "0xfff0", "instruction": "", "presentationHint": "invalid"},
{"instruction": "??"},
{"address": "0x10000", "instruction": "nop"},
]});
let got = instructions(&body);
assert_eq!((got[0].is_none(), got[1].is_none(), got[2].is_some()), (true, true, true));
assert!(instructions(&json!({})).is_empty());
}
#[test]
fn finds_the_reference_by_its_address() {
let list = instructions(&json!({"instructions": [
{"address": "0x00001000", "instruction": "push %rbp"},
{"address": "0x1001", "instruction": "mov %rsp,%rbp"},
]}));
assert!(at_index(&list, "0x1001", 1));
assert!(at_index(&list, "4097", 1));
assert!(at_index(&list, "0X1000", 0));
assert!(!at_index(&list, "0x1001", 0));
assert!(!at_index(&list, "0x1001", 2));
assert!(at_index(&list, "frame-3", 1), "opaque references cannot be checked");
assert_eq!(address("0xffffffffffffffff1"), Some(0xffffffffffffffff1));
}
}
+232 -9
Переглянути файл
@@ -13,6 +13,7 @@ pub mod attach;
mod cargo;
pub mod connection;
mod debugpy;
mod disassembly;
mod exception_classes;
pub mod jdwp;
mod js_cdp;
@@ -20,12 +21,15 @@ mod js_debug;
mod jvm_memory;
pub mod kotlin;
pub mod kotlin_lsp;
mod memory;
mod session;
mod stream_trace;
mod swiftpm;
pub mod unity;
use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
use adapter::{AdapterIo, AdapterLauncher, AdapterSpec, ProcessLauncher};
use connection::{Connection, DapError};
pub use disassembly::{Instruction, MAX_INSTRUCTIONS};
pub use exception_classes::{ExceptionClassBreakpoint, ExceptionClassSupport};
use futures::future::join_all;
use ide_core::{DebugSessionId, IdeError, IdeResult, RunId, SharedSink};
@@ -33,6 +37,7 @@ use ide_language::LanguageRegistry;
pub use js_cdp::JsResponseRule;
pub use js_debug::JsResponseBody;
pub use jvm_memory::*;
pub use memory::{MAX_READ, MemoryBlock};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -45,6 +50,11 @@ use std::sync::{Arc, Weak};
use std::time::Duration;
pub use stream_trace::{TracePhase, TraceProgress, TraceRun, TraceUnavailable};
/// The adapter name of a notebook kernel's own debugger (see [`DebugManager::start_over`]).
pub const NOTEBOOK_ADAPTER: &str = "jupyter-kernel";
/// How a notebook cell's breakpoints are keyed: `vscode-notebook-cell:<notebook>#<cell>`.
pub const NOTEBOOK_CELL_SCHEME: &str = "vscode-notebook-cell:";
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct LaunchConfig {
@@ -154,6 +164,12 @@ pub struct DebugCapabilities {
/// A stream chain can be traced while the program runs it ([`DebugManager::stream_trace`]).
/// Can change during the session, like `jvm_instances`.
pub stream_trace: bool,
/// The program's raw memory can be read ([`DebugManager::read_memory`]): the Memory View.
pub read_memory: bool,
/// The program's machine code can be disassembled ([`DebugManager::disassemble`]): the Disassembly view.
pub disassemble: bool,
/// Steps can move by one instruction ([`DebugManager::step_instruction`]).
pub instruction_stepping: bool,
}
/// Result of [`DebugManager::redefine_classes`].
@@ -220,6 +236,10 @@ pub struct StackFrame {
pub column: u32,
/// `subtle` frames (library/generated) are collapsed in the UI.
pub presentation_hint: Option<String>,
/// The frame's program counter, for [`DebugManager::disassemble`] (DAP `instructionPointerReference`).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub instruction_pointer_reference: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -244,6 +264,10 @@ pub struct Variable {
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
#[specta(optional)]
pub lazy: bool,
/// Where the value points to or is stored, for [`DebugManager::read_memory`] (DAP `memoryReference`).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub memory_reference: Option<String>,
}
/// A completion the adapter offers for an expression (DAP `completions`).
@@ -590,6 +614,15 @@ pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult<Option<Debug
Ok(Some(DebugServer { host, port }))
}
/// A source served only through the `source` request whose `path` is no file, such as
/// lldb-dap's ``/usr/lib/swift/libswiftCore.dylib`swift_willThrow`` for a frame without
/// debug info. Opening it would show an error tab; without a path the stop selects the
/// first frame with source instead. Non-file paths (`jdt://`, `<node_internals>`) stay.
fn is_pseudo_path(source: Option<&Value>, path: &str) -> bool {
let reference = source.and_then(|s| s.get("sourceReference")).and_then(Value::as_i64).unwrap_or(0);
reference > 0 && Path::new(path).is_absolute() && !Path::new(path).exists()
}
/// DAP stack frame → [`StackFrame`] (1-based → 0-based).
pub(crate) fn frame_from(f: &Value) -> StackFrame {
let source = f.get("source");
@@ -602,10 +635,19 @@ pub(crate) fn frame_from(f: &Value) -> StackFrame {
StackFrame {
id: f.get("id").and_then(Value::as_i64).unwrap_or_default(),
name: f.get("name").and_then(Value::as_str).unwrap_or_default().to_owned(),
path: source.and_then(|s| s.get("path")).and_then(Value::as_str).map(Into::into),
path: source
.and_then(|s| s.get("path"))
.and_then(Value::as_str)
.filter(|p| !is_pseudo_path(source, p))
.map(Into::into),
line: (f.get("line").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
column: (f.get("column").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
presentation_hint: hint,
instruction_pointer_reference: f
.get("instructionPointerReference")
.and_then(Value::as_str)
.filter(|r| !r.is_empty())
.map(str::to_owned),
}
}
@@ -682,6 +724,9 @@ pub(crate) fn capabilities_from(caps: &Value) -> DebugCapabilities {
js_page: false,
live_evaluate: false,
stream_trace: false,
read_memory: has("supportsReadMemoryRequest"),
disassemble: has("supportsDisassembleRequest"),
instruction_stepping: has("supportsSteppingGranularity"),
}
}
@@ -770,9 +815,15 @@ pub(crate) fn variable_from(v: &Value) -> Variable {
variables_reference: v.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
evaluate_name: s("evaluateName"),
lazy: v.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false),
memory_reference: memory_reference(v),
}
}
/// A variable's or evaluation result's `memoryReference`.
fn memory_reference(v: &Value) -> Option<String> {
v.get("memoryReference").and_then(Value::as_str).filter(|r| !r.is_empty()).map(str::to_owned)
}
async fn session_variables(session: &Session, reference: i64) -> IdeResult<Vec<Variable>> {
let body =
session.conn.request_timeout("variables", json!({ "variablesReference": reference }), REQUEST_TIMEOUT).await?;
@@ -796,6 +847,7 @@ async fn resolve_in(session: &Session, variable: Variable) -> IdeResult<Variable
value: value.value,
variables_reference: value.variables_reference,
lazy: value.lazy,
memory_reference: value.memory_reference.or(variable.memory_reference),
},
_ => variable,
})
@@ -874,6 +926,30 @@ impl DebugManager {
.collect()
}
/// Whether `s` is live and currently suspended (a breakpoint, step or manual pause).
/// `None` when the session has ended.
pub fn session_suspended(&self, s: DebugSessionId) -> Option<bool> {
self.sessions.lock().get(&s).map(|session| session.suspended.get())
}
/// The thread of `s`'s most recent stop, when the adapter named one.
pub fn stopped_thread(&self, s: DebugSessionId) -> Option<i64> {
self.sessions.lock().get(&s).and_then(|session| session.suspended.stopped_thread())
}
/// All stored breakpoints of `owner`, for tools that list or edit them. Line breakpoints
/// are keyed by file; function and data breakpoints have no file.
pub fn breakpoints(
&self,
owner: &str,
) -> (BTreeMap<PathBuf, Vec<Breakpoint>>, Vec<FunctionBreakpoint>, Vec<DataBreakpoint>) {
let store = self.breakpoints.lock();
match store.get(owner) {
Some(owner) => (owner.lines.clone(), owner.functions.clone(), owner.data.clone()),
None => Default::default(),
}
}
/// Starts a session: spawns the adapter, `initialize`, `launch`/`attach`,
/// waits for `initialized`, sends breakpoints, then `configurationDone`.
/// Events of the session (including cargo build output) go to `owner` only.
@@ -1018,6 +1094,9 @@ impl DebugManager {
.await?;
arguments["program"] = json!(program);
}
if let Some(spm) = arguments.as_object_mut().and_then(|o| o.remove("swiftpm")) {
arguments["program"] = json!(swiftpm::program(&cwd, &spm, &cancel).await?);
}
// Attach to a Node process started without `--inspect`: open its inspector first.
if config.adapter == "js-debug" && config.request == "attach" && arguments.get("port").is_none() {
let pid = arguments.get("processId").and_then(|p| match p {
@@ -1078,6 +1157,51 @@ impl DebugManager {
port,
exception_classes,
cancel,
None,
)
.await
}
/// Starts an `attach` session named `name` over `io`: a debugger reached without an
/// adapter process, such as a notebook kernel's over its control channel
/// ([`NOTEBOOK_ADAPTER`]). `arguments` is the `attach` request's. `notebook_cells`, the
/// prefix of a notebook's cell URIs, gives the session that notebook's cell breakpoints.
pub async fn start_over(
&self,
io: AdapterIo,
name: String,
adapter: String,
arguments: Value,
owner: SessionOwner,
notebook_cells: Option<String>,
) -> IdeResult<DebugSessionId> {
let spec = AdapterSpec {
adapter: adapter.clone(),
command: String::new(),
args: Vec::new(),
transport: adapter::Transport::Stdio,
install_hint: None,
cwd: PathBuf::new(),
env: Vec::new(),
server_host: None,
connect: None,
pinned: None,
resolve_lazy_variables: false,
};
let cancel = ide_core::CancellationToken::new();
self.start_session(
DebugSessionId::next(),
owner,
name,
adapter,
None,
"attach".into(),
arguments,
spec,
None,
None,
cancel,
Some((io, notebook_cells)),
)
.await
}
@@ -1113,6 +1237,7 @@ impl DebugManager {
port,
None,
ide_core::CancellationToken::new(),
None,
)
.await
.map(|_| ())
@@ -1132,6 +1257,7 @@ impl DebugManager {
reuse_port: Option<u16>,
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
cancel: ide_core::CancellationToken,
connected: Option<(AdapterIo, Option<String>)>,
) -> IdeResult<DebugSessionId> {
if request != "launch" && request != "attach" {
return Err(IdeError::invalid(format!("request must be `launch` or `attach`, got `{request}`")));
@@ -1139,10 +1265,16 @@ impl DebugManager {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let io = tokio::select! {
biased;
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
io = self.launcher.launch(spec.clone(), reuse_port) => io?,
let (io, notebook_cells) = match connected {
Some((io, cells)) => (io, cells),
None => (
tokio::select! {
biased;
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
io = self.launcher.launch(spec.clone(), reuse_port) => io?,
},
None,
),
};
let launch_after_configuration = io.launch_after_configuration && request == "launch";
let stderr = io.stderr.clone();
@@ -1155,6 +1287,7 @@ impl DebugManager {
.flatten();
let mut session = Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child);
session.exception_classes = exception_classes;
session.notebook_cells = notebook_cells;
session.run = take_run_link(&mut arguments);
let session = Arc::new(session);
if let Some(launch_type) = arguments.get("type").and_then(Value::as_str) {
@@ -1274,7 +1407,7 @@ impl DebugManager {
"supportsProgressReporting": true,
// kotlin-lsp sends `invalidated` either way.
"supportsInvalidatedEvent": is_kotlin_lsp,
"supportsMemoryReferences": false,
"supportsMemoryReferences": true,
"supportsArgsCanBeInterpretedByShell": false,
}),
INIT_TIMEOUT,
@@ -1282,6 +1415,9 @@ impl DebugManager {
.await?;
*s.caps.lock() = if caps.is_object() { caps } else { json!({}) };
if s.adapter == adapter::JAVA_ANALYZER && s.request == "launch" {
session::shorten_java_analyzer_classpath(s, &mut arguments)?;
}
// The Kotlin adapters ignore the resolved classpath and project runtime on launch.
let request = if kotlin::is_kotlin(&s.adapter) && s.request == "launch" {
session::start_kotlin_debuggee(s, &mut arguments).await?;
@@ -1378,6 +1514,7 @@ impl DebugManager {
.map(|b| b.lines.iter().map(|(p, b)| (p.clone(), b.clone())).collect::<Vec<_>>())
.unwrap_or_default()
.into_iter()
.filter(|(path, _)| s.takes(path))
.partition(|(_, b)| b.iter().any(|b| b.enabled));
let sent = join_all(files.iter().map(|(path, bps)| s.send_breakpoints(path, bps, None))).await;
// Breakpoint states follow the owner's first session.
@@ -1607,7 +1744,7 @@ impl DebugManager {
breakpoints: Vec<Breakpoint>,
) -> IdeResult<Vec<BreakpointState>> {
let mut result: Option<Vec<BreakpointState>> = None;
for s in self.configured_sessions(owner) {
for s in self.configured_sessions(owner).into_iter().filter(|s| s.takes(&path)) {
match s.send_breakpoints(&path, &breakpoints, None).await {
Ok(states) => {
result.get_or_insert(states);
@@ -1731,6 +1868,7 @@ impl DebugManager {
variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
evaluate_name: evaluate_name.or(Some(name)),
lazy: false,
memory_reference: memory_reference(&body),
})
}
@@ -1868,6 +2006,7 @@ impl DebugManager {
variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
evaluate_name: Some(expression),
lazy: body.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false),
memory_reference: memory_reference(&body),
};
if !session.spec.resolve_lazy_variables {
return Ok(result);
@@ -1959,6 +2098,22 @@ impl DebugManager {
}
pub async fn step(&self, s: DebugSessionId, thread_id: i64, kind: StepKind) -> IdeResult<()> {
self.step_with(s, thread_id, kind, json!({ "threadId": thread_id })).await
}
/// Step Over / Into Instruction: a step by one machine instruction (DAP `granularity`).
pub async fn step_instruction(&self, s: DebugSessionId, thread_id: i64, kind: StepKind) -> IdeResult<()> {
let session = self.session(s)?;
if !session.supports("supportsSteppingGranularity") {
return Err(IdeError::unavailable(format!(
"debug adapter `{}` cannot step by instruction",
session.adapter
)));
}
self.step_with(s, thread_id, kind, json!({ "threadId": thread_id, "granularity": "instruction" })).await
}
async fn step_with(&self, s: DebugSessionId, thread_id: i64, kind: StepKind, args: Value) -> IdeResult<()> {
let command = match kind {
StepKind::Over => "next",
StepKind::Into => "stepIn",
@@ -1970,7 +2125,7 @@ impl DebugManager {
quirks.step_sent();
}
let ticket = session.suspended.ticket();
let sent = session.conn.request_timeout(command, json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await;
let sent = session.conn.request_timeout(command, args, REQUEST_TIMEOUT).await;
step_settled(&session, sent)?;
// A step runs its thread; other threads stopped by their own events stay stopped.
session.finish_resume(ticket, thread_id, false);
@@ -2124,6 +2279,74 @@ impl DebugManager {
Ok(())
}
/// `count` bytes (at most [`MAX_READ`]) from `offset` bytes after `memory_reference`, which
/// comes from a variable, an evaluation result or an earlier read's address.
pub async fn read_memory(
&self,
s: DebugSessionId,
memory_reference: String,
offset: i64,
count: u32,
) -> IdeResult<MemoryBlock> {
let session = self.session(s)?;
if !session.supports("supportsReadMemoryRequest") {
return Err(IdeError::unavailable(format!("debug adapter `{}` cannot read memory", session.adapter)));
}
let count = count.min(MAX_READ);
let body = session
.conn
.request_timeout(
"readMemory",
json!({ "memoryReference": memory_reference, "offset": offset, "count": count }),
REQUEST_TIMEOUT,
)
.await?;
memory::memory_block(&body, count)
}
/// `count` instructions (at most [`MAX_INSTRUCTIONS`]) from `before` instructions ahead of
/// `memory_reference` (a frame's instruction pointer or an instruction's address). Adapters that
/// cannot disassemble backwards start at the reference instead.
pub async fn disassemble(
&self,
s: DebugSessionId,
memory_reference: String,
before: u32,
count: u32,
) -> IdeResult<Vec<Instruction>> {
let session = self.session(s)?;
if !session.supports("supportsDisassembleRequest") {
return Err(IdeError::unavailable(format!("debug adapter `{}` cannot disassemble", session.adapter)));
}
let count = count.clamp(1, MAX_INSTRUCTIONS);
let before = before.min(count - 1);
let request = |offset: i64, count: u32| {
session.conn.request_timeout(
"disassemble",
json!({
"memoryReference": memory_reference,
"offset": 0,
"instructionOffset": offset,
"instructionCount": count,
"resolveSymbols": true,
}),
REQUEST_TIMEOUT,
)
};
if before > 0 {
// GDB (up to 17 at least) answers a negative instruction offset with the instructions after
// the reference, or fails: only an answer with the reference in its place is used.
if let Ok(body) = request(-i64::from(before), count).await {
let instructions = disassembly::instructions(&body);
if disassembly::at_index(&instructions, &memory_reference, before as usize) {
return Ok(instructions.into_iter().flatten().collect());
}
}
}
let body = request(0, count - before).await?;
Ok(disassembly::instructions(&body).into_iter().flatten().collect())
}
pub fn capabilities(&self, s: DebugSessionId) -> IdeResult<DebugCapabilities> {
Ok(session_capabilities(&*self.session(s)?))
}
+88
Переглянути файл
@@ -0,0 +1,88 @@
//! Raw memory of a native program (DAP `readMemory`), for the Memory View.
use base64::Engine;
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use specta::Type;
/// The most bytes one read asks for: a few pages of the view, never a whole mapping.
pub const MAX_READ: u32 = 64 * 1024;
/// Answer of `readMemory`: `data` starts at `address`; the `unreadable_bytes` after it could not be read.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MemoryBlock {
/// Address of the first byte, as the adapter writes it (`0x7ffd…`; may be wider than 53 bits).
pub address: String,
pub data: Vec<u8>,
pub unreadable_bytes: u32,
}
/// `readMemory`'s body for a read of `count` bytes. Adapters leave `data` out (or empty) when
/// nothing could be read; the bytes asked for then count as unreadable.
pub(crate) fn memory_block(body: &Value, count: u32) -> IdeResult<MemoryBlock> {
let address = match body.get("address") {
Some(Value::String(a)) if !a.is_empty() => a.clone(),
Some(Value::Number(n)) => n.to_string(),
_ => return Err(IdeError::internal("the debug adapter answered readMemory without an address")),
};
let mut data = match body.get("data").and_then(Value::as_str) {
Some(b64) if !b64.is_empty() => base64::engine::general_purpose::STANDARD
.decode(b64)
.map_err(|e| IdeError::internal(format!("the debug adapter sent memory that is not base64: {e}")))?,
_ => Vec::new(),
};
data.truncate(count as usize);
// At most the rest of what was asked for (the data is never more than that).
let rest = count - data.len() as u32;
let unreadable_bytes = match body.get("unreadableBytes").and_then(Value::as_u64) {
Some(n) => n.min(u64::from(rest)) as u32,
None if data.is_empty() => count,
None => 0,
};
Ok(MemoryBlock { address, data, unreadable_bytes })
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn decodes_the_bytes_and_keeps_the_address_as_written() {
// The reporter's `&msg[0]` (#5921): "Hello, World!\n" and its terminator.
let body = json!({"address": "0x000000016FDFE9A0", "data": "SGVsbG8sIFdvcmxkIQoA"});
let block = memory_block(&body, 15).unwrap();
assert_eq!(block.address, "0x000000016FDFE9A0");
assert_eq!(block.data, b"Hello, World!\n\0");
assert_eq!(block.unreadable_bytes, 0);
}
#[test]
fn missing_data_is_unreadable_not_empty() {
let block = memory_block(&json!({"address": "0x0"}), 256).unwrap();
assert!(block.data.is_empty());
assert_eq!(block.unreadable_bytes, 256);
let block = memory_block(&json!({"address": "0x0", "data": "", "unreadableBytes": 16}), 256).unwrap();
assert_eq!(block.unreadable_bytes, 16);
}
#[test]
fn a_partial_read_reports_the_rest_as_unreadable() {
let block = memory_block(&json!({"address": "0x1000", "data": "AAEC", "unreadableBytes": 13}), 16).unwrap();
assert_eq!((block.data.as_slice(), block.unreadable_bytes), (&[0u8, 1, 2][..], 13));
// Counts that disagree with the request are clamped to it.
let block = memory_block(&json!({"address": "0x1000", "data": "AAEC", "unreadableBytes": 99}), 16).unwrap();
assert_eq!(block.unreadable_bytes, 13);
let block = memory_block(&json!({"address": "0x1000", "data": "AAECAw=="}), 2).unwrap();
assert_eq!((block.data.as_slice(), block.unreadable_bytes), (&[0u8, 1][..], 0));
}
#[test]
fn rejects_answers_without_an_address_or_with_bad_data() {
assert!(memory_block(&json!({"data": "AA=="}), 1).is_err());
assert!(memory_block(&json!({"address": "0x10", "data": "not base64!"}), 1).is_err());
assert_eq!(memory_block(&json!({"address": 4096, "data": "AA=="}), 1).unwrap().address, "4096");
}
}
+167 -30
Переглянути файл
@@ -125,6 +125,8 @@ pub(crate) struct Session {
pub stream_tracer: parking_lot::Mutex<Option<Arc<dyn ide_jvm_inspect::StreamTracer>>>,
/// Given at start: the class breakpoints must be armed before `configurationDone`.
pub(crate) exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
/// A notebook kernel's session: the prefix of its notebook's cell URIs (`…/a.ipynb#`).
pub(crate) notebook_cells: Option<String>,
/// Held from `setExceptionBreakpoints`, which drops the class breakpoints, until they are
/// armed again, so that the last list armed is the manager's.
pub(crate) exception_turn: tokio::sync::Mutex<()>,
@@ -134,6 +136,16 @@ pub(crate) struct Session {
/// Used only by a kotlin-lsp session: see [`Session::kotlin_lsp_quirks`].
pub(crate) quirks: kotlin_lsp::Quirks,
pub(crate) unity_startup_activity: Mutex<Instant>,
/// Temporary pathing jars / argfiles created for this session; removed on stop/drop.
temp_files: Mutex<Vec<TempFile>>,
}
struct TempFile(PathBuf);
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
/// Which threads of the program are suspended: each from its `stopped` event until a
@@ -205,6 +217,14 @@ impl Suspension {
stops.all.is_some() || !stops.threads.is_empty()
}
/// The most recently stopped individual thread, when the stop named one. A stop of every
/// thread (`allThreadsStopped`) names none, so callers fall back to the adapter's first thread.
pub fn stopped_thread(&self) -> Option<i64> {
let stops = self.0.lock();
let latest = stops.latest()?;
stops.threads.iter().find(|&&(_, ticket)| ticket == latest).map(|&(id, _)| id)
}
/// A `stopped` event; `all`: its `allThreadsStopped`.
pub fn stopped(&self, thread: Option<i64>, all: bool) {
let mut stops = self.0.lock();
@@ -342,11 +362,13 @@ impl Session {
run: None,
stream_tracer: parking_lot::Mutex::new(None),
exception_classes: None,
notebook_cells: None,
exception_turn: tokio::sync::Mutex::default(),
stream_trace: parking_lot::Mutex::new(None),
stream_trace_done: parking_lot::Mutex::new(None),
quirks: kotlin_lsp::Quirks::default(),
unity_startup_activity: Mutex::new(Instant::now()),
temp_files: Mutex::new(Vec::new()),
}
}
@@ -425,6 +447,14 @@ impl Session {
/// Sends the breakpoints of one file (disabled ones omitted, plus an optional
/// temporary line) and returns verification states aligned with `breakpoints`.
/// Whether this session gets the breakpoints of `path`: a notebook cell's go only to the
/// session of that notebook's kernel, which knows the cell's code.
pub(crate) fn takes(&self, path: &Path) -> bool {
let path = path.to_string_lossy();
!path.starts_with(crate::NOTEBOOK_CELL_SCHEME)
|| self.notebook_cells.as_deref().is_some_and(|cells| path.starts_with(cells))
}
pub async fn send_breakpoints(
&self,
path: &Path,
@@ -570,6 +600,7 @@ impl Session {
if let Some(mut program) = self.program.lock().take() {
program.kill();
}
self.temp_files.lock().clear();
}
}
@@ -1307,43 +1338,112 @@ fn kotlin_jvm_args(user: Vec<String>, windows: bool) -> Vec<String> {
args
}
fn json_string_list(args: &Value, key: &str) -> Vec<String> {
args.get(key)
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect())
.unwrap_or_default()
}
fn json_args_len(args: &Value, key: &str) -> usize {
match args.get(key) {
Some(Value::String(s)) => s.len() + 3,
Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(|s| s.len() + 3).sum(),
_ => 0,
}
}
/// Shortens `classPaths` for `java-analyzer dap` into a temporary manifest-only pathing jar when
/// the command line would exceed the OS limit (e.g. Windows `CreateProcessW` `os error 206` on
/// JDK 8 Spring Boot projects).
pub(crate) fn shorten_java_analyzer_classpath(s: &Arc<Session>, args: &mut Value) -> ide_core::IdeResult<()> {
let cwd = args.get("cwd").and_then(Value::as_str).map(PathBuf::from).unwrap_or_else(|| s.spec.cwd.clone());
if let Some(jar) =
shorten_java_analyzer_classpath_with(args, &cwd, cfg!(windows), &ide_run::java_cmdline::default_temp_dir())?
{
s.temp_files.lock().push(TempFile(jar));
}
Ok(())
}
fn shorten_java_analyzer_classpath_with(
args: &mut Value,
cwd: &Path,
windows: bool,
temp_dir: &Path,
) -> ide_core::IdeResult<Option<PathBuf>> {
let java = args.get("javaExec").and_then(Value::as_str).unwrap_or("java");
let class_paths = json_string_list(args, "classPaths");
let module_paths = json_string_list(args, "modulePaths");
let extra_len = json_args_len(args, "vmArgs")
+ json_args_len(args, "args")
+ args.get("mainClass").and_then(Value::as_str).map_or(0, |s| s.len() + 3);
let Some(jar) = ide_run::java_cmdline::shorten_classpath_to_jar(
Path::new(java),
&class_paths,
&module_paths,
extra_len,
cwd,
windows,
temp_dir,
)?
else {
return Ok(None);
};
args["classPaths"] = json!([jar.to_string_lossy()]);
Ok(Some(jar))
}
/// Launch with the IDE's resolved runtime and classpath; the adapter only attaches.
pub(crate) async fn start_kotlin_debuggee(s: &Arc<Session>, args: &mut Value) -> ide_core::IdeResult<()> {
use tokio::io::{AsyncBufReadExt, BufReader};
let java = args.get("javaExec").and_then(Value::as_str).unwrap_or("java");
let strings = |key: &str| -> Vec<String> {
args.get(key)
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect())
.unwrap_or_default()
};
let classpath =
std::env::join_paths(strings("classPaths")).map_err(|e| ide_core::IdeError::invalid(e.to_string()))?;
let classpath = std::env::join_paths(json_string_list(args, "classPaths"))
.map_err(|e| ide_core::IdeError::invalid(e.to_string()))?
.to_string_lossy()
.into_owned();
let mut java_args = kotlin_jvm_args(json_string_list(args, "vmArguments"), cfg!(windows));
// Let the JVM pick its own port (`:0`) and report it below: pre-picking a free
// port here races with other processes that may take it before the JVM binds.
java_args.push("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0".to_owned());
java_args.push("-cp".to_owned());
java_args.push(classpath);
let modules = json_string_list(args, "modulePaths");
if !modules.is_empty() {
java_args.push("--module-path".to_owned());
java_args.push(
std::env::join_paths(modules)
.map_err(|e| ide_core::IdeError::invalid(e.to_string()))?
.to_string_lossy()
.into_owned(),
);
}
java_args.push(
args.get("mainClass")
.and_then(Value::as_str)
.ok_or_else(|| ide_core::IdeError::invalid("Missing Kotlin main class"))?
.to_owned(),
);
java_args.extend(json_string_list(args, "programArgs"));
if let Some(shortened) = ide_run::java_cmdline::shorten(
Path::new(java),
&java_args,
&s.spec.cwd,
cfg!(windows),
&ide_run::java_cmdline::default_temp_dir(),
)? {
java_args = shortened.args;
s.temp_files.lock().push(TempFile(shortened.file));
}
let mut cmd = tokio::process::Command::new(java);
cmd.current_dir(&s.spec.cwd);
ide_core::process::prepare(cmd.as_std_mut());
cmd.args(kotlin_jvm_args(strings("vmArguments"), cfg!(windows)))
// Let the JVM pick its own port (`:0`) and report it below: pre-picking a free
// port here races with other processes that may take it before the JVM binds.
.arg("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0")
.arg("-cp")
.arg(classpath);
let modules = strings("modulePaths");
if !modules.is_empty() {
cmd.arg("--module-path")
.arg(std::env::join_paths(modules).map_err(|e| ide_core::IdeError::invalid(e.to_string()))?);
}
cmd.arg(
args.get("mainClass")
.and_then(Value::as_str)
.ok_or_else(|| ide_core::IdeError::invalid("Missing Kotlin main class"))?,
)
.args(strings("programArgs"))
.envs(ide_core::process::shell_env_in(&s.spec.cwd))
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
cmd.args(&java_args)
.envs(ide_core::process::shell_env_in(&s.spec.cwd))
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
if let Some(env) = args.get("env").and_then(Value::as_object) {
for (k, v) in env {
if let Some(v) = v.as_str() {
@@ -1662,4 +1762,41 @@ mod tests {
// SAFETY: signal 0 only checks whether the process exists.
assert_eq!(unsafe { libc::kill(pid, 0) }, -1);
}
#[test]
fn java_analyzer_long_windows_classpath_is_shortened_to_pathing_jar() {
let dir = tempfile::tempdir().unwrap();
let short_cp = vec![r"C:\app\target\classes".to_owned()];
let mut short_args = serde_json::json!({
"javaExec": r"E:\software\Java\jdk1.8.0_431\bin\java.exe",
"mainClass": "com.example.App",
"classPaths": short_cp,
"vmArgs": ["-Dspring.output.ansi.enabled=always"],
"args": [],
});
assert!(
super::shorten_java_analyzer_classpath_with(&mut short_args, dir.path(), true, dir.path())
.unwrap()
.is_none()
);
assert_eq!(short_args["classPaths"].as_array().unwrap().len(), 1);
let many: Vec<String> = (0..500)
.map(|i| format!(r"C:\Users\dev\.m2\repository\org\springframework\boot\dep-{i:04}\dep-{i:04}.jar"))
.collect();
let mut long_args = serde_json::json!({
"javaExec": r"E:\software\Java\jdk1.8.0_431\bin\java.exe",
"mainClass": "com.example.App",
"classPaths": many,
"vmArgs": ["-Dspring.output.ansi.enabled=always"],
"args": [],
});
let jar = super::shorten_java_analyzer_classpath_with(&mut long_args, dir.path(), true, dir.path())
.unwrap()
.expect("long Windows classpath must be shortened into a pathing jar");
assert!(jar.is_file());
let replaced = long_args["classPaths"].as_array().unwrap();
assert_eq!(replaced.len(), 1);
assert_eq!(replaced[0].as_str().unwrap(), jar.to_string_lossy());
}
}
+68
Переглянути файл
@@ -0,0 +1,68 @@
//! SwiftPM launch integration: a launch request may carry
//! `"swiftpm": {"product": "greet", "buildArgs": ["-c", "release"]}` instead of `program`.
//! The run configuration's before launch task has built the product; this asks
//! `swift build <buildArgs> --show-bin-path` where it went (`.build/<triple>/<configuration>`,
//! or wherever `--scratch-path` / `--build-path` put it) and launches it from there.
use crate::adapter::find_binary;
use ide_core::{IdeError, IdeResult};
use serde_json::Value;
use std::path::{Path, PathBuf};
use std::process::Stdio;
/// `swift build` arguments that print the bin path for `buildArgs` without building.
pub fn bin_path_args(swiftpm: &Value) -> Vec<String> {
let mut args = vec!["build".to_owned()];
if let Some(a) = swiftpm.get("buildArgs").and_then(Value::as_array) {
args.extend(a.iter().filter_map(|v| v.as_str().map(str::to_owned)));
}
args.push("--show-bin-path".into());
args
}
/// The built product of `swiftpm` (see the module docs).
pub async fn program(cwd: &Path, swiftpm: &Value, cancel: &ide_core::CancellationToken) -> IdeResult<PathBuf> {
let product = swiftpm
.get("product")
.and_then(Value::as_str)
.filter(|p| !p.is_empty())
.ok_or_else(|| IdeError::invalid("the SwiftPM launch names no product"))?;
let swift = find_binary("swift", cwd).ok_or_else(|| IdeError::unavailable("`swift` not found on PATH"))?;
let args = bin_path_args(swiftpm);
let mut cmd = tokio::process::Command::new(swift);
cmd.current_dir(cwd);
ide_core::process::prepare(cmd.as_std_mut());
cmd.args(&args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
let out = tokio::select! {
biased;
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
out = cmd.output() => out.map_err(|e| IdeError::unavailable(format!("failed to run swift: {e}")))?,
};
if !out.status.success() {
let err = String::from_utf8_lossy(&out.stderr);
return Err(IdeError::invalid(format!("swift {} failed: {}", args.join(" "), err.trim())));
}
// The bin path is the last line: SwiftPM may print warnings about the manifest first.
let stdout = String::from_utf8_lossy(&out.stdout);
let dir = stdout.lines().map(str::trim).rfind(|l| !l.is_empty()).unwrap_or_default();
if dir.is_empty() {
return Err(IdeError::invalid("swift build --show-bin-path printed no path"));
}
let exe = if cfg!(windows) { format!("{product}.exe") } else { product.to_owned() };
Ok(cwd.join(dir).join(exe))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn asks_swift_build_for_the_bin_path_of_the_run_configurations_build() {
assert_eq!(bin_path_args(&json!({"product": "greet"})), ["build", "--show-bin-path"]);
assert_eq!(
bin_path_args(&json!({"product": "greet", "buildArgs": ["-c", "release"]})),
["build", "-c", "release", "--show-bin-path"]
);
}
}
+243
Переглянути файл
@@ -6,6 +6,7 @@ mod stream_trace;
use super::*;
use crate::adapter::{AdapterIo, LaunchFuture};
use base64::Engine;
use ide_core::IdeEvent;
use ide_core::event::DebugEvent;
use ide_jsonrpc::framing;
@@ -195,6 +196,21 @@ struct Script {
accept: &'static [&'static str],
/// Requests of the adapter's own answered with a body and followed by events.
custom: Option<fn(&Value) -> Option<CustomReply>>,
/// Advertise `supportsReadMemoryRequest`: memory below 0x1010 reads as its low address byte,
/// memory from there on is unmapped.
read_memory: bool,
/// Advertise `supportsDisassembleRequest` and `supportsSteppingGranularity`, disassembling like
/// this adapter: 4-byte instructions from 0x1000 to 0x1100, nothing mapped around them.
disassemble: Option<FakeDisassembler>,
}
#[derive(Clone, Copy, PartialEq)]
enum FakeDisassembler {
/// Negative instruction offsets work; unmapped places are `invalid` padding.
Lldb,
/// GDB 17: disassembles `instructionOffset + instructionCount` instructions from the reference and
/// drops the first `instructionOffset` of them, the way a Python slice does.
Gdb,
}
/// The answer to a request of the adapter's own: the response body, then events (name, body).
@@ -242,6 +258,8 @@ impl Default for Script {
empty_thread_responses: 0,
accept: &[],
custom: None,
read_memory: false,
disassemble: None,
}
}
}
@@ -328,6 +346,9 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
"supportsDataBreakpoints": true,
"supportsStepInTargetsRequest": true,
"supportsRestartFrame": true,
"supportsReadMemoryRequest": script.read_memory,
"supportsDisassembleRequest": script.disassemble.is_some(),
"supportsSteppingGranularity": script.disassemble.is_some(),
"exceptionBreakpointFilters": [
{"filter": "raised", "label": "Raised"},
{"filter": "uncaught", "label": "Uncaught", "default": true, "description": "Uncaught exceptions"},
@@ -570,7 +591,58 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
]})
),
},
"evaluate" if msg["arguments"]["expression"] == "&msg[0]" => ok!(
msg,
json!({"result": "0x1000 \"Hello\"", "type": "char *", "variablesReference": 1, "memoryReference": "0x1000"})
),
"evaluate" => ok!(msg, json!({"result": "42", "type": "int", "variablesReference": 0})),
"readMemory" => {
let args = &msg["arguments"];
let reference = args["memoryReference"].as_str().unwrap().trim_start_matches("0x");
let start = i64::from_str_radix(reference, 16).unwrap() + args["offset"].as_i64().unwrap_or(0);
let count = args["count"].as_i64().unwrap();
const END: i64 = 0x1010;
if start >= END {
send!(
json!({"type": "response", "request_seq": msg["seq"], "command": "readMemory", "success": false, "message": format!("Cannot access memory at address {start:#x}")})
);
} else {
let bytes: Vec<u8> = (start..(start + count).min(END)).map(|a| a as u8).collect();
ok!(
msg,
json!({"address": format!("{start:#x}"), "data": base64::engine::general_purpose::STANDARD.encode(&bytes), "unreadableBytes": count - bytes.len() as i64})
);
}
}
"disassemble" => {
let args = &msg["arguments"];
let reference = args["memoryReference"].as_str().unwrap().trim_start_matches("0x");
let pc = i64::from_str_radix(reference, 16).unwrap() + args["offset"].as_i64().unwrap_or(0);
let (offset, count) =
(args["instructionOffset"].as_i64().unwrap(), args["instructionCount"].as_i64().unwrap());
let insn = |a: i64| {
if (0x1000..0x1100).contains(&a) {
json!({"address": format!("{a:#x}"), "instruction": format!("insn {}", (a - 0x1000) / 4), "instructionBytes": "90909090"})
} else {
json!({"address": format!("{a:#x}"), "instruction": "", "presentationHint": "invalid"})
}
};
let addresses: Option<Vec<i64>> = match script.disassemble.unwrap() {
FakeDisassembler::Lldb => Some((0..count).map(|i| pc + 4 * (offset + i)).collect()),
FakeDisassembler::Gdb if offset + count < 0 => None,
FakeDisassembler::Gdb => {
let all: Vec<i64> = (0..offset + count).map(|i| pc + 4 * i).collect();
let from = if offset >= 0 { offset } else { (all.len() as i64 + offset).max(0) };
Some(all[from as usize..].to_vec())
}
};
match addresses {
Some(a) => ok!(msg, json!({"instructions": a.into_iter().map(insn).collect::<Vec<_>>()})),
None => send!(
json!({"type": "response", "request_seq": msg["seq"], "command": "disassemble", "success": false, "message": "Argument 'count' should be an non-negative integer."})
),
}
}
"completions" => ok!(
msg,
json!({"targets": [
@@ -1952,6 +2024,161 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
h.manager.stop(id).await.unwrap();
}
#[tokio::test]
async fn memory_view_reads_memory_from_a_reference() {
let h = harness(Script { read_memory: true, ..Script::default() });
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
assert_eq!(
h.request("initialize")["arguments"]["supportsMemoryReferences"],
true,
"adapters only send references when asked"
);
assert!(h.manager.capabilities(id).unwrap().read_memory);
let pointer = h.manager.evaluate_in(id, Some(10), "&msg[0]".into(), Some("watch".into())).await.unwrap();
assert_eq!(pointer.memory_reference.as_deref(), Some("0x1000"));
let plain = h.manager.evaluate(id, Some(10), "n".into()).await.unwrap();
assert_eq!(plain.memory_reference, None);
let block = h.manager.read_memory(id, "0x1000".into(), 0, 8).await.unwrap();
assert_eq!(block, MemoryBlock { address: "0x1000".into(), data: (0..8).collect(), unreadable_bytes: 0 });
assert_eq!(h.request("readMemory")["arguments"], json!({"memoryReference": "0x1000", "offset": 0, "count": 8}));
// Paging back and forth goes through `offset` on the same reference; the end of the mapping
// comes back as unreadable bytes.
let block = h.manager.read_memory(id, "0x1000".into(), 8, 16).await.unwrap();
assert_eq!((block.address.as_str(), block.data.len(), block.unreadable_bytes), ("0x1008", 8, 8));
assert_eq!(block.data[0], 0x08);
// Unmapped memory is the adapter's error, and the session goes on.
let err = h.manager.read_memory(id, "0x1000".into(), 0x20, 16).await.unwrap_err();
assert!(err.to_string().contains("Cannot access memory at address 0x1020"), "{err}");
assert!(!h.manager.threads(id).await.unwrap().is_empty());
let _ = h.manager.read_memory(id, "0x1000".into(), 0, u32::MAX).await;
let last = h.log.lock().iter().rev().find(|m| m["command"] == "readMemory").cloned().unwrap();
assert_eq!(last["arguments"]["count"], MAX_READ, "one read never asks for more than a few pages");
h.manager.stop(id).await.unwrap();
}
#[tokio::test]
async fn memory_view_says_when_the_adapter_cannot_read_memory() {
let h = harness(Script::default());
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
assert!(!h.manager.capabilities(id).unwrap().read_memory);
let err = h.manager.read_memory(id, "0x1000".into(), 0, 16).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
assert!(err.to_string().contains("debug adapter `debugpy` cannot read memory"), "{err}");
assert!(!h.commands().iter().any(|c| c == "readMemory"), "nothing is sent to an adapter without support");
h.manager.stop(id).await.unwrap();
}
#[test]
fn variables_keep_their_memory_reference() {
let v = variable_from(
&json!({"name": "words", "value": "0x4010", "variablesReference": 3, "memoryReference": "0x4010"}),
);
assert_eq!(v.memory_reference.as_deref(), Some("0x4010"));
assert_eq!(variable_from(&json!({"name": "n", "value": "1", "memoryReference": ""})).memory_reference, None);
let json = serde_json::to_value(variable_from(&json!({"name": "n", "value": "1"}))).unwrap();
assert!(json.get("memoryReference").is_none(), "absent, not null, for the UI's optional field");
}
#[tokio::test]
async fn disassembly_reads_instructions_around_the_instruction_pointer() {
let h = harness(Script { disassemble: Some(FakeDisassembler::Lldb), ..Script::default() });
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
let caps = h.manager.capabilities(id).unwrap();
assert!(caps.disassemble && caps.instruction_stepping);
let list = h.manager.disassemble(id, "0x1010".into(), 2, 5).await.unwrap();
let addresses: Vec<&str> = list.iter().map(|i| i.address.as_str()).collect();
assert_eq!(addresses, ["0x1008", "0x100c", "0x1010", "0x1014", "0x1018"]);
assert_eq!((list[2].instruction.as_str(), list[2].bytes.as_deref()), ("insn 4", Some("90909090")));
assert_eq!(
requests(&h, "disassemble")[0],
json!({"memoryReference": "0x1010", "offset": 0, "instructionOffset": -2, "instructionCount": 5, "resolveSymbols": true})
);
// Before the first mapped instruction the adapter pads; the padding is not shown.
let list = h.manager.disassemble(id, "0x1004".into(), 4, 6).await.unwrap();
let addresses: Vec<&str> = list.iter().map(|i| i.address.as_str()).collect();
assert_eq!(addresses, ["0x1000", "0x1004", "0x1008"]);
let _ = h.manager.disassemble(id, "0x1000".into(), 0, u32::MAX).await;
assert_eq!(requests(&h, "disassemble").last().unwrap()["instructionCount"], MAX_INSTRUCTIONS);
h.manager.stop(id).await.unwrap();
}
#[tokio::test]
async fn disassembly_starts_at_the_instruction_pointer_when_the_adapter_cannot_go_back() {
let h = harness(Script { disassemble: Some(FakeDisassembler::Gdb), ..Script::default() });
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
// GDB's answer to "4 before" leaves out the instruction pointer; the view asks again from it.
let list = h.manager.disassemble(id, "0x1010".into(), 4, 10).await.unwrap();
assert_eq!(list.first().map(|i| i.address.as_str()), Some("0x1010"));
assert_eq!(list.len(), 6);
let offsets: Vec<Value> = requests(&h, "disassemble").iter().map(|r| r["instructionOffset"].clone()).collect();
assert_eq!(offsets, [json!(-4), json!(0)]);
h.manager.stop(id).await.unwrap();
}
#[tokio::test]
async fn instruction_steps_send_the_granularity_and_line_steps_do_not() {
let h = harness(Script { disassemble: Some(FakeDisassembler::Lldb), ..Script::default() });
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
h.manager.step_instruction(id, 1, StepKind::Into).await.unwrap();
assert_eq!(requests(&h, "stepIn").last().unwrap(), &json!({"threadId": 1, "granularity": "instruction"}));
h.manager.step(id, 1, StepKind::Over).await.unwrap();
assert_eq!(requests(&h, "next").last().unwrap(), &json!({"threadId": 1}));
h.manager.stop(id).await.unwrap();
}
#[tokio::test]
async fn disassembly_and_instruction_steps_say_when_the_adapter_cannot() {
let h = harness(Script::default());
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
let caps = h.manager.capabilities(id).unwrap();
assert!(!caps.disassemble && !caps.instruction_stepping);
let err = h.manager.disassemble(id, "0x1000".into(), 0, 16).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
assert!(err.to_string().contains("debug adapter `debugpy` cannot disassemble"), "{err}");
let err = h.manager.step_instruction(id, 1, StepKind::Over).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
let sent = h.commands();
assert!(!sent.iter().any(|c| c == "disassemble" || c == "next"), "nothing is sent to an adapter without support");
h.manager.stop(id).await.unwrap();
}
#[test]
fn frames_keep_their_instruction_pointer() {
let f = frame_from(&json!({"id": 1, "name": "atoi", "line": 0, "instructionPointerReference": "0x7ffff7c4a2e0"}));
assert_eq!(f.instruction_pointer_reference.as_deref(), Some("0x7ffff7c4a2e0"));
let json = serde_json::to_value(frame_from(&json!({"id": 1, "name": "main"}))).unwrap();
assert!(json.get("instructionPointerReference").is_none());
}
#[test]
fn frames_drop_pseudo_paths_of_referenced_sources() {
let frame = |path: &str, reference: i64| {
frame_from(&json!({"id": 1, "name": "f", "line": 1,
"source": {"path": path, "sourceReference": reference}}))
.path
};
let lldb = "/usr/lib/swift/libswiftCore.dylib`swift_willThrow";
assert_eq!(frame(lldb, 1), None, "lldb-dap disassembly");
assert_eq!(frame(lldb, 0).as_deref(), Some(Path::new(lldb)), "no reference: kept as sent");
let here = env!("CARGO_MANIFEST_DIR");
assert_eq!(frame(here, 3).as_deref(), Some(Path::new(here)), "an existing file");
assert!(frame("jdt://contents/rt.jar/java.lang/String.class", 2).is_some(), "not a file path");
}
#[tokio::test]
async fn smart_step_into_and_reset_frame() {
let h = harness(Script::default());
@@ -3791,3 +4018,19 @@ async fn stop_detaches_from_an_attached_program() {
assert!(!h.commands().contains(&"terminate".to_owned()));
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
}
#[tokio::test]
async fn cell_breakpoints_go_only_to_their_notebooks_kernel_session() {
use crate::jvm_memory::test_support::bare_session_of;
use std::path::Path;
let (a, b) = ("vscode-notebook-cell:/p/a.ipynb#c1", "vscode-notebook-cell:/p/b.ipynb#c1");
let mut kernel = bare_session_of(crate::NOTEBOOK_ADAPTER, "attach");
std::sync::Arc::get_mut(&mut kernel.session).unwrap().notebook_cells =
Some("vscode-notebook-cell:/p/a.ipynb#".into());
let python = bare_session_of("debugpy", "launch");
assert!(kernel.session.takes(Path::new(a)));
assert!(!kernel.session.takes(Path::new(b)), "another notebook's cells");
assert!(kernel.session.takes(Path::new("/p/lib.py")), "files the cells may call");
assert!(!python.session.takes(Path::new(a)));
assert!(python.session.takes(Path::new("/p/lib.py")));
}
+75 -2
Переглянути файл
@@ -1,11 +1,12 @@
//! Drives real debug adapters against tiny programs (one per language), checking the
//! launch templates and the IDEA-parity features: line / method breakpoints, Smart Step
//! Into, Reset Frame, Force Step Over, Force Run to Cursor and Set Value.
//! Into, Reset Frame, Force Step Over, Force Run to Cursor, Set Value, the Memory View and the Disassembly view.
//!
//! Ignored by default (needs the adapters installed). Run with
//! `OPENIDEA_DAP_FIXTURES=<dir> cargo test -p ide-dap --test real_adapters -- --ignored --nocapture`
//! where `<dir>` holds `py/app.py`, `node/app.js`, `go/demo` (built with `-N -l`),
//! `rust/target/debug/demo` and `c/main`. Adapters not found on `PATH` are skipped.
//! `rust/target/debug/demo` and `c/main` (whose loop function also has a `char msg[]` local, for
//! the Memory View). Adapters not found on `PATH` are skipped.
use ide_core::event::DebugEvent;
use ide_core::{DebugSessionId, IdeEvent, SharedSink};
@@ -280,6 +281,78 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
let caps = m.capabilities(s).map_err(|e| e.message)?;
report.push(format!("capabilities: {caps:?}"));
// Memory View: the bytes at an address expression (the C fixture's `msg`), and an unmapped address.
if caps.read_memory {
match m.evaluate_in(s, Some(top.id), "&msg[0]".into(), Some("watch".into())).await {
Ok(v) => match v.memory_reference {
Some(r) => match m.read_memory(s, r.clone(), 0, 16).await {
Ok(b) => report.push(format!(
"memory view `&msg[0]` ({r}): {} = {:02x?} {:?}, {} unreadable",
b.address,
b.data,
String::from_utf8_lossy(&b.data),
b.unreadable_bytes
)),
Err(e) => report.push(format!("memory view `&msg[0]`: FAILED {}", e.message)),
},
None => report.push(format!("memory view `&msg[0]` = {}: no memory reference", v.value)),
},
Err(e) => report.push(format!("memory view `&msg[0]`: not evaluated ({})", e.message)),
}
match m.read_memory(s, "0x0".into(), 0, 16).await {
Ok(b) => report.push(format!("memory view 0x0: {} bytes, {} unreadable", b.data.len(), b.unreadable_bytes)),
Err(e) => report.push(format!("memory view 0x0: error `{}`", e.message)),
}
} else {
report.push("memory view: readMemory not supported".into());
}
// Disassembly: the instructions around the stop's instruction pointer, then two instruction steps,
// which stay on the loop line and inside the instructions shown.
let address = |a: &str| u128::from_str_radix(a.trim_start_matches("0x"), 16).ok();
match (caps.disassemble, top.instruction_pointer_reference.clone()) {
(true, Some(pc)) => match m.disassemble(s, pc.clone(), 8, 24).await {
Ok(list) => {
let shown = |a: &str| list.iter().position(|i| address(&i.address) == address(a));
match shown(&pc) {
Some(at) => report.push(format!(
"disassembly at {pc}: {} instructions, the instruction pointer is #{at}: `{}` ({:?})",
list.len(),
list[at].instruction,
list[at].bytes
)),
None => report.push(format!("disassembly at {pc}: FAILED, not among {list:?}")),
}
if caps.instruction_stepping {
let mut steps = vec![pc];
for _ in 0..2 {
let seen = run.seen();
m.step_instruction(s, thread, StepKind::Over).await.map_err(|e| e.message)?;
run.stopped_after(seen).await.ok_or("no stop after step over instruction")?;
let f = run.top(s, thread).await;
if f.line != case.loop_line {
report.push(format!(
"step over instruction: left the loop line for {}:{}",
f.name,
f.line + 1
));
}
steps.push(f.instruction_pointer_reference.unwrap_or_default());
}
let all = steps.iter().all(|a| shown(a).is_some());
report.push(format!("step over instruction: {} (all shown: {all})", steps.join(" -> ")));
} else {
report.push("instruction stepping: not supported".into());
}
}
Err(e) => report.push(format!("disassembly at {pc}: FAILED {}", e.message)),
},
(true, None) => report.push("disassembly: the top frame has no instruction pointer".into()),
(false, _) => report.push("disassembly: not supported".into()),
}
// Instruction steps resumed the thread: frame ids from before them may be gone.
let top = run.top(s, thread).await;
// Set Value on the first local that is an integer.
let scopes = m.scopes(s, top.id).await.map_err(|e| e.message)?;
for scope in scopes.iter().filter(|sc| !sc.expensive) {
+136 -12
Переглянути файл
@@ -287,19 +287,56 @@ impl ClickhousePool {
}
/// `max_rows`: the rows the server may send (the skipped ones included).
fn request(&self, client: &Client, query_id: &str, max_rows: usize, session: &Session) -> RequestBuilder {
fn request(
&self,
client: &Client,
query_id: &str,
max_rows: usize,
session: &Session,
workspace_bytes: Option<usize>,
) -> RequestBuilder {
let mut request = client
.post(self.0.endpoint.clone())
.basic_auth(&self.0.user, Some(&self.0.password))
.header(reqwest::header::CONTENT_TYPE, "text/plain; charset=utf-8")
.query(&self.0.settings)
.query(&[("query_id", query_id), ("default_format", FORMAT)]);
if workspace_bytes.is_some() && !session.strict_read_only {
let settings: Vec<_> = self
.0
.settings
.iter()
.filter(|(name, _)| !matches!(name.as_str(), "read_overflow_mode" | "timeout_overflow_mode"))
.collect();
request = request.query(&settings);
} else {
request = request.query(&self.0.settings);
}
if !session.strict_read_only {
request = request.query(&[
("output_format_json_quote_denormals", "1".into()),
("max_result_rows", max_rows.saturating_add(1).to_string()),
("result_overflow_mode", "break".into()),
]);
if let Some(bytes) = workspace_bytes {
request = request.query(&[
("max_result_rows", max_rows.to_string()),
("result_overflow_mode", "throw".into()),
("read_overflow_mode", "throw".into()),
("timeout_overflow_mode", "throw".into()),
]);
for (name, value) in [
("max_result_bytes", bytes),
("max_execution_time", 20),
("cancel_http_readonly_queries_on_client_close", 1),
("max_rows_to_read", 1_000_000),
("max_bytes_to_read", 268_435_456),
] {
if !self.0.settings.iter().any(|(setting, _)| setting == name) {
request = request.query(&[(name, value)]);
}
}
} else {
request = request.query(&[
("output_format_json_quote_denormals", "1".into()),
("max_result_rows", max_rows.saturating_add(1).to_string()),
("result_overflow_mode", "break".into()),
]);
}
}
if let Some(session_id) = &session.id {
request = request.query(&[("session_id", session_id.as_str()), ("session_timeout", "3600")]);
@@ -376,7 +413,8 @@ impl ClickhousePool {
));
}
let query_id = uuid::Uuid::new_v4().to_string();
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), session).body(sql.to_owned());
let request =
self.request(&client, &query_id, skip.saturating_add(max_rows), session, None).body(sql.to_owned());
let started = Instant::now();
let request_error = |error: reqwest::Error| {
if error.is_timeout() && !error.is_connect() {
@@ -402,7 +440,7 @@ impl ClickhousePool {
.and_then(|n| n.as_str().and_then(|n| n.parse::<u64>().ok()).or_else(|| n.as_u64()))
});
if !status.is_success() || exception_code.as_deref().is_some_and(|code| code != "0") {
let body = response.bytes().await.map_err(request_error)?;
let body = response_prefix(response).await.map_err(request_error)?;
return Err(self.server_error(status, exception_code.as_deref(), &body));
}
let (columns, rows, has_more) = if format.as_deref().is_some_and(|f| f != FORMAT) {
@@ -458,6 +496,66 @@ impl ClickhousePool {
}
}
/// Dedicated workspace sessions consume the response before any grid truncation or formatting.
pub(crate) async fn workspace_rows(
&self,
sql: &str,
max_rows: usize,
max_bytes: usize,
cancel: &CancellationToken,
mut consume: impl FnMut(&[u8]) -> IdeResult<()>,
) -> IdeResult<()> {
let mut slot = self.session(&self.0.session, cancel).await?;
let state = slot.as_mut().expect("session was initialized");
let mut stateless;
let session = if self.0.use_http_session {
state
} else {
stateless = state.clone();
drop(slot);
&mut stateless
};
let client = self.client()?;
let query_id = uuid::Uuid::new_v4().to_string();
let request = self.request(&client, &query_id, max_rows, session, Some(max_bytes)).body(sql.to_owned());
let fetch = async {
let mut response = request.send().await.map_err(http_error)?;
let status = response.status();
let metadata = |name: &str| response.headers().get(name).and_then(|v| v.to_str().ok());
let code = metadata("X-ClickHouse-Exception-Code").map(str::to_owned);
if !status.is_success() || code.as_deref().is_some_and(|code| code != "0") {
let body = response_prefix(response).await.map_err(http_error)?;
return Err(self.server_error(status, code.as_deref(), &body));
}
if metadata("X-ClickHouse-Format").is_some_and(|format| format != FORMAT) {
return Err(IdeError::invalid("ClickHouse did not return the workspace response format"));
}
let mut received = 0;
while let Some(chunk) = response.chunk().await.map_err(http_error)? {
received += chunk.len();
if received > max_bytes {
return Err(IdeError::invalid("Workspace input exceeds the source byte limit"));
}
consume(&chunk)?;
}
Ok(())
};
let result = tokio::select! {
biased;
() = cancel.cancelled() => Err(IdeError::cancelled()),
() = self.0.closed.cancelled() => Err(IdeError::cancelled()),
() = tokio::time::sleep(Duration::from_secs(25)) =>
Err(IdeError::new(ErrorKind::TimedOut, "Workspace ClickHouse source read timed out")),
result = fetch => result,
};
if result.is_ok() {
session.initialized = true;
} else {
let _ = self.kill(&client, &query_id, session).await;
}
result.map_err(|e| self.redact_error(e))
}
async fn kill(&self, client: &Client, query_id: &str, session: &Session) -> IdeResult<()> {
let mut request = client
.post(self.0.endpoint.clone())
@@ -474,7 +572,7 @@ impl ClickhousePool {
.get("X-ClickHouse-Exception-Code")
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let body = response.bytes().await.map_err(http_error)?;
let body = response_prefix(response).await.map_err(http_error)?;
if status.is_success() && !code.as_deref().is_some_and(|code| code != "0") && !body.starts_with(b"Code:") {
Ok(())
} else {
@@ -503,6 +601,17 @@ impl ClickhousePool {
}
}
async fn response_prefix(mut response: reqwest::Response) -> Result<Vec<u8>, reqwest::Error> {
const LIMIT: usize = 16_384;
let mut body = Vec::new();
while body.len() < LIMIT {
let Some(chunk) = response.chunk().await? else { break };
let remaining = LIMIT - body.len();
body.extend_from_slice(&chunk[..chunk.len().min(remaining)]);
}
Ok(body)
}
type DecodedResult = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, bool);
/// Decodes a streamed [`FORMAT`] body. Reads past the first `skip` rows unparsed (a later
@@ -1448,6 +1557,15 @@ mod tests {
#[tokio::test]
async fn stateless_queries_do_not_wait_for_a_shared_session() {
assert_stateless_requests_overlap(false).await;
}
#[tokio::test]
async fn stateless_workspace_reads_do_not_block_queries() {
assert_stateless_requests_overlap(true).await;
}
async fn assert_stateless_requests_overlap(workspace: bool) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let (started, received) = tokio::sync::oneshot::channel();
@@ -1465,9 +1583,15 @@ mod tests {
(first_request, second_request)
});
let source = DataSource { properties: vec![property("use_http_session", "false")], ..source(port) };
let pool = Pool::connect(&source, None, None).await.unwrap();
let Pool::Clickhouse(pool) = Pool::connect(&source, None, None).await.unwrap() else { unreachable!() };
let cancel = CancellationToken::new();
let first = pool.execute("SELECT 1", 1, &cancel);
let first = async {
if workspace {
pool.workspace_rows("SELECT 1", 1, 1024, &cancel, |_| Ok(())).await
} else {
pool.execute("SELECT 1", 1, &cancel).await.map(drop)
}
};
let second = async {
received.await.unwrap();
pool.execute("SELECT 2", 1, &cancel).await
+65
Переглянути файл
@@ -1330,6 +1330,71 @@ impl Pool {
Ok(conn.finish_read_only(owned, result).await?.1)
}
pub(crate) async fn read_workspace_postgres(
&self,
request: &crate::workspace_input::WorkspaceInputRequest,
selection: Option<&[&str]>,
cancel: &CancellationToken,
) -> IdeResult<crate::workspace_input::WorkspaceInput> {
let Pool::Postgres(pool) = self else {
return Err(IdeError::internal("Expected a PostgreSQL workspace connection"));
};
let mut conn = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
result = pool.get() => result?,
};
let mut backend = None;
let read = async {
if conn.options.read_only == PgReadOnly::Transaction {
conn.start_read_only().await?;
} else {
sqlx::raw_sql("BEGIN READ ONLY").execute(&mut **conn).await.map_err(db_err)?;
}
let row = sqlx::raw_sql(
"SELECT pg_catalog.pg_backend_pid(), pg_catalog.current_setting('transaction_read_only') = 'on'",
)
.fetch_one(&mut **conn)
.await
.map_err(db_err)?;
backend = Some(row.try_get::<i32, _>(0).map_err(db_err)?);
if !row.try_get::<bool, _>(1).map_err(db_err)? {
return Err(IdeError::new(
ErrorKind::PermissionDenied,
"Workspace PostgreSQL transaction is not read-only",
));
}
crate::workspace_input::read_postgres(&mut conn, request, selection).await
};
let result = tokio::select! {
biased;
() = cancel.cancelled() => Err(IdeError::cancelled()),
() = tokio::time::sleep(Duration::from_secs(30)) =>
Err(IdeError::new(ErrorKind::TimedOut, "Workspace PostgreSQL source read timed out")),
result = read => result,
};
if result.is_ok() {
// Do not send a PID-based cancel once a pooler may have released this backend.
let rollback =
tokio::time::timeout(Duration::from_secs(3), sqlx::raw_sql("ROLLBACK").execute(&mut **conn)).await;
if matches!(rollback, Ok(Ok(_))) {
conn.in_transaction = false;
} else {
conn.conn.take();
}
} else {
if let Some(pid) = backend {
let _ = tokio::time::timeout(
Duration::from_secs(3),
self.cancel_query(format!("SELECT pg_catalog.pg_cancel_backend({pid})")),
)
.await;
}
conn.conn.take();
}
result
}
/// Runs one statement and keeps at most `max_rows` rows. Cancelling stops
/// the statement on the server (PostgreSQL, MySQL) and drops the connection.
pub async fn execute(&self, sql: &str, max_rows: usize, cancel: &CancellationToken) -> IdeResult<QueryResult> {
+103
Переглянути файл
@@ -0,0 +1,103 @@
use super::{DbJdbcDriver, JdbcPool};
use crate::source::{DUCKDB_URL, duck_lake_path};
use crate::{DataSource, DbDuckLake, DbDuckLakeKind, DbManager, Pool};
use ide_core::{IdeError, IdeResult};
const DUCKDB_CLASS: &str = "org.duckdb.DuckDBDriver";
impl DbManager {
pub fn approve_ducklake_source(&self, source: &DataSource) -> IdeResult<()> {
if source.duck_lake.is_none() {
return Err(IdeError::invalid("Expected a DuckLake data source"));
}
source.validate_duck_lake()?;
self.duck_lake_driver(&source.jdbc_driver)?.validate()?;
if source.global {
return Ok(());
}
self.record_jdbc_approval(source)
}
fn duck_lake_driver(&self, id: &str) -> IdeResult<DbJdbcDriver> {
let driver = self.jdbc_driver_by_id(id)?;
driver.require_vendor("duckdb")?;
if driver.class_name != DUCKDB_CLASS {
return Err(IdeError::invalid("Select a DuckDB driver profile with the official DuckDB JDBC driver class"));
}
Ok(driver)
}
/// Creates a lake in a new directory through a separate, disposable JDBC session.
pub async fn create_ducklake(&self, jdbc_driver: &str, directory: &str) -> IdeResult<()> {
duck_lake_path(directory, false)?;
let driver = self.duck_lake_driver(jdbc_driver)?;
let fields = duck_lake_fields("create", directory.to_owned(), "");
let pool = JdbcPool::open(driver, self.jdbc_registry()?.with_file_name("jdbc"), fields).await?;
pool.close().await;
Ok(())
}
pub(super) async fn open_ducklake(&self, source: &DataSource, lake: &DbDuckLake, testing: bool) -> IdeResult<Pool> {
source.validate_duck_lake()?;
self.check_jdbc_project_approval(source, testing)?;
let driver = self.duck_lake_driver(&source.jdbc_driver)?;
let cache = self.jdbc_registry()?.with_file_name("jdbc");
let (mode, value) = match lake.kind {
DbDuckLakeKind::Secret => ("secret", lake.value.clone()),
DbDuckLakeKind::File => {
let path = self.root.join(&lake.value);
let value = path.to_str().ok_or_else(|| IdeError::invalid("Invalid DuckLake catalog file path"))?;
duck_lake_path(value, false)?;
("file", value.to_owned())
}
};
let fields = duck_lake_fields(mode, value, lake.data_path.as_deref().unwrap_or_default());
JdbcPool::open(driver, cache, fields).await.map(Box::new).map(Pool::Jdbc)
}
}
fn duck_lake_fields(mode: &str, value: String, data_path: &str) -> Vec<String> {
vec![
"openDuckLake".into(),
DUCKDB_CLASS.into(),
DUCKDB_URL.into(),
String::new(),
String::new(),
(mode != "create").to_string(),
mode.into(),
value,
data_path.to_owned(),
]
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn ordinary_jdbc_rejects_a_ducklake_even_with_a_file_url() {
let source = DataSource {
driver: crate::DbDriver::Jdbc,
url: "jdbc:duckdb:existing.duckdb".into(),
duck_lake: Some(DbDuckLake {
kind: DbDuckLakeKind::File,
value: "catalog.ducklake".into(),
data_path: None,
}),
..Default::default()
};
let driver = DbJdbcDriver {
id: "duckdb".into(),
name: "DuckDB".into(),
vendor: Some("duckdb".into()),
jars: vec![],
class_name: DUCKDB_CLASS.into(),
url_template: DUCKDB_URL.into(),
};
let error = JdbcPool::connect(&source, None, driver, Default::default())
.await
.err()
.expect("ordinary JDBC must reject DuckLake fields before opening a connection");
assert_eq!(error.message, "DuckLake catalogs require a DuckLake connection");
}
}
+141 -26
Переглянути файл
@@ -15,6 +15,7 @@ use tokio::sync::Mutex;
use tokio::time::timeout;
mod bridge;
mod ducklake;
use bridge::Bridge;
@@ -79,6 +80,13 @@ pub fn jdbc_driver_classes(jars: &[String]) -> IdeResult<Vec<String>> {
}
impl DbJdbcDriver {
fn require_vendor(&self, vendor: &str) -> IdeResult<()> {
if self.vendor.as_deref() != Some(vendor) {
return Err(IdeError::invalid("The JDBC driver profile is not associated with this data source type"));
}
Ok(())
}
fn validate(&self) -> IdeResult<()> {
if self.id.is_empty()
|| self.name.trim().is_empty()
@@ -138,6 +146,30 @@ impl DbManager {
self.update_jdbc_driver(id, None)
}
fn record_jdbc_approval(&self, source: &DataSource) -> IdeResult<()> {
let (path, fingerprint) = self.jdbc_approval(source)?;
persist_local(&path, fingerprint.as_bytes())
}
fn jdbc_driver_by_id(&self, id: &str) -> IdeResult<DbJdbcDriver> {
self.jdbc_drivers()?
.into_iter()
.find(|d| d.id == id)
.ok_or_else(|| IdeError::invalid("Select an installed JDBC driver profile"))
}
fn check_jdbc_project_approval(&self, source: &DataSource, testing: bool) -> IdeResult<()> {
if !testing && !source.global {
let (path, expected) = self.jdbc_approval(source)?;
if std::fs::read_to_string(path).ok().as_deref() != Some(&expected) {
return Err(IdeError::invalid(
"Review this project's JDBC URL and properties, then save the data source before connecting",
));
}
}
Ok(())
}
fn jdbc_approval(&self, source: &DataSource) -> IdeResult<(PathBuf, String)> {
let registry = self.jdbc_registry()?;
let key = serde_json::to_vec(&(&self.root, &source.id)).map_err(|e| IdeError::internal(e.to_string()))?;
@@ -150,7 +182,10 @@ impl DbManager {
&source.options,
))
.map_err(|e| IdeError::internal(e.to_string()))?;
if self.jdbc_password_isolated(source) {
if let Some(lake) = &source.duck_lake {
settings.extend_from_slice(b"\0ducklake\0");
serde_json::to_writer(&mut settings, lake).map_err(|e| IdeError::internal(e.to_string()))?;
} else if self.jdbc_password_isolated(source) {
settings.extend_from_slice(b"\0jdbc-password");
}
Ok((
@@ -164,8 +199,70 @@ impl DbManager {
if source.driver != crate::DbDriver::Jdbc || source.plugin_owner.is_some() {
return Err(IdeError::invalid("Expected a user-managed JDBC data source"));
}
let (path, fingerprint) = self.jdbc_approval(source)?;
persist_local(&path, fingerprint.as_bytes())
if source.duck_lake.is_some() {
return self.approve_ducklake_source(source);
}
self.record_jdbc_approval(source)
}
/// A workspace uses only the selected host driver and a fresh in-memory database.
pub(crate) async fn workspace_engine(&self, profile: &str) -> IdeResult<JdbcPool> {
let driver = self
.jdbc_drivers()?
.into_iter()
.find(|driver| {
driver.id == profile
&& driver.vendor.as_deref() == Some("duckdb")
&& driver.class_name == "org.duckdb.DuckDBDriver"
})
.ok_or_else(|| IdeError::invalid("Choose an installed DuckDB JDBC driver for the workspace"))?;
let source = DataSource { url: "jdbc:duckdb:".into(), ..Default::default() };
JdbcPool::connect(&source, None, driver, self.jdbc_registry()?.with_file_name("jdbc")).await
}
pub(crate) async fn prepare_workspace_duckdb_source(
&self,
source: &DataSource,
) -> IdeResult<WorkspaceDuckDbSource> {
let driver = self.approved_jdbc_driver(source, false)?;
if driver.vendor.as_deref() != Some("duckdb") || driver.class_name != "org.duckdb.DuckDBDriver" {
return Err(IdeError::invalid("Choose a saved DuckDB source with an installed DuckDB driver"));
}
let target = source.url.strip_prefix("jdbc:duckdb:").unwrap_or_default();
let mut parts = target.split(';');
let filename = parts.next().unwrap_or_default();
let cache = self.jdbc_registry()?.with_file_name("jdbc");
let path = cache.join("files").join(filename);
if filename.is_empty()
|| filename.starts_with([':', ' '])
|| filename.starts_with("memory:")
|| filename.starts_with("md:")
|| filename.contains("://")
|| !tokio::fs::metadata(path).await.is_ok_and(|m| m.is_file())
{
return Err(IdeError::invalid("Choose an existing local DuckDB database file as the workspace source"));
}
let limits = [
("enable_external_access", "false"),
("allow_unsigned_extensions", "false"),
("autoinstall_known_extensions", "false"),
("autoload_known_extensions", "false"),
("memory_limit", "96MiB"),
("threads", "1"),
("temp_directory", ""),
("max_temp_directory_size", "0B"),
];
let protected = |name: &str| limits.iter().any(|(key, _)| name.trim().eq_ignore_ascii_case(key));
if parts.any(|option| protected(option.split('=').next().unwrap_or_default())) {
return Err(IdeError::invalid("DuckDB Workspace source URL changes a workspace read limit"));
}
let mut target = source.clone();
target.read_only = true;
target.properties.retain(|property| !protected(&property.name));
target
.properties
.extend(limits.map(|(name, value)| crate::DbProperty { name: name.into(), value: value.into() }));
Ok(WorkspaceDuckDbSource { target, driver, cache })
}
pub(crate) async fn open_pool(
@@ -174,33 +271,42 @@ impl DbManager {
password: Option<&str>,
testing: bool,
) -> IdeResult<crate::Pool> {
if let Some(lake) = &source.duck_lake {
return self.open_ducklake(source, lake, testing).await;
}
if source.driver != crate::DbDriver::Jdbc {
return crate::Pool::connect(source, password, Some(&self.root)).await;
}
if source.plugin_owner.is_some() {
return Err(IdeError::invalid("Plugins cannot start custom JDBC drivers"));
}
if !testing && !source.global {
let (path, expected) = self.jdbc_approval(source)?;
if std::fs::read_to_string(path).ok().as_deref() != Some(&expected) {
return Err(IdeError::invalid(
"Review this project's JDBC URL and properties, then save the data source before connecting",
));
}
}
let driver = self
.jdbc_drivers()?
.into_iter()
.find(|d| d.id == source.jdbc_driver)
.ok_or_else(|| IdeError::invalid("Select an installed JDBC driver profile"))?;
if !source.vendor.is_empty() && driver.vendor.as_deref() != Some(source.vendor.as_str()) {
return Err(IdeError::invalid("The JDBC driver profile is not associated with this data source type"));
}
let driver = self.approved_jdbc_driver(source, testing)?;
JdbcPool::connect(source, password, driver, self.jdbc_registry()?.with_file_name("jdbc"))
.await
.map(Box::new)
.map(crate::Pool::Jdbc)
}
fn approved_jdbc_driver(&self, source: &DataSource, testing: bool) -> IdeResult<DbJdbcDriver> {
if source.plugin_owner.is_some() {
return Err(IdeError::invalid("Plugins cannot start custom JDBC drivers"));
}
self.check_jdbc_project_approval(source, testing)?;
let driver = self.jdbc_driver_by_id(&source.jdbc_driver)?;
if !source.vendor.is_empty() {
driver.require_vendor(&source.vendor)?;
}
Ok(driver)
}
}
pub(crate) struct WorkspaceDuckDbSource {
target: DataSource,
driver: DbJdbcDriver,
cache: PathBuf,
}
impl WorkspaceDuckDbSource {
pub(crate) async fn connect(self, password: Option<&str>) -> IdeResult<JdbcPool> {
JdbcPool::connect(&self.target, password, self.driver, self.cache).await
}
}
struct Session {
@@ -277,10 +383,12 @@ impl JdbcPool {
driver: DbJdbcDriver,
cache: PathBuf,
) -> IdeResult<Self> {
driver.validate()?;
if source.duck_lake.is_some() {
return Err(IdeError::invalid("DuckLake catalogs require a DuckLake connection"));
}
let mut fields = vec![
"open".to_string(),
driver.class_name,
driver.class_name.clone(),
source.url.clone(),
source.user.clone(),
password.unwrap_or_default().to_owned(),
@@ -292,6 +400,11 @@ impl JdbcPool {
}
fields.extend([p.name.clone(), p.value.clone()]);
}
Self::open(driver, cache, fields).await
}
async fn open(driver: DbJdbcDriver, cache: PathBuf, fields: Vec<String>) -> IdeResult<Self> {
driver.validate()?;
let bridge = tokio::task::spawn_blocking(move || Bridge::start(&cache, &driver.jars))
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
@@ -306,7 +419,7 @@ impl JdbcPool {
bridge: Arc::new(bridge),
service: Session::new(0),
consoles: Default::default(),
shared_connection: private_database_url(&source.url),
shared_connection: private_database_url(&fields[2]),
version: metadata.next().flatten().unwrap_or_else(|| "Connected".into()),
identifier_quote: metadata.next().flatten().unwrap_or_default().trim().into(),
})
@@ -748,7 +861,9 @@ mod tests {
assert!(catalogs.contains(&vec![Some("memory".into()), Some("1".into())]));
assert!(catalogs.contains(&vec![Some("first".into()), Some("0".into())]));
assert!(catalogs.contains(&vec![Some(archive.into()), Some("0".into())]));
let schemas = pool.metadata(&["schemas", archive]).await?;
let mut schemas = pool.metadata(&["schemas", archive]).await?;
// DuckDB JDBC 1.1.3 also lists these system schemas for attached catalogs.
schemas.retain(|row| !matches!(row[0].as_deref(), Some("information_schema" | "pg_catalog")));
assert_eq!(schemas, ["main", "qaSimilar", "qa_%"].map(|schema| vec![Some(schema.into())]));
let tables = pool.metadata(&["tables", "qa_%", archive]).await?;
assert_eq!(tables.len(), 1);
+114 -14
Переглянути файл
@@ -25,14 +25,17 @@ pub mod sql;
pub mod tools;
mod watch;
pub use watch::SourcesWatch;
pub mod workspace;
pub mod workspace_input;
pub use catalog::{CatalogDatabase, CatalogSchema, SourceCatalog};
pub use conn::{Held, Pool, QueryResult, ResultColumn, TruncatedCell};
pub use history::HistoryEntry;
pub use plan::{PlanNode, PlanProperty};
pub use source::{
DataSource, DbColor, DbDriver, DbExternalTunnel, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection,
DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
DataSource, DbColor, DbDriver, DbDuckLake, DbDuckLakeKind, DbExternalTunnel, DbIntrospection, DbOptions,
DbProperty, DbSchemaSelection, DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode,
DbVisibilityChange,
};
pub use sql::{CellValue, DbRowEdit, SortKey};
@@ -201,7 +204,7 @@ impl DbKeyKind {
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbTableDetails")]
pub struct TableDetails {
@@ -213,6 +216,53 @@ pub struct TableDetails {
pub indexes: Vec<IndexInfo>,
pub foreign_keys: Vec<ForeignKey>,
pub triggers: Vec<TriggerInfo>,
/// The role owning the table (PostgreSQL); `None` where the schema owns its tables.
#[serde(default)]
#[specta(optional)]
pub owner: Option<String>,
/// The table's tablespace, the database's default one when it names none (PostgreSQL).
#[serde(default)]
#[specta(optional)]
pub tablespace: Option<String>,
/// The table access method (PostgreSQL's `heap`, …); `None` for a partitioned table, and on
/// the engines without one.
#[serde(default)]
#[specta(optional)]
pub access_method: Option<String>,
/// The storage parameters set on the table, as `(name, value)`: PostgreSQL's reloptions,
/// its TOAST table's prefixed `toast.`. `None` on the engines without any.
#[serde(default)]
#[specta(optional)]
pub storage_options: Option<Vec<(String, String)>>,
/// The partition key (`RANGE (created)`); `None` when the table isn't partitioned.
#[serde(default)]
#[specta(optional)]
pub partitioning: Option<String>,
/// Whether the table is logged, unlogged or temporary (PostgreSQL).
#[serde(default)]
#[specta(optional)]
pub persistence: Option<DbPersistence>,
}
/// Whether a table's changes are written to the write-ahead log, and whether it outlives the session.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum DbPersistence {
Permanent,
Unlogged,
Temporary,
}
impl DbPersistence {
/// PostgreSQL's `pg_class.relpersistence`.
fn from_catalog(v: &str) -> Option<Self> {
match v {
"p" => Some(Self::Permanent),
"u" => Some(Self::Unlogged),
"t" => Some(Self::Temporary),
_ => None,
}
}
}
/// One object privilege on a table: `grantee` may run `privilege` (`SELECT`, …), granted
@@ -330,6 +380,7 @@ pub struct DbManager {
sessions: Mutex<HashMap<String, Session>>,
/// Result pages read on from where the previous page stopped, not by running the statement again.
cursors: conn::Cursors,
workspace_run: tokio::sync::Mutex<()>,
/// The data sources as last read from disk, for [`DbManager::reconcile_sources`]
/// (`None` until [`DbManager::watch_sources`]).
on_disk: Mutex<Option<Vec<DataSource>>>,
@@ -379,6 +430,25 @@ async fn catalog_rows(pool: &Pool, q: &str) -> IdeResult<Vec<Vec<Option<String>>
}
}
/// One [`sql::table_properties`] row into `details`.
fn read_table_properties(details: &mut TableDetails, row: Vec<Option<String>>) {
let mut it = row.into_iter().map(|v| v.filter(|v| !v.is_empty()));
let mut next = || it.next().flatten();
details.owner = next();
details.tablespace = next();
details.access_method = next();
details.storage_options = Some(
next()
.unwrap_or_default()
.lines()
.filter_map(|o| o.split_once('='))
.map(|(name, value)| (name.to_owned(), value.to_owned()))
.collect(),
);
details.partitioning = next();
details.persistence = next().as_deref().and_then(DbPersistence::from_catalog);
}
fn flag(v: &Option<String>) -> bool {
matches!(v.as_deref(), Some("1" | "t" | "true" | "YES"))
}
@@ -478,6 +548,13 @@ pub fn split_target(target: &str) -> (&str, Option<&str>) {
}
}
fn reject_duck_lake_password(password: Option<&str>) -> IdeResult<()> {
if password.is_some_and(|p| !p.is_empty()) {
return Err(IdeError::invalid("DuckLake uses a catalog file or named secret without a JDBC or SSH password"));
}
Ok(())
}
/// Says which leg failed when the database is unreachable from the SSH host.
fn through_tunnel(e: IdeError, source: &DataSource, via: Option<&str>) -> IdeError {
let Some(via) = via.filter(|_| e.kind == ErrorKind::Io) else { return e };
@@ -548,6 +625,7 @@ impl DbManager {
on_disk: Mutex::default(),
sessions: Mutex::default(),
cursors: conn::Cursors::default(),
workspace_run: tokio::sync::Mutex::new(()),
}
}
@@ -631,13 +709,16 @@ impl DbManager {
/// Saves the data source list, preserving connections when only visibility rules change.
/// Global ones (`global`) go to the app-wide list, the others to the project's.
pub async fn save_sources(&self, mut sources: Vec<DataSource>) -> IdeResult<()> {
for source in &sources {
source.validate_duck_lake()?;
}
if sources.iter().any(|s| s.global && s.plugin_owner.is_some()) {
return Err(IdeError::invalid("plugin-owned data sources must stay project-scoped"));
}
let old = {
let _guard = plugin::EDIT.lock();
let old = self.sources().unwrap_or_default();
for source in sources.iter_mut().filter(|s| s.driver == DbDriver::Jdbc) {
for source in sources.iter_mut().filter(|s| s.driver == DbDriver::Jdbc && s.duck_lake.is_none()) {
// Retain the credential scope even when URL-only settings supplied the old authenticator.
if let Some(settings) = old.iter().find(|s| s.id == source.id).and_then(Self::non_password_snowflake) {
source.snowflake = Some(settings);
@@ -686,7 +767,7 @@ impl DbManager {
}
}
// Made global or project-level: its saved passwords move along.
Some(n) if n.global != o.global => {
Some(n) if n.global != o.global && n.duck_lake.is_none() && o.duck_lake.is_none() => {
for k in &keys {
if let Some(p) = self.store_of(&o).get(k) {
self.store_of(n).set(k, &p)?;
@@ -768,6 +849,9 @@ impl DbManager {
/// the data source saves passwords (`None` forgets it).
pub async fn set_password(&self, id: &str, password: Option<String>, save: bool) -> IdeResult<()> {
let source = self.sources()?.into_iter().find(|s| s.id == id);
if source.as_ref().is_some_and(|s| s.duck_lake.is_some()) {
return reject_duck_lake_password(password.as_deref());
}
let (store, key) = match source.as_ref() {
Some(source) => (self.store_of(source), self.password_key(source)),
None => (&self.saved_passwords, id.to_owned()),
@@ -778,7 +862,11 @@ impl DbManager {
/// [`DbManager::set_password`] for the SSH password / key passphrase.
/// A data source using an SSH configuration sets that configuration's secret.
pub async fn set_ssh_secret(&self, id: &str, secret: Option<String>, save: bool) -> IdeResult<()> {
let config = self.sources()?.into_iter().find(|s| s.id == id).and_then(|s| s.ssh).map(|s| s.config);
let source = self.sources()?.into_iter().find(|s| s.id == id);
if source.as_ref().is_some_and(|s| s.duck_lake.is_some()) {
return reject_duck_lake_password(secret.as_deref());
}
let config = source.and_then(|s| s.ssh).map(|s| s.config);
if let Some(c) = config.filter(|c| !c.trim().is_empty()) {
let save = self.ssh.config(&c).map(|c| c.save_secret).unwrap_or(save);
return self.ssh.set_secret(&c, secret, save);
@@ -823,6 +911,9 @@ impl DbManager {
}
async fn password(&self, source: &DataSource) -> Option<String> {
if source.duck_lake.is_some() {
return None;
}
match self
.secret(source, self.password_key(source), source.driver != DbDriver::Sqlite && source.save_password)
.await
@@ -931,6 +1022,10 @@ impl DbManager {
purpose: route::RouteUse,
) -> IdeResult<String> {
let source = &source.resolved()?;
if source.duck_lake.is_some() {
reject_duck_lake_password(password.as_deref())?;
reject_duck_lake_password(ssh_secret.as_deref())?;
}
let password = match password {
Some(p) => Some(p),
None => self.password(source).await,
@@ -1287,13 +1382,7 @@ impl DbManager {
})
.collect();
if driver == DbDriver::Jdbc {
return Ok(TableDetails {
comment: None,
columns,
indexes: vec![],
foreign_keys: vec![],
triggers: vec![],
});
return Ok(TableDetails { columns, ..Default::default() });
}
let mut indexes: Vec<IndexInfo> = Vec::new();
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
@@ -1360,7 +1449,18 @@ impl DbManager {
),
None => None,
};
Ok(TableDetails { comment, columns, indexes, foreign_keys, triggers })
let mut details = TableDetails { comment, columns, indexes, foreign_keys, triggers, ..Default::default() };
if let Some(q) = sql::table_properties(driver, schema, table) {
match catalog_rows(pool, &q).await {
Ok(rows) => {
if let Some(row) = rows.into_iter().next() {
read_table_properties(&mut details, row);
}
}
Err(e) => tracing::warn!("table properties: {}", e.message),
}
}
Ok(details)
}
/// The object privileges granted on `table`; empty, without a query, on the engines
+1 -1
Переглянути файл
@@ -154,7 +154,7 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
.and_then(|r| r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned)),
Err(_) => None,
};
Ok(TableDetails { comment, columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
Ok(TableDetails { comment, columns, foreign_keys, ..Default::default() })
}
fn foreign_keys(shown: &Shown) -> Vec<ForeignKey> {
+86
Переглянути файл
@@ -11,6 +11,7 @@ use std::collections::{BTreeMap, HashSet};
use std::path::Path;
pub(crate) const FILE: &str = "data-sources.toml";
pub(crate) const DUCKDB_URL: &str = "jdbc:duckdb:";
pub(crate) const FOLDERS_FILE: &str = "data-source-folders.toml";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
@@ -306,6 +307,25 @@ pub struct DbExternalTunnel {
pub arguments: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum DbDuckLakeKind {
File,
Secret,
}
/// How to open an existing DuckLake catalog read-only through DuckDB.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DbDuckLake {
pub kind: DbDuckLakeKind,
/// A local catalog file or an existing DuckDB secret name.
pub value: String,
/// An existing local data directory overriding the catalog's data path.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub data_path: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct DataSource {
@@ -346,6 +366,8 @@ pub struct DataSource {
pub properties: Vec<DbProperty>,
/// Snowflake settings (`None`: not a Snowflake data source, or all defaults).
pub snowflake: Option<DbSnowflake>,
#[serde(skip_serializing_if = "Option::is_none")]
pub duck_lake: Option<DbDuckLake>,
/// Stored app-wide and listed in every project. Implied by the file it is read from,
/// so not written to it.
pub global: bool,
@@ -386,6 +408,7 @@ impl Default for DataSource {
introspection: DbIntrospection::default(),
properties: Vec::new(),
snowflake: None,
duck_lake: None,
global: false,
plugin_owner: None,
plugin_source_id: None,
@@ -513,7 +536,69 @@ pub fn parse_url(raw: &str) -> IdeResult<ParsedUrl> {
Ok(parsed)
}
pub(crate) fn duck_lake_path(value: &str, relative: bool) -> IdeResult<&Path> {
let path = Path::new(value);
if value.trim().is_empty()
|| value.contains(['\0', '\r', '\n'])
|| value.starts_with("//")
|| value.starts_with('\\')
|| (!path.is_absolute() && (!relative || value.starts_with('/') || value.contains(':')))
{
return Err(IdeError::invalid("Choose a local DuckLake path on the database host"));
}
Ok(path)
}
impl DataSource {
pub(crate) fn validate_duck_lake(&self) -> IdeResult<()> {
let Some(lake) = &self.duck_lake else { return Ok(()) };
if self.driver != DbDriver::Jdbc
|| self.vendor != "duckdb"
|| self.url != DUCKDB_URL
|| self.url_only
|| !self.read_only
|| self.plugin_owner.is_some()
{
return Err(IdeError::invalid("Existing DuckLake catalogs require a read-only DuckDB JDBC data source"));
}
if !self.user.is_empty()
|| self.save_password
|| self.ssh.is_some()
|| self.external_tunnel.is_some()
|| !self.properties.is_empty()
{
return Err(IdeError::invalid(
"DuckLake uses its catalog file or named secret without JDBC credentials, properties or tunnels",
));
}
if self.options.transaction != DbTxMode::Auto
|| !self.options.default_schema.is_empty()
|| !self.options.time_zone.is_empty()
|| !self.options.startup_script.is_empty()
{
return Err(IdeError::invalid("DuckLake does not use JDBC session overrides"));
}
match lake.kind {
DbDuckLakeKind::File => {
duck_lake_path(&lake.value, true)?;
}
DbDuckLakeKind::Secret => {
let mut chars = lake.value.bytes();
if !chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == b'_')
|| !chars.all(|c| c.is_ascii_alphanumeric() || c == b'_')
{
return Err(IdeError::invalid(
"Enter an existing DuckLake secret name using letters, digits or underscores",
));
}
}
}
if let Some(path) = lake.data_path.as_deref().filter(|path| !path.is_empty()) {
duck_lake_path(path, false)?;
}
Ok(())
}
pub(crate) fn select_database(&mut self, database: Option<&str>) {
if let Some(db) = database {
// The configured schema belongs to the configured database.
@@ -536,6 +621,7 @@ impl DataSource {
/// database, user, SSL and driver properties come from the URL (properties
/// of the Advanced tab still apply after the URL's).
pub fn resolved(&self) -> IdeResult<DataSource> {
self.validate_duck_lake()?;
if self.driver == DbDriver::Jdbc {
if !self.url.starts_with("jdbc:") {
return Err(IdeError::invalid("Enter a JDBC URL starting with jdbc:"));
+31 -1
Переглянути файл
@@ -236,6 +236,29 @@ pub fn table_comment(driver: DbDriver, schema: &str, table: &str) -> Option<Stri
}
}
/// One row: `owner, tablespace, access method, storage options (name=value per line),
/// partition key, persistence (p/u/t)` of a table. `None` for the engines whose tables have none
/// of these the IDE reads (all but PostgreSQL).
pub fn table_properties(driver: DbDriver, schema: &str, table: &str) -> Option<String> {
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
match driver {
// `reltablespace` 0 is the database's default tablespace; the TOAST table's options are
// set as `toast.name`.
DbDriver::Postgres => Some(format!(
"SELECT pg_get_userbyid(c.relowner), COALESCE(ts.spcname, (SELECT dt.spcname FROM pg_database d \
JOIN pg_tablespace dt ON dt.oid = d.dattablespace WHERE d.datname = current_database())), \
am.amname, array_to_string(array_cat(c.reloptions, \
(SELECT array_agg('toast.' || o) FROM unnest(tc.reloptions) o)), chr(10)), \
pg_get_partkeydef(c.oid), c.relpersistence \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
LEFT JOIN pg_class tc ON tc.oid = c.reltoastrelid \
LEFT JOIN pg_tablespace ts ON ts.oid = c.reltablespace LEFT JOIN pg_am am ON am.oid = c.relam \
WHERE n.nspname = {s} AND c.relname = {t} AND c.relkind IN ('r', 'p')"
)),
_ => None,
}
}
/// Rows: `index name, unique (0/1), column, key` (one row per indexed column, in order); `key` is
/// `p` for the primary key's index, `u` for a unique constraint's, NULL otherwise (ClickHouse: absent).
// Key columns are paired from one series up to `max_index_keys` (the server's INDEX_MAX_KEYS, the
@@ -812,7 +835,12 @@ pub fn sqlite_trigger_event(sql: &str) -> (String, String) {
pub fn postgres_legacy(sql: &str) -> Option<String> {
let legacy = sql
.replace("CASE WHEN p.prokind = 'p' THEN 'procedure' ELSE 'function' END", "'function'")
.replace("p.prokind IN ('f', 'p')", "NOT p.proisagg AND NOT p.proiswindow");
.replace("p.prokind IN ('f', 'p')", "NOT p.proisagg AND NOT p.proiswindow")
// Table access methods (PostgreSQL 12) and partitioned tables (10).
.replace(" LEFT JOIN pg_am am ON am.oid = c.relam", "")
.replace("am.amname", "NULL")
.replace("pg_get_partkeydef(c.oid)", "NULL")
.replace("c.relkind IN ('r', 'p')", "c.relkind = 'r'");
(legacy != sql).then_some(legacy)
}
@@ -1534,5 +1562,7 @@ mod tests {
let routines = postgres_legacy(&routines(pg, "s").unwrap()).unwrap();
assert!(!routines.contains("prokind") && routines.contains("NOT p.proisagg"));
assert_eq!(postgres_legacy(&indexes(pg, "s", "t")), None);
let properties = postgres_legacy(&table_properties(pg, "s", "t").unwrap()).unwrap();
assert!(!properties.contains("relam") && !properties.contains("partkeydef"), "{properties}");
}
}
+579
Переглянути файл
@@ -0,0 +1,579 @@
//! A read-only equality join of explicitly selected source tables on the project host.
use crate::jdbc::JdbcPool;
use crate::workspace_input::{
self, WorkspaceInput, WorkspaceInputColumn, WorkspaceInputLimits, WorkspaceInputRequest, WorkspaceInputType,
};
use crate::{DbDriver, DbManager, QueryResult, sql};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::io::{BufWriter, Write};
use std::time::{Duration, Instant};
use tempfile::{NamedTempFile, TempPath};
const MAX_TABLES: usize = 8;
const MAX_RESULT_ROWS: usize = 100_000;
const MAX_RESULT_COLUMNS: usize = 256;
const WORKSPACE_INPUT_LIMITS: WorkspaceInputLimits =
WorkspaceInputLimits { max_rows: 100_000, max_cell_bytes: 1_048_576, max_bytes: 16_777_216 };
#[derive(Debug, Deserialize, Serialize, Type)]
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinRelation")]
pub struct WorkspaceJoinRelation {
pub source_id: String,
pub database: String,
pub schema: String,
pub table: String,
}
#[derive(Debug, Deserialize, Serialize, Type)]
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinColumn")]
pub struct WorkspaceJoinColumn {
pub relation: u32,
pub column: String,
}
#[derive(Debug, Deserialize, Serialize, Type)]
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinCondition")]
pub struct WorkspaceJoinCondition {
/// The right relation is the next table in the chain.
pub left: WorkspaceJoinColumn,
pub right_column: String,
}
#[derive(Debug, Deserialize, Serialize, Type)]
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinProjection")]
pub struct WorkspaceJoinProjection {
pub relation: u32,
/// None expands this relation's columns in source order.
pub column: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Type)]
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinPlan")]
pub struct WorkspaceJoinPlan {
pub tables: Vec<WorkspaceJoinRelation>,
pub joins: Vec<WorkspaceJoinCondition>,
/// None expands all relations in FROM/JOIN order.
pub projection: Option<Vec<WorkspaceJoinProjection>>,
}
fn validate_plan(
table_count: usize,
joins: &[WorkspaceJoinCondition],
projection: Option<&[WorkspaceJoinProjection]>,
) -> IdeResult<()> {
if !(2..=MAX_TABLES).contains(&table_count) || joins.len() + 1 != table_count {
return Err(IdeError::invalid("A workspace JOIN needs 2 to 8 tables and one equality per JOIN"));
}
let valid_column = |name: &str| !name.is_empty() && name.len() <= 255 && !name.contains('\0');
for (index, link) in joins.iter().enumerate() {
if link.left.relation as usize > index || !valid_column(&link.left.column) || !valid_column(&link.right_column)
{
return Err(IdeError::invalid("Each JOIN must compare a column of its new table with an earlier table"));
}
}
if let Some(projection) = projection
&& (projection.is_empty()
|| projection.len() > MAX_RESULT_COLUMNS
|| projection.iter().any(|item| {
item.relation as usize >= table_count || item.column.as_deref().is_some_and(|name| !valid_column(name))
}))
{
return Err(IdeError::invalid("Invalid workspace SELECT columns"));
}
Ok(())
}
struct StagedTable {
path: TempPath,
longest_row: usize,
columns: Vec<WorkspaceInputColumn>,
}
impl WorkspaceInputType {
fn is_integer(self) -> bool {
use WorkspaceInputType::*;
matches!(self, Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32 | UInt64)
}
fn duckdb_type(self) -> String {
use WorkspaceInputType::*;
match self {
Boolean => "BOOLEAN",
Int8 => "TINYINT",
Int16 => "SMALLINT",
Int32 => "INTEGER",
Int64 => "BIGINT",
UInt8 => "UTINYINT",
UInt16 => "USMALLINT",
UInt32 => "UINTEGER",
UInt64 => "UBIGINT",
Float32 => "FLOAT",
Float64 => "DOUBLE",
Decimal { precision, scale } => return format!("DECIMAL({precision},{scale})"),
Text => "VARCHAR",
Date => "DATE",
Time => "TIME",
Timestamp => "TIMESTAMP",
TimestampTz => "TIMESTAMPTZ",
Uuid => "UUID",
}
.into()
}
}
fn stage(input: WorkspaceInput, cancel: &CancellationToken) -> IdeResult<StagedTable> {
let mut file = NamedTempFile::new()?;
let mut longest_row = 1;
{
let mut out = BufWriter::new(file.as_file_mut());
for row in input.rows {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if row.len() != input.columns.len() {
return Err(IdeError::invalid("Incomplete workspace input row"));
}
let mut bytes = row.len(); // separators and newline
for (column, cell) in row.into_iter().enumerate() {
if column > 0 {
out.write_all(b",")?;
}
bytes += 2; // quotes or the NULL marker
if let Some(value) = cell {
bytes += value.len();
out.write_all(b"\"")?;
let mut pieces = value.split('"');
out.write_all(pieces.next().unwrap_or_default().as_bytes())?;
for piece in pieces {
bytes += 1;
out.write_all(b"\"\"")?;
out.write_all(piece.as_bytes())?;
}
out.write_all(b"\"")?;
} else {
out.write_all(br"\N")?;
}
}
longest_row = longest_row.max(bytes);
out.write_all(b"\n")?;
}
out.flush()?;
}
Ok(StagedTable { path: file.into_temp_path(), longest_row, columns: input.columns })
}
impl StagedTable {
fn quoted_path(&self) -> IdeResult<String> {
self.path
.to_str()
.map(|p| sql::quote_literal(DbDriver::Jdbc, p))
.ok_or_else(|| IdeError::invalid("The workspace temporary directory needs a UTF-8 path"))
}
fn scan(&self, path: &str) -> String {
// Synthetic column names also preserve case-distinct names from the source.
let columns = self
.columns
.iter()
.enumerate()
.map(|(i, c)| format!("'c{i}':'{}'", c.data_type.duckdb_type()))
.collect::<Vec<_>>()
.join(",");
let line = self.longest_row;
// The single-threaded reader only needs one complete CSV record per buffer.
let buffer = line.max(64 * 1024);
format!(
r#"read_csv({path},columns={{{columns}}},auto_detect=false,header=false,delim=',',quote='"',escape='"',nullstr='\N',allow_quoted_nulls=false,parallel=false,max_line_size={line},buffer_size={buffer})"#
)
}
fn column(&self, name: &str) -> IdeResult<usize> {
self.columns
.iter()
.position(|c| c.name == name)
.ok_or_else(|| IdeError::invalid(format!("Unknown workspace column: {name}")))
}
}
fn staging_columns<'a>(
table_count: usize,
joins: &'a [WorkspaceJoinCondition],
projection: Option<&'a [WorkspaceJoinProjection]>,
) -> Vec<Option<Vec<&'a str>>> {
let Some(projection) = projection else {
return vec![None; table_count];
};
let mut columns: Vec<Option<Vec<&str>>> = vec![Some(Vec::new()); table_count];
for item in projection {
let selected = &mut columns[item.relation as usize];
match (&item.column, selected) {
(Some(name), Some(selected)) => selected.push(name),
(None, selected) => *selected = None,
_ => {}
}
}
for (index, link) in joins.iter().enumerate() {
if let Some(selected) = &mut columns[link.left.relation as usize] {
selected.push(&link.left.column);
}
if let Some(selected) = &mut columns[index + 1] {
selected.push(&link.right_column);
}
}
for selected in columns.iter_mut().flatten() {
selected.sort_unstable();
selected.dedup();
}
columns
}
fn result_projection(
tables: &[StagedTable],
selection: Option<&[WorkspaceJoinProjection]>,
) -> IdeResult<Vec<(usize, usize)>> {
let mut fields = Vec::new();
match selection {
Some(selection) => {
for item in selection {
let relation = item.relation as usize;
let table = &tables[relation];
match &item.column {
Some(name) => fields.push((relation, table.column(name)?)),
None => fields.extend((0..table.columns.len()).map(|column| (relation, column))),
}
}
}
None => {
for (relation, table) in tables.iter().enumerate() {
fields.extend((0..table.columns.len()).map(|column| (relation, column)));
}
}
}
if fields.len() > MAX_RESULT_COLUMNS {
return Err(IdeError::invalid("Workspace result exceeds 256 columns"));
}
Ok(fields)
}
async fn join(
engine: &JdbcPool,
tables: &[StagedTable],
joins: &[WorkspaceJoinCondition],
selection: Option<&[WorkspaceJoinProjection]>,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
use std::fmt::Write as _;
let fields = result_projection(tables, selection)?;
let names = fields.iter().map(|(relation, column)| format!("r{relation}.c{column}")).collect::<Vec<_>>().join(", ");
let paths = tables.iter().map(StagedTable::quoted_path).collect::<IdeResult<Vec<_>>>()?;
let mut query = format!("SELECT {names} FROM {} r0", tables[0].scan(&paths[0]));
for (index, condition) in joins.iter().enumerate() {
let left_relation = condition.left.relation as usize;
let right_relation = index + 1;
let left = &tables[left_relation];
let right = &tables[right_relation];
let li = left.column(&condition.left.column)?;
let ri = right.column(&condition.right_column)?;
let (a, b) = (left.columns[li].data_type, right.columns[ri].data_type);
// DuckDB compares mixed integer widths and signs exactly, up to BIGINT against UBIGINT.
if a != b && !(a.is_integer() && b.is_integer()) {
return Err(IdeError::invalid("Choose integer join columns or columns of the same type and precision"));
}
write!(
query,
" INNER JOIN {} r{right_relation} ON r{left_relation}.c{li}=r{right_relation}.c{ri}",
right.scan(&paths[right_relation]),
)
.unwrap();
}
write!(query, " LIMIT {}", MAX_RESULT_ROWS + 1).unwrap();
for setting in [
"SET threads=1",
"SET memory_limit='96MiB'",
"SET temp_directory=''",
"SET max_temp_directory_size='0B'",
&format!("SET allowed_paths=[{}]", paths.join(",")),
"SET enable_external_access=false",
"SET lock_configuration=true",
] {
engine.query(setting, 0, 0, cancel).await?;
}
let mut result = engine.query(&query, 0, MAX_RESULT_ROWS, cancel).await?;
if result.has_more {
return Err(IdeError::invalid("Workspace result exceeds 100,000 rows"));
}
if result.columns.len() != fields.len() {
return Err(IdeError::invalid("Unexpected workspace result columns"));
}
for (display, (relation, column)) in result.columns.iter_mut().zip(fields) {
display.name.clone_from(&tables[relation].columns[column].name);
}
result.statement.clear();
Ok(result)
}
#[cfg(test)]
fn two_table_join(keys: [&str; 2]) -> WorkspaceJoinCondition {
WorkspaceJoinCondition {
left: WorkspaceJoinColumn { relation: 0, column: keys[0].into() },
right_column: keys[1].into(),
}
}
impl DbManager {
#[cfg(test)]
pub(crate) async fn workspace_join_pair_for_test(
&self,
driver: &str,
tables: [&WorkspaceInputRequest; 2],
keys: [&str; 2],
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
let joins = [two_table_join(keys)];
validate_plan(tables.len(), &joins, None)?;
self.execute_workspace_join(driver, &tables, &joins, None, cancel).await
}
/// The caller retains the bounded result for paging. Reading another page never reruns the sources.
pub async fn workspace_join(
&self,
driver: &str,
plan: WorkspaceJoinPlan,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
validate_plan(plan.tables.len(), &plan.joins, plan.projection.as_deref())?;
let tables: Vec<_> = plan
.tables
.into_iter()
.map(|table| WorkspaceInputRequest {
source_id: table.source_id,
database: table.database,
schema: table.schema,
table: table.table,
limits: WORKSPACE_INPUT_LIMITS,
})
.collect();
let tables: Vec<_> = tables.iter().collect();
self.execute_workspace_join(driver, &tables, &plan.joins, plan.projection.as_deref(), cancel).await
}
async fn execute_workspace_join(
&self,
driver: &str,
tables: &[&WorkspaceInputRequest],
joins: &[WorkspaceJoinCondition],
projection: Option<&[WorkspaceJoinProjection]>,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
let _run =
self.workspace_run.try_lock().map_err(|_| IdeError::invalid("A workspace query is already running"))?;
let start = Instant::now();
let child = cancel.child_token();
let run = async {
let cancel = &child;
let mut prepared = Vec::with_capacity(tables.len());
for table in tables {
let input = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
input = workspace_input::prepare_table(self, table) => input?,
};
prepared.push(input);
}
let selection = staging_columns(tables.len(), joins, projection);
let mut staged = Vec::with_capacity(tables.len());
let engine = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
engine = self.workspace_engine(driver) => engine?,
};
let result = async {
let mut remaining_rows = 200_000;
let mut remaining_bytes = 32 * 1024 * 1024;
for (mut table, columns) in prepared.into_iter().zip(&selection) {
let limits = &mut table.request.limits;
limits.max_rows = limits.max_rows.min(remaining_rows);
limits.max_bytes = limits.max_bytes.min(remaining_bytes);
let input = workspace_input::read_prepared_table(self, table, columns.as_deref(), cancel).await?;
remaining_rows -= input.rows.len();
remaining_bytes -= input.bytes;
let cancellation = cancel.clone();
let table = tokio::task::spawn_blocking(move || stage(input, &cancellation))
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
staged.push(table);
}
join(&engine, &staged, joins, projection, cancel).await
}
.await;
// Windows cannot remove a staged file while the JDBC process still has it open.
engine.close().await;
drop(staged);
let mut result = result?;
result.elapsed_ms = start.elapsed().as_secs_f64() * 1000.0;
Ok(result)
};
tokio::pin!(run);
let stopped = tokio::select! {
biased;
() = cancel.cancelled() => IdeError::cancelled(),
result = &mut run => return result,
() = tokio::time::sleep(Duration::from_secs(90)) => IdeError::new(ide_core::error::ErrorKind::TimedOut, "Workspace query timed out"),
};
child.cancel();
// Let the source or JDBC bridge deliver cancellation before dropping its connection.
let _ = tokio::time::timeout(Duration::from_secs(15), run).await;
Err(stopped)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::DbJdbcDriver;
fn input(values: &[(&str, Option<&str>)]) -> WorkspaceInput {
WorkspaceInput {
columns: vec![
WorkspaceInputColumn {
name: "key".into(),
data_type: WorkspaceInputType::Decimal { precision: 32, scale: 6 },
},
WorkspaceInputColumn { name: "text".into(), data_type: WorkspaceInputType::Text },
],
rows: values.iter().map(|(k, v)| vec![Some(k.to_string()), v.map(str::to_owned)]).collect(),
bytes: 0,
}
}
#[test]
fn workspace_join_chain_links_must_target_an_earlier_table() -> IdeResult<()> {
let first = two_table_join(["key", "key"]);
let second = two_table_join(["key", "id"]);
let links = [first, second];
validate_plan(3, &links, None)?;
let over_limit: Vec<_> = (0..8).map(|_| two_table_join(["key", "key"])).collect();
assert!(validate_plan(9, &over_limit, None).is_err());
validate_plan(8, &over_limit[..7], None)?;
assert!(validate_plan(4, &links, None).is_err());
assert!(validate_plan(3, &links, Some(&[])).is_err());
let invalid = WorkspaceJoinProjection { relation: 3, column: None };
assert!(validate_plan(3, &links, Some(&[invalid])).is_err());
let mut links = links;
links[0].left.relation = 1;
assert!(validate_plan(3, &links, None).is_err());
Ok(())
}
#[test]
fn staging_preserves_null_and_csv_text_and_removes_the_file_on_drop() -> IdeResult<()> {
let cancel = CancellationToken::new();
let table = stage(input(&[("1", None), ("2", Some("")), ("3", Some("a,\"b\"\nc"))]), &cancel)?;
let path = table.path.to_path_buf();
assert_eq!(std::fs::read_to_string(&path)?, "\"1\",\\N\n\"2\",\"\"\n\"3\",\"a,\"\"b\"\"\nc\"\n");
drop(table);
assert!(!path.exists());
cancel.cancel();
assert!(stage(input(&[("1", None)]), &cancel).is_err());
Ok(())
}
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR and Java 17+"]
async fn workspace_engine_joins_exact_keys_nulls_and_empty_inputs() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let root = tmp.path();
let db = DbManager::new(
root.join("project"),
root.join("passwords"),
root.join("history"),
std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh"))),
)
.with_global_sources(root.join("global"));
db.save_jdbc_driver(DbJdbcDriver {
id: "duck".into(),
name: "DuckDB".into(),
vendor: Some("duckdb".into()),
jars: vec![std::env::var("DUCKDB_JDBC_JAR").expect("driver fixture")],
class_name: "org.duckdb.DuckDBDriver".into(),
url_template: "jdbc:duckdb:".into(),
})?;
let cancel = CancellationToken::new();
let mut signed = input(&[("-1", None), ("9007199254740993", None), ("9223372036854775807", None)]);
signed.columns[0].data_type = WorkspaceInputType::Int64;
let mut unsigned = input(&[
("18446744073709551615", None),
("9007199254740992", None),
("9007199254740993", None),
("9223372036854775807", None),
]);
unsigned.columns[0].data_type = WorkspaceInputType::UInt64;
let tables = [stage(signed, &cancel)?, stage(unsigned, &cancel)?];
let engine = db.workspace_engine("duck").await?;
let output = join(&engine, &tables, &[two_table_join(["key", "key"])], None, &cancel).await?;
let mut matches: Vec<_> = output.rows.iter().map(|row| (row[0].as_deref(), row[2].as_deref())).collect();
matches.sort_unstable();
assert_eq!(
matches,
[
(Some("9007199254740993"), Some("9007199254740993")),
(Some("9223372036854775807"), Some("9223372036854775807")),
]
);
engine.close().await;
let wide = "a,\n\"b\"".repeat(32 * 1024);
let left = stage(input(&[("0", None), ("1", Some(&wide)), ("2", Some("short"))]), &cancel)?;
let right = stage(input(&[("1", Some(&wide))]), &cancel)?;
let engine = db.workspace_engine("duck").await?;
let output = join(&engine, &[left, right], &[two_table_join(["key", "key"])], None, &cancel).await?;
assert_eq!(output.rows.len(), 1);
assert_eq!(output.rows[0][1].as_deref(), Some(wide.as_str()));
assert_eq!(output.rows[0][3].as_deref(), Some(wide.as_str()));
engine.close().await;
for empty in [false, true] {
let left =
stage(input(&[("9007199254740993.000001", None), ("9007199254740993.000002", Some(""))]), &cancel)?;
let mut right =
input(&[("9007199254740993.000001", Some("a,\"b\"\nc")), ("9007199254740993.000002", Some(r"\N"))]);
if empty {
right.rows.clear();
}
let engine = db.workspace_engine("duck").await?;
let right = stage(right, &cancel)?;
let output = join(&engine, &[left, right], &[two_table_join(["key", "key"])], None, &cancel).await?;
assert_eq!(
output.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(),
["key", "text", "key", "text"]
);
let mut rows = output.rows;
rows.sort();
if empty {
assert!(rows.is_empty());
} else {
assert_eq!(rows.len(), 2);
assert_eq!(
rows[0],
[
Some("9007199254740993.000001".into()),
None,
Some("9007199254740993.000001".into()),
Some("a,\"b\"\nc".into())
]
);
assert_eq!(
rows[1],
[
Some("9007199254740993.000002".into()),
Some("".into()),
Some("9007199254740993.000002".into()),
Some(r"\N".into())
]
);
}
engine.close().await;
}
Ok(())
}
}
File diff suppressed because it is too large. Load diff
+134
Переглянути файл
@@ -0,0 +1,134 @@
#!/usr/bin/env bash
# Requires Docker, curl and Cargo. To exercise the JOIN and its cancellation as well
# as source reads, install Java 17+ and set DUCKDB_JDBC_JAR to an absolute JAR path.
# Usage: bash crates/ide-db/tests/fixtures/workspace.sh [command args...]
set -euo pipefail
cd "$(dirname "$0")/../../../.."
fixtures=$(mktemp -d "${TMPDIR:-/tmp}/openidea-workspace.XXXXXXXX")
pg=
ch=
cleanup() {
if [[ -n "$ch" ]]; then docker stop -t 2 "$ch" >/dev/null || true; fi
if [[ -n "$pg" ]]; then docker stop -t 2 "$pg" >/dev/null || true; fi
rm -f "$fixtures/users.xml"
rmdir "$fixtures"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
cat > "$fixtures/users.xml" <<'XML'
<clickhouse>
<profiles>
<workspace_strict>
<readonly>1</readonly>
<max_threads>1</max_threads>
<max_memory_usage>134217728</max_memory_usage>
<max_rows_to_read>100000</max_rows_to_read>
<max_execution_time>20</max_execution_time>
</workspace_strict>
<workspace_break>
<readonly>1</readonly>
<result_overflow_mode>break</result_overflow_mode>
</workspace_break>
<workspace_cap>
<readonly>1</readonly>
<max_result_rows>2</max_result_rows>
</workspace_cap>
</profiles>
<users>
<fixture_writer>
<no_password/>
<networks><ip>::/0</ip></networks>
<profile>default</profile>
<quota>default</quota>
</fixture_writer>
<fixture_strict>
<no_password/>
<networks><ip>::/0</ip></networks>
<profile>workspace_strict</profile>
<quota>default</quota>
</fixture_strict>
<fixture_break>
<no_password/>
<networks><ip>::/0</ip></networks>
<profile>workspace_break</profile>
<quota>default</quota>
</fixture_break>
<fixture_cap>
<no_password/>
<networks><ip>::/0</ip></networks>
<profile>workspace_cap</profile>
<quota>default</quota>
</fixture_cap>
</users>
</clickhouse>
XML
chmod 644 "$fixtures/users.xml"
pg=$(docker run --rm -d -p 127.0.0.1::5432 --cpus 1 --memory 320m \
--tmpfs /var/lib/postgresql/data:rw,size=128m \
-e POSTGRES_HOST_AUTH_METHOD=trust postgres:17-alpine)
ch=$(docker run --rm -d -p 127.0.0.1::8123 --cpus 1 --memory 1536m \
--tmpfs /var/lib/clickhouse --tmpfs /var/log/clickhouse-server \
--mount "type=bind,source=$fixtures/users.xml,target=/etc/clickhouse-server/users.d/workspace-fixture.xml,readonly" \
clickhouse/clickhouse-server:25.8.12.129)
WORKSPACE_PG_PORT=$(docker port "$pg" 5432/tcp | sed 's/^127\.0\.0\.1://')
WORKSPACE_CH_PORT=$(docker port "$ch" 8123/tcp | sed 's/^127\.0\.0\.1://')
export WORKSPACE_PG_PORT WORKSPACE_CH_PORT
ch_http="http://127.0.0.1:$WORKSPACE_CH_PORT"
ready() {
for ((attempt = 0; attempt < 45; ++attempt)); do
if "$@" >/dev/null 2>&1; then return 0; fi
sleep 1
done
printf 'Workspace fixture did not become ready: %s\n' "$1" >&2
return 1
}
ready docker exec "$pg" pg_isready -h 127.0.0.1 -U postgres
ready curl -fsS --max-time 1 "$ch_http/ping"
docker exec -i "$pg" psql -h 127.0.0.1 -U postgres -Xq -v ON_ERROR_STOP=1 <<'SQL'
CREATE TABLE "exact data" ("exact key" numeric(32,6), id bigint, ts timestamp(6) with time zone, label text);
INSERT INTO "exact data" VALUES
(100000000000000000001.000001, 9007199254740993, '2025-01-03 07:05:06.123456+03', E'a,b"c\nd'),
(100000000000000000002.000001, 9007199254740994, NULL, ''),
(NULL, 9007199254740995, NULL, NULL);
CREATE TABLE "empty data" (LIKE "exact data");
CREATE TABLE "unsupported data" (payload jsonb);
CREATE VIEW "fixture view" AS SELECT * FROM "exact data";
SQL
ch_sql() {
curl -fsS --max-time 5 --user fixture_writer: --data-binary "$1" "$ch_http/"
}
ch_sql "CREATE TABLE default.\"exact data\" (
\"exact key\" Nullable(Decimal(32,6)), id Int64, ts Nullable(DateTime64(6, 'Europe/Moscow')), label Nullable(String)
) ENGINE=Memory"
ch_sql "INSERT INTO default.\"exact data\" VALUES
(100000000000000000001.000001, 9007199254740993, '2025-01-03 07:05:06.123456', 'a,b\"c\\nd'),
(100000000000000000002.000001, 9007199254740994, NULL, ''),
(NULL, 9007199254740995, NULL, NULL)"
ch_sql 'CREATE TABLE default."empty data" AS default."exact data" ENGINE=Memory'
ch_sql 'CREATE TABLE default."unsupported data" (payload Array(String)) ENGINE=Memory'
ch_sql 'CREATE VIEW default."fixture view" AS SELECT * FROM default."exact data"'
ch_sql 'CREATE TABLE default."unsigned data" (id UInt64) ENGINE=Memory'
ch_sql 'INSERT INTO default."unsigned data" VALUES (9007199254740992), (9007199254740993), (18446744073709551615)'
ch_sql 'CREATE TABLE default."overflow data" (id Int64) ENGINE=Memory'
ch_sql 'INSERT INTO default."overflow data" VALUES (1), (2), (3), (4), (5)'
export WORKSPACE_CH_USER=fixture_writer
if (( $# > 0 )); then
"$@"
else
test_name=workspace_input::tests::native_workspace_sources_are_exact_and_fail_on_limits
cargo test --locked -p ide-db --lib "$test_name" -- --ignored
WORKSPACE_CH_USER=fixture_strict cargo test --locked -p ide-db --lib "$test_name" -- --ignored
cargo test --locked -p ide-db --lib clickhouse_workspace_refuses_truncated_reads -- --ignored
if [[ -n "${DUCKDB_JDBC_JAR:-}" ]]; then
WORKSPACE_CH_USER=fixture_strict cargo test --locked -p ide-db --lib workspace_join_chains_four_live_engines -- --ignored
fi
fi
+183 -24
Переглянути файл
@@ -1,5 +1,7 @@
use ide_core::{CancellationToken, IdeResult};
use ide_db::{ConsoleId, DataSource, DbDriver, DbJdbcDriver, DbManager, DbProperty, SortKey};
use ide_db::{
ConsoleId, DataSource, DbDriver, DbDuckLake, DbDuckLakeKind, DbJdbcDriver, DbManager, DbProperty, SortKey,
};
use std::{path::Path, sync::Arc};
fn manager(dir: &Path) -> DbManager {
@@ -8,6 +10,158 @@ fn manager(dir: &Path) -> DbManager {
.with_global_sources(dir.join("global"))
}
fn duck_lake_source(catalog: &str) -> DataSource {
DataSource {
id: "lake".into(),
name: "DuckLake".into(),
driver: DbDriver::Jdbc,
vendor: "duckdb".into(),
jdbc_driver: "duck".into(),
url: "jdbc:duckdb:".into(),
read_only: true,
duck_lake: Some(DbDuckLake { kind: DbDuckLakeKind::File, value: catalog.into(), data_path: None }),
..Default::default()
}
}
fn duck_lake_driver(jar: String) -> DbJdbcDriver {
DbJdbcDriver {
id: "duck".into(),
name: "DuckDB".into(),
vendor: Some("duckdb".into()),
jars: vec![jar],
class_name: "org.duckdb.DuckDBDriver".into(),
url_template: "jdbc:duckdb:".into(),
}
}
#[tokio::test]
async fn duck_lake_settings_are_validated_and_covered_by_project_approval() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let jar = tmp.path().join("fixture.jar");
std::fs::write(&jar, [])?;
let db = manager(tmp.path());
let profile = duck_lake_driver(jar.display().to_string());
let source = duck_lake_source("lake/catalog.ducklake");
let mut other_profile = profile.clone();
other_profile.class_name = "test.NotDuckDB".into();
db.save_jdbc_driver(other_profile)?;
assert!(db.approve_ducklake_source(&source).is_err());
let directory = tmp.path().join("create");
assert!(db.create_ducklake("duck", directory.to_str().unwrap()).await.is_err());
assert!(!directory.exists());
db.save_jdbc_driver(profile)?;
assert!(db.approve_ducklake_source(&DataSource { duck_lake: None, ..source.clone() }).is_err());
let mut invalid_secret = source.clone();
invalid_secret.duck_lake =
Some(DbDuckLake { kind: DbDuckLakeKind::Secret, value: "key=value".into(), data_path: None });
let mut data_path = source.clone();
data_path.duck_lake.as_mut().unwrap().data_path = Some("s3://example/ducklake".into());
let mut scripted = source.clone();
scripted.options.startup_script = "CREATE TABLE t (n int)".into();
for invalid in [
invalid_secret,
data_path,
scripted,
DataSource { driver: DbDriver::Sqlite, ..source.clone() },
DataSource { url: "jdbc:duckdb:unrelated.duckdb".into(), ..source.clone() },
DataSource { read_only: false, ..source.clone() },
DataSource { save_password: true, ..source.clone() },
DataSource {
properties: vec![DbProperty { name: "access_mode".into(), value: "READ_WRITE".into() }],
..source.clone()
},
] {
assert!(invalid.resolved().is_err());
assert!(db.save_sources(vec![invalid.clone()]).await.is_err());
assert!(db.approve_ducklake_source(&invalid).is_err());
}
assert!(db.sources()?.is_empty());
db.approve_ducklake_source(&DataSource { global: true, ..source.clone() })?;
db.save_sources(vec![source.clone()]).await?;
assert_eq!(db.source("lake")?, source);
let err = db.pool("lake").await.err().expect("global validation must not approve a project connection");
assert!(err.message.contains("Review this project"));
assert!(db.set_password("lake", Some("unused".into()), true).await.is_err());
assert!(db.test(&source, Some("unused".into()), None).await.is_err());
db.approve_ducklake_source(&source)?;
let mut changed = source;
changed.duck_lake.as_mut().unwrap().value = "another/catalog.ducklake".into();
db.save_sources(vec![changed]).await?;
let err = db.pool("lake").await.err().expect("new catalog path must be approved");
assert!(err.message.contains("Review this project"));
assert!(serde_json::from_value::<DbDuckLake>(serde_json::json!({"kind":"create", "value":"lake"})).is_err());
Ok(())
}
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR, DuckLake extension access, and Java 17+"]
async fn duck_lake_creates_only_explicitly_and_reopens_read_only() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
let jar = std::env::var("DUCKDB_JDBC_JAR").expect("DUCKDB_JDBC_JAR");
db.save_jdbc_driver(duck_lake_driver(jar))?;
let source = duck_lake_source("lake's files/catalog.ducklake");
let directory = tmp.path().join("project").join("lake's files");
let path = directory.to_str().unwrap();
db.save_sources(vec![source.clone()]).await?;
let err = db.test(&source, None, None).await.expect_err("Test must not create a missing catalog");
assert!(err.message.contains("does not exist"), "{}", err.message);
assert!(!directory.exists());
db.approve_ducklake_source(&source)?;
assert!(db.pool("lake").await.is_err());
assert!(!directory.exists());
db.create_ducklake("duck", path).await?;
assert!(directory.join("catalog.ducklake").is_file());
let err = db.create_ducklake("duck", path).await.expect_err("Create must reject an existing directory");
assert!(err.message.contains("already exists"), "{}", err.message);
assert!(db.test(&source, None, None).await?.contains("DuckDB"));
let db = manager(tmp.path());
assert_eq!(db.source("lake")?, source);
let cancel = CancellationToken::new();
let console = ConsoleId::new("window", "/lake.sql");
for scope in [None, Some(console)] {
let result = db
.execute_in_console(
"lake",
"SELECT readonly FROM duckdb_databases() WHERE database_name = current_database() AND type = 'ducklake'",
0,
1,
&cancel,
None,
scope,
)
.await?;
assert_eq!(result.rows, [vec![Some("true".into())]]);
assert!(
db.execute_in_console("lake", "CREATE TABLE main.rejected(id INTEGER)", 0, 1, &cancel, None, scope)
.await
.is_err(),
"the attached catalog must be read-only"
);
}
assert!(db.schemas("lake").await?.contains(&"main".into()));
assert!(db.tables("lake", "main").await?.is_empty());
let databases = db.databases("lake").await?;
assert_eq!(databases.current, "openidea_lake");
assert!(databases.names.contains(&databases.current));
let catalog = db.database_catalog("lake", &databases.current).await?;
assert!(catalog.iter().any(|schema| schema.name == "main" && schema.tables.is_empty()));
db.release_target_console(console, Some("lake")).await?;
db.disconnect("lake").await;
let global = DataSource { id: "global-lake".into(), global: true, ..source };
db.approve_ducklake_source(&global)?;
db.save_sources(vec![global]).await?;
assert!(db.schemas("global-lake").await?.contains(&"main".into()));
db.disconnect("global-lake").await;
Ok(())
}
#[tokio::test]
async fn jdbc_profiles_persist_and_project_files_cannot_start_drivers() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
@@ -278,34 +432,39 @@ async fn duckdb_named_memory_lives_until_disconnect() -> IdeResult<()> {
vendor: "duckdb".into(),
global: true,
jdbc_driver: "duck".into(),
url: "jdbc:duckdb:".into(),
..Default::default()
};
let cancel = CancellationToken::new();
db.save_sources(vec![source.clone()]).await?;
db.execute("test", "create table session_items as select 42 as id", 1, &cancel).await?;
assert_eq!(db.execute("test", "select id from session_items", 1, &cancel).await?.rows, [vec![Some("42".into())]]);
let join = "SELECT a.id FROM session_items a JOIN session_items b ON a.id = b.id";
let nodes = db.explain("test", join, &cancel, None).await?;
let join_node = nodes.iter().position(|n| n.operation == "HASH_JOIN").expect("physical join");
assert_eq!(nodes.iter().filter(|n| n.parent == Some(join_node as u32)).count(), 2);
assert!(nodes[join_node].properties.iter().any(|p| p.name == "Conditions" && p.value.contains("id")));
let batch = db.explain("test", "SELECT 1; SELECT 2", &cancel, None).await.unwrap_err();
assert!(batch.message.contains("one statement"));
assert!(!db.explain("test", "SELECT ';' AS delimiter", &cancel, None).await?.is_empty());
db.execute("test", "SET explain_output = 'optimized_only'", 1, &cancel).await?;
assert!(!db.explain("test", "SELECT id FROM session_items", &cancel, None).await?.is_empty());
db.explain("test", "INSERT INTO session_items VALUES (43)", &cancel, None).await?;
assert_eq!(
db.execute("test", "SELECT count(*) FROM session_items", 1, &cancel).await?.rows,
[vec![Some("1".into())]]
);
db.disconnect("test").await;
assert!(!db.tables("test", "main").await?.iter().any(|table| table.name == "session_items"));
db.disconnect("test").await;
for url in ["jdbc:duckdb:", "jdbc:duckdb:memory:default"] {
source.url = url.into();
db.save_sources(vec![source.clone()]).await?;
db.execute("test", "create table session_items as select 42 as id", 1, &cancel).await?;
assert_eq!(
db.execute("test", "select id from session_items", 1, &cancel).await?.rows,
[vec![Some("42".into())]]
);
let join = "SELECT a.id FROM session_items a JOIN session_items b ON a.id = b.id";
let nodes = db.explain("test", join, &cancel, None).await?;
let join_node = nodes.iter().position(|n| n.operation == "HASH_JOIN").expect("physical join");
assert_eq!(nodes.iter().filter(|n| n.parent == Some(join_node as u32)).count(), 2);
assert!(nodes[join_node].properties.iter().any(|p| p.name == "Conditions" && p.value.contains("id")));
let batch = db.explain("test", "SELECT 1; SELECT 2", &cancel, None).await.unwrap_err();
assert!(batch.message.contains("one statement"));
assert!(!db.explain("test", "SELECT ';' AS delimiter", &cancel, None).await?.is_empty());
db.execute("test", "SET explain_output = 'optimized_only'", 1, &cancel).await?;
assert!(!db.explain("test", "SELECT id FROM session_items", &cancel, None).await?.is_empty());
db.explain("test", "INSERT INTO session_items VALUES (43)", &cancel, None).await?;
assert_eq!(
db.execute("test", "SELECT count(*) FROM session_items", 1, &cancel).await?.rows,
[vec![Some("1".into())]]
);
db.disconnect("test").await;
assert!(!db.tables("test", "main").await?.iter().any(|table| table.name == "session_items"));
db.disconnect("test").await;
}
source.read_only = true;
for url in ["jdbc:duckdb:", "jdbc:duckdb::memory:"] {
for url in ["jdbc:duckdb:", "jdbc:duckdb::memory:", "jdbc:duckdb:memory:default"] {
source.url = url.into();
let err = db.test(&source, None, None).await.unwrap_err();
assert!(err.message.contains("existing database file"), "{}", err.message);
+70 -1
Переглянути файл
@@ -2,7 +2,7 @@
//! `OPENIDEA_TEST_POSTGRES=host:port:user:password` names a throwaway server.
use ide_core::{CancellationToken, IdeResult};
use ide_db::{DataSource, DbDriver, DbManager};
use ide_db::{DataSource, DbDriver, DbManager, DbPersistence};
fn server() -> Option<(String, u16, String, String)> {
endpoint("OPENIDEA_TEST_POSTGRES")
@@ -813,6 +813,75 @@ async fn table_grants_expand_the_acl_per_grantee() -> IdeResult<()> {
Ok(())
}
/// Modify Table's properties: owner, tablespace, access method, storage options (the TOAST
/// table's too), partition key and persistence, read again after the statements it runs.
#[tokio::test]
async fn table_details_read_the_storage_properties() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
for stmt in [
"DROP SCHEMA IF EXISTS oi_props CASCADE",
"DROP ROLE IF EXISTS oi_props_owner",
"CREATE ROLE oi_props_owner",
"CREATE SCHEMA oi_props",
"CREATE UNLOGGED TABLE oi_props.bulk (id INT, v TEXT) WITH (fillfactor = 70, toast.autovacuum_enabled = false)",
"CREATE TABLE oi_props.events (id INT, at DATE) PARTITION BY RANGE (at)",
"CREATE VIEW oi_props.recent AS SELECT 1 AS n",
] {
db.execute("p", stmt, 10, &c).await?;
}
let owner = db.execute("p", "SELECT current_user", 1, &c).await?.rows[0][0].clone().unwrap();
let default_tablespace = db
.execute(
"p",
"SELECT t.spcname FROM pg_database d JOIN pg_tablespace t ON t.oid = d.dattablespace \
WHERE d.datname = current_database()",
1,
&c,
)
.await?
.rows[0][0]
.clone();
let options = |pairs: &[(&str, &str)]| Some(pairs.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect());
let bulk = db.table_details("p", "oi_props", "bulk").await?;
assert_eq!(bulk.owner.as_deref(), Some(owner.as_str()));
assert_eq!(bulk.tablespace, default_tablespace);
assert_eq!(bulk.access_method.as_deref(), Some("heap"));
assert_eq!(bulk.storage_options, options(&[("fillfactor", "70"), ("toast.autovacuum_enabled", "false")]));
assert_eq!(bulk.partitioning, None);
assert_eq!(bulk.persistence, Some(DbPersistence::Unlogged));
let events = db.table_details("p", "oi_props", "events").await?;
assert_eq!(events.partitioning.as_deref(), Some("RANGE (at)"));
assert_eq!(events.storage_options, options(&[]));
assert_eq!(events.persistence, Some(DbPersistence::Permanent));
// A view has none of a table's storage.
let recent = db.table_details("p", "oi_props", "recent").await?;
assert_eq!((recent.owner, recent.storage_options, recent.persistence), (None, None, None));
// The statements Modify Table generates (objects.ts `tablePropertiesSql`).
for stmt in [
"alter table oi_props.bulk set logged;",
"alter table oi_props.bulk reset (toast.autovacuum_enabled);",
"alter table oi_props.bulk set (fillfactor = 50, autovacuum_enabled = false);",
"alter table oi_props.bulk set tablespace pg_default;",
"alter table oi_props.bulk owner to oi_props_owner;",
] {
db.execute("p", stmt, 10, &c).await?;
}
let bulk = db.table_details("p", "oi_props", "bulk").await?;
assert_eq!(bulk.owner.as_deref(), Some("oi_props_owner"));
assert_eq!(bulk.tablespace.as_deref(), Some("pg_default"));
assert_eq!(bulk.storage_options, options(&[("fillfactor", "50"), ("autovacuum_enabled", "false")]));
assert_eq!(bulk.persistence, Some(DbPersistence::Permanent));
for stmt in ["DROP SCHEMA oi_props CASCADE", "DROP ROLE oi_props_owner"] {
db.execute("p", stmt, 10, &c).await?;
}
Ok(())
}
/// Completion reads the default schema in full: 52,000 columns there passed the cap shared with
/// the other schemas, and the tables sorting last lost theirs (#6118).
#[tokio::test]
+15 -1
Переглянути файл
@@ -423,11 +423,25 @@ pub struct CapabilityInfo {
pub optional: bool,
/// Currently granted.
pub granted: bool,
/// The plugin's own explanation (`[capabilities.reasons]`), shown below `description`.
#[serde(default)]
pub reason: Option<String>,
/// `reason` translated by the plugin's `locales/<tag>.json`, by language tag.
#[serde(default)]
pub reason_locales: std::collections::BTreeMap<String, String>,
}
impl CapabilityInfo {
pub fn new(cap: &Capability, optional: bool, granted: bool) -> Self {
Self { id: cap.to_string(), risk: cap.risk(), description: cap.describe(), optional, granted }
Self {
id: cap.to_string(),
risk: cap.risk(),
description: cap.describe(),
optional,
granted,
reason: None,
reason_locales: Default::default(),
}
}
}
+108 -4
Переглянути файл
@@ -29,12 +29,14 @@ use crate::capability::Capability;
use crate::plugin_point::PointDecl;
use crate::resolve::Dependency;
use serde::Deserialize;
use std::collections::BTreeSet;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path, PathBuf};
pub const MANIFEST_FILE: &str = "plugin.toml";
/// The plugin API (engine) version this host implements.
pub const ENGINE_VERSION: &str = "1.18.0";
pub const ENGINE_VERSION: &str = "1.19.0";
/// The longest `[capabilities.reasons]` entry, in characters: a sentence or two.
pub const MAX_CAPABILITY_REASON: usize = 500;
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
pub const LEGACY_API: &str = "0.1";
/// Marketplace categories, in the order they are shown.
@@ -49,11 +51,15 @@ pub struct Manifest {
pub name: String,
pub version: String,
pub description: String,
/// Markdown file for Settings › Plugins › Overview (`description-file`).
pub description_file: Option<PathBuf>,
pub authors: Vec<String>,
pub homepage: Option<String>,
pub license: Option<String>,
/// Release notes of this version (Settings › Plugins › What's New).
pub change_notes: Option<String>,
/// Markdown file for Settings › Plugins › What's New (`change-notes-file`).
pub change_notes_file: Option<PathBuf>,
/// Marketplace categories as declared (see [`Manifest::categories`]).
pub declared_categories: Vec<String>,
/// SVG shown in Settings › Plugins and the marketplace.
@@ -80,6 +86,10 @@ pub struct Manifest {
pub struct Capabilities {
pub required: Vec<Capability>,
pub optional: Vec<Capability>,
/// `[capabilities.reasons]` (API 1.19): the plugin's own words on why it asks for a
/// declared capability, keyed by the capability as printed (`net:127.0.0.1`). Shown
/// below the host's description, never instead of it.
pub reasons: BTreeMap<String, String>,
}
impl Capabilities {
@@ -90,6 +100,11 @@ impl Capabilities {
pub fn is_optional(&self, cap: &Capability) -> bool {
self.optional.contains(cap) && !self.required.contains(cap)
}
/// The plugin's explanation of `cap`, if it gave one.
pub fn reason(&self, cap: &Capability) -> Option<&str> {
self.reasons.get(&cap.to_string()).map(String::as_str)
}
}
/// When a plugin's code is instantiated (plan 4.4). Contributions are live
@@ -195,6 +210,8 @@ struct Raw {
#[serde(default)]
description: String,
#[serde(default)]
description_file: Option<PathBuf>,
#[serde(default)]
authors: Vec<String>,
#[serde(default)]
homepage: Option<String>,
@@ -203,6 +220,8 @@ struct Raw {
#[serde(default)]
change_notes: Option<String>,
#[serde(default)]
change_notes_file: Option<PathBuf>,
#[serde(default)]
categories: Vec<String>,
#[serde(default)]
icon: Option<PathBuf>,
@@ -243,6 +262,8 @@ struct RawCapabilities {
required: Vec<String>,
#[serde(default)]
optional: Vec<String>,
#[serde(default)]
reasons: BTreeMap<String, String>,
}
impl Manifest {
@@ -271,8 +292,18 @@ impl Manifest {
Ok(out)
};
let capabilities = match (raw.capabilities, raw.permissions) {
(Some(c), _) => Capabilities { required: parse_caps(c.required)?, optional: parse_caps(c.optional)? },
(None, Some(p)) => Capabilities { required: parse_caps(p)?, optional: Vec::new() },
(Some(c), _) => {
let mut reasons = BTreeMap::new();
for (key, text) in c.reasons {
// Keyed as the capability prints, so `net:Example.com` finds `net:example.com`.
let cap: Capability = key.parse().map_err(|e| format!("capabilities.reasons: {e}"))?;
reasons.insert(cap.to_string(), text);
}
Capabilities { required: parse_caps(c.required)?, optional: parse_caps(c.optional)?, reasons }
}
(None, Some(p)) => {
Capabilities { required: parse_caps(p)?, optional: Vec::new(), reasons: BTreeMap::new() }
}
(None, None) => Capabilities::default(),
};
let activation = match raw.activation {
@@ -286,10 +317,12 @@ impl Manifest {
name: raw.name,
version: raw.version,
description: raw.description,
description_file: raw.description_file,
authors: raw.authors,
homepage: raw.homepage,
license: raw.license,
change_notes: raw.change_notes,
change_notes_file: raw.change_notes_file,
declared_categories: raw.categories,
icon: raw.icon,
icon_dark: raw.icon_dark,
@@ -347,6 +380,27 @@ impl Manifest {
self.needs_api("`icon`", 2)?;
check_relative(icon, "icon")?;
}
if let Some(path) = &self.description_file {
self.needs_api("`description-file`", 18)?;
check_relative(path, "description-file")?;
}
if let Some(path) = &self.change_notes_file {
self.needs_api("`change-notes-file`", 18)?;
check_relative(path, "change-notes-file")?;
}
if !self.capabilities.reasons.is_empty() {
self.needs_api("`capabilities.reasons`", 19)?;
}
for (key, text) in &self.capabilities.reasons {
if !self.capabilities.all().any(|c| c.to_string() == *key) {
return Err(format!("capabilities.reasons: {key:?} is not under `required` or `optional`"));
}
if text.trim().is_empty() || text.chars().count() > MAX_CAPABILITY_REASON {
return Err(format!(
"capabilities.reasons: the reason for {key:?} must be 1 to {MAX_CAPABILITY_REASON} characters"
));
}
}
for cap in self.capabilities.required.iter().chain(&self.capabilities.optional) {
if matches!(
cap,
@@ -762,6 +816,33 @@ required = [\"lsp:phoxite\"]
assert_eq!(m.capabilities.optional, [Capability::BuildRead]);
}
#[test]
fn capability_reasons_explain_declared_capabilities_from_api_1_19() {
let caps = "[capabilities]\nrequired = [\"net:Example.com\"]\noptional = [\"clipboard.read\"]\n\
[capabilities.reasons]\n\"net:Example.com\" = \"Fetches the schema.\"\n\
\"clipboard.read\" = \"Imports a log you copied.\"\n";
assert!(err(&format!("{}{caps}", BASE.replace("^1.2", "^1.18"))).contains("new in plugin API 1.19"));
let src = |caps: &str| format!("{}{caps}", BASE.replace("^1.2", "^1.19"));
let m = Manifest::parse(&src(caps)).unwrap();
// Keyed as the capability prints.
assert_eq!(m.capabilities.reason(&Capability::Net("example.com".into())), Some("Fetches the schema."));
assert_eq!(m.capabilities.reason(&Capability::ClipboardRead), Some("Imports a log you copied."));
assert_eq!(m.capabilities.reason(&Capability::ProjectRead), None);
let undeclared =
"[capabilities]\nrequired = [\"project.read\"]\n[capabilities.reasons]\n\"project.write\" = \"x\"\n";
assert!(err(&src(undeclared)).contains("not under `required` or `optional`"));
let invalid = "[capabilities]\nrequired = [\"project.read\"]\n[capabilities.reasons]\n\"teleport\" = \"x\"\n";
assert!(err(&src(invalid)).contains("capabilities.reasons"));
let empty = "[capabilities]\nrequired = [\"project.read\"]\n[capabilities.reasons]\n\"project.read\" = \" \"\n";
assert!(err(&src(empty)).contains("1 to 500 characters"));
let long = format!(
"[capabilities]\nrequired = [\"project.read\"]\n[capabilities.reasons]\n\"project.read\" = \"{}\"\n",
"x".repeat(MAX_CAPABILITY_REASON + 1)
);
assert!(err(&src(&long)).contains("1 to 500 characters"));
}
#[test]
fn the_clipboard_read_capability_needs_api_1_11() {
let caps = "[capabilities]\noptional = [\"clipboard.read\"]\n";
@@ -1005,4 +1086,27 @@ mod net_ask_api_tests {
}
}
}
#[test]
fn doc_files_require_api_1_18_and_relative_paths() {
for field in ["description-file", "change-notes-file"] {
for engine in ["^1.17", "^1.18"] {
let manifest = format!(
"id = 'test'\nname = 'Test'\nversion = '0.1.0'\nengines.openidea = '{engine}'\n{field} = 'docs.md'\n"
);
let parsed = Manifest::parse(&manifest);
if engine == "^1.18" {
parsed.unwrap();
} else {
assert!(parsed.unwrap_err().contains("new in plugin API 1.18"), "{field} {engine}");
}
}
for bad in ["../escape.md", "/abs/path.md"] {
let manifest = format!(
"id = 'test'\nname = 'Test'\nversion = '0.1.0'\nengines.openidea = '^1.18'\n{field} = '{bad}'\n"
);
assert!(Manifest::parse(&manifest).unwrap_err().contains("relative path"), "{field} {bad}");
}
}
}
}
+9
Переглянути файл
@@ -27,6 +27,7 @@ use crate::MANIFEST_FILE;
use base64::Engine as _;
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::io::{Read, Write};
use std::path::{Component, Path, PathBuf};
@@ -331,6 +332,9 @@ pub struct IndexEntry {
pub version: String,
#[serde(default)]
pub description: String,
/// Localized descriptions keyed by BCP 47 language tag (e.g. `zh-CN`).
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub description_locales: BTreeMap<String, String>,
#[serde(default)]
pub authors: Vec<String>,
pub publisher: String,
@@ -358,6 +362,9 @@ pub struct IndexEntry {
/// This version's release notes (the manifest's `change-notes`).
#[serde(default)]
pub notes: Option<String>,
/// Localized release notes keyed by BCP 47 language tag (e.g. `zh-CN`).
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub notes_locales: BTreeMap<String, String>,
/// Downloads of the plugin's packages, as counted by whoever serves them.
#[serde(default)]
pub downloads: Option<u64>,
@@ -715,6 +722,7 @@ mod tests {
name: id.into(),
version: "1.0.0".into(),
description: String::new(),
description_locales: BTreeMap::new(),
authors: Vec::new(),
publisher: publisher.into(),
download: format!("https://example.com/{id}.oiplugin"),
@@ -725,6 +733,7 @@ mod tests {
icon: None,
homepage: None,
notes: None,
notes_locales: BTreeMap::new(),
downloads: None,
featured: false,
suggest: Vec::new(),
+65 -4
Переглянути файл
@@ -111,7 +111,17 @@ pub fn availability(root: &Path) -> GhAvailability {
let login = login.ok().and_then(Result::ok).map(|l| l.trim().to_owned()).filter(|l| !l.is_empty());
match repo {
Ok(Ok(out)) if out.success => match parse_repo(&out.stdout) {
Ok(repo) => GhAvailability::Ready { repo, login },
Ok(repo) => {
// The login above is github.com's; an Enterprise repository has its own.
let login = match url_host(&repo.url).filter(|h| !h.eq_ignore_ascii_case("github.com")) {
Some(host) => run(root, &["api", "--hostname", host, "user", "--jq", ".login"])
.ok()
.map(|l| l.trim().to_owned())
.filter(|l| !l.is_empty()),
None => login,
};
GhAvailability::Ready { repo, login }
}
Err(e) => GhAvailability::Error { message: format!("unexpected gh output: {e}") },
},
Ok(Ok(out)) => classify_failure(if out.stderr.trim().is_empty() { &out.stdout } else { &out.stderr }),
@@ -286,6 +296,10 @@ pub struct GhApiRequest {
pub body: Option<String>,
/// Follow REST `Link` pages; the result is the array of all pages (`--slurp`).
pub paginate: bool,
/// The repository's GitHub host (`ghe.example.com`); none: gh's default host. `gh api`
/// doesn't take the host from the remote as `gh pr` does.
#[serde(default)]
pub host: Option<String>,
}
const METHODS: &[&str] = &["GET", "POST", "PATCH", "PUT", "DELETE"];
@@ -301,6 +315,13 @@ pub fn api_args(req: &GhApiRequest) -> IdeResult<Vec<String>> {
return Err(IdeError::invalid(format!("not a GitHub API endpoint: {endpoint}")));
}
let mut args: Vec<String> = vec!["api".into(), "--method".into(), method, endpoint.into()];
if let Some(host) = req.host.as_deref().map(str::trim).filter(|h| !h.is_empty()) {
if !is_host(host) {
return Err(IdeError::invalid(format!("not a GitHub host: {host}")));
}
args.push("--hostname".into());
args.push(host.into());
}
if req.body.is_some() {
args.push("--input".into());
args.push("-".into());
@@ -312,14 +333,45 @@ pub fn api_args(req: &GhApiRequest) -> IdeResult<Vec<String>> {
Ok(args)
}
/// `host` or `host:port`, as gh's `--hostname` takes it.
fn is_host(host: &str) -> bool {
let (name, port) = host.split_once(':').unwrap_or((host, "1"));
!name.is_empty()
&& !name.starts_with(['-', '.'])
&& name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.')
&& !port.is_empty()
&& port.bytes().all(|b| b.is_ascii_digit())
}
/// The host of a repository URL from gh (`https://ghe.example.com/o/r` → `ghe.example.com`).
pub fn url_host(url: &str) -> Option<&str> {
let rest = url.split_once("://")?.1;
let host = rest.split('/').next()?;
let host = host.rsplit_once('@').map_or(host, |(_, h)| h);
is_host(host).then_some(host)
}
/// Runs `req`; returns the response body (JSON text, empty for `204 No Content`).
pub fn api(root: &Path, req: &GhApiRequest) -> IdeResult<String> {
let args = api_args(req)?;
let refs: Vec<&str> = args.iter().map(String::as_str).collect();
let out = process::run_with_input(command(root, &refs)?, req.body.as_deref(), QUICK, None)?;
let mut args = api_args(req)?;
let run = |args: &[String]| {
let refs: Vec<&str> = args.iter().map(String::as_str).collect();
process::run_with_input(command(root, &refs)?, req.body.as_deref(), QUICK, None)
};
let mut out = run(&args)?;
// Recent gh refuses plain-text bodies with terminal escape sequences (coloured Actions job
// logs) unless allowed; older gh lacks the flag. Only a GET is safe to send twice.
if !out.success && req.method.eq_ignore_ascii_case("GET") && refused_escape_sequences(&out.stderr) {
args.insert(1, "--allow-escape-sequences".into());
out = run(&args)?;
}
if out.success { Ok(out.stdout) } else { Err(failure(&out.stderr, &out.stdout)) }
}
fn refused_escape_sequences(stderr: &str) -> bool {
stderr.contains("--allow-escape-sequences")
}
/// Revisions to diff a pull request's files with, present in the local repository.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -374,6 +426,15 @@ pub fn prepare_diff(
#[cfg(test)]
mod tests {
#[test]
fn recognises_gh_refusing_escape_sequences() {
// gh 2.104's message for a coloured Actions job log.
assert!(super::refused_escape_sequences(
"the response contains terminal escape sequences; pass --allow-escape-sequences to output it anyway\n"
));
assert!(!super::refused_escape_sequences("gh: Not Found (HTTP 404)"));
}
#[test]
fn gh_executable_picks_up_newly_installed_binary_without_restart() {
let dir = std::env::temp_dir().join(format!("openidea-gh-test-{}", std::process::id()));
+24 -2
Переглянути файл
@@ -101,14 +101,28 @@ fn list_arguments() {
#[test]
fn api_arguments() {
let req =
GhApiRequest { method: "post".into(), endpoint: "graphql".into(), body: Some("{}".into()), paginate: false };
let req = GhApiRequest {
method: "post".into(),
endpoint: "graphql".into(),
body: Some("{}".into()),
paginate: false,
host: None,
};
assert_eq!(api_args(&req).unwrap(), ["api", "--method", "POST", "graphql", "--input", "-"]);
let ghe = GhApiRequest { host: Some("ghe.example.com:8443".into()), ..req.clone() };
assert_eq!(
api_args(&ghe).unwrap(),
["api", "--method", "POST", "graphql", "--hostname", "ghe.example.com:8443", "--input", "-"]
);
for bad in ["--x", "evil.example/x", "a b", ".x", "h:", "h:8x"] {
assert!(api_args(&GhApiRequest { host: Some(bad.into()), ..req.clone() }).is_err(), "{bad}");
}
let req = GhApiRequest {
method: "GET".into(),
endpoint: "repos/{owner}/{repo}/labels".into(),
body: None,
paginate: true,
host: Some(" ".into()),
};
assert_eq!(
api_args(&req).unwrap(),
@@ -119,3 +133,11 @@ fn api_arguments() {
}
assert!(api_args(&GhApiRequest { method: "TRACE".into(), ..req }).is_err());
}
#[test]
fn repository_url_hosts() {
assert_eq!(url_host("https://ghe.example.com/acme/app"), Some("ghe.example.com"));
assert_eq!(url_host("https://github.com/o/r"), Some("github.com"));
assert_eq!(url_host("https://[email protected]:8443/o/r"), Some("ghe.example.com:8443"));
assert_eq!(url_host("ghe.example.com/o/r"), None);
}
+1
Переглянути файл
@@ -28,6 +28,7 @@ ide-syntax.workspace = true
ide-search.workspace = true
ide-lsp.workspace = true
ide-vcs.workspace = true
ide-github.workspace = true
ide-dap.workspace = true
ide-heap.workspace = true
ide-jvm-attach.workspace = true
+66 -4
Переглянути файл
@@ -22,7 +22,9 @@
mod templates;
use ide_extension::{Manifest, validate_plugin_id};
use ide_host::plugins::{PluginHost, market_href_reachable_from, plugin_icon, read_market_url, resolve_market_href};
use ide_host::plugins::{
PluginHost, market_href_reachable_from, plugin_docs, plugin_icon, read_market_url, resolve_market_href,
};
use ide_plugin::{Limits, PluginEngine};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
@@ -641,12 +643,15 @@ fn cmd_index(args: &[String]) -> Result<(), String> {
Some(wasm) => engine.check_component(&engine.compile(&scratch.join(wasm))?)?,
None => None,
};
let pkg = ide_extension::Package::new(m.clone(), scratch.clone());
let docs = plugin_docs(&pkg)?;
let file = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
Ok::<_, String>(IndexEntry {
id: m.id.clone(),
name: m.name.clone(),
version: m.version.clone(),
description: m.description.clone(),
description: docs.description,
description_locales: docs.description_locales,
authors: m.authors.clone(),
publisher: signer,
download: base.map_or_else(|| file.clone(), |b| format!("{b}/{file}")),
@@ -654,9 +659,10 @@ fn cmd_index(args: &[String]) -> Result<(), String> {
capabilities: m.capabilities.all().map(|c| c.to_string()).collect(),
engine: package::engine_requirement(&m.engine, built_for.as_ref()),
categories: m.categories(),
icon: plugin_icon(&ide_extension::Package::new(m.clone(), scratch.clone()))?,
icon: plugin_icon(&pkg)?,
homepage: m.homepage.clone().filter(|h| !h.trim().is_empty()),
notes: m.change_notes.clone().filter(|n| !n.trim().is_empty()),
notes: docs.change_notes.filter(|n| !n.trim().is_empty()),
notes_locales: docs.change_notes_locales,
downloads: None,
featured: false,
suggest: Vec::new(),
@@ -1078,6 +1084,62 @@ mod tests {
assert!(index.plugins[0].icon.as_ref().expect("icon").light.contains("<rect"));
}
#[test]
fn check_validates_markdown_doc_files_and_index_carries_localized_docs() {
let tmp = tempfile::tempdir().unwrap();
let t = tmp.path();
let key = t.join("acme.key");
std::fs::write(&key, PublisherKey::from_seed([7; 32]).seed_base64()).unwrap();
let src = t.join("src");
let vars = templates::Vars { id: "acme.docs", name: "Docs", sdk: None };
for (rel, content) in templates::render(templates::Template::Theme, &vars) {
let path = src.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, content).unwrap();
}
let manifest = std::fs::read_to_string(src.join("plugin.toml"))
.unwrap()
.replace("engines.openidea = \"^1.0\"", "engines.openidea = \"^1.18\"");
std::fs::write(
src.join("plugin.toml"),
format!("description-file = \"description.md\"\nchange-notes-file = \"CHANGELOG.md\"\n{manifest}"),
)
.unwrap();
// Missing md file fails `check`.
let err = check(&src).unwrap_err();
assert!(err.contains("no such file"), "{err}");
// Valid English + zh-CN md files pass `check`, `pack`, and `index`.
std::fs::write(src.join("description.md"), "# English\n\n- Fast\n").unwrap();
std::fs::write(src.join("description.zh-CN.md"), "# 中文\n\n- 快速\n").unwrap();
std::fs::write(src.join("CHANGELOG.md"), "## 0.1.0\n\n- First release\n").unwrap();
std::fs::write(src.join("CHANGELOG.zh-CN.md"), "## 0.1.0\n\n- 首次发布\n").unwrap();
check(&src).unwrap();
let out = t.join("out");
std::fs::create_dir_all(&out).unwrap();
let (src_str, key_str) = (src.to_string_lossy().into_owned(), key.to_string_lossy().into_owned());
let package = out.join("acme.docs-0.1.0.oiplugin").to_string_lossy().into_owned();
cmd_pack(&strings(&[&src_str, "--key", &key_str, "--publisher", "acme", "--out", &package])).unwrap();
cmd_index(&strings(&[out.to_str().unwrap(), "--publisher", "acme", "--key", &key_str])).unwrap();
let index = Index::parse(&std::fs::read_to_string(out.join("index.json")).unwrap()).unwrap();
let entry = &index.plugins[0];
assert!(entry.description.contains("# English"));
assert_eq!(entry.description_locales.get("zh-CN").map(String::as_str), Some("# 中文\n\n- 快速\n"));
assert_eq!(entry.notes.as_deref(), Some("## 0.1.0\n\n- First release\n"));
assert_eq!(entry.notes_locales.get("zh-CN").map(String::as_str), Some("## 0.1.0\n\n- 首次发布\n"));
// Invalid extension fails `check`.
std::fs::write(src.join("notes.txt"), "plain").unwrap();
let bad = std::fs::read_to_string(src.join("plugin.toml"))
.unwrap()
.replace("change-notes-file = \"CHANGELOG.md\"", "change-notes-file = \"notes.txt\"");
std::fs::write(src.join("plugin.toml"), bad).unwrap();
let err = check(&src).unwrap_err();
assert!(err.contains(".md or .markdown"), "{err}");
}
/// `cargo test` of a new Rust plugin (its own tests against the mock host) with this SDK.
#[test]
fn the_command_template_builds_against_the_sdk() {
+9 -2
Переглянути файл
@@ -406,8 +406,14 @@ pub async fn serve(
let result = loop {
tokio::select! {
_ = shutdown.cancelled() => break Ok(()),
_ = terminate.recv() => break Ok(()),
_ = shutdown.cancelled() => {
host.set_agent_shutdown_reason(ide_agent::AgentShutdownReason::BackendStop);
break Ok(());
}
_ = terminate.recv() => {
host.set_agent_shutdown_reason(ide_agent::AgentShutdownReason::BackendUpgrade);
break Ok(());
}
_ = async {
match &active {
Some(peer) => { peer.closed().await; }
@@ -445,6 +451,7 @@ pub async fn serve(
if busy {
let _ = stream.write_u8(BUSY).await;
} else if stream.write_u8(RETIRING).await.is_ok() {
host.set_agent_shutdown_reason(ide_agent::AgentShutdownReason::BackendUpgrade);
retiring = Some(stream);
break Ok(());
}
+76
Переглянути файл
@@ -14,6 +14,65 @@ pub const DATA_ENV: &str = "OPENIDEA_DATA_DIR";
/// Moves the logs.
pub const LOG_ENV: &str = "OPENIDEA_LOG_DIR";
/// A portable install's settings file, next to the executable: `NAME=value` lines setting the
/// variables above (and only those), so the install needs no environment. A variable already set
/// in the environment wins; a relative value is taken from the file's folder.
pub const PROPERTIES_FILE: &str = "openidea.properties";
/// The folder `openidea.properties` is read from: the executable's, the AppImage file's when run
/// from one, the folder holding the `.app` bundle on macOS.
fn install_dir() -> Option<PathBuf> {
let exe = std::env::current_exe().ok()?;
// `APPIMAGE` is inherited by everything started from inside one; only trust it for the
// executable it mounted.
let appdir = std::env::var_os("APPDIR").filter(|v| !v.is_empty());
if let (Some(image), Some(appdir)) = (std::env::var_os("APPIMAGE").filter(|v| !v.is_empty()), appdir)
&& exe.starts_with(appdir)
{
return PathBuf::from(image).parent().map(Path::to_path_buf);
}
let dir = exe.parent()?;
if cfg!(target_os = "macos")
&& let Some(bundle) = dir.ancestors().nth(2).filter(|b| b.extension().is_some_and(|e| e == "app"))
{
return bundle.parent().map(Path::to_path_buf);
}
Some(dir.to_path_buf())
}
/// The variables an `openidea.properties` in `dir` sets, made absolute, leaving out those
/// `is_set` reports the environment already has. Unknown keys and comments (`#`, `!`) are ignored.
fn properties_in(dir: &Path, text: &str, is_set: impl Fn(&str) -> bool) -> Vec<(&'static str, PathBuf)> {
let mut out: Vec<(&'static str, PathBuf)> = Vec::new();
for line in text.lines().map(str::trim) {
if line.starts_with(['#', '!']) {
continue;
}
let Some((key, value)) = line.split_once('=') else { continue };
let (key, value) = (key.trim(), value.trim());
let Some(name) = [CONFIG_ENV, DATA_ENV, LOCAL_DATA_ENV, LOG_ENV].into_iter().find(|n| *n == key) else {
continue;
};
if value.is_empty() || is_set(name) || out.iter().any(|(n, _)| *n == name) {
continue;
}
// An absolute value replaces `dir`.
out.push((name, dir.join(value)));
}
out
}
/// Applies the install's `openidea.properties` to the environment, so the directories below and
/// every process the IDE starts see the same locations. Call first thing in `main`.
pub fn load_properties_file() {
let Some(dir) = install_dir() else { return };
let Ok(text) = fs::read_to_string(dir.join(PROPERTIES_FILE)) else { return };
for (name, value) in properties_in(&dir, &text, |n| std::env::var_os(n).is_some_and(|v| !v.is_empty())) {
// SAFETY: called at the start of `main`, before any other thread exists.
unsafe { std::env::set_var(name, value) };
}
}
/// `$OPENIDEA_CONFIG_DIR/<identifier>` when set, else the OS configuration directory
/// (Tauri's `app_config_dir`). Like the local data, the identifier keeps release and
/// per-worktree debug builds apart under one root; a relative path is an error.
@@ -664,6 +723,23 @@ mod tests {
assert!(!tmp.path().join("copy/Default/Cache").exists());
}
#[test]
fn a_properties_file_sets_the_directory_variables_relative_to_its_folder() {
let dir = std::env::temp_dir().join("portable");
let abs = std::env::temp_dir().join("elsewhere");
let text = format!(
"# portable install\n! also a comment\nOPENIDEA_CONFIG_DIR = data\nOPENIDEA_DATA_DIR=data\n\
OPENIDEA_LOCAL_DATA_DIR={}\nOPENIDEA_LOG_DIR=\nOPENIDEA_CONFIG_DIR=ignored\nPATH=/bin\nnot a pair\n",
abs.display()
);
let set = properties_in(&dir, &text, |_| false);
assert_eq!(set, [(CONFIG_ENV, dir.join("data")), (DATA_ENV, dir.join("data")), (LOCAL_DATA_ENV, abs.clone())]);
// The environment wins over the file.
let set = properties_in(&dir, &text, |n| n == CONFIG_ENV);
assert_eq!(set.iter().map(|(n, _)| *n).collect::<Vec<_>>(), [DATA_ENV, LOCAL_DATA_ENV]);
assert!(set.iter().all(|(_, v)| v.is_absolute()));
}
#[test]
fn config_data_and_log_dirs_follow_the_os_unless_their_variable_is_set() {
let os = Some(PathBuf::from("/os"));
+65 -7
Переглянути файл
@@ -108,6 +108,7 @@ pub struct Host {
pub data_dir: PathBuf,
/// Machine-local tools and rebuildable caches.
pub local_data_dir: PathBuf,
home_dir: Option<PathBuf>,
pub languages: Arc<LanguageRegistry>,
syntax: Arc<OnceLock<Arc<Syntax>>>,
pub global_settings: SettingsStore,
@@ -139,6 +140,8 @@ pub struct Host {
pub web: ide_web::WebServer,
/// The HTTP proxy's saved password (see `proxy.rs`).
proxy_password: ide_ssh::secrets::SecretFile,
/// Tokens of the Jupyter servers notebooks run on, by server base URL.
jupyter_tokens: ide_ssh::secrets::SecretFile,
/// The proxy password when it could not be saved (no credential store).
proxy_session_password: Mutex<Option<String>>,
/// Values of agents' and MCP servers' environment variables and headers (see `agent_secrets.rs`).
@@ -153,6 +156,8 @@ pub struct Host {
project_requests: RwLock<HashMap<String, Vec<RequestId>>>,
/// Shutdowns of projects closed with [`Host::close_project_detached`].
closing: parking_lot::Mutex<Vec<DetachedClose>>,
/// Why this host's agents are shutting down when [`Host::shutdown`] runs.
agent_shutdown_reason: parking_lot::Mutex<ide_agent::AgentShutdownReason>,
/// One open at a time per window (see [`Host::opening`]).
open_locks: parking_lot::Mutex<HashMap<String, Arc<parking_lot::Mutex<()>>>>,
}
@@ -168,6 +173,7 @@ struct ShutdownWork {
lsp: Option<Arc<ide_lsp::LspManager>>,
debug: Option<(Arc<ide_dap::DebugManager>, String, Option<std::path::PathBuf>)>,
agents: Vec<Arc<ide_agent::AgentManager>>,
agent_reason: ide_agent::AgentShutdownReason,
terminals: Option<ide_terminal::DetachedTerminals>,
processes: Option<ide_run::DetachedProcessKills>,
retired: Option<Arc<Project>>,
@@ -201,6 +207,11 @@ impl Host {
self
}
/// User home directory used by agent memory discovery.
pub fn home_dir(&self) -> Option<PathBuf> {
self.home_dir.clone()
}
pub fn new(config: HostConfig) -> Self {
let HostConfig {
config_dir,
@@ -235,6 +246,7 @@ impl Host {
trust: std::sync::Arc::new(trust::TrustStore::load(&config_dir, &data_dir)),
mcp_approvals: Arc::new(trust::McpServerApprovals::load(&data_dir)),
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
jupyter_tokens: ide_ssh::secrets::SecretFile::new(data_dir.join("jupyter-tokens.json")),
proxy_session_password: Mutex::default(),
agent_secrets: Arc::new(agent_secrets::AgentSecrets::new(&data_dir)),
remote: Arc::new(ide_remote::RemoteService::new(ssh.clone(), data_dir.join("remote"))),
@@ -262,6 +274,7 @@ impl Host {
config_dir,
data_dir,
local_data_dir,
home_dir: dirs::home_dir(),
sink_for,
owner,
runtime,
@@ -270,6 +283,7 @@ impl Host {
requests: Default::default(),
project_requests: RwLock::default(),
closing: Default::default(),
agent_shutdown_reason: parking_lot::Mutex::new(ide_agent::AgentShutdownReason::Quit),
open_locks: Default::default(),
};
host.apply_proxy();
@@ -356,13 +370,18 @@ impl Host {
}
}
/// Records the shutdown reason reported on interrupted agent turns when [`Self::shutdown`] runs.
pub fn set_agent_shutdown_reason(&self, reason: ide_agent::AgentShutdownReason) {
*self.agent_shutdown_reason.lock() = reason;
}
/// Closes `window`'s project and waits until its language servers, kernels and
/// debug sessions have shut down. Never call this on the UI event-loop thread:
/// the shutdown runs on the async runtime, whose workers may themselves be
/// waiting for the event loop (IPC responses, window queries). Use
/// [`Self::close_project_detached`] there.
pub fn close_project(&self, window: &str) {
if let Some(shutdown) = self.begin_close(window) {
if let Some(shutdown) = self.begin_close(window, ide_agent::AgentShutdownReason::WindowClose) {
self.wait_blocking(shutdown.handle);
}
}
@@ -371,7 +390,12 @@ impl Host {
/// the window; its workers finish shutting down in the background, and
/// [`Self::shutdown_notebooks_on_exit`] waits for them before the process exits.
pub fn close_project_detached(&self, window: &str) {
if let Some(shutdown) = self.begin_close(window) {
self.close_project_detached_with(window, ide_agent::AgentShutdownReason::WindowClose);
}
/// Like [`Self::close_project_detached`], recording `reason` on any interrupted agent turn.
pub fn close_project_detached_with(&self, window: &str, reason: ide_agent::AgentShutdownReason) {
if let Some(shutdown) = self.begin_close(window, reason) {
let mut closing = self.closing.lock();
closing.retain(|entry| !entry.handle.is_finished());
closing.push(shutdown);
@@ -381,18 +405,25 @@ impl Host {
/// Detaches the project from `window` synchronously so the caller (including the UI
/// event-loop thread) never blocks on disk I/O or process shutdown, and returns the
/// background handle that stops its workers, agents, terminals and processes.
fn begin_close(&self, window: &str) -> Option<DetachedClose> {
fn begin_close(&self, window: &str, agent_reason: ide_agent::AgentShutdownReason) -> Option<DetachedClose> {
self.mcp_reports.forget_window(window);
self.mcp_requests.forget_window(window);
self.mcp_agent_runs.forget_window(window);
self.debugger.forget_breakpoints(self.owner_window(window));
self.external_logs.write().remove(self.owner_window(window));
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
let owner = self.owner_window(window);
let (project, requests) = {
// A request registering after the drain must not resolve the old project.
let mut project_requests = self.project_requests.write();
let mut projects = self.projects.write();
(projects.remove(window), project_requests.remove(owner).unwrap_or_default())
};
for request in requests {
self.cancel_request(request);
}
// After the cancels: a capture or open still running then discards what it registers.
ops::heap::close_window_snapshots(self, window);
let project = self.projects.write().remove(window)?;
let project = project?;
project.closed.cancel();
if let Some(plugins) = self.plugin_host() {
if self.windows_for_root(&project.root).is_empty() {
@@ -453,6 +484,7 @@ impl Host {
// Debug sessions under the root belong to windows: a project served without one starts none.
debug: Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
agents: vec![project.agents.clone()],
agent_reason,
terminals: Some(terminals),
processes: Some(processes),
retired: Some(project),
@@ -480,9 +512,10 @@ impl Host {
}
let agents = (!work.agents.is_empty()).then(|| {
let agents = work.agents;
let reason = work.agent_reason;
std::thread::spawn(move || {
for manager in agents {
manager.shutdown();
manager.shutdown_with(reason);
}
})
});
@@ -573,6 +606,10 @@ impl Host {
/// kernels and agents, but no longer than [`EXIT_SHUTDOWN_WAIT`], so a runtime worker
/// stuck on the event loop cannot keep the process from exiting.
pub fn shutdown_notebooks_on_exit(&self) {
self.shutdown_notebooks_on_exit_with(ide_agent::AgentShutdownReason::Quit);
}
pub fn shutdown_notebooks_on_exit_with(&self, agent_reason: ide_agent::AgentShutdownReason) {
let projects = self.projects();
let mut pending: Vec<_> = self.closing.lock().drain(..).map(|entry| entry.handle).collect();
if !projects.is_empty() {
@@ -582,6 +619,7 @@ impl Host {
lsp: None,
debug: None,
agents: projects.iter().map(|project| project.agents.clone()).collect(),
agent_reason,
terminals: None,
processes: None,
retired: None,
@@ -670,7 +708,8 @@ impl Host {
}
project.documents.clear_workspace_edit_history();
project.notebooks.stop_admission();
project.agents.shutdown();
let reason = *self.agent_shutdown_reason.lock();
project.agents.shutdown_with(reason);
}
let stop_processes = async {
for project in &projects {
@@ -766,6 +805,25 @@ impl Host {
let exe = self.global_settings.read_effective(|s| s.vcs.git.executable.trim().to_owned());
ide_vcs::set_default_git_executable((!exe.is_empty()).then(|| Path::new(&exe)));
}
/// Settings › Version Control › Git › Enable Git integration, as it applies to `window`
/// (its project's effective value, the global one without a project).
pub fn git_enabled(&self, window: &str) -> bool {
match self.project(window) {
Ok(project) => project.git_enabled(),
Err(_) => self.global_settings.read_effective(|s| s.vcs.git.enabled),
}
}
/// Fails while Git integration is switched off for `window`: commands that start git
/// outside the project's repositories (clone, init, an external log) check it first.
pub fn ensure_git_enabled(&self, window: &str) -> IdeResult<()> {
if self.git_enabled(window) {
Ok(())
} else {
Err(ide_core::IdeError::unavailable("Git integration is disabled in Settings › Version Control › Git"))
}
}
}
#[cfg(test)]
File diff suppressed because it is too large. Load diff
+19 -5
Переглянути файл
@@ -1,6 +1,7 @@
//! Built-in IDE tools. Transport and discovery live in `ide-mcp`.
mod background;
mod check;
mod debug;
mod edit;
mod editors;
mod requests;
@@ -43,6 +44,7 @@ fn tools() -> Vec<tool::Tool> {
tools.extend(search::tools());
tools.extend(editors::tools());
tools.push(check::check_files());
tools.extend(debug::tools());
tools.push(symbols::get_symbol_info());
tools.push(symbols::find_references());
tools.push(symbols::get_call_hierarchy());
@@ -58,6 +60,22 @@ fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
trusted || tool.read_only
}
fn tools_for(host: &Host, root: &Path, trusted: bool) -> Vec<ide_mcp::Tool> {
let mut all: Vec<_> = tools().into_iter().map(|t| t.metadata).collect();
if let Some(plugins) = host.plugin_host() {
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| tool));
}
all.into_iter().filter(|t| allowed(t, trusted)).collect()
}
/// Lists the built-in IDE and plugin-contributed MCP tools visible to `window`.
pub(crate) fn list_tools_for_window(host: &Host, window: &str) -> Vec<ide_mcp::Tool> {
match host.project(window).ok().filter(|p| !p.light) {
Some(project) => tools_for(host, &project.root, project.is_trusted()),
None => tools_for(host, Path::new(""), true),
}
}
impl Registry {
/// The window that answers for `root`: one with the root open, or one it is attached in.
fn window(&self, root: &Path) -> Result<Option<(String, Arc<crate::Project>)>, String> {
@@ -125,11 +143,7 @@ impl ToolRegistry for Registry {
}
fn tools(&self, root: &Path) -> Result<Vec<ide_mcp::Tool>, String> {
let trusted = self.lists_as_trusted(root)?;
let mut all: Vec<_> = tools().into_iter().map(|t| t.metadata).collect();
if let Some(plugins) = self.0.plugin_host() {
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| tool));
}
Ok(all.into_iter().filter(|t| allowed(t, trusted)).collect())
Ok(tools_for(&self.0, root, trusted))
}
fn call(
&self,
+24 -2
Переглянути файл
@@ -15,6 +15,7 @@ struct State {
struct Pending {
window: String,
answer: oneshot::Sender<Result<bool, String>>,
value: oneshot::Sender<Option<String>>,
}
impl Requests {
pub fn set_ready(&self, window: &str, ready: bool) {
@@ -30,11 +31,23 @@ impl Requests {
state.pending.retain(|_, p| p.window != window);
}
pub fn answer(&self, window: &str, id: u32, allow: bool, error: Option<String>) -> IdeResult<()> {
self.answer_with(window, id, allow, error, None)
}
/// A request can also answer with a value, e.g. the id of the debug session it started.
pub fn answer_with(
&self,
window: &str,
id: u32,
allow: bool,
error: Option<String>,
value: Option<String>,
) -> IdeResult<()> {
let mut state = self.0.lock();
if !state.pending.get(&id).is_some_and(|p| p.window == window) {
return Err(IdeError::invalid("MCP request expired or belongs to another window"));
}
let pending = state.pending.remove(&id).unwrap();
let _ = pending.value.send(value);
let _ = pending.answer.send(error.map_or(Ok(allow), Err));
Ok(())
}
@@ -44,14 +57,23 @@ impl Requests {
}
pub(super) async fn ask(&self, call: &Call, request: McpUiRequest) -> IdeResult<()> {
self.ask_inner(call, request).await.map(|_| ())
}
pub(super) async fn ask_value(&self, call: &Call, request: McpUiRequest) -> IdeResult<Option<String>> {
self.ask_inner(call, request).await
}
async fn ask_inner(&self, call: &Call, request: McpUiRequest) -> IdeResult<Option<String>> {
let id = super::tool::request_id().0;
let (tx, rx) = oneshot::channel();
let (value_tx, value_rx) = oneshot::channel();
{
let mut state = self.0.lock();
if !state.ready.contains(call.window()) {
return Err(IdeError::unavailable("MCP request denied: no project window is available"));
}
state.pending.insert(id, Pending { window: call.window.clone(), answer: tx });
state.pending.insert(id, Pending { window: call.window.clone(), answer: tx, value: value_tx });
}
struct Close<'a>(&'a Requests, &'a Call, u32);
impl Drop for Close<'_> {
@@ -68,7 +90,7 @@ impl Requests {
_ = call.cancel.cancelled() => return Err(IdeError::cancelled()),
};
match result {
Ok(true) => Ok(()),
Ok(true) => Ok(value_rx.await.unwrap_or(None)),
Ok(false) => Err(IdeError::invalid("MCP request denied by the user")),
Err(message) => Err(IdeError::unavailable(message)),
}
+19 -15
Переглянути файл
@@ -29,14 +29,14 @@ const MAX_PROCESS_OUTPUT_LENGTH: usize = 20_000;
/// A before-launch build gets this long.
const BEFORE_LAUNCH_BUILD_TIMEOUT: Duration = Duration::from_secs(3600);
async fn load_configs(call: &Call) -> IdeResult<Vec<RunConfig>> {
pub(crate) async fn load_configs(call: &Call) -> IdeResult<Vec<RunConfig>> {
let host = call.host();
let window = call.window().to_owned();
let h = host.clone();
host.blocking(move || crate::ops::run::configs(&h, &window)).await
}
fn supports_overrides(config: &RunConfig) -> bool {
pub(crate) fn supports_overrides(config: &RunConfig) -> bool {
config.extras.compound.is_empty() && !config.command.trim().is_empty()
}
@@ -178,13 +178,17 @@ in the file instead of project-wide run configurations.",
.param(Param::optional("offset", ParamType::Integer, OFFSET))
}
/// What `execute_run_configuration` runs.
enum ExecutionTarget {
/// What `execute_run_configuration` and `xdebug_start_debugger_session` run.
pub(crate) enum ExecutionTarget {
ByName(String),
ByContext(String, i64),
}
fn execution_target(name: Option<String>, file: Option<String>, line: Option<i64>) -> IdeResult<ExecutionTarget> {
pub(crate) fn execution_target(
name: Option<String>,
file: Option<String>,
line: Option<i64>,
) -> IdeResult<ExecutionTarget> {
let name = name.filter(|n| !n.trim().is_empty());
let file = file.filter(|f| !f.trim().is_empty());
match (name, file, line) {
@@ -203,7 +207,7 @@ fn execution_target(name: Option<String>, file: Option<String>, line: Option<i64
/// The temporary configuration of the run point at `file:line` (1-based): the innermost target
/// enclosing that line (as JetBrains walks up to the enclosing test), else the whole file's
/// (its tests, its main function).
async fn config_from_code_location(
pub(crate) async fn config_from_code_location(
call: &Call,
configs: Vec<RunConfig>,
file: &str,
@@ -234,7 +238,7 @@ filePath to find valid run locations."
/// Applies the one-off overrides (JetBrains' `prepareRunConfigurationForExecution`): a missing or
/// empty string keeps the value, a whitespace-only one clears it; `envs` merge over the configuration's.
fn apply_overrides(
pub(crate) fn apply_overrides(
config: &mut RunConfig,
root: &Path,
args: Option<String>,
@@ -413,13 +417,13 @@ fn process_output(mut f: impl FnMut(&str) + Send + 'static) -> crate::ops::Chann
/// What failed before launch (JetBrains' `RunConfigurationBuildErrors`): build errors as
/// `path:line: message`, else the output of before-launch processes that failed.
#[derive(Default)]
struct BuildErrors {
errors: Vec<String>,
process_outputs: Vec<String>,
pub(crate) struct BuildErrors {
pub(crate) errors: Vec<String>,
pub(crate) process_outputs: Vec<String>,
}
impl BuildErrors {
fn text(&self) -> Option<String> {
pub(crate) fn text(&self) -> Option<String> {
let mut seen = std::collections::HashSet::new();
let errors: Vec<&String> = self.errors.iter().filter(|e| seen.insert(*e)).collect();
if !errors.is_empty() {
@@ -573,7 +577,7 @@ async fn find_java_module(call: &Call, main: &str) -> IdeResult<Option<String>>
/// built per its before-launch build policy, with `${classpath}` / `${testClasspath}`, the
/// module path and the module's `java` resolved through jdtls. `Err` says why it cannot start
/// (compile errors are added to `errors`). Other configurations are returned as they are.
async fn resolve_jvm_application(
pub(crate) async fn resolve_jvm_application(
call: &Call,
mut config: RunConfig,
errors: &mut BuildErrors,
@@ -639,7 +643,7 @@ async fn resolve_jvm_application(
/// The configuration's before-launch tasks, as the Run tool window runs them; returns why
/// the launch is aborted, if it is. Tool windows are not activated.
async fn before_launch(
pub(crate) async fn before_launch(
call: &Call,
config: &RunConfig,
configs: &[RunConfig],
@@ -754,7 +758,7 @@ fn describe_before_launch(
/// or applies — before-launch tasks, the stored environment (for a configuration made from
/// code, the one of the configuration it derives from), `.env` files, the `envs` overrides
/// (`NODE_OPTIONS`, `PATH`, ...), the stop command and a remote run target.
fn confirmation_detail(
pub(crate) fn confirmation_detail(
config: &RunConfig,
cwd: &str,
stored_env: &std::collections::BTreeMap<String, String>,
@@ -797,7 +801,7 @@ fn confirmation_detail(
detail
}
fn execution_failed(details: &[Option<String>]) -> IdeError {
pub(crate) fn execution_failed(details: &[Option<String>]) -> IdeError {
let details: Vec<&str> = details.iter().flatten().map(String::as_str).collect();
IdeError::invalid(format!("Execution failed: {}", details.join("\n")))
}
+68
Переглянути файл
@@ -246,6 +246,29 @@ pub fn mcp_server_status(host: &Host, window: &str) -> IdeResult<McpServerStatus
})
}
/// Lists the tools advertised by OpenIDEA's built-in MCP server (core IDE tools plus
/// enabled plugin-contributed `mcpTools`) for the window's project.
#[command(trust = always)]
pub fn mcp_server_tools(host: &Host, window: &str) -> IdeResult<ide_agent::McpProbeResult> {
let started = Instant::now();
let tools = super::list_tools_for_window(host, window)
.into_iter()
.map(|tool| ide_agent::McpToolSummary {
name: tool.name,
description: (!tool.description.trim().is_empty()).then_some(tool.description),
})
.collect();
Ok(ide_agent::McpProbeResult {
ok: true,
server_name: Some("OpenIDEA".into()),
server_version: Some(env!("CARGO_PKG_VERSION").into()),
protocol_version: Some(ide_mcp::PROTOCOL_VERSION.into()),
tools,
duration_ms: u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX),
error: None,
})
}
/// Settings › Agents › IDE MCP Server › Regenerate Token: forgets the kept token, and restarts the
/// server with a new one. Clients configured with the old token stop working.
#[command(trust = outside_restricted)]
@@ -299,6 +322,19 @@ pub fn mcp_respond(host: &Host, window: &str, id: u32, allow: bool, error: Optio
host.mcp_requests.answer(host.owner_window(window), id, allow, error)
}
/// Like `mcp_respond`, with a value for requests that ask for one (the started debug session id).
#[command(trust = trusted)]
pub fn mcp_respond_with(
host: &Host,
window: &str,
id: u32,
allow: bool,
error: Option<String>,
value: Option<String>,
) -> IdeResult<()> {
host.mcp_requests.answer_with(host.owner_window(window), id, allow, error, value)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -315,6 +351,36 @@ mod tests {
assert_eq!(port_to_wait_for((local, 51234), Some(64342)), None);
assert_eq!(port_to_wait_for((local, 64342), None), None);
}
#[tokio::test]
async fn mcp_server_tools_lists_core_tools_and_respects_restricted_mode() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let project_dir = base.join("sample");
std::fs::create_dir_all(&project_dir).unwrap();
let host = Arc::new(Host::new(crate::HostConfig::for_test(&base)));
// Without an open project (e.g. Welcome screen Settings), all built-in tools are listed.
let without_project = mcp_server_tools(&host, "welcome").unwrap();
assert!(without_project.ok);
assert_eq!(without_project.server_name.as_deref(), Some("OpenIDEA"));
assert!(without_project.tools.iter().any(|t| t.name == "search_text"));
assert!(without_project.tools.iter().any(|t| t.name == "run_command"));
// Opening an untrusted project filters out write/run tools, matching Registry::tools.
host.open_project("main", &project_dir).unwrap();
let restricted = mcp_server_tools(&host, "main").unwrap();
assert!(restricted.ok);
assert!(restricted.tools.iter().any(|t| t.name == "search_text"));
assert!(!restricted.tools.iter().any(|t| t.name == "run_command"));
assert!(restricted.tools.len() < without_project.tools.len());
// Trusting the project restores the full tool set.
host.set_project_trust(&project_dir, true, false).await.unwrap();
let trusted = mcp_server_tools(&host, "main").unwrap();
assert_eq!(trusted.tools.len(), without_project.tools.len());
assert!(trusted.tools.iter().any(|t| t.name == "run_command"));
}
}
ide_command::domain!(
@@ -323,7 +389,9 @@ ide_command::domain!(
mcp_background_projects,
mcp_regenerate_token,
mcp_respond,
mcp_respond_with,
mcp_server_status,
mcp_server_tools,
mcp_ui_ready,
mcp_unload_background_project,
);
+4
Переглянути файл
@@ -70,6 +70,10 @@ impl Call {
pub async fn ask(&self, request: ide_core::event::McpUiRequest) -> IdeResult<()> {
self.host.mcp_requests.ask(self, request).await
}
/// A window request that answers with a value, e.g. the debug session it started.
pub async fn ask_value(&self, request: ide_core::event::McpUiRequest) -> IdeResult<Option<String>> {
self.host.mcp_requests.ask_value(self, request).await
}
/// Whether the project has a window to show what the tool starts (not one loaded for MCP alone).
pub fn has_window(&self) -> bool {
self.host.mcp_requests.window_ready(&self.window)
+2
Переглянути файл
@@ -251,6 +251,7 @@ fn git_status() -> Tool {
Returns porcelain-style index/worktree status codes and summary counters.
By default all Git repositories are returned.",
|call| async move {
call.host.ensure_git_enabled(&call.window)?;
let include_untracked = call.flag("includeUntracked", true)?;
let include_ignored = call.flag("includeIgnored", false)?;
let page = Page::of(&call, STATUS_DEFAULT_LIMIT)?;
@@ -360,6 +361,7 @@ By default all Git repositories are returned.",
fn git_diff() -> Tool {
Tool::new("git_diff", "Read a Git diff for a file or the working tree. staged=true compares the index with HEAD; otherwise compares disk with the index. Unsaved editor text is not part of this diff.", |call| async move {
call.host.ensure_git_enabled(&call.window)?;
let wanted = call.opt_str("repositoryPathRelativeToProject")?;
let path = wanted.as_deref().map(|p| call.resolve_inside(p)).transpose()?.unwrap_or_else(|| call.root().to_path_buf());
let root = find_git_root(call.root(), &path).ok_or_else(|| IdeError::not_found("No git repository found"))?;
+179 -24
Переглянути файл
@@ -9,12 +9,21 @@ use std::path::Path;
/// Prefix of Open Recent item ids; the rest of the id is the project path.
pub const RECENT_PREFIX: &str = "recent:";
/// Item id of the local-projects section header in Open Recent.
pub const RECENT_LOCAL_ID: &str = "recent.local";
/// Prefix of remote host section header ids in Open Recent.
pub const RECENT_SECTION_PREFIX: &str = "recent.section:";
/// Prefix of items the frontend lists ([`MenuConfig::dynamic`]): `dyn:<action>` or `dyn:<action>|<arg>`.
pub const DYNAMIC_PREFIX: &str = "dyn:";
/// Action run for an Open Recent entry (argument: the project path).
pub const OPEN_RECENT_ACTION: &str = "file.openRecentProject";
pub const MAX_RECENT: usize = 15;
/// Whether `id` names a non-interactive Open Recent placeholder or section header.
pub fn is_recent_placeholder(id: &str) -> bool {
id == "recent.none" || id == RECENT_LOCAL_ID || id.starts_with(RECENT_SECTION_PREFIX)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Os {
Mac,
@@ -164,6 +173,21 @@ pub const DYNAMIC_PLUGIN_TOOLS: &str = "pluginTools";
pub const DYNAMIC_FLUTTER_BUILD: &str = "flutterBuild";
/// Id (and `menu.` label key) of the Build › Flutter submenu.
pub const FLUTTER_BUILD_MENU: &str = "build.flutter";
/// Build › Xcode: Clean Build Folder and Delete DerivedData, filled only when the project has
/// Xcode schemes. A submenu after Build › Flutter when it has items, like it.
pub const DYNAMIC_XCODE_BUILD: &str = "xcodeBuild";
/// Id (and `menu.` label key) of the Build › Xcode submenu.
pub const XCODE_BUILD_MENU: &str = "build.xcode";
/// The submenu (id, English label) a dynamic slot is shown as when it has items, followed by a
/// separator; `None`: its items are listed in place.
pub fn dynamic_submenu(slot: &str) -> Option<(&'static str, &'static str)> {
match slot {
DYNAMIC_FLUTTER_BUILD => Some((FLUTTER_BUILD_MENU, "Flutter")),
DYNAMIC_XCODE_BUILD => Some((XCODE_BUILD_MENU, "Xcode")),
_ => None,
}
}
/// The menu bar for `os`. Labels are English defaults; the frontend replaces
/// them with `menu.<id>` strings from the active locale catalog.
@@ -236,7 +260,9 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("remote.stopBackend", "Stop Remote Backend"),
act("remote.reloadEnvironment", "Reload Environment"),
SEP,
act("file.saveAs", "Save As…"),
act("file.save", "Save All"),
act("templates.saveFileAsTemplate", "Save File as Template…"),
act("file.reloadAllFromDisk", "Reload All from Disk"),
sub("fileProperties", "File Properties", vec![act("file.toggleReadOnly", "Make File Read-only / Writable")]),
SEP,
@@ -251,6 +277,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("file.exportSettings", "Export Settings…"),
act("file.importSettings", "Import Settings…"),
act("file.importJetBrainsSettings", "Import Settings from JetBrains IDE…"),
act("file.syncSettings", "Sync Settings Now"),
],
),
sub(
@@ -413,6 +440,11 @@ pub fn spec(os: Os) -> Vec<Entry> {
vec![
act("editor.toggleSoftWrap", "Soft-Wrap"),
act("editor.toggleRenderedDocs", "Render Documentation Comments"),
SEP,
act("editor.toggleLocalWhitespaces", "Show Whitespaces"),
act("editor.toggleLocalLineNumbers", "Show Line Numbers"),
act("editor.toggleLocalGutterIcons", "Show Gutter Icons"),
act("editor.toggleLocalIndentGuides", "Show Indent Guides"),
],
),
SEP,
@@ -605,6 +637,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
"Build",
vec![
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD),
Entry::Dynamic(DYNAMIC_XCODE_BUILD),
act("build.buildProject", "Build Project"),
act("build.buildModule", "Build Module"),
act("build.compileFile", "Recompile"),
@@ -674,6 +707,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("vcs.pull", "Pull…"),
act("vcs.fetch", "Fetch"),
act("vcs.unshallow", "Fetch Full History"),
act("vcs.lfsPull", "Pull LFS Objects"),
SEP,
// Operation items (Abort Merge, Continue Rebase…) are enabled only while it is in progress.
act("vcs.merge", "Merge…"),
@@ -691,6 +725,14 @@ pub fn spec(os: Os) -> Vec<Entry> {
SEP,
act("vcs.newWorktree", "New Worktree…"),
act("vcs.worktrees", "Worktrees…"),
sub(
"gitSubmodules",
"Submodules",
vec![
act("vcs.initSubmodules", "Initialize Submodules"),
act("vcs.syncSubmodules", "Sync Submodule URLs"),
],
),
SEP,
act("vcs.showLog", "Show Git Log"),
sub(
@@ -739,6 +781,10 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("github.createPullRequest", "Create Pull Request…"),
act("github.checkoutPullRequest", "Checkout Pull Request…"),
act("github.openInBrowser", "Open on GitHub"),
SEP,
act("github.createGist", "Create Gist…"),
act("github.shareProject", "Share Project on GitHub"),
act("github.actions.show", "GitHub Actions"),
],
),
act("vcs.manageRemotes", "Manage Remotes…"),
@@ -922,12 +968,27 @@ pub fn route(spec: &[Entry], id: &str) -> Option<MenuRoute> {
/// `entries` without the action `id` (and a separator it leaves doubled or trailing).
pub fn without_action(entries: Vec<Entry>, id: &str) -> Vec<Entry> {
without(entries, &|e| e == id)
}
/// `entries` without the submenus and actions [`MenuConfig::hidden`] lists.
pub fn without_hidden(entries: Vec<Entry>, config: &MenuConfig) -> Vec<Entry> {
if config.hidden.is_empty() {
return entries;
}
without(entries, &|id| config.hidden.iter().any(|h| h == id))
}
/// `entries` without the actions and submenus whose id `drop` matches, and the separators
/// left dangling.
fn without(entries: Vec<Entry>, drop: &dyn Fn(&str) -> bool) -> Vec<Entry> {
let mut out: Vec<Entry> = Vec::with_capacity(entries.len());
for e in entries {
match e {
Entry::Action { id: a, .. } if a == id => {}
Entry::Action { id: a, .. } if drop(a) => {}
Entry::Submenu { id: sid, .. } if drop(sid) => {}
Entry::Submenu { id: sid, label, children } => {
out.push(Entry::Submenu { id: sid, label, children: without_action(children, id) })
out.push(Entry::Submenu { id: sid, label, children: without(children, drop) })
}
Entry::Separator if matches!(out.last(), None | Some(Entry::Separator)) => {}
e => out.push(e),
@@ -971,6 +1032,9 @@ pub struct MenuConfig {
/// Ids of the toggle actions currently on.
#[serde(default)]
pub checked: Vec<String>,
/// Ids of submenus and actions left out of the menu (the Git menu while Git integration is off).
#[serde(default)]
pub hidden: Vec<String>,
}
/// An item of a frontend-listed menu slot.
@@ -1086,33 +1150,107 @@ pub struct RemoteRecent {
pub opened_at_ms: f64,
}
pub struct RecentItem {
pub path: String,
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecentSection {
pub id: String,
pub label: String,
}
/// The local and remote recent projects, most recently opened first.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecentItem {
pub path: String,
pub label: String,
pub section: Option<RecentSection>,
}
fn parse_remote_recent(r: &RemoteRecent) -> (RecentSection, String) {
const SCHEMES: [(&str, &str, &str); 3] =
[("ssh://", "ssh", "SSH"), ("wsl://", "wsl", "WSL"), ("devcontainer://", "devContainer", "Dev Container")];
for (prefix, kind, kind_label) in SCHEMES {
if let Some(rest) = r.location.strip_prefix(prefix)
&& let Some(slash) = rest.find('/')
&& slash > 0
{
let remote_path = &rest[slash..];
let (host, shown_path) = match r.detail.strip_suffix(remote_path).and_then(|h| h.strip_suffix(':')) {
Some(host) if !host.is_empty() => (host, remote_path),
_ => r.detail.split_once(':').unwrap_or((&rest[..slash], remote_path)),
};
return (
RecentSection {
id: format!("{RECENT_SECTION_PREFIX}{kind}:{host}"),
label: format!("{kind_label} · {host}"),
},
format!("{} — {shown_path}", r.name),
);
}
}
let (host, shown_path) = r.detail.split_once(':').unwrap_or((r.detail.as_str(), r.detail.as_str()));
(
RecentSection { id: format!("{RECENT_SECTION_PREFIX}remote:{host}"), label: host.to_owned() },
format!("{} — {shown_path}", r.name),
)
}
/// The local and remote recent projects, grouped by host in MRU order when remote projects exist.
pub fn recent_items(
recent: &[ide_workspace::RecentProject],
remote: &[RemoteRecent],
home: Option<&Path>,
) -> Vec<RecentItem> {
enum Candidate<'a> {
Local { path: String, label: String },
Remote(&'a RemoteRecent),
}
let local = recent.iter().map(|p| {
let shown = match home.and_then(|h| p.path.strip_prefix(h).ok()) {
Some(rest) => format!("~/{}", rest.display()),
None => p.path.display().to_string(),
};
let item =
RecentItem { path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name) };
(p.opened_at_ms, item)
(
p.opened_at_ms,
Candidate::Local {
path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name)
},
)
});
let remote = remote.iter().map(|r| {
(r.opened_at_ms, RecentItem { path: r.location.clone(), label: format!("{} — {}", r.name, r.detail) })
});
let mut items: Vec<(f64, RecentItem)> = local.chain(remote).collect();
let remote_candidates = remote.iter().map(|r| (r.opened_at_ms, Candidate::Remote(r)));
let mut items: Vec<(f64, Candidate<'_>)> = local.chain(remote_candidates).collect();
// Stable: the local list's own order holds among equal times.
items.sort_by(|a, b| b.0.total_cmp(&a.0));
items.into_iter().take(MAX_RECENT).map(|(_, item)| item).collect()
items.truncate(MAX_RECENT);
let has_remote = items.iter().any(|(_, c)| matches!(c, Candidate::Remote(_)));
if !has_remote {
return items
.into_iter()
.filter_map(|(_, c)| match c {
Candidate::Local { path, label } => Some(RecentItem { path, label, section: None }),
Candidate::Remote(_) => None,
})
.collect();
}
let mut groups: Vec<(String, Vec<RecentItem>)> = Vec::new();
for (_, candidate) in items {
let (section, path, label) = match candidate {
Candidate::Local { path, label } => {
(RecentSection { id: RECENT_LOCAL_ID.into(), label: "Local".into() }, path, label)
}
Candidate::Remote(r) => {
let (section, label) = parse_remote_recent(r);
(section, r.location.clone(), label)
}
};
let item = RecentItem { path, label, section: Some(section.clone()) };
if let Some((_, members)) = groups.iter_mut().find(|(id, _)| *id == section.id) {
members.push(item);
} else {
groups.push((section.id, vec![item]));
}
}
groups.into_iter().flat_map(|(_, members)| members).collect()
}
/// A menu entry for a menu bar drawn by the frontend (Windows title bar).
@@ -1176,12 +1314,12 @@ pub fn model(spec: &[Entry], recent: &[RecentItem], config: &MenuConfig) -> Vec<
}
}));
}
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD) => {
let items = config.dynamic_items(DYNAMIC_FLUTTER_BUILD);
Entry::Dynamic(slot) if let Some((id, label)) = dynamic_submenu(slot) => {
let items = config.dynamic_items(slot);
if !items.is_empty() {
out.push(MenuNode::Submenu {
id: FLUTTER_BUILD_MENU.into(),
label: "Flutter".into(),
id: id.into(),
label: label.into(),
current: None,
children: items.iter().map(DynamicItem::model).collect(),
});
@@ -1201,13 +1339,30 @@ pub fn model(spec: &[Entry], recent: &[RecentItem], config: &MenuConfig) -> Vec<
Entry::RecentProjects if recent.is_empty() => {
out.push(MenuNode::Placeholder { id: "recent.none".into(), label: "No Recent Projects".into() })
}
Entry::RecentProjects => out.extend(recent.iter().map(|r| MenuNode::Action {
id: OPEN_RECENT_ACTION.into(),
label: r.label.clone(),
hint: None,
arg: Some(r.path.clone()),
checked: None,
})),
Entry::RecentProjects => {
let mut current_section: Option<&str> = None;
for r in recent {
if let Some(sec) = &r.section
&& current_section != Some(sec.id.as_str())
{
if current_section.is_some() {
out.push(MenuNode::Separator);
}
out.push(MenuNode::Placeholder {
id: sec.id.clone(),
label: config.label(&sec.id, &sec.label),
});
current_section = Some(sec.id.as_str());
}
out.push(MenuNode::Action {
id: OPEN_RECENT_ACTION.into(),
label: r.label.clone(),
hint: None,
arg: Some(r.path.clone()),
checked: None,
});
}
}
}
}
out
+45 -8
Переглянути файл
@@ -3,7 +3,7 @@ use crate::ops::Channel;
use base64::Engine;
use ide_core::error::ErrorKind;
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, IpcPath, SharedSink};
use ide_notebook::kernel::{KernelManager, KernelOutput};
use ide_notebook::kernel::{KernelManager, KernelOutput, KernelTarget};
use ide_notebook::{NotebookDocument, NotebookEdit, NotebookSnapshot};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
@@ -45,11 +45,12 @@ fn parse_variables(reply: &serde_json::Value) -> IdeResult<Vec<NotebookVariable>
let rows = &reply["rows"];
if rows["status"] != "ok" {
let reason = rows["evalue"].as_str().unwrap_or("no result");
return Err(IdeError::unavailable(format!("could not read the kernel's variables: {reason}")));
return Err(IdeError::new(ErrorKind::Protocol, format!("could not read the kernel's variables: {reason}")));
}
// The value is a base64 str, so its text/plain is that text in quotes.
let text = rows["data"]["text/plain"].as_str().unwrap_or_default().trim_matches(['\'', '"']);
let bad = |error: String| IdeError::unavailable(format!("could not read the kernel's variables: {error}"));
let bad =
|error: String| IdeError::new(ErrorKind::Protocol, format!("could not read the kernel's variables: {error}"));
let json = base64::engine::general_purpose::STANDARD.decode(text).map_err(|e| bad(e.to_string()))?;
serde_json::from_slice(&json).map_err(|e| bad(e.to_string()))
}
@@ -355,13 +356,49 @@ impl NotebookService {
if document.state.lock().active.is_some() {
return Err(IdeError::unavailable("notebook is running"));
}
let expressions = HashMap::from([("rows".to_owned(), "_openidea_variables()".to_owned())]);
let expressions = HashMap::from([("rows".to_owned(), r#"globals().pop("_openidea_variables")()"#.to_owned())]);
match self.kernels.inspect(&document.path, VARIABLES, expressions).await? {
Some(reply) => parse_variables(&reply).map(Some),
None => Ok(None),
}
}
/// Opens the debugger of the notebook's kernel, starting `target` first (or replacing a
/// kernel of another target). Also returns the notebook's code cells as (URI, source), read
/// when called, and the prefix of its cell URIs: what Debug Cell needs (see
/// `ide_notebook::kernel::debug`).
pub(crate) async fn debugger(
&self,
id: &str,
target: KernelTarget,
cancel: CancellationToken,
) -> IdeResult<(ide_notebook::kernel::KernelDebugger, impl Fn() -> Vec<(String, String)> + Send + 'static, String)>
{
let document = self.resolve(id)?;
if document.state.lock().active.is_some() {
return Err(IdeError::unavailable("notebook is running"));
}
// The drop-down's kernel, which may not be the one running yet.
tokio::select! {
biased;
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
result = self.kernels.start(&document.path, target) => result?,
}
let debugger = self.kernels.debugger(&document.path)?;
let prefix = ide_lsp::cell_uri(&document.path, "");
// Read again on each use: cells are added and edited while the session runs.
let cells = move || {
let Ok(snapshot) = snapshot(&document) else { return Vec::new() };
snapshot
.cells
.into_iter()
.filter(|cell| cell.cell_type == "code")
.map(|cell| (ide_lsp::cell_uri(&document.path, &cell.id), cell.source))
.collect()
};
Ok((debugger, cells, prefix))
}
pub(crate) fn admit(
&self,
id: &str,
@@ -374,7 +411,7 @@ impl NotebookService {
pub(crate) async fn execute(
self: &Arc<Self>,
admission: ExecutionAdmission,
python: PathBuf,
target: KernelTarget,
on_output: Channel<NotebookOutputEvent>,
) -> IdeResult<NotebookSnapshot> {
let document = admission.guard.document.clone();
@@ -383,7 +420,7 @@ impl NotebookService {
tokio::spawn(async move {
let ExecutionAdmission { guard, generation, plan } = admission;
let result =
service.run_batch(document.clone(), generation, plan, python, guard.batch.clone(), on_output).await;
service.run_batch(document.clone(), generation, plan, target, guard.batch.clone(), on_output).await;
drop(guard);
match result {
Ok(()) => snapshot(&document),
@@ -399,7 +436,7 @@ impl NotebookService {
document: Arc<ManagedDocument>,
generation: u64,
plan: Vec<(String, String)>,
python: PathBuf,
target: KernelTarget,
batch: Arc<Batch>,
on_output: Channel<NotebookOutputEvent>,
) -> IdeResult<()> {
@@ -427,7 +464,7 @@ impl NotebookService {
.kernels
.execute(
&document.path,
&python,
target.clone(),
&source,
batch.cancel.clone(),
Arc::new(move |output: KernelOutput| {
+27 -7
Переглянути файл
@@ -1,7 +1,9 @@
# Run silently on a notebook's kernel by the Jupyter Variables tool window; the IDE then
# evaluates `_openidea_variables()` as a user expression. Same rows as the Python Console's.
# Run silently on a notebook's kernel by the Jupyter Variables tool window. The IDE then
# evaluates `globals().pop("_openidea_variables")()` as a user expression, which also takes
# the function back out of the notebook's namespace. Same rows as the Python Console's.
def _openidea_variables():
import base64
import collections
import json
import reprlib
import types
@@ -9,15 +11,33 @@ def _openidea_variables():
shell = get_ipython() # noqa: F821 -- defined in every IPython namespace
short = reprlib.Repr()
short.maxstring = short.maxother = 200
limit = short.maxother
items = 100
containers = (dict, list, tuple, set, frozenset, collections.deque)
def value_text(value):
# reprlib shortens the exact builtin types itself; for anything else it builds the
# full repr() and then cuts it. That is right for a subclass's own repr (a namedtuple,
# an OrderedDict, a defaultdict), but costs seconds and gigabytes for a big one.
kind = type(value)
if isinstance(value, (str, bytes, bytearray)) and kind is not str and len(value) > limit:
return repr(value[:limit]) + "..."
if isinstance(value, containers) and kind not in containers and len(value) > items:
return "<%s len=%d>" % (kind.__name__, len(value))
return short.repr(value)
rows = []
for name, value in list(shell.user_ns.items()):
if name.startswith("_") or name in shell.user_ns_hidden or isinstance(value, types.ModuleType):
if name.startswith("_") or name in shell.user_ns_hidden:
continue
try:
text = short.repr(value)
except Exception as error: # a broken __repr__ must not hide the other variables
text = "<repr failed: %s>" % type(error).__name__
rows.append({"name": name, "type": type(value).__name__, "value": text})
if isinstance(value, types.ModuleType):
continue
kind = type(value).__name__
text = value_text(value)
except Exception as error: # a broken __repr__ or __class__ must not hide the other variables
kind, text = "?", "<unavailable: %s>" % type(error).__name__
rows.append({"name": name, "type": kind, "value": text})
rows.sort(key=lambda row: row["name"])
# Base64 so the expression's text/plain (a str repr) needs no unescaping.
return base64.b64encode(json.dumps(rows).encode()).decode()
+392 -12
Переглянути файл
@@ -6,10 +6,12 @@ use crate::agent_secrets::{AgentSecrets, Kept};
use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentModelCatalog,
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
CopilotAuthStatus, CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource,
McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentMemoryCatalog,
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemoryOverrides, AgentMemorySettings, AgentModelCatalog, AgentProbe,
AgentPrompt, AgentProvider, AgentProviderMemoryPolicy, AgentQueued, AgentRecoveryReport, AgentSkillMode,
AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode, CopilotAuthStatus, CreateAgentMemoryInput,
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource, McpImportSelection,
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput,
RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
};
use ide_command::command;
@@ -144,12 +146,18 @@ fn prepare_login_launch_env(
env: &mut std::collections::BTreeMap<String, String>,
host_has: impl Fn(&str) -> bool,
) {
if !is_remote {
return;
}
let has_non_empty = |env: &std::collections::BTreeMap<String, String>, key: &str| {
env.get(key).is_some_and(|v| !v.is_empty()) || host_has(key)
};
// Skip `gh`'s `termenv` OSC 11 background-color probe during interactive login (`gh auth login`
// renders no markdown); if an OSC 11 reply arrives late over a PTY or SSH link, `survey` aborts
// with `unexpected escape sequence from terminal: ['\x1b' ']']`.
if target_is_gh && !has_non_empty(env, "GLAMOUR_STYLE") {
env.insert("GLAMOUR_STYLE".into(), "notty".into());
}
if !is_remote {
return;
}
// `openidea-server` spawns sign-in commands in a real PTY even inside WSL, dev containers,
// and `--web`, where `SSH_*` variables are absent; mark the session remote so CLIs such as
// `copilot login` choose OAuth device-code sign-in over a remote-only loopback server.
@@ -610,6 +618,74 @@ pub fn agent_cancel(host: &Host, window: &str, task: String, subagent: Option<St
host.project(window)?.agents.cancel(&task, subagent)
}
/// Resumes an interrupted task with a continuation turn (or immediately wakes a task waiting
/// in the transient network outage retry loop).
#[command(trust = trusted)]
pub async fn agent_resume_task(host: &Host, window: &str, task: String) -> IdeResult<()> {
host.require_trust(window)?;
let agents = host.project(window)?.agents.clone();
host.blocking(move || agents.resume(&task)).await
}
/// Resumes all interrupted tasks in the project and returns their IDs.
#[command(trust = trusted)]
pub async fn agent_resume_all_interrupted(host: &Host, window: &str) -> IdeResult<Vec<String>> {
host.require_trust(window)?;
let agents = host.project(window)?.agents.clone();
host.blocking(move || agents.resume_all_interrupted()).await
}
/// Clears a task's interrupted state without sending a continuation prompt.
#[command(trust = always)]
pub async fn agent_dismiss_interrupted(host: &Host, window: &str, task: String) -> IdeResult<()> {
let agents = host.project(window)?.agents.clone();
host.blocking(move || agents.dismiss_interrupted(&task)).await
}
/// Marks a task as read (`unread = false`) when viewed by the user.
#[command(trust = always)]
pub async fn agent_mark_read(host: &Host, window: &str, task: String) -> IdeResult<()> {
let agents = host.project(window)?.agents.clone();
host.blocking(move || agents.mark_read(&task)).await
}
/// Overrides the recovery / network auto-retry window (`None` = global default,
/// `Some(0)` = Off / Ask, `Some(minutes)` = override) for `task`.
#[command(trust = trusted)]
pub async fn agent_set_recovery_window(host: &Host, window: &str, task: String, minutes: Option<u32>) -> IdeResult<()> {
host.require_trust(window)?;
let agents = host.project(window)?.agents.clone();
host.blocking(move || agents.set_recovery_window(&task, minutes)).await
}
/// Arms or clears the one-shot auto-resume flag on active/interrupted tasks before window close.
#[command(trust = trusted)]
pub async fn agent_set_auto_resume_once(host: &Host, window: &str, tasks: Vec<String>, enabled: bool) -> IdeResult<()> {
host.require_trust(window)?;
let agents = host.project(window)?.agents.clone();
host.blocking(move || {
agents.set_auto_resume_once(&tasks, enabled);
Ok(())
})
.await
}
/// Wakes any task waiting in the transient network outage loop so reachability is probed now.
#[command(trust = always)]
pub fn agent_poke_network(host: &Host, window: &str) -> IdeResult<()> {
host.project(window)?.agents.poke_network();
Ok(())
}
/// Reconciles interrupted tasks once per `AgentManager` incarnation according to the user's
/// recovery policy and safety guardrails.
#[command(trust = trusted)]
pub async fn agent_reconcile_interrupted(host: &Host, window: &str) -> IdeResult<AgentRecoveryReport> {
host.require_trust(window)?;
let agents = host.project(window)?.agents.clone();
host.blocking(move || Ok(agents.reconcile_interrupted())).await
}
/// Stops one of the task's background tasks.
#[command(trust = always)]
pub async fn agent_stop_background(host: &Host, window: &str, task: String, background: String) -> IdeResult<()> {
@@ -1221,6 +1297,17 @@ pub fn agent_set_skill_overrides(
host.project(window)?.agents.set_skill_overrides(&task, overrides)
}
/// Updates per-session memory overrides (auto-memory mode and per-entry modes) on `task`.
#[command(trust = always)]
pub fn agent_set_memory_overrides(
host: &Host,
window: &str,
task: String,
overrides: AgentMemoryOverrides,
) -> IdeResult<AgentTask> {
host.project(window)?.agents.set_memory_overrides(&task, overrides)
}
/// Every skill discovered in the project, the user's folders and enabled plugins, with
/// the mode a session runs it with (without any session's own overrides).
#[command(trust = always)]
@@ -1492,6 +1579,272 @@ fn host_skills_policy(host: &Host, project: Option<&crate::Project>) -> SkillsPo
}
}
fn host_memory_policy(host: &Host, project: Option<&crate::Project>) -> ide_agent::memory::MemoryPolicy {
match project {
Some(project) => ide_agent::memory::MemoryPolicy {
user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.memory.clone(),
workspace: project.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.memory.clone(),
workspace_trusted: project.trusted.load(std::sync::atomic::Ordering::Acquire),
workspace_roots: workspace_skill_roots(&project.root),
},
None => ide_agent::memory::MemoryPolicy {
user: host.global_settings.effective().agents.memory.clone(),
workspace: Default::default(),
workspace_trusted: true,
workspace_roots: Vec::new(),
},
}
}
fn memory_settings_layers(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
) -> (AgentMemorySettings, Option<AgentMemorySettings>) {
let user = host.global_settings.effective().agents.memory.clone();
let workspace =
project.map(|p| p.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.memory.clone());
(user, workspace)
}
fn is_default_memory_settings(s: &AgentMemorySettings) -> bool {
s.auto_memory == AutoMemoryMode::Inherit && s.providers.is_empty() && s.entries.is_empty()
}
fn persist_memory_settings(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
scope: McpScope,
settings: &AgentMemorySettings,
) -> IdeResult<()> {
let value = if is_default_memory_settings(settings) {
serde_json::Value::Null
} else {
serde_json::to_value(settings).map_err(|e| IdeError::invalid(e.to_string()))?
};
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
match scope {
McpScope::User => {
host.global_settings.set(ide_workspace::settings::SettingsScope::Global, "agents.memory", value)?;
for p in host.projects() {
p.settings.reload();
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
}
McpScope::Workspace => {
let p = project.ok_or_else(|| IdeError::invalid("Open a project to configure workspace memory"))?;
p.settings.set(ide_workspace::settings::SettingsScope::Project, "agents.memory", value)?;
p.agents.notify_mcp_servers_changed();
p.sink.emit(event);
}
}
Ok(())
}
async fn current_memory_catalog(host: &Host, project: Option<&crate::Project>) -> IdeResult<AgentMemoryCatalog> {
let policy = host_memory_policy(host, project);
let home = host.home_dir();
blocking(move || {
let entries = ide_agent::memory::discover_memories(&policy.workspace_roots, home.as_deref());
Ok(ide_agent::memory::resolve_catalog(entries, None, &policy, home.as_deref()))
})
.await
}
/// Discovers every agent instruction file, path-scoped rule, and learned auto-memory note
/// with resolved modes and per-provider auto-memory statuses.
#[command(trust = always)]
pub async fn agent_memory_list(host: &Host, window: &str) -> IdeResult<AgentMemoryCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
current_memory_catalog(host, project.as_deref()).await
}
/// Sets how memory entry `id` runs in `scope` (`settings.toml` vs `.openidea/settings.toml`),
/// never modifying the file on disk.
#[command(trust = always)]
pub async fn agent_memory_set_mode(
host: &Host,
window: &str,
id: String,
scope: McpScope,
mode: AgentMemoryMode,
agents: Vec<String>,
) -> IdeResult<AgentMemoryCatalog> {
let id = id.trim().to_owned();
if id.is_empty() {
return Err(IdeError::invalid("a memory entry needs an id"));
}
let clean_agents: Vec<String> = agents.into_iter().map(|a| a.trim().to_owned()).filter(|a| !a.is_empty()).collect();
let project = host.project(window).ok().filter(|p| !p.light);
let (mut user, mut workspace) = memory_settings_layers(host, project.as_ref());
let apply = |layer: &mut AgentMemorySettings| -> bool {
if mode == AgentMemoryMode::Auto && clean_agents.is_empty() {
layer.entries.remove(&id).is_some()
} else {
let next = AgentMemoryEntryPolicy { mode, agents: clean_agents.clone() };
layer.entries.insert(id.clone(), next.clone()).as_ref() != Some(&next)
}
};
match scope {
McpScope::User => {
if apply(&mut user) {
persist_memory_settings(host, None, scope, &user)?;
}
}
McpScope::Workspace => {
let ws =
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace memory"))?;
if apply(ws) {
let updated = ws.clone();
persist_memory_settings(host, project.as_ref(), scope, &updated)?;
}
}
}
current_memory_catalog(host, project.as_deref()).await
}
/// Sets the cross-session auto-memory policy (`Inherit`, `ReadWrite`, `ReadOnly`, `Off`)
/// globally or for one `provider` in `scope`.
#[command(trust = always)]
pub async fn agent_memory_set_auto(
host: &Host,
window: &str,
scope: McpScope,
provider: Option<String>,
mode: AutoMemoryMode,
) -> IdeResult<AgentMemoryCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
let (mut user, mut workspace) = memory_settings_layers(host, project.as_ref());
let prov_key = provider
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(|s| ide_agent::memory::normalize_provider_id(s).to_owned());
let apply = |layer: &mut AgentMemorySettings| -> bool {
match &prov_key {
None => {
let changed = layer.auto_memory != mode;
layer.auto_memory = mode;
changed
}
Some(key) => {
if mode == AutoMemoryMode::Inherit {
layer.providers.remove(key).is_some()
} else {
let next = AgentProviderMemoryPolicy { auto_memory: mode };
layer.providers.insert(key.clone(), next.clone()).as_ref() != Some(&next)
}
}
}
};
match scope {
McpScope::User => {
if apply(&mut user) {
persist_memory_settings(host, None, scope, &user)?;
}
}
McpScope::Workspace => {
let ws =
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace memory"))?;
if apply(ws) {
let updated = ws.clone();
persist_memory_settings(host, project.as_ref(), scope, &updated)?;
}
}
}
current_memory_catalog(host, project.as_deref()).await
}
/// Creates a new instruction or path-scoped rule file on disk.
#[command(trust = always)]
pub async fn agent_memory_create(
host: &Host,
window: &str,
input: CreateAgentMemoryInput,
) -> IdeResult<AgentMemoryCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
if input.scope == McpScope::Workspace {
host.require_trust(window)?;
}
let ws_root = project.as_ref().map(|p| p.root.clone());
let home = host.home_dir();
blocking(move || {
ide_agent::memory::create_memory(&input, ws_root.as_deref(), home.as_deref()).map_err(IdeError::invalid)
})
.await?;
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
current_memory_catalog(host, project.as_deref()).await
}
/// Promotes a learned auto-memory note into `<workspace>/AGENTS.md`.
#[command(trust = trusted)]
pub async fn agent_memory_promote(
host: &Host,
window: &str,
input: PromoteAgentMemoryInput,
) -> IdeResult<AgentMemoryCatalog> {
host.require_trust(window)?;
let project = host.project(window)?;
let ws_root = project.root.clone();
let roots = workspace_skill_roots(&ws_root);
let home = host.home_dir();
blocking(move || {
let entries = ide_agent::memory::discover_memories(&roots, home.as_deref());
ide_agent::memory::promote_memory(&input, &entries, &ws_root).map_err(IdeError::invalid)
})
.await?;
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
current_memory_catalog(host, Some(&project)).await
}
/// Deletes a writable memory entry (learned auto-memory note or OpenIDEA shared memory file).
#[command(trust = always)]
pub async fn agent_memory_delete(host: &Host, window: &str, id: String) -> IdeResult<AgentMemoryCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
if id.starts_with("workspace::") {
host.require_trust(window)?;
}
let roots = project.as_ref().map(|p| workspace_skill_roots(&p.root)).unwrap_or_default();
let home = host.home_dir();
blocking(move || {
let entries = ide_agent::memory::discover_memories(&roots, home.as_deref());
ide_agent::memory::delete_memory(&id, &entries).map_err(IdeError::invalid)
})
.await?;
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
current_memory_catalog(host, project.as_deref()).await
}
/// Clears local auto-memory files for `provider` (`claude`, `codex`, or `hermes`).
#[command(trust = always)]
pub async fn agent_memory_reset_provider(host: &Host, window: &str, provider: String) -> IdeResult<AgentMemoryCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
let roots = project.as_ref().map(|p| workspace_skill_roots(&p.root)).unwrap_or_default();
let home = host.home_dir();
blocking(move || {
ide_agent::memory::reset_provider_memory(&provider, &roots, home.as_deref()).map_err(IdeError::invalid)
})
.await?;
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
current_memory_catalog(host, project.as_deref()).await
}
fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::Path>) -> IdeResult<std::path::PathBuf> {
let Some(requested) = requested else {
return Ok(root.to_path_buf());
@@ -1602,25 +1955,36 @@ mod tests {
#[test]
fn prepare_login_launch_env_marks_remote_sessions_for_device_code_auth() {
let mut desktop_env = std::collections::BTreeMap::new();
prepare_login_launch_env(false, true, &mut desktop_env, |_| false);
assert!(desktop_env.is_empty());
let mut desktop_agent_env = std::collections::BTreeMap::new();
prepare_login_launch_env(false, false, &mut desktop_agent_env, |_| false);
assert!(desktop_agent_env.is_empty());
let mut desktop_gh_env = std::collections::BTreeMap::new();
prepare_login_launch_env(false, true, &mut desktop_gh_env, |_| false);
assert_eq!(desktop_gh_env.get("GLAMOUR_STYLE").map(String::as_str), Some("notty"));
assert!(!desktop_gh_env.contains_key("REMOTE_CONTAINERS"));
assert!(!desktop_gh_env.contains_key("GH_BROWSER"));
let mut remote_agent_env = std::collections::BTreeMap::new();
prepare_login_launch_env(true, false, &mut remote_agent_env, |_| false);
assert_eq!(remote_agent_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
assert!(!remote_agent_env.contains_key("GH_BROWSER"));
assert!(!remote_agent_env.contains_key("GLAMOUR_STYLE"));
let mut remote_gh_env = std::collections::BTreeMap::new();
prepare_login_launch_env(true, true, &mut remote_gh_env, |_| false);
assert_eq!(remote_gh_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
assert_eq!(remote_gh_env.get("GH_BROWSER").map(String::as_str), Some("true"));
assert_eq!(remote_gh_env.get("GLAMOUR_STYLE").map(String::as_str), Some("notty"));
// Preserves existing SSH/remote indicators and explicit browser settings.
// Preserves existing SSH/remote indicators, browser settings, and GLAMOUR_STYLE.
let mut ssh_env = std::collections::BTreeMap::new();
prepare_login_launch_env(true, true, &mut ssh_env, |k| matches!(k, "SSH_CONNECTION" | "BROWSER"));
prepare_login_launch_env(true, true, &mut ssh_env, |k| {
matches!(k, "SSH_CONNECTION" | "BROWSER" | "GLAMOUR_STYLE")
});
assert!(!ssh_env.contains_key("REMOTE_CONTAINERS"));
assert!(!ssh_env.contains_key("GH_BROWSER"));
assert!(!ssh_env.contains_key("GLAMOUR_STYLE"));
}
}
@@ -1639,6 +2003,7 @@ ide_command::domain!(
agent_copilot_auth_status,
agent_create,
agent_delete,
agent_dismiss_interrupted,
agent_entries,
agent_external_sessions,
agent_fork,
@@ -1648,6 +2013,7 @@ ide_command::domain!(
agent_hermes_profiles,
agent_import_session,
agent_login_spawn,
agent_mark_read,
agent_mcp_discover_sources,
agent_mcp_import,
agent_mcp_import_selected,
@@ -1657,25 +2023,39 @@ ide_command::domain!(
agent_mcp_save_json,
agent_mcp_set_enabled,
agent_mcp_test,
agent_memory_create,
agent_memory_delete,
agent_memory_list,
agent_memory_promote,
agent_memory_reset_provider,
agent_memory_set_auto,
agent_memory_set_mode,
agent_poke_network,
agent_preview_copilot_models,
agent_probe,
agent_prompt,
agent_providers,
agent_reconcile_interrupted,
agent_refresh_models,
agent_registry_install,
agent_registry_list,
agent_registry_remove,
agent_rename,
agent_respond,
agent_resume_all_interrupted,
agent_resume_task,
agent_rollback,
agent_rollback_changes,
agent_send_queued_now,
agent_set_additional_args,
agent_set_auto_resume_once,
agent_set_command,
agent_shell,
agent_set_config,
agent_set_env,
agent_set_mcp_overrides,
agent_set_memory_overrides,
agent_set_recovery_window,
agent_set_skill_overrides,
agent_skills_browse,
agent_skills_install,
+148
Переглянути файл
@@ -7,6 +7,7 @@ use crate::Host;
use ide_command::command;
use ide_core::{CancellationToken, IdeError, IdeResult, IpcPath, RequestId};
use ide_db::split::SqlStatement;
use ide_db::workspace::WorkspaceJoinPlan;
use ide_db::{
CompletionModel, ConsoleId, DataSource, Databases, DbObjectKind, DbRowEdit, DbSourceFolder, DbVisibilityChange,
HistoryEntry, PlanNode, QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
@@ -15,6 +16,27 @@ use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::PathBuf;
#[command(trust = trusted)]
pub async fn db_workspace_join(
host: &Host,
window: &str,
request: RequestId,
driver: String,
plan: WorkspaceJoinPlan,
) -> IdeResult<QueryResult> {
let cancel = host.begin_project_request(window, request);
let result = async {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let db = host.project(window)?.db.clone();
db.workspace_join(&driver, plan, &cancel).await
}
.await;
host.end_request(request);
result
}
/// One statement of a console run.
#[derive(Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -33,6 +55,11 @@ pub enum ExecutionEvent {
Done { error: Option<IdeError> },
}
#[command(trust = trusted)]
pub fn db_approve_ducklake_source(host: &Host, window: &str, source: DataSource) -> IdeResult<()> {
host.project(window)?.db.approve_ducklake_source(&source)
}
#[command(trust = trusted)]
pub fn db_approve_jdbc_source(host: &Host, window: &str, source: DataSource) -> IdeResult<()> {
host.project(window)?.db.approve_jdbc_source(&source)
@@ -75,6 +102,12 @@ pub async fn db_save_sources(host: &Host, window: &str, sources: Vec<DataSource>
sources_changed(host, window)
}
#[command(trust = trusted)]
pub async fn db_create_ducklake(host: &Host, window: &str, jdbc_driver: String, directory: String) -> IdeResult<()> {
let db = host.project(window)?.db.clone();
db.create_ducklake(&jdbc_driver, &directory).await
}
#[command(trust = trusted)]
pub fn db_source_folders(host: &Host, window: &str) -> IdeResult<Vec<DbSourceFolder>> {
// The project's user-created folders and their data source members.
@@ -829,6 +862,7 @@ pub async fn server_version(host: &Host, window: &str, id: &str) -> IdeResult<u3
ide_command::domain!(
db:
db_apply_edits,
db_workspace_join,
db_completion,
db_connect,
db_connected,
@@ -836,6 +870,7 @@ ide_command::domain!(
db_consoles_dir,
db_consoles,
db_create_database,
db_create_ducklake,
db_database_catalog,
db_catalog_table_details,
db_catalog_table_page,
@@ -851,6 +886,7 @@ ide_command::domain!(
db_history,
db_jdbc_driver_classes,
db_jdbc_drivers,
db_approve_ducklake_source,
db_approve_jdbc_source,
db_save_jdbc_driver,
db_remove_jdbc_driver,
@@ -911,6 +947,118 @@ mod tests {
host
}
fn workspace_test_plan() -> WorkspaceJoinPlan {
use ide_db::workspace::{WorkspaceJoinColumn, WorkspaceJoinCondition, WorkspaceJoinRelation};
let relation = |id: &str| WorkspaceJoinRelation {
source_id: id.into(),
database: "default".into(),
schema: "default".into(),
table: "items".into(),
};
WorkspaceJoinPlan {
tables: vec![relation("left"), relation("right")],
joins: vec![WorkspaceJoinCondition {
left: WorkspaceJoinColumn { relation: 0, column: "id".into() },
right_column: "id".into(),
}],
projection: None,
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn workspace_join_respects_an_early_cancel() {
let temp = tempfile::tempdir().unwrap();
let host = host_with_sqlite(&temp).await;
let request = RequestId(1);
host.cancel_request(request);
let error = db_workspace_join(&host, "main", request, "no driver installed".into(), workspace_test_plan())
.await
.unwrap_err();
assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn workspace_join_cannot_resolve_a_project_after_its_requests_are_drained() {
use std::time::{Duration, Instant};
let temp = tempfile::tempdir().unwrap();
let host = host_with_sqlite(&temp).await;
let window = "main";
let active = host.begin_project_request(window, RequestId(1));
std::thread::scope(|threads| {
// Hold close at heap cleanup, which follows cancellation of registered requests.
let heap = host.heap_windows.lock();
let close = threads.spawn(|| host.close_project_detached(window));
let deadline = Instant::now() + Duration::from_secs(3);
while !active.is_cancelled() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
let drained = active.is_cancelled();
let detached = host.project(window).is_err();
drop(heap);
close.join().unwrap();
assert!(drained, "close did not reach the cancellation step");
assert!(detached, "close drained its requests while the old project was still available");
});
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "requires DUCKDB_JDBC_JAR and Java 17+"]
async fn workspace_join_stops_when_its_project_closes() {
use std::time::Duration;
let temp = tempfile::tempdir().unwrap();
let host = host_with_sqlite(&temp).await;
let window = "main";
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let sources = ["left", "right"].map(|id| DataSource {
id: id.into(),
name: format!("ClickHouse fixture {id}"),
driver: DbDriver::Clickhouse,
host: "127.0.0.1".into(),
port: Some(listener.local_addr().unwrap().port()),
..Default::default()
});
db_save_sources(&host, window, sources.into()).await.unwrap();
host.project(window)
.unwrap()
.db
.save_jdbc_driver(ide_db::DbJdbcDriver {
id: "duck".into(),
name: "DuckDB".into(),
vendor: Some("duckdb".into()),
jars: vec![std::env::var("DUCKDB_JDBC_JAR").expect("official JDBC fixture")],
class_name: "org.duckdb.DuckDBDriver".into(),
url_template: "jdbc:duckdb:".into(),
})
.unwrap();
for (request, close_project) in [(RequestId(2), false), (RequestId(3), true)] {
let join = db_workspace_join(&host, window, request, "duck".into(), workspace_test_plan());
tokio::pin!(join);
// Accept the source connection and leave it open without replying.
let (socket, _) = tokio::select! {
result = &mut join => panic!("workspace ended before reaching the source: {result:?}"),
peer = tokio::time::timeout(Duration::from_secs(15), listener.accept()) => peer.unwrap().unwrap(),
};
if close_project {
host.close_project_detached(window);
} else {
host.cancel_request(request);
}
let stopped = tokio::time::timeout(Duration::from_secs(3), &mut join).await;
if stopped.is_err() {
host.cancel_request(request);
let _ = tokio::time::timeout(Duration::from_secs(5), &mut join).await;
}
let error = stopped.expect("workspace JOIN did not stop after cancellation").unwrap_err();
assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled);
assert!(!host.project_requests.read().values().flatten().any(|entry| *entry == request));
drop(socket);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "requires a disposable loopback PostgreSQL fixture with OPENIDEA_PG_CONSOLE_PORT"]
async fn postgres_console_commands_keep_commit_result_reads_and_release_scoped() {
+70 -2
Переглянути файл
@@ -62,8 +62,16 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
python.as_deref(),
config.cwd.as_deref(),
);
let plots = super::plots::prepare(host, &project);
super::python::prepare_debug(&mut config, &paths, plots.as_ref())?;
let conda = super::python::conda_prefix(&host.config_dir, &project, python.as_deref(), config.cwd.as_deref());
let plots = super::plots::prepare(host, &project).await;
// The debuggee inherits the IDE's environment as a run started in its folder does.
let dir = config.cwd.as_deref().map(|c| c.to_path_buf()).unwrap_or_else(|| project.root.clone());
super::python::prepare_debug(
&mut config,
&paths,
plots.as_ref().map(|p| (p, dir.as_path())),
conda.as_deref(),
)?;
}
let label = window;
let (sink, flush_output) = output::coalescing_sink(host.window_sink(label));
@@ -507,6 +515,17 @@ pub async fn debug_step(host: &Host, session: DebugSessionId, thread_id: i64, ki
host.debugger.step(session, thread_id, kind).await
}
/// Step Over / Into Instruction: a step by one machine instruction.
#[command(trust = trusted)]
pub async fn debug_step_instruction(
host: &Host,
session: DebugSessionId,
thread_id: i64,
kind: StepKind,
) -> IdeResult<()> {
host.debugger.step_instruction(session, thread_id, kind).await
}
#[command(trust = trusted)]
pub async fn debug_run_to(
host: &Host,
@@ -549,12 +568,58 @@ pub async fn debug_evaluate_in(
host.debugger.evaluate_in(session, frame_id, expression, context).await
}
/// Memory View: `count` bytes from `offset` bytes after `memory_reference` (a variable's,
/// an evaluation result's or an earlier read's address).
#[command(trust = trusted)]
pub async fn debug_read_memory(
host: &Host,
session: DebugSessionId,
memory_reference: String,
offset: i64,
count: u32,
) -> IdeResult<ide_dap::MemoryBlock> {
host.debugger.read_memory(session, memory_reference, offset, count).await
}
/// Disassembly view: `count` instructions from `before` instructions ahead of `memory_reference`
/// (a frame's instruction pointer or an instruction's address).
#[command(trust = trusted)]
pub async fn debug_disassemble(
host: &Host,
session: DebugSessionId,
memory_reference: String,
before: u32,
count: u32,
) -> IdeResult<Vec<ide_dap::Instruction>> {
host.debugger.disassemble(session, memory_reference, before, count).await
}
/// Last known verification states of a file's breakpoints (refetch on `breakpointsChanged`).
#[command(trust = trusted)]
pub fn debug_breakpoint_states(host: &Host, path: PathBuf) -> IdeResult<Vec<BreakpointState>> {
Ok(host.debugger.breakpoint_states(&path))
}
/// This window's stored breakpoints, with their full attributes (not just verification states).
/// Kept as a plain function: the MCP tools list and edit them under the window's owner, so they
/// are sent to this window's sessions just like breakpoints set in the editor.
pub fn debug_breakpoints(
host: &Host,
window: &str,
) -> (std::collections::BTreeMap<PathBuf, Vec<Breakpoint>>, Vec<FunctionBreakpoint>, Vec<DataBreakpoint>) {
host.debugger.breakpoints(host.owner_window(window))
}
/// Whether a live session is suspended; `None` once it has ended. Used by tools that wait for a pause.
pub fn debug_session_suspended(host: &Host, session: DebugSessionId) -> Option<bool> {
host.debugger.session_suspended(session)
}
/// The thread the session last stopped in, when the adapter named one. Frame tools default to it.
pub fn debug_stopped_thread(host: &Host, session: DebugSessionId) -> Option<i64> {
host.debugger.stopped_thread(session)
}
/// This window's live sessions, including adapter-started child sessions.
#[command(trust = always)]
pub fn debug_sessions(host: &Host, window: &str) -> IdeResult<Vec<SessionInfo>> {
@@ -1058,6 +1123,7 @@ ide_command::domain!(
debug_capabilities,
debug_completions,
debug_data_breakpoint_info,
debug_disassemble,
debug_evaluate,
debug_evaluate_in,
debug_exception_filters,
@@ -1075,6 +1141,7 @@ ide_command::domain!(
debug_jvm_thread_dump,
debug_listen_for_jvm,
debug_pause,
debug_read_memory,
debug_redefine_classes,
debug_replace_breakpoints,
debug_resolve_variable,
@@ -1095,6 +1162,7 @@ ide_command::domain!(
debug_step,
debug_step_in_target,
debug_step_in_targets,
debug_step_instruction,
debug_stop,
debug_threads,
debug_unity_processes,
+15
Переглянути файл
@@ -56,6 +56,20 @@ pub async fn doc_save_as(host: &Host, window: &str, doc: DocId, path: PathBuf) -
.await
}
/// Copies the current buffer, including unsaved edits, without changing the source; false for the source itself.
#[command(trust = always)]
pub async fn doc_copy_as(host: &Host, window: &str, doc: DocId, path: PathBuf) -> IdeResult<bool> {
let project = host.project(window)?;
host.blocking(move || {
let copied = project.documents.copy_as(doc, &path)?;
if let Some(dir) = path.parent().filter(|_| project.light) {
project.watch_light_dir(dir);
}
Ok(copied)
})
.await
}
/// Applies a CodeMirror change set; returns the new version. Rejects with
/// `outOfSync` when `base_version` is stale; the UI then calls `doc_snapshot`.
#[command(trust = always, desktop_body = async)]
@@ -141,6 +155,7 @@ mod tests;
ide_command::domain!(
doc:
doc_close,
doc_copy_as,
doc_edit,
doc_open,
doc_open_untitled,
+30
Переглянути файл
@@ -111,6 +111,36 @@ async fn dirty_document_keeps_edits_and_warns_once() {
assert!(f.document_events().is_empty());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn save_as_copies_the_current_buffer_and_leaves_the_source_on_disk() {
let f = Fixture::new();
let original = f.open(&f.path).await;
doc_edit(
&f.host,
"main",
original.id,
original.version,
ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "local ".into() }] },
)
.await
.unwrap();
let target = f.outside.with_extension("copy.txt");
std::fs::write(&target, "old\n").unwrap();
assert!(doc_copy_as(&f.host, "main", original.id, target.clone()).await.unwrap());
assert_eq!(std::fs::read_to_string(&f.path).unwrap(), "original\n");
assert_eq!(std::fs::read_to_string(&target).unwrap(), "local original\n");
let source = f.project.documents.snapshot(original.id).unwrap();
assert_eq!(source.path, f.path);
assert_eq!(source.text, "local original\n");
assert!(source.dirty);
let copy = f.open(&target).await;
assert_ne!(copy.id, original.id);
assert_eq!(copy.text, "local original\n");
assert!(!copy.dirty);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn deleted_document_keeps_its_buffer_and_other_documents_still_reload() {
let f = Fixture::new();
+21 -17
Переглянути файл
@@ -158,24 +158,28 @@ pub async fn fs_read_dir(host: &Host, window: &str, path: PathBuf) -> IdeResult<
// Runs on the blocking pool: on a network share (`\\wsl.localhost`) every stat is slow.
let project = host.project(window);
host.blocking(move || {
let excludes = project
.map(|p| {
// An attached project's folders follow its own exclusions.
let root = p.root_of(&path);
let globs = p.exclude_globs_in(&root);
// `read_dir` matches relative to the enclosing repository: re-anchor
// root patterns (`/build`) when the project is a repo subfolder.
let repo = root.ancestors().find(|d| d.join(".git").exists());
match repo.and_then(|r| root.strip_prefix(r).ok()).filter(|rel| !rel.as_os_str().is_empty()) {
Some(rel) => {
let rel = rel.to_string_lossy().replace('\\', "/");
globs.into_iter().map(|g| if g.starts_with('/') { format!("/{rel}{g}") } else { g }).collect()
}
None => globs,
let Ok(p) = project else { return ide_vfs::read_dir(&path, &[]) };
// An attached project's folders follow its own exclusions.
let root = p.root_of(&path);
let globs = p.exclude_globs_in(&root);
// `read_dir` matches relative to the enclosing repository: re-anchor
// root patterns (`/build`) when the project is a repo subfolder. The
// watcher already found the project folder's repository; on a network
// share each `.git` probe up the tree is a round trip.
let repo = if root == p.root && p.watcher.root() == p.root {
p.watcher.repo_root().map(Path::to_path_buf)
} else {
root.ancestors().find(|d| d.join(".git").exists()).map(Path::to_path_buf)
};
let excludes =
match repo.as_deref().and_then(|r| root.strip_prefix(r).ok()).filter(|rel| !rel.as_os_str().is_empty()) {
Some(rel) => {
let rel = rel.to_string_lossy().replace('\\', "/");
globs.into_iter().map(|g| if g.starts_with('/') { format!("/{rel}{g}") } else { g }).collect()
}
})
.unwrap_or_default();
ide_vfs::read_dir(&path, &excludes)
None => globs,
};
p.watcher.read_dir(&path, &excludes)
})
.await
}
+292
Переглянути файл
@@ -0,0 +1,292 @@
//! GitHub pull requests (`ide-github`, through the `gh` CLI) for the project of the window.
//!
//! Runs on the project host (`Host` locally, `openidea-server` in a remote window) so remote
//! SSH / WSL / dev-container projects use the remote host's `gh` CLI, repository, and
//! project-scoped `GH_TOKEN`.
use super::{Channel, blocking};
use crate::Host;
use ide_command::command;
use ide_core::{IdeError, IdeResult, RequestId};
use ide_github::{
CreatePullRequest, GhAccountRepos, GhApiRequest, GhAvailability, PrDiffRevisions, PrListQuery, PrReviewComment,
PullRequestDetails, PullRequestSummary, ReviewEvent,
};
use std::path::{Path, PathBuf};
/// The working directory of gh: the project repository `repo` names, else the project's
/// primary repository (a folder holding several repositories is not one itself).
fn root(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<PathBuf> {
let project = host.project(window)?;
if !project.git_enabled() {
return Err(IdeError::unavailable("Git integration is disabled in Settings › Version Control › Git"));
}
let repos = project.repos();
match repo {
Some(at) => match repos.at_root(&at) {
Some(r) => Ok(r.root().to_path_buf()),
None => Err(IdeError::unavailable(format!("{} is not a git repository of the project", at.display()))),
},
None => Ok(repos.primary().map_or_else(|| project.root.clone(), |r| r.root().to_path_buf())),
}
}
/// Emits `VcsChanged` after operations that move HEAD or refs (checkout, push).
fn vcs_changed(host: &Host, window: &str, root: &Path) {
if let Ok(p) = host.project(window) {
p.sink.emit(ide_core::IdeEvent::VcsChanged { root: ide_core::IpcPath(root.to_path_buf()) });
}
}
/// The repositories of the account gh is signed in to ("Get from Version Control" › GitHub); needs no project.
#[command(trust = outside_restricted)]
pub async fn gh_account_repos() -> IdeResult<GhAccountRepos> {
blocking(|| Ok(ide_github::account_repositories())).await
}
#[command(trust = trusted)]
pub async fn gh_availability(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<GhAvailability> {
let project = host.project(window)?;
let root = root(host, window, repo)?;
blocking(move || {
crate::github_auth::apply_to_project(&project);
Ok(ide_github::availability(&root))
})
.await
}
#[command(trust = trusted)]
pub async fn gh_pr_list(
host: &Host,
window: &str,
repo: Option<PathBuf>,
query: PrListQuery,
) -> IdeResult<Vec<PullRequestSummary>> {
let root = root(host, window, repo)?;
blocking(move || ide_github::list(&root, &query)).await
}
#[command(trust = trusted)]
pub async fn gh_pr_view(
host: &Host,
window: &str,
repo: Option<PathBuf>,
number: u32,
) -> IdeResult<PullRequestDetails> {
let root = root(host, window, repo)?;
blocking(move || ide_github::view(&root, number)).await
}
#[command(trust = trusted)]
pub async fn gh_pr_review_comments(
host: &Host,
window: &str,
repo: Option<PathBuf>,
number: u32,
) -> IdeResult<Vec<PrReviewComment>> {
let root = root(host, window, repo)?;
blocking(move || ide_github::review_comments(&root, number)).await
}
#[command(trust = trusted)]
pub async fn gh_pr_checkout(
host: &Host,
window: &str,
repo: Option<PathBuf>,
request: RequestId,
number: u32,
on_output: Channel<String>,
) -> IdeResult<()> {
let root = root(host, window, repo)?;
let cancel = host.begin_request(request);
let dir = root.clone();
let result = blocking(move || {
ide_github::checkout(&dir, number, &cancel, &|line| {
let _ = on_output.send(line);
})
})
.await;
host.end_request(request);
vcs_changed(host, window, &root);
result
}
/// Creates a pull request from the current branch (pushing it first when asked); returns its URL.
#[command(trust = trusted)]
pub async fn gh_pr_create(
host: &Host,
window: &str,
repo: Option<PathBuf>,
request: RequestId,
pr: CreatePullRequest,
on_output: Channel<String>,
) -> IdeResult<String> {
let root = root(host, window, repo)?;
let git = host.project(window)?.git_executable();
let cancel = host.begin_request(request);
let dir = root.clone();
let result = blocking(move || {
ide_vcs::with_git_executable(git.as_deref(), || {
ide_github::create(&dir, &pr, &cancel, &|line| {
let _ = on_output.send(line);
})
})
})
.await;
host.end_request(request);
vcs_changed(host, window, &root);
result
}
#[command(trust = trusted)]
pub async fn gh_pr_review(
host: &Host,
window: &str,
repo: Option<PathBuf>,
number: u32,
event: ReviewEvent,
body: String,
) -> IdeResult<()> {
let root = root(host, window, repo)?;
blocking(move || ide_github::submit_review(&root, number, event, &body)).await
}
#[command(trust = trusted)]
pub async fn gh_pr_comment(
host: &Host,
window: &str,
repo: Option<PathBuf>,
number: u32,
body: String,
) -> IdeResult<()> {
let root = root(host, window, repo)?;
blocking(move || ide_github::add_comment(&root, number, &body)).await
}
/// A GitHub GraphQL / REST call through `gh api`; returns the response body.
#[command(trust = trusted)]
pub async fn gh_api(host: &Host, window: &str, repo: Option<PathBuf>, request: GhApiRequest) -> IdeResult<String> {
let root = root(host, window, repo)?;
blocking(move || ide_github::api(&root, &request)).await
}
/// Fetches what is missing to diff a pull request locally; returns the revisions to compare.
#[command(trust = trusted)]
#[allow(clippy::too_many_arguments)]
pub async fn gh_pr_prepare_diff(
host: &Host,
window: &str,
repo: Option<PathBuf>,
request: RequestId,
number: u32,
head_oid: String,
base_oid: String,
base_ref: String,
name_with_owner: String,
on_output: Channel<String>,
) -> IdeResult<PrDiffRevisions> {
let root = root(host, window, repo)?;
let git = host.project(window)?.git_executable();
let cancel = host.begin_request(request);
let result = blocking(move || {
let output = |line: String| {
let _ = on_output.send(line);
};
ide_vcs::with_git_executable(git.as_deref(), || {
ide_github::prepare_diff(&root, number, &head_oid, &base_oid, &base_ref, &name_with_owner, &cancel, &output)
})
})
.await;
host.end_request(request);
result
}
ide_command::domain!(
github:
gh_account_repos,
gh_api,
gh_availability,
gh_pr_checkout,
gh_pr_comment,
gh_pr_create,
gh_pr_list,
gh_pr_prepare_diff,
gh_pr_review,
gh_pr_review_comments,
gh_pr_view,
);
#[cfg(test)]
mod tests {
use super::root;
use crate::catalogue::TrustClass;
use crate::rpc::Dispatcher;
use crate::{Host, HostConfig};
use ide_core::error::ErrorKind;
use ide_workspace::SettingsScope;
use std::path::Path;
use std::sync::Arc;
fn test_host(base: &Path) -> Host {
Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
})
}
#[test]
fn registers_github_commands_on_the_remote_rpc_dispatcher() {
let dispatcher = Dispatcher::standard();
assert_eq!(dispatcher.trust("gh_account_repos"), Some(TrustClass::OutsideRestricted));
for name in [
"gh_api",
"gh_availability",
"gh_pr_checkout",
"gh_pr_comment",
"gh_pr_create",
"gh_pr_list",
"gh_pr_prepare_diff",
"gh_pr_review",
"gh_pr_review_comments",
"gh_pr_view",
] {
assert_eq!(dispatcher.trust(name), Some(TrustClass::Trusted), "{name}");
}
}
#[tokio::test]
async fn authorizes_account_repos_without_a_project_and_scopes_repo_lookup_to_project() {
let dir = tempfile::tempdir().unwrap();
let host = test_host(dir.path());
assert!(host.authorize("main", TrustClass::OutsideRestricted).is_ok());
let err = host.authorize("main", TrustClass::Trusted).unwrap_err();
assert_eq!(err.kind, ErrorKind::NotFound);
let proj_dir = dir.path().join("repo");
std::fs::create_dir_all(&proj_dir).unwrap();
host.open_project("main", &proj_dir).unwrap();
assert_eq!(root(&host, "main", None).unwrap(), dunce::canonicalize(&proj_dir).unwrap());
let outsider = root(&host, "main", Some(dir.path().join("other"))).unwrap_err();
assert_eq!(outsider.kind, ErrorKind::Unavailable);
}
#[tokio::test]
async fn refuses_gh_while_git_integration_is_off() {
let dir = tempfile::tempdir().unwrap();
let host = test_host(dir.path());
let proj_dir = dir.path().join("repo");
std::fs::create_dir_all(&proj_dir).unwrap();
host.global_settings.set(SettingsScope::Global, "vcs.git.enabled", serde_json::json!(false)).unwrap();
host.open_project("main", &proj_dir).unwrap();
let err = root(&host, "main", None).unwrap_err();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert!(err.message.contains("Git integration is disabled"), "{}", err.message);
}
}
+40
Переглянути файл
@@ -0,0 +1,40 @@
//! iOS Simulators for Xcode projects, through `xcrun simctl` on the project host.
use crate::Host;
use ide_command::command;
use ide_core::{IdeError, IdeResult};
use ide_run::simulator::{self, IosSimulator};
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
/// The available iOS simulators, booted first; `None` outside macOS or when the project has no
/// Xcode project or workspace at its root. Asked again whenever the chooser opens: `simctl` has
/// no change feed, and one listing takes a fraction of a second.
#[command(trust = trusted)]
pub async fn ios_simulators(host: &Host, window: &str) -> IdeResult<Option<Vec<IosSimulator>>> {
let root = host.project(window)?.root.clone();
if !cfg!(target_os = "macos") || !simulator::is_xcode_project(&root) {
return Ok(None);
}
blocking(simulator::list).await.map(Some)
}
/// Boots a simulator; returns once it is booted.
#[command(trust = trusted)]
pub async fn ios_simulator_boot(_host: &Host, udid: String) -> IdeResult<()> {
blocking(move || simulator::boot(&udid)).await
}
#[command(trust = trusted)]
pub async fn ios_simulator_shutdown(_host: &Host, udid: String) -> IdeResult<()> {
blocking(move || simulator::shutdown(&udid)).await
}
/// Opens Simulator.app.
#[command(trust = trusted)]
pub async fn ios_simulator_open_app(_host: &Host) -> IdeResult<()> {
blocking(simulator::open_app).await
}
ide_command::domain!(ios: ios_simulators, ios_simulator_boot, ios_simulator_shutdown, ios_simulator_open_app);
+175 -44
Переглянути файл
@@ -84,7 +84,7 @@ pub(crate) async fn resolve_launch(
let build = policy != BuildPolicy::NoBuild;
let full = policy == BuildPolicy::Rebuild;
let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, external, mut delegated, is_maven, non_java, served) = {
let (model, external, mut delegated, is_maven, non_java, served, needs_cleanup) = {
let scope = scope.clone();
let launches = launches.clone();
let module = module.clone();
@@ -95,16 +95,11 @@ pub(crate) async fn resolve_launch(
let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test);
let is_maven = is_maven_module(root, &model, &module);
let served = served_by_service(root, &model, &scope.settings, &module);
let delegated = build
&& delegates_to_external_build(
is_maven,
policy,
non_java,
cache::has_record(root, &scope.cache, &module),
prefer_maven,
);
let needs_cleanup = build && is_maven && cache::needs_cleanup(root, &scope.cache, &model, &module, test);
let delegated =
build && delegates_to_external_build(is_maven, policy, non_java, needs_cleanup, prefer_maven);
let external = non_java || delegated;
(std::sync::Arc::new(model), external, delegated, is_maven, non_java, served)
(std::sync::Arc::new(model), external, delegated, is_maven, non_java, served, needs_cleanup)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -117,7 +112,7 @@ pub(crate) async fn resolve_launch(
// the launch debugs with java-debug, whose HotSwap reloads what jdtls compiles (ecj's
// classes differ from javac's: lambda names). jdtls keeps building for its diagnostics
// either way.
if served && !non_java && !debug {
if served && !non_java && !debug && !needs_cleanup {
let built = {
let (service, data_dir, scope, model, module, cancel, events) = (
host.java_build.clone(),
@@ -549,38 +544,24 @@ async fn resolve_launch_without_jdtls(
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
match from_server {
// The IDE's Java build gave the whole classpath; the server adds its JDK.
Some(server) if by_service => {
info.project_root = server.classpath.project_root;
info.java_home = server.jdk_home.map(Into::into);
}
None if by_service => {}
Some(server) => {
info.project_root = server.classpath.project_root;
info.module_paths = server.classpath.module_paths;
info.java_home = server.jdk_home.map(Into::into);
append_unique_class_paths(&mut class_paths, server.classpath.class_paths);
}
None => {
if !is_maven_module(root, &model, &module) {
return Err(IdeError::unavailable(
"Cannot resolve the classpath: the Java language server does not report it \
(java-analyzer/projectClasspath), and the module is not a Maven project",
));
}
let is_maven = is_maven_module(root, &model, &module);
let delegated_maven = !by_service && settings.languages.java.maven.delegate_build && is_maven;
apply_without_jdtls_classpath(
&mut class_paths,
&mut info,
from_server,
by_service,
is_maven,
delegated_maven,
|| {
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
let classpath = if aggregator && policy == BuildPolicy::NoBuild {
compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel)?
if aggregator && policy == BuildPolicy::NoBuild {
compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel)
} else {
compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?
};
append_unique_class_paths(
&mut class_paths,
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
);
}
}
compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)
}
},
)?;
info.class_paths = class_paths;
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
@@ -806,7 +787,7 @@ fn joining_launches(
is_maven,
o.policy,
compile::launch_has_non_java_sources(root, model, &o.module, test),
cache::has_record(root, cache_dir, &o.module),
is_maven && cache::needs_cleanup(root, cache_dir, model, &o.module, test),
prefer_maven,
)
})
@@ -820,16 +801,69 @@ fn delegates_to_external_build(
is_maven: bool,
policy: BuildPolicy,
non_java: bool,
has_record: bool,
needs_cleanup: bool,
prefer_maven: bool,
) -> bool {
is_maven && (prefer_maven || policy == BuildPolicy::Rebuild || non_java || has_record)
is_maven && (prefer_maven || policy == BuildPolicy::Rebuild || non_java || needs_cleanup)
}
fn same_entry(a: &str, b: &str, windows: bool) -> bool {
a == b || entry_key(a, windows) == entry_key(b, windows)
}
/// Resolves the runtime/test classpath for a launch without jdtls (e.g. `java-analyzer` or
/// no Java language server). When `delegated_maven` is true (`delegateBuild = true` on a Maven
/// module), delegates classpath resolution to Maven itself (falling back to the language server's
/// classpath on error, matching the jdtls path) so child POM `<exclusions>` and Maven dependency
/// mediation are respected (#5586).
fn apply_without_jdtls_classpath(
class_paths: &mut Vec<String>,
info: &mut JavaLaunchInfo,
from_server: Option<ide_lsp::java_project::ServerClasspath>,
by_service: bool,
is_maven: bool,
delegated_maven: bool,
probe_maven: impl FnOnce() -> IdeResult<String>,
) -> IdeResult<()> {
match from_server {
// The IDE's Java build gave the whole classpath; the server adds its JDK.
Some(server) if by_service => {
info.project_root = server.classpath.project_root;
info.java_home = server.jdk_home.map(Into::into);
Ok(())
}
None if by_service => Ok(()),
Some(server) if delegated_maven => {
info.project_root = server.classpath.project_root;
info.module_paths = server.classpath.module_paths;
info.java_home = server.jdk_home.map(Into::into);
info.class_paths = server.classpath.class_paths;
merge_maven_launch_classpath(class_paths, info, probe_maven(), &[])
}
Some(server) => {
info.project_root = server.classpath.project_root;
info.module_paths = server.classpath.module_paths;
info.java_home = server.jdk_home.map(Into::into);
append_unique_class_paths(class_paths, server.classpath.class_paths);
Ok(())
}
None => {
if !is_maven {
return Err(IdeError::unavailable(
"Cannot resolve the classpath: the Java language server does not report it \
(java-analyzer/projectClasspath), and the module is not a Maven project",
));
}
let classpath = probe_maven()?;
append_unique_class_paths(
class_paths,
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
);
Ok(())
}
}
}
/// Merge the Maven launch classpath without turning a recoverable probe failure into a
/// failed launch. Cancellation still propagates; ordinary failures keep jdtls' classpath
/// and leave the reason in the run console. Maven lists the module's and its reactor
@@ -1264,6 +1298,55 @@ mod tests {
);
}
#[test]
fn delegated_maven_without_jdtls_prefers_maven_classpath_over_server_classpath() {
let server = ide_lsp::java_project::ServerClasspath {
classpath: ide_lsp::jdtls::JavaClasspath {
project_root: Some(PathBuf::from("/work/child").into()),
// Static server resolver kept an excluded parent transitive jar (#5586).
class_paths: vec![
"/work/child/target/classes".into(),
"/m2/log4j-slf4j-impl-2.12.1.jar".into(),
"/m2/logback-classic.jar".into(),
],
module_paths: vec![],
},
jdk_home: Some(PathBuf::from("/jdk8")),
};
let maven = std::env::join_paths(["/work/child/target/classes", "/m2/logback-classic.jar"])
.unwrap()
.to_string_lossy()
.into_owned();
let mut class_paths = vec!["/work/child/target/classes".to_owned()];
let mut info = JavaLaunchInfo::default();
apply_without_jdtls_classpath(&mut class_paths, &mut info, Some(server), false, true, true, || Ok(maven))
.unwrap();
assert_eq!(class_paths, ["/work/child/target/classes", "/m2/logback-classic.jar"]);
assert_eq!(info.project_root, Some(PathBuf::from("/work/child").into()));
assert_eq!(info.java_home, Some(PathBuf::from("/jdk8").into()));
assert!(info.hints.is_empty(), "{:?}", info.hints);
}
#[test]
fn delegated_maven_without_jdtls_falls_back_to_server_classpath_on_probe_error() {
let server = ide_lsp::java_project::ServerClasspath {
classpath: ide_lsp::jdtls::JavaClasspath {
project_root: Some(PathBuf::from("/work/child").into()),
class_paths: vec!["/m2/server-fallback.jar".into()],
module_paths: vec![],
},
jdk_home: None,
};
let mut class_paths = vec!["/work/child/target/classes".to_owned()];
let mut info = JavaLaunchInfo::default();
apply_without_jdtls_classpath(&mut class_paths, &mut info, Some(server), false, true, true, || {
Err(IdeError::internal("maven offline"))
})
.unwrap();
assert_eq!(class_paths, ["/work/child/target/classes", "/m2/server-fallback.jar"]);
assert!(info.hints[0].contains("maven offline"), "{:?}", info.hints);
}
#[test]
fn cancelled_maven_classpath_probe_propagates_without_fallback() {
let mut class_paths = vec!["snapshot.jar".to_owned()];
@@ -1288,6 +1371,54 @@ mod tests {
assert!(!delegates_to_external_build(false, BuildPolicy::Automatic, false, false, true));
}
#[test]
fn shared_builds_do_not_join_plain_java_launches_only_because_of_legacy_null_records() {
use std::{fs, sync::Arc};
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let cache_dir = root.join("cache");
fs::write(
root.join("pom.xml"),
concat!(
"<project><groupId>sample</groupId><artifactId>root</artifactId><version>1</version>",
"<packaging>pom</packaging><modules><module>leader</module><module>plain</module>",
"<module>dirty</module></modules></project>",
),
)
.unwrap();
for name in ["leader", "plain", "dirty"] {
let module = root.join(name);
fs::create_dir_all(module.join("src/main/java")).unwrap();
fs::write(module.join("src/main/java/Main.java"), "class Main {}").unwrap();
fs::write(
module.join("pom.xml"),
format!(
"<project><groupId>sample</groupId><artifactId>{name}</artifactId><version>1</version></project>"
),
)
.unwrap();
let records = cache_dir.join("java-launch/records").join(name);
fs::create_dir_all(&records).unwrap();
fs::write(records.join("main.json"), b"null").unwrap();
}
fs::create_dir_all(root.join("dirty/target/classes")).unwrap();
fs::write(root.join("dirty/target/classes/Old.class"), "old-output").unwrap();
let model = ide_build::load(root, &cache_dir, None);
let waiting = ["plain", "dirty"]
.into_iter()
.map(|name| {
Arc::new(cache::WaitingLaunch {
module: root.join(name),
test: false,
policy: BuildPolicy::Automatic,
events: None,
})
})
.collect();
let joined = joining_launches(root, &cache_dir, &model, &root.join("leader"), false, waiting, false);
assert_eq!(joined.iter().map(|launch| &launch.module).collect::<Vec<_>>(), [&root.join("dirty")]);
}
#[test]
fn successful_external_compilation_does_not_erase_scoped_jdt_errors() {
for (failure, expected) in
+270 -18
Переглянути файл
@@ -1,4 +1,6 @@
//! Immutable Maven outputs retained in the project cache, including across close/reopen.
mod delegation;
use ide_build::compile::{self, BuildEvent, LaunchFingerprint};
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_run::BuildPolicy;
@@ -127,8 +129,14 @@ fn record_path(root: &Path, cache: &Path, module: &Path, test: bool) -> Option<P
}))
}
pub(super) fn has_record(root: &Path, cache: &Path, module: &Path) -> bool {
[false, true].into_iter().any(|test| record_path(root, cache, module, test).is_some_and(|record| record.is_file()))
pub(super) fn needs_cleanup(
root: &Path,
cache: &Path,
model: &ide_build::BuildModel,
module: &Path,
test: bool,
) -> bool {
delegation::required(root, cache, model, module, test)
}
/// Where the build of a launch streams its console, messages and progress: the run
@@ -233,6 +241,8 @@ struct Pending {
record: PathBuf,
before: Option<LaunchFingerprint>,
previous: Option<Outputs>,
non_java: bool,
cleanup: bool,
}
/// Owned by Project: running JVMs may still load superseded outputs until it drops.
@@ -296,13 +306,13 @@ impl Session {
// clean rebuild that replaces JDT's error-stub classes.
let policy = if rebuild_on_jdt_errors { BuildPolicy::Rebuild } else { policy };
let mut joined = Vec::new();
let mut rebuild = policy == BuildPolicy::Rebuild;
let mut rebuild = policy == BuildPolicy::Rebuild || lead.cleanup;
let mut sinks: Vec<LaunchEvents> = events.into_iter().collect();
for member in members {
if let Err(pending) =
self.prepare(root, model, &member.module, test, BuildPolicy::Make, &local_repo, cancel)?
{
rebuild |= member.rebuild_on_jdt_errors;
rebuild |= member.rebuild_on_jdt_errors || pending.cleanup;
sinks.extend(member.events);
joined.push(pending);
}
@@ -366,6 +376,9 @@ impl Session {
let snapshots = self.cache.join("java-launch/snapshots");
let mut before = fingerprint(root, model, module, test, local_repo, cancel)?;
let previous = fs::read(&record).ok().and_then(|bytes| serde_json::from_slice::<Outputs>(&bytes).ok());
let non_java = compile::launch_has_non_java_sources(root, model, module, test);
let needs_cleanup = needs_cleanup(root, &self.cache, model, module, test);
let cleanup = needs_cleanup && !non_java;
// Timestamp-incremental builders (Maven, the Kotlin plugin) skip sources whose
// mtime did not advance. An external edit that preserves both length and mtime
// invalidates the fingerprint but would still compile to nothing below, and the
@@ -388,6 +401,7 @@ impl Session {
}
if let Some(outputs) = previous.as_ref()
&& policy != BuildPolicy::Rebuild
&& !cleanup
&& let Some(maven) = &model.maven
&& outputs.reusable(
&before,
@@ -405,14 +419,18 @@ impl Session {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
// Retain a non-reusable record even on failure, so removing the final mixed
// source still delegates to Maven to clean its old classes on the next launch.
fs::create_dir_all(record.parent().unwrap())?;
fs::write(&record, b"null")?;
// Preserve build ownership independently of the reusable snapshot. In particular,
// a plain Java build that fails must not force delegation after the user disables it.
delegation::remember(root, &self.cache, module, test, non_java || needs_cleanup)?;
match fs::remove_file(&record) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
if let Some(previous) = &previous {
self.unreferenced.push(previous.snapshot.clone());
}
Ok(Err(Pending { module: module.to_path_buf(), record, before, previous }))
Ok(Err(Pending { module: module.to_path_buf(), record, before, previous, non_java, cleanup }))
}
/// Copies the built outputs of a prepared module into a new snapshot and records it
@@ -487,6 +505,10 @@ impl Session {
write_record(&pending.record, &outputs)?;
self.unreferenced.retain(|path| path != &outputs.snapshot);
}
if outputs.failure.is_none() && authoritative {
let mixed = pending.non_java || compile::launch_has_non_java_sources(root, model, &pending.module, test);
delegation::cleaned(root, &self.cache, &pending.module, test, mixed)?;
}
Ok(outputs)
}
}
@@ -509,7 +531,7 @@ fn fingerprint(
}
}
fn write_record(record: &Path, outputs: &Outputs) -> IdeResult<()> {
fn write_record(record: &Path, outputs: &impl Serialize) -> IdeResult<()> {
fs::create_dir_all(record.parent().unwrap())?;
let mut file = tempfile::NamedTempFile::new_in(record.parent().unwrap())?;
serde_json::to_writer(file.as_file_mut(), outputs).map_err(|e| IdeError::internal(e.to_string()))?;
@@ -530,7 +552,7 @@ impl Drop for Session {
}
/// Clears the fingerprint of every launch record under `cache`, so no snapshot matches the
/// sources any more. The records stay: their modules keep delegating to Maven.
/// sources any more. Delegation ownership is stored separately and is not invalidated.
fn forget_reusable_snapshots(cache: &Path) -> std::io::Result<()> {
let records = cache.join("java-launch/records");
if !records.try_exists()? {
@@ -609,6 +631,231 @@ fn sweep(cache: &Path) -> std::io::Result<()> {
Ok(())
}
#[cfg(test)]
mod delegation_tests {
use super::*;
fn fixture(root: &Path, mixed: bool) -> ide_build::BuildModel {
fs::write(
root.join("pom.xml"),
r#"<project><groupId>sample</groupId><artifactId>app</artifactId><version>1</version></project>"#,
)
.unwrap();
fs::create_dir_all(root.join("src/main/java")).unwrap();
fs::write(root.join("src/main/java/Main.java"), "java-source").unwrap();
if mixed {
fs::create_dir_all(root.join("src/main/kotlin")).unwrap();
fs::write(root.join("src/main/kotlin/Extra.kt"), "mixed-source").unwrap();
}
// A synthetic Maven wrapper: no JDK, Maven installation or network required.
#[cfg(windows)]
fs::write(root.join("mvnw.cmd"), concat!(
"@echo off\r\necho %*>>calls\r\n",
"if exist fail-build exit /b 1\r\n",
"for %%a in (%*) do if \"%%a\"==\"clean\" if exist target rmdir /s /q target\r\n",
"if not exist target\\classes mkdir target\\classes\r\n",
"copy /y src\\main\\java\\Main.java target\\classes\\Main.class >nul\r\n",
"if exist src\\main\\kotlin\\Extra.kt copy /y src\\main\\kotlin\\Extra.kt target\\classes\\Extra.class >nul\r\n",
"if exist edit-during-build echo changed>>src\\main\\java\\Main.java\r\n",
"if exist block-record (\r\n",
"if not exist cache\\java-launch\\records mkdir cache\\java-launch\\records\r\n",
"if exist cache\\java-launch\\records\\main.json del /q cache\\java-launch\\records\\main.json\r\n",
"mkdir cache\\java-launch\\records\\main.json\r\n",
")\r\n",
"exit /b 0\r\n",
)).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let script = root.join("mvnw");
fs::write(&script, concat!(
"#!/bin/sh\nset -e\nprintf '%s\\n' \"$*\" >> calls\n",
"if [ -f fail-build ]; then exit 1; fi\n",
"for arg in \"$@\"; do if [ \"$arg\" = clean ]; then rm -rf target; fi; done\n",
"mkdir -p target/classes\ncp src/main/java/Main.java target/classes/Main.class\n",
"if [ -f src/main/kotlin/Extra.kt ]; then cp src/main/kotlin/Extra.kt target/classes/Extra.class; fi\n",
"if [ -f edit-during-build ]; then echo changed >> src/main/java/Main.java; fi\n",
"if [ -f block-record ]; then\n",
"mkdir -p cache/java-launch/records\nrm -f cache/java-launch/records/main.json\n",
"mkdir cache/java-launch/records/main.json\nfi\n",
)).unwrap();
fs::set_permissions(script, fs::Permissions::from_mode(0o755)).unwrap();
}
ide_build::load(root, &root.join("cache"), None)
}
fn legacy(root: &Path, test: bool, bytes: &[u8]) {
let record = record_path(root, &root.join("cache"), root, test).unwrap();
fs::create_dir_all(record.parent().unwrap()).unwrap();
fs::write(record, bytes).unwrap();
}
fn calls(root: &Path) -> Vec<String> {
fs::read_to_string(root.join("calls")).unwrap_or_default().lines().map(str::to_owned).collect()
}
#[test]
fn failed_record_publication_keeps_new_and_previous_snapshots_until_session_drop() {
for has_previous in [false, true] {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root, false);
let cache = root.join("cache");
let cancel = CancellationToken::new();
let mut session = Session::new(cache.clone());
if has_previous {
session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
}
fs::write(root.join("src/main/java/Main.java"), "edited-java-source").unwrap();
fs::write(root.join("block-record"), "").unwrap();
let error = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap_err();
// Reach publication, rather than accepting an earlier wrapper/build failure.
assert!(!error.message.starts_with("Build failed:"), "{error:?}");
assert!(cache.join("java-launch/records/main.json").is_dir());
assert_eq!(session.unreferenced.len(), if has_previous { 2 } else { 1 });
let snapshots = session.unreferenced.clone();
assert_eq!(
fs::read_to_string(snapshots.last().unwrap().join("0/Main.class")).unwrap(),
"edited-java-source"
);
assert!(snapshots.iter().all(|p| p.join("0/Main.class").is_file()));
drop(session);
assert!(snapshots.iter().all(|p| !p.exists()));
}
}
#[test]
fn null_record_without_outputs_does_not_keep_delegation() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let cache = root.join("cache");
let model = fixture(root, false);
legacy(root, false, b"null");
assert!(!needs_cleanup(root, &cache, &model, root, false));
// The IDE's Java builder may produce outputs afterwards: migration must stick.
fs::create_dir_all(root.join("target/classes")).unwrap();
fs::write(root.join("target/classes/Main.class"), "java-output").unwrap();
assert!(!needs_cleanup(root, &cache, &model, root, false));
assert!(calls(root).is_empty());
}
#[test]
fn plain_java_failures_and_unpublished_snapshots_do_not_require_maven() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root, false);
let cache = root.join("cache");
let cancel = CancellationToken::new();
let mut session = Session::new(cache.clone());
fs::write(root.join("fail-build"), "").unwrap();
assert!(session.build(root, &model, root, BuildOptions::default(), None, &cancel).is_err());
assert!(!needs_cleanup(root, &cache, &model, root, false));
fs::remove_file(root.join("fail-build")).unwrap();
fs::write(root.join("edit-during-build"), "").unwrap();
let outputs = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert!(outputs.fingerprint.is_none());
assert!(!cache.join("java-launch/records/main.json").exists());
assert!(!needs_cleanup(root, &cache, &model, root, false));
// A valid snapshot is also not a reason to override the user's build preference.
fs::remove_file(root.join("edit-during-build")).unwrap();
session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert!(cache.join("java-launch/records/main.json").is_file());
assert!(!needs_cleanup(root, &cache, &model, root, false));
}
#[test]
fn legacy_null_or_damaged_records_with_outputs_are_cleaned_once() {
for bytes in [b"null".as_slice(), b"{invalid".as_slice()] {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root, false);
let cache = root.join("cache");
legacy(root, false, bytes);
fs::create_dir_all(root.join("target/classes")).unwrap();
fs::write(root.join("target/classes/Old.class"), "unknown-old-output").unwrap();
assert!(needs_cleanup(root, &cache, &model, root, false));
let mut session = Session::new(cache.clone());
session.build(root, &model, root, BuildOptions::default(), None, &CancellationToken::new()).unwrap();
drop(session);
assert!(!root.join("target/classes/Old.class").exists());
assert!(!needs_cleanup(root, &cache, &model, root, false));
assert_eq!(calls(root).len(), 1);
assert!(calls(root)[0].contains("clean"));
}
}
#[test]
fn a_legacy_reusable_snapshot_cannot_skip_pending_cleanup() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root, false);
let cache = root.join("cache");
let cancel = CancellationToken::new();
let mut session = Session::new(cache.clone());
let before = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
// Simulate a successful record written before ownership was tracked separately.
fs::remove_file(cache.join("java-launch/delegation/main.json")).unwrap();
assert!(needs_cleanup(root, &cache, &model, root, false));
let after = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_ne!(before.snapshot, after.snapshot);
assert_eq!(calls(root).len(), 2);
assert!(calls(root)[1].contains("clean"));
assert!(!needs_cleanup(root, &cache, &model, root, false));
}
#[test]
fn mixed_cleanup_survives_failure_and_reopen_then_releases_delegation() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root, true);
let cache = root.join("cache");
let cancel = CancellationToken::new();
let mut session = Session::new(cache.clone());
session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert!(root.join("target/classes/Extra.class").is_file());
fs::remove_file(root.join("src/main/kotlin/Extra.kt")).unwrap();
fs::write(root.join("fail-build"), "").unwrap();
assert!(session.build(root, &model, root, BuildOptions::default(), None, &cancel).is_err());
drop(session);
assert!(needs_cleanup(root, &cache, &model, root, false));
fs::remove_file(root.join("fail-build")).unwrap();
let mut session = Session::new(cache.clone());
session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert!(!root.join("target/classes/Extra.class").exists());
assert!(!needs_cleanup(root, &cache, &model, root, false));
assert_eq!(calls(root).len(), 3);
assert!(calls(root)[1..].iter().all(|call| call.contains("clean")));
}
#[test]
fn test_cleanup_does_not_force_a_main_launch_and_a_clean_test_build_releases_both_modes() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root, false);
let cache = root.join("cache");
legacy(root, true, b"null");
fs::create_dir_all(root.join("target/test-classes")).unwrap();
fs::write(root.join("target/test-classes/OldTest.class"), "old-test-output").unwrap();
assert!(!needs_cleanup(root, &cache, &model, root, false));
assert!(needs_cleanup(root, &cache, &model, root, true));
delegation::remember(root, &cache, root, false, true).unwrap();
let mut session = Session::new(cache.clone());
session
.build(
root,
&model,
root,
BuildOptions { test: true, ..Default::default() },
None,
&CancellationToken::new(),
)
.unwrap();
assert!(!needs_cleanup(root, &cache, &model, root, false));
assert!(!needs_cleanup(root, &cache, &model, root, true));
assert!(!root.join("target/test-classes/OldTest.class").exists());
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
@@ -864,7 +1111,7 @@ mod tests {
// Build › Rebuild cleans the outputs and compiles again.
fs::remove_file(root.join("target/classes/Stale.class")).unwrap();
session.forget_reusable_snapshots();
assert!(has_record(root, &root.join("cache"), root));
assert!(needs_cleanup(root, &root.join("cache"), &model, root, false));
let next = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_ne!(next.snapshot, first.snapshot);
assert!(!next.snapshot.join("0/Stale.class").exists());
@@ -943,7 +1190,7 @@ mod tests {
assert_ne!(rebuilt.snapshot, updated.snapshot);
fs::write(root.join("src/main/kotlin/broken"), "broken").unwrap();
assert!(build().is_err());
assert_eq!(fs::read(cache.join("java-launch/records/main.json")).unwrap(), b"null");
assert!(!cache.join("java-launch/records/main.json").exists());
fs::remove_file(root.join("src/main/kotlin/broken")).unwrap();
assert_ne!(rebuilt.snapshot, build().unwrap().snapshot, "a failed build invalidates success");
cancel.cancel();
@@ -1097,11 +1344,16 @@ mod tests {
let model = fixture(root);
let script = root.join("mvnw");
let mut text = fs::read_to_string(&script).unwrap();
text.push_str("rm cache/java-launch/records/main.json\nmkdir cache/java-launch/records/main.json\n");
// Snapshot invalidation no longer writes a null record or creates its parent.
// Arrange a publish failure independently of that earlier implementation detail.
text.push_str("mkdir -p cache/java-launch/records\nrm -f cache/java-launch/records/main.json\nmkdir cache/java-launch/records/main.json\n");
fs::write(script, text).unwrap();
let cache = root.join("cache");
let mut session = Session::new(cache.clone());
assert!(session.build(root, &model, root, BuildOptions::default(), None, &CancellationToken::new()).is_err());
let error =
session.build(root, &model, root, BuildOptions::default(), None, &CancellationToken::new()).unwrap_err();
assert!(!error.message.starts_with("Build failed:"), "{error:?}");
assert!(cache.join("java-launch/records/main.json").is_dir());
assert_eq!(session.unreferenced.len(), 1);
let snapshot = session.unreferenced[0].clone();
assert!(snapshot.join("0/Main.class").is_file());
@@ -1123,7 +1375,7 @@ mod tests {
let outputs =
session.build(root, &model, root, BuildOptions::default(), None, &CancellationToken::new()).unwrap();
assert!(outputs.fingerprint.is_none());
assert_eq!(fs::read(cache.join("java-launch/records/main.json")).unwrap(), b"null");
assert!(!cache.join("java-launch/records/main.json").exists());
assert!(outputs.snapshot.join("0/Main.class").is_file());
drop(session);
assert!(!outputs.snapshot.exists());
@@ -1265,9 +1517,9 @@ mod tests {
let first = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
fs::remove_file(root.join("src/main/kotlin/Main.kt")).unwrap();
assert!(!compile::launch_has_non_java_sources(root, &model, root, false));
assert!(has_record(root, &cache, root));
assert!(needs_cleanup(root, &cache, &model, root, false));
assert!(session.build(root, &model, root, BuildOptions::default(), None, &cancel).is_err());
assert!(has_record(root, &cache, root));
assert!(needs_cleanup(root, &cache, &model, root, false));
fs::write(root.join("src/main/kotlin/Main.kt"), "restored").unwrap();
let restored = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_ne!(first.snapshot, restored.snapshot);
+81
Переглянути файл
@@ -0,0 +1,81 @@
//! Build ownership is independent of whether a launch snapshot can be reused.
use super::{record_path, write_record};
use ide_build::{BuildModel, compile};
use ide_core::IdeResult;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
#[derive(Serialize, Deserialize)]
struct State {
/// External outputs may contain classes that JDT cannot remove after the final
/// Kotlin/Groovy/Scala source is deleted. Only a successful clean clears this.
needs_cleanup: bool,
}
fn state_path(root: &Path, cache: &Path, module: &Path, test: bool) -> Option<PathBuf> {
Some(cache.join("java-launch/delegation").join(module.strip_prefix(root).ok()?).join(if test {
"test.json"
} else {
"main.json"
}))
}
/// A test launch also uses main outputs; a main launch does not use test outputs.
pub(super) fn required(root: &Path, cache: &Path, model: &BuildModel, module: &Path, test: bool) -> bool {
mode_required(root, cache, model, module, false) || (test && mode_required(root, cache, model, module, true))
}
fn mode_required(root: &Path, cache: &Path, model: &BuildModel, module: &Path, test: bool) -> bool {
let Some(state) = state_path(root, cache, module, test) else { return false };
match fs::read(&state) {
Ok(bytes) => {
// A damaged ownership marker must not silently abandon pending cleanup.
return serde_json::from_slice::<State>(&bytes).map_or(true, |state| state.needs_cleanup);
}
Err(e) if e.kind() == ErrorKind::NotFound => {}
Err(_) => return true,
}
let Some(record) = record_path(root, cache, module, test).filter(|p| p.is_file()) else { return false };
let Some(maven) = &model.maven else { return false };
// Old records (including `null`) did not record why Maven owned the outputs.
// If outputs remain, clean once rather than guessing that they are all Java.
// Persist even a negative migration: subsequent JDT output must not turn an
// already ignored legacy record back into a reason to delegate.
let needs_cleanup = compile::maven_launch_output_dirs(root, maven, module, test).iter().any(|dir| dir.is_dir());
let publish = || -> std::io::Result<()> {
fs::create_dir_all(state.parent().unwrap())?;
let mut file = tempfile::NamedTempFile::new_in(state.parent().unwrap())?;
serde_json::to_writer(file.as_file_mut(), &State { needs_cleanup })?;
// Another launch may already have migrated or started building this mode.
file.persist_noclobber(&state).map_err(|e| e.error)?;
Ok(())
};
match publish() {
Ok(()) => needs_cleanup,
Err(e) if e.kind() == ErrorKind::AlreadyExists => mode_required(root, cache, model, module, test),
Err(error) => {
tracing::warn!(%error, path = %record.display(), "Cannot migrate Java launch delegation state");
needs_cleanup
}
}
}
/// Called before invalidating a snapshot or running an external build. A plain
/// Java failure records `false`; it must not override a later delegateBuild=false.
pub(super) fn remember(root: &Path, cache: &Path, module: &Path, test: bool, needs_cleanup: bool) -> IdeResult<()> {
if let Some(path) = state_path(root, cache, module, test) {
write_record(&path, &State { needs_cleanup })?;
}
Ok(())
}
pub(super) fn cleaned(root: &Path, cache: &Path, module: &Path, test: bool, mixed: bool) -> IdeResult<()> {
remember(root, cache, module, test, mixed)?;
if test && !mixed {
// A clean test build includes the main outputs and their reactor dependencies.
remember(root, cache, module, false, false)?;
}
Ok(())
}
+60 -3
Переглянути файл
@@ -336,20 +336,36 @@ pub async fn lsp_inline_completion(
let plugin = match plugin_providers(host, window, doc, ProviderKind::InlineCompletion) {
Some((plugins, d)) if !matches!(&result, Ok(items) if !items.is_empty()) => {
let cancel = cancel.clone();
plugin_call(move || plugins.provide_inline_completion(&d, pos, &cancel)).await.flatten()
plugin_call(move || {
let offered = plugins.offers_inline_completion(&d.language);
(offered, plugins.provide_inline_completion(&d, pos, &cancel).map(|(_, s)| s))
})
.await
}
_ => None,
};
host.end_request(request);
inline_items(result, plugin)
}
/// The plugin's suggestion, else the servers'. When a plugin offers ghost text
/// for the document, "no server supports inline completion" is not returned:
/// the editor would stop asking while typing for 30 s, and a plugin that had
/// nothing this time (cancelled by the next keystroke) may have some next time.
fn inline_items(
servers: IdeResult<Vec<InlineCompletionItem>>,
plugin: Option<(bool, Option<ide_plugin::InlineSuggestion>)>,
) -> IdeResult<Vec<InlineCompletionItem>> {
match plugin {
Some((_, s)) => Ok(vec![InlineCompletionItem {
Some((_, Some(s))) => Ok(vec![InlineCompletionItem {
insert_text: s.insert_text,
range: s.replace,
filter_text: None,
command: None,
server: PLUGIN_SERVER,
}]),
None => result,
Some((true, None)) => provider_server(servers),
_ => servers,
}
}
@@ -639,6 +655,26 @@ pub async fn lsp_file_references(
result
}
/// The header of the document's source file or the source of its header (C, C++,
/// Objective-C) as clangd finds it; `None` without clangd or an answer. Cancel with
/// `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_switch_source_header(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
) -> IdeResult<Option<String>> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let result = tokio::select! {
result = lsp.switch_source_header(doc, cancel.clone()) => result,
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
};
host.end_request(request);
Ok(result?.map(|path| path.to_string_lossy().into_owned()))
}
/// Implementations of the symbols at `positions`, one list per position (the
/// editor's "is implemented / overridden" gutter markers). Cancel with
/// `cancel_request(request)`.
@@ -2097,6 +2133,12 @@ pub async fn lsp_restart(host: &Host, window: &str, server: ServerId) -> IdeResu
Ok(())
}
/// Stops a language server; it starts again when a file it serves is opened.
#[command(trust = trusted)]
pub async fn lsp_stop(host: &Host, window: &str, server: ServerId) -> IdeResult<()> {
host.project(window)?.lsp.stop(server).await
}
/// Restarts the language servers named `name` in every open project, so a tool installed or
/// updated from one window is what all of them run (not only that window's project).
pub async fn lsp_restart_named(host: &Host, name: &str) -> IdeResult<()> {
@@ -2403,6 +2445,19 @@ pub fn plugin_formatters() -> IdeResult<Vec<crate::plugins::language_features::F
#[cfg(test)]
mod tests {
#[test]
fn a_plugin_offering_ghost_text_keeps_the_editor_asking() {
use super::*;
let none = || Err(ide_core::IdeError::unavailable("No server supports inline completion"));
// Nothing this time (cancelled by the next keystroke): an empty answer, not "unavailable".
assert!(inline_items(none(), Some((true, None))).unwrap().is_empty());
// No plugin for this language: the servers' answer as it is.
assert!(inline_items(none(), Some((false, None))).is_err());
assert!(inline_items(none(), None).is_err());
let s = ide_plugin::InlineSuggestion { insert_text: "a + b".into(), replace: None };
assert_eq!(inline_items(none(), Some((true, Some(s)))).unwrap()[0].insert_text, "a + b");
}
#[test]
fn a_completion_word_is_its_line_and_what_precedes_it() {
use super::*;
@@ -3288,6 +3343,7 @@ ide_command::domain!(
lsp_hover,
lsp_implementation_locations,
lsp_file_references,
lsp_switch_source_header,
lsp_implementations,
lsp_inlay_hints,
lsp_inline_completion,
@@ -3306,6 +3362,7 @@ ide_command::domain!(
lsp_resolve_command,
lsp_resolve_completion,
lsp_restart,
lsp_stop,
lsp_semantic_tokens,
lsp_servers,
lsp_signature_help,
+15 -1
Переглянути файл
@@ -17,27 +17,31 @@ pub mod docker;
pub mod env;
pub mod flutter;
pub mod fs;
pub mod github;
pub mod heap;
pub mod history;
pub mod host_metrics;
pub mod http;
pub mod ios;
pub mod java;
pub mod jvm_icons;
pub mod lsp;
pub mod maven_placeholder;
pub mod nav;
pub mod notebook;
mod plots;
pub mod plots;
pub mod project;
pub mod pytest_fixtures;
mod python;
pub mod python_stubs;
pub mod refactor;
pub mod routes;
pub mod rst;
pub mod run;
pub mod scaffold;
pub mod sdk;
pub mod search;
pub mod settings_sync;
pub mod spell;
pub mod ssh;
pub mod stream_trace;
@@ -47,6 +51,9 @@ pub mod thread_dump;
pub mod tools;
pub mod vcs;
pub mod web;
pub mod xcode_bsp;
pub mod xcode_clean;
pub mod xcode_files;
use crate::Host;
use ide_core::{IdeError, IdeResult};
@@ -94,10 +101,12 @@ ide_command::domains!(
env: crate::ops::env,
flutter: crate::ops::flutter,
fs: crate::ops::fs,
github: crate::ops::github,
heap: crate::ops::heap,
history: crate::ops::history,
host_metrics: crate::ops::host_metrics,
http: crate::ops::http,
ios: crate::ops::ios,
java: crate::ops::java,
jvm_icons: crate::ops::jvm_icons,
lsp: crate::ops::lsp,
@@ -105,6 +114,7 @@ ide_command::domains!(
mcp_reports: crate::mcp::reports,
nav: crate::ops::nav,
notebook: crate::ops::notebook,
plots: crate::ops::plots,
plugins_commands: crate::plugins::commands,
plugins_commit: crate::plugins::commit,
plugins_index_ops: crate::plugins::index_ops,
@@ -113,6 +123,7 @@ ide_command::domains!(
plugins_views: crate::plugins::views,
project: crate::ops::project,
refactor: crate::ops::refactor,
rst: crate::ops::rst,
run: crate::ops::run,
run_commands: crate::ops::run::commands,
scaffold: crate::ops::scaffold,
@@ -130,6 +141,9 @@ ide_command::domains!(
vcs: crate::ops::vcs,
vcs_commands: crate::ops::vcs::commands,
web: crate::ops::web,
xcode_bsp: crate::ops::xcode_bsp,
xcode_clean: crate::ops::xcode_clean,
xcode_files: crate::ops::xcode_files,
);
/// A blocking task that panicked or was cancelled, as the error a command returns.
+72 -8
Переглянути файл
@@ -1,12 +1,17 @@
use super::blocking;
use super::pytest_fixtures::{PytestFixtureAt, PytestFixtureUsages, fixture_at, fixture_usages, rename_fixture};
use super::pytest_fixtures::{
PytestFixtureAt, PytestFixtureRename, PytestFixtureTarget, PytestFixtureUsages, fixture_at, fixture_target,
fixture_usages, rename_fixture,
};
use super::python_stubs::{
PythonStubLinks, counterpart_candidates, match_declarations, module_name, site_packages, stub_path,
PythonStubLinks, counterpart_candidates, interpreter_site_packages, match_declarations, module_name, site_packages,
stub_path,
};
use crate::Host;
use crate::Project;
use ide_command::command;
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos, RequestId, WorkspaceEdit};
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos, RequestId};
use ide_index::python_library::{PythonImportCandidate, PythonLibraries};
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
use ide_language::{CSS_VARIABLE, FileReference, WebReference};
use ide_workspace::file_refs::{self, PathCompletion};
@@ -496,6 +501,41 @@ pub async fn nav_pytest_fixtures(host: &Host, window: &str, doc: DocId, pos: Pos
.await
}
static PYTHON_LIBRARIES: std::sync::LazyLock<PythonLibraries> = std::sync::LazyLock::new(Default::default);
/// Imports that bind `name` from the packages installed in the interpreter of the Python document
/// `doc` (its workspace member's, else the project's): PyCharm's "Import this name" for library
/// symbols, which basedpyright offers for the project and the standard library only. The first
/// request indexes the interpreter's `site-packages` in the background, and a change there
/// re-indexes it; a request waits for the index until cancelled.
#[command(trust = always)]
pub async fn nav_python_library_imports(
host: &Host,
window: &str,
doc: DocId,
name: String,
request: RequestId,
) -> IdeResult<Vec<PythonImportCandidate>> {
let project = host.project(window)?;
let syntax = host.syntax();
let config_dir = host.config_dir.clone();
let token = host.begin_request(request);
let result = blocking(move || {
let snap = project.documents.snapshot(doc)?;
if snap.language.as_str() != "python" {
return Ok(Vec::new());
}
let Some(python) = super::sdk::effective_python(&config_dir, &project, Some(&snap.path)) else {
return Ok(Vec::new());
};
let roots = interpreter_site_packages(&python);
Ok(PYTHON_LIBRARIES.index(&roots, &syntax, &token).map(|index| index.candidates(&name)).unwrap_or_default())
})
.await;
host.end_request(request);
result
}
/// Find Usages of the pytest fixture at `pos` (its definition, or a place asking for it): every
/// test and fixture parameter, `usefixtures` and `getfixturevalue` string that gets it.
/// None when `pos` names no fixture. Cancellable.
@@ -522,8 +562,30 @@ pub async fn nav_pytest_fixture_usages(
result
}
/// The pytest fixture at `pos` (its definition, a place asking for it, or a read of such a
/// parameter in a function body), without searching the project: what Rename renames.
#[command(trust = always)]
pub async fn nav_pytest_fixture_target(
host: &Host,
window: &str,
doc: DocId,
pos: Pos,
) -> IdeResult<Option<PytestFixtureTarget>> {
let project = host.project(window)?;
let syntax = host.syntax();
blocking(move || {
let snap = project.documents.snapshot(doc)?;
if snap.large || snap.language.as_str() != "python" {
return Ok(None);
}
Ok(fixture_target(&project, &syntax, &snap.path, &snap.text, pos))
})
.await
}
/// Rename of the pytest fixture at `pos`: its definition, every place that gets it and the
/// uses of those parameters in their functions. Cancellable.
/// reads of those parameters in their functions; or the parameter or fixture the new name
/// would clash with. Cancellable.
#[command(trust = always)]
pub async fn nav_pytest_fixture_rename(
host: &Host,
@@ -532,19 +594,19 @@ pub async fn nav_pytest_fixture_rename(
pos: Pos,
new_name: String,
request: RequestId,
) -> IdeResult<WorkspaceEdit> {
) -> IdeResult<PytestFixtureRename> {
let project = host.project(window)?;
let syntax = host.syntax();
let token = host.begin_request(request);
let result = blocking(move || {
let snap = project.documents.snapshot(doc)?;
let mut edit =
let mut renamed =
rename_fixture(&project, &syntax, &snap.path, &snap.text, pos, &new_name, &|| token.is_cancelled())?;
if token.is_cancelled() {
return Err(ide_core::IdeError::cancelled());
}
project.documents.prepare_workspace_edit(&mut edit)?;
Ok(edit)
project.documents.prepare_workspace_edit(&mut renamed.edit)?;
Ok(renamed)
})
.await;
host.end_request(request);
@@ -565,8 +627,10 @@ ide_command::domain!(
nav_index_definitions,
nav_inheritance,
nav_pytest_fixture_rename,
nav_pytest_fixture_target,
nav_pytest_fixture_usages,
nav_pytest_fixtures,
nav_python_library_imports,
nav_python_stubs,
nav_resolve_module,
path_completions,
+106 -2
Переглянути файл
@@ -4,6 +4,7 @@ pub use crate::notebook::NotebookOutputEvent;
use crate::ops::Channel;
use ide_command::command;
use ide_core::{IdeError, IdeResult, RequestId};
use ide_notebook::kernel::{KernelSpec, KernelTarget, RemoteKernel, kernel_specs, normalize_server_url};
use ide_notebook::{NotebookEdit, NotebookSnapshot};
use std::path::PathBuf;
@@ -122,8 +123,23 @@ pub async fn notebook_execute(
let _request = RequestGuard { host, request, cancel: cancel.clone() };
// Reserve the WHOLE batch and capture source before asynchronous discovery.
let admission = project.notebooks.admit(&id, cells, cancel.clone())?;
let target = kernel_target(host, &project, python, &cancel).await?;
project.notebooks.execute(admission, target, on_output).await
}
/// The kernel the notebook's drop-down chose: an interpreter (the project's when `None`) or
/// `<server>#<kernel spec>` of a saved Jupyter server.
async fn kernel_target(
host: &Host,
project: &crate::Project,
python: Option<String>,
cancel: &ide_core::CancellationToken,
) -> IdeResult<KernelTarget> {
let selected = match python {
Some(path) if path.trim().is_empty() => return Err(IdeError::invalid("select a Python interpreter")),
Some(kernel) if kernel.starts_with("http://") || kernel.starts_with("https://") => {
return Ok(KernelTarget::Remote(remote_kernel(host, &kernel)?));
}
Some(path) => PathBuf::from(path),
None => {
let root = project.root.clone();
@@ -142,8 +158,92 @@ pub async fn notebook_execute(
};
// Do not canonicalize this path: resolving a venv symlink to base Python
// changes sys.prefix and executes in the wrong environment.
let python = if selected.is_absolute() { selected } else { project.root.join(selected) };
project.notebooks.execute(admission, python, on_output).await
Ok(KernelTarget::Local(if selected.is_absolute() { selected } else { project.root.join(selected) }))
}
/// Debug Cell: a debug session named `name` on the notebook's kernel, starting the kernel
/// when none runs. The caller then runs the cell; ending the session leaves the kernel and
/// its state running.
#[command(trust = trusted)]
pub async fn notebook_debug_start(
host: &Host,
window: &str,
id: String,
python: Option<String>,
name: String,
just_my_code: bool,
) -> IdeResult<ide_core::DebugSessionId> {
host.require_trust(window)?;
let project = host.project(window)?;
let cancel = project.closed.child_token();
let target = kernel_target(host, &project, python, &cancel).await?;
let (debugger, cells, notebook_cells) = project.notebooks.debugger(&id, target, cancel).await?;
let (reader, writer) = tokio::io::split(ide_notebook::kernel::debug::dap_stream(debugger, cells));
let io = ide_dap::adapter::AdapterIo {
launch_after_configuration: false,
reader: Box::new(reader),
writer: Box::new(writer),
child: None,
port: None,
stderr: Default::default(),
program_output: None,
};
let owner = ide_dap::SessionOwner::new(host.owner_window(window), host.window_sink(window));
let arguments = serde_json::json!({ "justMyCode": just_my_code });
host.debugger.start_over(io, name, ide_dap::NOTEBOOK_ADAPTER.into(), arguments, owner, Some(notebook_cells)).await
}
/// A kernel choice on a Jupyter server, `<server base URL>#<kernel spec>`, with its saved token.
fn remote_kernel(host: &Host, choice: &str) -> IdeResult<RemoteKernel> {
let (base, spec) = choice
.split_once('#')
.filter(|(_, spec)| !spec.is_empty())
.ok_or_else(|| IdeError::invalid("select a kernel of the Jupyter server"))?;
let token = host.jupyter_tokens.get(base).ok_or_else(|| {
IdeError::unavailable(format!("connect to the Jupyter server {base} again: its token is not saved"))
})?;
Ok(RemoteKernel { base: base.to_owned(), token, spec: spec.to_owned() })
}
/// A Jupyter server notebooks can run on.
#[derive(serde::Serialize, specta::Type)]
pub struct JupyterServer {
/// Base URL, ending in `/`.
pub url: String,
pub kernels: Vec<KernelSpec>,
}
/// Checks `url` and `token` against the server and saves them. A `?token=` in the URL
/// (as JupyterLab prints it) is used when `token` is empty.
#[command(trust = trusted)]
pub async fn jupyter_server_add(host: &Host, window: &str, url: String, token: String) -> IdeResult<JupyterServer> {
host.require_trust(window)?;
let (url, in_url) = normalize_server_url(&url)?;
let token = if token.trim().is_empty() { in_url.unwrap_or_default() } else { token.trim().to_owned() };
let kernels = kernel_specs(&url, &token).await?;
host.jupyter_tokens.set(&url, &token)?;
Ok(JupyterServer { url, kernels })
}
/// The saved servers and their kernel specs; a server that cannot be reached has none.
#[command(trust = trusted)]
pub async fn jupyter_servers(host: &Host, window: &str) -> IdeResult<Vec<JupyterServer>> {
host.require_trust(window)?;
let servers = host.jupyter_tokens.keys().into_iter().map(|url| async move {
let kernels = match host.jupyter_tokens.get(&url) {
Some(token) => kernel_specs(&url, &token).await.unwrap_or_default(),
None => Vec::new(),
};
JupyterServer { url, kernels }
});
Ok(futures::future::join_all(servers).await)
}
#[command(trust = always)]
pub fn jupyter_server_remove(host: &Host, window: &str, url: String) -> IdeResult<()> {
let _ = window;
host.jupyter_tokens.delete(&url);
Ok(())
}
struct RequestGuard<'a> {
@@ -162,8 +262,12 @@ impl Drop for RequestGuard<'_> {
ide_command::domain!(
notebook:
jupyter_server_add,
jupyter_server_remove,
jupyter_servers,
notebook_cell_docs,
notebook_close,
notebook_debug_start,
notebook_edit,
notebook_execute,
notebook_get,
Loaded 100 of 1290 files, more files were not shown because too many files have changed in this diff. Show more