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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

---------

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

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

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

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

Refs #8017

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

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

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

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

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

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

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

---------

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

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

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

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-04 23:21:44 +08:00
306 змінених файлів з 8836 додано та 1032 видалено

No files matched your search

Створено
+11
Переглянути файл
@@ -4690,6 +4690,7 @@ dependencies = [
"tree-sitter-nix",
"tree-sitter-objc",
"tree-sitter-ocaml",
"tree-sitter-odin",
"tree-sitter-php",
"tree-sitter-prisma-io",
"tree-sitter-proto",
@@ -10573,6 +10574,16 @@ dependencies = [
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-odin"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24db210fe9ba2237c71c5030d7b146c7025420ba72dd8013d13cd822c3a8d77a"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-php"
version = "0.25.1"
+1 -1
Переглянути файл
@@ -4,7 +4,7 @@
`src/ui/brands/*.svg` use the unmodified logo paths from
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:odin`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
## DuckDB symbol
+25 -8
Переглянути файл
@@ -254,7 +254,14 @@ impl AgentCatalogs {
}
let unavailable = || "The agent did not report settings for the selected model".to_owned();
let spec = shared.spec(provider).ok_or_else(unavailable)?;
let (_, flight) = self.request(shared, spec, false, Some(model));
let flight = {
let catalogs = self.clone();
let shared = shared.clone();
let model = model.to_owned();
tokio::task::spawn_blocking(move || catalogs.request(&shared, spec, false, Some(&model)).1)
.await
.map_err(|e| e.to_string())?
};
if let Some(mut ready) = flight {
while !*ready.borrow_and_update() {
if ready.changed().await.is_err() {
@@ -444,7 +451,22 @@ impl AgentCatalogs {
let flight_key = key.clone();
let task = shared.runtime.clone().spawn(async move {
let result = discover(&shared, spec, model.as_deref()).await;
coordinator.complete(&shared, flight_key, generation, model, result);
let current = {
let shared = shared.clone();
let provider_id = flight_key.2.clone();
tokio::task::spawn_blocking(move || {
shared
.paths
.provider_specs()
.into_iter()
.find(|spec| spec.id == provider_id)
.map(|spec| LaunchContext::new(spec, &shared.paths.project_root))
})
.await
.ok()
.flatten()
};
coordinator.complete(&shared, flight_key, generation, model, current, result);
let _ = done.send(true);
});
// A subscriber can re-enter and change configuration during the start event.
@@ -466,14 +488,9 @@ impl AgentCatalogs {
key: Key,
generation: u64,
model: Option<String>,
current: Option<LaunchContext>,
result: Result<Discovered, String>,
) {
let current = shared
.paths
.provider_specs()
.into_iter()
.find(|spec| spec.id == key.2)
.map(|spec| LaunchContext::new(spec, &shared.paths.project_root));
let mut state = self.state.lock();
let Some(entry) = state.entries.get_mut(&key).filter(|e| e.generation == generation) else { return };
// Configuration may have changed without another refresh request arriving.
+21 -5
Переглянути файл
@@ -1499,10 +1499,18 @@ impl AgentManager {
// Commands the agent implements itself and never lists (its CLI builtins):
// merged without duplicating what `availableCommands` or the disk offer.
let mut offered = offered;
if task.is_none()
&& let Some(spec) = self.shared.paths.provider_specs().into_iter().find(|spec| spec.id == provider)
{
let (_, flight) = self.shared.paths.catalogs.request(&self.shared, spec, false, None);
if task.is_none() {
let shared = self.shared.clone();
let provider_id = provider.clone();
let flight = blocking(move || {
Ok(shared
.paths
.provider_specs()
.into_iter()
.find(|spec| spec.id == provider_id)
.and_then(|spec| shared.paths.catalogs.request(&shared, spec, false, None).1))
})
.await?;
if let Some(mut ready) = flight {
while !*ready.borrow_and_update() {
if ready.changed().await.is_err() {
@@ -2638,11 +2646,18 @@ impl AgentManager {
}
async fn probe_once(&self, spec: &provider::ProviderSpec) -> Result<Value, (String, bool)> {
let spec = {
let spec = spec.clone();
let cwd = self.shared.paths.project_root.clone();
tokio::task::spawn_blocking(move || spec.resolve_for_launch(&cwd))
.await
.map_err(|e| (e.to_string(), false))?
};
let stderr: Arc<Mutex<Vec<String>>> = Arc::default();
let lines = stderr.clone();
let on_stderr: Box<dyn Fn(String) + Send + Sync> = Box::new(move |l| lines.lock().push(l));
let started = (self.shared.connector)(
spec,
&spec,
&self.shared.paths.project_root,
Arc::new(ide_jsonrpc::NoopHandler),
on_stderr,
@@ -5456,6 +5471,7 @@ impl Task {
content
};
let mut content = with_shell(self.content(&live, prompt).await);
self.state.lock().history.conversation.main.seal();
let mut result: Result<Value, RpcError> =
live.peer.request("session/prompt", json!({ "sessionId": live.session, "prompt": content }), None).await;
if live.driver == provider::Driver::Copilot
+165 -9
Переглянути файл
@@ -18,8 +18,49 @@ pub(crate) mod codex;
pub(crate) mod copilot;
use ide_jsonrpc::{Framing, Handler, Peer};
use parking_lot::Mutex;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant, SystemTime};
const VERSION_CACHE_TTL: Duration = Duration::from_secs(60);
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct VersionCacheKey {
path: PathBuf,
modified: Option<SystemTime>,
len: Option<u64>,
#[cfg(unix)]
ino: Option<u64>,
}
impl VersionCacheKey {
fn of(real: &Path) -> Self {
let meta = std::fs::metadata(real).ok();
#[cfg(unix)]
let ino = meta.as_ref().map(std::os::unix::fs::MetadataExt::ino);
Self {
path: real.to_path_buf(),
modified: meta.as_ref().and_then(|m| m.modified().ok()),
len: meta.as_ref().map(std::fs::Metadata::len),
#[cfg(unix)]
ino,
}
}
}
struct CachedVersion {
version: Vec<u64>,
checked_at: Instant,
}
type VersionSlot = Arc<Mutex<Option<CachedVersion>>>;
fn version_cache() -> &'static Mutex<HashMap<VersionCacheKey, VersionSlot>> {
static CACHE: OnceLock<Mutex<HashMap<VersionCacheKey, VersionSlot>>> = OnceLock::new();
CACHE.get_or_init(Default::default)
}
/// The newest install of `command` on the `PATH` a child sees, by its `--version`.
/// Several installs are common (npm, Homebrew, the vendor's own installer), and the first
@@ -38,27 +79,69 @@ fn newest_install_in(command: &str, search: &std::ffi::OsStr) -> String {
let names =
ide_core::process::executable_names(command, cfg!(windows), pathext.as_deref().and_then(|p| p.to_str()));
let mut seen = Vec::new();
let candidates: Vec<PathBuf> = std::env::split_paths(search)
let candidates: Vec<(PathBuf, PathBuf)> = std::env::split_paths(search)
.filter(|d| !d.as_os_str().is_empty())
.flat_map(|dir| names.iter().map(move |n| dir.join(n)))
.filter(|p| p.is_file())
.filter(|p| {
let real = dunce::canonicalize(p).unwrap_or_else(|_| p.clone());
let new = !seen.contains(&real);
seen.push(real);
new
.filter_map(|p| {
let real = dunce::canonicalize(&p).unwrap_or_else(|_| p.clone());
if seen.contains(&real) {
return None;
}
seen.push(real.clone());
Some((p, real))
})
.collect();
if candidates.len() < 2 {
return candidates.into_iter().next().map_or_else(|| command.to_owned(), |p| p.to_string_lossy().into_owned());
return candidates
.into_iter()
.next()
.map_or_else(|| command.to_owned(), |(p, _)| p.to_string_lossy().into_owned());
}
// Probe distinct installs in parallel; per-binary cache + single-flight avoids re-spawning
// `--version` on concurrent or repeated lookups while still noticing upgraded binaries.
let versions: Vec<Option<Vec<u64>>> = std::thread::scope(|s| {
let handles: Vec<_> = candidates.iter().map(|(p, real)| s.spawn(|| cached_version_of(p, real))).collect();
handles.into_iter().map(|h| h.join().ok().flatten()).collect()
});
candidates
.into_iter()
.filter_map(|p| version_of(&p).map(|v| (v, p)))
.zip(versions)
.filter_map(|((p, _), v)| v.map(|v| (v, p)))
.max_by(|a, b| a.0.cmp(&b.0))
.map_or_else(|| command.to_owned(), |(_, p)| p.to_string_lossy().into_owned())
}
fn cached_version_of(program: &Path, real: &Path) -> Option<Vec<u64>> {
let key = VersionCacheKey::of(real);
let slot = {
let mut cache = version_cache().lock();
if cache.len() > 64 {
cache.retain(|_, slot| {
slot.try_lock()
.is_none_or(|guard| guard.as_ref().is_some_and(|c| c.checked_at.elapsed() < VERSION_CACHE_TTL))
});
}
cache.entry(key).or_default().clone()
};
let mut guard = slot.lock();
if let Some(cached) = guard.as_ref()
&& cached.checked_at.elapsed() < VERSION_CACHE_TTL
{
return Some(cached.version.clone());
}
match version_of(program) {
Some(version) => {
*guard = Some(CachedVersion { version: version.clone(), checked_at: Instant::now() });
Some(version)
}
None => {
*guard = None;
None
}
}
}
/// `x.y.z` from `<program> --version` ("codex-cli 0.164.0", "2.1.312 (Claude Code)").
fn version_of(program: &Path) -> Option<Vec<u64>> {
let mut cmd = std::process::Command::new(program);
@@ -144,4 +227,77 @@ mod tests {
assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy());
}
}
#[cfg(unix)]
#[test]
fn newest_install_caches_versions_and_invalidates_on_change() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let old = dir.path().join("old");
let new = dir.path().join("new");
let old_log = dir.path().join("old.log");
let new_log = dir.path().join("new.log");
for (path, log, version) in [(&old, &old_log, "2.9.0"), (&new, &new_log, "2.10.0")] {
std::fs::create_dir_all(path).unwrap();
let executable = path.join("agent");
std::fs::write(&executable, format!("#!/bin/sh\nprintf 'x\\n' >> '{}'\necho {version}\n", log.display()))
.unwrap();
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let search = std::env::join_paths([&old, &new]).unwrap();
assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy());
assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy());
assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 1);
assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1);
// Replacing the older binary with a newer version invalidates only its cache entry.
let upgraded = old.join("agent");
std::fs::write(&upgraded, format!("#!/bin/sh\nprintf 'x\\n' >> '{}'\necho 2.11.0\n", old_log.display()))
.unwrap();
std::fs::set_permissions(&upgraded, std::fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(newest_install_in("agent", &search), upgraded.to_string_lossy());
assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 2);
assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1);
}
#[cfg(unix)]
#[test]
fn newest_install_deduplicates_concurrent_probes() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let old = dir.path().join("old");
let new = dir.path().join("new");
let old_log = dir.path().join("old.log");
let new_log = dir.path().join("new.log");
for (path, log, version) in [(&old, &old_log, "2.9.0"), (&new, &new_log, "2.10.0")] {
std::fs::create_dir_all(path).unwrap();
let executable = path.join("agent");
std::fs::write(
&executable,
format!("#!/bin/sh\nsleep 0.05\nprintf 'x\\n' >> '{}'\necho {version}\n", log.display()),
)
.unwrap();
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let search = std::env::join_paths([&old, &new]).unwrap();
let expected = new.join("agent").to_string_lossy().into_owned();
let barrier = std::sync::Barrier::new(4);
std::thread::scope(|s| {
let handles: Vec<_> = (0..4)
.map(|_| {
s.spawn(|| {
barrier.wait();
newest_install_in("agent", &search)
})
})
.collect();
for handle in handles {
assert_eq!(handle.join().unwrap(), expected);
}
});
assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 1);
assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1);
}
}
+36
Переглянути файл
@@ -49,6 +49,8 @@ struct FakeAgent {
/// Hold the late mode reply until the prompt's permission request is already waiting.
hold_late_mode: bool,
empty_config: AtomicBool,
/// Text sent as an agent message when a session opens, before any prompt (pi-acp's startup info).
startup_notice: Mutex<Option<String>>,
/// Blocks `session/new` until discovery times out (see `acp::discover` test timeout).
hold_session_new: AtomicBool,
/// Sleeps this long at the start of `session/set_config_option`, after noting the time.
@@ -221,6 +223,9 @@ impl Handler for FakeAgent {
std::thread::sleep(Duration::from_millis(10));
}
}
if let Some(notice) = self.startup_notice.lock().clone() {
self.say("s1", &notice);
}
if self.empty_config.load(Ordering::Acquire) {
return Ok(json!({"sessionId": "s1"}));
}
@@ -919,6 +924,37 @@ async fn an_ephemeral_task_is_not_saved_and_asks_for_an_unsaved_session() {
}
}
#[tokio::test(flavor = "multi_thread")]
async fn text_the_agent_sends_before_the_prompt_is_not_part_of_the_reply() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.startup_notice.lock() = Some("pi v1.5.2\n---\n## Context\n- AGENTS.md\n".into());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude".into(),
isolation: Isolation::Local,
ephemeral: true,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let replies: Vec<String> = mgr
.entries(&task.id, None)
.unwrap()
.into_iter()
.filter_map(|e| match e {
AgentEntry::Agent { text } => Some(text),
_ => None,
})
.collect();
assert_eq!(replies.last().map(String::as_str), Some("second turn"));
assert!(replies.iter().any(|t| t.starts_with("pi v1.5.2")));
shut_down(&mgr, &agent).await;
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn claude_commands_share_catalog_discovery_and_persist_results() {
+11 -2
Переглянути файл
@@ -20,6 +20,8 @@ pub(crate) struct Timeline {
cards: HashMap<String, usize>,
/// Session messages, by message id.
messages: HashMap<String, usize>,
/// The next agent text starts an entry of its own (see [`Timeline::seal`]).
sealed: bool,
}
/// What a `session/update` changed in the timeline.
@@ -138,10 +140,17 @@ impl Timeline {
out
}
/// A prompt is being sent: text the agent sent before it (a startup notice) is not the
/// start of the reply, so the reply's text gets an entry of its own.
pub fn seal(&mut self) {
self.sealed = true;
}
fn append_text(&mut self, thought: bool, text: &str) -> usize {
let sealed = std::mem::take(&mut self.sealed);
match self.entries.last_mut() {
Some(AgentEntry::Agent { text: t }) if !thought => t.push_str(text),
Some(AgentEntry::Thought { text: t, .. }) if thought => t.push_str(text),
Some(AgentEntry::Agent { text: t }) if !thought && !sealed => t.push_str(text),
Some(AgentEntry::Thought { text: t, .. }) if thought && !sealed => t.push_str(text),
_ => {
let text = text.to_owned();
return self.push(if thought {
+17 -2
Переглянути файл
@@ -51,6 +51,8 @@ pub struct AdapterSpec {
pub pinned: Option<ProgramPin>,
/// See [`DebuggerConfig::resolve_lazy_variables`].
pub resolve_lazy_variables: bool,
/// Connect to the one lldb-dap server every such session shares ([`crate::lldb_server`]).
pub shared: bool,
}
/// Built-in adapters used when no language definition names `adapter`.
@@ -193,6 +195,7 @@ pub fn resolve(config: &DebuggerConfig, cwd: PathBuf) -> AdapterSpec {
connect: config.connect.clone(),
pinned: config.pinned.clone(),
resolve_lazy_variables: config.resolve_lazy_variables,
shared: false,
}
}
@@ -298,7 +301,7 @@ fn managed_dirs(root: &Path) -> Vec<PathBuf> {
/// The `PATH` an adapter runs with, unless its launch sets one: the search path language servers
/// get, so what it starts in turn (js-debug's wrapper runs `node`, Delve runs `go build`) is
/// found like Run finds it, even when the login shell's `PATH` didn't reach the app.
fn adapter_path(env: &[(String, String)], cwd: &Path) -> Option<std::ffi::OsString> {
pub(crate) fn adapter_path(env: &[(String, String)], cwd: &Path) -> Option<std::ffi::OsString> {
let own = env.iter().any(|(k, _)| if cfg!(windows) { k.eq_ignore_ascii_case("PATH") } else { k == "PATH" });
(!own).then(|| ide_core::tool_path::search_path_in(cwd))
}
@@ -744,6 +747,18 @@ impl AdapterLauncher for ProcessLauncher {
.ok_or_else(|| missing(&spec))?
}
};
#[cfg(target_os = "macos")]
if spec.shared && spec.transport == Transport::Stdio && spec.connect.is_none() && spec.args.is_empty() {
match crate::lldb_server::connect(&spec, &binary).await {
Ok(Some(io)) => return Ok(io),
Ok(None) => {}
Err(e) => tracing::warn!(
target: "ide_dap::adapter",
"no shared lldb-dap server ({}); starting one for this session",
e.message
),
}
}
let launch_after_configuration =
if spec.adapter == "gdb" { prepare_gdb(&spec, &binary).await? } else { false };
let base_args = substitute_root(&spec.args, &spec.cwd);
@@ -891,7 +906,7 @@ fn is_port_race(err: &IdeError) -> bool {
|| message.contains("exited before accepting connections")
}
fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(
pub(crate) fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(
stream: R,
name: String,
sink: Arc<parking_lot::Mutex<Vec<String>>>,
+1
Переглянути файл
@@ -103,6 +103,7 @@ pub(crate) fn bare_session_of(name: &str, request: &str) -> BareSession {
connect: None,
pinned: None,
resolve_lazy_variables: false,
shared: false,
};
let session = Session::new(
DebugSessionId(1),
+12 -1
Переглянути файл
@@ -21,6 +21,8 @@ mod js_debug;
mod jvm_memory;
pub mod kotlin;
pub mod kotlin_lsp;
#[cfg(target_os = "macos")]
mod lldb_server;
mod memory;
pub mod native;
mod session;
@@ -516,6 +518,7 @@ fn is_native(adapter: &str) -> bool {
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
/// adapter.
pub const RUN_LINK: &str = "__openideaRun";
const XCODE_ATTACH: &str = "__openideaXcodeAttach";
fn take_run_link(arguments: &mut Value) -> Option<RunId> {
let run = arguments.as_object_mut()?.remove(RUN_LINK)?;
@@ -1203,6 +1206,7 @@ impl DebugManager {
connect: None,
pinned: None,
resolve_lazy_variables: false,
shared: false,
};
let cancel = ide_core::CancellationToken::new();
self.start_session(
@@ -1269,7 +1273,7 @@ impl DebugManager {
parent: Option<DebugSessionId>,
request: String,
mut arguments: Value,
spec: AdapterSpec,
mut spec: AdapterSpec,
reuse_port: Option<u16>,
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
cancel: ide_core::CancellationToken,
@@ -1278,6 +1282,13 @@ impl DebugManager {
if request != "launch" && request != "attach" {
return Err(IdeError::invalid(format!("request must be `launch` or `attach`, got `{request}`")));
}
// Xcode Debug attaches to the app its run launched: a shared lldb-dap server keeps the
// system libraries it parsed, so the next attach skips that (#6665 E7).
let xcode_attach = arguments.as_object_mut().and_then(|args| args.remove(XCODE_ATTACH));
spec.shared = xcode_attach == Some(Value::Bool(true))
&& adapter_name == "lldb-dap"
&& request == "attach"
&& arguments.get(RUN_LINK).is_some();
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
+408
Переглянути файл
@@ -0,0 +1,408 @@
//! Cache one lldb-dap server for successive attaches to Xcode runs (#6665 E7).
//!
//! An iOS app loads about 550 system libraries before its first line runs, and a fresh lldb-dap
//! parses all of their symbol tables (about 5 million symbols) on each attach: 1.5 s on an idle
//! Mac, far more under load. A server keeps the modules it parsed, so later sessions skip that
//! and reach a breakpoint about as fast as Run reaches the same line. LLDB's own on-disk index
//! cache would serve the first session too, but Xcode 27.1's lldb crashes on cached symbols.
//!
//! The server holds about 1 GB, so it ends once no session has been connected for
//! [`IDLE_TIMEOUT`]; the next Debug then starts cold, as every Debug did before. A shell holds
//! it and ends it when its stdin closes: when the IDE quits or crashes, when the server idles
//! out, or when a server for another lldb-dap or environment replaces it.
use crate::adapter::{AdapterIo, AdapterSpec, adapter_path, pump_lines};
use ide_core::{IdeError, IdeResult};
use std::ffi::OsString;
use std::fs::Permissions;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::process::Stdio;
use std::sync::{Arc, LazyLock};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::net::UnixStream;
use tokio::process::{Child, Command};
/// What a server was started with: a session reuses it only when its own start would match.
#[derive(PartialEq)]
struct Key {
binary: PathBuf,
cwd: PathBuf,
cwd_env: Vec<(OsString, Option<OsString>)>,
}
struct Server {
key: Key,
socket: PathBuf,
/// Recent stderr for the active connection.
stderr: Arc<parking_lot::Mutex<Vec<String>>>,
idle: Arc<Idle>,
/// The shell holding the server; dropping it closes its stdin, which ends the server.
_holder: Child,
_socket_dir: tempfile::TempDir,
}
/// When the last session disconnected, or `None` while a session owns the server.
type Idle = parking_lot::Mutex<Option<Instant>>;
type Slot = tokio::sync::Mutex<Option<Server>>;
static SERVER: LazyLock<Slot> = LazyLock::new(Default::default);
/// How long a server with no session stays up.
const IDLE_TIMEOUT: Duration = Duration::from_secs(10 * 60);
/// How long a new server may take to listen.
const START_TIMEOUT: Duration = Duration::from_secs(15);
/// A connection to a running server; a server that does not take it is replaced.
const PROBE_TIMEOUT: Duration = Duration::from_millis(500);
/// Starts the server and ends it when the shell's stdin closes (`read` sees EOF) or when the
/// server exits on its own (`wait`), so a `binary` without `--connection` fails at once.
const HOLDER: &str = "exec 3<&0\n\
\"$0\" --connection \"$1\" </dev/null >/dev/null &\n\
server=$!\n\
(read _ <&3; kill \"$server\" 2>/dev/null) &\n\
watcher=$!\n\
wait \"$server\"\n\
result=$?\n\
kill \"$watcher\" 2>/dev/null\n\
wait \"$watcher\" 2>/dev/null\n\
exit \"$result\"\n";
/// A connection to the shared server of `binary`, started first when there is none.
pub async fn connect(spec: &AdapterSpec, binary: &Path) -> IdeResult<Option<AdapterIo>> {
connect_to(&SERVER, spec, binary, IDLE_TIMEOUT).await
}
async fn connect_to(
slot: &'static Slot,
spec: &AdapterSpec,
binary: &Path,
idle_timeout: Duration,
) -> IdeResult<Option<AdapterIo>> {
// The server gets the environment a per-session lldb-dap would: the project's (its Xcode's
// `DEVELOPER_DIR`, from `cwd`), the adapter's search path and the spec's own variables.
let mut cmd = Command::new("/bin/sh");
cmd.current_dir(&spec.cwd);
if let Some(path) = adapter_path(&spec.env, &spec.cwd) {
cmd.env("PATH", path);
}
cmd.envs(spec.env.iter().map(|(k, v)| (k, v)));
ide_core::process::prepare(cmd.as_std_mut());
let mut env: Vec<_> = cmd.as_std().get_envs().map(|(k, v)| (k.to_owned(), v.map(|v| v.to_owned()))).collect();
env.sort();
let key = Key { binary: binary.to_path_buf(), cwd: spec.cwd.clone(), cwd_env: env };
let mut server = slot.lock().await;
// A concurrent launch uses its own adapter. Replacing the cached process here would
// disconnect the ongoing session, and concurrent sessions would share its stderr.
if server.as_ref().is_some_and(|running| running.idle.lock().is_none()) {
return Ok(None);
}
if let Some(running) = server.as_ref().filter(|s| s.key == key)
&& let Ok(Ok(stream)) = tokio::time::timeout(PROBE_TIMEOUT, UnixStream::connect(&running.socket)).await
{
running.stderr.lock().clear();
return Ok(Some(io(stream, running.stderr.clone(), lease(&running.idle))));
}
*server = None;
let socket_dir = tempfile::Builder::new()
.permissions(Permissions::from_mode(0o700))
.tempdir()
.map_err(|e| IdeError::unavailable(format!("cannot create the lldb-dap socket directory: {e}")))?;
let socket = socket_dir.path().join("dap.sock");
let mut uri = OsString::from("accept://");
uri.push(&socket);
ide_core::process::own_group(cmd.as_std_mut());
cmd.arg("-c").arg(HOLDER).arg(binary).arg(uri).stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::piped());
let mut holder = cmd.spawn().map_err(|e| IdeError::unavailable(format!("failed to start lldb-dap: {e}")))?;
let stderr = Arc::new(parking_lot::Mutex::new(Vec::new()));
if let Some(err) = holder.stderr.take() {
pump_lines(err, spec.adapter.clone(), stderr.clone(), None);
}
let stream = connect_when_ready(&socket, &mut holder).await?;
let idle = Arc::new(Idle::default());
let first = lease(&idle);
tokio::spawn(end_when_idle(slot, idle.clone(), idle_timeout));
*server = Some(Server { key, socket, stderr: stderr.clone(), idle, _holder: holder, _socket_dir: socket_dir });
Ok(Some(io(stream, stderr, first)))
}
async fn connect_when_ready(socket: &Path, holder: &mut Child) -> IdeResult<UnixStream> {
let deadline = Instant::now() + START_TIMEOUT;
loop {
let error = match UnixStream::connect(socket).await {
Ok(stream) => return Ok(stream),
Err(error) => error,
};
if let Ok(Some(status)) = holder.try_wait() {
return Err(IdeError::unavailable(format!("debug adapter exited before accepting connections ({status})")));
}
if Instant::now() >= deadline {
return Err(IdeError::unavailable(format!("could not connect to lldb-dap: {error}")));
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
/// A session's hold on the server, released when its connection's both halves are gone.
struct Lease(Arc<Idle>);
fn lease(idle: &Arc<Idle>) -> Arc<Lease> {
*idle.lock() = None;
Arc::new(Lease(idle.clone()))
}
impl Drop for Lease {
fn drop(&mut self) {
*self.0.lock() = Some(Instant::now());
}
}
/// Ends the server in `slot` once no session has been connected to it for `timeout`; returns
/// early when another server took its place.
async fn end_when_idle(slot: &'static Slot, idle: Arc<Idle>, timeout: Duration) {
loop {
let since = *idle.lock();
let wait = since.map_or(timeout, |at| (at + timeout).saturating_duration_since(Instant::now()));
tokio::time::sleep(wait.max(Duration::from_millis(10))).await;
let mut server = slot.lock().await;
if !server.as_ref().is_some_and(|s| Arc::ptr_eq(&s.idle, &idle)) {
return;
}
if idle.lock().is_some_and(|at| at.elapsed() >= timeout) {
*server = None;
return;
}
}
}
/// One half of a session's connection, holding the session's [`Lease`].
struct Leased<T> {
inner: T,
_lease: Arc<Lease>,
}
impl<T: AsyncRead + Unpin> AsyncRead for Leased<T> {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.inner).poll_read(cx, buf)
}
}
impl<T: AsyncWrite + Unpin> AsyncWrite for Leased<T> {
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<std::io::Result<usize>> {
Pin::new(&mut self.inner).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.inner).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.inner).poll_shutdown(cx)
}
}
/// A session's streams. When the server dies the session's connection closes and the session
/// ends with the server's last stderr lines, whichever session started it.
fn io(stream: UnixStream, stderr: Arc<parking_lot::Mutex<Vec<String>>>, lease: Arc<Lease>) -> AdapterIo {
let (r, w) = stream.into_split();
AdapterIo {
launch_after_configuration: false,
reader: Box::new(Leased { inner: r, _lease: lease.clone() }),
writer: Box::new(Leased { inner: w, _lease: lease }),
// The server is not the session's to stop.
child: None,
port: None,
stderr,
program_output: None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::AsyncReadExt;
/// A stand-in for lldb-dap's server mode: it parses `--connection accept:///path`,
/// records each start in `starts`, and answers every connection with its pid and the
/// `DEVELOPER_DIR` it was started with.
fn fake_lldb_dap(dir: &Path) -> Option<PathBuf> {
use std::os::unix::fs::PermissionsExt;
std::process::Command::new("python3").arg("-c").arg("").status().ok()?.success().then_some(())?;
let path = dir.join("lldb-dap");
let log = dir.join("starts");
std::fs::write(
&path,
format!(
"#!/usr/bin/env python3\nimport os, socket, sys\n\
assert sys.argv[1] == '--connection'\n\
open({:?}, 'a').write('start\\n')\n\
path = sys.argv[2][len('accept://'):]\n\
s = socket.socket(socket.AF_UNIX)\n\
s.bind(path); s.listen()\n\
while True:\n c, _ = s.accept(); c.sendall(f\"{{os.getpid()}} {{os.environ.get('DEVELOPER_DIR', '')}}\".encode()); c.close()\n",
log.to_string_lossy(),
),
)
.unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
Some(path)
}
/// The server's pid and `DEVELOPER_DIR`; the session's connection is closed afterwards.
async fn server_of(io: AdapterIo) -> (i32, String) {
let mut reader = io.reader;
let mut text = String::new();
reader.read_to_string(&mut text).await.unwrap();
let (pid, dir) = text.split_once(' ').unwrap();
(pid.parse().unwrap(), dir.to_owned())
}
fn spec(dir: &Path) -> AdapterSpec {
AdapterSpec {
adapter: "lldb-dap".into(),
command: "lldb-dap".into(),
args: Vec::new(),
transport: crate::adapter::Transport::Stdio,
install_hint: None,
cwd: dir.to_path_buf(),
env: Vec::new(),
server_host: None,
connect: None,
pinned: None,
resolve_lazy_variables: false,
shared: true,
}
}
fn slot() -> &'static Slot {
Box::leak(Box::default())
}
fn starts(dir: &Path) -> usize {
std::fs::read_to_string(dir.join("starts")).unwrap_or_default().lines().count()
}
fn alive(pid: i32) -> bool {
unsafe { libc::kill(pid, 0) == 0 }
}
async fn until_gone(pid: i32) -> bool {
for _ in 0..150 {
if !alive(pid) {
return true;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
false
}
const LONG: Duration = Duration::from_secs(600);
/// Sessions share one server; it outlives them, and goes when its holder does (the IDE quits).
#[tokio::test]
async fn sessions_share_one_server_that_ends_with_its_holder() {
let dir = tempfile::tempdir().unwrap();
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
let slot = slot();
let first = connect_to(slot, &spec(dir.path()), &binary, LONG).await.unwrap().unwrap();
assert!(first.child.is_none(), "a session must not stop the shared server");
let first_stderr = first.stderr.clone();
let (pid, _) = server_of(first).await;
let second = connect_to(slot, &spec(dir.path()), &binary, LONG).await.unwrap().unwrap();
assert!(Arc::ptr_eq(&second.stderr, &first_stderr), "every session sees the server's errors");
assert_eq!(server_of(second).await.0, pid, "the second session reuses the server");
assert_eq!(starts(dir.path()), 1);
// Another lldb-dap (the selected Xcode changed) gets its own server; the old one ends.
let other_dir = tempfile::tempdir().unwrap();
let other = fake_lldb_dap(other_dir.path()).unwrap();
let (other_pid, _) =
server_of(connect_to(slot, &spec(other_dir.path()), &other, LONG).await.unwrap().unwrap()).await;
assert_ne!(other_pid, pid);
assert!(until_gone(pid).await, "the replaced server is still running");
*slot.lock().await = None;
assert!(until_gone(other_pid).await, "the server outlived its holder");
}
/// The server gets the session's environment, and a session with another Xcode
/// (`DEVELOPER_DIR`) does not reuse a server started for a different one.
#[tokio::test]
async fn a_server_is_reused_only_with_the_same_environment() {
let dir = tempfile::tempdir().unwrap();
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
let slot = slot();
let with = |xcode: &str| AdapterSpec { env: vec![("DEVELOPER_DIR".into(), xcode.into())], ..spec(dir.path()) };
let (a, dir_a) = server_of(connect_to(slot, &with("/Xcode-a"), &binary, LONG).await.unwrap().unwrap()).await;
assert_eq!(dir_a, "/Xcode-a");
let (b, dir_b) = server_of(connect_to(slot, &with("/Xcode-b"), &binary, LONG).await.unwrap().unwrap()).await;
assert_eq!(dir_b, "/Xcode-b");
assert_ne!(a, b);
assert_eq!(server_of(connect_to(slot, &with("/Xcode-b"), &binary, LONG).await.unwrap().unwrap()).await.0, b);
*slot.lock().await = None;
assert!(until_gone(b).await);
}
#[tokio::test]
async fn concurrent_attaches_leave_the_active_server_alone() {
let dir = tempfile::tempdir().unwrap();
let other = tempfile::tempdir().unwrap();
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
let slot = slot();
let first = connect_to(slot, &spec(dir.path()), &binary, LONG).await.unwrap().unwrap();
for cwd in [dir.path(), other.path()] {
assert!(connect_to(slot, &spec(cwd), &binary, LONG).await.unwrap().is_none());
}
assert_eq!(starts(dir.path()), 1);
let (first_pid, _) = server_of(first).await;
assert!(alive(first_pid));
let replacement = connect_to(slot, &spec(other.path()), &binary, LONG).await.unwrap().unwrap();
let (replacement_pid, _) = server_of(replacement).await;
assert_ne!(first_pid, replacement_pid, "changing only the working directory replaces an idle server");
assert!(until_gone(first_pid).await);
*slot.lock().await = None;
assert!(until_gone(replacement_pid).await);
}
/// The server ends once no session has been connected for the idle timeout; a connected
/// session, or a new one within the timeout, keeps it.
#[tokio::test]
async fn an_idle_server_ends_and_the_next_session_starts_another() {
let dir = tempfile::tempdir().unwrap();
let Some(binary) = fake_lldb_dap(dir.path()) else { return };
let slot = slot();
let idle = Duration::from_millis(400);
let held = connect_to(slot, &spec(dir.path()), &binary, idle).await.unwrap().unwrap();
tokio::time::sleep(idle * 2).await;
let (pid, _) = server_of(held).await;
assert!(alive(pid), "a connected session keeps the server");
tokio::time::sleep(idle / 4).await;
assert_eq!(server_of(connect_to(slot, &spec(dir.path()), &binary, idle).await.unwrap().unwrap()).await.0, pid);
assert_eq!(starts(dir.path()), 1, "a session within the timeout reuses the server");
assert!(until_gone(pid).await, "the idle server is still running");
let (next, _) = server_of(connect_to(slot, &spec(dir.path()), &binary, idle).await.unwrap().unwrap()).await;
assert_ne!(next, pid);
assert_eq!(starts(dir.path()), 2);
*slot.lock().await = None;
assert!(until_gone(next).await);
}
/// An lldb-dap without server mode fails at once, so the caller can start it as before.
#[tokio::test]
async fn an_lldb_dap_without_server_mode_fails_fast() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let binary = dir.path().join("lldb-dap");
std::fs::write(&binary, "#!/bin/sh\necho \"unknown option $1\" >&2\nexit 1\n").unwrap();
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap();
let started = std::time::Instant::now();
let e = connect_to(slot(), &spec(dir.path()), &binary, LONG).await.err().unwrap();
assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed());
assert!(e.message.contains("exited before accepting connections"), "{}", e.message);
}
}
+46
Переглянути файл
@@ -4044,6 +4044,52 @@ async fn stop_ends_a_native_program_a_run_started_for_the_debugger() {
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
}
/// Xcode Debug's attach goes to the shared lldb-dap server, which keeps the system libraries
/// parsed by earlier sessions (#6665 E7); other sessions start their own adapter.
#[tokio::test]
async fn only_an_lldb_dap_attach_to_a_run_shares_the_server() {
struct CaptureLauncher {
inner: FakeLauncher,
shared: Arc<parking_lot::Mutex<Vec<bool>>>,
}
impl AdapterLauncher for CaptureLauncher {
fn launch(&self, spec: AdapterSpec, reuse: Option<u16>) -> LaunchFuture {
self.shared.lock().push(spec.shared);
self.inner.launch(spec, reuse)
}
}
let shared: Arc<parking_lot::Mutex<Vec<bool>>> = Arc::default();
let launcher = CaptureLauncher {
inner: FakeLauncher { log: Arc::default(), script: Script::default() },
shared: shared.clone(),
};
let manager = DebugManager::with_launcher(Arc::new(LanguageRegistry::from_configs(Vec::new())), Arc::new(launcher));
let session = |adapter: &str, request: &str, linked: bool, xcode: bool| LaunchConfig {
adapter: adapter.into(),
request: request.into(),
extra_json: Some(
if linked {
json!({ RUN_LINK: 7, XCODE_ATTACH: xcode, "pid": 4242 })
} else {
json!({ XCODE_ATTACH: xcode, "pid": 4242 })
}
.to_string(),
),
..config()
};
for launch in [
session("lldb-dap", "attach", true, true),
session("lldb-dap", "attach", true, false),
session("lldb-dap", "attach", false, true),
session("lldb-dap", "launch", true, true),
session("debugpy", "attach", true, true),
] {
let (owner, _) = recording_owner("main");
manager.start(launch, owner).await.unwrap();
}
assert_eq!(*shared.lock(), [true, false, false, false, false]);
}
/// LLDB leaves a breakpoint it can't bind unverified without a reason: say what may be wrong
/// (#6665 E1b: Xcode's debug info had `/tmp/…` for a project under `/private/tmp`).
#[tokio::test]
+76 -4
Переглянути файл
@@ -157,6 +157,15 @@ pub struct TableInfo {
pub comment: Option<String>,
}
/// Non-secret identity of an already-connected data source target.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConnectedSourceInfo {
pub source_id: String,
pub name: String,
pub driver: DbDriver,
pub database: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbColumnInfo")]
@@ -1299,15 +1308,49 @@ impl DbManager {
}
}
/// Lists non-secret metadata for every currently connected source target on this project/window.
/// Never allocates a pool, connects a source, or reads credentials.
pub fn connected_sources(&self) -> Vec<ConnectedSourceInfo> {
let connected = self.connected();
if connected.is_empty() {
return Vec::new();
}
let sources: std::collections::HashMap<String, DataSource> =
self.sources().unwrap_or_default().into_iter().map(|s| (s.id.clone(), s)).collect();
let mut out: Vec<ConnectedSourceInfo> = connected
.into_iter()
.filter_map(|source_id| {
let (base_id, db_suffix) = split_target(&source_id);
let source = sources.get(base_id)?.resolved().ok()?;
let database =
db_suffix.map(str::to_owned).or_else(|| (!source.database.is_empty()).then_some(source.database));
Some(ConnectedSourceInfo { source_id, name: source.name, driver: source.driver, database })
})
.collect();
out.sort_by(|a, b| a.source_id.cmp(&b.source_id));
out
}
/// Every schema (the Schemas tab picks the ones the tree shows); system schemas
/// only with [`DbIntrospection::show_system`].
pub async fn schemas(&self, id: &str) -> IdeResult<Vec<String>> {
let system = self.source(id)?.introspection.show_system;
let pool = self.pool(id).await?;
if let Pool::Snowflake(p) = &*pool {
Self::schemas_on(&pool, system).await
}
/// Read schemas using an existing connection only. Never opens a connection or prompts for credentials.
pub async fn connected_schemas(&self, id: &str) -> IdeResult<Vec<String>> {
let system = self.source(id)?.introspection.show_system;
let pool = self.connected_pool(id)?;
Self::schemas_on(&pool, system).await
}
async fn schemas_on(pool: &Pool, system: bool) -> IdeResult<Vec<String>> {
if let Pool::Snowflake(p) = pool {
return snowflake::meta::schemas(p, system).await;
}
let rows = match &*pool {
let rows = match pool {
Pool::Jdbc(p) => p.metadata(&["schemas"]).await?,
_ => pool.rows(sql::schemas(pool.driver(), system), MAX_META_ROWS).await?,
};
@@ -1316,10 +1359,20 @@ impl DbManager {
pub async fn tables(&self, id: &str, schema: &str) -> IdeResult<Vec<TableInfo>> {
let pool = self.pool(id).await?;
if let Pool::Snowflake(p) = &*pool {
Self::tables_on(&pool, schema).await
}
/// Read tables using an existing connection only. Never opens a connection or prompts for credentials.
pub async fn connected_tables(&self, id: &str, schema: &str) -> IdeResult<Vec<TableInfo>> {
let pool = self.connected_pool(id)?;
Self::tables_on(&pool, schema).await
}
async fn tables_on(pool: &Pool, schema: &str) -> IdeResult<Vec<TableInfo>> {
if let Pool::Snowflake(p) = pool {
return snowflake::meta::tables(p, schema).await;
}
let rows = match &*pool {
let rows = match pool {
Pool::Jdbc(p) => p.metadata(&["tables", schema]).await?,
_ => pool.rows(&sql::tables(pool.driver(), schema), MAX_META_ROWS).await?,
};
@@ -1337,6 +1390,25 @@ impl DbManager {
.collect())
}
/// Executes a SQL statement using an existing connection only (used by extension hosts).
/// Respects read-only connections and never opens a disconnected source or prompts for credentials.
pub async fn connected_execute(
&self,
id: &str,
statement: &str,
max_rows: usize,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
let pool = self.connected_pool(id)?;
if pool.transaction_read_only() {
conn::validate_pg_read_only(statement).map_err(IdeError::invalid)?;
}
if !conn::cursor_statement(statement) {
self.cursors.release_target(id);
}
pool.execute_from(statement, 0, max_rows, cancel).await
}
async fn duckdb_catalog_pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
let source = self.source(id)?;
if id != source.id || source.driver != DbDriver::Jdbc || source.vendor != "duckdb" {
+23
Переглянути файл
@@ -26,6 +26,8 @@ pub enum Capability {
DatabaseSources,
/// Read table metadata of connected project sources; never rows or credentials.
DatabaseSchema,
/// Execute SQL statements against connected project database sources.
DatabaseQuery,
VcsRead,
VcsWrite,
/// The Maven / Gradle dependency graph the IDE resolved.
@@ -109,6 +111,7 @@ impl Capability {
// A trusted project's own files name the programs the IDE starts (its settings, its
// build scripts), so writing them is running code.
Self::ProjectWrite
| Self::DatabaseQuery
| Self::IdeCommands
| Self::Ipc(_)
| Self::Process(_)
@@ -134,6 +137,7 @@ impl Capability {
Self::ProjectWrite => "Create and change files in the open project".into(),
Self::DatabaseSources => "Manage its own database sources and store their passwords in trusted projects".into(),
Self::DatabaseSchema => "Read table structures of connected database sources in trusted projects, without rows or passwords".into(),
Self::DatabaseQuery => "Execute SQL queries and statements on connected database sources in trusted projects".into(),
Self::IdeCommands => "Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing".into(),
Self::VcsRead => "Read version control state".into(),
Self::VcsWrite => "Change version control state (commit, fetch, checkout)".into(),
@@ -294,6 +298,7 @@ impl fmt::Display for Capability {
Self::IdeCommands => f.write_str("ide.commands"),
Self::DatabaseSources => f.write_str("database.sources"),
Self::DatabaseSchema => f.write_str("database.schema"),
Self::DatabaseQuery => f.write_str("database.query"),
Self::VcsRead => f.write_str("vcs.read"),
Self::VcsWrite => f.write_str("vcs.write"),
Self::BuildRead => f.write_str("build.read"),
@@ -389,6 +394,7 @@ impl FromStr for Capability {
"ide.commands" => Self::IdeCommands,
"database.sources" => Self::DatabaseSources,
"database.schema" => Self::DatabaseSchema,
"database.query" => Self::DatabaseQuery,
"vcs.read" => Self::VcsRead,
"vcs.write" => Self::VcsWrite,
"build.read" => Self::BuildRead,
@@ -700,6 +706,23 @@ mod database_tests {
}
}
#[test]
fn database_query_is_a_separate_high_risk_grant_requiring_api21() {
let cap: Capability = "database.query".parse().unwrap();
assert_eq!(cap, Capability::DatabaseQuery);
assert_eq!(cap.to_string(), "database.query");
assert_eq!(cap.risk(), Risk::High);
assert!(!cap.auto_migrates());
for other in [Capability::ProjectRead, Capability::DatabaseSources, Capability::DatabaseSchema] {
assert!(!other.covers(&cap));
}
for (api, valid) in [("^1.20", false), ("^1.21", true)] {
let text = format!(
"id='query'\nname='Query'\nversion='1.0.0'\nengines.openidea='{api}'\n[capabilities]\nrequired=['database.query']"
);
assert_eq!(crate::Manifest::parse(&text).is_ok(), valid);
}
}
#[test]
fn database_sources_is_a_medium_risk_exact_grant_requiring_api4() {
let cap: Capability = "database.sources".parse().unwrap();
assert_eq!(cap, Capability::DatabaseSources);
+3
Переглянути файл
@@ -430,6 +430,9 @@ impl Manifest {
if matches!(cap, Capability::DatabaseSchema) {
self.needs_api(&format!("capability `{cap}`"), 20)?;
}
if matches!(cap, Capability::DatabaseQuery) {
self.needs_api(&format!("capability `{cap}`"), 21)?;
}
if matches!(cap, Capability::Agents) {
self.needs_api(&format!("capability `{cap}`"), 18)?;
}
+5 -2
Переглянути файл
@@ -101,8 +101,10 @@ pub async fn agent_hermes_profiles(host: &Host, window: &str) -> IdeResult<Vec<i
}
/// Refreshes the model catalog; force bypasses freshness, not the cooldown.
/// Reads provider config and resolves the agent executable on PATH, so it runs on the
/// blocking pool.
#[command(trust = trusted)]
pub fn agent_refresh_models(
pub async fn agent_refresh_models(
host: &Host,
window: &str,
provider: String,
@@ -111,7 +113,8 @@ pub fn agent_refresh_models(
) -> IdeResult<AgentModelCatalog> {
// Refreshes the selected agent's model catalog without sending a prompt.
host.require_trust(window)?;
host.project(window)?.agents.refresh_models(&provider, force, model.as_deref())
let agents = host.project(window)?.agents.clone();
host.blocking(move || agents.refresh_models(&provider, force, model.as_deref())).await
}
/// Probes Copilot's model catalog for a staged GitHub account without persisting until Apply.
+86 -12
Переглянути файл
@@ -1756,6 +1756,32 @@ impl PluginApi {
}
}
impl PluginApi {
fn database_for_client(
&self,
root: &Path,
client: Option<&str>,
source_id: Option<&str>,
) -> Result<(Arc<crate::Host>, Arc<ide_db::DbManager>), HostError> {
let (host, fallback) = self.database_host(root)?;
// Connections belong to windows, even when several windows open the same root.
// Prefer the invoking window; background calls may use any matching connected instance.
let db = client
.and_then(|client| host.project(client).ok())
.filter(|project| project.root == root)
.map(|project| project.db.clone())
.or_else(|| {
let target = source_id?;
host.projects()
.into_iter()
.find(|project| project.root == root && project.db.is_connected(target))
.map(|project| project.db.clone())
})
.unwrap_or(fallback);
Ok((host, db))
}
}
impl HostApi for PluginApi {
fn database_table_schema(
&self,
@@ -1766,21 +1792,69 @@ impl HostApi for PluginApi {
timeout: Duration,
) -> Result<ide_plugin::PluginDatabaseTableSchema, HostError> {
self.require_api("database table schema", 20)?;
let (host, fallback) = self.database_host(root)?;
// Connections belong to windows, even when several windows open the same root.
// Prefer the invoking window; background calls may use any connected instance.
let db = client
let (host, db) = self.database_for_client(root, client, Some(&table.source_id))?;
host.runtime.block_on(super::database::table_schema(&db, table, cancel, timeout))
}
fn database_connected_sources(
&self,
root: &Path,
client: Option<&str>,
) -> Result<Vec<ide_plugin::PluginConnectedDataSource>, HostError> {
self.require_api("database connected sources", 21)?;
let (host, _) = self.database_host(root)?;
if let Some(db) = client
.and_then(|client| host.project(client).ok())
.filter(|project| project.root == root)
.map(|project| project.db.clone())
.or_else(|| {
host.projects()
.into_iter()
.find(|project| project.root == root && project.db.is_connected(&table.source_id))
.map(|project| project.db.clone())
})
.unwrap_or(fallback);
host.runtime.block_on(super::database::table_schema(&db, table, cancel, timeout))
{
return super::database::connected_sources(&db);
}
let dbs: Vec<_> = host
.projects()
.into_iter()
.filter(|project| project.root == root)
.map(|project| project.db.clone())
.collect();
super::database::connected_sources_across(&dbs)
}
fn database_list_schemas(
&self,
root: &Path,
client: Option<&str>,
source_id: &str,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<Vec<String>, HostError> {
self.require_api("database schema listing", 21)?;
let (host, db) = self.database_for_client(root, client, Some(source_id))?;
host.runtime.block_on(super::database::list_schemas(&db, source_id, cancel, timeout))
}
fn database_list_tables(
&self,
root: &Path,
client: Option<&str>,
source_id: &str,
schema: &str,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<Vec<ide_plugin::PluginDatabaseTableSummary>, HostError> {
self.require_api("database table listing", 21)?;
let (host, db) = self.database_for_client(root, client, Some(source_id))?;
host.runtime.block_on(super::database::list_tables(&db, source_id, schema, cancel, timeout))
}
fn database_execute_query(
&self,
root: &Path,
client: Option<&str>,
source_id: &str,
sql: &str,
max_rows: Option<u32>,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<ide_plugin::PluginDatabaseQueryResult, HostError> {
self.require_api("database query execution", 21)?;
let (host, db) = self.database_for_client(root, client, Some(source_id))?;
host.runtime.block_on(super::database::execute_query(&db, source_id, sql, max_rows, cancel, timeout))
}
fn database_upsert(&self, root: &Path, source: ide_plugin::PluginDataSource) -> Result<(), HostError> {
let (host, db) = self.database_host(root)?;
+198 -2
Переглянути файл
@@ -2,8 +2,11 @@
use super::api::PluginApi;
use super::{PluginHost, WindowRequest};
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult};
use ide_db::{DataSource, DbDriver, DbProperty};
use ide_plugin::{HostError, PluginDataSource};
use ide_db::{DataSource, DbDriver, DbProperty, DbTableKind};
use ide_plugin::{
HostError, PluginConnectedDataSource, PluginDataSource, PluginDatabaseQueryColumn, PluginDatabaseQueryResult,
PluginDatabaseTableSummary,
};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
@@ -253,6 +256,199 @@ pub(super) async fn table_schema(
})
}
fn driver_name(driver: DbDriver) -> &'static str {
match driver {
DbDriver::Sqlite => "sqlite",
DbDriver::Postgres => "postgres",
DbDriver::Mysql => "mysql",
DbDriver::SqlServer => "sqlServer",
DbDriver::Clickhouse => "clickhouse",
DbDriver::Oracle => "oracle",
DbDriver::Snowflake => "snowflake",
DbDriver::Jdbc => "jdbc",
}
}
fn table_kind_name(kind: DbTableKind) -> &'static str {
match kind {
DbTableKind::Table => "table",
DbTableKind::View => "view",
DbTableKind::MaterializedView => "materializedView",
}
}
fn valid_db_ident(value: &str, non_empty: bool) -> bool {
(!non_empty || !value.is_empty()) && value.len() <= 4096 && !value.contains('\0')
}
pub(super) fn connected_sources(db: &ide_db::DbManager) -> Result<Vec<PluginConnectedDataSource>, HostError> {
Ok(db
.connected_sources()
.into_iter()
.take(4096)
.map(|s| PluginConnectedDataSource {
source_id: s.source_id,
name: s.name,
driver: driver_name(s.driver).to_owned(),
database: s.database,
})
.collect())
}
pub(super) fn connected_sources_across(
dbs: &[Arc<ide_db::DbManager>],
) -> Result<Vec<PluginConnectedDataSource>, HostError> {
let mut by_id = std::collections::BTreeMap::new();
for db in dbs {
for s in db.connected_sources() {
by_id.entry(s.source_id.clone()).or_insert_with(|| PluginConnectedDataSource {
source_id: s.source_id,
name: s.name,
driver: driver_name(s.driver).to_owned(),
database: s.database,
});
if by_id.len() >= 4096 {
break;
}
}
if by_id.len() >= 4096 {
break;
}
}
Ok(by_id.into_values().collect())
}
pub(super) async fn list_schemas(
db: &ide_db::DbManager,
source_id: &str,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<Vec<String>, HostError> {
if !valid_db_ident(source_id, true) {
return Err(HostError::Invalid("invalid database source id".into()));
}
if cancel.is_cancelled() {
return Err(HostError::Cancelled);
}
let read = db.connected_schemas(source_id);
let mut schemas = tokio::select! {
biased;
_ = cancel.cancelled() => return Err(HostError::Cancelled),
result = tokio::time::timeout(timeout, read) => result
.map_err(|_| HostError::Failed("Database schemas request timed out".into()))?.map_err(error)?,
};
schemas.truncate(4096);
Ok(schemas)
}
pub(super) async fn list_tables(
db: &ide_db::DbManager,
source_id: &str,
schema: &str,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<Vec<PluginDatabaseTableSummary>, HostError> {
if !valid_db_ident(source_id, true) || !valid_db_ident(schema, false) {
return Err(HostError::Invalid("invalid database schema reference".into()));
}
if cancel.is_cancelled() {
return Err(HostError::Cancelled);
}
let read = db.connected_tables(source_id, schema);
let tables = tokio::select! {
biased;
_ = cancel.cancelled() => return Err(HostError::Cancelled),
result = tokio::time::timeout(timeout, read) => result
.map_err(|_| HostError::Failed("Database tables request timed out".into()))?.map_err(error)?,
};
Ok(tables
.into_iter()
.take(4096)
.map(|t| PluginDatabaseTableSummary {
name: t.name,
kind: table_kind_name(t.kind).to_owned(),
comment: t.comment,
})
.collect())
}
pub(super) async fn execute_query(
db: &ide_db::DbManager,
source_id: &str,
sql: &str,
max_rows: Option<u32>,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<PluginDatabaseQueryResult, HostError> {
if !valid_db_ident(source_id, true) {
return Err(HostError::Invalid("invalid database source id".into()));
}
if sql.trim().is_empty() || sql.len() > 262_144 || sql.contains('\0') {
return Err(HostError::Invalid("invalid SQL statement".into()));
}
if cancel.is_cancelled() {
return Err(HostError::Cancelled);
}
let limit = max_rows.unwrap_or(100).clamp(1, 1000) as usize;
let query_cancel = cancel.child_token();
let timer_cancel = query_cancel.clone();
let timed_out = Arc::new(std::sync::atomic::AtomicBool::new(false));
let timed_out_flag = timed_out.clone();
let timer = tokio::spawn(async move {
tokio::time::sleep(timeout).await;
timed_out_flag.store(true, std::sync::atomic::Ordering::Release);
timer_cancel.cancel();
});
// Allow a brief grace window after cancelling `query_cancel` so drivers can send server-side
// cancel (`pg_cancel_backend` / `KILL QUERY`) and discard the interrupted connection cleanly.
let grace = timeout.saturating_add(Duration::from_secs(2));
let run = db.connected_execute(source_id, sql, limit, &query_cancel);
let outcome = tokio::select! {
biased;
result = tokio::time::timeout(grace, run) => result,
_ = async {
cancel.cancelled().await;
tokio::time::sleep(Duration::from_secs(2)).await;
} => {
timer.abort();
return Err(HostError::Cancelled);
}
};
timer.abort();
let mut result = match outcome {
Err(_) => {
return Err(if cancel.is_cancelled() {
HostError::Cancelled
} else {
HostError::Failed("Database query execution timed out".into())
});
}
Ok(Ok(result)) => result,
Ok(Err(err)) => {
if cancel.is_cancelled() {
return Err(HostError::Cancelled);
}
if timed_out.load(std::sync::atomic::Ordering::Acquire) && err.kind == ide_core::error::ErrorKind::Cancelled
{
return Err(HostError::Failed("Database query execution timed out".into()));
}
return Err(error(err));
}
};
result.cap_cells(8192);
Ok(PluginDatabaseQueryResult {
columns: result
.columns
.into_iter()
.map(|c| PluginDatabaseQueryColumn { name: c.name, type_name: c.type_name })
.collect(),
rows: result.rows,
affected: result.affected.and_then(|v| (v.is_finite() && v >= 0.0).then_some(v as u64)),
has_more: result.has_more,
elapsed_ms: if result.elapsed_ms.is_finite() { result.elapsed_ms.max(0.0) as u64 } else { 0 },
})
}
#[cfg(test)]
mod tests {
use super::*;
+81 -16
Переглянути файл
@@ -16,8 +16,10 @@ pub struct NavigationFiles {
}
/// Discovery offers at most this many files; larger projects get navigation
/// on the first ones instead of none.
const MAX_NAVIGATION_FILES: usize = 20_000;
/// on the first ones instead of none. As many as one graph covers, so the
/// "covers N of M files" notice stays true.
const MAX_NAVIGATION_FILES: usize = super::navigation::MAX_FILES;
const MAX_INDEX_BATCH: usize = 128;
/// The first `limit` files by path that `in_scope` accepts, and how many it accepts in all.
/// Sorting keeps the covered files the same across index rebuilds.
@@ -80,6 +82,15 @@ pub fn plugin_navigation_invalidate(
Ok(())
}
struct LoadedNavigationDoc {
path: PathBuf,
document: Option<ide_core::DocId>,
version: Option<u32>,
text: String,
symbols: Vec<ide_language::SymbolTag>,
scope: String,
}
#[command(trust = trusted)]
pub async fn plugin_navigation_index(
host: &crate::Host,
@@ -88,8 +99,8 @@ pub async fn plugin_navigation_index(
paths: Vec<PathBuf>,
request: ide_core::RequestId,
) -> IdeResult<()> {
if paths.len() > 16 {
return Err(IdeError::invalid("navigation batches are limited to 16 files"));
if paths.len() > MAX_INDEX_BATCH {
return Err(IdeError::invalid("navigation batches are limited to 128 files"));
}
let plugins = plugins.clone();
let project = host.project(window)?;
@@ -99,33 +110,45 @@ pub async fn plugin_navigation_index(
if !project.is_trusted() {
return Err(IdeError::unavailable("project is not trusted"));
}
let extensions = plugins.navigation_extensions(&project.root);
let project_roots = project.roots();
// A project window group's members are project scope.
let mut roots = vec![project.root.clone()];
roots.extend(crate::project::workspace_member_roots(&project.root));
for path in paths {
let mut loaded_docs = Vec::with_capacity(paths.len());
let mut evict_paths = Vec::new();
for raw_path in paths {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let Ok(path) = ide_plugin::resolve_in_roots(&roots, &path.to_string_lossy()) else {
let Ok(path) = ide_plugin::resolve_in_roots(&roots, &raw_path.to_string_lossy()) else {
evict_paths.push(raw_path);
continue;
};
let extensions = plugins.navigation_extensions(&project.root);
if !path.extension().and_then(|e| e.to_str()).is_some_and(|e| extensions.iter().any(|x| x == e)) {
evict_paths.push(path);
continue;
}
let document = project.documents.by_path(&path);
let (text, version, language) = if let Some(id) = document {
let snapshot = project.documents.text_snapshot(id)?;
let Ok(snapshot) = project.documents.text_snapshot(id) else {
evict_paths.push(path);
continue;
};
if snapshot.large {
evict_paths.push(path);
continue;
}
(snapshot.text, Some(snapshot.version), snapshot.language)
} else {
let Ok(loaded) = project.documents.load_file_bounded(&path, super::navigation::MAX_DOCUMENT_BYTES)
else {
evict_paths.push(path);
continue;
};
if loaded.binary || loaded.large {
evict_paths.push(path);
continue;
}
let text = loaded.text;
@@ -133,23 +156,42 @@ pub async fn plugin_navigation_index(
(text, None, language)
};
if text.len() > crate::plugins::navigation::MAX_DOCUMENT_BYTES {
evict_paths.push(path);
continue;
}
let symbols = project
.index
.symbols_for_text(&path, &text)
.unwrap_or_else(|| project.syntax.syntax().tags(&language, &text));
let roots = project.roots();
let scope = roots
let scope = project_roots
.roots
.iter()
.filter(|r| path.starts_with(project.root.join(&r.path)))
.max_by_key(|r| r.path.len())
.and_then(|r| r.detected_from.as_deref())
.unwrap_or("");
plugins.index_navigation(
.unwrap_or("")
.to_owned();
loaded_docs.push(LoadedNavigationDoc { path, document, version, text, symbols, scope });
}
if !evict_paths.is_empty() {
plugins.invalidate_client_navigation(&project.root, Some(&client), Some(&evict_paths));
}
if !loaded_docs.is_empty() {
let snapshots: Vec<_> = loaded_docs
.iter()
.map(|doc| crate::plugins::navigation::Snapshot {
path: &doc.path,
version: doc.version,
text: &doc.text,
symbols: &doc.symbols,
scope: &doc.scope,
})
.collect();
if let Err(err) = plugins.index_navigation_batch(
&project.root,
crate::plugins::navigation::Snapshot { path: &path, version, text: &text, symbols: &symbols, scope },
&snapshots,
Invocation {
command_chain: Vec::new(),
client: Some(client.clone()),
@@ -158,10 +200,33 @@ pub async fn plugin_navigation_index(
selected_paths: Vec::new(),
global_settings: false,
},
)?;
Some(&cancel),
) {
let remaining_paths: Vec<PathBuf> = loaded_docs
.into_iter()
.filter(|doc| {
cancel.is_cancelled()
|| doc.document.is_some_and(|id| project.documents.version(id).ok() != doc.version)
})
.map(|doc| doc.path)
.collect();
if !remaining_paths.is_empty() {
plugins.invalidate_client_navigation(&project.root, Some(&client), Some(&remaining_paths));
}
return Err(err);
}
// A document edit while WASM was executing must not publish stale ranges.
if cancel.is_cancelled() || document.is_some_and(|id| project.documents.version(id).ok() != version) {
plugins.invalidate_client_navigation(&project.root, Some(&client), Some(&[path]));
let stale_paths: Vec<PathBuf> = loaded_docs
.into_iter()
.filter(|doc| {
cancel.is_cancelled()
|| doc.document.is_some_and(|id| project.documents.version(id).ok() != doc.version)
})
.map(|doc| doc.path)
.collect();
if !stale_paths.is_empty() {
plugins.invalidate_client_navigation(&project.root, Some(&client), Some(&stale_paths));
}
}
Ok(())
+252 -55
Переглянути файл
@@ -15,6 +15,66 @@ pub const MAX_DOCUMENT_BYTES: usize = ide_lsp::MAX_INJECTED_DOCUMENT_BYTES;
/// Files one plugin's graph covers per project and window.
pub const MAX_FILES: usize = 20_000;
const MAX_EDGES: usize = 4096;
const MAX_GRAPH_EDGES: usize = 200_000;
const MAX_ACTOR_CHUNK: usize = 16;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct BatchIndexSummary {
pub skipped_invalid: usize,
}
fn edges_are_empty(edges: &Edges) -> bool {
edges.definitions.is_empty() && edges.references.is_empty() && edges.aliases.is_empty() && edges.markers.is_empty()
}
fn validate_edges(plugin_id: &str, path: &Path, text: &str, edges: &Edges) -> IdeResult<()> {
if edges_are_empty(edges) {
return Ok(());
}
let lines: Vec<_> = text.split('\n').map(|l| l.encode_utf16().count()).collect();
let output_bytes = edges
.definitions
.iter()
.chain(&edges.references)
.chain(&edges.markers)
.map(|a| a.key.len().saturating_add(32))
.sum::<usize>()
.saturating_add(edges.aliases.iter().map(|a| a.prefix.len() + a.target.len()).sum::<usize>());
if output_bytes > MAX_DOCUMENT_BYTES {
return Err(IdeError::invalid("document index output is too large"));
}
if edges.aliases.len() > 256
|| edges.aliases.iter().any(|a| {
!a.prefix.ends_with('#') || !a.target.ends_with('#') || a.prefix.len() > 1024 || a.target.len() > 1024
})
|| edges.definitions.len() + edges.references.len() > MAX_EDGES
|| edges
.definitions
.iter()
.chain(&edges.references)
.any(|a| a.key.is_empty() || a.key.len() > 1024 || !valid_range(&lines, a.range))
{
return Err(IdeError::invalid(format!("{plugin_id}: invalid navigation anchors in {}", path.display())));
}
if edges.markers.len() > MAX_EDGES
|| edges.markers.iter().any(|a| a.key.is_empty() || a.key.len() > 1024 || !valid_range(&lines, a.range))
{
return Err(IdeError::invalid(format!("{plugin_id}: invalid navigation markers in {}", path.display())));
}
Ok(())
}
fn to_index_symbols(symbols: &[SymbolTag]) -> Vec<ide_plugin::indexing::IndexSymbol> {
symbols
.iter()
.map(|s| ide_plugin::indexing::IndexSymbol {
name: s.name.clone(),
kind: serde_json::to_value(s.kind).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default(),
container: s.container.clone(),
range: s.range,
})
.collect()
}
pub struct Snapshot<'a> {
pub path: &'a Path,
@@ -236,7 +296,6 @@ impl PluginHost {
if plugins.is_empty() {
return Ok(());
}
let lines: Vec<_> = text.split('\n').map(|l| l.encode_utf16().count()).collect();
for plugin in plugins {
// A full graph keeps the files it covers; discovery already told the user
// the rest are left out, so they are skipped without running the plugin.
@@ -250,64 +309,14 @@ impl PluginHost {
self.changed();
}
let (owned_path, owned_text) = (path.to_string_lossy().into_owned(), text.to_owned());
let symbols = symbols
.iter()
.map(|s| ide_plugin::indexing::IndexSymbol {
name: s.name.clone(),
kind: serde_json::to_value(s.kind)
.ok()
.and_then(|v| v.as_str().map(str::to_owned))
.unwrap_or_default(),
container: s.container.clone(),
range: s.range,
})
.collect::<Vec<_>>();
let symbols = to_index_symbols(symbols);
let ctx = invocation.clone();
let started = std::time::Instant::now();
let result = actor.call(None, move |rt| rt.index_document(&owned_path, &owned_text, &symbols, ctx));
let edges = self
.finish_provider_call(&plugin, &actor, started, result)
.ok_or_else(|| IdeError::unavailable("document indexer did not return a result"))?;
let output_bytes = edges
.definitions
.iter()
.chain(&edges.references)
.chain(&edges.markers)
.map(|a| a.key.len().saturating_add(32))
.sum::<usize>()
.saturating_add(edges.aliases.iter().map(|a| a.prefix.len() + a.target.len()).sum::<usize>());
if output_bytes > MAX_DOCUMENT_BYTES {
return Err(IdeError::invalid("document index output is too large"));
}
if edges.aliases.len() > 256
|| edges.aliases.iter().any(|a| {
!a.prefix.ends_with('#')
|| !a.target.ends_with('#')
|| a.prefix.len() > 1024
|| a.target.len() > 1024
})
|| edges.definitions.len() + edges.references.len() > MAX_EDGES
|| edges
.definitions
.iter()
.chain(&edges.references)
.any(|a| a.key.is_empty() || a.key.len() > 1024 || !valid_range(&lines, a.range))
{
return Err(IdeError::invalid(format!(
"{}: invalid navigation anchors in {}",
plugin.id(),
path.display()
)));
}
if edges.markers.len() > MAX_EDGES
|| edges.markers.iter().any(|a| a.key.is_empty() || a.key.len() > 1024 || !valid_range(&lines, a.range))
{
return Err(IdeError::invalid(format!(
"{}: invalid navigation markers in {}",
plugin.id(),
path.display()
)));
}
validate_edges(plugin.id(), path, text, &edges)?;
let mut index = self.navigation.lock();
if index.epochs.get(root).copied() != generation {
return Err(IdeError::cancelled());
@@ -322,16 +331,19 @@ impl PluginHost {
if !graph.instance.ptr_eq(&Arc::downgrade(&plugin)) {
*graph = Graph { instance: Arc::downgrade(&plugin), ..Default::default() };
}
graph.remove(path);
if edges_are_empty(&edges) {
continue;
}
if graph.files.len() >= MAX_FILES && !graph.files.contains_key(path) {
continue;
}
graph.remove(path);
if graph.edges
+ edges.definitions.len()
+ edges.references.len()
+ edges.aliases.len()
+ edges.markers.len()
> 200_000
> MAX_GRAPH_EDGES
{
return Err(IdeError::unavailable("navigation association limit reached"));
}
@@ -340,6 +352,191 @@ impl PluginHost {
Ok(())
}
/// Index a batch of bounded snapshots in short actor chunks (up to 16 files per call).
/// Full graphs skip uncovered files before running the plugin, empty-edge documents are not
/// stored, and individual invalid documents are skipped/evicted without failing the batch.
pub fn index_navigation_batch(
&self,
root: &Path,
snapshots: &[Snapshot<'_>],
invocation: Invocation,
cancel: Option<&ide_core::CancellationToken>,
) -> IdeResult<BatchIndexSummary> {
if snapshots.is_empty() {
return Ok(BatchIndexSummary::default());
}
if !(self.project_policy.read())(root) {
return Err(IdeError::unavailable("project is not trusted"));
}
let mut roots = vec![root.to_path_buf()];
roots.extend(crate::project::workspace_member_roots(root));
let mut summary = BatchIndexSummary::default();
let mut prepared = Vec::with_capacity(snapshots.len());
for snap in snapshots {
if snap.text.len() > MAX_DOCUMENT_BYTES {
tracing::warn!(path = %snap.path.display(), "navigation document is too large");
summary.skipped_invalid += 1;
continue;
}
let path = dunce::simplified(snap.path);
match ide_plugin::resolve_in_roots(&roots, &path.to_string_lossy()) {
Ok(real) if real == path => {
let extension = path.extension().and_then(|e| e.to_str()).unwrap_or_default().to_owned();
prepared.push((path.to_owned(), extension, snap));
}
Ok(_) | Err(_) => {
tracing::warn!(path = %path.display(), "navigation skipped invalid path");
summary.skipped_invalid += 1;
}
}
}
if prepared.is_empty() {
return Ok(summary);
}
let project_key = (root.to_owned(), invocation.client.clone());
let generation = self.navigation.lock().epochs.get(root).copied();
let plugins: Vec<(Arc<super::LoadedPlugin>, Vec<String>)> = self
.plugins
.read()
.values()
.filter(|p| {
p.status().is_live()
&& p.dev_root.as_deref().is_none_or(|r| r == root)
&& p.meta.lock().granted.contains(&Capability::ProjectRead)
})
.filter_map(|p| declaration(p).map(|d| (p.clone(), d.extensions)))
.collect();
if plugins.is_empty() {
return Ok(summary);
}
for (plugin, exts) in plugins {
let matching_indices: Vec<usize> = {
let index = self.navigation.lock();
let full_graph = index
.projects
.get(&project_key)
.and_then(|g| g.get(plugin.id()))
.filter(|g| g.instance.ptr_eq(&Arc::downgrade(&plugin)) && g.files.len() >= MAX_FILES);
prepared
.iter()
.enumerate()
.filter_map(|(idx, (path, ext, _))| {
if !exts.iter().any(|e| e == ext) {
return None;
}
if full_graph.is_some_and(|g| !g.files.contains_key(path)) {
return None;
}
Some(idx)
})
.collect()
};
if matching_indices.is_empty() {
continue;
}
if cancel.is_some_and(ide_core::CancellationToken::is_cancelled) {
return Err(IdeError::cancelled());
}
let (actor, activated) = self.ensure_active(&plugin, invocation.client.as_deref())?;
if activated {
self.changed();
}
for chunk in matching_indices.chunks(MAX_ACTOR_CHUNK) {
if cancel.is_some_and(ide_core::CancellationToken::is_cancelled) {
return Err(IdeError::cancelled());
}
let items: Vec<_> = chunk
.iter()
.map(|&idx| {
let (ref path, _, snap) = prepared[idx];
(idx, path.to_string_lossy().into_owned(), snap.text.to_owned(), to_index_symbols(snap.symbols))
})
.collect();
let ctx = invocation.clone();
let chunk_cancel = cancel.cloned();
let started = std::time::Instant::now();
let result = actor.call(None, move |rt| {
let mut out = Vec::with_capacity(items.len());
for (idx, owned_path, owned_text, symbols) in items {
if chunk_cancel.as_ref().is_some_and(ide_core::CancellationToken::is_cancelled) {
return Ok(None);
}
let edges = rt.index_document(&owned_path, &owned_text, &symbols, ctx.clone())?;
out.push((idx, edges));
}
Ok(Some(out))
});
let Some(maybe_edges) = self.finish_provider_call(&plugin, &actor, started, result) else {
let mut index = self.navigation.lock();
if let Some(graph) = index.projects.get_mut(&project_key).and_then(|g| g.get_mut(plugin.id())) {
for &idx in chunk {
graph.remove(&prepared[idx].0);
}
}
return Err(IdeError::unavailable("document indexer did not return a result"));
};
let Some(chunk_edges) = maybe_edges else {
return Err(IdeError::cancelled());
};
if cancel.is_some_and(ide_core::CancellationToken::is_cancelled) {
return Err(IdeError::cancelled());
}
let mut index = self.navigation.lock();
if index.epochs.get(root).copied() != generation {
return Err(IdeError::cancelled());
}
if index.projects.len() >= 16 && !index.projects.contains_key(&project_key) {
return Err(IdeError::unavailable("navigation project limit reached"));
}
let graph =
index.projects.entry(project_key.clone()).or_default().entry(plugin.id().to_owned()).or_default();
if !graph.instance.ptr_eq(&Arc::downgrade(&plugin)) {
*graph = Graph { instance: Arc::downgrade(&plugin), ..Default::default() };
}
for (idx, edges) in chunk_edges {
let (ref path, _, snap) = prepared[idx];
graph.remove(path);
if let Err(err) = validate_edges(plugin.id(), path, snap.text, &edges) {
tracing::warn!("{err}");
summary.skipped_invalid += 1;
continue;
}
if edges_are_empty(&edges) {
continue;
}
if graph.files.len() >= MAX_FILES && !graph.files.contains_key(path) {
continue;
}
let new_edges =
edges.definitions.len() + edges.references.len() + edges.aliases.len() + edges.markers.len();
if graph.edges + new_edges > MAX_GRAPH_EDGES {
tracing::warn!(
plugin = %plugin.id(),
path = %path.display(),
"navigation association limit reached; skipping document"
);
summary.skipped_invalid += 1;
continue;
}
graph.insert(
path.clone(),
File {
version: snap.version,
scope: snap.scope.to_owned(),
hash: snapshot_hash(snap.text),
edges,
},
);
}
}
}
Ok(summary)
}
/// Resolves only current live providers. Disable/reload/trap cannot retain
/// navigable stale data, even if a background snapshot finished concurrently.
pub fn navigation_at(
+4 -2
Переглянути файл
@@ -62,7 +62,8 @@ done
}
for _ in 0..20 {
for window in ["first", "second"] {
let state = ops::agent::agent_refresh_models(&host, window, "catalog-test".into(), true, None).unwrap();
let state =
ops::agent::agent_refresh_models(&host, window, "catalog-test".into(), true, None).await.unwrap();
assert!(state.refreshing);
}
}
@@ -81,7 +82,8 @@ done
assert!(completed.is_ok(), "both windows must receive the completed catalog");
for _ in 0..20 {
for window in ["first", "second"] {
let catalog = ops::agent::agent_refresh_models(&host, window, "catalog-test".into(), true, None).unwrap();
let catalog =
ops::agent::agent_refresh_models(&host, window, "catalog-test".into(), true, None).await.unwrap();
assert!(!catalog.refreshing);
assert!(catalog.retry_at_ms.is_some());
let models = catalog.config.iter().find(|o| o.category.as_deref() == Some("model")).unwrap();
+153
Переглянути файл
@@ -422,3 +422,156 @@ async fn schema_reads_user_tables_without_rows_or_credentials_and_enforces_grant
assert!(db.connected_table_details("user-source", None, "main", "users").await.is_err());
assert!(!db.is_connected("user-source"), "schema reads cannot reconnect a disconnected source");
}
#[tokio::test(flavor = "multi_thread")]
async fn schema_discovery_and_query_execution_enforce_grants_trust_and_connection_isolation() {
let f = Harness::with_timeout(Duration::from_secs(10));
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let db = f.host.project("main").unwrap().db.clone();
db.save_sources(vec![ide_db::DataSource {
id: "user-source".into(),
name: "User SQLite".into(),
driver: ide_db::DbDriver::Sqlite,
file: Some(f.root.join("db.sqlite").into()),
..Default::default()
}])
.await
.unwrap();
// Disconnected sources are never listed or queried implicitly.
let initial_sources: Vec<serde_json::Value> =
serde_json::from_str(&f.run("connected-sources", None).unwrap().unwrap()).unwrap();
assert!(initial_sources.is_empty());
assert!(f.run("list-schemas", Some("user-source")).is_err());
assert!(!db.is_connected("user-source"));
let q_req = serde_json::json!({
"sourceId": "user-source",
"sql": "SELECT id, name FROM users ORDER BY id",
"maxRows": 1
})
.to_string();
assert!(f.run("execute-query", Some(&q_req)).is_err(), "query execution never connects implicitly");
assert!(!db.is_connected("user-source"));
let cancel = CancellationToken::new();
for sql in [
"CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT NOT NULL)",
"INSERT INTO users(name) VALUES ('alice'), ('bob')",
] {
db.execute("user-source", sql, 100, &cancel).await.unwrap();
}
// Window isolation: second window has no connection of its own for discovery or queries.
let second_inv = Invocation { client: Some("second".into()), ..f.invocation() };
let second_sources: Vec<serde_json::Value> = serde_json::from_str(
&f.plugins.run_command(ID, "connected-sources", None, second_inv.clone()).unwrap().unwrap(),
)
.unwrap();
assert!(second_sources.is_empty(), "a disconnected window cannot see another window's connections");
assert!(f.plugins.run_command(ID, "list-schemas", Some("user-source"), second_inv.clone()).is_err());
assert!(
f.plugins
.run_command(ID, "list-tables", Some(r#"{"sourceId":"user-source","schema":"main"}"#), second_inv.clone())
.is_err()
);
assert!(f.plugins.run_command(ID, "execute-query", Some(&q_req), second_inv).is_err());
// Schema discovery returns only non-secret identity + schemas/tables (never credentials or row data).
let sources_json = f.run("connected-sources", None).unwrap().unwrap();
let sources: Vec<serde_json::Value> = serde_json::from_str(&sources_json).unwrap();
assert_eq!(sources.len(), 1);
assert_eq!(sources[0]["sourceId"], "user-source");
assert_eq!(sources[0]["driver"], "sqlite");
assert!(!sources_json.contains("password") && !sources_json.contains("alice"));
let schemas: Vec<String> =
serde_json::from_str(&f.run("list-schemas", Some("user-source")).unwrap().unwrap()).unwrap();
assert!(schemas.iter().any(|s| s == "main"));
let tables: Vec<serde_json::Value> = serde_json::from_str(
&f.run("list-tables", Some(r#"{"sourceId":"user-source","schema":"main"}"#)).unwrap().unwrap(),
)
.unwrap();
assert!(tables.iter().any(|t| t["name"] == "users" && t["kind"] == "table"));
// Query execution respects max_rows & has_more and returns rows.
let q_res: serde_json::Value =
serde_json::from_str(&f.run("execute-query", Some(&q_req)).unwrap().unwrap()).unwrap();
assert_eq!(q_res["rows"].as_array().unwrap().len(), 1);
assert_eq!(q_res["rows"][0][1], "alice");
assert_eq!(q_res["hasMore"], true);
// Large cells are capped at 8192 UTF-16 code units.
let wide_req = serde_json::json!({
"sourceId": "user-source",
"sql": "SELECT replace(hex(zeroblob(5000)), '0', 'a')",
})
.to_string();
let wide_res: serde_json::Value =
serde_json::from_str(&f.run("execute-query", Some(&wide_req)).unwrap().unwrap()).unwrap();
assert_eq!(wide_res["rows"][0][0].as_str().unwrap().encode_utf16().count(), 8192);
// Invalid inputs (empty SQL, NUL bytes) are rejected cleanly.
for bad in [
serde_json::json!({ "sourceId": "user-source", "sql": " " }),
serde_json::json!({ "sourceId": "user-source", "sql": "SELECT 1\0" }),
serde_json::json!({ "sourceId": "user\0source", "sql": "SELECT 1" }),
] {
assert!(f.run("execute-query", Some(&bad.to_string())).is_err(), "{bad}");
}
// DDL/DML affected count works under database.query.
let dml_req = serde_json::json!({
"sourceId": "user-source",
"sql": "UPDATE users SET name = 'charlie' WHERE id = 2",
})
.to_string();
let dml_res: serde_json::Value =
serde_json::from_str(&f.run("execute-query", Some(&dml_req)).unwrap().unwrap()).unwrap();
assert_eq!(dml_res["affected"], 1);
// Background calls (client: None) see sources connected in any window of the project.
db.disconnect("user-source").await;
let second_db = f.host.project("second").unwrap().db.clone();
second_db.execute("user-source", "SELECT 1", 1, &cancel).await.unwrap();
let bg_sources: Vec<serde_json::Value> = serde_json::from_str(
&f.plugins
.run_command(ID, "connected-sources", None, Invocation { client: None, ..f.invocation() })
.unwrap()
.unwrap(),
)
.unwrap();
assert_eq!(bg_sources.len(), 1);
assert_eq!(bg_sources[0]["sourceId"], "user-source");
second_db.disconnect("user-source").await;
// Read-only sources allow SELECT but refuse writes even with database.query granted.
db.save_sources(vec![ide_db::DataSource {
id: "ro-source".into(),
name: "Read-only SQLite".into(),
driver: ide_db::DbDriver::Sqlite,
file: Some(f.root.join("db.sqlite").into()),
read_only: true,
..Default::default()
}])
.await
.unwrap();
db.execute("ro-source", "SELECT 1", 1, &cancel).await.unwrap();
let ro_select = serde_json::json!({ "sourceId": "ro-source", "sql": "SELECT count(*) FROM users" }).to_string();
let ro_update =
serde_json::json!({ "sourceId": "ro-source", "sql": "UPDATE users SET name = 'blocked'" }).to_string();
assert!(f.run("execute-query", Some(&ro_select)).is_ok());
assert!(f.run("execute-query", Some(&ro_update)).is_err(), "read-only sources must reject writes");
// Revoking `database.query` blocks queries while leaving `database.schema` discovery intact.
f.plugins.set_capability(ID, "database.query", false).unwrap();
let err = f.run("execute-query", Some(&ro_select)).unwrap_err();
assert!(err.message.contains("database.query"));
assert!(f.run("connected-sources", None).is_ok());
// Revoking project trust blocks both.
f.plugins.set_capability(ID, "database.query", true).unwrap();
f.host.set_project_trust(&f.root, false, false).await.unwrap();
assert!(f.run("connected-sources", None).is_err());
assert!(f.run("execute-query", Some(&ro_select)).is_err());
}
+106 -1
Переглянути файл
@@ -394,7 +394,17 @@ fn a_full_graph_keeps_updating_its_files_and_skips_others_without_running_the_pl
let f = Fixture::new();
let source = f.index("source.idx", SOURCE, &[method()], Some(1), "");
for i in 1..MAX_FILES {
f.index(&format!("filler/{i}.idx"), "", &[], None, "");
let p = f.root.join(format!("filler/{i}.idx"));
let txt = format!("def filler:{i}\n");
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(&p, &txt).unwrap();
f.host
.index_navigation(
&f.root,
Snapshot { path: &p, version: None, text: &txt, symbols: &[], scope: "" },
Invocation { workspace_root: Some(f.root.clone()), ..Default::default() },
)
.unwrap();
}
let calls = f.host.info_of("test.indexer").unwrap().stats.calls;
let mapping = f.index("mapping.idx", MAPPING, &[], Some(1), "");
@@ -403,4 +413,99 @@ fn a_full_graph_keeps_updating_its_files_and_skips_others_without_running_the_pl
f.index("source.idx", SOURCE, &[method()], Some(2), "");
assert_eq!(f.host.info_of("test.indexer").unwrap().stats.calls, calls + 1, "covered files still update");
assert!(f.host.navigation_at(&f.root, &source, 2, Pos::new(1, 5), None, |_| None).is_none());
// Batch indexing on the same full graph also skips uncovered files before invoking WASM.
let calls_before_batch = f.host.info_of("test.indexer").unwrap().stats.calls;
std::fs::write(&source, SOURCE).unwrap();
f.host
.index_navigation_batch(
&f.root,
&[
Snapshot { path: &mapping, version: Some(2), text: MAPPING, symbols: &[], scope: "" },
Snapshot { path: &source, version: Some(3), text: SOURCE, symbols: &[], scope: "" },
],
Invocation { workspace_root: Some(f.root.clone()), ..Default::default() },
None,
)
.unwrap();
assert_eq!(
f.host.info_of("test.indexer").unwrap().stats.calls,
calls_before_batch + 1,
"batch only invokes WASM for the already-covered file"
);
}
#[test]
fn empty_edges_do_not_consume_graph_slots_and_batch_isolates_invalid_documents() {
let f = Fixture::new();
let source = f.index("src/source.idx", SOURCE, &[method()], Some(1), "app");
let mapping = f.index("resources/mapping.idx", MAPPING, &[], Some(1), "app");
assert!(f.host.navigation_at(&f.root, &mapping, 1, reference_pos(), None, |_| None).is_some());
// Re-indexing `source` with empty content evicts its previous anchors cleanly.
std::fs::write(&source, "").unwrap();
f.host
.index_navigation(
&f.root,
Snapshot { path: &source, version: Some(2), text: "", symbols: &[], scope: "app" },
Invocation { workspace_root: Some(f.root.clone()), ..Default::default() },
)
.unwrap();
assert!(f.host.navigation_at(&f.root, &mapping, 1, reference_pos(), None, |_| None).is_none());
assert!(f.host.navigation_markers(&f.root, std::slice::from_ref(&mapping), None, |_| None).is_empty());
// Mixed batch containing 200 empty files, one invalid document, and two valid connected files:
// the invalid document is skipped/evicted while valid documents still commit cleanly.
let mut empty_paths = Vec::with_capacity(200);
for i in 0..200 {
let p = f.root.join(format!("empty/E{i}.idx"));
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(&p, "// nothing\n").unwrap();
empty_paths.push(p);
}
let bad = f.root.join("batch/bad.idx");
let connected_a = f.root.join("batch/source.idx");
let connected_b = f.root.join("batch/mapping.idx");
std::fs::create_dir_all(bad.parent().unwrap()).unwrap();
std::fs::write(&bad, "invalid key\n").unwrap();
std::fs::write(&connected_a, SOURCE).unwrap();
std::fs::write(&connected_b, MAPPING).unwrap();
let mut snapshots: Vec<Snapshot<'_>> = empty_paths
.iter()
.map(|p| Snapshot { path: p, version: None, text: "// nothing\n", symbols: &[], scope: "app" })
.collect();
snapshots.push(Snapshot { path: &bad, version: Some(1), text: "invalid key\n", symbols: &[], scope: "app" });
snapshots.push(Snapshot { path: &connected_a, version: Some(1), text: SOURCE, symbols: &[], scope: "app" });
snapshots.push(Snapshot { path: &connected_b, version: Some(1), text: MAPPING, symbols: &[], scope: "app" });
let summary = f
.host
.index_navigation_batch(
&f.root,
&snapshots,
Invocation { workspace_root: Some(f.root.clone()), ..Default::default() },
None,
)
.unwrap();
assert_eq!(summary.skipped_invalid, 1);
let res = f.host.navigation_at(&f.root, &connected_b, 1, reference_pos(), None, |_| None).unwrap();
assert_eq!(res.targets[0].path.0, connected_a);
let markers = f.host.navigation_markers(&f.root, &[connected_a.clone(), connected_b.clone()], None, |_| None);
assert_eq!(markers.len(), 2);
// Pre-cancelled batch aborts without publishing or modifying entries.
let cancelled_file = f.root.join("batch/cancelled.idx");
std::fs::write(&cancelled_file, SOURCE).unwrap();
let token = ide_core::CancellationToken::new();
token.cancel();
let cancelled_res = f.host.index_navigation_batch(
&f.root,
&[Snapshot { path: &cancelled_file, version: Some(1), text: SOURCE, symbols: &[], scope: "app" }],
Invocation { workspace_root: Some(f.root.clone()), ..Default::default() },
Some(&token),
);
assert!(cancelled_res.is_err());
assert!(f.host.navigation_markers(&f.root, &[cancelled_file], None, |_| None).is_empty());
}
+50
Переглянути файл
@@ -1565,3 +1565,53 @@ async fn remote_browser_export_checkout_options_and_restricted_mode() {
.unwrap_err();
assert_eq!(del_err.kind, ide_core::error::ErrorKind::Unavailable, "{del_err:?}");
}
/// Update Project in two working copies (issue #7433): the console gets svn's own output for
/// each, the files it changed and the revision reached, not only a summary line.
#[tokio::test]
async fn update_output_of_two_working_copies() {
let Some(fx) = fixture() else { return };
let seed = fx.checkout("seed");
for name in ["a.txt", "gone.txt"] {
std::fs::write(seed.join(name), "one\n").unwrap();
}
fx.svn(&seed, &["add", "-q", "a.txt", "gone.txt"]);
fx.svn(&seed, &["commit", "-q", "-m", "seed"]);
let project_root = fx.base.join("project");
std::fs::create_dir(&project_root).unwrap();
let trunk = format!("{}/trunk", fx.url);
for name in ["boot", "antd"] {
fx.svn(&fx.base, &["checkout", "-q", &trunk, project_root.join(name).to_str().unwrap()]);
}
std::fs::write(seed.join("a.txt"), "two\n").unwrap();
std::fs::write(seed.join("new.txt"), "new\n").unwrap();
fx.svn(&seed, &["add", "-q", "new.txt"]);
fx.svn(&seed, &["rm", "-q", "gone.txt"]);
fx.svn(&seed, &["commit", "-q", "-m", "two"]);
let host = Host::new(common::host_config(&fx.base)).with_subversion(false);
host.trust.decide(&project_root, true, false).unwrap();
let project = host.open_project("main", &project_root).unwrap();
until("both working copies", || project.backends().len() == 2).await;
for name in ["boot", "antd"] {
let lines = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
let sink = lines.clone();
let channel = ide_host::ops::Channel::new(move |line: String| sink.lock().unwrap().push(line));
let op = vcs::RemoteOp::UpdateProjectBranch { rebase: false };
let repo = Some(project_root.join(name));
vcs::vcs_remote(&host, "main", repo, ide_core::RequestId::next(), op, channel, None).await.unwrap();
let lines = lines.lock().unwrap().clone();
let changed: Vec<&str> = lines
.iter()
.filter_map(|l| {
l.split_once(char::is_whitespace).filter(|(code, _)| code.len() == 1).map(|(_, p)| p.trim())
})
.map(|p| p.rsplit(['/', '\\']).next().unwrap())
.collect();
assert!(lines.iter().any(|l| l.starts_with("Updating ")), "{name}: {lines:?}");
for file in ["a.txt", "new.txt", "gone.txt"] {
assert!(changed.contains(&file), "{name}: {file} in {lines:?}");
}
assert!(lines.last().is_some_and(|l| l.starts_with("Updated to revision ")), "{name}: {lines:?}");
}
}
+38
Переглянути файл
@@ -511,3 +511,41 @@ async fn attach_and_detach_preserve_the_primary_project_session() {
assert!(!reopened.is_trusted());
host.close_project("main");
}
/// Issue #7433: a member whose folder is gone (its checkout moved up a level) can be removed,
/// and the folder it moved to can be attached, under the same name, before or after that.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_member_whose_folder_is_gone_can_be_removed_and_its_new_folder_attached() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let primary = base.join("primary");
let moved_to = base.join("sapp");
let gone = moved_to.join("sapp");
std::fs::create_dir_all(&primary).unwrap();
std::fs::create_dir_all(&gone).unwrap();
std::fs::write(gone.join("pom.xml"), "<project/>").unwrap();
let host = Host::new(common::host_config(&base));
for root in [&primary, &gone, &moved_to] {
host.trust.decide(root, true, false).unwrap();
}
let project = host.open_project("main", &primary).unwrap();
ops::project::attach_workspace(&host, "main", &gone).unwrap();
// The checkout moves up a level: `sapp/sapp` is gone, its files are in `sapp`.
std::fs::rename(gone.join("pom.xml"), moved_to.join("pom.xml")).unwrap();
std::fs::remove_dir(&gone).unwrap();
// The folder it moved to, named the same, is attached while the old entry is still there.
ops::project::attach_workspace(&host, "main", &moved_to).unwrap();
let members = Workspace::load(&primary).unwrap().unwrap().projects;
assert_eq!(members, [primary.clone(), gone.clone(), moved_to.clone()]);
assert!(ops::project::info(&project).workspace.is_some());
// Remove from Workspace of the gone member.
ops::project::save_workspace(&host, "main", "primary", vec![primary.clone(), moved_to.clone()]).unwrap();
assert_eq!(Workspace::load(&primary).unwrap().unwrap().projects, [primary.clone(), moved_to.clone()]);
// Removed first, then attached again.
ops::project::save_workspace(&host, "main", "primary", vec![primary.clone()]).unwrap();
ops::project::attach_workspace(&host, "main", &moved_to).unwrap();
assert_eq!(Workspace::load(&primary).unwrap().unwrap().projects, [primary, moved_to]);
}
+1
Переглянути файл
@@ -61,6 +61,7 @@ tree-sitter-dart = "0.2.0"
tree-sitter-graphql = "0.3.0"
tree-sitter-prisma-io = "1.6.0"
tree-sitter-gdscript = "6.1.0"
tree-sitter-odin = "1.3.0"
[build-dependencies]
blake3.workspace = true
+24
Переглянути файл
@@ -0,0 +1,24 @@
; The name of a declaration is its first identifier; `@(...)` attributes may come before it.
(procedure_declaration . (identifier) @name (procedure (parameters) @detail)) @def.function
(procedure_declaration . (attributes) . (identifier) @name (procedure (parameters) @detail)) @def.function
(overloaded_procedure_declaration . (identifier) @name) @def.function
(overloaded_procedure_declaration . (attributes) . (identifier) @name) @def.function
(struct_declaration . (identifier) @name) @def.struct
(struct_declaration . (attributes) . (identifier) @name) @def.struct
(union_declaration . (identifier) @name) @def.struct
(union_declaration . (attributes) . (identifier) @name) @def.struct
(bit_field_declaration . (identifier) @name) @def.struct
(bit_field_declaration . (attributes) . (identifier) @name) @def.struct
(enum_declaration . (identifier) @name) @def.enum
(enum_declaration . (attributes) . (identifier) @name) @def.enum
(enum_declaration "{" . (identifier) @name @def.enum_member)
(enum_declaration "," . (identifier) @name @def.enum_member)
(field . (identifier) @name @def.field)
; `x, y: f32` declares two fields.
(field "," . (identifier) @name @def.field)
(source_file (const_declaration . (identifier) @name) @def.constant)
(source_file (const_declaration . (attributes) . (identifier) @name) @def.constant)
(source_file (const_type_declaration . (identifier) @name) @def.constant)
(source_file (variable_declaration . (identifier) @name) @def.variable)
(source_file (var_declaration . (identifier) @name) @def.variable)
(source_file (var_declaration . (attributes) . (identifier) @name) @def.variable)
+2
Переглянути файл
@@ -73,6 +73,7 @@ const BUILTIN: &[(&str, &str)] = &[
("objective-cpp", include_str!("../../../languages/objective-cpp.toml")),
("ocaml", include_str!("../../../languages/ocaml.toml")),
("ocaml-interface", include_str!("../../../languages/ocaml-interface.toml")),
("odin", include_str!("../../../languages/odin.toml")),
("perl", include_str!("../../../languages/perl.toml")),
("php", include_str!("../../../languages/php.toml")),
("plaintext", include_str!("../../../languages/plaintext.toml")),
@@ -1618,6 +1619,7 @@ mod tests {
("init.lua", "lua"),
("main.dart", "dart"),
("build.zig", "zig"),
("main.odin", "odin"),
("mix.exs", "elixir"),
("Main.hs", "haskell"),
("a.ml", "ocaml"),
+10
Переглянути файл
@@ -279,6 +279,16 @@ pub(crate) static SPECS: &[Spec] = &[
imports: NONE,
constructors: NONE,
},
Spec {
name: "odin",
language: tree_sitter_odin::LANGUAGE,
outline: outline!("odin"),
highlights: Some(Highlights { query: tree_sitter_odin::HIGHLIGHTS_QUERY, first_wins: false }),
fold_nodes: NONE,
fold_bodies: NONE,
imports: &["import_declaration"],
constructors: NONE,
},
Spec {
name: "elixir",
language: tree_sitter_elixir::LANGUAGE,
+12
Переглянути файл
@@ -503,6 +503,18 @@ mod tests {
("u32", K::Builtin),
],
),
(
"odin",
"package main\nimport \"core:fmt\"\n// hi\nmain :: proc() {\n x: u32 = 42\n fmt.println(x)\n}\n",
&[
("package", K::Keyword),
("\"core:fmt\"", K::String),
("// hi", K::Comment),
("proc", K::Keyword),
("42", K::Number),
("u32", K::Builtin),
],
),
(
"nix",
"{ pkgs ? import <nixpkgs> {} }:\n# hi\nlet x = 1; in pkgs.mkShell { name = \"dev\"; }\n",
+29
Переглянути файл
@@ -932,6 +932,35 @@ fn outline_more_languages() {
Function basic
",
);
check_outline(
"odin",
concat!(
"package demo\n",
"import \"core:fmt\"\n",
"Vec :: struct {\n x, y: f32,\n}\n",
"Shape :: enum {\n Circle,\n Square = 2,\n}\n",
"Value :: union {\n int,\n f32,\n}\n",
"MAX :: 10\n",
"counter: int\n",
"@(private)\n",
"length :: proc(v: Vec) -> f32 {\n helper :: proc() {}\n return v.x\n}\n",
"add :: proc{add_int, add_f32}\n",
),
"
Struct Vec
Field x
Field y
Enum Shape
EnumMember Circle
EnumMember Square
Struct Value
Constant MAX
Variable counter
Function length
Function helper
Function add
",
);
check_outline(
"elixir",
"defmodule Foo.Bar do\n def go(a), do: a\n defp priv(b) do\n b\n end\n defmacro m(x), do: x\nend\n",
+317 -39
Переглянути файл
@@ -1,16 +1,147 @@
//! Extract Interface through jdtls' own requests: `java/checkExtractInterfaceStatus` lists the
//! members of the file's class an interface can declare and the packages it can go to,
//! `java/getRefactorEdit` (`extractInterface`) creates the interface, makes the class implement
//! it and uses it where possible. The UI picks the name, package and members and applies the edit.
//! Extract Interface through java-analyzer's dialog-driven requests when the server advertises
//! them in `capabilities.experimental`, falling back to jdtls' `java/checkExtractInterfaceStatus`
//! and `java/getRefactorEdit` (`extractInterface`). The UI picks the name, package and members
//! and applies the edit.
use super::COMMAND_TIMEOUT;
use super::signature::{RefactorEdit, changed};
use crate::caps::ServerCaps;
use crate::text::DocText;
use crate::types::{ExtractInterfaceInfo, InterfaceMember, ProblemSeverity, RefactoringProblem, ServerRefactored};
use crate::{LspManager, convert};
use crate::{DocSnap, LspManager, Target, convert};
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Pos};
use serde::Deserialize;
use serde_json::{Value, json};
use std::path::Path;
const FEATURE: &str = "Extract Interface";
/// java-analyzer's dialog-driven requests, advertised in `capabilities.experimental`.
const JAVA_INFO: &str = "java-analyzer/extractInterfaceInfo";
const JAVA_EDIT: &str = "java-analyzer/extractInterface";
/// A server that advertises the extract-interface pair answers it without JDT internals.
fn java_analyzer(caps: &ServerCaps) -> bool {
caps.raw["experimental"][JAVA_INFO] == true && caps.raw["experimental"][JAVA_EDIT] == true
}
enum ExtractTarget {
JavaAnalyzer(Target),
Jdtls(Target),
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct JavaInfo {
/// Suggested interface name from java-analyzer (e.g. `Main` for `MainImpl`). Not used as
/// `ExtractInterfaceInfo::class_name` because the dialog displays `className` as the source
/// class and rejects entering an interface name equal to it.
#[allow(dead_code)]
#[serde(default)]
interface_name: String,
#[serde(default)]
members: Vec<InterfaceMember>,
#[serde(default)]
packages: Vec<String>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct JavaResult {
edit: Option<lsp_types::WorkspaceEdit>,
#[serde(default)]
problems: Vec<JavaProblem>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct JavaProblem {
severity: JavaSeverity,
message: String,
}
#[derive(Deserialize, Debug, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum JavaSeverity {
Error,
Warning,
}
/// jdtls packages are JSON-encoded destination objects; keep the same shape for the dialog.
fn java_packages(packages: Vec<String>) -> Vec<String> {
packages
.into_iter()
.enumerate()
.map(|(i, name)| {
json!({
"displayName": name,
"isParentOfSelectedFile": i == 0,
})
.to_string()
})
.collect()
}
/// The dialog sends back the same JSON string it was given; recover the package name.
fn java_package(pkg: &Value) -> IdeResult<String> {
if let Some(text) = pkg.as_str() {
let value: Value = serde_json::from_str(text).map_err(|e| IdeError::invalid(e.to_string()))?;
return value
.get("displayName")
.and_then(Value::as_str)
.map(str::to_owned)
.ok_or_else(|| IdeError::invalid("No package selected"));
}
pkg.get("displayName")
.and_then(Value::as_str)
.map(str::to_owned)
.ok_or_else(|| IdeError::invalid("No package selected"))
}
/// Source class/enum/record name at `pos` (falling back to the file stem), since
/// `java-analyzer/extractInterfaceInfo` returns the suggested interface name rather than the
/// class name that the dialog shows and checks for collisions against.
fn class_name_at(text: &DocText, path: &Path, pos: Pos) -> String {
if let Some(range) = text.word_range_at(pos) {
let start = text.byte_offset(range.start);
let end = text.byte_offset(range.end);
let ident = &text.as_str()[start..end];
let before = text.as_str()[..start].trim_end();
let preceded_by_type_kw = ["class", "enum", "record"].iter().any(|kw| {
before.strip_suffix(kw).is_some_and(|head| {
head.chars().next_back().is_none_or(|c| !(c.is_alphanumeric() || c == '_' || c == '$'))
})
});
if preceded_by_type_kw {
return ident.to_owned();
}
}
path.file_stem().and_then(|s| s.to_str()).unwrap_or_default().to_owned()
}
fn java_info_of(info: Option<JavaInfo>, class_name: String) -> IdeResult<ExtractInterfaceInfo> {
let info = info.ok_or_else(|| {
IdeError::invalid("Place the caret on the name of a top-level class, enum or record with public methods")
})?;
Ok(ExtractInterfaceInfo { class_name, members: info.members, packages: java_packages(info.packages) })
}
fn java_result_of(
answer: JavaResult,
convert_edit: impl FnOnce(lsp_types::WorkspaceEdit) -> ide_core::WorkspaceEdit,
) -> ServerRefactored {
let problems = answer
.problems
.into_iter()
.map(|p| RefactoringProblem {
severity: match p.severity {
JavaSeverity::Error => ProblemSeverity::Error,
JavaSeverity::Warning => ProblemSeverity::Warning,
},
message: p.message,
})
.collect();
// java-analyzer is stateless: no confirmation token, the client applies what it got.
ServerRefactored { problems, edit: answer.edit.map(convert_edit), confirmation: None }
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -42,6 +173,18 @@ fn info_of(status: Option<Status>) -> IdeResult<ExtractInterfaceInfo> {
}
impl LspManager {
async fn extract_interface_target(&self, doc: DocId) -> IdeResult<(DocSnap, ExtractTarget)> {
let (snap, targets) = self.doc_targets(doc, FEATURE, |_| true).await?;
if let Some(t) = targets.iter().find(|t| java_analyzer(&t.caps())) {
return Ok((snap, ExtractTarget::JavaAnalyzer(t.clone())));
}
let t = targets
.into_iter()
.find(|t| t.server.name == super::SERVER)
.ok_or_else(|| IdeError::unavailable(format!("{FEATURE} needs the Java language server (jdtls)")))?;
Ok((snap, ExtractTarget::Jdtls(t)))
}
/// The class of the file at `doc`, its members and the packages for the interface.
pub async fn extract_interface_info(
&self,
@@ -49,14 +192,29 @@ impl LspManager {
pos: Pos,
cancel: CancellationToken,
) -> IdeResult<ExtractInterfaceInfo> {
let (snap, t) = self.jdtls_target(doc, FEATURE).await?;
let params = Self::signature_context(&snap, &t, pos);
let status: Option<Status> =
self.call(&t, "java/checkExtractInterfaceStatus", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
let (snap, target) = self.extract_interface_target(doc).await?;
match target {
ExtractTarget::JavaAnalyzer(t) => {
let params = json!({
"textDocument": { "uri": snap.uri },
"position": snap.position(&t, pos),
});
let info: Option<JavaInfo> = self.call(&t, JAVA_INFO, params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
java_info_of(info, class_name_at(&snap.text, &snap.path, pos))
}
ExtractTarget::Jdtls(t) => {
let params = Self::signature_context(&snap, &t, pos);
let status: Option<Status> =
self.call(&t, "java/checkExtractInterfaceStatus", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
info_of(status)
}
}
info_of(status)
}
/// Checks extracting `members` into the interface `name` in `package` (a package from
@@ -72,40 +230,63 @@ impl LspManager {
confirmation: Option<String>,
cancel: CancellationToken,
) -> IdeResult<ServerRefactored> {
let (snap, t) = self.jdtls_target(doc, FEATURE).await?;
let mut params = json!({
"command": "extractInterface",
"context": Self::signature_context(&snap, &t, pos),
"options": { "tabSize": 4, "insertSpaces": true },
"commandArguments": [members, name, package],
});
if let Some(token) = confirmation {
params["confirmationToken"] = json!(token);
let (snap, target) = self.extract_interface_target(doc).await?;
match target {
ExtractTarget::JavaAnalyzer(t) => {
// The server defaults to the class's own package; sending it explicitly is optional.
let mut params = json!({
"textDocument": { "uri": snap.uri },
"position": snap.position(&t, pos),
"name": name,
"members": members,
});
if let Ok(package) = java_package(&package) {
params["package"] = json!(package);
}
let answer: JavaResult = self.call(&t, JAVA_EDIT, params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let conv = self.conv(t.enc());
Ok(java_result_of(answer, |e| convert::workspace_edit(&conv, e)))
}
ExtractTarget::Jdtls(t) => {
let mut params = json!({
"command": "extractInterface",
"context": Self::signature_context(&snap, &t, pos),
"options": { "tabSize": 4, "insertSpaces": true },
"commandArguments": [members, name, package],
});
if let Some(token) = confirmation {
params["confirmationToken"] = json!(token);
}
let answer: Option<RefactorEdit> =
self.call(&t, "java/getRefactorEdit", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
// jdtls answers nothing when its checks fail, and reports why in a message of its own.
let Some(answer) = answer else {
return Ok(ServerRefactored {
problems: vec![RefactoringProblem {
severity: ProblemSeverity::Fatal,
message: "The interface could not be extracted".to_owned(),
}],
edit: None,
confirmation: None,
});
};
let conv = self.conv(t.enc());
Ok(changed(answer, |e| convert::workspace_edit(&conv, e)))
}
}
let answer: Option<RefactorEdit> =
self.call(&t, "java/getRefactorEdit", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
// jdtls answers nothing when its checks fail, and reports why in a message of its own.
let Some(answer) = answer else {
return Ok(ServerRefactored {
problems: vec![RefactoringProblem {
severity: ProblemSeverity::Fatal,
message: "The interface could not be extracted".to_owned(),
}],
edit: None,
confirmation: None,
});
};
let conv = self.conv(t.enc());
Ok(changed(answer, |e| convert::workspace_edit(&conv, e)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ErrorKind;
#[test]
fn reads_the_members_and_packages() {
@@ -125,4 +306,101 @@ mod tests {
assert_eq!(serde_json::from_str::<Value>(&info.packages[0]).unwrap()["displayName"], "a");
assert!(info_of(None).is_err());
}
#[test]
fn finds_the_server_by_its_capability() {
let both = ServerCaps::parse(json!({
"experimental": { "java-analyzer/extractInterfaceInfo": true, "java-analyzer/extractInterface": true },
}));
let info_only = ServerCaps::parse(json!({
"experimental": { "java-analyzer/extractInterfaceInfo": true },
}));
let edit_only = ServerCaps::parse(json!({
"experimental": { "java-analyzer/extractInterface": true },
}));
let disabled = ServerCaps::parse(json!({
"experimental": { "java-analyzer/extractInterfaceInfo": false, "java-analyzer/extractInterface": true },
}));
assert!(java_analyzer(&both));
assert!(!java_analyzer(&info_only));
assert!(!java_analyzer(&edit_only));
assert!(!java_analyzer(&disabled));
assert!(!java_analyzer(&ServerCaps::parse(json!({}))));
}
#[test]
fn java_analysis_packages_round_trip_through_the_dialog() {
let packages = java_packages(vec!["app".to_owned(), "".to_owned()]);
assert_eq!(serde_json::from_str::<Value>(&packages[0]).unwrap()["displayName"], "app");
assert_eq!(serde_json::from_str::<Value>(&packages[0]).unwrap()["isParentOfSelectedFile"], true);
assert_eq!(serde_json::from_str::<Value>(&packages[1]).unwrap()["isParentOfSelectedFile"], false);
assert_eq!(java_package(&json!(packages[0])).unwrap(), "app");
assert_eq!(java_package(&json!(packages[1])).unwrap(), "");
assert_eq!(java_package(&json!({ "displayName": "com.example" })).unwrap(), "com.example");
assert!(java_package(&json!({})).is_err());
}
#[test]
fn class_name_at_reads_type_declaration_or_file_stem() {
let text = DocText::new(
"package app;\n/* 😀 */ public class MainImpl {\n public void hello() {}\n}\nclass Helper {}\npublic record Point(int x) {}\nenum Color { RED }\n",
);
let path = Path::new("/w/src/app/MainImpl.java");
// Line 1: `/* 😀 */ public class MainImpl {` — 😀 is 2 UTF-16 units, so MainImpl starts at col 22.
assert_eq!(class_name_at(&text, path, Pos::new(1, 22)), "MainImpl");
assert_eq!(class_name_at(&text, path, Pos::new(1, 26)), "MainImpl");
assert_eq!(class_name_at(&text, path, Pos::new(1, 30)), "MainImpl");
// Caret on a method name falls back to the file stem.
assert_eq!(class_name_at(&text, path, Pos::new(2, 16)), "MainImpl");
// Non-public top-level class in the same file uses its own name.
assert_eq!(class_name_at(&text, path, Pos::new(4, 7)), "Helper");
assert_eq!(class_name_at(&text, path, Pos::new(5, 14)), "Point");
assert_eq!(class_name_at(&text, path, Pos::new(6, 5)), "Color");
// A keyword suffix like `subclass` is not treated as `class`.
let fake = DocText::new("int subclass Foo;");
assert_eq!(class_name_at(&fake, path, Pos::new(0, 14)), "MainImpl");
}
#[test]
fn java_analysis_info_reads_handles_and_rejects_null() {
let info: JavaInfo = serde_json::from_value(json!({
"interfaceName": "Main",
"members": [{
"name": "hello",
"typeName": "void",
"parameters": [],
"handleIdentifier": "hello()",
}],
"packages": ["app"],
}))
.unwrap();
let converted = java_info_of(Some(info), "MainImpl".to_owned()).unwrap();
// `class_name` stays the source class name so the dialog lets the user name the interface `Main`.
assert_eq!(converted.class_name, "MainImpl");
assert_eq!(converted.members[0].handle_identifier, "hello()");
assert_eq!(serde_json::from_str::<Value>(&converted.packages[0]).unwrap()["displayName"], "app");
let err = java_info_of(None, "MainImpl".to_owned()).unwrap_err();
assert_eq!(err.kind, ErrorKind::InvalidInput);
}
#[test]
fn maps_java_analysis_problems_to_the_refactoring_ui() {
let result: JavaResult = serde_json::from_value(json!({
"edit": null,
"problems": [
{ "severity": "error", "message": "Interface already exists" },
{ "severity": "warning", "message": "Package-private type referenced" },
],
}))
.unwrap();
let mapped = java_result_of(result, |_| ide_core::WorkspaceEdit::default());
assert!(mapped.edit.is_none());
assert!(mapped.confirmation.is_none());
assert_eq!(mapped.problems.len(), 2);
assert_eq!(mapped.problems[0].severity, ProblemSeverity::Error);
assert_eq!(mapped.problems[0].message, "Interface already exists");
assert_eq!(mapped.problems[1].severity, ProblemSeverity::Warning);
assert_eq!(mapped.problems[1].message, "Package-private type referenced");
}
}
+168
Переглянути файл
@@ -10064,3 +10064,171 @@ async fn spring_bean_markers_follow_the_servers_features() {
assert_eq!(h.mgr.spring_bean_markers(doc, Default::default()).await.unwrap(), None);
assert!(beans.requested("java-analyzer/springBeanMarkers").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn extract_interface_uses_java_analyzer_when_advertised() {
let mut ja_caps = incremental_caps();
ja_caps["positionEncoding"] = json!("utf-8");
ja_caps["experimental"] = json!({
"java-analyzer/extractInterfaceInfo": true,
"java-analyzer/extractInterface": true,
});
let h = harness_configured("java", "java", &[("java-analyzer", ja_caps), ("jdtls", incremental_caps())], |_| {});
// "/* 😀 */ " is 9 UTF-16 units (😀 = 2) and 11 UTF-8 bytes (😀 = 4).
let (doc, path) =
h.open("MainImpl.java", "package app;\n/* 😀 */ public class MainImpl {\n public void hello() {}\n}\n");
for name in ["java-analyzer", "jdtls"] {
h.wait_status(name, ServerStatus::Ready).await;
}
let (ja, jdtls) = (h.launcher.state("java-analyzer"), h.launcher.state("jdtls"));
eventually(|| !ja.notified("textDocument/didOpen").is_empty()).await;
// Caret on `MainImpl`: UTF-16 col 22 -> UTF-8 byte col 24.
let caret = Pos::new(1, 22);
ja.respond(
"java-analyzer/extractInterfaceInfo",
json!({
"interfaceName": "Main",
"members": [{
"name": "hello",
"typeName": "void",
"parameters": [],
"handleIdentifier": "hello()",
}],
"packages": ["app"],
}),
);
let info = h.mgr.extract_interface_info(doc, caret, Default::default()).await.unwrap();
assert_eq!(info.class_name, "MainImpl");
assert_eq!(info.members.len(), 1);
assert_eq!(info.members[0].handle_identifier, "hello()");
assert_eq!(
ja.requested("java-analyzer/extractInterfaceInfo")[0],
json!({ "textDocument": { "uri": uri_of(&path) }, "position": { "line": 1, "character": 24 } })
);
assert!(jdtls.requested("java/checkExtractInterfaceStatus").is_empty());
// Null info (e.g. caret outside a class name) reports InvalidInput rather than a protocol error.
ja.respond("java-analyzer/extractInterfaceInfo", Value::Null);
let err = h.mgr.extract_interface_info(doc, Pos::new(0, 0), Default::default()).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
// Edit request sends handles + recovered package and converts CreateFile + TextDocumentEdit.
let iface_path = path.with_file_name("Main.java");
let iface_uri = uri_of(&iface_path);
ja.respond(
"java-analyzer/extractInterface",
json!({
"edit": {
"documentChanges": [
{ "kind": "create", "uri": iface_uri },
{
"textDocument": { "uri": iface_uri, "version": null },
"edits": [{
"range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } },
"newText": "package app;\n\npublic interface Main {\n void hello();\n}\n",
}],
},
{
"textDocument": { "uri": uri_of(&path), "version": null },
"edits": [{
"range": { "start": { "line": 1, "character": 32 }, "end": { "line": 1, "character": 32 } },
"newText": " implements Main",
}],
},
],
},
"problems": [],
}),
);
let pkg: Value = serde_json::from_str(&info.packages[0]).unwrap();
let res = h
.mgr
.extract_interface(doc, caret, vec!["hello()".into()], "Main".into(), pkg, None, Default::default())
.await
.unwrap();
assert!(res.problems.is_empty());
assert!(res.confirmation.is_none());
let edit = res.edit.expect("expected workspace edit");
assert!(matches!(&edit.files[0], FileEdit::Create { path: p, .. } if p.as_ref() == iface_path.as_path()));
// UTF-8 byte col 32 on line 1 (`/* 😀 */ public class MainImpl|`) converts back to UTF-16 col 30.
assert!(matches!(
&edit.files[2],
FileEdit::Edit { edits, .. } if edits[0].range == rng(1, 30, 1, 30) && edits[0].new_text == " implements Main"
));
assert_eq!(
ja.requested("java-analyzer/extractInterface")[0],
json!({
"textDocument": { "uri": uri_of(&path) },
"position": { "line": 1, "character": 24 },
"name": "Main",
"package": "app",
"members": ["hello()"],
})
);
assert!(jdtls.requested("java/getRefactorEdit").is_empty());
// Pre-cancelled token returns Cancelled without falling back to jdtls.
let cancel = CancellationToken::new();
cancel.cancel();
let err = h.mgr.extract_interface_info(doc, caret, cancel).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
assert!(jdtls.requested("java/checkExtractInterfaceStatus").is_empty());
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn extract_interface_falls_back_to_jdtls_without_capability() {
// Older java-analyzer without the experimental capability: route to jdtls instead.
let h = harness_configured(
"java",
"java",
&[("java-analyzer", incremental_caps()), ("jdtls", incremental_caps())],
|_| {},
);
let (doc, path) = h.open("Shape.java", "package a;\npublic class Shape { public double area() { return 0; } }\n");
for name in ["java-analyzer", "jdtls"] {
h.wait_status(name, ServerStatus::Ready).await;
}
let (ja, jdtls) = (h.launcher.state("java-analyzer"), h.launcher.state("jdtls"));
eventually(|| !jdtls.notified("textDocument/didOpen").is_empty()).await;
jdtls.respond(
"java/checkExtractInterfaceStatus",
json!({
"subTypeName": "Shape",
"members": [{ "name": "area", "typeName": "double", "parameters": [], "handleIdentifier": "h1" }],
"destinationResponse": { "destinations": [{ "displayName": "a", "isParentOfSelectedFile": true }] },
}),
);
let info = h.mgr.extract_interface_info(doc, Pos::new(1, 13), Default::default()).await.unwrap();
assert_eq!(info.class_name, "Shape");
assert_eq!(jdtls.requested("java/checkExtractInterfaceStatus").len(), 1);
assert!(ja.requested("java-analyzer/extractInterfaceInfo").is_empty());
jdtls.respond(
"java/getRefactorEdit",
json!({
"edit": { "changes": { uri_of(&path): [] } },
}),
);
let pkg: Value = serde_json::from_str(&info.packages[0]).unwrap();
let res = h
.mgr
.extract_interface(doc, Pos::new(1, 13), vec!["h1".into()], "HasArea".into(), pkg, None, Default::default())
.await
.unwrap();
assert!(res.edit.is_some());
assert_eq!(jdtls.requested("java/getRefactorEdit").len(), 1);
assert!(ja.requested("java-analyzer/extractInterface").is_empty());
h.mgr.shutdown_all().await;
// Without jdtls and without the capability, reports Unavailable.
let h = harness_configured("java", "java", &[("java-analyzer", incremental_caps())], |_| {});
let (doc, _) = h.open("Shape.java", "package a;\npublic class Shape {}\n");
h.wait_status("java-analyzer", ServerStatus::Ready).await;
let err = h.mgr.extract_interface_info(doc, Pos::new(1, 13), Default::default()).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
h.mgr.shutdown_all().await;
}
+45
Переглянути файл
@@ -100,6 +100,51 @@ pub trait HostApi: Send + Sync {
) -> Result<crate::PluginDatabaseTableSchema, HostError> {
Err(HostError::Invalid("Database schema access is unavailable on this host".into()))
}
/// Lists already-connected project sources; database.schema was checked (API 1.21).
fn database_connected_sources(
&self,
_root: &Path,
_client: Option<&str>,
) -> Result<Vec<crate::PluginConnectedDataSource>, HostError> {
Err(HostError::Invalid("Database schema access is unavailable on this host".into()))
}
/// Lists schemas of an already-connected project source; database.schema was checked (API 1.21).
fn database_list_schemas(
&self,
_root: &Path,
_client: Option<&str>,
_source_id: &str,
_cancel: &CancellationToken,
_timeout: Duration,
) -> Result<Vec<String>, HostError> {
Err(HostError::Invalid("Database schema access is unavailable on this host".into()))
}
/// Lists tables and views in a schema of a connected project source; database.schema was checked (API 1.21).
fn database_list_tables(
&self,
_root: &Path,
_client: Option<&str>,
_source_id: &str,
_schema: &str,
_cancel: &CancellationToken,
_timeout: Duration,
) -> Result<Vec<crate::PluginDatabaseTableSummary>, HostError> {
Err(HostError::Invalid("Database schema access is unavailable on this host".into()))
}
/// Executes SQL against an already-connected project source; database.query was checked (API 1.21).
#[allow(clippy::too_many_arguments)]
fn database_execute_query(
&self,
_root: &Path,
_client: Option<&str>,
_source_id: &str,
_sql: &str,
_max_rows: Option<u32>,
_cancel: &CancellationToken,
_timeout: Duration,
) -> Result<crate::PluginDatabaseQueryResult, HostError> {
Err(HostError::Invalid("Database query execution is unavailable on this host".into()))
}
/// Creates/replaces this plugin's non-secret project connection settings.
fn database_upsert(&self, root: &Path, source: crate::PluginDataSource) -> Result<(), HostError>;
/// Removes only an owned data source and its credentials.
+34
Переглянути файл
@@ -1307,3 +1307,37 @@ pub struct PluginDatabaseTableSchema {
pub indexes: Vec<PluginDatabaseIndex>,
pub foreign_keys: Vec<PluginDatabaseForeignKey>,
}
/// Non-secret identity of an already-connected project data source (API 1.21).
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginConnectedDataSource {
pub source_id: String,
pub name: String,
pub driver: String,
pub database: Option<String>,
}
/// Summary of a table or view in a connected schema (API 1.21).
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginDatabaseTableSummary {
pub name: String,
pub kind: String,
pub comment: Option<String>,
}
/// Column metadata of a query result (API 1.21).
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginDatabaseQueryColumn {
pub name: String,
pub type_name: String,
}
/// Bounded result of executing a SQL statement on a connected source (API 1.21).
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginDatabaseQueryResult {
pub columns: Vec<PluginDatabaseQueryColumn>,
pub rows: Vec<Vec<Option<String>>>,
pub affected: Option<u64>,
pub has_more: bool,
pub elapsed_ms: u64,
}
+108
Переглянути файл
@@ -3491,6 +3491,114 @@ impl bindings::openidea::plugin::database::Host for StoreData {
})
.map_err(to_wit))
}
fn connected_sources(
&mut self,
project: Resource<ProjectRes>,
) -> Fallible<Vec<bindings::openidea::plugin::database::ConnectedSource>> {
if let Err(e) = self.require(Capability::DatabaseSchema) {
return Ok(Err(e));
}
let root = self.table.get(&project)?.root.clone();
let result = self.host.database_connected_sources(&root, self.client());
if result.is_err() {
self.grant_io_error_grace();
}
use bindings::openidea::plugin::database as db;
Ok(result
.map(|sources| {
sources
.into_iter()
.map(|s| db::ConnectedSource {
source_id: s.source_id,
name: s.name,
driver: s.driver,
database: s.database,
})
.collect()
})
.map_err(to_wit))
}
fn list_schemas(&mut self, project: Resource<ProjectRes>, source_id: String) -> Fallible<Vec<String>> {
if let Err(e) = self.require(Capability::DatabaseSchema) {
return Ok(Err(e));
}
let root = self.table.get(&project)?.root.clone();
let result =
self.host.database_list_schemas(&root, self.client(), &source_id, &self.cancel.token(), self.io_timeout());
if result.is_err() {
self.grant_io_error_grace();
}
Ok(result.map_err(to_wit))
}
fn list_tables(
&mut self,
project: Resource<ProjectRes>,
source_id: String,
schema: String,
) -> Fallible<Vec<bindings::openidea::plugin::database::TableSummary>> {
if let Err(e) = self.require(Capability::DatabaseSchema) {
return Ok(Err(e));
}
let root = self.table.get(&project)?.root.clone();
let result = self.host.database_list_tables(
&root,
self.client(),
&source_id,
&schema,
&self.cancel.token(),
self.io_timeout(),
);
if result.is_err() {
self.grant_io_error_grace();
}
use bindings::openidea::plugin::database as db;
Ok(result
.map(|tables| {
tables
.into_iter()
.map(|t| db::TableSummary { name: t.name, kind: t.kind, comment: t.comment })
.collect()
})
.map_err(to_wit))
}
fn execute_query(
&mut self,
project: Resource<ProjectRes>,
source_id: String,
sql: String,
max_rows: Option<u32>,
) -> Fallible<bindings::openidea::plugin::database::QueryResult> {
if let Err(e) = self.require(Capability::DatabaseQuery) {
return Ok(Err(e));
}
let root = self.table.get(&project)?.root.clone();
let result = self.host.database_execute_query(
&root,
self.client(),
&source_id,
&sql,
max_rows,
&self.cancel.token(),
self.io_timeout(),
);
if result.is_err() {
self.grant_io_error_grace();
}
use bindings::openidea::plugin::database as db;
Ok(result
.map(|r| db::QueryResult {
columns: r
.columns
.into_iter()
.map(|c| db::QueryColumn { name: c.name, type_name: c.type_name })
.collect(),
rows: r.rows,
affected: r.affected,
has_more: r.has_more,
elapsed_ms: r.elapsed_ms,
})
.map_err(to_wit))
}
fn upsert_source(
&mut self,
project: Resource<ProjectRes>,
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
8fec8f3f93d13050a7d7579ba6e29baf2b8654777971f59087f34f2540fdf23d
fbd767ccf69c37807aa8f535197ab9fac47f809ef887ab9fd99c0b2886201ae1
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
9046ec47087a78f8a99f9f57b04178df91c31c7ea2dedf7610ee9ebfb5a2fb9f
583b5ee3f495851ca14c378a3a4fe4cfd92be772e5f33a383d4f3b9f935f4b7e
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
69644d5a8240e9407889df1b48400b1c89c6a9e15873dd47dca3015aceaf580b
a29fb8d12bc4bb7fdba146706ce941ecfce1e4ddecdbbe1672aac88b1adfb4da
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
7556cd36ed5769f3961abc67a2906c50e8b639f98a7ce631b8b7589c96f60291
f99c40e69fba8d835f578dc6d1dc2a078ad774d881ae454e3703d5d150cf2c8d
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
1e83a86f4a3f9ec70a8489e9d172f2a3829d2fa8546ca9c93deec9c05f899483
c732a0688e0cfcd71ce8471c4d929e5e5496461e44ef705a2bf468fad62b4ae8
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ebeb0be05062276fd9b24dae57c72fa58bc35ce054b4639687d4c3280c14300e
ee71ad8f7a4c3786c8221188fc117304ac68db6d567093661d4056d83e45cc99
+18 -2
Переглянути файл
@@ -1,12 +1,12 @@
id = "test.data-tools"
name = "Data tools fixture"
version = "0.1.0"
engines.openidea = "^1.20"
engines.openidea = "^1.21"
wasm = "dist/plugin.wasm"
activation = ["on-command:*"]
[capabilities]
required = ["project.read"]
optional = ["database.sources", "database.schema"]
optional = ["database.sources", "database.schema", "database.query"]
[[contributes.commands]]
id = "upsert"
@@ -71,6 +71,22 @@ destructive = false
id = "table-schema"
title = "Read table schema"
[[contributes.commands]]
id = "connected-sources"
title = "Connected sources"
[[contributes.commands]]
id = "list-schemas"
title = "List schemas"
[[contributes.commands]]
id = "list-tables"
title = "List tables"
[[contributes.commands]]
id = "execute-query"
title = "Execute query"
[[contributes.menus]]
menu = "database.table.context"
command = "table-schema"
+20
Переглянути файл
@@ -25,6 +25,26 @@ impl Plugin for DataTools {
return Ok(Some(serde_json::to_string(&schema).unwrap()));
}
"sources" => return Ok(Some(serde_json::to_string(&p.data_sources()?).unwrap())),
"connected-sources" => return Ok(Some(serde_json::to_string(&p.connected_data_sources()?).unwrap())),
"list-schemas" => {
let source_id = arg.ok_or("sourceId required")?;
return Ok(Some(serde_json::to_string(&p.database_schemas(source_id)?).unwrap()));
}
"list-tables" => {
let value: serde_json::Value = serde_json::from_str(arg.ok_or("sourceId and schema required")?)
.map_err(|e| Error::Invalid(e.to_string()))?;
let source_id = value["sourceId"].as_str().ok_or("sourceId required")?;
let schema = value["schema"].as_str().ok_or("schema required")?;
return Ok(Some(serde_json::to_string(&p.database_tables(source_id, schema)?).unwrap()));
}
"execute-query" => {
let value: serde_json::Value = serde_json::from_str(arg.ok_or("query request required")?)
.map_err(|e| Error::Invalid(e.to_string()))?;
let source_id = value["sourceId"].as_str().ok_or("sourceId required")?;
let sql = value["sql"].as_str().ok_or("sql required")?;
let max_rows = value["maxRows"].as_u64().map(|n| n as u32);
return Ok(Some(serde_json::to_string(&p.database_execute_query(source_id, sql, max_rows)?).unwrap()));
}
"credential" => p.set_data_source_credential("local", arg.unwrap_or("secret"))?,
"connect" => p.connect_data_source(arg.unwrap_or("local"))?,
_ => return Err(Error::NotFound(id.into())),
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
2a1f38092bb34e9864e9607a08521f8cf7dc74f24ad4bea4c4f7d021b41b34f5
33020cf1117fc910e2984a2bd0110924cf5ffdf24ae015bf191762993c06c532
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
0d64b659501e637eac7dc586d2e6bc7db09c7c6ea369dc8b3c6db7dc9b006787
9923493b942447f729a8568de02e3d02c3d59b3d7468f569a1ae978adaa3176d
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
f89bc44615d6b340046d9247f0f328a5d22a2ffafdfb34ce9e6356fc6d4b403a
d12f681411fda1fed05e537f291705a3ce26faa009044fdf9d0a01b964fc0056
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
008368cbac33887301d5bea31f1f090e0ba785a96ef3edc213da54299686d26d
893ce9fe2bb20cd5adc34794ad3ddc1c8779631fecf4d14dfa51290f55eb0377
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
bd66e872b60c7cf3919381257654f21407f86d47d84d884c7e8a357f9ad1b169
c5ec51674a2c7556ffd65ac856dbe68e024a6d9361348653b6ff32d31dcf3ff8
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b4b5b2286bc842d93aaaa49ec13579c21b1c3a3d0d7d44fa6e8e1b1a99e2cb8b
9212ac37ebb4e2a4c09afccec3d29ffd4ad6fb77a5444b108dc5381a66b3f3fd
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
7b84a518235f863e893e244c84d3d782049465a3176eb27ea27779c7cdd57c59
a0c79f2e2798894eaea06ccbf7c1a80cfb269817563273ede8ade9903b310f78
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b07a8f999a1c34cf1e437641c52ac9070c62ee933fe615ce490bc74e9eda5d44
d2c95eb484ec574031ea01e77e32fca49f5dca0b419a2ed9d6556c3db6810d4c
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
abf565f7c718c6647a5a170131de1abc5e16345a759060640bcdfe732921a9e7
82bdefebd3747dcda62acd8e9a11eb9e8ef137fddb0c29c5011c475cb184530b
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
2606ddcd55d3659ca29f2db12bd239124eb580fd96e273e8eacdc1df45be9275
5c383892b3c7345d2d230da7c4e5b3f1e1e1899491e0cf3df8ce3b02c41b5154
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
2ec881b3b984095389583c115de6a60dff6c6fef6888682b5113237c9459167e
11287c6ce9ad5b964ad730ccfd2ee846c6cc0a671b83f86daad78891e2463aba
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
a7712d7ae6dc79713432a62544571ed25a0f752bdf8cc8de01701958e3853ff7
a912aed6c1a64745240d16e6b8e69c7966023d7001ca712ccad32b8d1918e3df
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
0631360ca5b16015bc94cd461e562f37b24e982ac5b6dd6fa78ed87fd4ae0c54
76d52287de2178c4f7f19286a6fe387faf9c33d4d84e19dc6d447ad42b858256
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
eecb2014a22c74ebfe5a33ca8ad9ceeef139663f07f0f1216d0f777ac3f3fae2
87f6d2121aec400c280cc4c0d1b1cca762c7bad8432b833d0ee2b5b17002c733
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
8f9c04d37ee46cfdcd63fe101b9c84937ad1ea52b8c8051aea73c9e9c5fb9735
ed2c0bb9f9f91744b49e3e22240df3bb3a08eda6473013bf16e82946ac113a58
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
cfd459348ed64a64e86660c25db1163ce16a2f0bc9c74fda721f26980d0c16f2
e9673042b2e02fa544fdcc1f80a80b05765f3b9d30055668ad537ef59f19a2e2
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b34cea4bfdafae31c609581a295e20556be3b16b7d3a2a09b3bff0b059d63455
bc3e3af1b33eb2dab9d05caddb0c4f60205dbf4513d2afb39034f20e1364c471
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
1e44c2bf968fec294827f666f522e08db6b899431a02b53ca61a1a9aa9c77cd0
e19f1b0b2f46fed4ff0069e75fdc66a47cc231dc08c875076ffe4e90177a7228
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
cc2ecd77d2f7521c92496e659f8cd9e461d175d3acaf0740771ec8e3157b844a
57cf79449c2e030badd366fad9ba95d38e4988ccb7ff6d597eba250ded2722ff
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
d77719fdf8df15baedfc6de0e9e1b3a14344405892468eda0edba244a63bf8d9
bf9bff2aab8b32205131fdc961d084a8ca4b5553bfb52b9690cdb51c2bff43ed
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
55424888269455182c05a6dbd781460fbe51fec3d26116fd3026d593317a07bb
ec5994ac7a65203eb036af1ff58275ca543295b41d60644d48b00461a99f9c63
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
30e6598f5d9ab7aa3fb0a26b3e382fc9451c06b8c685c82a7cbf890a55ce3c05
cf48e6cd63b356a864e2b89beb2819540e6351854a70c0b258ba5170932c9749
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
7e35c37420037f87f669ad2ff2f3ad6133f36ff7bfcef0a2724fbcda3b036133
f61c925836203778feabab5df85ed96a36b4d9a1fca76144e216c9bdb3b80f76
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
08a7c7b6cd212506d3580114f9b57f14cd99e9db4673ee7cb048971815f55295
b576ff8d2e7ea172b0fa9f4a666d5f055add50cd2dc522ccf9395768b398e5e2
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
2b0bb4b5932d3c337376a6090bfd5c5af5de7bd42831c419fad9d373c5932191
53bb516f95537947d936f5c35598ea0f66c77611058131f7a6518f7c00540e0e
Loaded 100 of 306 files, more files were not shown because too many files have changed in this diff. Show more