дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
Порівняти коміти
69
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
b830760a88 | ||
|
|
1e6ab2ecff | ||
|
|
0f0e3e73e7 | ||
|
|
a2498f096a | ||
|
|
494d1a9bf5 | ||
|
|
417ecfed50 | ||
|
|
94653b487d | ||
|
|
a5473e896a | ||
|
|
8483c355c8 | ||
|
|
8d2d2d27e6 | ||
|
|
72db7ecb97 | ||
|
|
406cf4e474 | ||
|
|
bc019ace9d | ||
|
|
55c9787996 | ||
|
|
5b1e4a31f2 | ||
|
|
f3582403f3 | ||
|
|
a5f958d544 | ||
|
|
4aeeb4d883 | ||
|
|
15f3eadcf1 | ||
|
|
ae9804bc8b | ||
|
|
644a380616 | ||
|
|
4a41b14992 | ||
|
|
551328c901 | ||
|
|
54ce7ac6f8 | ||
|
|
a33c46465b | ||
|
|
b747e81cb6 | ||
|
|
24fdbb54db | ||
|
|
535f7584ee | ||
|
|
49e26d1de1 | ||
|
|
40fb4923e6 | ||
|
|
8fefbc1c82 | ||
|
|
059dca5b34 | ||
|
|
277464e93b | ||
|
|
a6e9c79c96 | ||
|
|
1a6c0dff36 | ||
|
|
73708c8e7d | ||
|
|
d2cc2093b1 | ||
|
|
ff9a48eb0e | ||
|
|
24e42bb302 | ||
|
|
67c00a986a | ||
|
|
896ec3b924 | ||
|
|
2f18cacbaf | ||
|
|
2cad48b401 | ||
|
|
1f8cf7e3a8 | ||
|
|
978bcd6dd4 | ||
|
|
a1d406beb3 | ||
|
|
b46c467fc3 | ||
|
|
091dd85ef0 | ||
|
|
4eab243ef2 | ||
|
|
56c6e8090a | ||
|
|
bd3f0cb651 | ||
|
|
fe1838aca6 | ||
|
|
9737adb66c | ||
|
|
1c4aa9f1b2 | ||
|
|
4335cf46af | ||
|
|
f2b602a48e | ||
|
|
b4c8a6708c | ||
|
|
8e36365bc4 | ||
|
|
b5a8a77cfa | ||
|
|
70a4fbec3a | ||
|
|
b640078b11 | ||
|
|
e186f74782 | ||
|
|
25d0294947 | ||
|
|
5d26e44c0e | ||
|
|
6e327e6ffc | ||
|
|
81d1285e38 | ||
|
|
8a92a7b10c | ||
|
|
3eb4b54525 | ||
|
|
5dd0565456 |
No files matched your search
@@ -7,7 +7,7 @@ BASEDPYRIGHT=1.40.2
|
||||
RUFF=0.17.3
|
||||
GOPLS=v0.24.0
|
||||
JDTLS=1.63.0-202610191322
|
||||
KOTLIN_LSP=271.2085.0
|
||||
KOTLIN_LSP=271.3588.0
|
||||
GRADLE=8.14.3
|
||||
INTELEPHENSE=1.18.5
|
||||
# The JDK projects compile against (JAVA_HOME): library navigation opens its sources.
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
English · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a>
|
||||
English · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
<p align="center">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="src-tauri/icons/source/openidea-wordmark-dark.svg">
|
||||
<img src="src-tauri/icons/source/openidea-wordmark.svg" alt="OpenIDEA" height="56">
|
||||
</picture>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
Знакомая вам IDE, переписанная на Rust.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a> · Русский
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>Скачать</b></a>
|
||||
·
|
||||
<a href="https://openidea.sh">Документация</a>
|
||||
·
|
||||
<a href="#сравнение-производительности">Производительность</a>
|
||||
·
|
||||
<a href="#плагины">Плагины</a>
|
||||
·
|
||||
<a href="#сообщество">Сообщество</a>
|
||||
</p>
|
||||
|
||||
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
|
||||
|
||||
OpenIDEA переносит привычные для пользователей IntelliJ IDEA сочетания клавиш, окна инструментов
|
||||
и глобальный поиск в нативное приложение с ядром на Rust.
|
||||
|
||||
Редактор, средства анализа кода, отладчик, Git, терминал, клиенты для работы с базами данных и HTTP.
|
||||
Поддержка более 60 языков. Сборки для macOS, Windows и Linux.
|
||||
|
||||
На macOS IDE также можно установить через Homebrew:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## Сравнение производительности
|
||||
|
||||
Открытие проекта [freqtrade](https://github.com/freqtrade/freqtrade) (Python, около 770 файлов)
|
||||
с прогретыми кешами, медиана пяти запусков:
|
||||
|
||||
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
|
||||
| ---------------------------------------------- | ------------------- | ---------------------- |
|
||||
| Появление окна с проектом | **0,9 с** | 3,1 с |
|
||||
| Готовность (нагрузка на CPU стабилизировалась) | **1,1 с** | 13,2 с |
|
||||
| Память (USS, все процессы) | **169 МБ** | 2011 МБ |
|
||||
| Процессорное время до готовности | **2,4 с** | 47,9 с |
|
||||
| Загрузка CPU в простое | **4 %** одного ядра | 7 % одного ядра |
|
||||
| Завершение работы | **0,3 с** | 5,9 с |
|
||||
|
||||
В тесте использовались релизная сборка OpenIDEA из ветки `main` и IDEA с настройками и плагинами по умолчанию.
|
||||
Окружение: Windows 11, 32-ядерный процессор AMD, 62 ГБ оперативной памяти.
|
||||
IDEA глубже анализирует Python-код, поэтому к моменту готовности обе IDE выполняют разный объём работы.
|
||||
Измерения обеих IDE проводились извне по одной методике: с помощью
|
||||
[`perf/compare`](perf/compare) можно повторить тест на своём компьютере со своими проектами.
|
||||
|
||||
## Плагины
|
||||
|
||||
Плагины добавляют действия, автодополнение кода, быстрые исправления, окна инструментов, пользовательские редакторы,
|
||||
темы оформления, значки файлов и поддержку языков. Они работают как компоненты WebAssembly в изолированной среде;
|
||||
для тем оформления, тем значков и языков писать код не нужно.
|
||||
|
||||
Плагины можно установить в разделе «Настройки › Плагины» (Settings › Plugins) или создать собственный командой
|
||||
`openidea-plugin new`. См. [руководство по созданию плагинов OpenIDEA](https://openidea.sh/en/plugins)
|
||||
и [официальные плагины](plugins/official). API плагинов пока доступен в предварительной версии.
|
||||
|
||||
## Сообщество
|
||||
|
||||
- [Discord](https://discord.gg/AsZqMgxZm): вопросы, обратная связь и новости о релизах.
|
||||
- Группа WeChat: отсканируйте QR-код, чтобы присоединиться.
|
||||
|
||||
<img src=".github/assets/wechat-group-5.png" alt="QR-код группы WeChat" width="200">
|
||||
|
||||
- Как внести вклад: см. [CONTRIBUTING.md](CONTRIBUTING.md) и [документацию для участников проекта](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
## Лицензия
|
||||
|
||||
[Apache 2.0](LICENSE). Включённые в поставку сторонние ресурсы перечислены в [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md).
|
||||
|
||||
<sub>OpenIDEA не связан с JetBrains. IntelliJ IDEA — товарный знак JetBrains s.r.o.</sub>
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · Türkçe
|
||||
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · Türkçe · <a href="README.ru.md">Русский</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> · 简体中文
|
||||
<a href="README.md">English</a> · 简体中文 · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
|
||||
@@ -24,7 +24,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
|
||||
match run_once(shared, spec, prefer_stored, model).await {
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
&& crate::provider::is_copilot_provider(&spec.id)
|
||||
&& crate::provider::is_copilot_provider(spec.base_id())
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root)
|
||||
&& super::auth_required(0, &err) =>
|
||||
{
|
||||
@@ -53,7 +53,7 @@ async fn run_once(
|
||||
.await
|
||||
.map_err(|e| e.to_string())??;
|
||||
let cwd = dunce::canonicalize(&root).unwrap_or(root);
|
||||
let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), ..Default::default() });
|
||||
let updates = Arc::new(DiscoveryUpdates { provider: spec.base_id().to_owned(), ..Default::default() });
|
||||
let client = Dialect::wrap(updates.clone());
|
||||
let on_stderr: Box<dyn Fn(String) + Send + Sync> = Box::new(|_| {});
|
||||
let peer = (shared.connector)(&launch, &cwd, client.clone(), on_stderr)
|
||||
@@ -69,7 +69,7 @@ async fn run_once(
|
||||
.await
|
||||
.map_err(discovery_error)?;
|
||||
let mut options = config::options_of(&new);
|
||||
config::add_client_options(&launch.id, &mut options);
|
||||
config::add_client_options(launch.base_id(), &mut options);
|
||||
let model_option = options.iter().find(|o| o.category.as_deref() == Some("model"));
|
||||
let mut levels = BTreeMap::new();
|
||||
let has_config = new.get("configOptions").is_some_and(Value::is_array);
|
||||
@@ -119,7 +119,7 @@ async fn run_once(
|
||||
.commands
|
||||
.lock()
|
||||
.clone()
|
||||
.or_else(|| new.get("availableCommands").map(|_| config::commands_of(&new, &launch.id)));
|
||||
.or_else(|| new.get("availableCommands").map(|_| config::commands_of(&new, launch.base_id())));
|
||||
Ok::<_, String>(Discovered { config: options, commands, levels })
|
||||
};
|
||||
let result = tokio::time::timeout(DISCOVER_TIMEOUT, work).await;
|
||||
|
||||
@@ -680,7 +680,7 @@ async fn discover(
|
||||
Ok(Discovered {
|
||||
commands: Some(config::commands_of(
|
||||
&serde_json::json!({ "availableCommands": found.commands }),
|
||||
&spec.id,
|
||||
spec.base_id(),
|
||||
)),
|
||||
config: config::options_of(&serde_json::json!({ "configOptions": found.options })),
|
||||
levels: found
|
||||
@@ -704,7 +704,7 @@ async fn discover(
|
||||
Ok(found) => Ok(Discovered {
|
||||
commands: Some(config::commands_of(
|
||||
&serde_json::json!({ "availableCommands": found.commands }),
|
||||
&spec.id,
|
||||
spec.base_id(),
|
||||
)),
|
||||
config: config::options_of(&serde_json::json!({ "configOptions": found.options })),
|
||||
levels: found
|
||||
|
||||
@@ -79,6 +79,12 @@ pub fn login_launch_without_project(
|
||||
.ok_or_else(|| IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name)))
|
||||
}
|
||||
|
||||
/// The built-in agent `id` is an instance of, or `id` itself, outside a project.
|
||||
pub fn base_provider_id_without_project(custom_agents_dir: Option<&Path>, id: &str) -> String {
|
||||
let specs = provider::load(custom_agents_dir, None);
|
||||
specs.iter().find(|p| p.id == id).map_or(id, |p| p.base_id()).to_owned()
|
||||
}
|
||||
|
||||
/// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts.
|
||||
pub async fn copilot_auth_status_with(
|
||||
custom_agents_dir: Option<&Path>,
|
||||
@@ -231,11 +237,13 @@ impl AgentPaths {
|
||||
fn provider_specs(&self) -> Vec<provider::ProviderSpec> {
|
||||
let mut specs = provider::load(self.custom_agents_dir.as_deref(), self.env_secrets.as_deref());
|
||||
for spec in &mut specs {
|
||||
if spec.source == AgentSource::Builtin
|
||||
&& let Some(pkg) = cli_update::package(&spec.id)
|
||||
&& let Some(builtin) = provider::builtin_spec(&spec.id)
|
||||
// An instance launching its base's command shares the base's managed install.
|
||||
let base = spec.base_id().to_owned();
|
||||
if (spec.source == AgentSource::Builtin || spec.base.is_some())
|
||||
&& let Some(pkg) = cli_update::package(&base)
|
||||
&& let Some(builtin) = provider::builtin_spec(&base)
|
||||
&& spec.command == builtin.command
|
||||
&& let Some(link) = cli_update::managed_cli(&self.cli_dir.join(&spec.id), pkg, &spec.command)
|
||||
&& let Some(link) = cli_update::managed_cli(&self.cli_dir.join(&base), pkg, &spec.command)
|
||||
&& !provider::installed_with_env(&spec.command, &spec.env)
|
||||
{
|
||||
spec.managed_cli = link.to_str().map(str::to_owned);
|
||||
@@ -397,6 +405,11 @@ impl Shared {
|
||||
self.providers.read().iter().find(|p| p.id == id).cloned()
|
||||
}
|
||||
|
||||
/// The built-in id agent `id` is an instance of, or else `id` itself.
|
||||
fn base_id(&self, id: &str) -> String {
|
||||
self.providers.read().iter().find(|p| p.id == id).map_or(id, |p| p.base_id()).to_owned()
|
||||
}
|
||||
|
||||
fn env_secrets(&self) -> Option<&dyn EnvSecrets> {
|
||||
self.paths.env_secrets.as_deref()
|
||||
}
|
||||
@@ -420,7 +433,7 @@ impl Shared {
|
||||
|
||||
async fn probe_network(&self, provider: &str) -> bool {
|
||||
let hook = self.network_probe_hook.read().clone();
|
||||
let provider = provider.to_owned();
|
||||
let provider = self.base_id(provider);
|
||||
tokio::task::spawn_blocking(move || match hook {
|
||||
Some(hook) => hook(&provider),
|
||||
None => default_network_probe(&provider),
|
||||
@@ -511,7 +524,7 @@ impl Shared {
|
||||
fn config_for_new_task(&self, mut config: Vec<AgentConfigOption>, provider: &str) -> Vec<AgentConfigOption> {
|
||||
// Model-specific options are offered separately, never as provider-wide defaults.
|
||||
config.retain(|o| !config::is_per_model_option(o));
|
||||
config::add_client_options(provider, &mut config);
|
||||
config::add_client_options(&self.base_id(provider), &mut config);
|
||||
let hook = self.new_task_approvals.read().clone();
|
||||
if hook.is_some_and(|ask| ask() == ide_core::settings::NewTaskApprovals::Ask) {
|
||||
config::ask_for_approvals(&mut config);
|
||||
@@ -526,8 +539,9 @@ impl Shared {
|
||||
mut levels: BTreeMap<String, Vec<AgentConfigOption>>,
|
||||
provider: &str,
|
||||
) -> BTreeMap<String, Vec<AgentConfigOption>> {
|
||||
let base = self.base_id(provider);
|
||||
for options in levels.values_mut() {
|
||||
config::apply_model_defaults(provider, options);
|
||||
config::apply_model_defaults(&base, options);
|
||||
}
|
||||
levels
|
||||
}
|
||||
@@ -1306,10 +1320,20 @@ impl AgentManager {
|
||||
/// The agents (custom ones re-read), whether each is installed, and what they offered last time.
|
||||
pub fn providers(&self) -> Vec<AgentProvider> {
|
||||
let specs = self.shared.paths.provider_specs();
|
||||
{
|
||||
let mut prev = self.shared.providers.write();
|
||||
let mut probes = self.shared.probes.lock();
|
||||
probes.retain(|id, _| {
|
||||
let old = prev.iter().find(|p| &p.id == id);
|
||||
let new = specs.iter().find(|p| &p.id == id);
|
||||
matches!((old, new), (Some(a), Some(b)) if a.executable() == b.executable() && a.args == b.args && a.env == b.env)
|
||||
});
|
||||
*prev = specs.clone();
|
||||
}
|
||||
let in_use: std::collections::HashSet<String> =
|
||||
self.tasks.read().values().map(|t| t.state.lock().task.provider.clone()).collect();
|
||||
let terminal_auth = self.shared.terminal_auth_args.read();
|
||||
let list = specs
|
||||
specs
|
||||
.iter()
|
||||
.filter(|p| !provider::is_unlisted(p) || in_use.contains(&p.id))
|
||||
.map(|p| {
|
||||
@@ -1329,19 +1353,12 @@ impl AgentManager {
|
||||
info.commands = self.shared.known_commands(&p.id);
|
||||
info
|
||||
})
|
||||
.collect();
|
||||
drop(terminal_auth);
|
||||
let mut prev = self.shared.providers.write();
|
||||
let mut probes = self.shared.probes.lock();
|
||||
probes.retain(|id, _| {
|
||||
let old = prev.iter().find(|p| &p.id == id);
|
||||
let new = specs.iter().find(|p| &p.id == id);
|
||||
matches!((old, new), (Some(a), Some(b)) if a.executable() == b.executable() && a.args == b.args && a.env == b.env)
|
||||
});
|
||||
*prev = specs.clone();
|
||||
drop(probes);
|
||||
drop(prev);
|
||||
list
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The built-in id agent `id` is an instance of, or else `id` itself.
|
||||
pub fn base_provider_id(&self, id: &str) -> String {
|
||||
self.shared.base_id(id)
|
||||
}
|
||||
|
||||
/// Resolves the interactive sign-in command for agent `id`.
|
||||
@@ -1386,7 +1403,7 @@ impl AgentManager {
|
||||
provider::set_builtin_additional_args(dir, self.shared.env_secrets(), id, args)
|
||||
}
|
||||
|
||||
/// Sets the environment variables built-in `id` starts with; empty clears them.
|
||||
/// Sets the environment variables built-in `id` (or an instance of one) starts with; empty clears them.
|
||||
pub fn set_builtin_env(&self, id: &str, env: std::collections::BTreeMap<String, String>) -> IdeResult<()> {
|
||||
let Some(dir) = self.shared.paths.custom_agents_dir.clone() else {
|
||||
return Err(IdeError::unavailable("there is no custom agents directory"));
|
||||
@@ -1396,12 +1413,14 @@ impl AgentManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Saves a new custom ACP agent through its agent file.
|
||||
/// Saves a new custom ACP agent, or an instance of a built-in agent, through its agent file.
|
||||
pub fn save_custom_agent(&self, input: CustomAgentInput) -> IdeResult<()> {
|
||||
let Some(dir) = self.shared.paths.custom_agents_dir.clone() else {
|
||||
return Err(IdeError::unavailable("there is no custom agents directory"));
|
||||
};
|
||||
provider::save_custom(&dir, self.shared.env_secrets(), &input)
|
||||
provider::save_custom(&dir, self.shared.env_secrets(), &input)?;
|
||||
*self.shared.providers.write() = self.shared.paths.provider_specs();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes a custom agent's file (registry installs go through `registry_remove`).
|
||||
@@ -1409,7 +1428,10 @@ impl AgentManager {
|
||||
let Some(dir) = self.shared.paths.custom_agents_dir.clone() else {
|
||||
return Err(IdeError::unavailable("there is no custom agents directory"));
|
||||
};
|
||||
provider::remove_custom(&dir, self.shared.env_secrets(), id)
|
||||
provider::remove_custom(&dir, self.shared.env_secrets(), id)?;
|
||||
*self.shared.providers.write() = self.shared.paths.provider_specs();
|
||||
self.shared.paths.catalogs.evict_if_idle(&self.shared, id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Imports a JetBrains `acp.json` file's `agent_servers` entries as custom agents.
|
||||
@@ -1490,23 +1512,26 @@ impl AgentManager {
|
||||
}
|
||||
offered = self.shared.known_commands(&provider);
|
||||
}
|
||||
for command in builtin_commands(&provider) {
|
||||
let base_id = self.shared.base_id(&provider);
|
||||
for command in builtin_commands(&base_id) {
|
||||
if !offered.iter().any(|c| c.name == command.name) {
|
||||
offered.push(command);
|
||||
}
|
||||
}
|
||||
let home = self.shared.paths.home_dir.clone();
|
||||
if provider == "hermes" || provider.starts_with("hermes-") {
|
||||
if base_id == "hermes" || provider.starts_with("hermes-") {
|
||||
let hermes_home = home.clone();
|
||||
let hermes_provider = provider.clone();
|
||||
let hermes_base = base_id.clone();
|
||||
let found = blocking(move || {
|
||||
let profile =
|
||||
hermes::root(hermes_home.as_deref()).and_then(|root| hermes::profile_home(&root, &hermes_provider));
|
||||
let profile = hermes::root(hermes_home.as_deref()).and_then(|root| {
|
||||
hermes::profile_home(&root, &hermes_provider).or_else(|| hermes::profile_home(&root, &hermes_base))
|
||||
});
|
||||
Ok(profile.map(|p| skills::hermes(&p)).unwrap_or_default())
|
||||
})
|
||||
.await?;
|
||||
offered = skills::merge(offered, found);
|
||||
} else if provider == "claude" || provider == "claude-acp" {
|
||||
} else if base_id == "claude" || base_id == "claude-acp" {
|
||||
let claude_cwd = cwd.clone();
|
||||
let found = blocking(move || Ok(skills::discover(&claude_cwd, home.as_deref()))).await?;
|
||||
offered = skills::merge(offered, found);
|
||||
@@ -1527,7 +1552,7 @@ impl AgentManager {
|
||||
let plugin_dirs = policy.plugin_dirs;
|
||||
let indexed_skill_files = policy.indexed_skill_files;
|
||||
let home = self.shared.paths.home_dir.clone();
|
||||
let cmd_provider = provider.clone();
|
||||
let cmd_provider = base_id.clone();
|
||||
blocking(move || {
|
||||
let mut p_pol = plug_policy;
|
||||
if p_pol.workspace_roots.is_empty() {
|
||||
@@ -1896,7 +1921,7 @@ impl AgentManager {
|
||||
.map(|h| h())
|
||||
.unwrap_or(ide_core::settings::NewTaskApprovals::Bypass);
|
||||
let mode = Some(meta.permissions.unwrap_or_default());
|
||||
config::clamp_automation_permissions(&spec.id, mode, interactive, &mut config, &mut wanted);
|
||||
config::clamp_automation_permissions(spec.base_id(), mode, interactive, &mut config, &mut wanted);
|
||||
}
|
||||
let now = now_ms();
|
||||
// Copies of the files the user had changed already, for rolling back the task's changes to them.
|
||||
@@ -2329,10 +2354,16 @@ impl AgentManager {
|
||||
let epoch = self.shared.shutdown_epoch();
|
||||
// A Codex fork must be opened by its own task: the creating app-server owns its writer.
|
||||
// It can also fork a recorded thread whose writer is held by another process.
|
||||
let codex_source = {
|
||||
let (source_provider, source_session) = {
|
||||
let s = source.state.lock();
|
||||
(s.task.provider == "codex").then(|| s.session_id.clone()).flatten()
|
||||
(s.task.provider.clone(), s.session_id.clone())
|
||||
};
|
||||
let codex_source = source
|
||||
.shared
|
||||
.spec(&source_provider)
|
||||
.is_some_and(|spec| spec.driver == provider::Driver::Codex)
|
||||
.then_some(source_session)
|
||||
.flatten();
|
||||
let live = if codex_source.is_none() {
|
||||
Some(source.ensure_session(epoch).await.map_err(IdeError::internal)?)
|
||||
} else {
|
||||
@@ -2354,10 +2385,11 @@ impl AgentManager {
|
||||
let t = &s.task;
|
||||
(t.cwd.0.clone(), t.provider.clone(), t.mcp_overrides.clone(), t.project_root.clone().map(|p| p.0))
|
||||
};
|
||||
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides, None);
|
||||
let base_id = source.shared.base_id(&provider_id);
|
||||
let mcp_servers = source.shared.mcp_servers_for_session(&base_id, &live.init, &mcp_overrides, None);
|
||||
let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref());
|
||||
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
|
||||
let memory_delivery = source.stage_memory(&provider_id, &cwd).await;
|
||||
let memory_delivery = source.stage_memory(&base_id, &cwd).await;
|
||||
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
|
||||
let reply: Value = live
|
||||
.peer
|
||||
@@ -3897,7 +3929,7 @@ impl Task {
|
||||
/// The task from the parts of `file` other than its history, which `history` holds.
|
||||
fn assemble(file: TaskFile, history: StoredHistory, adopt: bool, shared: Arc<Shared>) -> Arc<Self> {
|
||||
let mut task = file.task;
|
||||
config::add_client_options(&task.provider, &mut task.config);
|
||||
config::add_client_options(&shared.base_id(&task.provider), &mut task.config);
|
||||
let mut wanted = file.wanted;
|
||||
let mut pending_model = file.pending_switch.or_else(|| {
|
||||
let id = file.pending_model?;
|
||||
@@ -4500,7 +4532,11 @@ impl Task {
|
||||
.as_ref()
|
||||
.map(|h| h())
|
||||
.unwrap_or(ide_core::settings::NewTaskApprovals::Bypass);
|
||||
let (provider, mut non_approval_choices) = {
|
||||
let base = {
|
||||
let provider = self.state.lock().task.provider.clone();
|
||||
self.shared.base_id(&provider)
|
||||
};
|
||||
let mut non_approval_choices = {
|
||||
let mut s = self.state.lock();
|
||||
let model_opt_id =
|
||||
s.task.config.iter().find(|o| o.category.as_deref() == Some("model")).map(|o| o.id.clone());
|
||||
@@ -4521,10 +4557,9 @@ impl Task {
|
||||
s.wanted.push(choice.clone());
|
||||
}
|
||||
}
|
||||
let provider = s.task.provider.clone();
|
||||
let mut target_config = s.task.config.clone();
|
||||
let mut target_wanted = s.wanted.clone();
|
||||
config::clamp_automation_permissions(&provider, mode, interactive, &mut target_config, &mut target_wanted);
|
||||
config::clamp_automation_permissions(&base, mode, interactive, &mut target_config, &mut target_wanted);
|
||||
s.wanted = target_wanted;
|
||||
let non_approval: Vec<AgentConfigChoice> = extra_choices
|
||||
.iter()
|
||||
@@ -4535,7 +4570,7 @@ impl Task {
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
(provider, non_approval)
|
||||
non_approval
|
||||
};
|
||||
self.persist();
|
||||
|
||||
@@ -4608,13 +4643,7 @@ impl Task {
|
||||
let mut s = self.state.lock();
|
||||
let mut target_config = s.task.config.clone();
|
||||
let mut target_wanted = s.wanted.clone();
|
||||
config::clamp_automation_permissions(
|
||||
&provider,
|
||||
mode,
|
||||
interactive,
|
||||
&mut target_config,
|
||||
&mut target_wanted,
|
||||
);
|
||||
config::clamp_automation_permissions(&base, mode, interactive, &mut target_config, &mut target_wanted);
|
||||
let mut diffs = Vec::new();
|
||||
for next_opt in &target_config {
|
||||
let prev_cur =
|
||||
@@ -4655,7 +4684,7 @@ impl Task {
|
||||
}
|
||||
}
|
||||
let current_cfg = self.state.lock().task.config.clone();
|
||||
config::verify_automation_ceiling(&provider, mode, interactive, ¤t_cfg).map_err(IdeError::invalid)?;
|
||||
config::verify_automation_ceiling(&base, mode, interactive, ¤t_cfg).map_err(IdeError::invalid)?;
|
||||
self.approve_pending();
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
@@ -4982,10 +5011,11 @@ impl Task {
|
||||
}
|
||||
|
||||
fn cursor_at_capacity(&self, result: &Result<String, Failure>) -> bool {
|
||||
let s = self.state.lock();
|
||||
if s.task.provider != "cursor" {
|
||||
let provider = self.state.lock().task.provider.clone();
|
||||
if self.shared.base_id(&provider) != "cursor" {
|
||||
return false;
|
||||
}
|
||||
let s = self.state.lock();
|
||||
matches!(result, Ok(stop) if stop == "end_turn")
|
||||
&& matches!(
|
||||
s.history.conversation.main.entries.last(),
|
||||
@@ -5307,11 +5337,13 @@ impl Task {
|
||||
/// Adds `prompt` to the running turn when the agent takes that; gives it back otherwise.
|
||||
async fn steer(self: &Arc<Self>, prompt: AgentPrompt) -> Result<(), AgentPrompt> {
|
||||
let live = self.live.lock().clone().filter(|l| l.capabilities.steer && !l.peer.is_closed());
|
||||
let provider = self.state.lock().task.provider.clone();
|
||||
let cursor = self.shared.base_id(&provider) == "cursor";
|
||||
let running = {
|
||||
let s = self.state.lock();
|
||||
// During Cursor backoff the ACP turn has already ended. Send Now must
|
||||
// cancel the wait and dispatch the new prompt as a turn of its own.
|
||||
s.busy && s.task.status == AgentStatus::Running && !(s.task.provider == "cursor" && s.task.retry.is_some())
|
||||
s.busy && s.task.status == AgentStatus::Running && !(cursor && s.task.retry.is_some())
|
||||
};
|
||||
let Some((live, method)) = live
|
||||
.filter(|l| running && (prompt.images.is_empty() || l.capabilities.images))
|
||||
@@ -5563,11 +5595,13 @@ impl Task {
|
||||
if self.recorded_load_started.load(Ordering::Acquire) || !self.adopts_replay() || self.live.lock().is_some() {
|
||||
return false;
|
||||
}
|
||||
let provider = self.state.lock().task.provider.clone();
|
||||
let base = self.shared.base_id(&provider);
|
||||
let s = self.state.lock();
|
||||
!s.busy
|
||||
&& s.session_id.is_some()
|
||||
&& s.pending_native_fork.is_none()
|
||||
&& RECORDED_SESSION_AGENTS.contains(&s.task.provider.as_str())
|
||||
&& RECORDED_SESSION_AGENTS.contains(&base.as_str())
|
||||
}
|
||||
|
||||
/// Opens the recorded session in the background, once per run: its replay shows the history
|
||||
@@ -5669,6 +5703,7 @@ impl Task {
|
||||
.map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?;
|
||||
let cwd = verified_cwd.as_path();
|
||||
let launch_cwd = cwd.to_path_buf();
|
||||
let base_id = spec.base_id().to_owned();
|
||||
let mut spec = tokio::task::spawn_blocking(move || {
|
||||
spec.resolve_for_launch_with_copilot_env(&launch_cwd, provider::prefer_stored_copilot_auth())
|
||||
})
|
||||
@@ -5678,10 +5713,10 @@ impl Task {
|
||||
if self.shared.shut_down_since(epoch) {
|
||||
return Err(SessionOpenError { message: "The agent manager shut down.".into(), allow_acp_fallback: false });
|
||||
}
|
||||
let memory_delivery = self.stage_memory(provider_id, cwd).await;
|
||||
if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(provider_id) {
|
||||
let memory_delivery = self.stage_memory(&base_id, cwd).await;
|
||||
if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(&base_id) {
|
||||
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
|
||||
for name in self.shared.mcp_servers_off_for_session(provider_id, &mcp_overrides) {
|
||||
for name in self.shared.mcp_servers_off_for_session(&base_id, &mcp_overrides) {
|
||||
spec.args.push("--disable-mcp-server".into());
|
||||
spec.args.push(name);
|
||||
}
|
||||
@@ -5757,7 +5792,7 @@ impl Task {
|
||||
})
|
||||
};
|
||||
let mcp_servers = self.shared.mcp_servers_for_session(
|
||||
provider_id,
|
||||
&base_id,
|
||||
&init,
|
||||
&mcp_overrides,
|
||||
mcp_nonce.as_ref().map(|g| g.nonce.as_str()),
|
||||
@@ -5959,7 +5994,7 @@ impl Task {
|
||||
let effective_perm_mode = sched_perm.unwrap_or(auto_perm);
|
||||
(options, wanted, ceiling_active, effective_perm_mode)
|
||||
};
|
||||
config::add_client_options(provider_id, &mut options);
|
||||
config::add_client_options(&base_id, &mut options);
|
||||
let interactive = self
|
||||
.shared
|
||||
.new_task_approvals
|
||||
@@ -5971,13 +6006,7 @@ impl Task {
|
||||
// Compute clamped choices on a scratch copy of `options` so `options[i].current` still
|
||||
// reflects what the CLI reported and the `wanted` loop below sends any needed downgrade!
|
||||
let mut scratch = options.clone();
|
||||
config::clamp_automation_permissions(
|
||||
provider_id,
|
||||
effective_perm_mode,
|
||||
interactive,
|
||||
&mut scratch,
|
||||
&mut wanted,
|
||||
);
|
||||
config::clamp_automation_permissions(&base_id, effective_perm_mode, interactive, &mut scratch, &mut wanted);
|
||||
}
|
||||
// Changing model can replace the effort / context-tier choices; validate those only afterwards.
|
||||
wanted.sort_by_key(|c| {
|
||||
@@ -6094,7 +6123,7 @@ impl Task {
|
||||
}
|
||||
}
|
||||
if ceiling_active {
|
||||
config::verify_automation_ceiling(provider_id, effective_perm_mode, interactive, &options)
|
||||
config::verify_automation_ceiling(&base_id, effective_perm_mode, interactive, &options)
|
||||
.map_err(|message| SessionOpenError { message, allow_acp_fallback: false })?;
|
||||
}
|
||||
if self.shared.shut_down_since(epoch) {
|
||||
@@ -6327,6 +6356,7 @@ impl Task {
|
||||
}
|
||||
// Session state (also while `session/load` replays history).
|
||||
let provider = self.state.lock().task.provider.clone();
|
||||
let base = self.shared.base_id(&provider);
|
||||
let task_changed = {
|
||||
let mut s = self.state.lock();
|
||||
match kind {
|
||||
@@ -6344,7 +6374,7 @@ impl Task {
|
||||
true
|
||||
}
|
||||
"available_commands_update" => {
|
||||
s.task.commands = config::commands_of(update, &provider);
|
||||
s.task.commands = config::commands_of(update, &base);
|
||||
true
|
||||
}
|
||||
"usage_update" => {
|
||||
|
||||
@@ -769,6 +769,12 @@ pub struct AgentProvider {
|
||||
/// The built-in command can be owned by a global npm package.
|
||||
#[serde(default)]
|
||||
pub can_check_cli_update: bool,
|
||||
/// The built-in agent this one is an instance of.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub base: Option<String>,
|
||||
/// A built-in agent, of which another instance can be added.
|
||||
#[serde(default)]
|
||||
pub can_duplicate: bool,
|
||||
/// Environment variables it starts with (from its agent file).
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Settings (models, modes…) the agent offered last time it ran; empty before its first session.
|
||||
@@ -1876,13 +1882,16 @@ pub struct McpProbeResult {
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Payload for creating a custom ACP agent (always the ACP driver); the id
|
||||
/// becomes the `<config>/agents/<id>.toml` file name.
|
||||
/// Payload for creating a custom ACP agent, or an instance of built-in `base` (which
|
||||
/// launches as its base does when `command` is empty); the id becomes the
|
||||
/// `<config>/agents/<id>.toml` file name.
|
||||
#[derive(Clone, Debug, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CustomAgentInput {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub base: Option<String>,
|
||||
pub command: String,
|
||||
#[serde(default)]
|
||||
pub args: Vec<String>,
|
||||
|
||||
@@ -131,6 +131,7 @@ for line in sys.stdin:
|
||||
env: Vec::new(),
|
||||
login_hint: String::new(),
|
||||
source: crate::AgentSource::Builtin,
|
||||
base: None,
|
||||
};
|
||||
let found = discover(spec, tmp.path().to_path_buf()).await.unwrap();
|
||||
let models: Vec<_> = found
|
||||
|
||||
@@ -43,6 +43,8 @@ pub(crate) struct ProviderSpec {
|
||||
/// How to sign in when the agent reports it needs authentication.
|
||||
pub login_hint: String,
|
||||
pub source: AgentSource,
|
||||
/// The built-in agent an instance copies (its identity); `None` for every other agent.
|
||||
pub base: Option<String>,
|
||||
}
|
||||
|
||||
/// `(id, name, driver, command line, sign-in hint)`. npm adapters are pinned so a
|
||||
@@ -108,11 +110,17 @@ fn builtins() -> Vec<ProviderSpec> {
|
||||
env: Vec::new(),
|
||||
login_hint: (*hint).into(),
|
||||
source: AgentSource::Builtin,
|
||||
base: None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl ProviderSpec {
|
||||
/// The built-in id this agent is an instance of, or else its own id.
|
||||
pub(crate) fn base_id(&self) -> &str {
|
||||
self.base.as_deref().unwrap_or(&self.id)
|
||||
}
|
||||
|
||||
pub(crate) fn executable(&self) -> &str {
|
||||
self.managed_cli.as_deref().unwrap_or(&self.command)
|
||||
}
|
||||
@@ -122,7 +130,7 @@ impl ProviderSpec {
|
||||
return self.login_hint.clone();
|
||||
}
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let builtin = builtin_spec(&self.id);
|
||||
let builtin = builtin_spec(self.base_id());
|
||||
let on_path = builtin.as_ref().and_then(|b| ide_core::process::find_executable(&b.command, &search));
|
||||
render_login_hint(self, program, on_path.as_deref(), cfg!(windows))
|
||||
}
|
||||
@@ -161,7 +169,7 @@ impl ProviderSpec {
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Result<Self, String> {
|
||||
let is_copilot = is_copilot_provider(&self.id);
|
||||
let is_copilot = is_copilot_provider(self.base_id());
|
||||
let account = is_copilot.then(|| copilot_github_account(&self.env)).flatten();
|
||||
let explicit_copilot_token =
|
||||
self.env.iter().any(|(name, value)| name == "COPILOT_GITHUB_TOKEN" && !value.is_empty());
|
||||
@@ -191,7 +199,7 @@ impl ProviderSpec {
|
||||
} else if self.driver != Driver::Acp {
|
||||
self.command = crate::native::newest_install(&self.command);
|
||||
}
|
||||
if is_copilot_provider(&self.id) {
|
||||
if is_copilot_provider(self.base_id()) {
|
||||
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
|
||||
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
}
|
||||
@@ -217,7 +225,7 @@ impl ProviderSpec {
|
||||
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
|
||||
};
|
||||
|
||||
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
|
||||
if let Some((separate_cmd, separate_args)) = match self.base_id() {
|
||||
"claude-acp" => Some(("claude", &[][..])),
|
||||
"codex-acp" => Some(("codex", &["login"][..])),
|
||||
"vibe" => Some(("vibe", &[][..])),
|
||||
@@ -231,7 +239,7 @@ impl ProviderSpec {
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(builtin) = builtin_spec(&self.id)
|
||||
if let Some(builtin) = builtin_spec(self.base_id())
|
||||
&& !(matches!(self.source, AgentSource::Registry { .. }) && registry_uses_separate_binary(&self.id))
|
||||
{
|
||||
let args = terminal_auth_args
|
||||
@@ -241,7 +249,7 @@ impl ProviderSpec {
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
let mut env: BTreeMap<String, String> = resolved.env.into_iter().collect();
|
||||
if is_copilot_provider(&self.id) {
|
||||
if is_copilot_provider(self.base_id()) {
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
@@ -532,7 +540,7 @@ pub(crate) fn sanitize_copilot_env_with(
|
||||
}
|
||||
|
||||
fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>, windows: bool) -> String {
|
||||
let Some(builtin) = builtin_spec(&spec.id) else { return spec.login_hint.clone() };
|
||||
let Some(builtin) = builtin_spec(spec.base_id()) else { return spec.login_hint.clone() };
|
||||
let prefix = format!("Run `{}", builtin.command);
|
||||
let Some(rest) = spec.login_hint.strip_prefix(&prefix).filter(|rest| rest.starts_with([' ', '`'])) else {
|
||||
return spec.login_hint.clone();
|
||||
@@ -620,6 +628,8 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
let builtin = builtin_spec(&spec.id);
|
||||
let reason = if matches!(spec.source, AgentSource::Registry { .. }) {
|
||||
Some(AgentCommandReadOnlyReason::Registry)
|
||||
} else if spec.base.is_some() {
|
||||
Some(AgentCommandReadOnlyReason::CustomAgent)
|
||||
} else if let Some(default) = &builtin {
|
||||
uses_package_runner(&default.command).then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
} else {
|
||||
@@ -649,6 +659,8 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
cli_install_command: None,
|
||||
can_sign_in: spec.can_sign_in(Path::new("."), None),
|
||||
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
|
||||
base: spec.base.clone(),
|
||||
can_duplicate: builtin.is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
config: vec![],
|
||||
thought_levels: BTreeMap::new(),
|
||||
@@ -687,13 +699,17 @@ pub(crate) fn set_builtin_additional_args(
|
||||
})
|
||||
}
|
||||
|
||||
/// The environment built-in `id` starts with, through its agent file (empty clears it).
|
||||
/// The environment built-in `id` (or an instance of one) starts with, through its agent file
|
||||
/// (empty clears it).
|
||||
pub(crate) fn set_builtin_env(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
env: BTreeMap<String, String>,
|
||||
) -> IdeResult<()> {
|
||||
if builtin_spec(id).is_none() {
|
||||
return set_instance_env(custom_dir, secrets, id, env);
|
||||
}
|
||||
if id == "copilot" {
|
||||
let file = custom_dir.join("copilot.toml");
|
||||
if file.try_exists()?
|
||||
@@ -725,6 +741,26 @@ pub(crate) fn set_builtin_env(
|
||||
})
|
||||
}
|
||||
|
||||
/// An instance's environment is all its own: never merged with its base's.
|
||||
fn set_instance_env(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
env: BTreeMap<String, String>,
|
||||
) -> IdeResult<()> {
|
||||
let id = validated_custom_id(id)?;
|
||||
let _lock = lock_custom_agents(custom_dir)?;
|
||||
let file = custom_dir.join(format!("{id}.toml"));
|
||||
let mut agent = match CustomAgent::read_with(&file, &id, secrets) {
|
||||
Ok(agent) if agent.registry.is_none() && agent.base.as_deref().is_some_and(|b| builtin_spec(b).is_some()) => {
|
||||
agent
|
||||
}
|
||||
_ => return Err(IdeError::invalid(format!("{id} is not a built-in agent or an instance of one"))),
|
||||
};
|
||||
agent.env = env;
|
||||
agent.write_with(&file, &id, secrets)
|
||||
}
|
||||
|
||||
/// Changes built-in `id`'s agent file; a file left with only the built-in's values is removed.
|
||||
fn update_builtin(
|
||||
custom_dir: &Path,
|
||||
@@ -741,6 +777,7 @@ fn update_builtin(
|
||||
} else {
|
||||
CustomAgent {
|
||||
name: Some(builtin.name.clone()),
|
||||
base: None,
|
||||
driver: builtin.driver,
|
||||
command: builtin.command.clone(),
|
||||
args: builtin.args.clone(),
|
||||
@@ -786,7 +823,8 @@ fn lock_custom_agents(custom_dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
|
||||
/// Saves a new custom agent; refuses built-in and ACP Registry ids, taken ids
|
||||
/// and an empty command. The id is also the agent file's name, so it must be
|
||||
/// a safe file stem.
|
||||
/// a safe file stem. An instance of a built-in (`base`) may leave the command
|
||||
/// empty to launch as its base does.
|
||||
pub(crate) fn save_custom(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
@@ -796,9 +834,19 @@ pub(crate) fn save_custom(
|
||||
if builtin_spec(&id).is_some() {
|
||||
return Err(IdeError::invalid(format!("{id} is a built-in agent; change its command instead")));
|
||||
}
|
||||
if input.command.trim().is_empty() {
|
||||
let base = match input.base.as_deref() {
|
||||
Some(base) => {
|
||||
Some(builtin_spec(base).ok_or_else(|| IdeError::invalid(format!("{base} is not a built-in agent")))?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let inherits = input.command.trim().is_empty();
|
||||
if inherits && base.is_none() {
|
||||
return Err(IdeError::invalid("the agent command must not be empty"));
|
||||
}
|
||||
if inherits && !input.args.is_empty() {
|
||||
return Err(IdeError::invalid("an agent without its own command takes no arguments"));
|
||||
}
|
||||
let _lock = lock_custom_agents(custom_dir)?;
|
||||
let file = custom_dir.join(format!("{id}.toml"));
|
||||
if file.try_exists()? {
|
||||
@@ -811,8 +859,9 @@ pub(crate) fn save_custom(
|
||||
}
|
||||
CustomAgent {
|
||||
name: Some(input.name.clone()),
|
||||
driver: Driver::Acp,
|
||||
command: input.command.clone(),
|
||||
driver: base.as_ref().filter(|_| !inherits).map_or(Driver::Acp, |b| b.driver),
|
||||
command: if inherits { String::new() } else { input.command.clone() },
|
||||
base: base.map(|b| b.id),
|
||||
args: input.args.clone(),
|
||||
additional_args: Vec::new(),
|
||||
env: input.env.clone(),
|
||||
@@ -884,6 +933,7 @@ pub(crate) fn import_acp(
|
||||
} else {
|
||||
CustomAgent {
|
||||
name: Some(outcome.name.clone()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: server.command,
|
||||
args: server.args,
|
||||
@@ -926,8 +976,12 @@ pub(crate) fn slugify_id(name: &str) -> String {
|
||||
pub(crate) struct CustomAgent {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
/// The built-in agent this one is an instance of; without a `command` it launches as the base does.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub base: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Driver::is_acp")]
|
||||
pub driver: Driver,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub command: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub args: Vec<String>,
|
||||
@@ -956,9 +1010,13 @@ impl Driver {
|
||||
|
||||
impl CustomAgent {
|
||||
pub(crate) fn read(path: &Path) -> Result<Self, String> {
|
||||
std::fs::read_to_string(path)
|
||||
let agent = std::fs::read_to_string(path)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|t| toml::from_str::<CustomAgent>(&t).map_err(|e| e.to_string()))
|
||||
.and_then(|t| toml::from_str::<CustomAgent>(&t).map_err(|e| e.to_string()))?;
|
||||
if agent.command.is_empty() && agent.base.is_none() {
|
||||
return Err("missing field `command`".into());
|
||||
}
|
||||
Ok(agent)
|
||||
}
|
||||
|
||||
/// Writes the file atomically (a reader never sees half of it).
|
||||
@@ -1030,7 +1088,8 @@ fn forget_env(secrets: Option<&dyn EnvSecrets>, id: &str, keep: &[String]) {
|
||||
}
|
||||
|
||||
/// Built-in agents, then the `*.toml` agents of `custom_dir`; a custom agent with a
|
||||
/// built-in id replaces it.
|
||||
/// built-in id replaces it. Instances of a built-in (`base`) are resolved last, against
|
||||
/// the built-in as its own file left it, so file order does not matter.
|
||||
pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>) -> Vec<ProviderSpec> {
|
||||
let mut specs = builtins();
|
||||
let mut files: Vec<PathBuf> = custom_dir
|
||||
@@ -1042,6 +1101,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
.filter(|p| p.extension().is_some_and(|e| e == "toml"))
|
||||
.collect();
|
||||
files.sort();
|
||||
let mut instances = Vec::new();
|
||||
for path in files {
|
||||
let Some(id) = path.file_stem().and_then(|s| s.to_str()).map(str::to_owned) else { continue };
|
||||
let explicit_driver = std::fs::read_to_string(&path)
|
||||
@@ -1055,6 +1115,18 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Some(base) = agent.base.clone() {
|
||||
if builtin_spec(&id).is_some() {
|
||||
tracing::warn!("skipping agent {}: a built-in agent cannot have a base", path.display());
|
||||
} else if agent.registry.is_some() {
|
||||
tracing::warn!("skipping agent {}: an ACP Registry install cannot have a base", path.display());
|
||||
} else if builtin_spec(&base).is_none() {
|
||||
tracing::warn!("skipping agent {}: {base} is not a built-in agent", path.display());
|
||||
} else {
|
||||
instances.push((id, agent));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let env: Vec<(String, String)> = agent.env.into_iter().collect();
|
||||
let source = match agent.registry {
|
||||
Some(r) => AgentSource::Registry { version: r.version, update: None },
|
||||
@@ -1070,6 +1142,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
env,
|
||||
login_hint: "Sign in with the agent's own command line first.".into(),
|
||||
source,
|
||||
base: None,
|
||||
id,
|
||||
};
|
||||
match specs.iter_mut().find(|s| s.id == spec.id) {
|
||||
@@ -1097,6 +1170,34 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
None => specs.push(spec),
|
||||
}
|
||||
}
|
||||
for (id, agent) in instances {
|
||||
let base = agent.base.expect("instances have a base");
|
||||
let Some(base_spec) = specs.iter().find(|s| s.id == base && s.base.is_none()) else { continue };
|
||||
let (driver, command, args) = if agent.command.is_empty() {
|
||||
(base_spec.driver, base_spec.command.clone(), base_spec.args.clone())
|
||||
} else {
|
||||
(agent.driver, agent.command, agent.args)
|
||||
};
|
||||
let login_hint = base_spec.login_hint.clone();
|
||||
// Copies of one agent follow it, in the order of their file names.
|
||||
let at = specs.iter().rposition(|s| s.base_id() == base).map_or(specs.len(), |i| i + 1);
|
||||
specs.insert(
|
||||
at,
|
||||
ProviderSpec {
|
||||
name: agent.name.unwrap_or_else(|| id.clone()),
|
||||
driver,
|
||||
command,
|
||||
managed_cli: None,
|
||||
args,
|
||||
additional_args_len: 0,
|
||||
env: agent.env.into_iter().collect(),
|
||||
login_hint,
|
||||
source: AgentSource::Custom,
|
||||
base: Some(base),
|
||||
id,
|
||||
},
|
||||
);
|
||||
}
|
||||
specs
|
||||
}
|
||||
|
||||
@@ -1169,6 +1270,7 @@ mod tests {
|
||||
}
|
||||
CustomAgent {
|
||||
name: Some("Google Antigravity".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: bin.to_string_lossy().into_owned(),
|
||||
args: Vec::new(),
|
||||
@@ -1509,6 +1611,7 @@ mod tests {
|
||||
let file = dir.path().join("copilot.toml");
|
||||
CustomAgent {
|
||||
name: Some("GitHub Copilot".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/tools/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
@@ -1566,6 +1669,7 @@ mod tests {
|
||||
let path = dir.path().join("codex.toml");
|
||||
CustomAgent {
|
||||
name: None,
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "amp".into(),
|
||||
args: vec![],
|
||||
@@ -1592,6 +1696,7 @@ mod tests {
|
||||
for field in ["name", "driver", "args", "env", "unnamed"] {
|
||||
let mut agent = CustomAgent {
|
||||
name: Some("Claude Code".into()),
|
||||
base: None,
|
||||
driver: Driver::Claude,
|
||||
command: "/old/claude".into(),
|
||||
args: vec![],
|
||||
@@ -1646,6 +1751,7 @@ mod tests {
|
||||
let path = dir.path().join("agents").join("amp-acp.toml");
|
||||
let agent = CustomAgent {
|
||||
name: Some("Amp".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/data/agents/tools/amp-acp/0.10.0/amp-acp".into(),
|
||||
args: vec!["acp".into()],
|
||||
@@ -1666,6 +1772,7 @@ mod tests {
|
||||
CustomAgentInput {
|
||||
id: id.into(),
|
||||
name: "Mine".into(),
|
||||
base: None,
|
||||
command: "/opt/mine".into(),
|
||||
args: vec!["acp".into()],
|
||||
env: BTreeMap::from([("K".to_owned(), "v".to_owned())]),
|
||||
@@ -1887,4 +1994,188 @@ github.com
|
||||
assert_eq!(launch.env.get("GH_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("COPILOT_GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
}
|
||||
|
||||
fn write_agent(dir: &Path, id: &str, text: &str) {
|
||||
std::fs::write(dir.join(format!("{id}.toml")), text).unwrap();
|
||||
}
|
||||
|
||||
fn spec_of(dir: &Path, id: &str) -> Option<ProviderSpec> {
|
||||
load(Some(dir), None).into_iter().find(|s| s.id == id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_inherit_the_base_launch_whatever_the_file_order() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let instance =
|
||||
"base = \"claude\"\nname = \"Claude Work\"\n[env]\nCLAUDE_CONFIG_DIR = \"/home/me/.claude-work\"\n";
|
||||
// `a-claude` sorts before the base's own file, `z-claude` after it.
|
||||
write_agent(dir.path(), "a-claude", instance);
|
||||
write_agent(dir.path(), "z-claude", instance);
|
||||
write_agent(
|
||||
dir.path(),
|
||||
"claude",
|
||||
"name = \"Claude Code\"\ndriver = \"claude\"\ncommand = \"/opt/claude\"\n[env]\nB = \"1\"\n",
|
||||
);
|
||||
let builtin = builtin_spec("claude").unwrap();
|
||||
for id in ["a-claude", "z-claude"] {
|
||||
let spec = spec_of(dir.path(), id).unwrap();
|
||||
assert_eq!((spec.driver, spec.command.as_str()), (Driver::Claude, "/opt/claude"), "{id}");
|
||||
assert_eq!(spec.args, builtin.args);
|
||||
assert_eq!(spec.env, [("CLAUDE_CONFIG_DIR".to_owned(), "/home/me/.claude-work".to_owned())]);
|
||||
assert_eq!(spec.login_hint, builtin.login_hint);
|
||||
assert_eq!(
|
||||
(&spec.source, spec.base.as_deref(), spec.base_id()),
|
||||
(&AgentSource::Custom, Some("claude"), "claude")
|
||||
);
|
||||
assert_eq!(spec.name, "Claude Work");
|
||||
}
|
||||
std::fs::remove_file(dir.path().join("claude.toml")).unwrap();
|
||||
assert_eq!(spec_of(dir.path(), "a-claude").unwrap().command, "claude");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_follow_their_base_in_the_list() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(dir.path(), "z-claude", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "a-claude", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "codex-2", "base = \"codex\"\n");
|
||||
write_agent(dir.path(), "mine", "command = \"/opt/mine\"\n");
|
||||
let ids: Vec<String> = load(Some(dir.path()), None).into_iter().map(|s| s.id).collect();
|
||||
let at = |id: &str| ids.iter().position(|i| i == id).unwrap();
|
||||
assert_eq!((at("a-claude"), at("z-claude")), (at("claude") + 1, at("claude") + 2));
|
||||
assert_eq!(at("codex-2"), at("codex") + 1);
|
||||
assert_eq!(at("mine"), ids.len() - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instance_with_its_own_command_keeps_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(
|
||||
dir.path(),
|
||||
"codex-2",
|
||||
"base = \"codex\"\ndriver = \"codex\"\ncommand = \"/opt/codex2\"\nargs = [\"app-server\", \"-v\"]\n",
|
||||
);
|
||||
write_agent(dir.path(), "codex", "driver = \"codex\"\ncommand = \"/opt/codex\"\nargs = [\"app-server\"]\n");
|
||||
let spec = spec_of(dir.path(), "codex-2").unwrap();
|
||||
assert_eq!((spec.driver, spec.command.as_str()), (Driver::Codex, "/opt/codex2"));
|
||||
assert_eq!(spec.args, ["app-server", "-v"]);
|
||||
assert_eq!(spec.base.as_deref(), Some("codex"));
|
||||
assert_eq!(spec.login_hint, builtin_spec("codex").unwrap().login_hint);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_instances_are_skipped() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(dir.path(), "unknown-base", "base = \"nope\"\n");
|
||||
write_agent(dir.path(), "first", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "chained", "base = \"first\"\n");
|
||||
write_agent(dir.path(), "codex", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "no-command", "name = \"Nothing\"\n");
|
||||
let specs = load(Some(dir.path()), None);
|
||||
let ids: Vec<&str> = specs.iter().filter(|s| s.source != AgentSource::Builtin).map(|s| s.id.as_str()).collect();
|
||||
assert_eq!(ids, ["first"]);
|
||||
assert_eq!(specs.iter().find(|s| s.id == "codex").unwrap(), &builtin_spec("codex").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_custom_writes_instances() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let instance = |id: &str, base: &str| CustomAgentInput {
|
||||
base: Some(base.into()),
|
||||
command: String::new(),
|
||||
args: Vec::new(),
|
||||
..custom_input(id)
|
||||
};
|
||||
save_custom(dir.path(), None, &instance("work", "claude")).unwrap();
|
||||
let text = std::fs::read_to_string(dir.path().join("work.toml")).unwrap();
|
||||
assert!(text.contains("base = \"claude\"") && !text.contains("command") && !text.contains("driver"), "{text}");
|
||||
let spec = spec_of(dir.path(), "work").unwrap();
|
||||
assert_eq!(
|
||||
(spec.driver, spec.command.as_str(), spec.base.as_deref()),
|
||||
(Driver::Claude, "claude", Some("claude"))
|
||||
);
|
||||
|
||||
save_custom(dir.path(), None, &CustomAgentInput { command: "/opt/codex".into(), ..instance("own", "codex") })
|
||||
.unwrap();
|
||||
let own = spec_of(dir.path(), "own").unwrap();
|
||||
assert_eq!((own.driver, own.command.as_str()), (Driver::Codex, "/opt/codex"));
|
||||
|
||||
save_custom(dir.path(), None, &instance("work", "claude")).unwrap_err();
|
||||
save_custom(dir.path(), None, &instance("other", "nope")).unwrap_err();
|
||||
save_custom(dir.path(), None, &instance("other", "work")).unwrap_err();
|
||||
save_custom(dir.path(), None, &instance("codex", "claude")).unwrap_err();
|
||||
save_custom(dir.path(), None, &CustomAgentInput { args: vec!["x".into()], ..instance("other", "claude") })
|
||||
.unwrap_err();
|
||||
assert!(!dir.path().join("other.toml").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_describe_their_base() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(dir.path(), "work", "base = \"claude\"\n");
|
||||
save_custom(dir.path(), None, &custom_input("mine")).unwrap();
|
||||
let info = |id: &str| describe(&spec_of(dir.path(), id).unwrap());
|
||||
let work = info("work");
|
||||
assert_eq!(work.base.as_deref(), Some("claude"));
|
||||
assert!(!work.can_duplicate && !work.can_check_cli_update && !work.command_editable);
|
||||
assert_eq!(work.command_read_only_reason, Some(AgentCommandReadOnlyReason::CustomAgent));
|
||||
assert_eq!(work.login_hint.as_deref(), Some("Run `claude` in a terminal and sign in."));
|
||||
let claude = info("claude");
|
||||
assert!(claude.can_duplicate && claude.base.is_none());
|
||||
let mine = info("mine");
|
||||
assert!(!mine.can_duplicate && mine.base.is_none());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn instances_sign_in_with_their_own_environment() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bin = dir.path().join("claude");
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
write_agent(dir.path(), "claude", &format!("driver = \"claude\"\ncommand = {:?}\n", bin.to_string_lossy()));
|
||||
write_agent(dir.path(), "work", "base = \"claude\"\n[env]\nCLAUDE_CONFIG_DIR = \"/home/me/.claude-work\"\n");
|
||||
let spec = spec_of(dir.path(), "work").unwrap();
|
||||
assert!(spec.can_sign_in(dir.path(), None));
|
||||
let launch = spec.login_launch(dir.path(), None).unwrap();
|
||||
assert_eq!(launch.program, bin);
|
||||
assert!(launch.args.is_empty());
|
||||
assert_eq!(launch.env.get("CLAUDE_CONFIG_DIR").map(String::as_str), Some("/home/me/.claude-work"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_environment_is_set_and_forgotten_through_the_secrets() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let secrets = MemorySecrets::default();
|
||||
let s = Some(&secrets as &dyn EnvSecrets);
|
||||
let instance = CustomAgentInput {
|
||||
base: Some("copilot".into()),
|
||||
command: String::new(),
|
||||
args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
..custom_input("copilot-work")
|
||||
};
|
||||
save_custom(dir.path(), s, &instance).unwrap();
|
||||
let env = BTreeMap::from([
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.to_owned(), "octo-work".to_owned()),
|
||||
("COPILOT_HOME".to_owned(), "/home/me/.copilot-work".to_owned()),
|
||||
]);
|
||||
set_builtin_env(dir.path(), s, "copilot-work", env.clone()).unwrap();
|
||||
let text = std::fs::read_to_string(dir.path().join("copilot-work.toml")).unwrap();
|
||||
assert!(text.contains("base = \"copilot\"") && !text.contains("octo-work"), "{text}");
|
||||
let spec = load(Some(dir.path()), s).into_iter().find(|p| p.id == "copilot-work").unwrap();
|
||||
assert_eq!(describe(&spec).env, env);
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("octo-work"));
|
||||
assert!(load(Some(dir.path()), s).iter().find(|p| p.id == "copilot").unwrap().env.is_empty());
|
||||
|
||||
save_custom(dir.path(), s, &custom_input("mine")).unwrap();
|
||||
set_builtin_env(dir.path(), s, "mine", env.clone()).unwrap_err();
|
||||
write_agent(dir.path(), "bad-base", "base = \"nope\"\n");
|
||||
set_builtin_env(dir.path(), s, "bad-base", env).unwrap_err();
|
||||
assert!(secrets.keys("agent/bad-base/").is_empty());
|
||||
remove_custom(dir.path(), s, "copilot-work").unwrap();
|
||||
assert!(!dir.path().join("copilot-work.toml").exists());
|
||||
assert!(secrets.keys("agent/copilot-work/").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -587,6 +587,7 @@ fn install_entry_with(
|
||||
}
|
||||
let agent = CustomAgent {
|
||||
name: Some(entry.name.clone()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: exe.to_string_lossy().into_owned(),
|
||||
args,
|
||||
@@ -985,6 +986,7 @@ mod tests {
|
||||
let entries = parse(INDEX).unwrap();
|
||||
let installed = |id: &str, version: &str| CustomAgent {
|
||||
name: None,
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/x".into(),
|
||||
args: vec![],
|
||||
@@ -1222,6 +1224,7 @@ esac
|
||||
|
||||
CustomAgent {
|
||||
name: Some("GitHub Copilot".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/data/tools/copilot/1.0.104/node_modules/.bin/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
|
||||
@@ -1395,6 +1395,31 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
assert_eq!(names(mgr_a.providers().into_iter().find(|p| p.id == "claude").unwrap().commands), ["review"]);
|
||||
}
|
||||
|
||||
fn instance_of(id: &str, base: &str) -> crate::CustomAgentInput {
|
||||
crate::CustomAgentInput {
|
||||
id: id.into(),
|
||||
name: id.into(),
|
||||
base: Some(base.into()),
|
||||
command: String::new(),
|
||||
args: Vec::new(),
|
||||
env: std::collections::BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn instances_offer_the_commands_of_their_base() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager_at(tmp.path(), &tmp.path().join("models.json"), agent);
|
||||
mgr.save_custom_agent(instance_of("codex-work", "codex")).unwrap();
|
||||
mgr.reload_providers();
|
||||
assert_eq!((mgr.base_provider_id("codex-work"), mgr.base_provider_id("custom")), ("codex".into(), "custom".into()));
|
||||
let names = |commands: Vec<AgentCommand>| commands.into_iter().map(|c| c.name).collect::<Vec<_>>();
|
||||
let instance = names(mgr.commands("codex-work", None).await.unwrap());
|
||||
assert!(instance.iter().any(|name| name == "review"), "{instance:?}");
|
||||
assert_eq!(instance, names(mgr.commands("codex", None).await.unwrap()));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metadata() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -2272,14 +2297,25 @@ async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_ag
|
||||
assert_eq!(calls(&agent), ["session/load", "session/new", "session/prompt"]);
|
||||
}
|
||||
|
||||
/// A locked Codex recording can be forked without resuming it or moving its writer between tasks.
|
||||
/// A locked Codex recording can be forked without resuming it or moving its writer between tasks,
|
||||
/// also when the task runs an instance of Codex.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
|
||||
for provider in ["codex", "codex-work"] {
|
||||
codex_writer_conflict_forks_on_a_new_connection(provider).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn codex_writer_conflict_forks_on_a_new_connection(provider: &str) {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let task = {
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
if provider != "codex" {
|
||||
mgr.save_custom_agent(instance_of(provider, "codex")).unwrap();
|
||||
mgr.reload_providers();
|
||||
}
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "codex".into(), ..Default::default() })
|
||||
.create(NewAgentTask { prompt: text("again"), provider: provider.into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
@@ -4229,6 +4265,59 @@ async fn cursor_approval_switch_resolves_pending_and_survives_restart() {
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
/// Saving or dropping a Cursor instance on disk is reflected on the very first `providers()` call.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn new_cursor_instance_has_approval_option_on_first_providers_call() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
// Saved through the API: base_provider_id and providers() see it immediately without reload_providers().
|
||||
mgr.save_custom_agent(instance_of("cursor-work", "cursor")).unwrap();
|
||||
assert_eq!(mgr.base_provider_id("cursor-work"), "cursor");
|
||||
// Hand-written on disk: providers() updates its cache before mapping per-provider options.
|
||||
std::fs::write(tmp.path().join("agents/cursor-disk.toml"), "base = \"cursor\"\nname = \"Cursor Disk\"\n").unwrap();
|
||||
let list = mgr.providers();
|
||||
for id in ["cursor-work", "cursor-disk"] {
|
||||
let info = list.iter().find(|p| p.id == id).unwrap_or_else(|| panic!("{id}"));
|
||||
assert!(info.config.iter().any(|o| o.id == config::CURSOR_APPROVAL), "{id}: {:?}", info.config);
|
||||
}
|
||||
}
|
||||
|
||||
/// An instance of Cursor offers Cursor's client-side approval option, and a scheduled turn
|
||||
/// clamps it as it clamps Cursor's own.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn instances_take_the_approval_options_and_automation_clamp_of_their_base() {
|
||||
for provider in ["cursor", "cursor-work"] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
mgr.save_custom_agent(instance_of("cursor-work", "cursor")).unwrap();
|
||||
mgr.reload_providers();
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: provider.into(),
|
||||
config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }],
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let approval = || {
|
||||
let snapshot = mgr.task_snapshot(&task.id).unwrap();
|
||||
snapshot.config.iter().find(|o| o.id == config::CURSOR_APPROVAL).and_then(|o| o.current.clone())
|
||||
};
|
||||
assert_eq!(approval().as_deref(), Some("bypass"), "{provider}");
|
||||
let meta = ScheduledTurnMeta {
|
||||
permissions: Some(automation::AutomationPermissionMode::Default),
|
||||
..Default::default()
|
||||
};
|
||||
mgr.prompt_scheduled(&task.id, text("again"), meta).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(approval().as_deref(), Some("ask"), "{provider}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn bypass_approvals_keeps_both_question_dialects_pending_but_allows_permissions() {
|
||||
for prompt in ["ask", "qwen ask"] {
|
||||
|
||||
@@ -103,9 +103,19 @@ pub fn load_linked_with_jdk(
|
||||
let mut m = maven::load_with_linked_jdk(root, repo, &profiles, maven_jdk_version, &settings.linked_projects);
|
||||
maven::UnlinkedProjects::from_model(&m, settings).filter(&mut m);
|
||||
// The user settings' profiles can be chosen too (`-P` applies to them as well).
|
||||
for p in maven::user_settings_file(root, settings).map(|f| maven::settings_profiles(&f)).unwrap_or_default() {
|
||||
if !m.profiles.iter().any(|x| x.id == p.id) {
|
||||
m.profiles.push(p);
|
||||
if let Some(settings_file) = maven::user_settings_file(root, settings) {
|
||||
for p in maven::settings_profiles(&settings_file) {
|
||||
if let Some(existing) = m.profiles.iter_mut().find(|x| x.id == p.id) {
|
||||
existing.active_by_default |= p.active_by_default;
|
||||
} else {
|
||||
m.profiles.push(p);
|
||||
}
|
||||
}
|
||||
let active_in_settings = maven::settings_active_profiles(&settings_file);
|
||||
for existing in &mut m.profiles {
|
||||
if active_in_settings.iter().any(|id| id == &existing.id) {
|
||||
existing.active_by_default = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
sync::apply_maven_cache(root, cache_dir, &mut m);
|
||||
@@ -358,6 +368,49 @@ mod tests {
|
||||
assert!(modules(&settings).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_xml_active_profiles_mark_pom_profiles_active_by_default() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::create_dir(root.join("child")).unwrap();
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
r#"<project><groupId>demo</groupId><artifactId>root</artifactId><version>1.0</version><packaging>pom</packaging>
|
||||
<modules><module>child</module></modules>
|
||||
<profiles>
|
||||
<profile><id>test3</id></profile>
|
||||
<profile><id>dev</id><activation><activeByDefault>TRUE</activeByDefault></activation></profile>
|
||||
</profiles></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
root.join("child/pom.xml"),
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>root</artifactId><version>1.0</version></parent>
|
||||
<artifactId>child</artifactId>
|
||||
<profiles><profile><id>child-default</id><activation><activeByDefault>true</activeByDefault></activation></profile></profiles></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let settings_xml = root.join("settings.xml");
|
||||
std::fs::write(
|
||||
&settings_xml,
|
||||
r#"<settings><activeProfiles><activeProfile>test3</activeProfile></activeProfiles></settings>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let cache = root.join("cache");
|
||||
let settings = ide_core::settings::MavenSettings {
|
||||
user_settings: settings_xml.to_string_lossy().into_owned(),
|
||||
..Default::default()
|
||||
};
|
||||
let model = load_linked(root, &cache, None, &settings, &Default::default()).maven.unwrap();
|
||||
let flags: Vec<(&str, bool)> = model.profiles.iter().map(|p| (p.id.as_str(), p.active_by_default)).collect();
|
||||
assert!(
|
||||
flags.contains(&("test3", true)),
|
||||
"activeProfile from settings.xml marks POM profile active: {flags:?}"
|
||||
);
|
||||
assert!(flags.contains(&("dev", true)), "case-insensitive activeByDefault: {flags:?}");
|
||||
assert!(flags.contains(&("child-default", true)), "child module activeByDefault: {flags:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_build_systems_and_build_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -437,7 +437,9 @@ fn read_raw(project: &Element) -> RawPom {
|
||||
for p in project.list("profiles", "profile") {
|
||||
let mut profile = RawProfile {
|
||||
id: p.text_of("id").unwrap_or_else(|| "default".into()),
|
||||
active_by_default: p.at("activation/activeByDefault").is_some_and(|a| a.text.trim() == "true"),
|
||||
active_by_default: p
|
||||
.at("activation/activeByDefault")
|
||||
.is_some_and(|a| a.text.trim().eq_ignore_ascii_case("true")),
|
||||
activation_jdk: p.at("activation/jdk").map(|jdk| jdk.text.trim().to_owned()).filter(|jdk| !jdk.is_empty()),
|
||||
modules: module_names(p),
|
||||
properties: read_properties(p.child("properties")),
|
||||
@@ -601,12 +603,25 @@ pub fn settings_profiles(settings: &Path) -> Vec<MavenProfile> {
|
||||
if profiles.iter().any(|p| p.id == id) {
|
||||
continue;
|
||||
}
|
||||
let by_default = profile.at("activation/activeByDefault").is_some_and(|e| e.text.trim() == "true");
|
||||
let by_default =
|
||||
profile.at("activation/activeByDefault").is_some_and(|e| e.text.trim().eq_ignore_ascii_case("true"));
|
||||
profiles.push(MavenProfile { active_by_default: by_default || active.contains(&id), id, ..Default::default() });
|
||||
}
|
||||
profiles
|
||||
}
|
||||
|
||||
/// Profile IDs listed under `<activeProfiles>` in `settings.xml` (may refer to profiles defined in POMs).
|
||||
pub fn settings_active_profiles(settings: &Path) -> Vec<String> {
|
||||
let Some(root) = xml::read_text(settings).as_deref().and_then(xml::parse) else {
|
||||
return Vec::new();
|
||||
};
|
||||
root.list("activeProfiles", "activeProfile")
|
||||
.iter()
|
||||
.map(|e| e.text.trim().to_owned())
|
||||
.filter(|id| !id.is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `<localRepository>` of a settings file, when it names one: the repository a build
|
||||
/// with `-s <file>` resolves into, which is not necessarily the user's default.
|
||||
pub fn local_repository_of(settings: &Path) -> Option<PathBuf> {
|
||||
@@ -1708,7 +1723,9 @@ pub fn load_with_linked_jdk(
|
||||
|
||||
// The project can activate the profiles of its own POM and its ancestors'.
|
||||
for (id, active) in &ctx.profiles {
|
||||
if !model.profiles.iter().any(|x| x.id == *id) {
|
||||
if let Some(existing) = model.profiles.iter_mut().find(|x| x.id == *id) {
|
||||
existing.active_by_default |= *active;
|
||||
} else {
|
||||
model.profiles.push(MavenProfile { id: id.clone(), active_by_default: *active, ..Default::default() });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,6 +86,8 @@ pub struct EditorAppearanceSettings {
|
||||
pub indent_guides: bool,
|
||||
/// Colour indent guides by depth (`--syn-rainbow-*`), while `indent_guides` is on.
|
||||
pub rainbow_indent_guides: bool,
|
||||
/// Also tint each indent level's whitespace in its rainbow colour, while `rainbow_indent_guides` is on.
|
||||
pub rainbow_indent_guides_fill: bool,
|
||||
/// Right margin and visual guides from Code Style.
|
||||
pub hard_wrap_guides: bool,
|
||||
pub intention_bulb: bool,
|
||||
@@ -114,6 +116,7 @@ impl Default for EditorAppearanceSettings {
|
||||
whitespace_trailing: true,
|
||||
indent_guides: true,
|
||||
rainbow_indent_guides: false,
|
||||
rainbow_indent_guides_fill: false,
|
||||
hard_wrap_guides: true,
|
||||
intention_bulb: true,
|
||||
render_doc_comments: false,
|
||||
|
||||
@@ -1087,6 +1087,8 @@ pub struct GeneralSettings {
|
||||
pub close_tabs_with_window: bool,
|
||||
/// Where Open… puts a project while one is open: `ask` | `new` | `same` | `attach`.
|
||||
pub open_project_in: String,
|
||||
/// What closing a remote development window does with its backend: `ask` | `keep` | `stop`.
|
||||
pub close_remote_window: String,
|
||||
/// Initial folder of the Open / Clone dialogs; empty = the OS default.
|
||||
pub default_project_directory: String,
|
||||
/// Save all files after `idle_seconds` without input.
|
||||
@@ -1117,6 +1119,7 @@ impl Default for GeneralSettings {
|
||||
close_without_welcome: false,
|
||||
close_tabs_with_window: false,
|
||||
open_project_in: "ask".into(),
|
||||
close_remote_window: "ask".into(),
|
||||
default_project_directory: String::new(),
|
||||
save_on_idle: false,
|
||||
idle_seconds: 15,
|
||||
|
||||
@@ -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>>>,
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -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" {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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)?;
|
||||
}
|
||||
|
||||
@@ -803,6 +803,10 @@ fn shell_invocation(shell: Option<&str>, line: &str) -> (String, Vec<String>) {
|
||||
"cmd" => (line.to_owned(), Vec::new()),
|
||||
"pwsh" | "powershell" => {
|
||||
args.retain(|a| a != "-l");
|
||||
// As in the terminal: script shims such as npm.ps1 run under the default policy.
|
||||
if cfg!(windows) {
|
||||
args.extend(["-ExecutionPolicy".to_owned(), "Bypass".to_owned()]);
|
||||
}
|
||||
args.extend(["-NoLogo".to_owned(), "-Command".to_owned(), line.to_owned()]);
|
||||
(program, args)
|
||||
}
|
||||
@@ -1141,7 +1145,12 @@ mod tests {
|
||||
assert_eq!(shell_invocation(Some("/bin/zsh"), "ls -a").1, ["-l", "-c", "ls -a"]);
|
||||
assert_eq!(shell_invocation(Some("/bin/bash --norc"), "ls").1, ["--norc", "-c", "ls"]);
|
||||
assert_eq!(shell_invocation(Some("/bin/tcsh"), "ls").1, ["-c", "ls"]);
|
||||
assert_eq!(shell_invocation(Some("/usr/bin/pwsh"), "ls").1, ["-NoLogo", "-Command", "ls"]);
|
||||
let pwsh: &[&str] = if cfg!(windows) {
|
||||
&["-ExecutionPolicy", "Bypass", "-NoLogo", "-Command", "ls"]
|
||||
} else {
|
||||
&["-NoLogo", "-Command", "ls"]
|
||||
};
|
||||
assert_eq!(shell_invocation(Some("/usr/bin/pwsh"), "ls").1, pwsh);
|
||||
assert_eq!(shell_invocation(Some("cmd.exe"), "dir /b"), ("dir /b".to_owned(), Vec::new()));
|
||||
}
|
||||
|
||||
|
||||
@@ -939,8 +939,10 @@ impl Walk {
|
||||
continue;
|
||||
}
|
||||
let Ok(in_base) = entry.path.strip_prefix(base) else { continue };
|
||||
let in_base = in_base.to_string_lossy().replace('\\', "/");
|
||||
let mask = self.excludes.iter().find(|(b, _)| b == base).map(|(_, m)| m);
|
||||
if mask.is_some_and(|m| !m.matches(&in_base.to_string_lossy().replace('\\', "/"))) {
|
||||
if mask.is_some_and(|m| !m.matches(&in_base) || (entry.kind == EntryKind::Dir && m.excludes_dir(&in_base)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match entry.kind {
|
||||
|
||||
@@ -142,8 +142,8 @@ pub fn agent_set_additional_args(host: &Host, window: &str, id: String, args: Ve
|
||||
host.project(window)?.agents.set_builtin_additional_args(&id, args)
|
||||
}
|
||||
|
||||
/// Environment variables built-in agent `id` starts with (saved in its agent file);
|
||||
/// an empty map clears them.
|
||||
/// Environment variables built-in agent `id`, or an instance of one, starts with (saved in
|
||||
/// its agent file); an empty map clears them.
|
||||
#[command(trust = trusted)]
|
||||
pub fn agent_set_env(
|
||||
host: &Host,
|
||||
@@ -250,6 +250,42 @@ fn spawn_login_pty(
|
||||
)
|
||||
}
|
||||
|
||||
async fn resolve_login_launch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: &str,
|
||||
) -> IdeResult<(std::path::PathBuf, LoginLaunch, String)> {
|
||||
let agent = id.to_owned();
|
||||
match host.project(window) {
|
||||
Ok(project) => {
|
||||
let root = project.root.clone();
|
||||
let agents = project.agents.clone();
|
||||
let base = agents.base_provider_id(&agent);
|
||||
let launch = host.blocking(move || agents.login_launch(&agent)).await?;
|
||||
Ok((root, launch, base))
|
||||
}
|
||||
Err(_) => {
|
||||
let custom_dir = host.config_dir.join("agents");
|
||||
let secrets = host.agent_secrets.clone();
|
||||
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
|
||||
let cwd_for_lookup = cwd.clone();
|
||||
let (launch, base) = host
|
||||
.blocking(move || {
|
||||
let base = ide_agent::base_provider_id_without_project(Some(&custom_dir), &agent);
|
||||
ide_agent::login_launch_without_project(
|
||||
Some(&custom_dir),
|
||||
Some(secrets.as_ref()),
|
||||
&cwd_for_lookup,
|
||||
&agent,
|
||||
)
|
||||
.map(|launch| (launch, base))
|
||||
})
|
||||
.await?;
|
||||
Ok((cwd, launch, base))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts agent `id`'s interactive sign-in flow in an IDE-managed PTY and streams its output and exit code.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn agent_login_spawn(
|
||||
@@ -261,28 +297,9 @@ pub async fn agent_login_spawn(
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let agent = id.clone();
|
||||
let (cwd, mut launch) = match host.project(window) {
|
||||
Ok(project) => {
|
||||
let root = project.root.clone();
|
||||
let agents = project.agents.clone();
|
||||
let launch = host.blocking(move || agents.login_launch(&agent)).await?;
|
||||
(root, launch)
|
||||
}
|
||||
Err(_) => {
|
||||
let custom_dir = host.config_dir.join("agents");
|
||||
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
|
||||
let cwd_for_lookup = cwd.clone();
|
||||
let launch = host
|
||||
.blocking(move || {
|
||||
ide_agent::login_launch_without_project(Some(&custom_dir), None, &cwd_for_lookup, &agent)
|
||||
})
|
||||
.await?;
|
||||
(cwd, launch)
|
||||
}
|
||||
};
|
||||
let (cwd, mut launch, base) = resolve_login_launch(host, window, &id).await?;
|
||||
apply_remote_login_env(host, &cwd, false, &mut launch);
|
||||
use_device_auth(host.environment.is_remote(), &id, &mut launch.args);
|
||||
use_device_auth(host.environment.is_remote(), &base, &mut launch.args);
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
@@ -306,8 +323,8 @@ pub async fn agent_gh_login_spawn(
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
/// Saves a new custom ACP agent through its agent file; refuses built-in and
|
||||
/// ACP Registry ids and taken ids.
|
||||
/// Saves a new custom ACP agent, or an instance of a built-in agent, through its agent
|
||||
/// file; refuses built-in and ACP Registry ids and taken ids.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_custom_save(host: &Host, window: &str, input: CustomAgentInput) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
@@ -1890,11 +1907,10 @@ pub async fn agent_memory_set_auto(
|
||||
) -> IdeResult<AgentMemoryCatalog> {
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
let (mut user, mut workspace) = memory_settings_layers(host, project.as_ref());
|
||||
let prov_key = provider
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| ide_agent::memory::normalize_provider_id(s).to_owned());
|
||||
let prov_key = provider.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(|s| {
|
||||
let base = project.as_ref().map(|p| p.agents.base_provider_id(s));
|
||||
ide_agent::memory::normalize_provider_id(base.as_deref().unwrap_or(s)).to_owned()
|
||||
});
|
||||
let apply = |layer: &mut AgentMemorySettings| -> bool {
|
||||
match &prov_key {
|
||||
None => {
|
||||
@@ -2887,6 +2903,45 @@ mod tests {
|
||||
assert!(!ssh_env.contains_key("GH_BROWSER"));
|
||||
assert!(!ssh_env.contains_key("GLAMOUR_STYLE"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn resolve_login_launch_without_project_reads_instance_env_from_secrets() {
|
||||
ide_ssh::secrets::testing::use_memory_store();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = Host::new(crate::HostConfig {
|
||||
config_dir: tmp.path().join("config"),
|
||||
data_dir: tmp.path().join("data"),
|
||||
local_data_dir: tmp.path().join("data"),
|
||||
languages: std::sync::Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: std::sync::Arc::default(),
|
||||
sink_for: Box::new(|_| std::sync::Arc::new(ide_core::NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
let bin = tmp.path().join(if cfg!(windows) { "claude.cmd" } else { "claude" });
|
||||
std::fs::write(&bin, if cfg!(windows) { "@echo off\r\n" } else { "#!/bin/sh\n" }).unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let agents_dir = host.config_dir.join("agents");
|
||||
std::fs::create_dir_all(&agents_dir).unwrap();
|
||||
std::fs::write(
|
||||
agents_dir.join("claude.toml"),
|
||||
format!("driver = \"claude\"\ncommand = {:?}\n", bin.to_string_lossy()),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(agents_dir.join("claude-work.toml"), "base = \"claude\"\n[env]\nCLAUDE_CONFIG_DIR = \"\"\n")
|
||||
.unwrap();
|
||||
host.agent_secrets.set("agent/claude-work/env/CLAUDE_CONFIG_DIR", "/home/me/.claude-work").unwrap();
|
||||
|
||||
let (_, launch, base) = resolve_login_launch(&host, "no-project", "claude-work").await.unwrap();
|
||||
assert_eq!(base, "claude");
|
||||
assert_eq!(launch.program, bin);
|
||||
assert_eq!(launch.env.get("CLAUDE_CONFIG_DIR").map(String::as_str), Some("/home/me/.claude-work"));
|
||||
}
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
|
||||
@@ -2369,6 +2369,7 @@ pub async fn lsp_execute_command(host: &Host, window: &str, doc: DocId, command:
|
||||
path: snap.path.0.clone(),
|
||||
language: snap.language.0,
|
||||
selections: vec![],
|
||||
visible_lines: None,
|
||||
}),
|
||||
selected_paths: vec![snap.path.0],
|
||||
..Default::default()
|
||||
@@ -2410,6 +2411,7 @@ async fn run_plugin_server_command(
|
||||
path: snap.path.0.clone(),
|
||||
language: snap.language.0,
|
||||
selections: vec![],
|
||||
visible_lines: None,
|
||||
}),
|
||||
selected_paths: vec![snap.path.0],
|
||||
..Default::default()
|
||||
|
||||
@@ -725,13 +725,22 @@ pub async fn vcs_check_incoming(
|
||||
result
|
||||
}
|
||||
|
||||
/// Whether an editor file reached through a symlink has a tracked file at its target's HEAD.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_linked_file_has_history(host: &Host, window: &str, path: PathBuf) -> IdeResult<bool> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.linked_file_has_history(&path)).await
|
||||
}
|
||||
|
||||
/// Gutter change markers for a file, computed against its current (unsaved) text.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_line_hunks(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<LineHunk>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let text = project.text_of(&path)?;
|
||||
project.with_backend_of(&path, |r| r.line_hunks(&path, &text, false, project.vcs_encoding(&path, None)?))
|
||||
project.with_editor_backend_of(&path, |repo, repo_path| {
|
||||
let text = project.text_of(&path)?;
|
||||
repo.line_hunks(repo_path, &text, false, project.vcs_encoding(&path, None)?)
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -745,6 +754,11 @@ pub async fn vcs_staging_line_hunks(
|
||||
) -> IdeResult<Option<ide_vcs::StagingLineHunks>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
// A linked editor file uses the target's HEAD for markers, not the
|
||||
// index of a repository that might track the link itself.
|
||||
if project.linked_file_target(&path).is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
let text = project.text_of(&path)?;
|
||||
project.with_repo_of(&path, |repo| {
|
||||
repo.staging_line_hunks(
|
||||
@@ -881,14 +895,20 @@ pub async fn vcs_blame(
|
||||
// An explicit text wins (merge view annotates its side panes, not the worktree).
|
||||
blocking(move || {
|
||||
let text = text.or_else(|| project.documents.text_of(&path));
|
||||
project.with_backend_of(&path, |backend| {
|
||||
project.with_editor_backend_of(&path, |backend, repo_path| {
|
||||
let encoding = project.vcs_encoding(&path, revision.as_deref())?;
|
||||
let text = text.as_deref();
|
||||
let revision = revision.as_deref();
|
||||
if let Some(repo) = backend.as_git() {
|
||||
repo.blame_with_options(&path, text, revision, encoding, project.settings.effective().vcs.git.annotate)
|
||||
repo.blame_with_options(
|
||||
repo_path,
|
||||
text,
|
||||
revision,
|
||||
encoding,
|
||||
project.settings.effective().vcs.git.annotate,
|
||||
)
|
||||
} else {
|
||||
backend.blame(&path, text, revision, encoding)
|
||||
backend.blame(repo_path, text, revision, encoding)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -2863,8 +2883,10 @@ pub async fn vcs_add_worktree(
|
||||
});
|
||||
// A worktree below the project is a new repository: rescan so its files
|
||||
// join the status and gutter queries (the watcher picks the gitfile up
|
||||
// too, but only as a debounced event later).
|
||||
// too, but only as a debounced event later), and refresh detected roots
|
||||
// so the nested worktree is excluded from indexing and search at once.
|
||||
project.refresh_repositories();
|
||||
project.refresh_detected_roots();
|
||||
result
|
||||
})
|
||||
.await;
|
||||
@@ -2897,6 +2919,7 @@ pub async fn vcs_remove_worktree(
|
||||
)?;
|
||||
let result = project.with_repo_at(repo.as_deref(), |r| r.remove_worktree(&path, force));
|
||||
project.refresh_repositories();
|
||||
project.refresh_detected_roots();
|
||||
result
|
||||
})
|
||||
.await
|
||||
@@ -2917,6 +2940,7 @@ pub async fn vcs_move_worktree(
|
||||
check_worktree_away_from_project(&project.root, &path, "Cannot move a worktree containing the open project.")?;
|
||||
let result = project.with_repo_at(repo.as_deref(), |r| r.move_worktree(&path, &to));
|
||||
project.refresh_repositories();
|
||||
project.refresh_detected_roots();
|
||||
result
|
||||
})
|
||||
.await
|
||||
@@ -3770,6 +3794,7 @@ ide_command::domain!(
|
||||
vcs_has_hook,
|
||||
vcs_ignore_blame_revision,
|
||||
vcs_init,
|
||||
vcs_linked_file_has_history,
|
||||
vcs_line_hunks,
|
||||
vcs_staging_line_hunks,
|
||||
vcs_log,
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -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::*;
|
||||
|
||||
@@ -10,18 +10,22 @@ pub struct NavigationFiles {
|
||||
pub indexing: bool,
|
||||
pub extensions: Vec<String>,
|
||||
/// In-scope files matching `extensions`; `paths` holds the first
|
||||
/// `MAX_NAVIGATION_FILES` of them.
|
||||
/// `MAX_NAVIGATION_FILES` of them by path.
|
||||
pub total: u32,
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// 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 `in_scope` accepts, and how many it accepts in all.
|
||||
/// 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.
|
||||
fn first_in_scope(files: Vec<PathBuf>, in_scope: impl Fn(&PathBuf) -> bool, limit: usize) -> (Vec<PathBuf>, usize) {
|
||||
let mut files: Vec<_> = files.into_iter().filter(in_scope).collect();
|
||||
files.sort_unstable();
|
||||
let total = files.len();
|
||||
files.truncate(limit);
|
||||
(files, total)
|
||||
@@ -78,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,
|
||||
@@ -86,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)?;
|
||||
@@ -97,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;
|
||||
@@ -131,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()),
|
||||
@@ -156,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(())
|
||||
@@ -239,7 +306,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn discovery_keeps_the_first_in_scope_files_and_counts_them_all() {
|
||||
let files: Vec<PathBuf> = (0..7).map(|i| PathBuf::from(format!("/p/{}/f{i}.xml", i % 2))).collect();
|
||||
let files: Vec<PathBuf> = (0..7).rev().map(|i| PathBuf::from(format!("/p/{}/f{i}.xml", i % 2))).collect();
|
||||
let (kept, total) = first_in_scope(files, |p| p.starts_with("/p/0"), 3);
|
||||
// Out-of-scope files neither take a slot nor count toward the total.
|
||||
assert_eq!(total, 4);
|
||||
|
||||
@@ -12,8 +12,69 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
pub const MAX_DOCUMENT_BYTES: usize = ide_lsp::MAX_INJECTED_DOCUMENT_BYTES;
|
||||
const MAX_FILES: usize = 20_000;
|
||||
/// 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,
|
||||
@@ -235,71 +296,27 @@ 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.
|
||||
if self.navigation.lock().projects.get(&project_key).and_then(|g| g.get(plugin.id())).is_some_and(|g| {
|
||||
g.instance.ptr_eq(&Arc::downgrade(&plugin)) && g.files.len() >= MAX_FILES && !g.files.contains_key(path)
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
let (actor, activated) = self.ensure_active(&plugin, invocation.client.as_deref())?;
|
||||
if activated {
|
||||
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());
|
||||
@@ -314,16 +331,19 @@ impl PluginHost {
|
||||
if !graph.instance.ptr_eq(&Arc::downgrade(&plugin)) {
|
||||
*graph = Graph { instance: Arc::downgrade(&plugin), ..Default::default() };
|
||||
}
|
||||
if graph.files.len() >= MAX_FILES && !graph.files.contains_key(path) {
|
||||
return Err(IdeError::unavailable("navigation file limit reached"));
|
||||
}
|
||||
graph.remove(path);
|
||||
if edges_are_empty(&edges) {
|
||||
continue;
|
||||
}
|
||||
if graph.files.len() >= MAX_FILES && !graph.files.contains_key(path) {
|
||||
continue;
|
||||
}
|
||||
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"));
|
||||
}
|
||||
@@ -332,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(
|
||||
|
||||
@@ -99,6 +99,7 @@ pub fn register_builtin_points(
|
||||
registry.register(Arc::new(UiPoint::new(p::DIALOGS, ui.clone(), p::dialog)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::RUN_CONFIG_TYPES, ui.clone(), p::run_config_type)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::RUN_ANYTHING, ui.clone(), p::run_anything)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::CLONE_SOURCES, ui.clone(), p::clone_source)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::MARKER_ICONS, ui.clone(), p::marker_icon)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::FILE_ICONS, ui.clone(), p::file_icon)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::FILE_TEMPLATES, ui.clone(), p::file_template)))?;
|
||||
|
||||
@@ -463,11 +463,19 @@ pub struct PluginEditor {
|
||||
pub path: String,
|
||||
pub language: String,
|
||||
pub selections: Vec<ide_core::Range>,
|
||||
/// First and last document line on screen (0-based, inclusive); absent from older clients.
|
||||
#[serde(default)]
|
||||
pub visible_lines: Option<(u32, u32)>,
|
||||
}
|
||||
|
||||
impl PluginEditor {
|
||||
pub fn context(self) -> ide_plugin::EditorContext {
|
||||
ide_plugin::EditorContext { path: self.path.into(), language: self.language, selections: self.selections }
|
||||
ide_plugin::EditorContext {
|
||||
path: self.path.into(),
|
||||
language: self.language,
|
||||
selections: self.selections,
|
||||
visible_lines: self.visible_lines,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -110,8 +110,11 @@ pub const OVERLAYS: &str = "overlays";
|
||||
pub const DIALOGS: &str = "dialogs";
|
||||
pub const RUN_CONFIG_TYPES: &str = "runConfigTypes";
|
||||
pub const RUN_ANYTHING: &str = "runAnything";
|
||||
/// Entries of the Clone Repository dialog's source list, each a web page.
|
||||
pub const CLONE_SOURCES: &str = "cloneSources";
|
||||
/// The points whose declarations can name a `web` page (served, messaged, sent view events).
|
||||
pub const WEB_POINTS: [&str; 6] = [VIEWS, CUSTOM_EDITORS, EDITOR_PANELS, OVERLAYS, DIALOGS, RUN_CONFIG_TYPES];
|
||||
pub const WEB_POINTS: [&str; 7] =
|
||||
[VIEWS, CUSTOM_EDITORS, EDITOR_PANELS, OVERLAYS, DIALOGS, RUN_CONFIG_TYPES, CLONE_SOURCES];
|
||||
pub const FILE_ICONS: &str = "fileIcons";
|
||||
pub const MARKER_ICONS: &str = "markerIcons";
|
||||
pub const FILE_TEMPLATES: &str = "fileTemplates";
|
||||
@@ -1345,6 +1348,10 @@ struct DialogDecl {
|
||||
web: String,
|
||||
width: u32,
|
||||
height: u32,
|
||||
/// API 1.21: a lightweight popup (the title in its header, no title bar) that closes when
|
||||
/// the user clicks outside it or switches to another window, as Search Everywhere does.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
popup: bool,
|
||||
}
|
||||
|
||||
const DIALOG_WIDTH: std::ops::RangeInclusive<u32> = 320..=1600;
|
||||
@@ -1359,6 +1366,9 @@ pub(super) fn dialog(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String>
|
||||
pkg.manifest.needs_api(&format!("contributes.{DIALOGS}"), 18)?;
|
||||
validate_item_id(&d.id, "dialog id")?;
|
||||
let what = format!("dialog {:?}", d.id);
|
||||
if d.popup {
|
||||
pkg.manifest.needs_api(&format!("{what}: `popup`"), 21)?;
|
||||
}
|
||||
// `views.reveal(id)` opens it, so it can't share an id with a tool window.
|
||||
if pkg.manifest.declarations(VIEWS).iter().any(|v| v.get("id").and_then(|i| i.as_str()) == Some(&d.id)) {
|
||||
return Err(format!("{what}: a view has the same id"));
|
||||
@@ -1530,6 +1540,48 @@ pub(super) fn run_config_type(pkg: &Package, decl: toml::Value) -> Result<UiDecl
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CloneSourceDecl {
|
||||
id: String,
|
||||
label: String,
|
||||
/// An IDE icon name (`branch`, `git-pull`) or a package SVG (`icons/gitee.svg`),
|
||||
/// as on a view: the pane lists the service's own logo.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
/// The page that lists repositories and posts the chosen clone URL.
|
||||
/// Required: the dialog has nothing else to show for a source.
|
||||
web: String,
|
||||
}
|
||||
|
||||
pub(super) fn clone_source(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
let d: CloneSourceDecl = decode(CLONE_SOURCES, decl)?;
|
||||
pkg.manifest.needs_api(&format!("contributes.{CLONE_SOURCES}"), 21)?;
|
||||
validate_item_id(&d.id, "clone source id")?;
|
||||
title(CLONE_SOURCES, &d.label)?;
|
||||
let what = format!("clone source {:?}", d.id);
|
||||
if d.icon.as_ref().is_some_and(|i| i.len() > 64) {
|
||||
return Err(format!("clone source {:?}: icon names are up to 64 bytes", d.id));
|
||||
}
|
||||
let files = super::web::web_files(pkg, &d.web, &what)?;
|
||||
// The key is namespaced with the point: a source's page is served, messaged
|
||||
// and sent view events under it, and it cannot collide with a view's id.
|
||||
let mut out = UiDecl::new(format!("{CLONE_SOURCES}/{}", d.id), d.label.clone(), json(&d)?);
|
||||
out.files = files;
|
||||
if let Some(icon) = d.icon.as_deref().filter(|i| i.ends_with(".svg")) {
|
||||
let path = std::path::PathBuf::from(icon);
|
||||
let svg = super::icons::read_icon(pkg, &path, super::icons::MAX_SVG)?;
|
||||
out.assets.push((clone_source_icon_asset(&d.id), svg));
|
||||
out.files.push(path);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Asset id of a clone source's SVG icon, fetched by the workbench for the dialog.
|
||||
pub fn clone_source_icon_asset(id: &str) -> String {
|
||||
format!("cloneSourceIcon/{id}")
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct FileIconDecl {
|
||||
@@ -2615,7 +2667,11 @@ height = 600
|
||||
serde_json::json!({"id": "preview", "title": "SQL Preview", "web": "web/preview.html", "width": 900, "height": 600})
|
||||
);
|
||||
assert_eq!(valid.files, [PathBuf::from("web/preview.html")]);
|
||||
// API 1.21: a popup dialog.
|
||||
let popup = source.replace("^1.18", "^1.21").replace("height = 600", "height = 600\npopup = true");
|
||||
assert_eq!(check(&popup).unwrap().json["popup"], true);
|
||||
for (bad, error) in [
|
||||
(source.replace("height = 600", "height = 600\npopup = true"), "1.21"),
|
||||
(source.replace("^1.18", "^1.17"), "1.18"),
|
||||
(source.replace("width = 900", "width = 319"), "320–1600"),
|
||||
(source.replace("height = 600", "height = 1201"), "`height`"),
|
||||
|
||||
@@ -25,7 +25,12 @@ pub fn view_invocation(
|
||||
Some(doc) => {
|
||||
let project = project.as_ref().ok_or_else(|| IdeError::not_found("no project is open in this window"))?;
|
||||
let info = project.documents.snapshot(doc)?;
|
||||
Some(EditorContext { path: info.path.0, language: info.language.0, selections: Vec::new() })
|
||||
Some(EditorContext {
|
||||
path: info.path.0,
|
||||
language: info.language.0,
|
||||
selections: Vec::new(),
|
||||
visible_lines: None,
|
||||
})
|
||||
}
|
||||
};
|
||||
Ok(Invocation {
|
||||
@@ -56,8 +61,9 @@ pub async fn plugin_view_render(
|
||||
}
|
||||
|
||||
/// A user action in a plugin view or custom editor (`doc`, `editor`: as for rendering).
|
||||
/// Clone-source pages live in projectless Get from VCS windows; Restricted Mode still runs no plugin code.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn plugin_view_event(
|
||||
host: &crate::Host,
|
||||
plugins: &Arc<PluginHost>,
|
||||
@@ -129,7 +135,12 @@ mod tests {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = Host::new(HostConfig::for_test(tmp.path()));
|
||||
let range = ide_core::Range::new(ide_core::Pos::new(1, 0), ide_core::Pos::new(1, 4));
|
||||
let active = PluginEditor { path: "/p/a.rs".into(), language: "rust".into(), selections: vec![range] };
|
||||
let active = PluginEditor {
|
||||
path: "/p/a.rs".into(),
|
||||
language: "rust".into(),
|
||||
selections: vec![range],
|
||||
visible_lines: None,
|
||||
};
|
||||
let inv = view_invocation(&host, "main", None, Some(active)).unwrap();
|
||||
let editor = inv.editor.expect("the active editor");
|
||||
assert_eq!((editor.path.to_string_lossy().as_ref(), editor.selections.as_slice()), ("/p/a.rs", &[range][..]));
|
||||
|
||||
@@ -274,6 +274,7 @@ impl Host {
|
||||
{
|
||||
let settings = settings.clone();
|
||||
let root = root.clone();
|
||||
let detected_roots = detected_roots.clone();
|
||||
let data_dir = self.local_data_dir.clone();
|
||||
let config_dir = self.config_dir.clone();
|
||||
let build_cache = self.local_data_dir.join("cache").join(&project_key).join("build");
|
||||
@@ -416,11 +417,35 @@ impl Host {
|
||||
ide_sdk::php::configure_intelephense_storage(cfg, &data_dir);
|
||||
if cfg.name == "jdtls" {
|
||||
let (excluded_poms, build_files) = jdtls_maven_import(root, &effective);
|
||||
// Only the agent worktree folders that exist: another excluded folder
|
||||
// gives jdtls a fresh workspace, which every Java project would pay for.
|
||||
let mut excluded_folders: Vec<String> = AGENT_WORKTREE_DIRS
|
||||
.iter()
|
||||
.filter(|dir| root.join(dir).is_dir())
|
||||
.map(|dir| (*dir).to_owned())
|
||||
.chain(effective.project_structure.excluded.iter().cloned())
|
||||
.collect();
|
||||
let detected = if root == window_root {
|
||||
detected_roots.read().clone()
|
||||
} else {
|
||||
ide_workspace::roots::detect(root)
|
||||
};
|
||||
for folder in linked_roots(root, &effective, &detected).roots {
|
||||
if folder.is_detected_worktree()
|
||||
&& !excluded_folders.iter().any(|existing| {
|
||||
let existing = existing.trim_matches('/');
|
||||
folder.path == existing
|
||||
|| folder.path.strip_prefix(existing).is_some_and(|rest| rest.starts_with('/'))
|
||||
})
|
||||
{
|
||||
excluded_folders.push(folder.path);
|
||||
}
|
||||
}
|
||||
ide_sdk::apply::configure_maven_import(
|
||||
cfg,
|
||||
root,
|
||||
&excluded_poms,
|
||||
&effective.project_structure.excluded,
|
||||
&excluded_folders,
|
||||
build_files.as_deref(),
|
||||
);
|
||||
ide_sdk::apply::configure_gradle_import(
|
||||
@@ -616,28 +641,6 @@ impl Host {
|
||||
sink.clone(),
|
||||
);
|
||||
}
|
||||
// Build files / conventional folders changed: re-detect roots.
|
||||
let touched = changed.iter().chain(&batch.removed).filter_map(|p| p.strip_prefix(&root).ok());
|
||||
if touched.into_iter().any(ide_workspace::roots::affects_roots) {
|
||||
ide_build::gradle::forget_build_dirs(&root);
|
||||
let fresh = ide_workspace::roots::detect(&root);
|
||||
if *detected_roots.read() != fresh {
|
||||
// Detected excluded folders (`target`, `build`) leave the index too.
|
||||
let effective = settings.effective();
|
||||
let members = member_excludes.read();
|
||||
index.set_scope(
|
||||
index_roots(
|
||||
&root,
|
||||
content_roots(&effective, &root, &build_cache, trusted.load(Ordering::Acquire)),
|
||||
&effective,
|
||||
&members,
|
||||
),
|
||||
exclude_globs(&root, &effective, &fresh, &members),
|
||||
);
|
||||
*detected_roots.write() = fresh;
|
||||
sink.emit(IdeEvent::ProjectRootsChanged { root: root.clone().into() });
|
||||
}
|
||||
}
|
||||
// A repository was cloned / initialised / removed below the project:
|
||||
// its `.git/HEAD` appeared or went. A linked worktree's `.git` is a
|
||||
// plain gitfile, and that file is the only marker written inside the
|
||||
@@ -688,6 +691,40 @@ impl Host {
|
||||
// the signal. A `git clone` / `git init` inside the project already arrives
|
||||
// through the `.git` paths above; this covers the whole tree being brought in.
|
||||
git_dirs |= batch.created.iter().any(|p| p.join(".git").exists());
|
||||
// Build files, conventional folders, or linked Git worktrees changed: re-detect roots.
|
||||
let touched = changed.iter().chain(&batch.removed).filter_map(|p| p.strip_prefix(&root).ok());
|
||||
let build_roots_changed = touched.into_iter().any(ide_workspace::roots::affects_roots);
|
||||
let removed_worktree = !batch.removed.is_empty()
|
||||
&& detected_roots.read().iter().any(|r| {
|
||||
r.is_detected_worktree() && batch.removed.iter().any(|p| *p == root.join(&r.path))
|
||||
});
|
||||
if build_roots_changed || git_dirs || removed_worktree {
|
||||
if build_roots_changed {
|
||||
ide_build::gradle::forget_build_dirs(&root);
|
||||
}
|
||||
let fresh = ide_workspace::roots::detect(&root);
|
||||
if *detected_roots.read() != fresh {
|
||||
// Detected excluded folders (`target`, `build`, linked worktrees)
|
||||
// leave the index and watcher too.
|
||||
let effective = settings.effective();
|
||||
let members = member_excludes.read();
|
||||
let fresh_excludes = exclude_globs(&root, &effective, &fresh, &members);
|
||||
index.set_scope(
|
||||
index_roots(
|
||||
&root,
|
||||
content_roots(&effective, &root, &build_cache, trusted.load(Ordering::Acquire)),
|
||||
&effective,
|
||||
&members,
|
||||
),
|
||||
fresh_excludes.clone(),
|
||||
);
|
||||
if let Some(watcher) = watcher_weak.get().and_then(std::sync::Weak::upgrade) {
|
||||
watcher.set_excludes(&fresh_excludes);
|
||||
}
|
||||
*detected_roots.write() = fresh;
|
||||
sink.emit(IdeEvent::ProjectRootsChanged { root: root.clone().into() });
|
||||
}
|
||||
}
|
||||
if git_dirs {
|
||||
scan_repositories(
|
||||
&root,
|
||||
@@ -1491,15 +1528,17 @@ fn repository_scan_skips(settings: &ide_core::settings::Settings) -> impl Fn(&Pa
|
||||
/// Whether a scan of the project at `root` would look for a repository at `dir` and keep it.
|
||||
fn repository_searched(root: &Path, dir: &Path, settings: &ide_core::settings::Settings) -> bool {
|
||||
settings.vcs.git.enabled
|
||||
&& !settings
|
||||
.vcs
|
||||
.mappings
|
||||
.excluded
|
||||
.iter()
|
||||
.any(|p| dunce::canonicalize(VcsMappings::resolve(root, p)).is_ok_and(|e| e == dir))
|
||||
&& !repository_excluded(root, dir, &settings.vcs.mappings)
|
||||
&& Repos::searched(root, dir, &repository_scan_skips(settings))
|
||||
}
|
||||
|
||||
fn repository_excluded(project_root: &Path, repo_root: &Path, mappings: &VcsMappings) -> bool {
|
||||
mappings.excluded.iter().any(|entry| {
|
||||
let excluded = VcsMappings::resolve(project_root, entry);
|
||||
excluded == repo_root || dunce::canonicalize(excluded).is_ok_and(|path| path == repo_root)
|
||||
})
|
||||
}
|
||||
|
||||
/// When `dir`'s working-copy marker last changed.
|
||||
fn marker_time(dir: &Path, markers: &[String]) -> Option<std::time::SystemTime> {
|
||||
markers.iter().find_map(|m| dir.join(m).metadata().and_then(|m| m.modified()).ok())
|
||||
@@ -1810,6 +1849,71 @@ impl Project {
|
||||
self.with_repo_of(path, |r| f(r as &dyn Backend))
|
||||
}
|
||||
|
||||
/// Read-only editor commands can use the worktree reached through a project symlink
|
||||
/// without registering it for status, staging or other repository operations.
|
||||
pub(crate) fn with_editor_backend_of<T>(
|
||||
&self,
|
||||
path: &Path,
|
||||
f: impl FnOnce(&dyn Backend, &Path) -> IdeResult<T>,
|
||||
) -> IdeResult<T> {
|
||||
let Some(target) = self.linked_file_target(path) else {
|
||||
return self.with_backend_of(path, |backend| f(backend, path));
|
||||
};
|
||||
let unavailable = || IdeError::unavailable(format!("{} is not in a git repository", path.display()));
|
||||
if !self.git_enabled() {
|
||||
let backend = self.backend_of(path).ok_or_else(unavailable)?;
|
||||
return f(backend.as_ref(), path);
|
||||
}
|
||||
let Some(repo) = self.linked_editor_repo(path, &target)? else {
|
||||
return self.with_backend_of(path, |backend| f(backend, path));
|
||||
};
|
||||
f(repo.as_ref(), &target)
|
||||
}
|
||||
|
||||
pub(crate) fn linked_file_has_history(&self, path: &Path) -> IdeResult<bool> {
|
||||
if !self.git_enabled() {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(target) = self.linked_file_target(path) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let Some(repo) = self.linked_editor_repo(path, &target)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
Ok(repo.file_mode_at(&target, None)?.is_some_and(|mode| mode.starts_with("100")))
|
||||
}
|
||||
|
||||
fn linked_editor_repo(&self, path: &Path, target: &Path) -> IdeResult<Option<Arc<Repo>>> {
|
||||
let Some(repo) = Repo::discover(target)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mappings = self.settings.read_effective(|settings| settings.vcs.mappings.clone());
|
||||
if repository_excluded(&self.root, repo.root(), &mappings) {
|
||||
return Err(IdeError::unavailable(format!("{} is not in a git repository", path.display())));
|
||||
}
|
||||
// An unregistered target may have its own Git filters and executable settings.
|
||||
// Use the restricted read policy even when the editor's project is trusted.
|
||||
Ok(Some(self.repos().at_root(repo.root()).cloned().unwrap_or_else(|| Arc::new(repo))))
|
||||
}
|
||||
|
||||
/// Resolves a file reached through a symlink under one of the workspace project folders.
|
||||
pub(crate) fn linked_file_target(&self, path: &Path) -> Option<PathBuf> {
|
||||
let project_root = self.root_of(path);
|
||||
let relative = path.strip_prefix(&project_root).ok()?;
|
||||
if relative.components().any(|component| !matches!(component, std::path::Component::Normal(_))) {
|
||||
return None;
|
||||
}
|
||||
let target = dunce::canonicalize(path).ok()?;
|
||||
if target == path || !target.is_file() {
|
||||
return None;
|
||||
}
|
||||
// A different spelling of the same path is not by itself evidence of a symlink.
|
||||
path.ancestors()
|
||||
.take_while(|ancestor| *ancestor != project_root.as_path())
|
||||
.any(|ancestor| ancestor.symlink_metadata().is_ok_and(|metadata| metadata.is_symlink()))
|
||||
.then_some(target)
|
||||
}
|
||||
|
||||
fn run_in<T>(&self, repo: &Repo, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
|
||||
let settings = self.settings.effective();
|
||||
repo.set_ignored_names(settings.ignored_names());
|
||||
@@ -2071,6 +2175,21 @@ impl Project {
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-detects project roots (build files, environments, linked worktrees) and refreshes
|
||||
/// index and watcher scopes when they changed.
|
||||
pub fn refresh_detected_roots(&self) {
|
||||
if self.light {
|
||||
return;
|
||||
}
|
||||
let fresh = ide_workspace::roots::detect(&self.root);
|
||||
if *self.detected_roots.read() == fresh {
|
||||
return;
|
||||
}
|
||||
*self.detected_roots.write() = fresh;
|
||||
self.refresh_index_scope();
|
||||
self.sink.emit(IdeEvent::ProjectRootsChanged { root: self.root.clone().into() });
|
||||
}
|
||||
|
||||
/// Applies changed content roots and exclude settings to the index (which
|
||||
/// rescans in the background) and the file watchers, without reopening the project.
|
||||
pub fn refresh_index_scope(&self) {
|
||||
@@ -2241,6 +2360,7 @@ fn root_globs(
|
||||
) -> Option<Vec<String>> {
|
||||
let own = members.get(dir)?;
|
||||
let mut globs = settings.file_excludes();
|
||||
globs.extend(agent_worktree_globs());
|
||||
globs.extend(own.iter().cloned());
|
||||
Some(globs)
|
||||
}
|
||||
@@ -2678,16 +2798,63 @@ fn with_gradle_roots(
|
||||
out
|
||||
}
|
||||
|
||||
/// Project-relative paths of explicitly attached workspace projects or content roots inside `root`.
|
||||
fn attached_in_root(root: &Path, settings: &ide_core::settings::Settings) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut push = |p: &Path| {
|
||||
if p != root
|
||||
&& let Ok(rel) = p.strip_prefix(root)
|
||||
{
|
||||
let rel = ide_workspace::roots::normalize(&rel.to_string_lossy());
|
||||
if !rel.is_empty() && !out.contains(&rel) {
|
||||
out.push(rel);
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Ok(Some(ws)) = ide_workspace::workspace::Workspace::load(root)
|
||||
&& !ws.is_container(root)
|
||||
{
|
||||
for p in &ws.projects {
|
||||
push(p);
|
||||
}
|
||||
}
|
||||
for raw in &settings.project_structure.content_roots {
|
||||
let trimmed = raw.trim();
|
||||
if trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let p = Path::new(trimmed);
|
||||
let abs = if p.is_absolute() { p.to_path_buf() } else { root.join(p) };
|
||||
push(&dunce::canonicalize(&abs).unwrap_or(abs));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn linked_roots(root: &Path, settings: &ide_core::settings::Settings, detected: &[SourceFolder]) -> ProjectRoots {
|
||||
let unlinked = ide_build::maven::UnlinkedProjects::load(root, &settings.languages.java.maven);
|
||||
let attached = attached_in_root(root, settings);
|
||||
let detected = detected
|
||||
.iter()
|
||||
.filter(|folder| !folder.detected_from.as_ref().is_some_and(|pom| unlinked.contains(pom)))
|
||||
.filter(|folder| {
|
||||
!(folder.is_detected_worktree()
|
||||
&& attached.iter().any(|a| {
|
||||
a == &folder.path || a.strip_prefix(&folder.path).is_some_and(|rest| rest.starts_with('/'))
|
||||
}))
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
ProjectRoots::compute(detected, &settings.project_structure)
|
||||
}
|
||||
|
||||
/// Folders below a project or content root where agents put their git worktrees: copies of
|
||||
/// the project, excluded so search, indexing and navigation don't return them twice.
|
||||
const AGENT_WORKTREE_DIRS: &[&str] = &[".worktrees", ".claude/worktrees"];
|
||||
|
||||
fn agent_worktree_globs() -> impl Iterator<Item = String> {
|
||||
AGENT_WORKTREE_DIRS.iter().map(|dir| format!("/{dir}"))
|
||||
}
|
||||
|
||||
fn exclude_globs(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::Settings,
|
||||
@@ -2695,6 +2862,7 @@ fn exclude_globs(
|
||||
members: &BTreeMap<PathBuf, Vec<String>>,
|
||||
) -> Vec<String> {
|
||||
let mut globs = settings.file_excludes();
|
||||
globs.extend(agent_worktree_globs());
|
||||
globs.extend(linked_roots(root, settings, detected).excluded_globs());
|
||||
globs.extend(nested_member_globs(root, members));
|
||||
globs
|
||||
@@ -3605,6 +3773,14 @@ mod content_roots_tests {
|
||||
let own = root_globs(&settings, &members, &other).unwrap();
|
||||
assert!(own.contains(&"/gen".to_owned()) && !own.contains(&"/target".to_owned()));
|
||||
assert_eq!(root_globs(&settings, &members, &root), None, "the project folder has the project's");
|
||||
// Agent worktree folders are excluded in each project, at its root only.
|
||||
for globs in [&globs, &own] {
|
||||
let matcher = ide_vfs::ExcludeMatcher::new(globs);
|
||||
assert!(matcher.is_excluded(Path::new(".worktrees/topic/src/A.java")));
|
||||
assert!(matcher.is_excluded(Path::new(".claude/worktrees/topic")));
|
||||
assert!(!matcher.is_excluded(Path::new(".claude/settings.json")));
|
||||
assert!(!matcher.is_excluded(Path::new("src/.worktrees")));
|
||||
}
|
||||
|
||||
// A workspace folder's own excluded folders apply in every member, as before.
|
||||
let ws = base.join("ws");
|
||||
|
||||
@@ -28,6 +28,34 @@ pub struct TrustStore {
|
||||
struct RemoteDecisions {
|
||||
trusted: Vec<String>,
|
||||
restricted: Vec<String>,
|
||||
/// Folders trusted with everything under them (Trust Folder), per target.
|
||||
#[serde(default)]
|
||||
locations: Vec<RemoteLocation>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct RemoteLocation {
|
||||
target: String,
|
||||
folder: String,
|
||||
}
|
||||
|
||||
/// The key of a remote project's decisions: `[<target>,"<root>"]`, as `serde_json` writes the
|
||||
/// `(target, root)` tuple (the format of earlier versions). `target` is the target's JSON.
|
||||
pub fn remote_key(target: &str, root: &str) -> String {
|
||||
format!("[{target},{}]", serde_json::to_string(root).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The folder Trust Folder trusts for remote project `root`: its parent (`/`-separated).
|
||||
fn remote_parent(root: &str) -> Option<&str> {
|
||||
let root = root.trim_end_matches('/');
|
||||
let (parent, _) = root.rsplit_once('/')?;
|
||||
Some(if parent.is_empty() { "/" } else { parent })
|
||||
}
|
||||
|
||||
fn remote_under(root: &str, folder: &str) -> bool {
|
||||
let root = root.trim_end_matches('/');
|
||||
let folder = folder.trim_end_matches('/');
|
||||
root == folder || root.strip_prefix(folder).is_some_and(|rest| rest.starts_with('/'))
|
||||
}
|
||||
|
||||
/// Set by the desktop when it starts the server in a dev container of a folder the user trusts
|
||||
@@ -59,25 +87,52 @@ impl TrustStore {
|
||||
Self { file, state: Mutex::new(state), inherited: Mutex::default(), remote_file, remote: Mutex::new(remote) }
|
||||
}
|
||||
|
||||
/// The decision made on this machine for the remote project at `location` (`None`: none yet).
|
||||
/// Commands a remote window runs here follow it, not the server's own trust.
|
||||
pub fn remote_decision(&self, location: &str) -> IdeResult<Option<bool>> {
|
||||
/// The decision made on this machine for the remote project `root` of `target` (the
|
||||
/// target's JSON; `None`: none yet). Commands a remote window runs here follow it, not the
|
||||
/// server's own trust. A project under a trusted folder of the same target is trusted.
|
||||
pub fn remote_decision(&self, target: &str, root: &str) -> IdeResult<Option<bool>> {
|
||||
let remote = self.remote.lock().clone()?;
|
||||
Ok(if remote.restricted.iter().any(|l| l == location) {
|
||||
let location = remote_key(target, root);
|
||||
Ok(if remote.restricted.contains(&location) {
|
||||
Some(false)
|
||||
} else if remote.trusted.iter().any(|l| l == location) {
|
||||
} else if remote.trusted.contains(&location)
|
||||
|| remote.locations.iter().any(|l| l.target == target && remote_under(root, &l.folder))
|
||||
{
|
||||
Some(true)
|
||||
} else {
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
pub fn decide_remote(&self, location: &str, trusted: bool) -> IdeResult<()> {
|
||||
/// Records the decision for remote project `root` of `target`; `folder` also trusts its
|
||||
/// parent folder (Trust Folder).
|
||||
pub fn decide_remote(&self, target: &str, root: &str, trusted: bool, folder: bool) -> IdeResult<()> {
|
||||
let location = remote_key(target, root);
|
||||
let mut state = self.remote.lock();
|
||||
let mut next = state.clone()?;
|
||||
next.trusted.retain(|l| l != location);
|
||||
next.restricted.retain(|l| l != location);
|
||||
if trusted { &mut next.trusted } else { &mut next.restricted }.push(location.to_owned());
|
||||
next.trusted.retain(|l| *l != location);
|
||||
next.restricted.retain(|l| *l != location);
|
||||
if trusted { &mut next.trusted } else { &mut next.restricted }.push(location);
|
||||
if trusted
|
||||
&& folder
|
||||
&& let Some(parent) = remote_parent(root)
|
||||
{
|
||||
let parent = RemoteLocation { target: target.to_owned(), folder: parent.to_owned() };
|
||||
if !next.locations.contains(&parent) {
|
||||
next.locations.push(parent);
|
||||
}
|
||||
}
|
||||
persist(&self.remote_file, &next)?;
|
||||
*state = Ok(next);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Forgets trusted folder `folder` of `target` (Remove Trusted Location in a remote window).
|
||||
pub fn remove_remote_location(&self, target: &str, folder: &str) -> IdeResult<()> {
|
||||
let mut state = self.remote.lock();
|
||||
let mut next = state.clone()?;
|
||||
let folder = folder.trim_end_matches('/');
|
||||
next.locations.retain(|l| l.target != target || l.folder.trim_end_matches('/') != folder);
|
||||
persist(&self.remote_file, &next)?;
|
||||
*state = Ok(next);
|
||||
Ok(())
|
||||
@@ -439,12 +494,35 @@ mod tests {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let load = || super::TrustStore::load(&tmp.path().join("config"), &tmp.path().join("data"));
|
||||
let store = load();
|
||||
let here = r#"[{"kind":"ssh","config":"box"},"/srv/app"]"#;
|
||||
assert_eq!(store.remote_decision(here).unwrap(), None);
|
||||
store.decide_remote(here, true).unwrap();
|
||||
assert_eq!(store.remote_decision(here).unwrap(), Some(true));
|
||||
assert_eq!(store.remote_decision(r#"[{"kind":"ssh","config":"box"},"/srv/other"]"#).unwrap(), None);
|
||||
store.decide_remote(here, false).unwrap();
|
||||
assert_eq!(load().remote_decision(here).unwrap(), Some(false));
|
||||
let target = r#"{"kind":"ssh","config":"box"}"#;
|
||||
assert_eq!(store.remote_decision(target, "/srv/app").unwrap(), None);
|
||||
store.decide_remote(target, "/srv/app", true, false).unwrap();
|
||||
assert_eq!(store.remote_decision(target, "/srv/app").unwrap(), Some(true));
|
||||
assert_eq!(store.remote_decision(target, "/srv/other").unwrap(), None);
|
||||
store.decide_remote(target, "/srv/app", false, false).unwrap();
|
||||
assert_eq!(load().remote_decision(target, "/srv/app").unwrap(), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trusting_a_remote_folder_trusts_the_projects_under_it_on_that_target() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let load = || super::TrustStore::load(&tmp.path().join("config"), &tmp.path().join("data"));
|
||||
let store = load();
|
||||
let target = r#"{"kind":"ssh","config":"box"}"#;
|
||||
let other = r#"{"kind":"ssh","config":"other"}"#;
|
||||
store.decide_remote(target, "/srv/work/app", true, true).unwrap();
|
||||
let store = load();
|
||||
assert_eq!(store.remote_decision(target, "/srv/work/api").unwrap(), Some(true));
|
||||
assert_eq!(store.remote_decision(target, "/srv/work/a/b").unwrap(), Some(true));
|
||||
assert_eq!(store.remote_decision(target, "/srv/workshop").unwrap(), None);
|
||||
assert_eq!(store.remote_decision(other, "/srv/work/api").unwrap(), None);
|
||||
// An explicit Don't Trust of a project under it still wins.
|
||||
store.decide_remote(target, "/srv/work/api", false, false).unwrap();
|
||||
assert_eq!(store.remote_decision(target, "/srv/work/api").unwrap(), Some(false));
|
||||
store.remove_remote_location(target, "/srv/work/").unwrap();
|
||||
assert_eq!(load().remote_decision(target, "/srv/work/lib").unwrap(), None);
|
||||
assert_eq!(load().remote_decision(target, "/srv/work/app").unwrap(), Some(true));
|
||||
store.decide_remote(target, "/app", true, true).unwrap();
|
||||
assert_eq!(store.remote_decision(target, "/anything").unwrap(), Some(true));
|
||||
}
|
||||
}
|
||||
@@ -526,6 +526,7 @@ fn setup_host_and_repo(base: &Path) -> (Arc<Host>, PathBuf) {
|
||||
.save_custom_agent(CustomAgentInput {
|
||||
id: "mock-acp".into(),
|
||||
name: "Mock ACP".into(),
|
||||
base: None,
|
||||
command: "node".into(),
|
||||
args: vec![script_path.to_string_lossy().into_owned()],
|
||||
env: Default::default(),
|
||||
@@ -2071,6 +2072,7 @@ async fn ceiling_rejection_persist_rollback_cross_owner_auth_queued_trust_and_wo
|
||||
.save_custom_agent(CustomAgentInput {
|
||||
id: "mock-acp-stubborn".into(),
|
||||
name: "Mock ACP Stubborn".into(),
|
||||
base: None,
|
||||
command: "node".into(),
|
||||
args: vec![script_path.to_string_lossy().into_owned()],
|
||||
env: std::collections::BTreeMap::from([("MOCK_REJECT_DOWNGRADE".to_owned(), "1".to_owned())]),
|
||||
@@ -2081,6 +2083,7 @@ async fn ceiling_rejection_persist_rollback_cross_owner_auth_queued_trust_and_wo
|
||||
.save_custom_agent(CustomAgentInput {
|
||||
id: "mock-acp-err".into(),
|
||||
name: "Mock ACP Error".into(),
|
||||
base: None,
|
||||
command: "node".into(),
|
||||
args: vec![script_path.to_string_lossy().into_owned()],
|
||||
env: std::collections::BTreeMap::from([("MOCK_ERROR_DOWNGRADE".to_owned(), "1".to_owned())]),
|
||||
@@ -2611,6 +2614,7 @@ async fn scheduled_runs_cannot_recursively_mutate_automations_via_mcp_stdio_whil
|
||||
.save_custom_agent(CustomAgentInput {
|
||||
id: "mock-acp".into(),
|
||||
name: "Mock ACP".into(),
|
||||
base: None,
|
||||
command: "node".into(),
|
||||
args: vec![script_path.to_string_lossy().into_owned()],
|
||||
env: std::collections::BTreeMap::from([(
|
||||
@@ -3085,6 +3089,7 @@ async fn oneshot_self_chaining_and_override_preservation_on_edit() {
|
||||
.save_custom_agent(CustomAgentInput {
|
||||
id: "mock-acp-mcp".into(),
|
||||
name: "Mock ACP MCP".into(),
|
||||
base: None,
|
||||
command: "node".into(),
|
||||
args: vec![script_path.to_string_lossy().into_owned()],
|
||||
env: std::collections::BTreeMap::from([(
|
||||
|
||||
@@ -40,6 +40,7 @@ async fn agent_environment_values_stay_out_of_agent_files() {
|
||||
ide_agent::CustomAgentInput {
|
||||
id: "mine".into(),
|
||||
name: "Mine".into(),
|
||||
base: None,
|
||||
command: "/opt/mine".into(),
|
||||
args: vec![],
|
||||
env: env.clone(),
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -387,3 +387,125 @@ fn cross_module_reference_and_definition_have_the_same_rename_anchors() {
|
||||
assert_eq!(symbol.files.iter().map(|f| f.ranges.len()).sum::<usize>(), 3);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_graph_keeps_updating_its_files_and_skips_others_without_running_the_plugin() {
|
||||
use ide_host::plugins::navigation::MAX_FILES;
|
||||
let f = Fixture::new();
|
||||
let source = f.index("source.idx", SOURCE, &[method()], Some(1), "");
|
||||
for i in 1..MAX_FILES {
|
||||
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), "");
|
||||
assert_eq!(f.host.info_of("test.indexer").unwrap().stats.calls, calls, "a file the graph can't take is skipped");
|
||||
assert!(f.host.navigation_at(&f.root, &mapping, 1, reference_pos(), None, |_| None).is_none());
|
||||
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());
|
||||
}
|
||||
@@ -65,7 +65,7 @@ impl TestWorkspace {
|
||||
.iter()
|
||||
.map(|&(a, b, c, d)| ide_core::Range::new(ide_core::Pos::new(a, b), ide_core::Pos::new(c, d)))
|
||||
.collect();
|
||||
EditorContext { path, language: "text".into(), selections }
|
||||
EditorContext { path, language: "text".into(), selections, visible_lines: None }
|
||||
}
|
||||
|
||||
fn text(&self, rel: &str) -> String {
|
||||
@@ -7374,6 +7374,7 @@ fn api14_settings_and_input_events_use_other_and_capture_the_editor() {
|
||||
path: path.clone(),
|
||||
language: "text".into(),
|
||||
selections: vec![ide_core::Range::default()],
|
||||
visible_lines: Some((10, 52)),
|
||||
}),
|
||||
);
|
||||
f.host.flush_events_at(Instant::now() + Duration::from_secs(2));
|
||||
@@ -7399,6 +7400,7 @@ fn api14_settings_and_input_events_use_other_and_capture_the_editor() {
|
||||
assert_eq!(events[4]["editor"][0], path.as_str());
|
||||
assert_eq!(events[2]["editor"][0], path);
|
||||
assert_eq!(events[2]["editor"][1][0], serde_json::json!([0, 0, 0, 0]));
|
||||
assert_eq!(events[2]["editor"][2], serde_json::json!([10, 52]));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -8458,3 +8460,77 @@ title = "Prepare"
|
||||
f.host.set_enabled("jobs", false).unwrap();
|
||||
assert!(f.host.web_page("jobs", "jobs").is_err());
|
||||
}
|
||||
|
||||
/// A clone source is a page the Clone Repository dialog lists: its key carries
|
||||
/// the point's name, its page is served like a view's, and it needs a `web`
|
||||
/// entry plus API 1.21.
|
||||
#[test]
|
||||
fn clone_sources_are_web_pages_under_a_namespaced_key() {
|
||||
let f = fixture(Limits::default());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let pkg = tmp.path().join("gitee-demo");
|
||||
std::fs::create_dir_all(pkg.join("clone")).unwrap();
|
||||
std::fs::write(pkg.join("clone/index.html"), "<!doctype html><html><body>repos</body></html>").unwrap();
|
||||
std::fs::write(
|
||||
pkg.join("plugin.toml"),
|
||||
r#"id = "gitee-demo"
|
||||
name = "Gitee Demo"
|
||||
version = "1.0.0"
|
||||
engines.openidea = "^1.21"
|
||||
|
||||
[[contributes.cloneSources]]
|
||||
id = "gitee"
|
||||
label = "Gitee"
|
||||
icon = "branch"
|
||||
web = "clone/index.html"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let info = f.install(&pkg);
|
||||
assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error);
|
||||
|
||||
let item = f.host.ui_items("cloneSources").into_iter().find(|i| i.plugin_id == "gitee-demo").expect("the source");
|
||||
assert_eq!(item.key, "cloneSources/gitee");
|
||||
assert_eq!((item.decl["label"].as_str(), item.decl["icon"].as_str()), (Some("Gitee"), Some("branch")));
|
||||
// A source is not a tool window.
|
||||
assert!(f.host.ui_items("views").iter().all(|i| i.plugin_id != "gitee-demo"));
|
||||
|
||||
let page = f.host.web_page("gitee-demo", "cloneSources/gitee").unwrap();
|
||||
let (rev, entry) = page.path.strip_prefix("gitee-demo/").unwrap().split_once('/').unwrap();
|
||||
assert_eq!(entry, "clone/index.html");
|
||||
assert!(f.host.web_file("gitee-demo", &format!("{rev}/clone/index.html")).is_ok());
|
||||
assert!(f.host.web_page("gitee-demo", "cloneSources/nope").is_err());
|
||||
|
||||
// Refused: no page, a bad id, and an engine older than the point.
|
||||
for (name, body, message) in [
|
||||
("no-page", "id = \"gitee\"\nlabel = \"Gitee\"\nweb = \"clone/missing.html\"", "no such file"),
|
||||
("bad-id", "id = \"Gitee\"\nlabel = \"Gitee\"\nweb = \"clone/index.html\"", "invalid clone source id"),
|
||||
("no-web", "id = \"gitee\"\nlabel = \"Gitee\"", "missing field `web`"),
|
||||
] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let pkg = dir.path().join(name);
|
||||
std::fs::create_dir_all(pkg.join("clone")).unwrap();
|
||||
std::fs::write(pkg.join("clone/index.html"), "<p>repos</p>").unwrap();
|
||||
std::fs::write(
|
||||
pkg.join("plugin.toml"),
|
||||
format!(
|
||||
"id = \"gitee-{name}\"\nname = \"Gitee\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.21\"\n\n[[contributes.cloneSources]]\n{body}\n"
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let err = f.host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
|
||||
assert!(err.message.contains(message), "{name}: {}", err.message);
|
||||
}
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let old = dir.path().join("old");
|
||||
std::fs::create_dir_all(old.join("clone")).unwrap();
|
||||
std::fs::write(old.join("clone/index.html"), "<p>repos</p>").unwrap();
|
||||
std::fs::write(
|
||||
old.join("plugin.toml"),
|
||||
"id = \"gitee-old\"\nname = \"Gitee\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.20\"\n\n[[contributes.cloneSources]]\nid = \"gitee\"\nlabel = \"Gitee\"\nweb = \"clone/index.html\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let err = f.host.install_from_dir(&old, &Consent::all()).unwrap_err();
|
||||
assert!(err.message.contains("new in plugin API 1.21"), "{}", err.message);
|
||||
}
|
||||
@@ -1091,7 +1091,7 @@ async fn remote_focus_preserves_the_editor_for_following_plugin_events() {
|
||||
let events: Value = serde_json::from_str(received.as_str().unwrap()).unwrap();
|
||||
let event = events.as_array().unwrap().iter().rev().find(|e| e["kind"] == "input-mode-changed").unwrap();
|
||||
if focused {
|
||||
assert_eq!(event["editor"], json!([path, [[4, 2, 4, 5]]]));
|
||||
assert_eq!(event["editor"], json!([path, [[4, 2, 4, 5]], null]));
|
||||
} else {
|
||||
assert!(event["editor"].is_null(), "lost focus must clear the previous editor: {event}");
|
||||
}
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
}
|
||||
@@ -152,6 +152,14 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
|
||||
let host = &host;
|
||||
let w = "main";
|
||||
let file = project.root.join("src/a.txt");
|
||||
#[cfg(unix)]
|
||||
let history_path = {
|
||||
let link = project.root.join("linked.txt");
|
||||
std::os::unix::fs::symlink(external.root.join("src/a.txt"), &link).unwrap();
|
||||
link
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let history_path = file.clone();
|
||||
let root = || Some(project.root.clone());
|
||||
let log = || Some(external.root.clone());
|
||||
|
||||
@@ -169,6 +177,7 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
|
||||
call!("vcs_detected_roots", "", vcs::vcs_detected_roots(host, w)),
|
||||
call!("vcs_branch_info", "", vcs::vcs_branch_info(host, w, root())),
|
||||
call!("vcs_line_hunks", "", vcs::vcs_line_hunks(host, w, file.clone())),
|
||||
call!("vcs_linked_file_has_history", "", vcs::vcs_linked_file_has_history(host, w, history_path)),
|
||||
call!("vcs_staging_line_hunks", "", vcs::vcs_staging_line_hunks(host, w, file.clone(), None)),
|
||||
call!("vcs_file_at", "", vcs::vcs_file_at(host, w, file.clone(), None)),
|
||||
call!("vcs_image_at", "", vcs::vcs_image_at(host, w, project.root.join("asset.jpg"), ":0".into())),
|
||||
|
||||
@@ -74,6 +74,110 @@ impl Drop for Fixture {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn linked_editor_files_use_target_history_and_unsaved_text() {
|
||||
use ide_workspace::settings::SettingsScope;
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let target = base.join("target");
|
||||
let root = base.join("workspace");
|
||||
std::fs::create_dir(&target).unwrap();
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let target_file = target.join("notes.txt");
|
||||
let original = "first\nsecond\n";
|
||||
std::fs::write(&target_file, original).unwrap();
|
||||
git(&target, &["init", "-b", "main"]);
|
||||
git(&target, &["add", "notes.txt"]);
|
||||
git(
|
||||
&target,
|
||||
&[
|
||||
"-c",
|
||||
"user.name=Target",
|
||||
"-c",
|
||||
"[email protected]",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
"commit",
|
||||
"-m",
|
||||
"Add notes",
|
||||
],
|
||||
);
|
||||
symlink("../target", root.join("linked")).unwrap();
|
||||
let directory_link_file = root.join("linked/notes.txt");
|
||||
let file_link = root.join("notes.txt");
|
||||
symlink("../target/notes.txt", &file_link).unwrap();
|
||||
let new_file = target.join("new.txt");
|
||||
std::fs::write(&new_file, "not committed\n").unwrap();
|
||||
git(&target, &["add", "new.txt"]);
|
||||
symlink("../target/new.txt", root.join("new.txt")).unwrap();
|
||||
std::fs::write(root.join("plain.txt"), "not a link\n").unwrap();
|
||||
|
||||
let host = Host::new(common::host_config(&base));
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
for path in [root.join("plain.txt"), root.join("new.txt"), new_file] {
|
||||
assert!(!vcs::vcs_linked_file_has_history(&host, "main", path).await.unwrap());
|
||||
}
|
||||
for path in [&directory_link_file, &file_link] {
|
||||
assert!(vcs::vcs_linked_file_has_history(&host, "main", path.clone()).await.unwrap());
|
||||
let blame = vcs::vcs_blame(&host, "main", path.clone(), None, None).await.unwrap();
|
||||
assert_eq!(blame.len(), 2);
|
||||
assert!(blame.iter().all(|line| line.author == "Target"));
|
||||
assert!(vcs::vcs_line_hunks(&host, "main", path.clone()).await.unwrap().is_empty());
|
||||
let doc = project.documents.open(path).unwrap().id;
|
||||
project.documents.replace_all(doc, "first\nupdated\n").unwrap();
|
||||
let hunks = vcs::vcs_line_hunks(&host, "main", path.clone()).await.unwrap();
|
||||
assert_eq!(hunks.len(), 1);
|
||||
assert_eq!((hunks[0].start, hunks[0].lines, hunks[0].old_text.as_str()), (1, 1, "second\n"));
|
||||
let blame = vcs::vcs_blame(&host, "main", path.clone(), None, None).await.unwrap();
|
||||
assert_eq!(blame[0].author, "Target");
|
||||
assert!(blame[1].commit.chars().all(|character| character == '0'));
|
||||
assert!(vcs::vcs_staging_line_hunks(&host, "main", path.clone(), None).await.unwrap().is_none());
|
||||
project.documents.close(doc);
|
||||
}
|
||||
assert_eq!(std::fs::read_to_string(&target_file).unwrap(), original);
|
||||
assert!(project.repos().is_empty());
|
||||
assert!(vcs::vcs_line_hunks(&host, "main", target_file).await.is_err());
|
||||
|
||||
// The workspace's Git history can contain the link itself, but the editor reads its target.
|
||||
git(&root, &["init", "-b", "main"]);
|
||||
git(&root, &["add", "linked", "notes.txt"]);
|
||||
git(
|
||||
&root,
|
||||
&[
|
||||
"-c",
|
||||
"user.name=Workspace",
|
||||
"-c",
|
||||
"[email protected]",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
"commit",
|
||||
"-m",
|
||||
"Add links",
|
||||
],
|
||||
);
|
||||
project.refresh_repositories();
|
||||
assert_eq!(project.repos().roots(), vec![root.clone()]);
|
||||
let blame = vcs::vcs_blame(&host, "main", file_link.clone(), None, None).await.unwrap();
|
||||
assert_eq!(blame[0].author, "Target");
|
||||
assert!(vcs::vcs_staging_line_hunks(&host, "main", file_link, None).await.unwrap().is_none());
|
||||
|
||||
for excluded in ["linked".to_owned(), target.to_string_lossy().into_owned()] {
|
||||
project.settings.set(SettingsScope::Project, "vcs.mappings.excluded", serde_json::json!([excluded])).unwrap();
|
||||
assert!(vcs::vcs_linked_file_has_history(&host, "main", directory_link_file.clone()).await.is_err());
|
||||
assert!(vcs::vcs_line_hunks(&host, "main", directory_link_file.clone()).await.is_err());
|
||||
assert!(vcs::vcs_blame(&host, "main", directory_link_file.clone(), None, None).await.is_err());
|
||||
}
|
||||
project.settings.set(SettingsScope::Project, "vcs.mappings.excluded", serde_json::json!([])).unwrap();
|
||||
project.settings.set(SettingsScope::Project, "vcs.git.enabled", serde_json::json!(false)).unwrap();
|
||||
assert!(!vcs::vcs_linked_file_has_history(&host, "main", directory_link_file.clone()).await.unwrap());
|
||||
assert!(vcs::vcs_line_hunks(&host, "main", directory_link_file.clone()).await.is_err());
|
||||
assert!(vcs::vcs_blame(&host, "main", directory_link_file, None, None).await.is_err());
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn checkout_reloads_clean_open_documents_before_returning() {
|
||||
let f = Fixture::new().await;
|
||||
|
||||
@@ -432,3 +432,168 @@ async fn tmp_alias_is_protected() {
|
||||
let alias = std::path::Path::new("/").join(linked.strip_prefix("/private").unwrap());
|
||||
f.assert_protected(&alias).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn linked_worktree_below_project_repo_is_excluded_until_unmarked_or_attached() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let workspace = base.join("workspace");
|
||||
let repo = workspace.join("app");
|
||||
std::fs::create_dir_all(repo.join("src")).unwrap();
|
||||
std::fs::write(repo.join("Cargo.toml"), "[package]\nname = \"app\"\nversion = \"0.1.0\"\n").unwrap();
|
||||
std::fs::write(
|
||||
repo.join("src/lib.rs"),
|
||||
"pub fn unique_worktree_symbol() -> &'static str { \"unique_worktree_needle\" }\n",
|
||||
)
|
||||
.unwrap();
|
||||
git(&repo, &["init", "-b", "main"]);
|
||||
git(&repo, &["config", "user.name", "Test"]);
|
||||
git(&repo, &["config", "user.email", "[email protected]"]);
|
||||
git(&repo, &["config", "commit.gpgsign", "false"]);
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-m", "initial"]);
|
||||
|
||||
// Linked worktree of `repo` placed below `repo` at a custom path (not `.worktrees`).
|
||||
let nested = repo.join("topics/feature");
|
||||
git(&repo, &["worktree", "add", "-b", "feature", nested.to_str().unwrap()]);
|
||||
// Sibling linked worktree outside `repo`, inside the non-repo parent folder `workspace`.
|
||||
let sibling = workspace.join("app-sibling");
|
||||
git(&repo, &["worktree", "add", "-b", "sibling", sibling.to_str().unwrap()]);
|
||||
|
||||
let host = Host::new(common::host_config(&base));
|
||||
host.trust.decide(&repo, true, false).unwrap();
|
||||
let project = host.open_project("main", &repo).unwrap();
|
||||
wait_for_repos(&project, 2).await;
|
||||
assert!(project.index.wait_idle(Duration::from_secs(10)));
|
||||
|
||||
let search = |include_excluded: bool| {
|
||||
let host = &host;
|
||||
async move {
|
||||
let hits = Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let out = hits.clone();
|
||||
let query = serde_json::from_value(serde_json::json!({
|
||||
"pattern": "unique_worktree_needle",
|
||||
"isRegex": false,
|
||||
"caseSensitive": true,
|
||||
"wholeWord": false,
|
||||
"include": [],
|
||||
"exclude": [],
|
||||
"scope": { "kind": "project" },
|
||||
"maxMatches": 100,
|
||||
"includeExcluded": include_excluded
|
||||
}))
|
||||
.unwrap();
|
||||
ide_host::ops::search::search_start(
|
||||
host,
|
||||
"main",
|
||||
RequestId::next(),
|
||||
query,
|
||||
ide_host::ops::Channel::new(move |event| {
|
||||
if let ide_host::ops::search::SearchEvent::File { file } = event {
|
||||
out.lock().unwrap().push(file.rel_path);
|
||||
}
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut found = hits.lock().unwrap().clone();
|
||||
found.sort();
|
||||
found
|
||||
}
|
||||
};
|
||||
|
||||
// Detected as excluded root; skipped in file index, symbol index, and Find in Files.
|
||||
assert!(project.roots().excluded_globs().contains(&"/topics/feature".to_owned()));
|
||||
let indexed_files: Vec<String> = project.index.find_files("lib.rs", 20).into_iter().map(|m| m.rel_path).collect();
|
||||
assert_eq!(indexed_files, vec!["src/lib.rs"]);
|
||||
let indexed_syms: Vec<String> = project
|
||||
.index
|
||||
.find_symbols("unique_worktree_symbol", ide_index::SymbolFilter::All, 20)
|
||||
.into_iter()
|
||||
.map(|m| m.rel_path)
|
||||
.collect();
|
||||
assert_eq!(indexed_syms, vec!["src/lib.rs"]);
|
||||
assert_eq!(search(false).await, vec!["src/lib.rs"]);
|
||||
assert_eq!(search(true).await, vec!["src/lib.rs", "topics/feature/src/lib.rs"]);
|
||||
|
||||
// Adding a worktree below `repo` via VCS command excludes it immediately; removing drops it.
|
||||
let live_wt = repo.join("live-worktree");
|
||||
vcs::vcs_add_worktree(&host, "main", None, live_wt.clone(), "main".into(), Some("live".into()), None, None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(project.roots().excluded_globs().contains(&"/live-worktree".to_owned()));
|
||||
assert!(project.index.wait_idle(Duration::from_secs(10)));
|
||||
assert_eq!(search(false).await, vec!["src/lib.rs"]);
|
||||
vcs::vcs_remove_worktree(&host, "main", None, live_wt, false).await.unwrap();
|
||||
assert!(!project.roots().excluded_globs().contains(&"/live-worktree".to_owned()));
|
||||
|
||||
// Unmarking the detected exclusion (Cancel Exclusion) opts the worktree back in.
|
||||
ide_host::ops::project::set_settings(
|
||||
&host,
|
||||
"main",
|
||||
ide_workspace::settings::SettingsScope::Project,
|
||||
"projectStructure.unmarked",
|
||||
r#"["topics/feature"]"#,
|
||||
)
|
||||
.unwrap();
|
||||
let expected_both = vec!["src/lib.rs".to_owned(), "topics/feature/src/lib.rs".to_owned()];
|
||||
let mut after_unmark = Vec::new();
|
||||
for _ in 0..100 {
|
||||
assert!(project.index.wait_idle(Duration::from_secs(10)));
|
||||
after_unmark = project.index.find_files("lib.rs", 20).into_iter().map(|m| m.rel_path).collect();
|
||||
after_unmark.sort();
|
||||
if after_unmark == expected_both {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
assert_eq!(after_unmark, expected_both);
|
||||
assert_eq!(search(false).await, expected_both);
|
||||
|
||||
// Clear the unmark so the worktree is excluded again, then verify `attach_workspace` opts it back in.
|
||||
ide_host::ops::project::set_settings(
|
||||
&host,
|
||||
"main",
|
||||
ide_workspace::settings::SettingsScope::Project,
|
||||
"projectStructure.unmarked",
|
||||
"[]",
|
||||
)
|
||||
.unwrap();
|
||||
for _ in 0..100 {
|
||||
assert!(project.index.wait_idle(Duration::from_secs(10)));
|
||||
if project.index.find_files("lib.rs", 20).len() == 1 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
assert_eq!(search(false).await, vec!["src/lib.rs"]);
|
||||
host.trust.decide(&nested, true, false).unwrap();
|
||||
ide_host::ops::project::attach_workspace(&host, "main", &nested).unwrap();
|
||||
assert!(project.index.wait_idle(Duration::from_secs(10)));
|
||||
let mut after_attach: Vec<String> =
|
||||
project.index.find_files("lib.rs", 20).into_iter().map(|m| m.rel_path).collect();
|
||||
after_attach.sort();
|
||||
assert_eq!(after_attach, expected_both);
|
||||
assert_eq!(search(false).await, expected_both);
|
||||
|
||||
// Opening the linked worktree directly as the project root indexes and searches it normally.
|
||||
host.close_project("main");
|
||||
host.trust.decide(&nested, true, false).unwrap();
|
||||
let wt_project = host.open_project("main", &nested).unwrap();
|
||||
assert!(wt_project.index.wait_idle(Duration::from_secs(10)));
|
||||
assert!(wt_project.roots().excluded_globs().is_empty());
|
||||
let wt_files: Vec<String> = wt_project.index.find_files("lib.rs", 20).into_iter().map(|m| m.rel_path).collect();
|
||||
assert_eq!(wt_files, vec!["src/lib.rs"]);
|
||||
assert_eq!(search(false).await, vec!["src/lib.rs"]);
|
||||
|
||||
// Opening a non-repository parent folder holding `app` and sibling `app-sibling` keeps both indexed.
|
||||
host.close_project("main");
|
||||
host.trust.decide(&workspace, true, false).unwrap();
|
||||
let parent_project = host.open_project("main", &workspace).unwrap();
|
||||
assert!(parent_project.index.wait_idle(Duration::from_secs(10)));
|
||||
assert!(!parent_project.roots().excluded_globs().contains(&"/app-sibling".to_owned()));
|
||||
let parent_found = search(false).await;
|
||||
assert!(parent_found.contains(&"app/src/lib.rs".to_owned()), "{parent_found:?}");
|
||||
assert!(parent_found.contains(&"app-sibling/src/lib.rs".to_owned()), "{parent_found:?}");
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -428,6 +428,17 @@ fn script_class_change(body: Node, text: &str) -> Option<Change> {
|
||||
return None;
|
||||
}
|
||||
let ranges: Vec<Range<usize>> = blocks.into_iter().map(|b| b.3).collect();
|
||||
// A method moved to the top would continue a field left open above it when it starts with an
|
||||
// operator: `x = 1` then `*gen() {}` reads as `1 * gen()`.
|
||||
let children: Vec<Node> = body.children(&mut body.walk()).filter(|n| n.kind() != "comment").collect();
|
||||
let top = children.iter().find(|n| n.start_byte() >= ranges[order[0]].start);
|
||||
let above = children.iter().rev().find(|n| n.end_byte() <= ranges[0].start);
|
||||
if order[0] != 0
|
||||
&& top.is_some_and(|n| n.child(0).is_some_and(|c| matches!(&text[c.byte_range()], "*" | "in" | "instanceof")))
|
||||
&& !above.is_some_and(|n| n.kind() == "class_static_block" || text[n.byte_range()].ends_with(['{', ';']))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// Whole lines move: what shares the last method's last line (the closing brace, a comment
|
||||
// running on below it) stays at the end, so the last method must too.
|
||||
let end = ranges.last()?.end;
|
||||
@@ -664,10 +675,18 @@ mod tests {
|
||||
"const A = class {\n b() {}\n constructor() {} };",
|
||||
// So would the first line of a comment running on below it.
|
||||
"class A {\n b() {}\n constructor() {}; /* note\n */\n}\n",
|
||||
// A generator moved below a field without a semicolon would continue its initializer,
|
||||
// and so would one moved above the semicolon ending it.
|
||||
"class A {\n x = 1\n #p() {}\n *gen() {}\n}\n",
|
||||
"class A {\n x = {}\n #p() {}\n *gen() {}\n}\n",
|
||||
"class A {\n x = 1\n #p() {}\n in(a) {}\n}\n",
|
||||
"class A {\n x = 1\n #p() {}\n instanceof(a) {}\n}\n",
|
||||
"class A {\n x = 1\n /* c */ ;\n #p() {}\n *gen() {}\n}\n",
|
||||
// A syntax error anywhere in the file.
|
||||
"class A {\n b() {}\n constructor() {}\n}\nlet = ;\n",
|
||||
] {
|
||||
assert_eq!(script("typescript", text), None, "{text}");
|
||||
assert_eq!(script("javascript", text), None, "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -696,6 +715,21 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generator_moves_to_the_top_only_below_a_closed_member() {
|
||||
let text = "class A {\n x = 1;\n #p() {}\n *gen() {}\n}\n";
|
||||
let expected = "class A {\n x = 1;\n *gen() {}\n #p() {}\n}\n";
|
||||
assert_eq!(script("javascript", text).as_deref(), Some(expected));
|
||||
let text = "class A {\n static {}\n #p() {}\n *gen() {}\n}\n";
|
||||
let expected = "class A {\n static {}\n *gen() {}\n #p() {}\n}\n";
|
||||
assert_eq!(script("javascript", text).as_deref(), Some(expected));
|
||||
// The first method stays first, so the field's line ending is untouched.
|
||||
let text = "class A {\n x = 1\n /* c */ ;\n constructor() {}\n #p() {}\n *gen() {}\n}\n";
|
||||
let expected = "class A {\n x = 1\n /* c */ ;\n constructor() {}\n *gen() {}\n #p() {}\n}\n";
|
||||
assert_eq!(script("typescript", text).as_deref(), Some(expected));
|
||||
assert_eq!(script("javascript", text).as_deref(), Some(expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_and_instance_methods_with_one_name_stay_separate() {
|
||||
let text = "class A {\n of() {}\n static of() {}\n}\n";
|
||||
|
||||
@@ -513,6 +513,10 @@ impl ClientHandler {
|
||||
|
||||
fn show_message(&self, mgr: &LspManager, params: &Value) {
|
||||
let text = params.get("message").and_then(Value::as_str).unwrap_or_default().to_owned();
|
||||
// "Renew or activate a license" doesn't apply to a free preview build: its status offers the update.
|
||||
if self.expired_license(mgr, &text) {
|
||||
return;
|
||||
}
|
||||
// rust-analyzer built from source reports its own slow main-loop turns as errors, meant for
|
||||
// its developers (`poke_rust_analyzer_developer`); nothing for the user to act on.
|
||||
if text.starts_with("overly long loop turn") {
|
||||
@@ -534,6 +538,16 @@ impl ClientHandler {
|
||||
mgr.sink().emit(IdeEvent::Notify { level, title: self.server.name.clone(), body: Some(text) });
|
||||
}
|
||||
|
||||
/// Whether `text` says the running build's license ran out; if so, its status says so.
|
||||
fn expired_license(&self, mgr: &LspManager, text: &str) -> bool {
|
||||
if !crate::server::reports_expired_license(text) {
|
||||
return false;
|
||||
}
|
||||
tracing::warn!(server = ?self.server.id, generation = self.generation, "[{}] {text}", self.server.name);
|
||||
self.server.report_expired_while_running(self.generation, mgr.sink());
|
||||
true
|
||||
}
|
||||
|
||||
/// `window/showMessageRequest` expects `MessageActionItem | null`. Showing
|
||||
/// the question as a plain notification and replying null made Dart cancel
|
||||
/// renames with a warning (`Renamed field will be invisible in …`).
|
||||
@@ -770,6 +784,7 @@ impl Handler for ClientHandler {
|
||||
"window/showMessage" => self.show_message(&mgr, ¶ms),
|
||||
"window/logMessage" => {
|
||||
let text = params.get("message").and_then(Value::as_str).unwrap_or_default();
|
||||
self.expired_license(&mgr, text);
|
||||
if self.server.config.tsserver_project && tsserver_ran_out_of_memory(text) {
|
||||
tracing::warn!(server = ?self.server.id, generation = self.generation, "[{}] {text}", self.server.name);
|
||||
// The tasks of the dead tsserver never see their `end`: end them now
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -175,6 +175,9 @@ pub struct Server {
|
||||
/// Why the current instance's `initialize` failed, for the crash report.
|
||||
start_error: Mutex<Option<(u64, String)>>,
|
||||
stderr: Mutex<VecDeque<String>>,
|
||||
/// The instance whose JetBrains preview build reported, while running, that its license
|
||||
/// ran out: it stops serving after a short grace period, and only an update helps.
|
||||
expired_while_running: Mutex<Option<u64>>,
|
||||
pub progress: Mutex<HashMap<String, Progress>>,
|
||||
/// What the editor shows per path: the pushed and the pulled diagnostics together.
|
||||
diagnostics: Mutex<HashMap<PathBuf, Vec<lsp::Diagnostic>>>,
|
||||
@@ -240,6 +243,7 @@ impl Server {
|
||||
started: Mutex::new(None),
|
||||
start_error: Mutex::new(None),
|
||||
stderr: Mutex::new(VecDeque::new()),
|
||||
expired_while_running: Mutex::new(None),
|
||||
progress: Mutex::new(HashMap::new()),
|
||||
diagnostics: Mutex::new(HashMap::new()),
|
||||
pushed: Mutex::new(HashMap::new()),
|
||||
@@ -750,11 +754,35 @@ impl Server {
|
||||
return;
|
||||
}
|
||||
let busy = self.is_busy();
|
||||
self.queue_status(&mut st, if busy { ServerStatus::Busy } else { ServerStatus::Ready }, None);
|
||||
let message = self.expired_message(st.generation);
|
||||
self.queue_status(&mut st, if busy { ServerStatus::Busy } else { ServerStatus::Ready }, message);
|
||||
drop(st);
|
||||
self.publish(sink);
|
||||
}
|
||||
|
||||
/// A running JetBrains preview build (kotlin-lsp) said its license ran out: it keeps the
|
||||
/// process alive but stops serving once a short grace period ends, without crashing. Its
|
||||
/// status then says the build expired, which offers the update a crashed one gets.
|
||||
pub fn report_expired_while_running(&self, generation: u64, sink: &SharedSink) {
|
||||
let mut st = self.state.lock();
|
||||
if st.generation != generation || !matches!(st.conn, Conn::Ready(_)) {
|
||||
return;
|
||||
}
|
||||
if self.expired_while_running.lock().replace(generation) == Some(generation) {
|
||||
return;
|
||||
}
|
||||
let busy = self.is_busy();
|
||||
let message = self.expired_message(generation);
|
||||
self.queue_status(&mut st, if busy { ServerStatus::Busy } else { ServerStatus::Ready }, message);
|
||||
drop(st);
|
||||
self.publish(sink);
|
||||
}
|
||||
|
||||
fn expired_message(&self, generation: u64) -> Option<String> {
|
||||
(*self.expired_while_running.lock() == Some(generation))
|
||||
.then(|| format!("This build of {} has expired and stops working soon; update it.", self.name))
|
||||
}
|
||||
|
||||
/// Whether the server reports work in progress (indexing, analysis). A task marked
|
||||
/// stuck stays visible but no longer holds the server busy.
|
||||
pub fn is_busy(&self) -> bool {
|
||||
@@ -1167,6 +1195,14 @@ fn is_expired_build_line(line: &str) -> bool {
|
||||
line.contains("This build of ") && line.contains(" has expired")
|
||||
}
|
||||
|
||||
/// What a running JetBrains preview build says once its date passes: "Your JetBrains license has
|
||||
/// expired or is no longer valid. The language server keeps working for a short grace period…",
|
||||
/// then a parked license gate.
|
||||
pub(crate) fn reports_expired_license(text: &str) -> bool {
|
||||
let text = text.to_ascii_lowercase();
|
||||
text.contains("jetbrains license has expired") || text.contains("license gate: parked")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -2094,6 +2094,28 @@ async fn apply_edit_hook_and_server_requests() {
|
||||
"showMessageRequest is now a question with actions, not a notification; info and developer notices are not surfaced"
|
||||
);
|
||||
|
||||
// A JetBrains preview build past its date keeps running but stops serving after a grace
|
||||
// period: its status says the build expired (the UI offers the update), once per instance.
|
||||
let expired = |e: &IdeEvent| matches!(e, IdeEvent::LanguageServer { status: ide_core::event::ServerStatus::Ready | ide_core::event::ServerStatus::Busy, message: Some(m), .. } if m.contains("has expired"));
|
||||
peer.notify(
|
||||
"window/showMessage",
|
||||
json!({ "type": 2, "message": "Your JetBrains license has expired or is no longer valid. The language server keeps working for a short grace period; renew or activate a license to avoid interruption." }),
|
||||
)
|
||||
.unwrap();
|
||||
peer.notify(
|
||||
"window/logMessage",
|
||||
json!({ "type": 3, "message": "#LicenseManager - License gate: Parked(reason=GraceExpired)" }),
|
||||
)
|
||||
.unwrap();
|
||||
peer.notify("window/showMessage", json!({ "type": 2, "message": "after" })).unwrap();
|
||||
eventually(|| h.events.lock().iter().any(|e| matches!(e, IdeEvent::Notify { body: Some(b), .. } if b == "after")))
|
||||
.await;
|
||||
assert_eq!(h.events.lock().iter().filter(|e| expired(e)).count(), 1);
|
||||
assert!(
|
||||
!h.events.lock().iter().any(|e| matches!(e, IdeEvent::Notify { body: Some(b), .. } if b.contains("license"))),
|
||||
"the license notice is not shown as is"
|
||||
);
|
||||
|
||||
// Dynamically registered capability is now usable.
|
||||
s.respond(
|
||||
"textDocument/documentHighlight",
|
||||
@@ -10042,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;
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -20,6 +20,8 @@ pub struct EditorContext {
|
||||
pub language: String,
|
||||
/// Selections when the command was invoked (cursors are empty ranges).
|
||||
pub selections: Vec<ide_core::Range>,
|
||||
/// First and last document line on screen when the command was invoked.
|
||||
pub visible_lines: Option<(u32, u32)>,
|
||||
}
|
||||
|
||||
/// Where a command or event batch comes from: the window and its project.
|
||||
@@ -1305,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,
|
||||
}
|
||||
@@ -1337,6 +1337,13 @@ impl editor::HostTextEditor for StoreData {
|
||||
Ok(Ok(self.table.get(&this)?.ctx.selections.iter().map(range_to_wit).collect()))
|
||||
}
|
||||
|
||||
fn visible_lines(&mut self, this: Resource<EditorRes>) -> Fallible<Option<(u32, u32)>> {
|
||||
if let Err(e) = self.require(Capability::EditorRead) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
Ok(Ok(self.table.get(&this)?.ctx.visible_lines))
|
||||
}
|
||||
|
||||
fn apply_edits(&mut self, this: Resource<EditorRes>, version: u64, edits: Vec<wit::TextEdit>) -> Fallible<u64> {
|
||||
if let Err(e) = self.require(Capability::EditorWrite) {
|
||||
return Ok(Err(e));
|
||||
@@ -3484,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>,
|
||||
|
||||
@@ -96,6 +96,24 @@ fn the_sdk_carries_the_hosts_wit() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `MockHost::install()` grants every capability that takes no value, so plugin tests see what
|
||||
/// a fully granted plugin sees.
|
||||
#[test]
|
||||
fn the_sdk_mock_grants_every_capability_without_a_value() {
|
||||
let mock = std::fs::read_to_string(repo().join("sdk/rust/openidea-plugin/src/mock.rs")).unwrap();
|
||||
let list = mock.split_once("const ALL: &[&str] = &[").unwrap().1.split_once("];").unwrap().0;
|
||||
let granted: Vec<&str> = list.split('"').skip(1).step_by(2).collect();
|
||||
let parser = std::fs::read_to_string(repo().join("crates/ide-extension/src/capability.rs")).unwrap();
|
||||
let fixed = parser.split_once("Ok(match s {").unwrap().1.split_once("_ => return Err").unwrap().0;
|
||||
let names: Vec<&str> =
|
||||
fixed.lines().filter_map(|line| line.trim().strip_prefix('"')?.split_once('"').map(|(n, _)| n)).collect();
|
||||
assert!(names.len() > 10, "{names:?}");
|
||||
for name in names {
|
||||
assert!(granted.contains(&name), "MockHost::install() in the SDK does not grant {name:?}");
|
||||
assert!(name.parse::<ide_extension::Capability>().is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_version_check_runs_compatible_components_and_explains_the_rest() {
|
||||
let host = v("1.21.0");
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
391e0b78cbb610ca32b7b74b6b2026376557554ee3d9e607579173157d6505c0
|
||||
fbd767ccf69c37807aa8f535197ab9fac47f809ef887ab9fd99c0b2886201ae1
|
||||
@@ -174,6 +174,7 @@ impl Plugin for Api14 {
|
||||
.into_iter()
|
||||
.map(|r| [r.start.line, r.start.character, r.end.line, r.end.character])
|
||||
.collect::<Vec<_>>(),
|
||||
e.visible_lines().unwrap(),
|
||||
)
|
||||
});
|
||||
received.push(serde_json::json!({ "kind": kind, "data": data, "editor": editor }));
|
||||
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
28ae86e361923f5603829368d4e51f9c11323e9871b348191b046b171a455837
|
||||
583b5ee3f495851ca14c378a3a4fe4cfd92be772e5f33a383d4f3b9f935f4b7e
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
885e682ee7bdab8c44257cefb0266c31582fbd76a1a00c867697379b57ebf431
|
||||
a29fb8d12bc4bb7fdba146706ce941ecfce1e4ddecdbbe1672aac88b1adfb4da
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
25de09055141345b3de8939a43dad4f79d57304b140367097a1016ed076ca4fc
|
||||
f99c40e69fba8d835f578dc6d1dc2a078ad774d881ae454e3703d5d150cf2c8d
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
c84299a4bdeade40350fffb6020bfb5378f824d96651045c82ddcc121f6a9547
|
||||
c732a0688e0cfcd71ce8471c4d929e5e5496461e44ef705a2bf468fad62b4ae8
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
65ea37261173e1100f6a5a650e95c0c07ddce0f81cba737d277c385196c5674b
|
||||
ee71ad8f7a4c3786c8221188fc117304ac68db6d567093661d4056d83e45cc99
|
||||
@@ -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"
|
||||
@@ -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 @@
|
||||
44e139c052f87ec409eb7ac36240a22272d9f2b0bd41a37ff6c01e726457e424
|
||||
33020cf1117fc910e2984a2bd0110924cf5ffdf24ae015bf191762993c06c532
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
c59d0f0d1fb4abc052a2e978201a8b149ace29699d38d1924720b77e9ee41d92
|
||||
9923493b942447f729a8568de02e3d02c3d59b3d7468f569a1ae978adaa3176d
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
47fe447ccb9f76d69cffe69713a2177fceca1b69eb039f13bb912b80578e6126
|
||||
d12f681411fda1fed05e537f291705a3ce26faa009044fdf9d0a01b964fc0056
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
925e17f44beeb4ba34b1e60466299101b3e8dbd025f7e011ec335839b5e1077c
|
||||
893ce9fe2bb20cd5adc34794ad3ddc1c8779631fecf4d14dfa51290f55eb0377
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
2602908184d78bcad536606ce9af2bcc893067f2fce8f78273beef523a470b73
|
||||
c5ec51674a2c7556ffd65ac856dbe68e024a6d9361348653b6ff32d31dcf3ff8
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
36de99a64635a3536433b328c787578593435f82c5f8e714b185ea2af6d08f60
|
||||
9212ac37ebb4e2a4c09afccec3d29ffd4ad6fb77a5444b108dc5381a66b3f3fd
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
51f6a7efff3b6d48e2ee37aa830f3ff79fa12adbfbe39407d56edb1149e8c55a
|
||||
a0c79f2e2798894eaea06ccbf7c1a80cfb269817563273ede8ade9903b310f78
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
0d75629cdc43f130ba3628b068caf36dacac07e26ef55c89b999e8bafc13ebc0
|
||||
d2c95eb484ec574031ea01e77e32fca49f5dca0b419a2ed9d6556c3db6810d4c
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
0972b15707c35be7e27846e6d219cd4d02c0ae3fef91d414f521a2f4f6ca96ff
|
||||
82bdefebd3747dcda62acd8e9a11eb9e8ef137fddb0c29c5011c475cb184530b
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
23fc8f3a0c7920d91e0cf90ec4a58e82ff6deb92159e197a971fd47a280810a6
|
||||
5c383892b3c7345d2d230da7c4e5b3f1e1e1899491e0cf3df8ce3b02c41b5154
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
491b3794111b43a0c6408fb3399d1a9ac080df213d962ef04adebee411e9def1
|
||||
11287c6ce9ad5b964ad730ccfd2ee846c6cc0a671b83f86daad78891e2463aba
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
b887aa0ed1908edf6dc684d4d84a15209f14c7dfb1c7fdf6d2c3e7f61ff2d720
|
||||
a912aed6c1a64745240d16e6b8e69c7966023d7001ca712ccad32b8d1918e3df
|
||||
Бінарний файл не відображається.
Loaded 100 of 472 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача