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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 4f697bf274 fix(settings): align field edges across settings sections 2026-12-02 19:07:39 +08:00
Ivan 2221afad01 feat(mcp): tools for the project's dev container (#7378)
Five MCP tools report, start, rebuild and run commands in the project's dev container through the IDE's own Docker and Dev Containers support, inside its trust checks and confirmations.

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

Closes #7293

Co-authored-by: Pecnikas <[email protected]>
2026-12-02 19:06:17 +08:00
45 змінених файлів з 2401 додано та 417 видалено

No files matched your search

+1 -1
Переглянути файл
@@ -63,7 +63,7 @@ pub(crate) fn stream_batched<T>(
}
}
flush(&mut batch, on_batch);
Ok((lines.finish(cancel)?, stderr_tail))
Ok((lines.finish(cancel)?.success(), stderr_tail))
}
#[cfg(all(test, unix))]
+5 -5
Переглянути файл
@@ -175,7 +175,7 @@ impl CliTool {
Poll::Finished => break,
}
}
Ok((lines.finish(cancel)?, stderr_tail))
Ok((lines.finish(cancel)?.success(), stderr_tail))
}
/// Starts `cmd` with a reader thread per pipe, for a caller that drives the loop itself
@@ -301,9 +301,9 @@ impl Lines {
}
}
/// Waits for the child to exit and returns whether it did so successfully. Fails, after
/// killing it, when `cancel` fires first.
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<bool> {
/// Waits for the child to exit and returns how it exited. Fails, after killing it, when
/// `cancel` fires first.
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<std::process::ExitStatus> {
let status = loop {
if let Some(status) = self.child.try_wait()? {
break status;
@@ -314,6 +314,6 @@ impl Lines {
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(status.success())
Ok(status)
}
}
+9
Переглянути файл
@@ -11,6 +11,14 @@ use specta::Type;
use std::collections::BTreeMap;
use std::sync::Arc;
/// The execution target recorded with an MCP agent run.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum McpAgentRunTarget {
Host,
Container { id: String },
}
/// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
@@ -42,6 +50,7 @@ pub enum McpUiRequest {
command: String,
cwd: crate::IpcPath,
env: BTreeMap<String, String>,
target: McpAgentRunTarget,
},
RunConfiguration {
#[specta(type = specta_typescript::Unknown)]
+5
Переглянути файл
@@ -403,6 +403,11 @@ pub(crate) fn snapshot(ep: &DockerEndpoint, timeout: Duration) -> Option<DockerS
Some(snap)
}
/// Every container (`docker ps --all`).
pub(crate) fn containers(ep: &DockerEndpoint, timeout: Duration) -> Option<IdeResult<Vec<DockerContainer>>> {
Some(list_containers(&address(ep)?, timeout))
}
fn list_containers(addr: &Address, timeout: Duration) -> IdeResult<Vec<DockerContainer>> {
let body = check(request(addr, "GET", "/containers/json?all=1", timeout)?)?;
Ok(map_containers(&body))
+19
Переглянути файл
@@ -193,6 +193,25 @@ pub fn snapshot(ep: &DockerEndpoint) -> DockerSnapshot {
snap
}
/// The containers (running or not) that carry every label in `labels`, each `key=value` (or
/// just `key`): `docker ps --all --filter label=…`.
pub fn containers(ep: &DockerEndpoint, labels: &[String]) -> IdeResult<Vec<DockerContainer>> {
if docker_executable().is_none()
&& let Some(listed) = engine::containers(ep, QUICK)
{
let has = |c: &DockerContainer, label: &String| match label.split_once('=') {
Some((key, value)) => c.labels.get(key).is_some_and(|v| v == value),
None => c.labels.contains_key(label),
};
return listed.map(|all| all.into_iter().filter(|c| labels.iter().all(|l| has(c, l))).collect());
}
let filters: Vec<String> = labels.iter().flat_map(|l| ["--filter".to_owned(), format!("label={l}")]).collect();
let mut args: Vec<&str> = vec!["ps", "--all", "--no-trunc"];
args.extend(filters.iter().map(String::as_str));
args.extend(["--format", PS_FORMAT]);
run(ep, &args, QUICK).map(|text| parse_containers(&text))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum ContainerOp {
+72
Переглянути файл
@@ -0,0 +1,72 @@
//! Dev containers as the backend sees them: the Dev Containers CLI, and which containers a
//! window is open in.
use ide_core::{IdeError, IdeResult};
use parking_lot::Mutex;
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// The Dev Containers CLI: the IDE-managed copy (Settings › Languages & Frameworks › Language Servers) or one on `PATH`.
pub fn cli(data_dir: &Path) -> IdeResult<PathBuf> {
ide_tools::Tools::new(data_dir)
.info("devcontainer", &[])
.ok()
.and_then(|t| t.path)
.map(ide_core::IpcPath::into_path_buf)
.ok_or_else(|| {
IdeError::unavailable(
"The Dev Containers CLI is not installed. Install it in Settings › Languages & Frameworks › Language Servers.",
)
})
}
/// The containers a window is attached to (Reopen in Container), by id. A container may be held
/// by more than one window.
#[derive(Default)]
pub struct AttachedContainers(Mutex<Vec<String>>);
impl AttachedContainers {
/// Marks `id` attached until the returned guard is dropped.
pub fn hold(self: &Arc<Self>, id: &str) -> AttachedContainer {
self.0.lock().push(id.to_owned());
AttachedContainer { set: self.clone(), id: id.to_owned() }
}
/// Whether a window is attached to the container `id` (a full id or a prefix of one).
pub fn contains(&self, id: &str) -> bool {
!id.is_empty() && self.0.lock().iter().any(|held| held.starts_with(id) || id.starts_with(held.as_str()))
}
}
/// A window's attachment to a container, released on drop.
pub struct AttachedContainer {
set: Arc<AttachedContainers>,
id: String,
}
impl Drop for AttachedContainer {
fn drop(&mut self) {
let mut held = self.set.0.lock();
if let Some(at) = held.iter().position(|id| *id == self.id) {
held.remove(at);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_container_stays_attached_until_every_window_released_it() {
let set = Arc::new(AttachedContainers::default());
let id = "3f1c2b9a7d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8";
let (first, second) = (set.hold(id), set.hold(id));
assert!(set.contains(id) && set.contains(&id[..12]));
assert!(!set.contains("ffffffffffff") && !set.contains(""));
drop(first);
assert!(set.contains(id));
drop(second);
assert!(!set.contains(id));
}
}
+12
Переглянути файл
@@ -9,6 +9,7 @@ pub mod catalogue;
#[cfg(unix)]
pub mod daemon;
pub mod data_dirs;
pub mod devcontainer;
pub mod diagnostics_store;
mod direnv;
pub mod environment;
@@ -91,6 +92,7 @@ impl HostConfig {
}
pub struct Host {
pub(crate) local_desktop: bool,
local_database_tunnels: bool,
/// Finders of non-Git working copies ([`Host::with_vcs_provider`]); Git is built in.
pub(crate) vcs_providers: Vec<Arc<dyn ide_vcs::BackendProvider>>,
@@ -106,6 +108,8 @@ pub struct Host {
pub mcp_requests: mcp::Requests,
/// Commands agents run in the Run tool window (`run_command`).
pub mcp_agent_runs: mcp::AgentRuns,
/// Dev containers a window is attached to; the MCP tools leave them alone.
pub dev_containers_attached: Arc<devcontainer::AttachedContainers>,
/// Projects the MCP server serves without a window.
pub mcp_background: mcp::BackgroundProjects,
/// Host-owned scheduled agent automations and in-session follow-up timers.
@@ -212,6 +216,12 @@ impl Host {
windows
}
/// Enables tools that control services on the local desktop.
pub fn with_local_desktop(mut self) -> Self {
self.local_desktop = true;
self
}
/// Enables user-approved database helper processes on the local desktop.
pub fn with_local_database_tunnels(mut self) -> Self {
self.local_database_tunnels = true;
@@ -262,6 +272,7 @@ impl Host {
let automations = automations::AutomationService::new(&data_dir, boot_override);
let host = Self {
plugin_host: RwLock::default(),
local_desktop: false,
local_database_tunnels: false,
vcs_providers: Vec::new(),
subversion: None,
@@ -271,6 +282,7 @@ impl Host {
mcp_reports: Default::default(),
mcp_requests: Default::default(),
mcp_agent_runs: Default::default(),
dev_containers_attached: Default::default(),
mcp_background: Default::default(),
automations,
agent_catalogs: Arc::default(),
+894
Переглянути файл
@@ -0,0 +1,894 @@
//! `devcontainer_*`: the project's dev container for agents. Which container is the project's
//! is decided by the labels the Dev Containers CLI puts on it (folder and configuration file);
//! nothing else is ever touched. Starting and running go through the CLI, listing, logs and
//! stopping through `ops::docker`.
use super::run::agent::{Execution, tab_name};
use super::run::agent_tools::{
INTERVENTIONS, MAX_LINES, NAME, OUTPUT, SEQUENCE, TRUNCATE_MODE, Tab, busy, start_in_tab,
};
use super::run::timeout;
use super::tool::{Call, Output, Param, ParamType, Tool, ensure_inside};
use crate::Host;
use crate::ops::docker as ops;
use ide_core::{IdeError, IdeResult};
use ide_docker::{DockerAvailability, DockerContainer, DockerEndpoint, DockerObject};
use ide_remote::devcontainer::{CONFIG_LABEL, FOLDER_LABEL, Target, UP_TIMEOUT, label_value};
use serde_json::{Map, Value, json};
use std::path::{Path, PathBuf};
const EXEC_TIMEOUT_MS: usize = 120_000;
const DEFAULT_TAIL: i64 = 200;
const MAX_TAIL: i64 = 5000;
const COMPOSE_PROJECT: &str = "com.docker.compose.project";
const CONFIG_NAMES: [&str; 2] = ["devcontainer.json", ".devcontainer.json"];
const CONFIG: &str = "Which configuration file to use: a path inside the project to a `devcontainer.json` or \
`.devcontainer.json`. Default: `.devcontainer/devcontainer.json`, else `.devcontainer.json` (`devcontainer_status` \
lists the others)";
const WHICH: &str = "The project's container is the one the Dev Containers CLI started for the project folder and \
configuration file (its `devcontainer.local_folder` and `devcontainer.config_file` labels), plus the other containers \
of its Docker Compose project; no other container is ever touched. Needs Docker on this machine.";
pub fn tools() -> Vec<Tool> {
vec![status(), logs(), up(), exec(), stop()]
}
// ---- which container is the project's ----
/// Containers with both project labels, running before stopped, then newest.
fn project_containers(mut candidates: Vec<DockerContainer>, target: &Target) -> Vec<DockerContainer> {
let Some(config) = target.config_label() else { return Vec::new() };
let folder = target.folder_label();
candidates.retain(|c| {
let label = |key: &str| c.labels.get(key).map(|value| label_value(value));
label(FOLDER_LABEL).as_deref() == Some(&folder) && label(CONFIG_LABEL).as_deref() == Some(&config)
});
// `created_at` is docker's `2026-01-02 03:04:05 +0000 UTC`: newest sorts last as text.
candidates.sort_by(|a, b| b.running().cmp(&a.running()).then_with(|| b.created_at.cmp(&a.created_at)));
candidates
}
/// The project's containers.
#[derive(Default)]
struct Found {
primary: Option<DockerContainer>,
/// Other containers with the project's labels, such as one left from before a rebuild.
stale: Vec<DockerContainer>,
/// The other containers of the primary's Compose project.
siblings: Vec<DockerContainer>,
}
impl Found {
fn primary_id(&self) -> Option<&str> {
self.primary.as_ref().map(|c| c.id.as_str())
}
fn all(&self) -> impl Iterator<Item = &DockerContainer> {
self.primary.iter().chain(&self.stale).chain(&self.siblings)
}
/// What `stop` acts on: the primary and its Compose project.
fn running_group(&self) -> Vec<&DockerContainer> {
self.primary.iter().chain(&self.siblings).filter(|c| c.running()).collect()
}
}
async fn find(host: &Host, target: &Target) -> IdeResult<Found> {
if target.config().is_none() {
return Ok(Found::default());
}
let ep = || DockerEndpoint::Default;
let folder =
ops::containers_with_labels(host, ep(), vec![format!("{FOLDER_LABEL}={}", target.folder_label())]).await?;
let mut matching = project_containers(folder, target).into_iter();
let primary = matching.next();
let stale: Vec<DockerContainer> = matching.collect();
let mut siblings = Vec::new();
if let Some(project) = primary.as_ref().and_then(|p| p.compose_project.clone()) {
let members = ops::containers_with_labels(host, ep(), vec![format!("{COMPOSE_PROJECT}={project}")]).await?;
siblings = siblings_of(primary.as_ref().unwrap(), members);
}
Ok(Found { primary, stale, siblings })
}
/// The other containers of `primary`'s Compose project. Another checkout may give its project the
/// same name, so only those of the same working directory, which the primary has to have.
fn siblings_of(primary: &DockerContainer, members: Vec<DockerContainer>) -> Vec<DockerContainer> {
let dir = primary.compose_working_dir.as_deref();
let same = |c: &DockerContainer| dir.is_some() && c.compose_working_dir.as_deref() == dir;
members
.into_iter()
.filter(|c| {
same(c)
&& c.id != primary.id
&& !c.labels.contains_key(FOLDER_LABEL)
&& !c.labels.contains_key(CONFIG_LABEL)
})
.collect()
}
/// The container `containerId` names, among the project's containers: the primary without one.
fn choose<'a>(found: &'a Found, wanted: Option<&str>) -> IdeResult<&'a DockerContainer> {
let Some(wanted) = wanted.map(str::trim).filter(|w| !w.is_empty()) else {
return found.primary.as_ref().ok_or_else(|| {
IdeError::not_found("this project has no dev container yet; start it with devcontainer_up")
});
};
let wanted = wanted.to_ascii_lowercase();
let mut hits = found.all().filter(|c| wanted.len() >= 12 && c.id.to_ascii_lowercase().starts_with(&wanted));
match (hits.next(), hits.next()) {
(Some(container), None) => Ok(container),
_ => Err(IdeError::invalid(format!("container {wanted} does not belong to this project's dev container"))),
}
}
fn describe(container: &DockerContainer) -> String {
format!("{} ({})", container.name, ide_docker::short_id(&container.id))
}
// ---- docker, the CLI and the arguments ----
/// Docker is installed, its daemon answers and is on this machine (the project folder is
/// bind-mounted, and its labels name this machine's folders).
fn daemon() -> IdeResult<()> {
match ide_docker::availability(&DockerEndpoint::Default) {
DockerAvailability::Ready { .. } => {}
DockerAvailability::NotInstalled => return Err(IdeError::unavailable("Docker is not installed")),
DockerAvailability::DaemonDown { message, .. } => return Err(IdeError::unavailable(message)),
}
if ide_docker::endpoint_is_local(&DockerEndpoint::Default)? {
Ok(())
} else {
Err(IdeError::unavailable(
"The Docker daemon of the current context is not on this machine; dev containers need a local one.",
))
}
}
async fn docker_ready(host: &Host) -> IdeResult<()> {
host.blocking(daemon).await
}
fn is_config_file(path: &Path) -> bool {
path.file_name().and_then(|n| n.to_str()).is_some_and(|n| CONFIG_NAMES.contains(&n))
}
/// The folder and configuration the call is about: the project root as opened, and `config`
/// (or the default one) joined to it, as the CLI is given them and labels the container.
fn target(call: &Call) -> IdeResult<Target> {
let root = call.root();
let config = match call.opt_str("config")?.map(|c| c.trim().to_owned()).filter(|c| !c.is_empty()) {
Some(raw) => {
let real = call.resolve_inside(&raw)?;
if !is_config_file(&real) {
return Err(IdeError::invalid("config must be a devcontainer.json or .devcontainer.json file"));
}
if !real.is_file() {
return Err(IdeError::not_found(format!("config {raw} does not exist")));
}
let base = dunce::canonicalize(root)?;
let inside =
real.strip_prefix(&base).map_err(|_| IdeError::invalid("config must be inside the project"))?;
Some(root.join(inside))
}
None => {
let config = ide_workspace::devcontainer::find(root);
if let Some(config) = &config {
ensure_inside(root, config)?;
}
config
}
};
Ok(Target::new(root, config))
}
/// Every configuration file of the project the CLI can be pointed at.
fn config_files(root: &Path) -> Vec<PathBuf> {
let dir = root.join(".devcontainer");
let mut files = vec![dir.join("devcontainer.json"), root.join(".devcontainer.json")];
if ensure_inside(root, &dir).is_ok() {
let mut named: Vec<PathBuf> = std::fs::read_dir(&dir)
.into_iter()
.flatten()
.flatten()
.map(|e| e.path().join("devcontainer.json"))
.collect();
named.sort();
files.extend(named);
}
files.retain(|f| f.is_file() && ensure_inside(root, f).is_ok());
files
}
/// The error of a project without a configuration the tools can use by default.
fn no_config(call: &Call) -> IdeError {
let root = call.root().display();
let others: Vec<String> = config_files(call.root()).iter().map(|f| call.display(f)).collect();
if others.is_empty() {
return IdeError::not_found(format!("{root} has no devcontainer.json"));
}
IdeError::not_found(format!(
"{root} has no .devcontainer/devcontainer.json or .devcontainer.json: pass `config` with one of {}",
others.join(", ")
))
}
/// `timeout` in milliseconds for a start: a positive number.
fn start_timeout(call: &Call) -> IdeResult<std::time::Duration> {
if call.opt_i64("timeout")?.is_some_and(|n| n <= 0) {
return Err(IdeError::invalid("timeout must be positive"));
}
timeout(call, UP_TIMEOUT.as_millis() as usize)
}
fn tail_of(tail: Option<i64>) -> IdeResult<u32> {
match tail.unwrap_or(DEFAULT_TAIL) {
n @ 1..=MAX_TAIL => Ok(n as u32),
_ => Err(IdeError::invalid(format!("tail must be between 1 and {MAX_TAIL}"))),
}
}
/// `envs` as `(name, value)`: names a shell accepts.
fn envs_of(call: &Call) -> IdeResult<Vec<(String, String)>> {
let Some(value) = call.args.get("envs").filter(|v| !v.is_null()) else { return Ok(Vec::new()) };
if !value.is_object() {
return Err(IdeError::invalid("envs must be an object"));
}
let envs = call.str_map("envs")?;
for (name, value) in &envs {
let valid = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
if !valid {
return Err(IdeError::invalid(format!("envs: `{name}` is not a valid variable name")));
}
if value.contains('\0') {
return Err(IdeError::invalid(format!("envs: the value of {name} contains a NUL character")));
}
}
Ok(envs)
}
/// Pass the full approved ID to the CLI, including when the Run tab reruns this command.
fn exec_argv(
cli: &Path,
docker: &Path,
target: &Target,
container_id: &str,
envs: &[(String, String)],
command: &str,
) -> Vec<String> {
let lossy = |p: &std::ffi::OsStr| p.to_string_lossy().into_owned();
let mut argv = vec![lossy(cli.as_os_str()), "exec".to_owned()];
argv.extend(target.args().iter().map(|a| lossy(a)));
argv.extend(["--container-id".to_owned(), container_id.to_owned()]);
argv.extend(["--docker-path".to_owned(), lossy(docker.as_os_str())]);
argv.extend(envs.iter().map(|(k, v)| format!("--remote-env={k}={v}")));
argv.extend(["sh".to_owned(), "-c".to_owned(), command.to_owned()]);
argv
}
/// A command line for people: the arguments that need it in quotes.
fn shown(argv: &[String]) -> String {
let word = |a: &String| {
if !a.is_empty() && a.chars().all(|c| c.is_ascii_alphanumeric() || "-_./=:@%+,".contains(c)) {
a.clone()
} else {
format!("'{}'", a.replace('\'', r"'\''"))
}
};
argv.iter().map(word).collect::<Vec<_>>().join(" ")
}
/// Refuses to change a container a window is open in.
fn not_attached(call: &Call, containers: &[&DockerContainer], what: &str) -> IdeResult<()> {
let attached = &call.host.dev_containers_attached;
match containers.iter().find(|c| attached.contains(&c.id)) {
Some(c) => Err(IdeError::invalid(format!(
"cannot {what}: {} is open in a window (Reopen in Container). Close that window or use Rebuild Container in it.",
describe(c)
))),
None => Ok(()),
}
}
// ---- the tools ----
fn status() -> Tool {
Tool::new(
"devcontainer_status",
&format!(
"Reports the project's dev container: `configFile` (the configuration in use, relative to the project, \
or null), `configFiles` (every configuration the project has, including `.devcontainer/<name>/devcontainer.json`), \
`forwardPorts` of the configuration, the project's `containers` (`id`, `name`, `state`, `status`, `image`, `ports`, \
`service` for Docker Compose, `primary`: the one the other tools act on; none when it was never started), `docker` \
(`ready`, or why Docker cannot be used), `dockerLocal` (the Docker daemon is on this machine) and `cliInstalled` \
(the Dev Containers CLI that starts it). Starts nothing. {WHICH}"
),
|call| async move {
let target = target(&call)?;
let data_dir = call.host.local_data_dir.clone();
let cli = call.host.blocking(move || Ok(crate::devcontainer::cli(&data_dir).is_ok())).await?;
let (docker, local, found) = match docker_ready(&call.host).await {
Ok(()) => match find(&call.host, &target).await {
Ok(found) => ("ready".to_owned(), true, found),
Err(e) => (format!("cannot list the containers: {}", e.message), true, Found::default()),
},
// Not usable: say why, and whether the fault is only that it is not local.
Err(e) => {
let local = call
.host
.blocking(|| Ok(ide_docker::endpoint_is_local(&DockerEndpoint::Default).unwrap_or(false)))
.await?;
(e.message, local, Found::default())
}
};
let root = call.root();
let primary = found.primary.as_ref().map(|p| p.id.clone());
let containers: Vec<Value> = found
.all()
.map(|c| {
let mut v = json!({
"id": c.id, "name": c.name, "state": c.state, "status": c.status,
"image": c.image, "ports": c.ports, "primary": Some(&c.id) == primary.as_ref(),
});
if let Some(service) = &c.compose_service {
v["service"] = service.clone().into();
}
v
})
.collect();
let mut out = Map::new();
out.insert("configFile".into(), target.config().map(|c| call.display(c)).into());
let files: Vec<String> = config_files(root).iter().map(|f| call.display(f)).collect();
out.insert("configFiles".into(), files.into());
let mut ports: Vec<Value> = Vec::new();
if let Some(config) = target.config() {
match ide_workspace::devcontainer::load_file(config) {
Ok(c) => {
ports.extend(c.forward_ports.iter().map(|p| Value::from(*p)));
ports.extend(c.forward_host_ports.iter().map(|(h, p)| Value::from(format!("{h}:{p}"))));
}
Err(e) => {
out.insert("configError".into(), e.into());
}
}
}
out.insert("forwardPorts".into(), ports.into());
out.insert("containers".into(), containers.into());
out.insert("docker".into(), docker.into());
out.insert("dockerLocal".into(), local.into());
out.insert("cliInstalled".into(), cli.into());
Output::json(Value::Object(out))
},
)
.param(Param::optional("config", ParamType::String, CONFIG))
}
fn logs() -> Tool {
Tool::new(
"devcontainer_logs",
&format!(
"Reads the end of a container's log (`docker logs`): the last `tail` lines (default {DEFAULT_TAIL}, at \
most {MAX_TAIL}) of the project's dev container, or of `containerId`, which must be one of the containers \
`devcontainer_status` lists (a Compose service's, for example). Returns `containerId`, `lines` (`text`, and `stderr` \
for what the container wrote to its error output) and `truncated` (the log may go on before them). Works on a \
stopped container. {WHICH}"
),
|call| async move {
let tail = tail_of(call.opt_i64("tail")?)?;
let timestamps = call.flag("timestamps", false)?;
let wanted = call.opt_str("containerId")?;
let target = target(&call)?;
docker_ready(&call.host).await?;
let found = find(&call.host, &target).await?;
let id = choose(&found, wanted.as_deref())?.id.clone();
let lines =
ops::log_tail(&call.host, DockerEndpoint::Default, id.clone(), tail, timestamps, call.cancel.clone())
.await?;
let truncated = lines.len() >= tail as usize;
let lines: Vec<Value> = lines.iter().map(|l| json!({ "text": l.text, "stderr": l.stderr })).collect();
Output::json(json!({ "containerId": id, "lines": lines, "truncated": truncated }))
},
)
.param(Param::optional("config", ParamType::String, CONFIG))
.param(Param::optional(
"containerId",
ParamType::String,
"A container of the project (at least 12 characters of its id, from `devcontainer_status`); default: the \
primary one",
))
.param(Param::optional("tail", ParamType::Integer, "Lines from the end of the log (1 to 5000, default 200)"))
.param(Param::optional("timestamps", ParamType::Boolean, "Prefix every line with its time (default false)"))
}
async fn start(call: Call) -> IdeResult<Output> {
let rebuild = call.flag("rebuild", false)?;
let target = target(&call)?;
let config = target.config().ok_or_else(|| no_config(&call))?;
let limit = start_timeout(&call)?;
let no_cache = call.flag("noCache", false)?;
if no_cache && !rebuild {
return Err(IdeError::invalid("noCache needs rebuild: true"));
}
let data_dir = call.host.local_data_dir.clone();
let (cli, docker) = call
.host
.blocking(move || {
daemon()?;
let docker =
ide_docker::docker_executable().ok_or_else(|| IdeError::unavailable("Docker is not installed"))?;
Ok((crate::devcontainer::cli(&data_dir)?, docker))
})
.await?;
let found = find(&call.host, &target).await?;
if !found.stale.is_empty() {
return Err(IdeError::unavailable("multiple dev containers match this configuration; see devcontainer_status"));
}
// Held until the start ends; a second one for the folder is refused, not queued.
let _busy = ide_remote::devcontainer::Busy::take(target.folder())?;
// Explicit labels disable the CLI's fallback to containers with the folder label alone.
let mut extra = vec![
"--id-label".to_owned(),
format!("{FOLDER_LABEL}={}", target.folder_label()),
"--id-label".to_owned(),
format!("{CONFIG_LABEL}={}", label_value(&config.to_string_lossy())),
];
if rebuild {
not_attached(&call, &found.primary.iter().collect::<Vec<_>>(), "rebuild it")?;
}
if no_cache {
extra.push("--build-no-cache".to_owned());
}
let mut command = vec!["devcontainer".to_owned(), "up".to_owned()];
command.extend(target.args().iter().map(|a| a.to_string_lossy().into_owned()));
command.extend(extra.iter().cloned());
let removed = found.primary_id().filter(|_| rebuild);
let command = match removed {
Some(id) => format!("docker container rm --force {id}\n{}", shown(&command)),
None => shown(&command),
};
let existing = found.primary.as_ref().map(describe);
let detail = format!(
"{}\n\nContainer: {}",
command,
match (&existing, rebuild) {
(Some(c), true) => format!("{c}, removed first"),
(Some(c), false) => c.clone(),
(None, _) => "none yet".to_owned(),
}
);
call.confirm(if rebuild { "Rebuild dev container" } else { "Start dev container" }, Some(detail)).await?;
docker_ready(&call.host).await?;
let current = find(&call.host, &target).await?;
if found.primary_id() != current.primary_id() || !current.stale.is_empty() {
return Err(IdeError::unavailable(
"the dev container changed while awaiting approval; call devcontainer_up again",
));
}
if rebuild {
not_attached(&call, &current.primary.iter().collect::<Vec<_>>(), "rebuild it")?;
}
ensure_inside(call.root(), config)?;
if let Some(id) = removed {
ide_workspace::devcontainer::load_file(config).map_err(IdeError::invalid)?;
if call.cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
call.project.require_trust()?;
// The CLI's rebuild flag resolves labels again. Remove only the ID shown for approval.
ops::docker_remove(&call.host, DockerEndpoint::Default, DockerObject::Container, vec![id.to_owned()], true)
.await?;
if find(&call.host, &target).await?.primary.is_some() {
return Err(IdeError::unavailable("a replacement dev container appeared; call devcontainer_up again"));
}
}
let removed = removed.map(str::to_owned);
let cancel = call.cancel.clone();
let up = call
.host
.blocking(move || {
if let Some(config) = target.config() {
ensure_inside(target.folder(), config)?;
}
let extra: Vec<&str> = extra.iter().map(String::as_str).collect();
ide_remote::devcontainer::up(
&cli,
&docker,
&target,
&extra,
limit,
&mut |line| tracing::debug!(target: "devcontainer", "{line}"),
&cancel,
)
})
.await?;
let mut out = json!({
"containerId": up.container, "remoteUser": up.user, "remoteWorkspaceFolder": up.folder, "outcome": "success",
});
if rebuild {
out["removed"] = removed.into();
}
Output::json(out)
}
fn up() -> Tool {
Tool::new(
"devcontainer_up",
&format!(
"Starts the project's dev container with the Dev Containers CLI (`devcontainer up`): builds the image \
when needed, creates or starts the container and runs the lifecycle commands of its configuration, which run the \
project's code on this machine and in the container; the user is asked first (unless the IDE runs tools without \
confirmation). With `rebuild` it removes the project's approved container first and builds \
and starts it again, to pick up a changed `devcontainer.json`, Dockerfile or features; files in the container that \
are not in the project folder or a volume are lost, and a container a window is open in is refused (use Rebuild \
Container in that window). Waits for it to finish, up to `timeout` milliseconds (default 30 minutes; the CLI is \
stopped when it passes), and returns `containerId`, `remoteUser`, `remoteWorkspaceFolder` and `outcome`, and with \
`rebuild` `removed`, the id of the container it replaced (null when there was none). An error carries the end of \
the CLI's log. One start per project folder runs at a time. {WHICH}"
),
start,
)
.write()
.param(Param::optional("config", ParamType::String, CONFIG))
.param(Param::optional(
"rebuild",
ParamType::Boolean,
"Remove the existing container and build it again (default false)",
))
.param(Param::optional(
"noCache",
ParamType::Boolean,
"With `rebuild`: build the image without Docker's cache (default false); refused without `rebuild`",
))
.param(Param::optional(
"timeout",
ParamType::Integer,
"Milliseconds to wait at most, more than 0 (default 1800000); the CLI is stopped when it passes",
))
}
fn exec() -> Tool {
Tool::new(
"devcontainer_exec",
&format!(
"Runs a shell command line in the project's running dev container (`devcontainer exec`: as the \
configuration's `remoteUser`, with its `remoteEnv`, in the project folder of the container), in a new or reused \
tab of OpenIDEA's Run tool window, as `run_command` does in the shell of this machine: the user is asked first \
(unless the IDE runs tools without confirmation), and the call returns when the command finishes, its output \
matches `pattern` or `timeout` milliseconds (default {EXEC_TIMEOUT_MS}) pass, with the same result (`state`, \
`exitCode`, `output`, `waitEnded`…) plus `containerId`; `wait_for_run`, `read_run_output`, `get_run_status`, \
`send_run_input` and `stop_run` follow it up by name. Stopping the tab ends the CLI on this machine; a process it \
started in the container may keep running there. The container must be running (see `devcontainer_status`, \
`devcontainer_up`). {WHICH}{OUTPUT}{SEQUENCE}{INTERVENTIONS}"
),
|call| async move {
call.needs_window()?;
let name = tab_name(&call.str("name")?)?;
let command = call.str("command")?;
if command.trim().is_empty() {
return Err(IdeError::invalid("command must not be empty"));
}
let envs = envs_of(&call)?;
let target = target(&call)?;
let config = target.config().ok_or_else(|| no_config(&call))?.to_path_buf();
if let Some(run) = call.host.mcp_agent_runs.get(call.root(), &name).filter(|r| r.running()) {
return Err(busy(&run));
}
let data_dir = call.host.local_data_dir.clone();
let (cli, docker) = call
.host
.blocking(move || {
daemon()?;
let docker = ide_docker::docker_executable()
.ok_or_else(|| IdeError::unavailable("Docker is not installed"))?;
Ok((crate::devcontainer::cli(&data_dir)?, docker))
})
.await?;
let found = find(&call.host, &target).await?;
let container = found.primary.filter(DockerContainer::running).ok_or_else(|| {
IdeError::unavailable("the dev container is not running; start it with devcontainer_up")
})?;
let argv = exec_argv(&cli, &docker, &target, &container.id, &envs, &command);
let mut detail = format!(
"{command}\n\nTab: {name}\nContainer: {}\nCommand line: {}",
describe(&container),
shown(&argv)
);
for (key, value) in &envs {
detail.push_str(&format!("\n{key}={value}"));
}
let mut extra = Map::new();
extra.insert("containerId".into(), container.id.clone().into());
let tab = Tab {
subject: "Run in dev container".into(),
command: format!("in dev container {}: {command}", container.name),
name,
detail,
cwd: call.root().to_path_buf(),
env: Vec::new(),
execution: Execution::Container { id: container.id, config, argv },
extra,
};
start_in_tab(&call, tab, EXEC_TIMEOUT_MS).await
},
)
.write()
.param(Param::required("name", ParamType::String, NAME))
.param(Param::required(
"command",
ParamType::String,
"Shell command line to run in the container with `sh -c`, e.g. `npm test` or `pytest -x`",
))
.param(Param::optional("config", ParamType::String, CONFIG))
.param(Param::optional(
"envs",
ParamType::StringMap,
"Environment variables added for this command (names of letters, digits and `_`)",
))
.param(Param::optional(
"timeout",
ParamType::Integer,
"Milliseconds to wait for the command to finish before returning (0 returns once it started); the command \
keeps running after it",
))
.param(Param::optional(
"pattern",
ParamType::String,
"Regular expression that ends the wait when the command's output matches it. `waitEnded` is then `matched`",
))
.param(Param::optional("maxLinesCount", ParamType::Integer, MAX_LINES))
.param(Param::optional("truncateMode", ParamType::String, TRUNCATE_MODE))
}
fn stop() -> Tool {
Tool::new(
"devcontainer_stop",
&format!(
"Stops the project's dev container and the other containers of its Docker Compose project \
(`docker container stop`); nothing is removed, and `devcontainer_up` starts it again. Refused for a container a \
window is open in. The user is asked first (unless the IDE runs tools without confirmation). Returns `stopped`, \
the ids of the containers that were running (none when nothing was). {WHICH}"
),
|call| async move {
let target = target(&call)?;
docker_ready(&call.host).await?;
let found = find(&call.host, &target).await?;
let running = found.running_group();
if running.is_empty() {
return Output::json(json!({ "stopped": [] }));
}
not_attached(&call, &running, "stop it")?;
let ids: Vec<String> = running.iter().map(|c| c.id.clone()).collect();
let names: Vec<String> = running.iter().map(|c| describe(c)).collect();
let mut command = vec!["docker".to_owned(), "container".to_owned(), "stop".to_owned()];
command.extend(ids.iter().cloned());
call.confirm(
"Stop dev container",
Some(format!("{}\n\nContainers: {}", shown(&command), names.join(", "))),
)
.await?;
ops::stop_containers(&call.host, DockerEndpoint::Default, ids.clone()).await?;
Output::json(json!({ "stopped": ids }))
},
)
.write()
.param(Param::optional("config", ParamType::String, CONFIG))
}
#[cfg(test)]
mod tests {
use super::*;
const ROOT: &str = "/work/app";
const CONFIG_FILE: &str = "/work/app/.devcontainer/devcontainer.json";
fn container(id: &str, labels: &[(&str, &str)]) -> DockerContainer {
DockerContainer {
id: id.repeat(64 / id.len()),
name: format!("name-{id}"),
image: "img".into(),
command: String::new(),
state: "running".into(),
status: "Up".into(),
ports: String::new(),
created_at: "2026-01-01 10:00:00 +0000 UTC".into(),
compose_project: None,
compose_service: None,
compose_working_dir: None,
compose_files: Vec::new(),
mounts: Vec::new(),
networks: Vec::new(),
labels: labels.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(),
}
}
fn target() -> Target {
Target::new(ROOT, Some(PathBuf::from(CONFIG_FILE)))
}
#[test]
fn labels_decide_which_container_is_the_projects() {
let both = container("a", &[(FOLDER_LABEL, ROOT), (CONFIG_LABEL, CONFIG_FILE)]);
let legacy = container("b", &[(FOLDER_LABEL, ROOT)]);
let other_folder = container("c", &[(FOLDER_LABEL, "/work/other"), (CONFIG_LABEL, CONFIG_FILE)]);
let other_config =
container("d", &[(FOLDER_LABEL, ROOT), (CONFIG_LABEL, "/work/app/.devcontainer/b/devcontainer.json")]);
let unlabelled = container("e", &[("com.docker.compose.project", "app")]);
let t = target();
let config_only = container("f", &[(CONFIG_LABEL, CONFIG_FILE)]);
assert!(project_containers(vec![legacy.clone()], &t).is_empty());
let matches =
project_containers(vec![both.clone(), legacy, other_folder, other_config, unlabelled, config_only], &t);
assert_eq!(matches.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(), [both.id.as_str()]);
assert!(project_containers(vec![both], &Target::new(ROOT, None)).is_empty());
}
#[test]
fn a_windows_drive_letter_is_matched_in_lower_case() {
let root = r"C:\Users\me\app";
let config = r"C:\Users\me\app\.devcontainer\devcontainer.json";
let t = Target::new(root, Some(PathBuf::from(config)));
let written = container("a", &[(FOLDER_LABEL, r"c:\Users\me\app"), (CONFIG_LABEL, config)]);
assert_eq!(project_containers(vec![written], &t).len(), 1);
assert_eq!(t.folder_label(), r"c:\Users\me\app");
}
#[test]
fn the_primary_is_running_before_stopped_and_new_before_old() {
let labels = [(FOLDER_LABEL, ROOT), (CONFIG_LABEL, CONFIG_FILE)];
let mut old_running = container("a", &labels);
old_running.created_at = "2026-01-01 10:00:00 +0000 UTC".into();
let mut new_running = container("b", &labels);
new_running.created_at = "2026-02-01 10:00:00 +0000 UTC".into();
let mut newest_stopped = container("c", &labels);
newest_stopped.created_at = "2026-03-01 10:00:00 +0000 UTC".into();
newest_stopped.state = "exited".into();
let order: Vec<String> = project_containers(vec![old_running, newest_stopped, new_running], &target())
.into_iter()
.map(|c| c.name)
.collect();
assert_eq!(order, ["name-b", "name-a", "name-c"]);
}
fn found() -> Found {
let labels = [(FOLDER_LABEL, ROOT), (CONFIG_LABEL, CONFIG_FILE)];
let mut sibling = container("d", &[("com.docker.compose.project", "app")]);
sibling.compose_service = Some("db".into());
Found { primary: Some(container("a", &labels)), stale: vec![container("b", &labels)], siblings: vec![sibling] }
}
#[test]
fn compose_siblings_share_the_working_directory_of_a_primary_that_has_one() {
let labels = [(FOLDER_LABEL, ROOT), (CONFIG_LABEL, CONFIG_FILE)];
let mut primary = container("a", &labels);
let (mut mine, mut foreign, mut unlabelled) = (container("d", &[]), container("e", &[]), container("f", &[]));
primary.compose_working_dir = Some("/work/app/.devcontainer".into());
mine.compose_working_dir = primary.compose_working_dir.clone();
foreign.compose_working_dir = Some("/other/app/.devcontainer".into());
let mut legacy = container("b", &[(FOLDER_LABEL, ROOT)]);
legacy.compose_working_dir = primary.compose_working_dir.clone();
let members = vec![primary.clone(), mine.clone(), foreign.clone(), unlabelled.clone(), legacy];
let ids: Vec<String> = siblings_of(&primary, members.clone()).into_iter().map(|c| c.id).collect();
assert_eq!(ids, [mine.id.clone()]);
// A primary without a working directory matches nobody, not even containers without one.
primary.compose_working_dir = None;
unlabelled.compose_working_dir = None;
assert!(siblings_of(&primary, members).is_empty());
}
#[test]
fn a_container_id_must_name_one_of_the_projects_containers() {
let found = found();
let id = |c: &DockerContainer| c.id.clone();
let primary = id(found.primary.as_ref().unwrap());
assert_eq!(choose(&found, None).unwrap().id, primary);
assert_eq!(choose(&found, Some(&primary)).unwrap().id, primary);
assert_eq!(choose(&found, Some(&primary[..12].to_uppercase())).unwrap().id, primary);
assert_eq!(choose(&found, Some(&id(&found.siblings[0]))).unwrap().name, "name-d");
for foreign in ["e".repeat(64).as_str(), "ffffffffffff", &primary[..11], "", "--all", "name-a"] {
let refused = choose(&found, Some(foreign)).map(|c| c.id.clone());
if foreign.trim().is_empty() {
assert_eq!(refused.unwrap(), primary);
continue;
}
let message = refused.unwrap_err().message;
assert!(message.ends_with("does not belong to this project's dev container"), "{foreign}: {message}");
}
let none = Found { primary: None, stale: Vec::new(), siblings: Vec::new() };
assert!(choose(&none, None).unwrap_err().message.contains("devcontainer_up"));
}
#[test]
fn stop_acts_on_the_primary_and_its_compose_project_only() {
let mut found = found();
found.stale[0].state = "running".into();
let names: Vec<&str> = found.running_group().into_iter().map(|c| c.name.as_str()).collect();
assert_eq!(names, ["name-a", "name-d"]);
found.siblings[0].state = "exited".into();
assert_eq!(found.running_group().len(), 1);
}
#[test]
fn tail_is_one_to_five_thousand() {
assert_eq!(tail_of(None).unwrap(), 200);
assert_eq!(tail_of(Some(1)).unwrap(), 1);
assert_eq!(tail_of(Some(5000)).unwrap(), 5000);
for bad in [0, -1, 5001] {
assert!(tail_of(Some(bad)).is_err(), "{bad}");
}
}
#[test]
fn only_devcontainer_json_files_are_configurations() {
assert!(is_config_file(Path::new("/p/.devcontainer/devcontainer.json")));
assert!(is_config_file(Path::new("/p/.devcontainer.json")));
assert!(!is_config_file(Path::new("/p/package.json")));
assert!(!is_config_file(Path::new("/p/.devcontainer/Dockerfile")));
}
#[test]
fn every_configuration_of_the_project_is_listed() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
for f in [".devcontainer/devcontainer.json", ".devcontainer/py/devcontainer.json", ".devcontainer.json"] {
std::fs::create_dir_all(root.join(f).parent().unwrap()).unwrap();
std::fs::write(root.join(f), "{}").unwrap();
}
std::fs::create_dir_all(root.join(".devcontainer/empty")).unwrap();
let found: Vec<String> = config_files(root)
.iter()
.map(|f| f.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/"))
.collect();
assert_eq!(
found,
[".devcontainer/devcontainer.json", ".devcontainer.json", ".devcontainer/py/devcontainer.json"]
);
}
#[test]
fn a_command_line_for_people_quotes_what_needs_it() {
let argv = ["devcontainer", "exec", "--remote-env=A=b c", "sh", "-c", "echo 'x' && ls"].map(String::from);
assert_eq!(shown(&argv), r#"devcontainer exec '--remote-env=A=b c' sh -c 'echo '\''x'\'' && ls'"#);
}
/// A stand-in for the Dev Containers CLI that checks where `exec` and `sh -c` are.
#[cfg(unix)]
#[test]
fn exec_pins_the_approved_id_even_when_a_replacement_matches() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let cli = dir.path().join("devcontainer");
let approved = "a".repeat(64);
let replacement = "b".repeat(64);
let script = format!(
r#"#!/bin/sh
[ "$1" = exec ] || {{ echo "exec is not first: $*" >&2; exit 2; }}
[ "$2 $3" = "--workspace-folder {ROOT}" ] || {{ echo "no folder: $*" >&2; exit 2; }}
[ "$4 $5" = "--config {CONFIG_FILE}" ] || {{ echo "no config: $*" >&2; exit 2; }}
[ "$6" = "--container-id" ] || {{ echo "no approved id: $*" >&2; exit 2; }}
[ "$7" = "$MATCHING_CONTAINER" ] || {{ echo "pinned container unavailable" >&2; exit 3; }}
[ "$8 $9" = "--docker-path /usr/bin/docker" ] || {{ echo "no docker: $*" >&2; exit 2; }}
shift 9
[ "$1" = "--remote-env=A=1 2" ] && [ "$2" = "--remote-env=B_=" ] || {{ echo "no env: $*" >&2; exit 2; }}
[ $# -eq 5 ] && [ "$3 $4" = "sh -c" ] || {{ echo "sh -c is not last: $*" >&2; exit 2; }}
printf '%s' "$5"
"#,
);
std::fs::write(&cli, script).unwrap();
std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap();
let command = "echo \"$A\" && ls -- 'x y'; exit 3";
let envs = vec![("A".to_owned(), "1 2".to_owned()), ("B_".to_owned(), String::new())];
let argv = exec_argv(&cli, Path::new("/usr/bin/docker"), &target(), &approved, &envs, command);
assert_eq!(argv[1], "exec");
assert_eq!(&argv[argv.len() - 3..], ["sh", "-c", command]);
let invoke =
|id| std::process::Command::new(&argv[0]).args(&argv[1..]).env("MATCHING_CONTAINER", id).output().unwrap();
let out = invoke(&approved);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert_eq!(String::from_utf8_lossy(&out.stdout), command);
let out = invoke(&replacement);
assert_eq!(out.status.code(), Some(3));
assert!(out.stdout.is_empty());
}
}
+20 -5
Переглянути файл
@@ -2,6 +2,7 @@
mod background;
mod check;
mod debug;
mod devcontainer;
mod edit;
mod editors;
mod requests;
@@ -27,7 +28,7 @@ use ide_mcp::{ToolCallError, ToolRegistry};
pub use reports::{
FileProblems, FocusedEditor, Reports, mcp_report_problems, mcp_set_focused_editor, mcp_set_open_editors,
};
pub use run::agent::{AGENT_PARAM, AgentRun, AgentRuns, NAME_PREFIX, SHELL_PARAM};
pub use run::agent::{AGENT_PARAM, AgentRun, AgentRuns, NAME_PREFIX, SHELL_PARAM, TARGET_PARAM};
use serde_json::json;
pub use service::{McpServerStatus, McpService};
use std::path::{Path, PathBuf};
@@ -40,7 +41,7 @@ impl Registry {
}
}
fn tools() -> Vec<tool::Tool> {
fn tools(local_desktop: bool) -> Vec<tool::Tool> {
let mut tools = files::tools();
tools.extend(search::tools());
tools.extend(editors::tools());
@@ -53,6 +54,9 @@ fn tools() -> Vec<tool::Tool> {
tools.extend(run::tools());
tools.extend(vcs::tools());
tools.extend(http::tools());
if local_desktop {
tools.extend(devcontainer::tools());
}
tools
}
@@ -63,7 +67,7 @@ fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
}
fn tools_for(host: &Host, root: &Path, trusted: bool) -> Vec<ide_mcp::Tool> {
let mut all: Vec<_> = tools().into_iter().map(|t| t.metadata).collect();
let mut all: Vec<_> = tools(host.local_desktop).into_iter().map(|t| t.metadata).collect();
if let Some(plugins) = host.plugin_host() {
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| with_project_path(tool)));
}
@@ -144,7 +148,7 @@ impl Registry {
{
return Some(Found::Plugin { plugins, plugin, tool, metadata });
}
tools().into_iter().find(|t| t.metadata.name == name).map(Found::Builtin)
tools(self.0.local_desktop).into_iter().find(|t| t.metadata.name == name).map(Found::Builtin)
}
/// Whether the tools listed for `root` include those that write and run. Opens nothing:
@@ -307,10 +311,21 @@ impl Registry {
mod tests {
#[test]
fn restricted_mode_excludes_execution_tools() {
let mut tool = super::tools().remove(0).metadata;
let mut tool = super::tools(false).remove(0).metadata;
assert!(super::allowed(&tool, false));
tool.read_only = false;
assert!(!super::allowed(&tool, false));
assert!(super::allowed(&tool, true));
}
#[test]
fn dev_container_tools_that_start_run_or_stop_are_not_read_only() {
let tools = super::devcontainer::tools();
let read_only = |name: &str| tools.iter().find(|t| t.metadata.name == name).unwrap().metadata.read_only;
assert!(read_only("devcontainer_status") && read_only("devcontainer_logs"));
for name in ["devcontainer_up", "devcontainer_exec", "devcontainer_stop"] {
assert!(!read_only(name), "{name}");
}
assert_eq!(tools.len(), 5);
}
}
+216 -44
Переглянути файл
@@ -9,7 +9,8 @@
use super::output::{TRUNCATED_MARKER, temp_output_file};
use crate::ops::Emit;
use ide_core::{IdeEvent, IdeResult, RunId, SharedSink};
use ide_core::event::McpAgentRunTarget;
use ide_core::{IdeError, IdeEvent, IdeResult, RunId, SharedSink};
use ide_run::{OutputChunk, RunConfig, RunInfo};
use parking_lot::Mutex;
use serde_json::{Map, Value, json};
@@ -20,6 +21,8 @@ use std::time::SystemTime;
/// Run configuration parameter naming the agent tab a start belongs to.
pub const AGENT_PARAM: &str = "mcp.agentRun";
/// Run configuration parameter containing the serialized execution target.
pub const TARGET_PARAM: &str = "mcp.agentTarget";
/// Run configuration parameter with Settings › Tools › Terminal › Shell path (may be empty).
pub const SHELL_PARAM: &str = "mcp.agentShell";
/// What every agent tab's name starts with.
@@ -28,6 +31,21 @@ const MAX_NAME_LENGTH: usize = 64;
/// How much of the log a wait for a pattern reads at a time.
const SCAN_CHUNK: usize = 4 << 20;
#[derive(Clone)]
pub(crate) enum Execution {
Host,
Container { id: String, config: PathBuf, argv: Vec<String> },
}
impl Execution {
pub(crate) fn target(&self) -> McpAgentRunTarget {
match self {
Self::Host => McpAgentRunTarget::Host,
Self::Container { id, .. } => McpAgentRunTarget::Container { id: id.clone() },
}
}
}
/// The tab name for what an agent asked for: trimmed, with [`NAME_PREFIX`] once.
pub fn tab_name(raw: &str) -> IdeResult<String> {
let raw = raw.trim();
@@ -58,7 +76,7 @@ impl AgentRuns {
}
/// The tab for the agent's next start of `name`: refused while its process runs, since
/// only an explicit `stop_run` may end it.
/// only an explicit `stop_run` may end it. The execution applies to exactly this command.
pub(crate) fn prepare(
&self,
root: &Path,
@@ -66,6 +84,7 @@ impl AgentRuns {
name: &str,
command: &str,
cwd: &str,
execution: Execution,
) -> Result<Arc<AgentRun>, Arc<AgentRun>> {
let mut runs = self.0.lock();
let run = match runs.iter().find(|r| r.root == root && r.name == name) {
@@ -78,13 +97,15 @@ impl AgentRuns {
};
drop(runs);
let mut s = run.state.lock();
if s.running() {
if s.running() || s.agent_start {
drop(s);
return Err(run);
}
*run.window.lock() = window.to_owned();
s.previous = Some(Previous { command: s.command.clone(), cwd: s.cwd.clone(), execution: s.execution.clone() });
s.command = command.to_owned();
s.cwd = cwd.to_owned();
s.execution = execution;
s.agent_start = true;
s.start_error = None;
s.closed_at = None;
@@ -94,11 +115,16 @@ impl AgentRuns {
Ok(run)
}
/// The agent's start did not reach the Run tool window: a tab that never ran is dropped.
/// The agent's start did not reach the Run tool window: a tab that never ran is dropped, and
/// one that did keeps the command and execution its window still has the configuration of.
pub(crate) fn abandon(&self, run: &Arc<AgentRun>) {
let never_ran = {
let mut s = run.state.lock();
s.agent_start = false;
if std::mem::take(&mut s.agent_start)
&& let Some(Previous { command, cwd, execution }) = s.previous.take()
{
(s.command, s.cwd, s.execution) = (command, cwd, execution);
}
s.process.is_none()
};
if never_ran {
@@ -109,31 +135,59 @@ impl AgentRuns {
/// Called for every run start: for a start of an agent tab, turns its command line into
/// the shell's invocation and opens a new process record.
pub(crate) fn launch(&self, root: &Path, window: &str, config: &mut RunConfig) -> Option<Launch> {
let name = config.extras.params.get(AGENT_PARAM).cloned()?;
pub(crate) fn launch(&self, root: &Path, window: &str, config: &mut RunConfig) -> IdeResult<Option<Launch>> {
let unavailable = || IdeError::invalid("the approved agent run target is unavailable; start a new MCP run");
let Some(name) = config.extras.params.get(AGENT_PARAM) else {
if config.id.starts_with("mcp-agent:") || config.extras.params.contains_key(TARGET_PARAM) {
return Err(unavailable());
}
return Ok(None);
};
let target: McpAgentRunTarget = config
.extras
.params
.get(TARGET_PARAM)
.and_then(|target| serde_json::from_str(target).ok())
.ok_or_else(unavailable)?;
let line = config.command.clone();
let cwd = config.cwd.as_deref().map(|p| p.to_string_lossy().into_owned()).unwrap_or_default();
let run = {
let mut runs = self.0.lock();
match runs.iter().find(|r| r.root == root && r.name == name) {
match runs.iter().find(|r| r.root == root && r.name == *name) {
Some(run) => run.clone(),
None => {
let run = Arc::new(AgentRun::new(root, &name, &line, &cwd));
None if target == McpAgentRunTarget::Host => {
let run = Arc::new(AgentRun::new(root, name, &line, &cwd));
runs.push(run.clone());
run
}
None => return Err(unavailable()),
}
};
let mut state = run.state.lock();
if state.execution.target() != target || state.running() {
return Err(unavailable());
}
let (program, args) = match &state.execution {
Execution::Host => shell_invocation(config.extras.params.get(SHELL_PARAM).map(String::as_str), &line),
Execution::Container { config, argv, .. } => {
if state.command != line {
return Err(unavailable());
}
crate::mcp::tool::ensure_inside(root, config)?;
let (program, args) = argv.split_first().ok_or_else(unavailable)?;
(program.clone(), args.to_vec())
}
};
*run.window.lock() = window.to_owned();
let shell = config.extras.params.get(SHELL_PARAM).cloned();
let (program, args) = shell_invocation(shell.as_deref(), &line);
config.command = program;
config.args = args;
config.extras.target = Some(String::new());
// Pipes: the Run tool window's console shows the output and sends the user's input lines.
config.extras.emulate_terminal = false;
let generation = run.begin(&line);
Some(Launch { run, generation })
*run.window.lock() = window.to_owned();
let generation = state.begin(&line);
drop(state);
run.changed.notify_waiters();
Ok(Some(Launch { run, generation }))
}
fn by_process(&self, id: RunId) -> Option<Arc<AgentRun>> {
@@ -255,9 +309,18 @@ struct Process {
stopped_by: Option<Actor>,
}
struct Previous {
command: String,
cwd: String,
execution: Execution,
}
struct State {
command: String,
cwd: String,
execution: Execution,
/// What the tab was before the agent's pending start, for [`AgentRuns::abandon`].
previous: Option<Previous>,
log: Option<(PathBuf, std::fs::File)>,
log_len: u64,
generation: u64,
@@ -280,6 +343,32 @@ impl State {
fn running(&self) -> bool {
self.process.as_ref().is_some_and(|p| p.ended.is_none())
}
fn begin(&mut self, line: &str) -> u64 {
self.generation += 1;
let by = if std::mem::take(&mut self.agent_start) { Actor::Agent } else { Actor::User };
let now = SystemTime::now();
if by == Actor::User {
self.interventions.push((now, Intervention::Rerun));
}
self.command = line.to_owned();
self.previous = None;
self.agent_stop = false;
self.start_error = None;
self.closed_at = None;
self.typed.clear();
self.escape = Escape::None;
self.process = Some(Process {
generation: self.generation,
run: None,
by,
started_at: now,
offset: self.log_len,
ended: None,
stopped_by: None,
});
self.generation
}
}
/// An agent tab.
@@ -326,6 +415,8 @@ impl AgentRun {
state: Mutex::new(State {
command: command.to_owned(),
cwd: cwd.to_owned(),
execution: Execution::Host,
previous: None,
log: None,
log_len: 0,
generation: 0,
@@ -348,28 +439,6 @@ impl AgentRun {
self.window.lock().clone()
}
fn begin(&self, line: &str) -> u64 {
let mut s = self.state.lock();
s.generation += 1;
let generation = s.generation;
let by = if std::mem::take(&mut s.agent_start) { Actor::Agent } else { Actor::User };
let now = SystemTime::now();
if by == Actor::User {
s.interventions.push((now, Intervention::Rerun));
}
s.command = line.to_owned();
s.agent_stop = false;
s.start_error = None;
s.closed_at = None;
s.typed.clear();
s.escape = Escape::None;
let offset = s.log_len;
s.process = Some(Process { generation, run: None, by, started_at: now, offset, ended: None, stopped_by: None });
drop(s);
self.changed.notify_waiters();
generation
}
fn output(&self, text: &str) {
let mut s = self.state.lock();
if s.log.is_none() {
@@ -874,6 +943,109 @@ mod tests {
run.take_interventions().iter().map(|v| v["message"].as_str().unwrap().to_owned()).collect()
}
fn agent_config(line: &str, target: McpAgentRunTarget) -> RunConfig {
let mut config = RunConfig {
id: "mcp-agent:x".into(),
name: "x".into(),
kind: "shell".into(),
command: line.into(),
args: Vec::new(),
cwd: None,
env: Default::default(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: true,
extras: Default::default(),
};
config.extras.params.insert(AGENT_PARAM.into(), "_agent_x".into());
config.extras.params.insert(SHELL_PARAM.into(), "/bin/sh".into());
config.extras.params.insert(TARGET_PARAM.into(), serde_json::to_string(&target).unwrap());
config
}
fn container_execution(root: &Path, id: &str) -> Execution {
Execution::Container {
id: id.to_owned(),
config: root.join(".devcontainer.json"),
argv: ["devcontainer", "exec", "--container-id", id, "sh", "-c", "echo 'a b'"].map(str::to_owned).to_vec(),
}
}
#[test]
fn reruns_keep_the_approved_container_and_refuse_missing_or_changed_targets() {
let runs = AgentRuns::default();
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let id = "a".repeat(64);
let execution = container_execution(root, &id);
let line = "in the container: echo";
let saved = agent_config(line, execution.target());
let approve = |execution| runs.prepare(root, "main", "_agent_x", line, "", execution).ok().unwrap();
let run = approve(execution);
for _ in 0..2 {
let mut config = saved.clone();
let launch = runs.launch(root, "main", &mut config).unwrap().unwrap();
assert_eq!(config.command, "devcontainer");
assert_eq!(config.args, ["exec", "--container-id", &id, "sh", "-c", "echo 'a b'"]);
run.exited(launch.generation, Some(0));
}
let mut missing = saved.clone();
missing.extras.params.remove(TARGET_PARAM);
assert!(runs.launch(root, "main", &mut missing).is_err());
missing.extras.params.remove(AGENT_PARAM);
assert!(runs.launch(root, "main", &mut missing).is_err());
let mut other_line = saved.clone();
other_line.command = "something else".into();
assert!(runs.launch(root, "main", &mut other_line).is_err());
let mut wrong_kind = agent_config(line, McpAgentRunTarget::Host);
assert!(runs.launch(root, "main", &mut wrong_kind).is_err());
approve(container_execution(root, &"b".repeat(64)));
assert!(runs.launch(root, "main", &mut saved.clone()).is_err());
runs.abandon(&run);
runs.forget_window("main");
assert!(runs.launch(root, "main", &mut saved.clone()).is_err());
runs.prepare(root, "main", "_agent_x", "ls", "", Execution::Host).ok().unwrap();
assert!(runs.launch(root, "main", &mut saved.clone()).is_err());
let mut shell = agent_config("ls", McpAgentRunTarget::Host);
runs.launch(root, "main", &mut shell).unwrap().unwrap();
assert_eq!((shell.command.as_str(), shell.args.last().map(String::as_str)), ("/bin/sh", Some("ls")));
}
#[test]
fn an_abandoned_start_leaves_the_tab_as_its_window_knows_it() {
let runs = AgentRuns::default();
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let execution = container_execution(root, &"a".repeat(64));
let target = execution.target();
let finish = |run: &AgentRun| {
let generation = run.state.lock().generation;
run.exited(generation, Some(0));
};
// A shell command, then a dev container one whose start never reaches the window: a
// rerun of the shell configuration still runs in the shell.
let run = runs.prepare(root, "main", "_agent_x", "ls", "", Execution::Host).ok().unwrap();
runs.launch(root, "main", &mut agent_config("ls", McpAgentRunTarget::Host)).unwrap().unwrap();
finish(&run);
runs.prepare(root, "main", "_agent_x", "in the container: ls", "", execution.clone()).ok().unwrap();
runs.abandon(&run);
let mut rerun = agent_config("ls", McpAgentRunTarget::Host);
runs.launch(root, "main", &mut rerun).unwrap().unwrap();
assert_eq!(rerun.command, "/bin/sh");
finish(&run);
// And the other way round: the dev container configuration keeps its argv.
runs.prepare(root, "main", "_agent_x", "in the container: ls", "", execution).ok().unwrap();
runs.launch(root, "main", &mut agent_config("in the container: ls", target.clone())).unwrap().unwrap();
finish(&run);
runs.prepare(root, "main", "_agent_x", "pwd", "", Execution::Host).ok().unwrap();
runs.abandon(&run);
let mut rerun = agent_config("in the container: ls", target);
runs.launch(root, "main", &mut rerun).unwrap().unwrap();
assert_eq!(rerun.command, "devcontainer");
}
#[test]
fn names_get_the_prefix_once() {
assert_eq!(tab_name(" build ").unwrap(), "_agent_build");
@@ -898,11 +1070,11 @@ mod tests {
fn starts_that_the_agent_did_not_ask_for_are_reruns() {
let run = run();
run.state.lock().agent_start = true;
let first = run.begin("echo");
let first = run.state.lock().begin("echo");
assert!(messages(&run).is_empty());
run.exited(first, Some(0));
assert_eq!(run.status()["state"], "succeeded");
run.begin("echo");
run.state.lock().begin("echo");
let told = messages(&run);
assert_eq!(told.len(), 1);
assert!(told[0].starts_with("The user reran this command at "), "{told:?}");
@@ -913,7 +1085,7 @@ mod tests {
fn stops_are_the_agents_only_when_it_asked() {
let run = run();
run.state.lock().agent_start = true;
let generation = run.begin("sleep 9");
let generation = run.state.lock().begin("sleep 9");
run.state.lock().process.as_mut().unwrap().run = Some(RunId(7));
run.stopping(RunId(7));
run.stopping(RunId(7));
@@ -922,7 +1094,7 @@ mod tests {
assert_eq!(run.status()["state"], "stoppedByUser");
run.state.lock().agent_start = true;
let generation = run.begin("sleep 9");
let generation = run.state.lock().begin("sleep 9");
run.state.lock().process.as_mut().unwrap().run = Some(RunId(8));
run.agent_stopping();
run.stopping(RunId(8));
@@ -934,12 +1106,12 @@ mod tests {
fn faults_are_crashes_and_other_codes_failures() {
let run = run();
for (code, state) in [(1, "failed"), (130, "failed")] {
let generation = run.begin("x");
let generation = run.state.lock().begin("x");
run.exited(generation, Some(code));
assert_eq!(run.status()["state"], state, "{code}");
}
if cfg!(unix) {
let generation = run.begin("x");
let generation = run.state.lock().begin("x");
run.exited(generation, Some(139));
let status = run.status();
assert_eq!(status["state"], "crashed");
@@ -950,7 +1122,7 @@ mod tests {
#[test]
fn reads_whole_characters_and_tails_lines() {
let run = run();
run.begin("x");
run.state.lock().begin("x");
run.output("one\n");
run.output("twö\nthree\n");
// `ö` is bytes 6..8: a cut inside it moves to the character's end or start.
+80 -38
Переглянути файл
@@ -1,13 +1,14 @@
//! `run_command` and the tools that follow its tab up: `wait_for_run`, `read_run_output`,
//! `get_run_status`, `send_run_input`, `stop_run` and `list_runs` (see [`super::agent`]).
use super::agent::{AgentRun, INTERVENTION_ADVICE, TruncateMode, clean_output, tab_name, truncate_lines};
use super::agent::{AgentRun, Execution, INTERVENTION_ADVICE, TruncateMode, clean_output, tab_name, truncate_lines};
use super::output::RUN_PREVIEW_MAX_LENGTH;
use crate::mcp::page::{OFFSET, Page};
use crate::mcp::run::timeout;
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
use ide_core::{IdeError, IdeResult};
use serde_json::{Map, Value};
use std::path::PathBuf;
use std::sync::Arc;
const RUN_TIMEOUT_MS: usize = 10_000;
@@ -20,21 +21,22 @@ const READ_CAP: usize = 1 << 20;
/// Lines of output quoted when a name is still running.
const BUSY_TAIL_LINES: usize = 20;
const NAME: &str = "Tab name. OpenIDEA shows the tab as `_agent_<name>`; passing the prefixed name works too.";
const SEQUENCE: &str = "\n\nUsing the same name for every command of one task reuses its tab: a name whose command \
pub(crate) const NAME: &str =
"Tab name. OpenIDEA shows the tab as `_agent_<name>`; passing the prefixed name works too.";
pub(crate) const SEQUENCE: &str = "\n\nUsing the same name for every command of one task reuses its tab: a name whose command \
has finished starts the next command in the same tab. A name whose command is still running is refused (with that \
command and its last output); stop it with `stop_run` first or use another name. Nothing is stopped implicitly.";
const INTERVENTIONS: &str = "\n\nThe user sees every tab and can type into it, rerun or stop its command, or close \
pub(crate) const INTERVENTIONS: &str = "\n\nThe user sees every tab and can type into it, rerun or stop its command, or close \
it. Results then carry `interventions` (for example `User input: …` or `The user reran this command at …`) and \
`advice`: unless the user asked otherwise, stop what you are doing, tell the user you received the intervention and \
wait for their confirmation before you continue.";
const OUTPUT: &str = "\n\nThe command runs on pipes, not a terminal, so programs print plain lines (no progress \
pub(crate) const OUTPUT: &str = "\n\nThe command runs on pipes, not a terminal, so programs print plain lines (no progress \
bars). `output` is that text cleaned of escape sequences, at most `maxLinesCount` lines (default 2000): beyond it, \
`truncateMode` START (default) keeps the end, END the start, MIDDLE both ends, NONE everything, with a \
`<<<...content truncated...>>>` line where lines were left out and `truncatedLines` saying how many. `outputStart` \
and `nextOffset` are positions in the tab's raw output log; pass `nextOffset` as `offset` to read on.";
const MAX_LINES: &str = "Lines of output to return at most (default 2000)";
const TRUNCATE_MODE: &str = "Which lines to leave out beyond maxLinesCount: START (default, keeps the end), END \
pub(crate) const MAX_LINES: &str = "Lines of output to return at most (default 2000)";
pub(crate) const TRUNCATE_MODE: &str = "Which lines to leave out beyond maxLinesCount: START (default, keeps the end), END \
(keeps the start), MIDDLE (keeps both ends) or NONE";
/// `list_runs`: tabs returned by default, and characters of each command, enough to tell them apart.
const LIST_LIMIT: usize = 10;
@@ -112,7 +114,7 @@ fn offset(call: &Call, name: &str) -> IdeResult<Option<u64>> {
}
}
fn busy(run: &AgentRun) -> IdeError {
pub(crate) fn busy(run: &AgentRun) -> IdeError {
let tail = run.tail(run.process_offset(), BUSY_TAIL_LINES, RUN_PREVIEW_MAX_LENGTH).map(|t| t.0).unwrap_or_default();
IdeError::invalid(format!(
"`{}` is still running `{}`. Stop it with stop_run first, or use another name.\nLast output:\n{}",
@@ -122,6 +124,66 @@ fn busy(run: &AgentRun) -> IdeError {
))
}
/// A command to start in an agent tab: [`start_in_tab`].
pub(crate) struct Tab {
/// What the confirmation dialog is titled with.
pub subject: String,
/// The tab's name, with its prefix.
pub name: String,
/// The command line the tab shows and records.
pub command: String,
/// What the confirmation dialog says the command does.
pub detail: String,
pub cwd: PathBuf,
pub env: Vec<(String, String)>,
pub execution: Execution,
/// Added to the result.
pub extra: Map<String, Value>,
}
/// The rest of `run_command`: asks the user, starts `tab` in the Run tool window and waits as
/// the `timeout` and `pattern` arguments say. Refused while the tab's command runs.
pub(crate) async fn start_in_tab(call: &Call, tab: Tab, default_timeout_ms: usize) -> IdeResult<Output> {
let name = tab.name.clone();
let deadline = deadline(call, default_timeout_ms)?;
let ready = pattern(call)?;
let host = call.host();
let runs = &host.mcp_agent_runs;
if let Some(run) = runs.get(call.root(), &name).filter(|r| r.running()) {
return Err(busy(&run));
}
call.confirm(&tab.subject, Some(tab.detail)).await?;
let shown_cwd = call.display(&tab.cwd);
let target = tab.execution.target();
let run = runs
.prepare(call.root(), call.window(), &name, &tab.command, &shown_cwd, tab.execution)
.map_err(|r| busy(&r))?;
let request = ide_core::event::McpUiRequest::AgentRun {
name: name.clone(),
command: tab.command,
cwd: tab.cwd.into(),
env: tab.env.into_iter().collect(),
target,
};
if let Err(e) = call.ask(request).await {
let error = run.start_error();
runs.abandon(&run);
return Err(match error {
Some(error) => IdeError::invalid(format!("`{name}` did not start: {error}")),
None => e,
});
}
if let Some(error) = run.start_error() {
return Err(IdeError::invalid(format!("`{name}` did not start: {error}")));
}
let from = run.process_offset();
let end = run.wait(deadline, ready.as_ref(), from, &call.cancel).await?;
let mut extra = output_view(call, &run, from)?;
extra.insert("waitEnded".into(), end.as_str().into());
extra.extend(tab.extra);
result(&run, extra)
}
pub fn run_command() -> Tool {
Tool::new(
"run_command",
@@ -154,13 +216,6 @@ process) and its output so far.{OUTPUT}{SEQUENCE}{INTERVENTIONS}"
None => call.root().to_path_buf(),
};
let env = call.args.get("envs").filter(|v| !v.is_null()).map(|_| call.str_map("envs")).transpose()?;
let deadline = deadline(&call, RUN_TIMEOUT_MS)?;
let ready = pattern(&call)?;
let host = call.host();
let runs = &host.mcp_agent_runs;
if let Some(run) = runs.get(call.root(), &name).filter(|r| r.running()) {
return Err(busy(&run));
}
let shown_cwd = call.display(&cwd);
let mut detail = format!(
"{command}\n\nTab: {name}\nWorking directory: {}",
@@ -169,30 +224,17 @@ process) and its output so far.{OUTPUT}{SEQUENCE}{INTERVENTIONS}"
for (key, value) in env.iter().flatten() {
detail.push_str(&format!("\n{key}={value}"));
}
call.confirm(&name, Some(detail)).await?;
let run = runs.prepare(call.root(), call.window(), &name, &command, &shown_cwd).map_err(|r| busy(&r))?;
let request = ide_core::event::McpUiRequest::AgentRun {
name: name.clone(),
command: command.clone(),
cwd: cwd.into(),
env: env.unwrap_or_default().into_iter().collect(),
let tab = Tab {
subject: name.clone(),
name,
command,
detail,
cwd,
env: env.unwrap_or_default(),
execution: Execution::Host,
extra: Map::new(),
};
if let Err(e) = call.ask(request).await {
let error = run.start_error();
runs.abandon(&run);
return Err(match error {
Some(error) => IdeError::invalid(format!("`{name}` did not start: {error}")),
None => e,
});
}
if let Some(error) = run.start_error() {
return Err(IdeError::invalid(format!("`{name}` did not start: {error}")));
}
let from = run.process_offset();
let end = run.wait(deadline, ready.as_ref(), from, &call.cancel).await?;
let mut extra = output_view(&call, &run, from)?;
extra.insert("waitEnded".into(), end.as_str().into());
result(&run, extra)
start_in_tab(&call, tab, RUN_TIMEOUT_MS).await
},
)
.write()
+1 -1
Переглянути файл
@@ -1,7 +1,7 @@
//! Run configurations, builds and agent commands; every start asks the user first.
pub(crate) mod agent;
mod agent_tools;
pub(crate) mod agent_tools;
mod build;
pub(crate) mod configs;
mod output;
+38 -2
Переглянути файл
@@ -6,8 +6,9 @@ use crate::Host;
use ide_command::command;
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
use ide_docker::{
ComposeOp, ContainerOp, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer, DockerLogLine,
DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget, RegistryAuth,
ComposeOp, ContainerOp, DockerContainer, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer,
DockerLogLine, DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget,
RegistryAuth,
};
use ide_ssh::Tunnel;
use std::collections::{BTreeMap, HashMap};
@@ -97,6 +98,41 @@ pub async fn docker_container_op(
host.blocking(move || ide_docker::container_op(&endpoint, &ids, op)).await
}
/// The containers (running or not) that carry every `label` (`key` or `key=value`).
pub(crate) async fn containers_with_labels(
host: &Host,
endpoint: DockerEndpoint,
labels: Vec<String>,
) -> IdeResult<Vec<DockerContainer>> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::containers(&endpoint, &labels)).await
}
/// The last `tail` lines of a container's log, without following it.
pub(crate) async fn log_tail(
host: &Host,
endpoint: DockerEndpoint,
id: String,
tail: u32,
timestamps: bool,
cancel: CancellationToken,
) -> IdeResult<Vec<DockerLogLine>> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || {
let lines = std::sync::Mutex::new(Vec::new());
ide_docker::logs(&endpoint, &id, tail, false, timestamps, &cancel, &|batch| {
lines.lock().unwrap_or_else(|e| e.into_inner()).extend(batch)
})?;
Ok(lines.into_inner().unwrap_or_else(|e| e.into_inner()))
})
.await
}
pub(crate) async fn stop_containers(host: &Host, endpoint: DockerEndpoint, ids: Vec<String>) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::container_op(&endpoint, &ids, ContainerOp::Stop)).await
}
#[command(trust = trusted)]
pub async fn docker_remove(
host: &Host,
+3 -5
Переглянути файл
@@ -326,13 +326,11 @@ pub async fn run_start(
let on_output: Emit<OutputChunk> = Arc::new(move |chunk| {
let _ = on_output.send(chunk);
});
let cancel = request.map(|id| host.begin_request(id)).unwrap_or_default();
let operation = config.extras.params.get("plugin.operation").cloned();
let mut config = config;
let agent = match host.project(window) {
Ok(project) => host.mcp_agent_runs.launch(&project.root, window, &mut config),
Err(_) => None,
};
let project = host.project(window)?;
let agent = host.mcp_agent_runs.launch(&project.root, window, &mut config)?;
let cancel = request.map(|id| host.begin_request(id)).unwrap_or_default();
let on_output = match &agent {
Some(agent) => agent.wrap_output(on_output),
None => on_output,
+259 -5
Переглянути файл
@@ -19,6 +19,10 @@ struct Harness {
}
impl Harness {
fn new() -> Self {
Self::for_host(true)
}
fn for_host(local_desktop: bool) -> Self {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
std::fs::create_dir_all(root.join("src")).unwrap();
@@ -29,14 +33,15 @@ impl Harness {
std::fs::write(root.join(".gitignore"), "ignored/\n").unwrap();
let events = Arc::new(std::sync::Mutex::new(Vec::new()));
let sink = events.clone();
let host = Arc::new(Host::new(HostConfig {
let host = Host::new(HostConfig {
sink_for: Box::new(move |window| {
let (window, events) = (window.to_owned(), sink.clone());
Arc::new(move |e| events.lock().unwrap().push((window.clone(), e)))
}),
local_data_dir: tmp.path().join("local"),
..common::host_config(tmp.path())
}));
});
let host = Arc::new(if local_desktop { host.with_local_desktop() } else { host });
host.open_project("main", &root).unwrap();
Self { host, root, tmp, events }
}
@@ -1120,11 +1125,13 @@ fn run_tool_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig>>
let request = events.lock().unwrap().iter().find_map(|(_, e)| match e {
IdeEvent::McpRequest {
id,
request: ide_core::event::McpUiRequest::AgentRun { name, command, cwd, env },
} if !handled.contains(id) => Some((*id, name.clone(), command.clone(), cwd.clone(), env.clone())),
request: ide_core::event::McpUiRequest::AgentRun { name, command, cwd, env, target },
} if !handled.contains(id) => {
Some((*id, name.clone(), command.clone(), cwd.clone(), env.clone(), target.clone()))
}
_ => None,
});
let Some((id, name, command, cwd, env)) = request else {
let Some((id, name, command, cwd, env, target)) = request else {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
continue;
};
@@ -1144,6 +1151,7 @@ fn run_tool_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig>>
extras: Default::default(),
};
config.extras.params.insert(ide_host::mcp::AGENT_PARAM.into(), name);
config.extras.params.insert(ide_host::mcp::TARGET_PARAM.into(), serde_json::to_string(&target).unwrap());
config.extras.target = Some(String::new());
out.lock().unwrap().push(config.clone());
let result =
@@ -2516,3 +2524,249 @@ async fn agent_plugins_ipc_installs_for_a_harness_and_projects_native_children()
.unwrap_err();
assert!(stale.message.contains("changed since they were shown"), "{stale:?}");
}
const DEV_CONTAINER_TOOLS: [&str; 5] =
["devcontainer_status", "devcontainer_logs", "devcontainer_up", "devcontainer_exec", "devcontainer_stop"];
fn dev_container_tools(tools: Vec<ide_mcp::Tool>) -> Vec<String> {
let mut names: Vec<String> = tools.into_iter().map(|t| t.name).filter(|n| n.starts_with("devcontainer_")).collect();
names.sort();
names
}
#[tokio::test(flavor = "multi_thread")]
async fn server_hosts_neither_list_nor_dispatch_dev_container_tools() {
let h = Harness::for_host(false);
h.trust().await;
let registry = Registry::new(h.host.clone());
let tools = registry.tools(&h.root).unwrap();
assert!(tools.iter().any(|t| t.name == "run_command"));
assert!(dev_container_tools(tools).is_empty());
assert!(dev_container_tools(registry.tools_without_project()).is_empty());
for name in DEV_CONTAINER_TOOLS {
assert_eq!(h.error(name, json!({})).await, format!("unknown tool: {name}"));
}
}
#[tokio::test(flavor = "multi_thread")]
async fn an_untrusted_project_lists_only_the_read_only_dev_container_tools() {
let h = Harness::new();
let registry = Registry::new(h.host.clone());
assert!(!h.host.project("main").unwrap().is_trusted());
assert_eq!(dev_container_tools(registry.tools(&h.root).unwrap()), ["devcontainer_logs", "devcontainer_status"]);
// A write tool called all the same is refused before it asks or runs anything.
for tool in ["devcontainer_up", "devcontainer_exec", "devcontainer_stop"] {
let refused = h.error(tool, json!({"name": "x", "command": "true"})).await;
assert_eq!(refused, "Project is in Restricted Mode. Trust the project to enable execution.", "{tool}");
}
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
h.trust().await;
let mut all = DEV_CONTAINER_TOOLS.map(str::to_owned).to_vec();
all.sort();
assert_eq!(dev_container_tools(registry.tools(&h.root).unwrap()), all);
}
#[tokio::test(flavor = "multi_thread")]
async fn dev_container_arguments_are_checked_before_docker_is_asked() {
let h = Harness::new();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
h.set("runWithoutConfirmation", json!(true));
std::fs::create_dir_all(h.root.join(".devcontainer")).unwrap();
std::fs::write(h.root.join(".devcontainer/devcontainer.json"), "{}").unwrap();
std::fs::write(h.tmp.path().join("devcontainer.json"), "{}").unwrap();
let error = |tool: &'static str, args: Value| {
let h = &h;
async move { h.error(tool, args).await }
};
for tail in [0, -3, 5001] {
let e = error("devcontainer_logs", json!({"tail": tail})).await;
assert_eq!(e, "tail must be between 1 and 5000", "{tail}");
}
assert_eq!(error("devcontainer_logs", json!({"tail": "x"})).await, "tail must be an integer");
// `config` is a devcontainer file of the project.
let outside = h.tmp.path().join("devcontainer.json");
let e = error("devcontainer_status", json!({"config": outside})).await;
assert!(e.contains("outside the project"), "{e}");
let e = error("devcontainer_status", json!({"config": "src/a.txt"})).await;
assert_eq!(e, "config must be a devcontainer.json or .devcontainer.json file");
let e = error("devcontainer_status", json!({"config": ".devcontainer/other/devcontainer.json"})).await;
assert!(e.contains("does not exist") || e.contains("no existing parent"), "{e}");
let e = error("devcontainer_up", json!({"config": "../devcontainer.json"})).await;
assert!(e.contains("outside the project"), "{e}");
for timeout in [0, -1] {
let e = error("devcontainer_up", json!({"timeout": timeout})).await;
assert_eq!(e, "timeout must be positive", "{timeout}");
}
// `noCache` belongs to a rebuild; refused before anything is asked.
let e = error("devcontainer_up", json!({"noCache": true})).await;
assert_eq!(e, "noCache needs rebuild: true");
let e = error("devcontainer_up", json!({"rebuild": true, "timeout": 0})).await;
assert_eq!(e, "timeout must be positive");
// `exec` arguments.
let e = error("devcontainer_exec", json!({"name": "t", "command": " "})).await;
assert_eq!(e, "command must not be empty");
for name in ["1A", "A-B", "", "A B", "A=B"] {
let e = error("devcontainer_exec", json!({"name": "t", "command": "true", "envs": {name: "1"}})).await;
assert!(e.contains("is not a valid variable name"), "{name}: {e}");
}
let e = error("devcontainer_exec", json!({"name": "t", "command": "true", "envs": {"A": 1}})).await;
assert_eq!(e, "envs must contain strings");
let e = error("devcontainer_exec", json!({"name": "t", "command": "true", "envs": ["A=1"]})).await;
assert_eq!(e, "envs must be an object");
// Without a window it is refused like `run_command`.
let inventory = h.serve_inventory();
h.host.trust.decide(&inventory, true, false).unwrap();
let e = h.call_at(&inventory, "devcontainer_exec", json!({"name": "t", "command": "true"})).await.unwrap_err();
assert!(e.starts_with("devcontainer_exec needs the project open in a window"), "{e}");
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn dev_container_configs_cannot_escape_the_project_through_symlinks() {
let h = Harness::new();
h.trust().await;
let outside = h.tmp.path().join("devcontainer.json");
std::fs::write(&outside, "{}").unwrap();
std::fs::create_dir(h.root.join(".devcontainer")).unwrap();
for name in [".devcontainer/devcontainer.json", ".devcontainer.json"] {
let link = h.root.join(name);
std::os::unix::fs::symlink(&outside, &link).unwrap();
for (tool, args) in [
("devcontainer_status", json!({})),
("devcontainer_status", json!({"config": name})),
("devcontainer_up", json!({})),
("devcontainer_exec", json!({"name": "t", "command": "true"})),
] {
let error = h.error(tool, args).await;
assert!(error.contains("path is outside the project"), "{tool} ({name}): {error}");
}
std::fs::remove_file(link).unwrap();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_with_only_named_configurations_says_to_pass_one() {
let h = Harness::new();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
h.set("runWithoutConfirmation", json!(true));
std::fs::create_dir_all(h.root.join(".devcontainer/py")).unwrap();
std::fs::write(h.root.join(".devcontainer/py/devcontainer.json"), "{}").unwrap();
for (tool, args) in [("devcontainer_up", json!({})), ("devcontainer_exec", json!({"name": "t", "command": "true"}))]
{
let e = h.error(tool, args).await;
assert!(e.contains("pass `config` with one of .devcontainer/py/devcontainer.json"), "{tool}: {e}");
}
}
/// Runs `docker` with `args`, returning its trimmed output (None when it failed).
fn docker_output(docker: &Path, args: &[&str]) -> Option<String> {
let out = std::process::Command::new(docker).args(args).output().ok()?;
out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned())
}
/// Removes the test containers (never any other) when dropped, also after a panic.
struct TestContainers(PathBuf, Vec<String>);
impl Drop for TestContainers {
fn drop(&mut self) {
for name in &self.1 {
assert!(name.starts_with("oi-mcpdc-test-"));
let _ = std::process::Command::new(&self.0).args(["rm", "-f", name]).output();
}
}
}
#[tokio::test(flavor = "multi_thread")]
async fn dev_container_tools_work_on_the_containers_of_the_project_only() {
let ep = ide_docker::DockerEndpoint::Default;
let ready = tokio::task::spawn_blocking(move || {
matches!(ide_docker::availability(&ep), ide_docker::DockerAvailability::Ready { .. })
&& ide_docker::endpoint_is_local(&ide_docker::DockerEndpoint::Default).unwrap_or(false)
})
.await
.unwrap();
let docker = ide_docker::docker_executable();
let Some(docker) = docker.filter(|_| ready) else {
eprintln!("skipped: no local Docker daemon is ready");
return;
};
if docker_output(&docker, &["image", "inspect", "--format", "{{.Id}}", "alpine:latest"]).is_none() {
eprintln!("skipped: the image alpine:latest is not present locally (it is not pulled here)");
return;
}
let h = Harness::new();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
h.set("runWithoutConfirmation", json!(true));
std::fs::create_dir_all(h.root.join(".devcontainer")).unwrap();
let config = h.root.join(".devcontainer/devcontainer.json");
std::fs::write(
&config,
r#"{ // comment
"image": "alpine:latest", "forwardPorts": [3000, "db:5432"] }"#,
)
.unwrap();
let pid = std::process::id();
let (a, b) = (format!("oi-mcpdc-test-{pid}-a"), format!("oi-mcpdc-test-{pid}-b"));
let _remove = TestContainers(docker.clone(), vec![a.clone(), b.clone()]);
let folder_label = format!("devcontainer.local_folder={}", h.root.display());
let config_label = format!("devcontainer.config_file={}", config.display());
let run = |name: &str, labels: &[&str]| {
let mut args = vec!["run", "-d", "--init", "--name", name];
for label in labels {
args.extend(["--label", label]);
}
args.extend(["alpine:latest", "sleep", "300"]);
docker_output(&docker, &args).unwrap_or_else(|| panic!("cannot start {name}"))
};
let id_a = run(&a, &[&folder_label, &config_label]);
let id_b = run(&b, &[&folder_label]);
let status = h.json("devcontainer_status", json!({})).await;
assert_eq!(status["docker"], "ready", "{status}");
assert_eq!(
(status["dockerLocal"].as_bool(), status["configFile"].as_str()),
(Some(true), Some(".devcontainer/devcontainer.json"))
);
assert_eq!(status["configFiles"], json!([".devcontainer/devcontainer.json"]));
assert_eq!(status["forwardPorts"], json!([3000, "db:5432"]));
let containers = status["containers"].as_array().unwrap();
assert_eq!(containers.len(), 1, "only the labelled container: {status}");
assert_eq!((containers[0]["id"].as_str(), containers[0]["name"].as_str()), (Some(id_a.as_str()), Some(a.as_str())));
assert_eq!((containers[0]["state"].as_str(), containers[0]["primary"].as_bool()), (Some("running"), Some(true)));
let logs = h.json("devcontainer_logs", json!({"tail": 5})).await;
assert_eq!(logs["containerId"], id_a.as_str());
assert!(logs["lines"].is_array());
let foreign = h.error("devcontainer_logs", json!({"containerId": id_b})).await;
assert_eq!(foreign, format!("container {id_b} does not belong to this project's dev container"));
let short = h.error("devcontainer_logs", json!({"containerId": &id_b[..12]})).await;
assert!(short.ends_with("does not belong to this project's dev container"), "{short}");
// Without the CLI the tools that need it say so, wherever the container is.
if status["cliInstalled"] == false {
for (tool, args) in
[("devcontainer_up", json!({})), ("devcontainer_exec", json!({"name": "t", "command": "true"}))]
{
let e = h.error(tool, args).await;
assert!(e.starts_with("The Dev Containers CLI is not installed"), "{tool}: {e}");
}
}
// A window open in the container keeps it from being stopped.
let held = h.host.dev_containers_attached.hold(&id_a);
let refused = h.error("devcontainer_stop", json!({})).await;
assert!(refused.contains("is open in a window"), "{refused}");
assert_eq!(docker_output(&docker, &["inspect", "-f", "{{.State.Running}}", &a]).as_deref(), Some("true"));
drop(held);
let stopped = h.json("devcontainer_stop", json!({})).await;
assert_eq!(stopped["stopped"], json!([id_a]));
assert_eq!(docker_output(&docker, &["inspect", "-f", "{{.State.Running}}", &a]).as_deref(), Some("false"));
assert_eq!(docker_output(&docker, &["inspect", "-f", "{{.State.Running}}", &b]).as_deref(), Some("true"));
assert_eq!(h.json("devcontainer_stop", json!({})).await["stopped"], json!([]), "nothing runs now");
let status = h.json("devcontainer_status", json!({})).await;
assert_eq!(status["containers"][0]["state"], "exited", "{status}");
}
+5
Переглянути файл
@@ -20,6 +20,11 @@ impl Exec {
Self { docker, up, bin }
}
/// The id of the container.
pub fn container(&self) -> &str {
&self.up.container
}
/// The arguments of `docker` for one connection from the container to `<host>:<port>`.
fn connect_args(&self, host: &str, port: u16) -> Vec<String> {
let port = port.to_string();
+284 -2
Переглянути файл
@@ -1,7 +1,84 @@
//! Validated results of the Dev Containers CLI.
//! The Dev Containers CLI: `devcontainer up` and its validated result, and how a folder and
//! configuration are named to the CLI and to the labels it puts on the container.
use ide_core::{IdeError, IdeResult};
use ide_core::cli_process::{CarriageReturn, CliTool, Decoding, Poll, Stream, keep_stderr_line};
use ide_core::{CancellationToken, IdeError, IdeResult};
use parking_lot::Mutex;
use serde::Deserialize;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
/// Building an image (and its features) can take a while on a first open.
pub const UP_TIMEOUT: Duration = Duration::from_secs(30 * 60);
/// The label of a container naming the folder `devcontainer up` was given.
pub const FOLDER_LABEL: &str = "devcontainer.local_folder";
/// The label of a container naming the configuration file it was started from.
pub const CONFIG_LABEL: &str = "devcontainer.config_file";
/// The folder and configuration file the CLI is pointed at. The same values name the container
/// in its labels, which is how the project's container is found again: the folder as opened
/// (not canonicalised) and the configuration as `folder.join(config)`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Target {
folder: PathBuf,
config: Option<PathBuf>,
}
impl Target {
/// `config` is the configuration file itself; `None` leaves it to the CLI (the default one).
pub fn new(folder: impl Into<PathBuf>, config: Option<PathBuf>) -> Self {
// Native separators throughout, as the CLI's `path.resolve` writes the label on Windows.
Self { folder: folder.into(), config: config.map(|c| c.components().collect()) }
}
/// `config` relative to `folder`; blank means the default one.
pub fn relative(folder: &Path, config: &str) -> Self {
let config = config.trim();
Self::new(folder, (!config.is_empty()).then(|| folder.join(config)))
}
pub fn folder(&self) -> &Path {
&self.folder
}
pub fn config(&self) -> Option<&Path> {
self.config.as_deref()
}
/// `--workspace-folder <folder>` and, with a configuration, `--config <file>`.
pub fn args(&self) -> Vec<OsString> {
let mut args = vec![OsString::from("--workspace-folder"), self.folder.clone().into_os_string()];
if let Some(config) = &self.config {
args.extend([OsString::from("--config"), config.clone().into_os_string()]);
}
args
}
/// The value of [`FOLDER_LABEL`] the CLI puts on this folder's container.
pub fn folder_label(&self) -> String {
label_value(&self.folder.to_string_lossy())
}
/// The value of [`CONFIG_LABEL`], when the configuration is known.
pub fn config_label(&self) -> Option<String> {
self.config.as_deref().map(|c| label_value(&c.to_string_lossy()))
}
}
/// A path as the CLI writes it into a label: on Windows its drive letter is lower case
/// (`c:\work\app`), so a label is compared that way.
pub fn label_value(path: &str) -> String {
let mut chars = path.chars();
match (chars.next(), chars.next()) {
(Some(drive), Some(':')) if drive.is_ascii_alphabetic() => {
format!("{}{}", drive.to_ascii_lowercase(), &path[1..])
}
_ => path.to_owned(),
}
}
/// The container `devcontainer up` started, as it reported it.
#[derive(Debug, PartialEq, Eq)]
@@ -60,9 +137,103 @@ pub fn parse_up(stdout: &str) -> IdeResult<Up> {
}
}
/// The folders whose `devcontainer up` the MCP tools run now.
static BUSY: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
/// Holds `folder` as having an `up` or rebuild of the MCP tools running; released on drop.
#[derive(Debug)]
pub struct Busy(PathBuf);
impl Busy {
/// Takes `folder`, or refuses when another start of it runs. Only the MCP tools take it:
/// Reopen in Container does not, as a retry must not be refused for the length of a build.
pub fn take(folder: &Path) -> IdeResult<Self> {
let mut busy = BUSY.lock();
if busy.iter().any(|f| f == folder) {
return Err(IdeError::unavailable(format!(
"devcontainer up is already running for {}; wait for it to finish",
folder.display()
)));
}
busy.push(folder.to_owned());
Ok(Self(folder.to_owned()))
}
}
impl Drop for Busy {
fn drop(&mut self) {
BUSY.lock().retain(|f| *f != self.0);
}
}
/// `devcontainer up` for `target`, with `extra_args` after the standard ones. Blocks until the
/// CLI exits, `timeout` passes or `cancel` fires (the CLI and what it started are then
/// stopped); its log lines go to `on_line`.
pub fn up(
cli: &Path,
docker: &Path,
target: &Target,
extra_args: &[&str],
timeout: Duration,
on_line: &mut dyn FnMut(&str),
cancel: &CancellationToken,
) -> IdeResult<Up> {
const TOOL: CliTool = CliTool::new("devcontainer", Decoding::Utf8Lossy);
let timed_out = || IdeError::unavailable("devcontainer up did not finish in time");
if timeout.is_zero() {
return Err(timed_out());
}
let mut cmd = Command::new(cli);
cmd.arg("up").args(target.args()).arg("--docker-path").arg(docker).args(extra_args);
// Cancelled by `cancel` and, at the deadline, by the watch below: also while the CLI has
// closed its pipes and runs on.
let stop = cancel.child_token();
let mut lines = TOOL.lines(cmd, &stop, CarriageReturn::Dropped)?;
let (finished, deadline) = std::sync::mpsc::channel::<()>();
let watch = stop.clone();
std::thread::spawn(move || {
// Dropping `finished` (the function returned) ends the watch.
if deadline.recv_timeout(timeout) == Err(std::sync::mpsc::RecvTimeoutError::Timeout) {
watch.cancel();
}
});
let _finished = finished;
let (mut stdout, mut log) = (String::new(), Vec::new());
loop {
match lines.poll(&stop, Duration::from_millis(50)) {
Ok(Poll::Line(Stream::Stdout, line)) => {
stdout.push_str(&line);
stdout.push('\n');
}
Ok(Poll::Line(Stream::Stderr, line)) => {
on_line(&line);
if !line.trim().is_empty() {
keep_stderr_line(&mut log, line);
}
}
Ok(Poll::Closed | Poll::Timeout) => {}
Ok(Poll::Finished) => break,
Err(e) if cancel.is_cancelled() => return Err(e),
Err(_) => return Err(timed_out()),
}
}
let status = lines.finish(&stop).map_err(|e| if cancel.is_cancelled() { e } else { timed_out() })?;
let result = parse_up(&stdout);
if status.success() {
return result;
}
let error = result.err().unwrap_or_else(|| IdeError::unavailable(format!("devcontainer up exited with {status}")));
Err(match log.join("\n") {
t if t.is_empty() => error,
t => IdeError::unavailable(format!("{}\n{t}", error.message)),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
use std::time::Instant;
const ID: &str = "3f1c2b9a7d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8";
@@ -99,4 +270,115 @@ mod tests {
}
assert!(is_user("1000:1000") && is_user("node") && is_user("dev.user"));
}
#[test]
fn the_folder_and_configuration_name_the_cli_arguments_and_the_labels() {
let target = Target::relative(Path::new("/work/my app"), " .devcontainer/py/devcontainer.json ");
let config: PathBuf = Path::new("/work/my app/.devcontainer/py/devcontainer.json").components().collect();
let expected: Vec<OsString> =
vec!["--workspace-folder".into(), "/work/my app".into(), "--config".into(), config.clone().into()];
assert_eq!(target.args(), expected);
assert_eq!(target.folder_label(), "/work/my app");
assert_eq!(target.config_label().unwrap(), config.to_string_lossy());
let default = Target::relative(Path::new("/work/app"), "");
assert_eq!(default.args(), ["--workspace-folder", "/work/app"]);
assert_eq!(default.config_label(), None);
}
#[cfg(windows)]
#[test]
fn a_windows_configuration_label_has_native_separators() {
let target = Target::relative(Path::new(r"C:\work\app"), ".devcontainer/py/devcontainer.json");
assert_eq!(target.config_label().unwrap(), r"c:\work\app\.devcontainer\py\devcontainer.json");
}
#[test]
fn a_windows_drive_letter_is_lower_case_in_a_label() {
assert_eq!(label_value(r"C:\Users\me\app"), r"c:\Users\me\app");
assert_eq!(label_value(r"c:\Users\me\app"), r"c:\Users\me\app");
assert_eq!(label_value("/Users/me/C:/app"), "/Users/me/C:/app");
assert_eq!(label_value("C"), "C");
assert_eq!(label_value(""), "");
}
#[cfg(unix)]
fn fake_cli(dir: &Path, script: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let cli = dir.join("devcontainer");
std::fs::write(&cli, format!("#!/bin/sh\n{script}\n")).unwrap();
std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap();
cli
}
#[test]
fn a_folder_is_held_by_one_start_at_a_time() {
let folder = Path::new("/work/held");
let first = Busy::take(folder).unwrap();
assert!(Busy::take(folder).unwrap_err().message.contains("already running"));
let other = Busy::take(Path::new("/work/other")).unwrap();
drop(first);
drop(Busy::take(folder).unwrap());
drop(other);
}
#[cfg(unix)]
#[test]
fn up_stops_the_cli_on_cancel() {
let dir = tempfile::tempdir().unwrap();
let started = dir.path().join("started");
let cli = fake_cli(dir.path(), &format!("touch '{}'\nsleep 30 & wait", started.display()));
let target = Target::new(dir.path().join("app"), None);
let cancel = CancellationToken::new();
let slow = {
let (cancel, target) = (cancel.clone(), target.clone());
std::thread::spawn(move || up(&cli, Path::new("docker"), &target, &[], UP_TIMEOUT, &mut |_| {}, &cancel))
};
while !started.exists() {
std::thread::sleep(Duration::from_millis(10));
}
cancel.cancel();
assert_eq!(slow.join().unwrap().unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
}
#[cfg(unix)]
#[test]
fn up_stops_a_cli_that_closed_its_pipes_and_runs_on() {
let dir = tempfile::tempdir().unwrap();
let cli = fake_cli(dir.path(), "exec 1>&- 2>&-\nsleep 30");
let target = Target::new(dir.path().join("app"), None);
let began = Instant::now();
let err = up(
&cli,
Path::new("docker"),
&target,
&[],
Duration::from_millis(300),
&mut |_| {},
&CancellationToken::new(),
)
.unwrap_err();
assert!(err.message.contains("did not finish in time"), "{}", err.message);
assert!(began.elapsed() < Duration::from_secs(10));
}
#[cfg(unix)]
#[test]
fn up_stops_a_cli_that_outlives_the_timeout() {
let dir = tempfile::tempdir().unwrap();
let cli = fake_cli(dir.path(), "sleep 30");
let target = Target::new(dir.path().join("app"), None);
let began = Instant::now();
let err = up(
&cli,
Path::new("docker"),
&target,
&[],
Duration::from_millis(200),
&mut |_| {},
&CancellationToken::new(),
)
.unwrap_err();
assert!(err.message.contains("did not finish in time"), "{}", err.message);
assert!(began.elapsed() < Duration::from_secs(10));
}
}
+22 -3
Переглянути файл
@@ -135,6 +135,25 @@ As JetBrains IDEs do, the command runs on pipes, not a terminal: programs print
Plugins can add more tools; they appear in the same list. A plugin tool marked as destructive asks for confirmation the same way.
## Dev containers
Five tools work on the project's [dev container](/en/guide/remote/containers) from the local desktop. `devcontainer_status` and `devcontainer_logs` only read Docker's state and are available for any local project. `devcontainer_up`, `devcontainer_exec` and `devcontainer_stop` need a trusted project and ask first, unless brave mode is on.
- `devcontainer_status` lists the project's `devcontainer.json` files and its containers with their state, image and ports, and says whether Docker and the Dev Containers CLI are ready.
- `devcontainer_logs` returns the last lines of a container's log (200 by default, at most 5000).
- `devcontainer_up` starts the container, building it if needed. With `rebuild: true` it removes the container and builds it again; `noCache` (only with `rebuild`) skips the build cache. It waits up to `timeout` milliseconds (30 minutes by default, and more than 0); the Dev Containers CLI is stopped when it passes.
- `devcontainer_exec` runs a command in the container, with the user and environment a terminal in the container has. It runs in a tab of the Run tool window like `run_command`, takes the same `name`, `timeout`, `pattern`, `maxLinesCount` and `truncateMode` arguments, plus `envs` and `config`, and is followed up with `wait_for_run`, `read_run_output` and `stop_run`. It needs a window.
- `devcontainer_stop` stops the container and the other containers of its Compose project. Nothing is removed.
**Which container.** The tools act on the container the Dev Containers CLI labels for the project folder and its `devcontainer.json`. `config` picks another `devcontainer.json` inside the project. For a Compose setup, `devcontainer_logs` and `devcontainer_stop` also cover the other containers of the same Compose project. Any other container is refused, including one named by `containerId`.
**Requirements.** The tools need Docker with a daemon on this computer and the Dev Containers CLI, which you install in **Settings › Languages & Frameworks › Language Servers**. Without them, `devcontainer_status` still answers and says what is missing; the other tools fail with that reason.
- `devcontainer_up` with `rebuild` and `devcontainer_stop` refuse a container that a window is opened in.
- A Run tab rerun uses the original `devcontainer_exec` container ID. To run the command in a replacement container, call `devcontainer_exec` again.
- Stopping the `devcontainer_exec` tab ends the CLI. A process it started in the container may keep running there, because Docker does not stop it when the client goes away.
- Background projects can use every dev container tool except `devcontainer_exec`.
## Background projects
By default the server answers only for projects open in a window. **Serve without a window** lets it also answer for a folder that has no window: the first tool call for a path inside it opens the project, and OpenIDEA unloads it again after it has been idle for a while. The setting is under **Background projects** on **Settings › Agents › IDE MCP Server**. It is off by default.
@@ -170,7 +189,7 @@ What trust decides: a trusted project works as one open in a window, with its la
A background project has no window, so some tools differ:
- `run_command`, `open_file_in_editor`, `xdebug_start_debugger_session` and the breakpoint tools (`xdebug_set_breakpoint`, `xdebug_remove_breakpoint`, `xdebug_list_breakpoints`) need a window. They refuse before they ask.
- `run_command`, `devcontainer_exec`, `open_file_in_editor`, `xdebug_start_debugger_session` and the breakpoint tools (`xdebug_set_breakpoint`, `xdebug_remove_breakpoint`, `xdebug_list_breakpoints`) need a window. They refuse before they ask.
- `get_file_problems` and `get_project_problems` report what a window shows. In a background project they answer with an error that points to `check_files`.
- `get_current_file` and `get_all_open_file_paths` also describe a window. In a background project they answer with an error that says the project needs a window.
- `execute_run_configuration`, `build_project`, `http_run_request` and destructive plugin tools ask in the project window you used last. The dialog has a line `Background project <folder name>` with the full path under it, and requests queue there. The dialog does not take keyboard focus: answer it with a click, or click into it first and then use the keys. If that window closes or loses trust, the request moves to another open project window. With no project window open, the call fails with "no project window is available". Brave mode runs these tools without asking, with or without a window.
@@ -178,13 +197,13 @@ A background project has no window, so some tools differ:
## Safety
- **Untrusted projects** expose only the read-only tools. Tools that write files, rename, reformat, build or run need a project you have trusted. A client started outside every project sees every tool, and so does one that names no project while no window or several windows are open. A tool that writes or runs still refuses a project you have not trusted.
- **Running and building ask first.** `execute_run_configuration`, `build_project`, `run_command` and `http_run_request` show a dialog in OpenIDEA naming the client, the project, the tool and what will run. Choose **Allow** or **Deny**; several requests queue up. In a background project, all of them but `run_command` ask in the project window you used last, and the dialog names the project.
- **Running and building ask first.** `execute_run_configuration`, `build_project`, `run_command`, `http_run_request`, `devcontainer_up`, `devcontainer_exec` and `devcontainer_stop` show a dialog in OpenIDEA naming the client, the project, the tool and what will run. Choose **Allow** or **Deny**; several requests queue up. In a background project, all of them but `run_command` and `devcontainer_exec` ask in the project window you used last, and the dialog names the project.
- Tools that write refuse paths outside the project.
- **Background projects.** Anyone with the token can make the IDE load a project that **Serve without a window** serves, so the setting and the token decide who can open folders on this computer. Listed folders you have not trusted open in Restricted Mode and get only the read-only tools. Keep the list to folders you want agents to reach.
## Remote development
In a remote window ([SSH](/en/guide/remote/ssh), WSL or [Dev Containers](/en/guide/remote/containers)), `openidea-server` runs its own MCP server on the remote host, configured independently in **Settings › Agents › IDE MCP Server** while that remote window is focused. Coding agents started inside the remote window connect to it automatically; external CLI clients on the remote host can use **Copy Stdio Config** (`~/.openidea/bin/openidea-server --mcp-stdio`) or **Copy HTTP Config**, and clients on your desktop can reach it by forwarding its port in the **Ports** tool window. The remote server serves only the project open in its window: [background projects](#background-projects) are served by OpenIDEA on your desktop, and the **Background projects** group is disabled in a remote window's Settings.
In a remote window ([SSH](/en/guide/remote/ssh), WSL or [Dev Containers](/en/guide/remote/containers)), `openidea-server` runs its own MCP server on the remote host, configured independently in **Settings › Agents › IDE MCP Server** while that remote window is focused. Coding agents started inside the remote window connect to it automatically; external CLI clients on the remote host can use **Copy Stdio Config** (`~/.openidea/bin/openidea-server --mcp-stdio`) or **Copy HTTP Config**, and clients on your desktop can reach it by forwarding its port in the **Ports** tool window. The remote server serves only the project open in its window: [background projects](#background-projects) are served by OpenIDEA on your desktop, and the **Background projects** group is disabled in a remote window's Settings. The [dev container tools](#dev-containers) run on the desktop for the local folder; a window opened in the container is a remote window, and its MCP server has no access to the desktop's Docker.
## Limits
+22 -3
Переглянути файл
@@ -134,6 +134,25 @@ stdio 配置大致如下(路径以你机器上的为准):
插件可以添加更多工具,它们会出现在同一个列表中。标记为破坏性操作的插件工具同样会先请求确认。
## 开发容器
五个工具在本地桌面端操作项目的[开发容器](/zh/guide/remote/containers)。`devcontainer_status` 和 `devcontainer_logs` 只读取 Docker 的状态,在所有本地项目中都可用。`devcontainer_up`、`devcontainer_exec` 和 `devcontainer_stop` 需要项目已被信任,并且会先询问,勇敢模式下除外。
- `devcontainer_status` 列出项目的 `devcontainer.json` 文件和容器(含状态、镜像和端口),并说明 Docker 和 Dev Containers CLI 是否就绪。
- `devcontainer_logs` 返回容器日志的最后若干行(默认 200 行,最多 5000 行)。
- `devcontainer_up` 启动容器,需要时先构建。`rebuild: true` 会删除容器并重新构建;`noCache`(仅与 `rebuild` 一起使用)跳过构建缓存。它最多等待 `timeout` 毫秒(默认 30 分钟,且必须大于 0),超时后会停止 Dev Containers CLI。
- `devcontainer_exec` 在容器中执行命令,使用与容器内终端相同的用户和环境。它和 `run_command` 一样在运行工具窗口的标签页中运行,接受相同的 `name`、`timeout`、`pattern`、`maxLinesCount` 和 `truncateMode` 参数,另有 `envs` 和 `config`,之后用 `wait_for_run`、`read_run_output` 和 `stop_run` 跟进。此工具需要窗口。
- `devcontainer_stop` 停止容器,以及同一 Compose 项目中的其他容器。不会删除任何容器。
**操作哪个容器。** 这些工具操作 Dev Containers CLI 为项目文件夹及其 `devcontainer.json` 打上标签的那个容器。`config` 可以指定项目内的另一个 `devcontainer.json`。对于 Compose 配置,`devcontainer_logs` 和 `devcontainer_stop` 还涵盖同一 Compose 项目中的其他容器。其他任何容器都会被拒绝,包括用 `containerId` 指定的。
**前提条件。** 这些工具需要本机上有守护进程的 Docker,以及 Dev Containers CLI(在 **设置 › 语言和框架 › 语言服务器** 中安装)。缺少它们时,`devcontainer_status` 仍会返回结果并说明缺什么;其他工具会失败并给出原因。
- 带 `rebuild` 的 `devcontainer_up` 和 `devcontainer_stop` 会拒绝已有窗口打开的容器。
- 运行标签页重跑时使用 `devcontainer_exec` 原先的容器 ID。要在替换后的容器内运行命令,请再次调用 `devcontainer_exec`。
- 停止 `devcontainer_exec` 的标签页会结束 CLI。它在容器中启动的进程可能继续运行,因为客户端退出后 Docker 不会停止它。
- 后台项目可以使用除 `devcontainer_exec` 之外的所有开发容器工具。
## 后台项目
默认情况下,服务器只为在窗口中打开的项目提供服务。**无窗口时提供服务** 让它也能为没有窗口的文件夹提供服务:第一次针对其中某个路径的工具调用会打开该项目,空闲一段时间后 OpenIDEA 再把它卸载。这项设置在 **设置 › 智能体 › IDE MCP 服务器** 的 **后台项目** 下,默认关闭。
@@ -169,7 +188,7 @@ stdio 配置大致如下(路径以你机器上的为准):
后台项目没有窗口,所以有些工具不同:
- `run_command`、`open_file_in_editor`、`xdebug_start_debugger_session` 和断点工具(`xdebug_set_breakpoint`、`xdebug_remove_breakpoint`、`xdebug_list_breakpoints`)需要窗口,它们会在询问之前直接拒绝。
- `run_command`、`devcontainer_exec`、`open_file_in_editor`、`xdebug_start_debugger_session` 和断点工具(`xdebug_set_breakpoint`、`xdebug_remove_breakpoint`、`xdebug_list_breakpoints`)需要窗口,它们会在询问之前直接拒绝。
- `get_file_problems` 和 `get_project_problems` 报告的是窗口中显示的内容。在后台项目中,它们会返回一个错误,指向 `check_files`。
- `get_current_file` 和 `get_all_open_file_paths` 描述的同样是窗口。在后台项目中,它们会返回一个错误,说明该项目需要窗口。
- `execute_run_configuration`、`build_project`、`http_run_request` 和带破坏性标记的插件工具会在你最后使用的项目窗口中询问。对话框中有一行 `后台项目 <文件夹名>`,下面是完整路径,请求在这里排队。对话框不会获得键盘焦点:用鼠标点击它,或先点进对话框再用键盘操作。该窗口关闭或失去信任时,请求会转到另一个打开的项目窗口。没有打开任何项目窗口时,调用会失败,返回 `no project window is available`。勇敢模式下,这些工具无需询问即可运行,有没有窗口都一样。
@@ -177,13 +196,13 @@ stdio 配置大致如下(路径以你机器上的为准):
## 安全
- **未受信任的项目** 只开放只读工具。写文件、重命名、重新格式化、构建或运行的工具都要求项目已被信任。在所有项目之外启动的客户端能看到全部工具;没有打开窗口或打开了多个窗口时,未指定项目的客户端也是如此。会写入或运行的工具仍会拒绝你没有信任的项目。
- **运行和构建会先询问。** `execute_run_configuration`、`build_project`、`run_command` 和 `http_run_request` 会在 OpenIDEA 中弹出对话框,说明是哪个客户端、哪个项目、哪个工具以及要运行什么,选择 **允许** 或 **拒绝**;多个请求会排队。在后台项目中,除 `run_command` 外,这些工具都会在你最后使用的项目窗口中询问,对话框会写明该项目。
- **运行和构建会先询问。** `execute_run_configuration`、`build_project`、`run_command`、`http_run_request`、`devcontainer_up`、`devcontainer_exec` 和 `devcontainer_stop` 会在 OpenIDEA 中弹出对话框,说明是哪个客户端、哪个项目、哪个工具以及要运行什么,选择 **允许** 或 **拒绝**;多个请求会排队。在后台项目中,除 `run_command` 和 `devcontainer_exec` 外,这些工具都会在你最后使用的项目窗口中询问,对话框会写明该项目。
- 会写入的工具拒绝项目之外的路径。
- **后台项目。** 任何持有令牌的人都能让 IDE 加载 **无窗口时提供服务** 所提供的项目,所以这项设置和令牌共同决定谁能在这台电脑上打开文件夹。你没有信任的列出文件夹会以受限模式打开,只开放只读工具。列表里只放你愿意让智能体访问的文件夹。
## 远程开发
在远程窗口([SSH](/zh/guide/remote/ssh)、WSL 或[容器](/zh/guide/remote/containers))中,`openidea-server` 会在远程主机上运行自己的 MCP 服务器,可在该远程窗口的 **Settings › Agents › IDE MCP Server** 中独立配置。远程窗口内启动的编程智能体会立即可用内置工具;在远程主机终端运行的外部客户端可使用 **Copy Stdio Config**(`~/.openidea/bin/openidea-server --mcp-stdio`)或 **Copy HTTP Config**,桌面端客户端则可在 **Ports** 工具窗口转发该端口后连接。远程服务器只为其窗口中打开的项目提供服务:[后台项目](#后台项目)由桌面上的 OpenIDEA 提供,远程窗口的设置里 **后台项目** 分组不可编辑。
在远程窗口([SSH](/zh/guide/remote/ssh)、WSL 或[容器](/zh/guide/remote/containers))中,`openidea-server` 会在远程主机上运行自己的 MCP 服务器,可在该远程窗口的 **Settings › Agents › IDE MCP Server** 中独立配置。远程窗口内启动的编程智能体会立即可用内置工具;在远程主机终端运行的外部客户端可使用 **Copy Stdio Config**(`~/.openidea/bin/openidea-server --mcp-stdio`)或 **Copy HTTP Config**,桌面端客户端则可在 **Ports** 工具窗口转发该端口后连接。远程服务器只为其窗口中打开的项目提供服务:[后台项目](#后台项目)由桌面上的 OpenIDEA 提供,远程窗口的设置里 **后台项目** 分组不可编辑。[开发容器工具](#开发容器)在桌面端针对本地文件夹运行;在容器中打开的窗口是远程窗口,它的 MCP 服务器无法访问桌面端的 Docker。
## 限制
+12
Переглянути файл
@@ -44,6 +44,18 @@ test("Gradle keeps the local installation with Distribution and saves edits in p
await expect(distribution).toHaveText("Gradle wrapper");
await expect(installation).toHaveCount(0);
const fields = userHome.or(runUsing).or(distribution).or(jvm);
for (const width of [1120, 800, 520]) {
await page.setViewportSize({ width, height: 760 });
const edges = await fields.evaluateAll((elements) =>
elements.map((element) => {
const { left, right } = element.getBoundingClientRect();
return [Math.round(left), Math.round(right)];
}),
);
expect(edges).toHaveLength(4);
for (const edge of edges.slice(1)) expect(edge).toEqual(edges[0]);
}
await distribution.click();
await page.getByRole("option", { name: "Local installation", exact: true }).click();
const browse = installation.locator("..").getByRole("button", { name: /^Browse/ });
+41
Переглянути файл
@@ -74,6 +74,47 @@ test("settings forms share control columns and keep font metrics on one row", as
}
});
test("toolchain, encoding and Subversion settings align field frames across sections", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const body = page.getByRole("dialog", { name: "Settings", exact: true }).locator("[class*='pageBody']");
for (const [id, title, count] of [
["languages.go", "Go", 2],
["languages.java", "Java", 4],
["languages.rust", "Rust", 4],
["languages.node", "JavaScript Runtime", 4],
["languages.php", "PHP", 4],
["build.maven", "Maven", 8],
["editor.fileEncodings", "File Encodings", 4],
["vcs.svn", "Subversion", 2],
] as const) {
await selectPage(page, id);
await expect(page.getByLabel("Breadcrumb").locator('[aria-current="page"]')).toHaveText(title);
if (id === "vcs.svn") {
await body.getByRole("checkbox", { name: "Use custom configuration directory" }).check();
await expect(body.getByRole("textbox", { name: /Configuration directory/ })).toBeEnabled();
}
const fields = body
.getByRole("button")
.and(body.locator("[aria-haspopup='listbox']"))
.or(body.getByRole("textbox"))
.or(body.getByRole("combobox"))
.and(body.locator(':not([aria-label="Thread count"])'));
await expect(fields).toHaveCount(count);
for (const width of [1200, 800, 520]) {
await page.setViewportSize({ width, height: 800 });
for (const group of [fields, body.getByRole("button", { name: "Browse…", exact: true })]) {
const edges = await group.evaluateAll((elements) =>
elements.map((element) => {
const { left, right } = element.getBoundingClientRect();
return [Math.round(left), Math.round(right)];
}),
);
for (const edge of edges.slice(1)) expect(edge, `${id} at ${width}px`).toEqual(edges[0]);
}
}
}
});
for (const locale of ["en", "zh"]) {
test(`${locale} forms fit narrow settings panes without horizontal scrolling`, async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
+23
Переглянути файл
@@ -117,6 +117,29 @@ test("Live Templates gives the editor the full settings pane width and keeps var
expect(await variables.evaluate((element) => element.scrollWidth - element.clientWidth)).toBe(0);
});
test("Project settings aligns the visible fields and their browse buttons", async ({ workbench: page }) => {
await page.keyboard.press("Meta+;");
const dialog = page.getByRole("dialog", { name: "Project Structure", exact: true });
const fields = dialog
.getByRole("button", { name: /^(Project SDK|Project language level|Language server JDK)$/ })
.or(dialog.getByRole("textbox", { name: "Compiler output" }));
const browse = dialog.getByRole("button", { name: "Browse…" });
await expect(fields).toHaveCount(4);
await expect(browse).toHaveCount(3);
for (const width of [1400, 800, 520]) {
await page.setViewportSize({ width, height: 800 });
for (const group of [fields, browse]) {
const edges = await group.evaluateAll((elements) =>
elements.map((element) => {
const { left, right } = element.getBoundingClientRect();
return [Math.round(left), Math.round(right)];
}),
);
for (const edge of edges.slice(1)) expect(edge).toEqual(edges[0]);
}
}
});
test("Project Structure keeps every details pane usable in a compact window", async ({ workbench: page }) => {
await page.keyboard.press("Meta+;");
const dialog = page.getByRole("dialog", { name: "Project Structure", exact: true });
+25 -58
Переглянути файл
@@ -14,73 +14,39 @@ use crate::remote_wsl::{Probe, Tail, install_script, parse_probe, probe_script,
use ide_core::{IdeError, IdeResult};
use ide_jsonrpc::{Handler, Peer};
use ide_remote::container_tunnel::Exec;
use ide_remote::devcontainer::{Up, parse_up};
use ide_remote::devcontainer::{self, Target, UP_TIMEOUT, Up};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::AsyncBufReadExt;
/// Building an image (and its features) can take a while on a first open.
const UP_TIMEOUT: Duration = Duration::from_secs(30 * 60);
const PROBE_TIMEOUT: Duration = Duration::from_secs(60);
/// The Dev Containers CLI: the IDE-managed copy (Settings › Languages & Frameworks › Language Servers) or one on `PATH`.
fn cli(data_dir: &Path) -> IdeResult<PathBuf> {
ide_tools::Tools::new(data_dir)
.info("devcontainer", &[])
.ok()
.and_then(|t| t.path)
.map(ide_core::IpcPath::into_path_buf)
.ok_or_else(|| {
IdeError::unavailable(
"The Dev Containers CLI is not installed. Install it in Settings › Languages & Frameworks › Language Servers.",
)
})
}
/// `devcontainer up` for `folder` (with configuration `config`, relative to it; empty = the
/// default one). Its log goes to `tail` and the IDE log.
async fn up(cli: &Path, docker: &Path, folder: &Path, config: &str, tail: &Tail) -> IdeResult<Up> {
let mut cmd = tokio::process::Command::new(cli);
ide_core::process::prepare(cmd.as_std_mut());
cmd.arg("up").arg("--workspace-folder").arg(folder);
if !config.trim().is_empty() {
cmd.arg("--config").arg(folder.join(config.trim()));
}
cmd.arg("--docker-path")
.arg(docker)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let mut child = cmd.spawn().map_err(|e| IdeError::unavailable(format!("cannot start devcontainer: {e}")))?;
let stderr = child.stderr.take();
let log = tail.clone();
let reader = tokio::spawn(async move {
let Some(stderr) = stderr else { return };
let mut lines = tokio::io::BufReader::new(stderr).lines();
while let Ok(Some(line)) = lines.next_line().await {
tracing::info!(target: "devcontainer", "{line}");
log.push(line);
}
});
let out = tokio::time::timeout(UP_TIMEOUT, child.wait_with_output())
.await
.map_err(|_| IdeError::unavailable("devcontainer up did not finish in time"))?
.map_err(|e| IdeError::unavailable(format!("devcontainer up failed: {e}")))?;
let _ = reader.await;
let result = parse_up(&String::from_utf8_lossy(&out.stdout));
if out.status.success() {
return result;
}
let error = result
.err()
.unwrap_or_else(|| IdeError::unavailable(format!("devcontainer up exited with {status}", status = out.status)));
Err(match tail.text() {
t if t.is_empty() => error,
t => IdeError::unavailable(format!("{}\n{t}", error.message)),
let (cli, docker, target, tail) =
(cli.to_owned(), docker.to_owned(), Target::relative(folder, config), tail.clone());
let cancel = ide_core::CancellationToken::new();
// This future dropped (the command was cancelled): the CLI stops with it. A superseded
// attempt is not dropped and runs on; Reopen in Container is not held to one start per folder.
let _stop = cancel.clone().drop_guard();
tokio::task::spawn_blocking(move || {
devcontainer::up(
&cli,
&docker,
&target,
&[],
UP_TIMEOUT,
&mut |line| {
tracing::info!(target: "devcontainer", "{line}");
tail.push(line.to_owned());
},
&cancel,
)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// `docker exec [-i] -u <user> <container> sh -c <script> sh <args>…`.
@@ -214,8 +180,9 @@ pub(crate) async fn connect(
));
}
let data = state.host.local_data_dir.clone();
let cli =
tokio::task::spawn_blocking(move || cli(&data)).await.map_err(|e| IdeError::internal(e.to_string()))??;
let cli = tokio::task::spawn_blocking(move || ide_host::devcontainer::cli(&data))
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
let up = up(&cli, &docker, &local, config, tail).await?;
let bin = ensure_server(state, &docker, &up, progress).await?;
progress(RemoteStage::Starting, None);
+7
Переглянути файл
@@ -89,6 +89,8 @@ pub struct Connection {
session: Option<Arc<ide_ssh::Session>>,
/// How to reach a dev container's ports; `None` for SSH and WSL.
exec: Option<Arc<ide_remote::container_tunnel::Exec>>,
/// Marks a dev container's container as open in a window for as long as the connection lives.
_attached: Option<ide_host::devcontainer::AttachedContainer>,
/// Remote ports forwarded to this machine (Ports tool window), by host (`None`: the remote
/// host itself) and remote port.
forwards: Mutex<Vec<(ForwardKey, Forward)>>,
@@ -738,6 +740,7 @@ pub async fn remote_connect(
});
let tail = crate::remote_wsl::Tail::default();
let mut exec = None;
let mut attached = None;
let (peer, session, host, title_tag) = match &target {
RemoteTarget::Ssh { config: id } => {
let config = state.ssh.config(id)?;
@@ -774,6 +777,8 @@ pub async fn remote_connect(
let (peer, root, run) =
crate::remote_container::connect(&state, folder, config, replace, handler, &tail, &progress).await?;
path = root;
// The MCP tools leave this container alone while a window is open in it.
attached = Some(state.host.dev_containers_attached.hold(run.container()));
exec = Some(Arc::new(run));
let name = std::path::Path::new(folder)
.file_name()
@@ -847,6 +852,7 @@ pub async fn remote_connect(
forwards: Mutex::new(Vec::new()),
web_forwards: Mutex::new(Vec::new()),
exec,
_attached: attached,
});
let _ = connection_slot.set(Arc::downgrade(&connection));
if let RemoteTarget::DevContainer { folder, config } = &target {
@@ -1615,6 +1621,7 @@ mod tests {
next_channel: std::sync::atomic::AtomicU64::new(1),
session: None,
exec: None,
_attached: None,
forwards: Mutex::new(Vec::new()),
web_forwards: Mutex::new(Vec::new()),
}
+1
Переглянути файл
@@ -112,6 +112,7 @@ impl AppState {
runtime,
project_environment: false,
})
.with_local_desktop()
.with_local_database_tunnels()
.with_subversion(true),
);
+4 -1
Переглянути файл
@@ -12499,6 +12499,9 @@ export type MavenSettings = {
runTestsUsing?: MavenRunTestsUsing,
};
/** The execution target recorded with an MCP agent run. */
export type McpAgentRunTarget = { kind: "host" } | { kind: "container"; id: string };
/** What keeps an idle background project loaded. */
export type McpBackgroundHold =
/** A tool call is in flight. */
@@ -12822,7 +12825,7 @@ export type McpUiRequest = { type: "confirm"; client: string; tool: string; subj
* The project is served without a window: the request shows in another project's window,
* which names it and keeps the keyboard focus where it is.
*/
background?: boolean } | { type: "openFile"; path: IpcPath; line: number | null; column: number | null } | { type: "agentRun"; name: string; command: string; cwd: IpcPath; env: { [key in string]: string } } | { type: "runConfiguration"; config: unknown } |
background?: boolean } | { type: "openFile"; path: IpcPath; line: number | null; column: number | null } | { type: "agentRun"; name: string; command: string; cwd: IpcPath; env: { [key in string]: string }; target: McpAgentRunTarget } | { type: "runConfiguration"; config: unknown } |
/** Start a run configuration in Debug mode as the IDE's Debug action would. */
{ type: "debugConfiguration"; config: unknown } |
/**
+10 -1
Переглянути файл
@@ -130,13 +130,22 @@ describe("MCP confirmations", () => {
expect(mocks.respond).toHaveBeenCalledWith(8, false, "Error: cannot open");
});
it("starts an agent command in the Run tool window and says whether it started", async () => {
const request = { type: "agentRun", name: "_agent_test", command: "npm test", cwd: "/project", env: {} } as const;
const target = { kind: "container", id: "a".repeat(64) } as const;
const request = {
type: "agentRun",
name: "_agent_test",
command: "npm test",
cwd: "/project",
env: {},
target,
} as const;
await handleMcpRequest(9, request);
expect(mocks.execute).toHaveBeenCalledWith("run.agentStart", {
name: "_agent_test",
command: "npm test",
cwd: "/project",
env: {},
target,
});
expect(mocks.respond).toHaveBeenCalledWith(9, true, null);
mocks.execute.mockRejectedValueOnce(new Error("The command did not start"));
+2 -2
Переглянути файл
@@ -105,8 +105,8 @@ export async function handleMcpRequest(
if (request.type === "agentRun") {
// The Run tool window starts it in the agent tab; the answer says whether it started.
try {
const { name, command, cwd, env } = request;
await executeActionOrThrow("run.agentStart", { name, command, cwd, env });
const { name, command, cwd, env, target } = request;
await executeActionOrThrow("run.agentStart", { name, command, cwd, env, target });
await send(id, true);
} catch (error) {
await send(id, false, error instanceof Error ? error.message : String(error)).catch(() => {});
+17 -7
Переглянути файл
@@ -1,11 +1,12 @@
/** Run configurations of commands agents run through the IDE's MCP server (`run_command`). */
import type { IpcPath, RunConfig } from "@/bindings";
import type { IpcPath, McpAgentRunTarget, RunConfig } from "@/bindings";
import { workflowSettings } from "@/platform/workflowSettings";
/** Names the agent tab a run belongs to; the backend logs it for the agent. */
export const AGENT_PARAM = "mcp.agentRun";
/** Settings › Tools › Terminal › Shell path, which the backend runs the command line with. */
const SHELL_PARAM = "mcp.agentShell";
const TARGET_PARAM = "mcp.agentTarget";
/** The agent tab name of a configuration, or `null` for any other run. */
export function agentName(config: Pick<RunConfig, "params">): string | null {
@@ -13,11 +14,16 @@ export function agentName(config: Pick<RunConfig, "params">): string | null {
}
/**
* The command line of agent tab `name`, with the shell of the IDE's terminal but on pipes (as
* JetBrains' `execute_terminal_command`): programs print plain lines, the console shows them and
* sends the user's input lines.
* The command line and approved execution target of agent tab `name`. The console shows output
* from the process's pipes and sends the user's input lines.
*/
export function agentConfig(name: string, command: string, cwd: IpcPath, env: Record<string, string>): RunConfig {
export function agentConfig(
name: string,
command: string,
cwd: IpcPath,
env: Record<string, string>,
target: McpAgentRunTarget,
): RunConfig {
const terminal = workflowSettings().terminal;
return {
id: `mcp-agent:${name}`,
@@ -31,8 +37,12 @@ export function agentConfig(name: string, command: string, cwd: IpcPath, env: Re
isTest: false,
debugAdapter: null,
allowParallel: true,
params: { [AGENT_PARAM]: name, [SHELL_PARAM]: terminal.shellPath },
// This machine: an agent's command never goes to a default run target.
params: {
[AGENT_PARAM]: name,
[SHELL_PARAM]: terminal.shellPath,
[TARGET_PARAM]: JSON.stringify(target),
},
// The backend starts the shell or Dev Containers CLI on this machine.
target: "",
};
}
+9 -2
Переглянути файл
@@ -23,7 +23,7 @@ function session(id: string, config: RunConfig, status: RunSession["status"], en
describe("agent tabs", () => {
it("run the command line on pipes, on this machine", () => {
const config = agentConfig("_agent_build", "cargo build", "/project", { A: "1" });
const config = agentConfig("_agent_build", "cargo build", "/project", { A: "1" }, { kind: "host" });
expect(agentName(config)).toBe("_agent_build");
expect(agentName(plain)).toBeNull();
expect(config).toMatchObject({
@@ -38,10 +38,17 @@ describe("agent tabs", () => {
expect(config.emulateTerminal).toBeFalsy();
expect(config.env).toMatchObject({ A: "1" });
expect(config.params).toHaveProperty("mcp.agentShell");
expect(config.params?.["mcp.agentTarget"]).toBe(JSON.stringify({ kind: "host" }));
});
it("stores the approved container target in the config reused by reruns", () => {
const target = { kind: "container", id: "a".repeat(64) } as const;
const config = agentConfig("_agent_build", "in dev container app: cargo build", "/project", {}, target);
expect(config.params?.["mcp.agentTarget"]).toBe(JSON.stringify(target));
});
it("archive the oldest finished ones beyond the limit, never a running one or another run", () => {
const agent = (name: string) => agentConfig(name, "true", "/p", {});
const agent = (name: string) => agentConfig(name, "true", "/p", {}, { kind: "host" });
const sessions = [
session("old", agent("_agent_old"), "finished", 1),
session("failed", agent("_agent_failed"), "failed", 2),
+3 -8
Переглянути файл
@@ -1,19 +1,14 @@
/** The Run tool window's agent tabs: starting them, and archiving finished ones. */
import type { IpcPath } from "@/bindings";
import type { McpUiRequest } from "@/bindings";
import { agentRunSettings } from "@/platform/workflowSettings";
import { agentConfig, agentName } from "./agentConfig";
import { closeSession, isLive, startRun, useRun, type RunSession } from "./store";
export interface AgentRunRequest {
name: string;
command: string;
cwd: IpcPath;
env: Record<string, string>;
}
export type AgentRunRequest = Omit<Extract<McpUiRequest, { type: "agentRun" }>, "type">;
/** Starts an agent's command in its tab (reused once its last command finished). */
export async function startAgentRun(request: AgentRunRequest): Promise<void> {
const config = agentConfig(request.name, request.command, request.cwd, request.env);
const config = agentConfig(request.name, request.command, request.cwd, request.env, request.target);
const existing = useRun.getState().sessions.find((s) => s.config.id === config.id);
// The backend refuses a running name first; nothing here stops a run on the agent's behalf.
if (existing && isLive(existing)) throw new Error(`${request.name} is still running`);
+9 -1
Переглянути файл
@@ -38,9 +38,17 @@
min-width: 0;
}
.formGroup > .row,
.formGroup > .formGroup {
.formGroup > .formGroup,
.formGroup > .section,
.formGroup > .section > .sectionBody {
grid-template-columns: subgrid;
}
.formGroup > .section {
display: grid;
}
.formGroup > .section > * {
grid-column: 1 / -1;
}
.formGroup > .stacked,
.formGroup > .toggleRow {
grid-template-columns: minmax(0, 1fr);
+65 -57
Переглянути файл
@@ -10,7 +10,7 @@ import { useCallback, useEffect, useId, useMemo, useState } from "react";
import { call, commands, type FlutterVersion, type Sdk } from "@/platform/ipc";
import { IconButton, Input, type SelectOption, T } from "@/ui";
import { JAVA_LANGUAGE_LEVELS, PHP_LANGUAGE_LEVELS } from "@/platform/languageSettings";
import { GlobListEditor, Row, Section, Select, Toggle } from "../components/Form";
import { FormGroup, GlobListEditor, Row, Section, Select, Toggle, type RowProps } from "../components/Form";
import { choosePath } from "@/platform/choosePath";
import { usePageContext, useSetting } from "../components/context";
import { SdkField, tildify, useDetected, useJdtlsJdk } from "./components";
@@ -19,6 +19,14 @@ import { mavenHomeProblem } from "./mavenHome";
import { PathField, PathInput } from "./PathInput";
import styles from "./Sdk.module.css";
function FieldRow({ children, ...row }: RowProps) {
return (
<Row {...row}>
<span className={styles.alignedField}>{children}</span>
</Row>
);
}
function SdkRow({
k,
label,
@@ -47,9 +55,9 @@ function RunTargetRow({ language }: { language: "php" | "node" }) {
if (target && target !== "local" && !targets.some((t) => t.id === target))
options.push({ value: target, label: tx`Run in target ${target}` });
return (
<Row label="Run in target">
<FieldRow label="Run in target">
<Select value={target ?? ""} options={options} onChange={setTarget} aria-label="Run in target" />
</Row>
</FieldRow>
);
}
@@ -80,19 +88,19 @@ export function NodePage() {
[list],
);
return (
<div className={styles.page}>
<Section>
<Row
<FormGroup className={styles.toolchainSettings}>
<Section stackFields>
<FieldRow
label="Preferred runtime"
hint="Runs JavaScript and TypeScript files from the gutter and the editor's Run action."
>
<Select value={runtime} options={RUNTIME_OPTIONS} onChange={setRuntime} aria-label="Preferred runtime" />
</Row>
<Row label="Package manager" hint="Used by the npm run configurations detected from package.json scripts.">
</FieldRow>
<FieldRow label="Package manager" hint="Used by the npm run configurations detected from package.json scripts.">
<Select value={pm} options={pmOptions} onChange={setPm} aria-label="Package manager" />
</Row>
</FieldRow>
</Section>
<Section title="Node.js">
<Section title="Node.js" stackFields>
<SdkRow
k="languages.node.interpreter"
label="Node interpreter"
@@ -105,7 +113,7 @@ export function NodePage() {
/>
<RunTargetRow language="node" />
</Section>
</div>
</FormGroup>
);
}
@@ -162,14 +170,14 @@ export function PhpPage() {
const selected = list.find((s) => s.path === (interpreter || pathPhp));
const xdebug = useXdebug(selected);
return (
<div className={styles.page}>
<Section>
<Row
<FormGroup className={styles.toolchainSettings}>
<Section stackFields>
<FieldRow
label="PHP language level"
hint="The PHP version Intelephense checks the code against: newer syntax and functions are reported. Auto uses config.platform.php from composer.json, else the lowest version require.php allows."
>
<Select value={level} options={PHP_LEVEL_OPTIONS} onChange={setLevel} aria-label="PHP language level" />
</Row>
</FieldRow>
<Row
label="Include paths"
stacked
@@ -200,7 +208,7 @@ export function PhpPage() {
/>
</Row>
</Section>
<Section title="PHPStan">
<Section title="PHPStan" stackFields>
<PathInput
k="languages.php.phpstanConfig"
label="Configuration file"
@@ -210,7 +218,7 @@ export function PhpPage() {
file
/>
</Section>
<Section title="CLI Interpreter">
<Section title="CLI Interpreter" stackFields>
<RunTargetRow language="php" />
<SdkRow
k="languages.php.interpreter"
@@ -225,7 +233,7 @@ export function PhpPage() {
{selected?.version && <Row label="Version">{selected.version}</Row>}
{xdebug !== undefined && <Row label="Xdebug">{xdebug ?? <T>Not installed</T>}</Row>}
</Section>
</div>
</FormGroup>
);
}
@@ -263,8 +271,8 @@ export function RustPage() {
const selected = list.find((s) => s.path === toolchain);
const argsId = useId();
return (
<div className={styles.page}>
<Section title="Toolchain">
<FormGroup className={styles.toolchainSettings}>
<Section title="Toolchain" stackFields>
<SdkRow
k="languages.rust.toolchain"
label="Toolchain location"
@@ -284,8 +292,8 @@ export function RustPage() {
hint="Sources of std for navigation and completion (RUST_SRC_PATH)."
/>
</Section>
<Section title="External Linters">
<Row label="External tool">
<Section title="External Linters" stackFields>
<FieldRow label="External tool">
<Select
value={checkCommand}
options={[
@@ -295,7 +303,7 @@ export function RustPage() {
onChange={setCheckCommand}
aria-label="External tool"
/>
</Row>
</FieldRow>
<Toggle
label="Run external linter on save"
checked={checkOnSave}
@@ -303,8 +311,8 @@ export function RustPage() {
hint="rust-analyzer runs the tool after each save and reports its diagnostics."
/>
</Section>
<Section title="Rustfmt">
<Row
<Section title="Rustfmt" stackFields>
<FieldRow
label="Additional arguments"
htmlFor={argsId}
hint="Passed to rustfmt when reformatting, e.g. --edition 2024"
@@ -316,9 +324,9 @@ export function RustPage() {
value={rustfmtArgs}
onChange={(e) => setRustfmtArgs(e.target.value)}
/>
</Row>
</FieldRow>
</Section>
</div>
</FormGroup>
);
}
@@ -330,8 +338,8 @@ export function GoPage() {
const { list } = useDetected("go");
const defaultGopath = list.find((s) => s.extra)?.extra;
return (
<div className={styles.page}>
<Section title="GOROOT">
<FormGroup className={styles.toolchainSettings}>
<Section title="GOROOT" stackFields>
<SdkRow
k="languages.go.goroot"
label="GOROOT"
@@ -344,7 +352,7 @@ export function GoPage() {
hint="Go SDK used by gopls and the go run / test configurations."
/>
</Section>
<Section title="GOPATH">
<Section title="GOPATH" stackFields>
<PathInput
k="languages.go.gopath"
label="Project GOPATH"
@@ -352,7 +360,7 @@ export function GoPage() {
title="Select GOPATH"
/>
</Section>
<Section title="Formatting">
<Section title="Formatting" stackFields>
<Toggle
label="Format with gofumpt"
checked={gofumpt}
@@ -360,7 +368,7 @@ export function GoPage() {
hint="gopls applies gofumpt's stricter rules on top of gofmt when reformatting."
/>
</Section>
</div>
</FormGroup>
);
}
@@ -385,8 +393,8 @@ export function JavaPage() {
);
const id = useId();
return (
<div className={styles.page}>
<Section title="Project JDK">
<FormGroup className={styles.toolchainSettings}>
<Section title="Project JDK" stackFields>
<SdkRow
k="languages.java.jdk"
label="SDK"
@@ -398,7 +406,7 @@ export function JavaPage() {
aria-label="Project JDK"
hint="Compiles and runs the project: Run/Debug and JAVA_HOME for Maven and Gradle; it also runs jdtls when new enough for it."
/>
<Row
<FieldRow
label="Language level"
hint="Java source and bytecode compliance level when no build descriptor overrides it."
>
@@ -408,9 +416,9 @@ export function JavaPage() {
onChange={setLanguageLevel}
aria-label="Java language level"
/>
</Row>
</FieldRow>
</Section>
<Section title="Language Server">
<Section title="Language Server" stackFields>
<Toggle
label="Share JDT LS across builds"
checked={shared}
@@ -434,7 +442,7 @@ export function JavaPage() {
hint={jdtls.hint}
minJava={jdtls.minJava}
/>
<Row
<FieldRow
label="JVM options"
htmlFor={id}
hint="Passed to the JVM running jdtls (java.jdt.ls.vmargs), e.g. -Xmx4g. jdtls runs with -XX:+UseG1GC -XX:G1PeriodicGCInterval=60000 -XX:MinHeapFreeRatio=10 -XX:MaxHeapFreeRatio=30 -Xmx2G -Xms100m by default; an option set here replaces the default for the same setting, and another collector (e.g. -XX:+UseZGC) replaces the default collector options. A Lombok agent is added automatically: the one installed in Language Servers, else, when the project uses Lombok (its build, an inherited parent POM or Gradle build, or its sources' imports), the newest from the Maven / Gradle caches."
@@ -447,9 +455,9 @@ export function JavaPage() {
placeholder="-Xmx4g"
onChange={(e) => setVmArgs(e.target.value)}
/>
</Row>
</FieldRow>
</Section>
</div>
</FormGroup>
);
}
@@ -461,8 +469,8 @@ export function GradlePage() {
const [runUsing, setRunUsing] = useSetting<string>("languages.java.gradle.runUsing");
const local = distribution === "local";
return (
<div className={styles.gradleSettings}>
<Section>
<FormGroup className={styles.toolchainSettings}>
<Section stackFields>
<PathInput
k="languages.java.gradle.userHome"
label="Gradle user home"
@@ -471,8 +479,8 @@ export function GradlePage() {
hint="Sets GRADLE_USER_HOME. Empty uses Gradle's default."
/>
</Section>
<Section title="Build and Run">
<Row
<Section title="Build and Run" stackFields>
<FieldRow
label="Build and run using"
hint="Gradle runs a main class as a JavaExec task on its source set's runtime classpath (Gradle's resource processing included). OpenIDEA launches it on the Java language server's classpath."
>
@@ -485,9 +493,9 @@ export function GradlePage() {
{ value: "ide", label: "OpenIDEA" },
]}
/>
</Row>
</FieldRow>
</Section>
<Section title="Gradle runtime">
<Section title="Gradle runtime" stackFields>
<Row
label="Distribution"
hint={
@@ -496,7 +504,7 @@ export function GradlePage() {
: "Uses the Gradle wrapper when present, otherwise the project-pinned mise/asdf Gradle, then Gradle on PATH."
}
>
<div className={styles.gradleDistribution}>
<div className={local ? styles.localDistribution : styles.alignedField}>
<Select
value={distribution}
onChange={setDistribution}
@@ -527,7 +535,7 @@ export function GradlePage() {
hint="JDK used for Gradle sync, tasks, run configurations and tests. An explicit JAVA_HOME in a run configuration takes precedence."
/>
</Section>
</div>
</FormGroup>
);
}
@@ -544,8 +552,8 @@ export function MavenPage() {
const [activeProfiles, setActiveProfiles] = useSetting<string>("languages.java.maven.activeProfiles");
const id = useId();
return (
<div className={styles.mavenSettings}>
<Section>
<FormGroup className={styles.toolchainSettings}>
<Section stackFields>
<Toggle
label="Always update snapshots"
checked={updateSnapshots}
@@ -617,7 +625,7 @@ export function MavenPage() {
hint="Passed as -t; selects the JDKs Maven compiles with."
/>
</Section>
<Section title="Importing">
<Section title="Importing" stackFields>
<Toggle
label="Automatically download sources"
checked={downloadSources}
@@ -632,7 +640,7 @@ export function MavenPage() {
onChange={setDelegateBuild}
hint="Run and Debug build Maven modules with Maven (the project's javac) instead of the Java language server. Editor problems still come from the language server."
/>
<Row
<FieldRow
label="Run tests using"
hint="OpenIDEA runs a JUnit 4 or JUnit 5 test from the gutter on the Java language server's test classpath, without starting Maven, with the POM's Surefire configuration (argLine, system properties, environment variables, working directory). Maven runs it through Surefire, with filtered test resources."
>
@@ -645,7 +653,7 @@ export function MavenPage() {
{ value: "maven", label: "Maven" },
]}
/>
</Row>
</FieldRow>
<SdkRow
k="languages.java.maven.runnerJre"
label="JRE"
@@ -656,7 +664,7 @@ export function MavenPage() {
aria-label="JRE"
hint="JDK used for Maven sync, builds, goals and tests. An explicit JAVA_HOME in a run configuration takes precedence."
/>
<Row
<FieldRow
label="Active profiles"
htmlFor={`${id}-profiles`}
hint="Comma-separated profiles (-P), combined with Maven tool window choices; !id excludes a profile. A run configuration’s own -P replaces these profiles."
@@ -670,9 +678,9 @@ export function MavenPage() {
onChange={(e) => setActiveProfiles(e.target.value)}
aria-label="Active profiles"
/>
</Row>
</FieldRow>
</Section>
<Section>
<Section stackFields>
<Toggle
label="Use Maven Daemon (mvnd)"
checked={daemon}
@@ -687,7 +695,7 @@ export function MavenPage() {
hint="The mvnd home (or its executable). Empty = $MVND_HOME, else mvnd on PATH."
/>
</Section>
</div>
</FormGroup>
);
}
+15 -12
Переглянути файл
@@ -68,7 +68,7 @@ import {
type ProjectStructureValid,
} from "@/platform/languageSettings";
import { initProjectRoots, useDetectedRoots } from "@/platform/projectRoots";
import { Row, SearchLabel, Section } from "../components/Form";
import { FormGroup, Row, SearchLabel, Section } from "../components/Form";
import { detectSdks, forgetSdk, rememberSdk, useSdks, type SdkKind } from "./api";
import { choosePath } from "@/platform/choosePath";
import { DownloadJdkDialog } from "./DownloadJdkDialog";
@@ -340,8 +340,8 @@ function ProjectSection() {
const outId = useId();
return (
<div className={styles.page}>
<Section title="Project">
<FormGroup className={styles.projectSettings}>
<Section title="Project" stackFields>
<Row label="Project name" hint={root ?? "No project is currently open."}>
<span className={styles.path}>{name || "Default Project"}</span>
</Row>
@@ -364,19 +364,21 @@ function ProjectSection() {
label="Language level"
hint="Default Java language level for source code assistance and compilation across project modules."
>
<Select
value={languageLevel ?? ""}
options={PROJECT_JAVA_LEVEL_OPTIONS}
onChange={setLanguageLevel}
aria-label="Project language level"
/>
<span className={styles.alignedField}>
<Select
value={languageLevel ?? ""}
options={PROJECT_JAVA_LEVEL_OPTIONS}
onChange={setLanguageLevel}
aria-label="Project language level"
/>
</span>
</Row>
<Row
label="Compiler output"
htmlFor={outId}
hint="Default directory where compiled classes are placed when not managed by Maven or Gradle."
>
<span className={styles.pathRow}>
<span className={styles.alignedField}>
<Input
id={outId}
mono
@@ -386,6 +388,7 @@ function ProjectSection() {
onChange={(e) => setCompilerOutput(e.target.value)}
/>
<IconButton
className={styles.alignedBrowse}
icon="folder-open"
size="small"
title="Browse…"
@@ -401,7 +404,7 @@ function ProjectSection() {
</span>
</Row>
</Section>
<Section title="Language Server">
<Section title="Language Server" stackFields>
<Row label="JDK" hint={jdtls.hint}>
<SdkField
kind="jdk"
@@ -416,7 +419,7 @@ function ProjectSection() {
/>
</Row>
</Section>
</div>
</FormGroup>
);
}
+45 -23
Переглянути файл
@@ -17,6 +17,38 @@
flex: 1;
min-width: 0;
}
.projectSettings {
container: settings-content / inline-size;
row-gap: var(--space-2);
overflow-wrap: anywhere;
}
.toolchainSettings {
overflow-wrap: anywhere;
}
.projectSettings .sdkField,
.toolchainSettings .sdkField,
.toolchainSettings .pathRow,
.localDistribution,
.alignedField {
display: grid;
/* Reserve the refresh and browse columns even on rows with fewer actions. */
grid-template-columns: minmax(0, 1fr) repeat(2, 20px);
align-items: center;
gap: var(--space-1);
width: 100%;
max-width: 560px;
min-width: 0;
}
.alignedField > :first-child,
.localDistribution > :first-child {
max-width: none;
width: 100%;
min-width: 0;
}
.alignedBrowse,
.toolchainSettings .pathRow > button {
grid-column: 3;
}
/* Editable ComboBox (Maven home): a text field with the combo's arrow inside its frame. */
.sdkEditable {
display: inline-flex;
@@ -59,10 +91,8 @@
font-size: var(--fs-small);
}
.mavenSettings .sdkField,
.mavenSettings .sdkEditable {
.toolchainSettings .sdkEditable {
min-width: 0;
max-width: none;
}
.mavenThreads {
@@ -328,28 +358,20 @@
min-width: 0;
}
.gradleSettings .pathRow {
max-width: 560px;
.localDistribution {
grid-template-columns: minmax(0, 180px) minmax(0, 1fr) repeat(2, 20px);
}
.gradleSettings .sdkField {
min-width: 0;
.localDistribution > .pathRow {
grid-column: 2 / -1;
grid-template-columns: subgrid;
}
.gradleDistribution {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
width: 560px;
}
.gradleDistribution > :first-child {
flex: 0 1 180px;
}
.gradleDistribution > .pathRow {
flex: 1 1 230px;
@container settings-content (max-width: 600px) {
.localDistribution {
grid-template-columns: minmax(0, 1fr) repeat(2, 20px);
}
.localDistribution > .pathRow {
grid-column: 1 / -1;
}
}
/* Project Structure */
+34
Переглянути файл
@@ -52,3 +52,37 @@
grid-column: 1;
}
}
/* Share the input, browse and Test columns across both Subversion paths. */
section > :has(> .svnPath) {
grid-template-columns: fit-content(45%) minmax(0, 1fr) 20px max-content;
}
.svnPath > div {
grid-column: 2 / -1;
}
.svnPath > div:first-of-type {
display: grid;
grid-template-columns: subgrid;
}
.svnPath input {
width: 100%;
min-width: 0;
}
.svnConfig > label {
padding-inline-start: var(--space-4);
}
@container settings-content (max-width: 440px) {
section > :has(> .svnPath) {
grid-template-columns: minmax(0, 1fr) 20px max-content;
}
.svnPath > label,
.svnPath > div {
grid-column: 1 / -1;
}
}
+5
Переглянути файл
@@ -4,6 +4,11 @@
max-width: 760px;
}
.alignedFields button[aria-haspopup="listbox"] {
width: min(320px, 100%);
min-width: 0;
}
.check {
display: flex;
align-items: center;
+1
Переглянути файл
@@ -630,6 +630,7 @@ const ENCODINGS: SelectOption[] = ENCODING_CHOICES.map(([value, label]) => ({ va
const ENCODINGS_PAGE = editorPage({
id: "editor.fileEncodings",
alignFields: true,
title: "File Encodings",
order: 27,
projectScope: true,
+11 -13
Переглянути файл
@@ -10,7 +10,7 @@ import clsx from "clsx";
import { Checkbox, Input, T, type SelectOption } from "@/ui";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { NumberInput, Row, SearchLabel, Section, Select } from "../../components/Form";
import { FormGroup, NumberInput, Row, SearchLabel, Section, Select } from "../../components/Form";
import { useLabelMatch, usePageContext, useSetting } from "../../components/context";
import type { PageSpec } from "../spec";
import styles from "./Editor.module.css";
@@ -67,6 +67,7 @@ export interface EditorPageDef {
keywords?: string[];
projectScope?: boolean;
sections: EditorSection[];
alignFields?: boolean;
/** Rendered below the sections (previews, tables). */
footer?: ComponentType;
}
@@ -324,18 +325,15 @@ export function ItemView({ item }: { item: Item }) {
}
}
export function EditorSections({ sections }: { sections: EditorSection[] }) {
return (
<>
{sections.map((s, i) => (
<Section key={s.title ?? i} title={s.title}>
{s.items.map((item, j) => (
<ItemView key={itemKey(item, j)} item={item} />
))}
</Section>
export function EditorSections({ sections, alignFields }: Pick<EditorPageDef, "sections" | "alignFields">) {
const body = sections.map((s, i) => (
<Section key={s.title ?? i} title={s.title} stackFields={alignFields}>
{s.items.map((item, j) => (
<ItemView key={itemKey(item, j)} item={item} />
))}
</>
);
</Section>
));
return alignFields ? <FormGroup className={styles.alignedFields}>{body}</FormGroup> : <>{body}</>;
}
/** Search texts of an item tree (labels, option labels, custom keywords). */
@@ -365,7 +363,7 @@ export function editorPage(def: EditorPageDef): PageSpec {
const Footer = def.footer;
const Page = () => (
<div className={styles.page}>
<EditorSections sections={def.sections} />
<EditorSections sections={def.sections} alignFields={def.alignFields} />
{Footer && <Footer />}
</div>
);
+58 -65
Переглянути файл
@@ -385,47 +385,44 @@ function SvnExecutableRow() {
}
};
return (
<div className={gitStyles.executable}>
<Row
label="Path to Subversion executable"
htmlFor={id}
hint={
result ? (
<span className={clsx(gitStyles.testResult, result.ok ? styles.ok : styles.error)} role="status">
{result.text}
</span>
) : undefined
}
>
<div className={gitStyles.executableControls}>
<Input
id={id}
mono
value={path}
placeholder={detected ? tx`Auto-detected: ${detected}` : "Auto-detected"}
onChange={(e) => {
setPath(e.target.value);
setResult(null);
}}
/>
<IconButton
icon="folder-open"
size="small"
title="Browse…"
onClick={async () => {
const chosen = await choosePath({ directory: false, defaultPath: path || detected || undefined });
if (chosen) {
setPath(chosen);
setResult(null);
}
}}
/>
<Button disabled={testing || !isTauri()} onClick={() => void test()}>
<T>Test</T>
</Button>
</div>
</Row>
</div>
<Row
className={gitStyles.svnPath}
label="Path to Subversion executable"
htmlFor={id}
hint={
result ? (
<span className={clsx(gitStyles.testResult, result.ok ? styles.ok : styles.error)} role="status">
{result.text}
</span>
) : undefined
}
>
<Input
id={id}
mono
value={path}
placeholder={detected ? tx`Auto-detected: ${detected}` : "Auto-detected"}
onChange={(e) => {
setPath(e.target.value);
setResult(null);
}}
/>
<IconButton
icon="folder-open"
size="small"
title="Browse…"
onClick={async () => {
const chosen = await choosePath({ directory: false, defaultPath: path || detected || undefined });
if (chosen) {
setPath(chosen);
setResult(null);
}
}}
/>
<Button disabled={testing || !isTauri()} onClick={() => void test()}>
<T>Test</T>
</Button>
</Row>
);
}
@@ -436,30 +433,26 @@ function SvnConfigDirRow() {
return (
<>
<BoundToggle k="vcs.svn.useCustomConfigDir" label="Use custom configuration directory" />
<Indented>
<Row label="Configuration directory" htmlFor={id}>
<div className={gitStyles.executableControls}>
<Input
id={id}
mono
disabled={!custom}
value={dir}
placeholder="~/.subversion"
onChange={(e) => setDir(e.target.value)}
/>
<IconButton
icon="folder-open"
size="small"
title="Browse…"
disabled={!custom}
onClick={async () => {
const chosen = await choosePath({ directory: true, defaultPath: dir || undefined });
if (chosen) setDir(chosen);
}}
/>
</div>
</Row>
</Indented>
<Row label="Configuration directory" htmlFor={id} className={clsx(gitStyles.svnPath, gitStyles.svnConfig)}>
<Input
id={id}
mono
disabled={!custom}
value={dir}
placeholder="~/.subversion"
onChange={(e) => setDir(e.target.value)}
/>
<IconButton
icon="folder-open"
size="small"
title="Browse…"
disabled={!custom}
onClick={async () => {
const chosen = await choosePath({ directory: true, defaultPath: dir || undefined });
if (chosen) setDir(chosen);
}}
/>
</Row>
</>
);
}
-1
Переглянути файл
@@ -233,7 +233,6 @@ function WorktreeForm({
level: "warning",
title: tx("Some worktree configuration could not be copied"),
body: result.copyWarning,
userInitiated: true,
});
}
if (result.setupWarning) {
+26 -19
Переглянути файл
@@ -1,7 +1,4 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createElement } from "react";
import { fireEvent, render, screen, within } from "@testing-library/react";
import { MessagesHost } from "@/workbench/messages";
import type { Branch, BranchInfo, ProjectInfo, Worktree } from "@/bindings";
const mocks = vi.hoisted(() => ({
prompt: vi.fn(),
@@ -315,7 +312,6 @@ it("shows a partial failure without claiming that the rename failed", async () =
expect(mocks.notify).toHaveBeenCalledExactlyOnceWith({
group: "vcs",
level: "error",
userInitiated: true,
title: "Rename branch topic",
body: message,
});
@@ -415,9 +411,7 @@ it("checks every affected repository before moving any HEAD", async () => {
await checkoutRevision({ repos });
expect(mocks.hasCommit.mock.calls).toEqual(repos.map((root) => [root, "release"]));
expect(mocks.checkout).not.toHaveBeenCalled();
expect(mocks.notify).toHaveBeenCalledWith(
expect.objectContaining({ userInitiated: true, body: "Revision was not found in nested" }),
);
expect(mocks.notify).toHaveBeenCalledWith(expect.objectContaining({ body: "Revision was not found in nested" }));
mocks.hasCommit.mockResolvedValue(ok(true));
mocks.checkout.mockResolvedValue(ok({ kind: "done" }));
@@ -484,19 +478,32 @@ it("does not open the worktree when the checkout offer is declined", async () =>
expect(mocks.executeAction).not.toHaveBeenCalled();
});
it.each([
[true, "removed"],
[false, "overwritten"],
])("shows the files that checkout would affect in an error dialog (%s)", async (removed, verb) => {
mocks.checkout.mockResolvedValue(ok({ kind: "untrackedFiles", files: ["TEST.md", "dir/new.txt"], removed }));
render(createElement(MessagesHost));
const checkout = checkoutBranch(local("feature/x"));
const dialog = await screen.findByRole("dialog", { name: "Untracked files prevent checkout" });
expect(dialog).toHaveTextContent(`The following untracked working tree files would be ${verb} by checkout:`);
expect(dialog).toHaveTextContent("TEST.md dir/new.txt");
fireEvent.click(within(dialog).getByRole("button", { name: "OK" }));
await checkout;
it("names the files git would remove when untracked ones block the checkout", async () => {
mocks.checkout.mockResolvedValue(ok({ kind: "untrackedFiles", files: ["TEST.md"], removed: true }));
await checkoutBranch(local("feature/x"));
expect(mocks.checkout).toHaveBeenCalledTimes(1);
expect(mocks.notify).toHaveBeenCalledWith(
expect.objectContaining({
level: "error",
title: "Untracked files prevent checkout",
body: expect.stringContaining(
"The following untracked working tree files would be removed by checkout:\nTEST.md",
),
}),
);
});
it("still says overwritten when untracked files would be overwritten", async () => {
mocks.checkout.mockResolvedValue(ok({ kind: "untrackedFiles", files: ["dir/new.txt"], removed: false }));
await checkoutBranch(local("feature/x"));
expect(mocks.notify).toHaveBeenCalledWith(
expect.objectContaining({
level: "error",
body: expect.stringContaining(
"The following untracked working tree files would be overwritten by checkout:\ndir/new.txt",
),
}),
);
});
it("keeps the branch when the worktree question is turned down", async () => {
-11
Переглянути файл
@@ -269,17 +269,6 @@ describe("Checkout and Update", () => {
]);
});
it("reports a failed HEAD read before the update", async () => {
mocks.checkout.mockResolvedValue({ status: "ok", data: { kind: "done" } });
mocks.head.mockResolvedValue({ status: "error", error: { kind: "io", message: "Cannot read HEAD" } });
await checkoutAndUpdate(branch("topic"));
expect(mocks.notify).toHaveBeenCalledWith(
expect.objectContaining({ level: "error", userInitiated: true, body: "Cannot read HEAD" }),
);
expect(mocks.updateCurrent).not.toHaveBeenCalled();
expect(mocks.update).not.toHaveBeenCalled();
});
it("updates nothing when the checkout did not happen", async () => {
mocks.checkout.mockResolvedValue({ status: "error", error: { kind: "failed", message: "nope" } });
await checkoutAndUpdate(branch("topic"));
+9 -21
Переглянути файл
@@ -19,7 +19,7 @@ import { notifications } from "@/workbench/contributions";
import { openWorktree } from "./openWorktree";
import { githubHttpsFailureHelp } from "./githubHttpsFailure";
import { activeRepository } from "./activeRepository";
import { ask, confirmChecked, showError } from "@/workbench/messages";
import { ask, confirmChecked } from "@/workbench/messages";
import { branchNamePrefixes, isFavoriteBranch, isProtectedBranch, pushRecent, shortRemoteName } from "./branches";
import { showCommitRanges } from "./CompareBranches";
import type { AffectedFiles } from "./LocalChangesReviewDialog";
@@ -27,7 +27,6 @@ import { confirmDialog, promptText } from "./dialogs";
import { cleanUpBranchNameOnTyping } from "@/platform/gitRefName";
import {
errorMessage,
logConsole,
runBranchUpdates,
runGitOperation,
runOp,
@@ -207,7 +206,6 @@ async function reviewCheckout<T>(
const shelved = workflowSettings().vcs.git.saveChangesPolicy === "shelve";
notifications().notify({
group: "vcs",
userInitiated: true,
level: "warning",
title: tx("Could not restore local changes after checkout"),
body: outcome.message,
@@ -223,7 +221,6 @@ async function reviewCheckout<T>(
const shelved = opts.mode === "smart" && workflowSettings().vcs.git.saveChangesPolicy === "shelve";
notifications().notify({
group: "vcs",
userInitiated: true,
level: "warning",
title: `${success()}, with conflicts`,
body: outcome.files.join("\n"),
@@ -244,9 +241,12 @@ async function reviewCheckout<T>(
const body = outcome.removed
? tx`The following untracked working tree files would be removed by checkout:\n${files}\nPlease move or remove them before you switch branches.`
: tx`The following untracked working tree files would be overwritten by checkout:\n${files}\nPlease move or remove them before you switch branches.`;
logConsole("err", body);
// oxlint-disable-next-line no-await-in-loop -- acknowledge the blocked checkout before a possible multi-root rollback
await showError(tx("Untracked files prevent checkout"), body);
notifications().notify({
group: "vcs",
level: "error",
title: "Untracked files prevent checkout",
body,
});
return undefined;
}
case "localChanges": {
@@ -604,7 +604,6 @@ export async function checkoutRevision(scope?: CheckoutRevisionScope) {
notifications().notify({
group: "vcs",
level: "error",
userInitiated: true,
title: tx`Could not check out ${label}`,
body: names ? tx`Revision was not found in ${names}` : tx("Revision was not found"),
});
@@ -785,13 +784,7 @@ export async function renameBranch(branch: Branch) {
success: tx`Renamed branch ${name} to ${to}`,
onError: (message) => {
// Unsetting the upstream can fail after the rename has succeeded.
notifications().notify({
group: "vcs",
userInitiated: true,
level: "error",
title: tx`Rename branch ${name}`,
body: message,
});
notifications().notify({ group: "vcs", level: "error", title: tx`Rename branch ${name}`, body: message });
return true;
},
},
@@ -1427,12 +1420,7 @@ export async function checkoutAndUpdate(branch: NamedBranch, roots?: readonly st
if (useProject.getState().project !== project) return;
const repos: readonly (string | null)[] = roots ?? [currentRepo()];
const heads = await Promise.all(
repos.map(async (repo) => {
const head = await runOp(tx("Read repository HEAD"), () => call(commands.vcsBranchInfo(repo)), {
refresh: false,
});
return [repo, head] as const;
}),
repos.map(async (repo) => [repo, await call(commands.vcsBranchInfo(repo)).catch(() => null)] as const),
);
if (useProject.getState().project !== project) return;
const targets = heads
+2 -1
Переглянути файл
@@ -139,7 +139,8 @@ export async function saveAll() {
try {
await saveDiffWindows();
} catch (error) {
notify({
notifications().notify({
group: "vcs",
level: "error",
title: tx("Could not save diff"),
body: errorMessage(error),