дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 18:17:15 +02:00
Порівняти коміти
27
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
9661981d59 | ||
|
|
3278eab0c8 | ||
|
|
71bfc70996 | ||
|
|
1e6ab2ecff | ||
|
|
0f0e3e73e7 | ||
|
|
a2498f096a | ||
|
|
494d1a9bf5 | ||
|
|
417ecfed50 | ||
|
|
94653b487d | ||
|
|
a5473e896a | ||
|
|
8483c355c8 | ||
|
|
8d2d2d27e6 | ||
|
|
72db7ecb97 | ||
|
|
406cf4e474 | ||
|
|
bc019ace9d | ||
|
|
55c9787996 | ||
|
|
5b1e4a31f2 | ||
|
|
f3582403f3 | ||
|
|
a5f958d544 | ||
|
|
4aeeb4d883 | ||
|
|
15f3eadcf1 | ||
|
|
ae9804bc8b | ||
|
|
644a380616 | ||
|
|
4a41b14992 | ||
|
|
551328c901 | ||
|
|
54ce7ac6f8 | ||
|
|
a33c46465b |
No files matched your search
@@ -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"] {
|
||||
|
||||
@@ -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)?;
|
||||
}
|
||||
|
||||
@@ -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!(
|
||||
|
||||
@@ -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::*;
|
||||
|
||||
@@ -16,8 +16,10 @@ pub struct NavigationFiles {
|
||||
}
|
||||
|
||||
/// Discovery offers at most this many files; larger projects get navigation
|
||||
/// on the first ones instead of none.
|
||||
const MAX_NAVIGATION_FILES: usize = 20_000;
|
||||
/// on the first ones instead of none. As many as one graph covers, so the
|
||||
/// "covers N of M files" notice stays true.
|
||||
const MAX_NAVIGATION_FILES: usize = super::navigation::MAX_FILES;
|
||||
const MAX_INDEX_BATCH: usize = 128;
|
||||
|
||||
/// The first `limit` files by path that `in_scope` accepts, and how many it accepts in all.
|
||||
/// Sorting keeps the covered files the same across index rebuilds.
|
||||
@@ -80,6 +82,15 @@ pub fn plugin_navigation_invalidate(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct LoadedNavigationDoc {
|
||||
path: PathBuf,
|
||||
document: Option<ide_core::DocId>,
|
||||
version: Option<u32>,
|
||||
text: String,
|
||||
symbols: Vec<ide_language::SymbolTag>,
|
||||
scope: String,
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn plugin_navigation_index(
|
||||
host: &crate::Host,
|
||||
@@ -88,8 +99,8 @@ pub async fn plugin_navigation_index(
|
||||
paths: Vec<PathBuf>,
|
||||
request: ide_core::RequestId,
|
||||
) -> IdeResult<()> {
|
||||
if paths.len() > 16 {
|
||||
return Err(IdeError::invalid("navigation batches are limited to 16 files"));
|
||||
if paths.len() > MAX_INDEX_BATCH {
|
||||
return Err(IdeError::invalid("navigation batches are limited to 128 files"));
|
||||
}
|
||||
let plugins = plugins.clone();
|
||||
let project = host.project(window)?;
|
||||
@@ -99,33 +110,45 @@ pub async fn plugin_navigation_index(
|
||||
if !project.is_trusted() {
|
||||
return Err(IdeError::unavailable("project is not trusted"));
|
||||
}
|
||||
let extensions = plugins.navigation_extensions(&project.root);
|
||||
let project_roots = project.roots();
|
||||
// A project window group's members are project scope.
|
||||
let mut roots = vec![project.root.clone()];
|
||||
roots.extend(crate::project::workspace_member_roots(&project.root));
|
||||
for path in paths {
|
||||
|
||||
let mut loaded_docs = Vec::with_capacity(paths.len());
|
||||
let mut evict_paths = Vec::new();
|
||||
for raw_path in paths {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let Ok(path) = ide_plugin::resolve_in_roots(&roots, &path.to_string_lossy()) else {
|
||||
let Ok(path) = ide_plugin::resolve_in_roots(&roots, &raw_path.to_string_lossy()) else {
|
||||
evict_paths.push(raw_path);
|
||||
continue;
|
||||
};
|
||||
let extensions = plugins.navigation_extensions(&project.root);
|
||||
if !path.extension().and_then(|e| e.to_str()).is_some_and(|e| extensions.iter().any(|x| x == e)) {
|
||||
evict_paths.push(path);
|
||||
continue;
|
||||
}
|
||||
let document = project.documents.by_path(&path);
|
||||
let (text, version, language) = if let Some(id) = document {
|
||||
let snapshot = project.documents.text_snapshot(id)?;
|
||||
let Ok(snapshot) = project.documents.text_snapshot(id) else {
|
||||
evict_paths.push(path);
|
||||
continue;
|
||||
};
|
||||
if snapshot.large {
|
||||
evict_paths.push(path);
|
||||
continue;
|
||||
}
|
||||
(snapshot.text, Some(snapshot.version), snapshot.language)
|
||||
} else {
|
||||
let Ok(loaded) = project.documents.load_file_bounded(&path, super::navigation::MAX_DOCUMENT_BYTES)
|
||||
else {
|
||||
evict_paths.push(path);
|
||||
continue;
|
||||
};
|
||||
if loaded.binary || loaded.large {
|
||||
evict_paths.push(path);
|
||||
continue;
|
||||
}
|
||||
let text = loaded.text;
|
||||
@@ -133,23 +156,42 @@ pub async fn plugin_navigation_index(
|
||||
(text, None, language)
|
||||
};
|
||||
if text.len() > crate::plugins::navigation::MAX_DOCUMENT_BYTES {
|
||||
evict_paths.push(path);
|
||||
continue;
|
||||
}
|
||||
let symbols = project
|
||||
.index
|
||||
.symbols_for_text(&path, &text)
|
||||
.unwrap_or_else(|| project.syntax.syntax().tags(&language, &text));
|
||||
let roots = project.roots();
|
||||
let scope = roots
|
||||
let scope = project_roots
|
||||
.roots
|
||||
.iter()
|
||||
.filter(|r| path.starts_with(project.root.join(&r.path)))
|
||||
.max_by_key(|r| r.path.len())
|
||||
.and_then(|r| r.detected_from.as_deref())
|
||||
.unwrap_or("");
|
||||
plugins.index_navigation(
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
loaded_docs.push(LoadedNavigationDoc { path, document, version, text, symbols, scope });
|
||||
}
|
||||
|
||||
if !evict_paths.is_empty() {
|
||||
plugins.invalidate_client_navigation(&project.root, Some(&client), Some(&evict_paths));
|
||||
}
|
||||
|
||||
if !loaded_docs.is_empty() {
|
||||
let snapshots: Vec<_> = loaded_docs
|
||||
.iter()
|
||||
.map(|doc| crate::plugins::navigation::Snapshot {
|
||||
path: &doc.path,
|
||||
version: doc.version,
|
||||
text: &doc.text,
|
||||
symbols: &doc.symbols,
|
||||
scope: &doc.scope,
|
||||
})
|
||||
.collect();
|
||||
if let Err(err) = plugins.index_navigation_batch(
|
||||
&project.root,
|
||||
crate::plugins::navigation::Snapshot { path: &path, version, text: &text, symbols: &symbols, scope },
|
||||
&snapshots,
|
||||
Invocation {
|
||||
command_chain: Vec::new(),
|
||||
client: Some(client.clone()),
|
||||
@@ -158,10 +200,33 @@ pub async fn plugin_navigation_index(
|
||||
selected_paths: Vec::new(),
|
||||
global_settings: false,
|
||||
},
|
||||
)?;
|
||||
Some(&cancel),
|
||||
) {
|
||||
let remaining_paths: Vec<PathBuf> = loaded_docs
|
||||
.into_iter()
|
||||
.filter(|doc| {
|
||||
cancel.is_cancelled()
|
||||
|| doc.document.is_some_and(|id| project.documents.version(id).ok() != doc.version)
|
||||
})
|
||||
.map(|doc| doc.path)
|
||||
.collect();
|
||||
if !remaining_paths.is_empty() {
|
||||
plugins.invalidate_client_navigation(&project.root, Some(&client), Some(&remaining_paths));
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
// A document edit while WASM was executing must not publish stale ranges.
|
||||
if cancel.is_cancelled() || document.is_some_and(|id| project.documents.version(id).ok() != version) {
|
||||
plugins.invalidate_client_navigation(&project.root, Some(&client), Some(&[path]));
|
||||
let stale_paths: Vec<PathBuf> = loaded_docs
|
||||
.into_iter()
|
||||
.filter(|doc| {
|
||||
cancel.is_cancelled()
|
||||
|| doc.document.is_some_and(|id| project.documents.version(id).ok() != doc.version)
|
||||
})
|
||||
.map(|doc| doc.path)
|
||||
.collect();
|
||||
if !stale_paths.is_empty() {
|
||||
plugins.invalidate_client_navigation(&project.root, Some(&client), Some(&stale_paths));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -15,6 +15,66 @@ pub const MAX_DOCUMENT_BYTES: usize = ide_lsp::MAX_INJECTED_DOCUMENT_BYTES;
|
||||
/// Files one plugin's graph covers per project and window.
|
||||
pub const MAX_FILES: usize = 20_000;
|
||||
const MAX_EDGES: usize = 4096;
|
||||
const MAX_GRAPH_EDGES: usize = 200_000;
|
||||
const MAX_ACTOR_CHUNK: usize = 16;
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct BatchIndexSummary {
|
||||
pub skipped_invalid: usize,
|
||||
}
|
||||
|
||||
fn edges_are_empty(edges: &Edges) -> bool {
|
||||
edges.definitions.is_empty() && edges.references.is_empty() && edges.aliases.is_empty() && edges.markers.is_empty()
|
||||
}
|
||||
|
||||
fn validate_edges(plugin_id: &str, path: &Path, text: &str, edges: &Edges) -> IdeResult<()> {
|
||||
if edges_are_empty(edges) {
|
||||
return Ok(());
|
||||
}
|
||||
let lines: Vec<_> = text.split('\n').map(|l| l.encode_utf16().count()).collect();
|
||||
let output_bytes = edges
|
||||
.definitions
|
||||
.iter()
|
||||
.chain(&edges.references)
|
||||
.chain(&edges.markers)
|
||||
.map(|a| a.key.len().saturating_add(32))
|
||||
.sum::<usize>()
|
||||
.saturating_add(edges.aliases.iter().map(|a| a.prefix.len() + a.target.len()).sum::<usize>());
|
||||
if output_bytes > MAX_DOCUMENT_BYTES {
|
||||
return Err(IdeError::invalid("document index output is too large"));
|
||||
}
|
||||
if edges.aliases.len() > 256
|
||||
|| edges.aliases.iter().any(|a| {
|
||||
!a.prefix.ends_with('#') || !a.target.ends_with('#') || a.prefix.len() > 1024 || a.target.len() > 1024
|
||||
})
|
||||
|| edges.definitions.len() + edges.references.len() > MAX_EDGES
|
||||
|| edges
|
||||
.definitions
|
||||
.iter()
|
||||
.chain(&edges.references)
|
||||
.any(|a| a.key.is_empty() || a.key.len() > 1024 || !valid_range(&lines, a.range))
|
||||
{
|
||||
return Err(IdeError::invalid(format!("{plugin_id}: invalid navigation anchors in {}", path.display())));
|
||||
}
|
||||
if edges.markers.len() > MAX_EDGES
|
||||
|| edges.markers.iter().any(|a| a.key.is_empty() || a.key.len() > 1024 || !valid_range(&lines, a.range))
|
||||
{
|
||||
return Err(IdeError::invalid(format!("{plugin_id}: invalid navigation markers in {}", path.display())));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn to_index_symbols(symbols: &[SymbolTag]) -> Vec<ide_plugin::indexing::IndexSymbol> {
|
||||
symbols
|
||||
.iter()
|
||||
.map(|s| ide_plugin::indexing::IndexSymbol {
|
||||
name: s.name.clone(),
|
||||
kind: serde_json::to_value(s.kind).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default(),
|
||||
container: s.container.clone(),
|
||||
range: s.range,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub struct Snapshot<'a> {
|
||||
pub path: &'a Path,
|
||||
@@ -236,7 +296,6 @@ impl PluginHost {
|
||||
if plugins.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let lines: Vec<_> = text.split('\n').map(|l| l.encode_utf16().count()).collect();
|
||||
for plugin in plugins {
|
||||
// A full graph keeps the files it covers; discovery already told the user
|
||||
// the rest are left out, so they are skipped without running the plugin.
|
||||
@@ -250,64 +309,14 @@ impl PluginHost {
|
||||
self.changed();
|
||||
}
|
||||
let (owned_path, owned_text) = (path.to_string_lossy().into_owned(), text.to_owned());
|
||||
let symbols = symbols
|
||||
.iter()
|
||||
.map(|s| ide_plugin::indexing::IndexSymbol {
|
||||
name: s.name.clone(),
|
||||
kind: serde_json::to_value(s.kind)
|
||||
.ok()
|
||||
.and_then(|v| v.as_str().map(str::to_owned))
|
||||
.unwrap_or_default(),
|
||||
container: s.container.clone(),
|
||||
range: s.range,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let symbols = to_index_symbols(symbols);
|
||||
let ctx = invocation.clone();
|
||||
let started = std::time::Instant::now();
|
||||
let result = actor.call(None, move |rt| rt.index_document(&owned_path, &owned_text, &symbols, ctx));
|
||||
let edges = self
|
||||
.finish_provider_call(&plugin, &actor, started, result)
|
||||
.ok_or_else(|| IdeError::unavailable("document indexer did not return a result"))?;
|
||||
let output_bytes = edges
|
||||
.definitions
|
||||
.iter()
|
||||
.chain(&edges.references)
|
||||
.chain(&edges.markers)
|
||||
.map(|a| a.key.len().saturating_add(32))
|
||||
.sum::<usize>()
|
||||
.saturating_add(edges.aliases.iter().map(|a| a.prefix.len() + a.target.len()).sum::<usize>());
|
||||
if output_bytes > MAX_DOCUMENT_BYTES {
|
||||
return Err(IdeError::invalid("document index output is too large"));
|
||||
}
|
||||
if edges.aliases.len() > 256
|
||||
|| edges.aliases.iter().any(|a| {
|
||||
!a.prefix.ends_with('#')
|
||||
|| !a.target.ends_with('#')
|
||||
|| a.prefix.len() > 1024
|
||||
|| a.target.len() > 1024
|
||||
})
|
||||
|| edges.definitions.len() + edges.references.len() > MAX_EDGES
|
||||
|| edges
|
||||
.definitions
|
||||
.iter()
|
||||
.chain(&edges.references)
|
||||
.any(|a| a.key.is_empty() || a.key.len() > 1024 || !valid_range(&lines, a.range))
|
||||
{
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{}: invalid navigation anchors in {}",
|
||||
plugin.id(),
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
if edges.markers.len() > MAX_EDGES
|
||||
|| edges.markers.iter().any(|a| a.key.is_empty() || a.key.len() > 1024 || !valid_range(&lines, a.range))
|
||||
{
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{}: invalid navigation markers in {}",
|
||||
plugin.id(),
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
validate_edges(plugin.id(), path, text, &edges)?;
|
||||
let mut index = self.navigation.lock();
|
||||
if index.epochs.get(root).copied() != generation {
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -322,16 +331,19 @@ impl PluginHost {
|
||||
if !graph.instance.ptr_eq(&Arc::downgrade(&plugin)) {
|
||||
*graph = Graph { instance: Arc::downgrade(&plugin), ..Default::default() };
|
||||
}
|
||||
graph.remove(path);
|
||||
if edges_are_empty(&edges) {
|
||||
continue;
|
||||
}
|
||||
if graph.files.len() >= MAX_FILES && !graph.files.contains_key(path) {
|
||||
continue;
|
||||
}
|
||||
graph.remove(path);
|
||||
if graph.edges
|
||||
+ edges.definitions.len()
|
||||
+ edges.references.len()
|
||||
+ edges.aliases.len()
|
||||
+ edges.markers.len()
|
||||
> 200_000
|
||||
> MAX_GRAPH_EDGES
|
||||
{
|
||||
return Err(IdeError::unavailable("navigation association limit reached"));
|
||||
}
|
||||
@@ -340,6 +352,191 @@ impl PluginHost {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Index a batch of bounded snapshots in short actor chunks (up to 16 files per call).
|
||||
/// Full graphs skip uncovered files before running the plugin, empty-edge documents are not
|
||||
/// stored, and individual invalid documents are skipped/evicted without failing the batch.
|
||||
pub fn index_navigation_batch(
|
||||
&self,
|
||||
root: &Path,
|
||||
snapshots: &[Snapshot<'_>],
|
||||
invocation: Invocation,
|
||||
cancel: Option<&ide_core::CancellationToken>,
|
||||
) -> IdeResult<BatchIndexSummary> {
|
||||
if snapshots.is_empty() {
|
||||
return Ok(BatchIndexSummary::default());
|
||||
}
|
||||
if !(self.project_policy.read())(root) {
|
||||
return Err(IdeError::unavailable("project is not trusted"));
|
||||
}
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(crate::project::workspace_member_roots(root));
|
||||
let mut summary = BatchIndexSummary::default();
|
||||
let mut prepared = Vec::with_capacity(snapshots.len());
|
||||
for snap in snapshots {
|
||||
if snap.text.len() > MAX_DOCUMENT_BYTES {
|
||||
tracing::warn!(path = %snap.path.display(), "navigation document is too large");
|
||||
summary.skipped_invalid += 1;
|
||||
continue;
|
||||
}
|
||||
let path = dunce::simplified(snap.path);
|
||||
match ide_plugin::resolve_in_roots(&roots, &path.to_string_lossy()) {
|
||||
Ok(real) if real == path => {
|
||||
let extension = path.extension().and_then(|e| e.to_str()).unwrap_or_default().to_owned();
|
||||
prepared.push((path.to_owned(), extension, snap));
|
||||
}
|
||||
Ok(_) | Err(_) => {
|
||||
tracing::warn!(path = %path.display(), "navigation skipped invalid path");
|
||||
summary.skipped_invalid += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if prepared.is_empty() {
|
||||
return Ok(summary);
|
||||
}
|
||||
|
||||
let project_key = (root.to_owned(), invocation.client.clone());
|
||||
let generation = self.navigation.lock().epochs.get(root).copied();
|
||||
let plugins: Vec<(Arc<super::LoadedPlugin>, Vec<String>)> = self
|
||||
.plugins
|
||||
.read()
|
||||
.values()
|
||||
.filter(|p| {
|
||||
p.status().is_live()
|
||||
&& p.dev_root.as_deref().is_none_or(|r| r == root)
|
||||
&& p.meta.lock().granted.contains(&Capability::ProjectRead)
|
||||
})
|
||||
.filter_map(|p| declaration(p).map(|d| (p.clone(), d.extensions)))
|
||||
.collect();
|
||||
if plugins.is_empty() {
|
||||
return Ok(summary);
|
||||
}
|
||||
|
||||
for (plugin, exts) in plugins {
|
||||
let matching_indices: Vec<usize> = {
|
||||
let index = self.navigation.lock();
|
||||
let full_graph = index
|
||||
.projects
|
||||
.get(&project_key)
|
||||
.and_then(|g| g.get(plugin.id()))
|
||||
.filter(|g| g.instance.ptr_eq(&Arc::downgrade(&plugin)) && g.files.len() >= MAX_FILES);
|
||||
prepared
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, (path, ext, _))| {
|
||||
if !exts.iter().any(|e| e == ext) {
|
||||
return None;
|
||||
}
|
||||
if full_graph.is_some_and(|g| !g.files.contains_key(path)) {
|
||||
return None;
|
||||
}
|
||||
Some(idx)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
if matching_indices.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if cancel.is_some_and(ide_core::CancellationToken::is_cancelled) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let (actor, activated) = self.ensure_active(&plugin, invocation.client.as_deref())?;
|
||||
if activated {
|
||||
self.changed();
|
||||
}
|
||||
|
||||
for chunk in matching_indices.chunks(MAX_ACTOR_CHUNK) {
|
||||
if cancel.is_some_and(ide_core::CancellationToken::is_cancelled) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let items: Vec<_> = chunk
|
||||
.iter()
|
||||
.map(|&idx| {
|
||||
let (ref path, _, snap) = prepared[idx];
|
||||
(idx, path.to_string_lossy().into_owned(), snap.text.to_owned(), to_index_symbols(snap.symbols))
|
||||
})
|
||||
.collect();
|
||||
let ctx = invocation.clone();
|
||||
let chunk_cancel = cancel.cloned();
|
||||
let started = std::time::Instant::now();
|
||||
let result = actor.call(None, move |rt| {
|
||||
let mut out = Vec::with_capacity(items.len());
|
||||
for (idx, owned_path, owned_text, symbols) in items {
|
||||
if chunk_cancel.as_ref().is_some_and(ide_core::CancellationToken::is_cancelled) {
|
||||
return Ok(None);
|
||||
}
|
||||
let edges = rt.index_document(&owned_path, &owned_text, &symbols, ctx.clone())?;
|
||||
out.push((idx, edges));
|
||||
}
|
||||
Ok(Some(out))
|
||||
});
|
||||
let Some(maybe_edges) = self.finish_provider_call(&plugin, &actor, started, result) else {
|
||||
let mut index = self.navigation.lock();
|
||||
if let Some(graph) = index.projects.get_mut(&project_key).and_then(|g| g.get_mut(plugin.id())) {
|
||||
for &idx in chunk {
|
||||
graph.remove(&prepared[idx].0);
|
||||
}
|
||||
}
|
||||
return Err(IdeError::unavailable("document indexer did not return a result"));
|
||||
};
|
||||
let Some(chunk_edges) = maybe_edges else {
|
||||
return Err(IdeError::cancelled());
|
||||
};
|
||||
if cancel.is_some_and(ide_core::CancellationToken::is_cancelled) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
|
||||
let mut index = self.navigation.lock();
|
||||
if index.epochs.get(root).copied() != generation {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if index.projects.len() >= 16 && !index.projects.contains_key(&project_key) {
|
||||
return Err(IdeError::unavailable("navigation project limit reached"));
|
||||
}
|
||||
let graph =
|
||||
index.projects.entry(project_key.clone()).or_default().entry(plugin.id().to_owned()).or_default();
|
||||
if !graph.instance.ptr_eq(&Arc::downgrade(&plugin)) {
|
||||
*graph = Graph { instance: Arc::downgrade(&plugin), ..Default::default() };
|
||||
}
|
||||
for (idx, edges) in chunk_edges {
|
||||
let (ref path, _, snap) = prepared[idx];
|
||||
graph.remove(path);
|
||||
if let Err(err) = validate_edges(plugin.id(), path, snap.text, &edges) {
|
||||
tracing::warn!("{err}");
|
||||
summary.skipped_invalid += 1;
|
||||
continue;
|
||||
}
|
||||
if edges_are_empty(&edges) {
|
||||
continue;
|
||||
}
|
||||
if graph.files.len() >= MAX_FILES && !graph.files.contains_key(path) {
|
||||
continue;
|
||||
}
|
||||
let new_edges =
|
||||
edges.definitions.len() + edges.references.len() + edges.aliases.len() + edges.markers.len();
|
||||
if graph.edges + new_edges > MAX_GRAPH_EDGES {
|
||||
tracing::warn!(
|
||||
plugin = %plugin.id(),
|
||||
path = %path.display(),
|
||||
"navigation association limit reached; skipping document"
|
||||
);
|
||||
summary.skipped_invalid += 1;
|
||||
continue;
|
||||
}
|
||||
graph.insert(
|
||||
path.clone(),
|
||||
File {
|
||||
version: snap.version,
|
||||
scope: snap.scope.to_owned(),
|
||||
hash: snapshot_hash(snap.text),
|
||||
edges,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
/// Resolves only current live providers. Disable/reload/trap cannot retain
|
||||
/// navigable stale data, even if a background snapshot finished concurrently.
|
||||
pub fn navigation_at(
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -394,7 +394,17 @@ fn a_full_graph_keeps_updating_its_files_and_skips_others_without_running_the_pl
|
||||
let f = Fixture::new();
|
||||
let source = f.index("source.idx", SOURCE, &[method()], Some(1), "");
|
||||
for i in 1..MAX_FILES {
|
||||
f.index(&format!("filler/{i}.idx"), "", &[], None, "");
|
||||
let p = f.root.join(format!("filler/{i}.idx"));
|
||||
let txt = format!("def filler:{i}\n");
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(&p, &txt).unwrap();
|
||||
f.host
|
||||
.index_navigation(
|
||||
&f.root,
|
||||
Snapshot { path: &p, version: None, text: &txt, symbols: &[], scope: "" },
|
||||
Invocation { workspace_root: Some(f.root.clone()), ..Default::default() },
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let calls = f.host.info_of("test.indexer").unwrap().stats.calls;
|
||||
let mapping = f.index("mapping.idx", MAPPING, &[], Some(1), "");
|
||||
@@ -403,4 +413,99 @@ fn a_full_graph_keeps_updating_its_files_and_skips_others_without_running_the_pl
|
||||
f.index("source.idx", SOURCE, &[method()], Some(2), "");
|
||||
assert_eq!(f.host.info_of("test.indexer").unwrap().stats.calls, calls + 1, "covered files still update");
|
||||
assert!(f.host.navigation_at(&f.root, &source, 2, Pos::new(1, 5), None, |_| None).is_none());
|
||||
|
||||
// Batch indexing on the same full graph also skips uncovered files before invoking WASM.
|
||||
let calls_before_batch = f.host.info_of("test.indexer").unwrap().stats.calls;
|
||||
std::fs::write(&source, SOURCE).unwrap();
|
||||
f.host
|
||||
.index_navigation_batch(
|
||||
&f.root,
|
||||
&[
|
||||
Snapshot { path: &mapping, version: Some(2), text: MAPPING, symbols: &[], scope: "" },
|
||||
Snapshot { path: &source, version: Some(3), text: SOURCE, symbols: &[], scope: "" },
|
||||
],
|
||||
Invocation { workspace_root: Some(f.root.clone()), ..Default::default() },
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
f.host.info_of("test.indexer").unwrap().stats.calls,
|
||||
calls_before_batch + 1,
|
||||
"batch only invokes WASM for the already-covered file"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_edges_do_not_consume_graph_slots_and_batch_isolates_invalid_documents() {
|
||||
let f = Fixture::new();
|
||||
let source = f.index("src/source.idx", SOURCE, &[method()], Some(1), "app");
|
||||
let mapping = f.index("resources/mapping.idx", MAPPING, &[], Some(1), "app");
|
||||
assert!(f.host.navigation_at(&f.root, &mapping, 1, reference_pos(), None, |_| None).is_some());
|
||||
|
||||
// Re-indexing `source` with empty content evicts its previous anchors cleanly.
|
||||
std::fs::write(&source, "").unwrap();
|
||||
f.host
|
||||
.index_navigation(
|
||||
&f.root,
|
||||
Snapshot { path: &source, version: Some(2), text: "", symbols: &[], scope: "app" },
|
||||
Invocation { workspace_root: Some(f.root.clone()), ..Default::default() },
|
||||
)
|
||||
.unwrap();
|
||||
assert!(f.host.navigation_at(&f.root, &mapping, 1, reference_pos(), None, |_| None).is_none());
|
||||
assert!(f.host.navigation_markers(&f.root, std::slice::from_ref(&mapping), None, |_| None).is_empty());
|
||||
|
||||
// Mixed batch containing 200 empty files, one invalid document, and two valid connected files:
|
||||
// the invalid document is skipped/evicted while valid documents still commit cleanly.
|
||||
let mut empty_paths = Vec::with_capacity(200);
|
||||
for i in 0..200 {
|
||||
let p = f.root.join(format!("empty/E{i}.idx"));
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(&p, "// nothing\n").unwrap();
|
||||
empty_paths.push(p);
|
||||
}
|
||||
let bad = f.root.join("batch/bad.idx");
|
||||
let connected_a = f.root.join("batch/source.idx");
|
||||
let connected_b = f.root.join("batch/mapping.idx");
|
||||
std::fs::create_dir_all(bad.parent().unwrap()).unwrap();
|
||||
std::fs::write(&bad, "invalid key\n").unwrap();
|
||||
std::fs::write(&connected_a, SOURCE).unwrap();
|
||||
std::fs::write(&connected_b, MAPPING).unwrap();
|
||||
|
||||
let mut snapshots: Vec<Snapshot<'_>> = empty_paths
|
||||
.iter()
|
||||
.map(|p| Snapshot { path: p, version: None, text: "// nothing\n", symbols: &[], scope: "app" })
|
||||
.collect();
|
||||
snapshots.push(Snapshot { path: &bad, version: Some(1), text: "invalid key\n", symbols: &[], scope: "app" });
|
||||
snapshots.push(Snapshot { path: &connected_a, version: Some(1), text: SOURCE, symbols: &[], scope: "app" });
|
||||
snapshots.push(Snapshot { path: &connected_b, version: Some(1), text: MAPPING, symbols: &[], scope: "app" });
|
||||
|
||||
let summary = f
|
||||
.host
|
||||
.index_navigation_batch(
|
||||
&f.root,
|
||||
&snapshots,
|
||||
Invocation { workspace_root: Some(f.root.clone()), ..Default::default() },
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(summary.skipped_invalid, 1);
|
||||
|
||||
let res = f.host.navigation_at(&f.root, &connected_b, 1, reference_pos(), None, |_| None).unwrap();
|
||||
assert_eq!(res.targets[0].path.0, connected_a);
|
||||
let markers = f.host.navigation_markers(&f.root, &[connected_a.clone(), connected_b.clone()], None, |_| None);
|
||||
assert_eq!(markers.len(), 2);
|
||||
|
||||
// Pre-cancelled batch aborts without publishing or modifying entries.
|
||||
let cancelled_file = f.root.join("batch/cancelled.idx");
|
||||
std::fs::write(&cancelled_file, SOURCE).unwrap();
|
||||
let token = ide_core::CancellationToken::new();
|
||||
token.cancel();
|
||||
let cancelled_res = f.host.index_navigation_batch(
|
||||
&f.root,
|
||||
&[Snapshot { path: &cancelled_file, version: Some(1), text: SOURCE, symbols: &[], scope: "app" }],
|
||||
Invocation { workspace_root: Some(f.root.clone()), ..Default::default() },
|
||||
Some(&token),
|
||||
);
|
||||
assert!(cancelled_res.is_err());
|
||||
assert!(f.host.navigation_markers(&f.root, &[cancelled_file], None, |_| None).is_empty());
|
||||
}
|
||||
@@ -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:?}");
|
||||
}
|
||||
}
|
||||
@@ -511,3 +511,41 @@ async fn attach_and_detach_preserve_the_primary_project_session() {
|
||||
assert!(!reopened.is_trusted());
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
/// Issue #7433: a member whose folder is gone (its checkout moved up a level) can be removed,
|
||||
/// and the folder it moved to can be attached, under the same name, before or after that.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_member_whose_folder_is_gone_can_be_removed_and_its_new_folder_attached() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let primary = base.join("primary");
|
||||
let moved_to = base.join("sapp");
|
||||
let gone = moved_to.join("sapp");
|
||||
std::fs::create_dir_all(&primary).unwrap();
|
||||
std::fs::create_dir_all(&gone).unwrap();
|
||||
std::fs::write(gone.join("pom.xml"), "<project/>").unwrap();
|
||||
let host = Host::new(common::host_config(&base));
|
||||
for root in [&primary, &gone, &moved_to] {
|
||||
host.trust.decide(root, true, false).unwrap();
|
||||
}
|
||||
let project = host.open_project("main", &primary).unwrap();
|
||||
ops::project::attach_workspace(&host, "main", &gone).unwrap();
|
||||
// The checkout moves up a level: `sapp/sapp` is gone, its files are in `sapp`.
|
||||
std::fs::rename(gone.join("pom.xml"), moved_to.join("pom.xml")).unwrap();
|
||||
std::fs::remove_dir(&gone).unwrap();
|
||||
|
||||
// The folder it moved to, named the same, is attached while the old entry is still there.
|
||||
ops::project::attach_workspace(&host, "main", &moved_to).unwrap();
|
||||
let members = Workspace::load(&primary).unwrap().unwrap().projects;
|
||||
assert_eq!(members, [primary.clone(), gone.clone(), moved_to.clone()]);
|
||||
assert!(ops::project::info(&project).workspace.is_some());
|
||||
|
||||
// Remove from Workspace of the gone member.
|
||||
ops::project::save_workspace(&host, "main", "primary", vec![primary.clone(), moved_to.clone()]).unwrap();
|
||||
assert_eq!(Workspace::load(&primary).unwrap().unwrap().projects, [primary.clone(), moved_to.clone()]);
|
||||
|
||||
// Removed first, then attached again.
|
||||
ops::project::save_workspace(&host, "main", "primary", vec![primary.clone()]).unwrap();
|
||||
ops::project::attach_workspace(&host, "main", &moved_to).unwrap();
|
||||
assert_eq!(Workspace::load(&primary).unwrap().unwrap().projects, [primary, moved_to]);
|
||||
}
|
||||
@@ -1,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");
|
||||
}
|
||||
}
|
||||
@@ -10064,3 +10064,171 @@ async fn spring_bean_markers_follow_the_servers_features() {
|
||||
assert_eq!(h.mgr.spring_bean_markers(doc, Default::default()).await.unwrap(), None);
|
||||
assert!(beans.requested("java-analyzer/springBeanMarkers").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn extract_interface_uses_java_analyzer_when_advertised() {
|
||||
let mut ja_caps = incremental_caps();
|
||||
ja_caps["positionEncoding"] = json!("utf-8");
|
||||
ja_caps["experimental"] = json!({
|
||||
"java-analyzer/extractInterfaceInfo": true,
|
||||
"java-analyzer/extractInterface": true,
|
||||
});
|
||||
let h = harness_configured("java", "java", &[("java-analyzer", ja_caps), ("jdtls", incremental_caps())], |_| {});
|
||||
// "/* 😀 */ " is 9 UTF-16 units (😀 = 2) and 11 UTF-8 bytes (😀 = 4).
|
||||
let (doc, path) =
|
||||
h.open("MainImpl.java", "package app;\n/* 😀 */ public class MainImpl {\n public void hello() {}\n}\n");
|
||||
for name in ["java-analyzer", "jdtls"] {
|
||||
h.wait_status(name, ServerStatus::Ready).await;
|
||||
}
|
||||
let (ja, jdtls) = (h.launcher.state("java-analyzer"), h.launcher.state("jdtls"));
|
||||
eventually(|| !ja.notified("textDocument/didOpen").is_empty()).await;
|
||||
|
||||
// Caret on `MainImpl`: UTF-16 col 22 -> UTF-8 byte col 24.
|
||||
let caret = Pos::new(1, 22);
|
||||
ja.respond(
|
||||
"java-analyzer/extractInterfaceInfo",
|
||||
json!({
|
||||
"interfaceName": "Main",
|
||||
"members": [{
|
||||
"name": "hello",
|
||||
"typeName": "void",
|
||||
"parameters": [],
|
||||
"handleIdentifier": "hello()",
|
||||
}],
|
||||
"packages": ["app"],
|
||||
}),
|
||||
);
|
||||
let info = h.mgr.extract_interface_info(doc, caret, Default::default()).await.unwrap();
|
||||
assert_eq!(info.class_name, "MainImpl");
|
||||
assert_eq!(info.members.len(), 1);
|
||||
assert_eq!(info.members[0].handle_identifier, "hello()");
|
||||
assert_eq!(
|
||||
ja.requested("java-analyzer/extractInterfaceInfo")[0],
|
||||
json!({ "textDocument": { "uri": uri_of(&path) }, "position": { "line": 1, "character": 24 } })
|
||||
);
|
||||
assert!(jdtls.requested("java/checkExtractInterfaceStatus").is_empty());
|
||||
|
||||
// Null info (e.g. caret outside a class name) reports InvalidInput rather than a protocol error.
|
||||
ja.respond("java-analyzer/extractInterfaceInfo", Value::Null);
|
||||
let err = h.mgr.extract_interface_info(doc, Pos::new(0, 0), Default::default()).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
|
||||
// Edit request sends handles + recovered package and converts CreateFile + TextDocumentEdit.
|
||||
let iface_path = path.with_file_name("Main.java");
|
||||
let iface_uri = uri_of(&iface_path);
|
||||
ja.respond(
|
||||
"java-analyzer/extractInterface",
|
||||
json!({
|
||||
"edit": {
|
||||
"documentChanges": [
|
||||
{ "kind": "create", "uri": iface_uri },
|
||||
{
|
||||
"textDocument": { "uri": iface_uri, "version": null },
|
||||
"edits": [{
|
||||
"range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } },
|
||||
"newText": "package app;\n\npublic interface Main {\n void hello();\n}\n",
|
||||
}],
|
||||
},
|
||||
{
|
||||
"textDocument": { "uri": uri_of(&path), "version": null },
|
||||
"edits": [{
|
||||
"range": { "start": { "line": 1, "character": 32 }, "end": { "line": 1, "character": 32 } },
|
||||
"newText": " implements Main",
|
||||
}],
|
||||
},
|
||||
],
|
||||
},
|
||||
"problems": [],
|
||||
}),
|
||||
);
|
||||
let pkg: Value = serde_json::from_str(&info.packages[0]).unwrap();
|
||||
let res = h
|
||||
.mgr
|
||||
.extract_interface(doc, caret, vec!["hello()".into()], "Main".into(), pkg, None, Default::default())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(res.problems.is_empty());
|
||||
assert!(res.confirmation.is_none());
|
||||
let edit = res.edit.expect("expected workspace edit");
|
||||
assert!(matches!(&edit.files[0], FileEdit::Create { path: p, .. } if p.as_ref() == iface_path.as_path()));
|
||||
// UTF-8 byte col 32 on line 1 (`/* 😀 */ public class MainImpl|`) converts back to UTF-16 col 30.
|
||||
assert!(matches!(
|
||||
&edit.files[2],
|
||||
FileEdit::Edit { edits, .. } if edits[0].range == rng(1, 30, 1, 30) && edits[0].new_text == " implements Main"
|
||||
));
|
||||
assert_eq!(
|
||||
ja.requested("java-analyzer/extractInterface")[0],
|
||||
json!({
|
||||
"textDocument": { "uri": uri_of(&path) },
|
||||
"position": { "line": 1, "character": 24 },
|
||||
"name": "Main",
|
||||
"package": "app",
|
||||
"members": ["hello()"],
|
||||
})
|
||||
);
|
||||
assert!(jdtls.requested("java/getRefactorEdit").is_empty());
|
||||
|
||||
// Pre-cancelled token returns Cancelled without falling back to jdtls.
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
let err = h.mgr.extract_interface_info(doc, caret, cancel).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert!(jdtls.requested("java/checkExtractInterfaceStatus").is_empty());
|
||||
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn extract_interface_falls_back_to_jdtls_without_capability() {
|
||||
// Older java-analyzer without the experimental capability: route to jdtls instead.
|
||||
let h = harness_configured(
|
||||
"java",
|
||||
"java",
|
||||
&[("java-analyzer", incremental_caps()), ("jdtls", incremental_caps())],
|
||||
|_| {},
|
||||
);
|
||||
let (doc, path) = h.open("Shape.java", "package a;\npublic class Shape { public double area() { return 0; } }\n");
|
||||
for name in ["java-analyzer", "jdtls"] {
|
||||
h.wait_status(name, ServerStatus::Ready).await;
|
||||
}
|
||||
let (ja, jdtls) = (h.launcher.state("java-analyzer"), h.launcher.state("jdtls"));
|
||||
eventually(|| !jdtls.notified("textDocument/didOpen").is_empty()).await;
|
||||
|
||||
jdtls.respond(
|
||||
"java/checkExtractInterfaceStatus",
|
||||
json!({
|
||||
"subTypeName": "Shape",
|
||||
"members": [{ "name": "area", "typeName": "double", "parameters": [], "handleIdentifier": "h1" }],
|
||||
"destinationResponse": { "destinations": [{ "displayName": "a", "isParentOfSelectedFile": true }] },
|
||||
}),
|
||||
);
|
||||
let info = h.mgr.extract_interface_info(doc, Pos::new(1, 13), Default::default()).await.unwrap();
|
||||
assert_eq!(info.class_name, "Shape");
|
||||
assert_eq!(jdtls.requested("java/checkExtractInterfaceStatus").len(), 1);
|
||||
assert!(ja.requested("java-analyzer/extractInterfaceInfo").is_empty());
|
||||
|
||||
jdtls.respond(
|
||||
"java/getRefactorEdit",
|
||||
json!({
|
||||
"edit": { "changes": { uri_of(&path): [] } },
|
||||
}),
|
||||
);
|
||||
let pkg: Value = serde_json::from_str(&info.packages[0]).unwrap();
|
||||
let res = h
|
||||
.mgr
|
||||
.extract_interface(doc, Pos::new(1, 13), vec!["h1".into()], "HasArea".into(), pkg, None, Default::default())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(res.edit.is_some());
|
||||
assert_eq!(jdtls.requested("java/getRefactorEdit").len(), 1);
|
||||
assert!(ja.requested("java-analyzer/extractInterface").is_empty());
|
||||
h.mgr.shutdown_all().await;
|
||||
|
||||
// Without jdtls and without the capability, reports Unavailable.
|
||||
let h = harness_configured("java", "java", &[("java-analyzer", incremental_caps())], |_| {});
|
||||
let (doc, _) = h.open("Shape.java", "package a;\npublic class Shape {}\n");
|
||||
h.wait_status("java-analyzer", ServerStatus::Ready).await;
|
||||
let err = h.mgr.extract_interface_info(doc, Pos::new(1, 13), Default::default()).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -1307,3 +1307,37 @@ pub struct PluginDatabaseTableSchema {
|
||||
pub indexes: Vec<PluginDatabaseIndex>,
|
||||
pub foreign_keys: Vec<PluginDatabaseForeignKey>,
|
||||
}
|
||||
/// Non-secret identity of an already-connected project data source (API 1.21).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginConnectedDataSource {
|
||||
pub source_id: String,
|
||||
pub name: String,
|
||||
pub driver: String,
|
||||
pub database: Option<String>,
|
||||
}
|
||||
/// Summary of a table or view in a connected schema (API 1.21).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginDatabaseTableSummary {
|
||||
pub name: String,
|
||||
pub kind: String,
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
/// Column metadata of a query result (API 1.21).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginDatabaseQueryColumn {
|
||||
pub name: String,
|
||||
pub type_name: String,
|
||||
}
|
||||
/// Bounded result of executing a SQL statement on a connected source (API 1.21).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginDatabaseQueryResult {
|
||||
pub columns: Vec<PluginDatabaseQueryColumn>,
|
||||
pub rows: Vec<Vec<Option<String>>>,
|
||||
pub affected: Option<u64>,
|
||||
pub has_more: bool,
|
||||
pub elapsed_ms: u64,
|
||||
}
|
||||
@@ -3491,6 +3491,114 @@ impl bindings::openidea::plugin::database::Host for StoreData {
|
||||
})
|
||||
.map_err(to_wit))
|
||||
}
|
||||
fn connected_sources(
|
||||
&mut self,
|
||||
project: Resource<ProjectRes>,
|
||||
) -> Fallible<Vec<bindings::openidea::plugin::database::ConnectedSource>> {
|
||||
if let Err(e) = self.require(Capability::DatabaseSchema) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&project)?.root.clone();
|
||||
let result = self.host.database_connected_sources(&root, self.client());
|
||||
if result.is_err() {
|
||||
self.grant_io_error_grace();
|
||||
}
|
||||
use bindings::openidea::plugin::database as db;
|
||||
Ok(result
|
||||
.map(|sources| {
|
||||
sources
|
||||
.into_iter()
|
||||
.map(|s| db::ConnectedSource {
|
||||
source_id: s.source_id,
|
||||
name: s.name,
|
||||
driver: s.driver,
|
||||
database: s.database,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.map_err(to_wit))
|
||||
}
|
||||
fn list_schemas(&mut self, project: Resource<ProjectRes>, source_id: String) -> Fallible<Vec<String>> {
|
||||
if let Err(e) = self.require(Capability::DatabaseSchema) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&project)?.root.clone();
|
||||
let result =
|
||||
self.host.database_list_schemas(&root, self.client(), &source_id, &self.cancel.token(), self.io_timeout());
|
||||
if result.is_err() {
|
||||
self.grant_io_error_grace();
|
||||
}
|
||||
Ok(result.map_err(to_wit))
|
||||
}
|
||||
fn list_tables(
|
||||
&mut self,
|
||||
project: Resource<ProjectRes>,
|
||||
source_id: String,
|
||||
schema: String,
|
||||
) -> Fallible<Vec<bindings::openidea::plugin::database::TableSummary>> {
|
||||
if let Err(e) = self.require(Capability::DatabaseSchema) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&project)?.root.clone();
|
||||
let result = self.host.database_list_tables(
|
||||
&root,
|
||||
self.client(),
|
||||
&source_id,
|
||||
&schema,
|
||||
&self.cancel.token(),
|
||||
self.io_timeout(),
|
||||
);
|
||||
if result.is_err() {
|
||||
self.grant_io_error_grace();
|
||||
}
|
||||
use bindings::openidea::plugin::database as db;
|
||||
Ok(result
|
||||
.map(|tables| {
|
||||
tables
|
||||
.into_iter()
|
||||
.map(|t| db::TableSummary { name: t.name, kind: t.kind, comment: t.comment })
|
||||
.collect()
|
||||
})
|
||||
.map_err(to_wit))
|
||||
}
|
||||
fn execute_query(
|
||||
&mut self,
|
||||
project: Resource<ProjectRes>,
|
||||
source_id: String,
|
||||
sql: String,
|
||||
max_rows: Option<u32>,
|
||||
) -> Fallible<bindings::openidea::plugin::database::QueryResult> {
|
||||
if let Err(e) = self.require(Capability::DatabaseQuery) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&project)?.root.clone();
|
||||
let result = self.host.database_execute_query(
|
||||
&root,
|
||||
self.client(),
|
||||
&source_id,
|
||||
&sql,
|
||||
max_rows,
|
||||
&self.cancel.token(),
|
||||
self.io_timeout(),
|
||||
);
|
||||
if result.is_err() {
|
||||
self.grant_io_error_grace();
|
||||
}
|
||||
use bindings::openidea::plugin::database as db;
|
||||
Ok(result
|
||||
.map(|r| db::QueryResult {
|
||||
columns: r
|
||||
.columns
|
||||
.into_iter()
|
||||
.map(|c| db::QueryColumn { name: c.name, type_name: c.type_name })
|
||||
.collect(),
|
||||
rows: r.rows,
|
||||
affected: r.affected,
|
||||
has_more: r.has_more,
|
||||
elapsed_ms: r.elapsed_ms,
|
||||
})
|
||||
.map_err(to_wit))
|
||||
}
|
||||
fn upsert_source(
|
||||
&mut self,
|
||||
project: Resource<ProjectRes>,
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
8fec8f3f93d13050a7d7579ba6e29baf2b8654777971f59087f34f2540fdf23d
|
||||
fbd767ccf69c37807aa8f535197ab9fac47f809ef887ab9fd99c0b2886201ae1
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
9046ec47087a78f8a99f9f57b04178df91c31c7ea2dedf7610ee9ebfb5a2fb9f
|
||||
583b5ee3f495851ca14c378a3a4fe4cfd92be772e5f33a383d4f3b9f935f4b7e
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
69644d5a8240e9407889df1b48400b1c89c6a9e15873dd47dca3015aceaf580b
|
||||
a29fb8d12bc4bb7fdba146706ce941ecfce1e4ddecdbbe1672aac88b1adfb4da
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
7556cd36ed5769f3961abc67a2906c50e8b639f98a7ce631b8b7589c96f60291
|
||||
f99c40e69fba8d835f578dc6d1dc2a078ad774d881ae454e3703d5d150cf2c8d
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
1e83a86f4a3f9ec70a8489e9d172f2a3829d2fa8546ca9c93deec9c05f899483
|
||||
c732a0688e0cfcd71ce8471c4d929e5e5496461e44ef705a2bf468fad62b4ae8
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
ebeb0be05062276fd9b24dae57c72fa58bc35ce054b4639687d4c3280c14300e
|
||||
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 @@
|
||||
2a1f38092bb34e9864e9607a08521f8cf7dc74f24ad4bea4c4f7d021b41b34f5
|
||||
33020cf1117fc910e2984a2bd0110924cf5ffdf24ae015bf191762993c06c532
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
0d64b659501e637eac7dc586d2e6bc7db09c7c6ea369dc8b3c6db7dc9b006787
|
||||
9923493b942447f729a8568de02e3d02c3d59b3d7468f569a1ae978adaa3176d
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
f89bc44615d6b340046d9247f0f328a5d22a2ffafdfb34ce9e6356fc6d4b403a
|
||||
d12f681411fda1fed05e537f291705a3ce26faa009044fdf9d0a01b964fc0056
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
008368cbac33887301d5bea31f1f090e0ba785a96ef3edc213da54299686d26d
|
||||
893ce9fe2bb20cd5adc34794ad3ddc1c8779631fecf4d14dfa51290f55eb0377
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
bd66e872b60c7cf3919381257654f21407f86d47d84d884c7e8a357f9ad1b169
|
||||
c5ec51674a2c7556ffd65ac856dbe68e024a6d9361348653b6ff32d31dcf3ff8
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
b4b5b2286bc842d93aaaa49ec13579c21b1c3a3d0d7d44fa6e8e1b1a99e2cb8b
|
||||
9212ac37ebb4e2a4c09afccec3d29ffd4ad6fb77a5444b108dc5381a66b3f3fd
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
7b84a518235f863e893e244c84d3d782049465a3176eb27ea27779c7cdd57c59
|
||||
a0c79f2e2798894eaea06ccbf7c1a80cfb269817563273ede8ade9903b310f78
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
b07a8f999a1c34cf1e437641c52ac9070c62ee933fe615ce490bc74e9eda5d44
|
||||
d2c95eb484ec574031ea01e77e32fca49f5dca0b419a2ed9d6556c3db6810d4c
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
abf565f7c718c6647a5a170131de1abc5e16345a759060640bcdfe732921a9e7
|
||||
82bdefebd3747dcda62acd8e9a11eb9e8ef137fddb0c29c5011c475cb184530b
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
2606ddcd55d3659ca29f2db12bd239124eb580fd96e273e8eacdc1df45be9275
|
||||
5c383892b3c7345d2d230da7c4e5b3f1e1e1899491e0cf3df8ce3b02c41b5154
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
2ec881b3b984095389583c115de6a60dff6c6fef6888682b5113237c9459167e
|
||||
11287c6ce9ad5b964ad730ccfd2ee846c6cc0a671b83f86daad78891e2463aba
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
a7712d7ae6dc79713432a62544571ed25a0f752bdf8cc8de01701958e3853ff7
|
||||
a912aed6c1a64745240d16e6b8e69c7966023d7001ca712ccad32b8d1918e3df
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
0631360ca5b16015bc94cd461e562f37b24e982ac5b6dd6fa78ed87fd4ae0c54
|
||||
76d52287de2178c4f7f19286a6fe387faf9c33d4d84e19dc6d447ad42b858256
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
eecb2014a22c74ebfe5a33ca8ad9ceeef139663f07f0f1216d0f777ac3f3fae2
|
||||
87f6d2121aec400c280cc4c0d1b1cca762c7bad8432b833d0ee2b5b17002c733
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
8f9c04d37ee46cfdcd63fe101b9c84937ad1ea52b8c8051aea73c9e9c5fb9735
|
||||
ed2c0bb9f9f91744b49e3e22240df3bb3a08eda6473013bf16e82946ac113a58
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
cfd459348ed64a64e86660c25db1163ce16a2f0bc9c74fda721f26980d0c16f2
|
||||
e9673042b2e02fa544fdcc1f80a80b05765f3b9d30055668ad537ef59f19a2e2
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
b34cea4bfdafae31c609581a295e20556be3b16b7d3a2a09b3bff0b059d63455
|
||||
bc3e3af1b33eb2dab9d05caddb0c4f60205dbf4513d2afb39034f20e1364c471
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
1e44c2bf968fec294827f666f522e08db6b899431a02b53ca61a1a9aa9c77cd0
|
||||
e19f1b0b2f46fed4ff0069e75fdc66a47cc231dc08c875076ffe4e90177a7228
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
cc2ecd77d2f7521c92496e659f8cd9e461d175d3acaf0740771ec8e3157b844a
|
||||
57cf79449c2e030badd366fad9ba95d38e4988ccb7ff6d597eba250ded2722ff
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
d77719fdf8df15baedfc6de0e9e1b3a14344405892468eda0edba244a63bf8d9
|
||||
bf9bff2aab8b32205131fdc961d084a8ca4b5553bfb52b9690cdb51c2bff43ed
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
55424888269455182c05a6dbd781460fbe51fec3d26116fd3026d593317a07bb
|
||||
ec5994ac7a65203eb036af1ff58275ca543295b41d60644d48b00461a99f9c63
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
30e6598f5d9ab7aa3fb0a26b3e382fc9451c06b8c685c82a7cbf890a55ce3c05
|
||||
cf48e6cd63b356a864e2b89beb2819540e6351854a70c0b258ba5170932c9749
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
7e35c37420037f87f669ad2ff2f3ad6133f36ff7bfcef0a2724fbcda3b036133
|
||||
f61c925836203778feabab5df85ed96a36b4d9a1fca76144e216c9bdb3b80f76
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
08a7c7b6cd212506d3580114f9b57f14cd99e9db4673ee7cb048971815f55295
|
||||
b576ff8d2e7ea172b0fa9f4a666d5f055add50cd2dc522ccf9395768b398e5e2
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
2b0bb4b5932d3c337376a6090bfd5c5af5de7bd42831c419fad9d373c5932191
|
||||
53bb516f95537947d936f5c35598ea0f66c77611058131f7a6518f7c00540e0e
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
056274122bb131ebbfad8adf21600109dec13b3e2b4f46d8f81f0d536646c960
|
||||
83bda60bbf1efbe3912bbe46f4ba25d7ab44f3c85ce41d5b737a840003f58e02
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
aaa370a35257b58871dab1617b452ac2b3cb60a82fd48a7ce94958b69f6791d6
|
||||
eb6887c297f9b5657ceefcbaa57c09fc965d80e48744a67fdbda2e227d24696f
|
||||
Loaded 100 of 303 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача