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

..
6 Коміти
Автор SHA1 Повідомлення Дата
l0ng-ai f53f7c0208 feat(refactor): Java Move for classes, static members, nested types and instance methods
Move… (F6, Refactor This) in Java now asks for the destination and moves:
a top-level class to another package (package declaration, imports and
references follow), a static member or nested type to another class (or a
nested type to a new file), an instance method to the class of one of its
fields or parameters. jdtls offers these only as client-side commands
(java.action.applyRefactoringCommand), now enabled with
moveRefactoringSupport; the IDE picks the destination from
java/getMoveDestinations or java/searchSymbols, then java/move checks the move
and computes the edit, confirmed in Problems Detected when it warns.

Code actions can register client-side command handlers
(registerClientCommand); jdtls' changeSignature command opens the Change
Signature dialog. New IPC: lsp_java_move_destinations, lsp_java_source_types,
lsp_java_move. SignatureChanged is now ServerRefactored.
2026-11-16 15:34:57 +08:00
l0ng-ai 3cc4c1c9b1 feat(refactor): Change Signature dialog for Java methods (#3701)
Change Signature… (⌘F6, also in Refactor This) on a Java method opens a
dialog for its visibility, return type, name and parameters (add with a
default value for existing calls, remove, reorder), with Delegate via
overloading method and a signature preview. jdtls reads the method
(java/getChangeSignatureInfo) and checks the new signature and computes the
edit for the method, its overrides and its calls (java/getRefactorEdit
changeSignature); warnings are confirmed in Problems Detected before the edit,
and Preview lists the changes first. jdtls offers the refactoring only through
a client-side command, so Java had no Change Signature before.

New IPC: lsp_signature_info, lsp_change_signature.
2026-11-16 15:18:43 +08:00
l0ng-ai 9c07e3e136 feat(rails): go to declaration from callback symbols and routes (#3700)
Go to Declaration (and ⌘-click) on a method symbol in a callback
(before_action :load_user, skip_before_action, helper_method, validate,
if: :admin?) opens its def in the class, or in ApplicationController /
ApplicationRecord. In config/routes.rb, "controller#action" strings open the
action's def and resources / resource symbols open the controller.

Refs #900
2026-11-16 15:01:26 +08:00
l0ng-ai 844611c7d5 feat(navigation): Navigate › Related Symbol for header/source and Rails files (#3699)
Related Symbol… (⌃⌘↑ / Ctrl+Alt+Home, in the Navigate menu and the editor's
Go To submenu) goes to the files tied to the current one by convention: one
target opens directly, several open a Choose Target list, none shows
"No related symbols". Providers register through editor/relatedProviders.

- C, C++, Objective-C and CUDA: a header and its source files of the same
  name, the ones in the same folder first.
- Rails: a controller action and its views, a controller and all its views,
  helper and model, a view and its controller action, a helper and its
  controller and views, a model and its controller and migrations.

Refs #900
2026-11-16 14:58:13 +08:00
l0ng-ai c9c75fa3b7 feat(django): Django Template LSP for template tags, filters, templates and URL names (#3696)
Django Template files start djlsp (django-template-lsp, installed into its own
virtualenv on request) next to the HTML language server: completion, hover and
Go to Declaration for the project's template tags, filters, template names,
static files and URL names. The project interpreter's environment is passed as
its env_directories, so a virtualenv, conda or pixi environment outside the
project root is used too.

Refs #2581
2026-11-16 14:44:46 +08:00
Deng Liuтаdengliu 32abc77a74 feat(agents): multi-level MCP hub, CLI config discovery, and per-session MCP picker (#3626)
MCP servers can be configured at user and project level, imported from pasted JSON, tested with their tool list shown, and discovered from other agent CLIs' config files. Discovery reports only env and header key names, never values, and importing is explicit; external config files are never modified. Testing a server requires a trusted project. Each agent session can turn individual servers on or off from a picker; the overrides are stored with the task and applied when the session opens.

Closes #3608

Co-authored-by: dengliu <[email protected]>
2026-11-16 14:32:11 +08:00
67 змінених файлів з 7309 додано та 407 видалено

No files matched your search

+1
Переглянути файл
@@ -155,6 +155,7 @@ async fn a_task_runs_on_a_v2_agent_and_resumes_its_session() {
config: vec![AgentConfigChoice { id: "model".into(), value: "haiku".into() }],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
+90 -11
Переглянути файл
@@ -208,10 +208,19 @@ impl Shared {
}
}
fn mcp_servers_for_session(&self, provider: &str, init: &acp::Negotiated) -> Vec<Value> {
let mut servers = mcp_servers_for(init.mcp_stdio(), &self.paths.project_root);
fn mcp_servers_for_session(
&self,
provider: &str,
init: &acp::Negotiated,
overrides: &BTreeMap<String, bool>,
) -> Vec<Value> {
let mut servers = if overrides.get(mcp::BUILTIN_MCP_NAME) == Some(&false) {
Vec::new()
} else {
mcp_servers_for(init.mcp_stdio(), &self.paths.project_root)
};
let configured = self.mcp_servers_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
servers.extend(mcp::acp_mcp_servers(&configured, provider, init));
servers.extend(mcp::acp_mcp_servers(&configured, provider, init, overrides));
servers
}
@@ -409,6 +418,8 @@ struct Task {
/// Bumped when the agent's last background task finishes: an idle release scheduled
/// before that is void, the usual delay starts over from the report.
idle_epoch: AtomicU64,
/// Turned on when per-session MCP overrides changed while a turn was busy; dropped once idle.
mcp_reload_pending: AtomicBool,
/// Settings already sent this session (`(option, value)`), so a refusal is not retried.
config_sent: Mutex<HashSet<(String, String)>>,
dirty: Mutex<BTreeSet<(Session, usize)>>,
@@ -724,6 +735,7 @@ impl AgentManager {
resets_ms: None,
retry: None,
background: Box::default(),
mcp_overrides: BTreeMap::new(),
};
let handle = self.register(TaskFile {
task: task.clone(),
@@ -815,6 +827,7 @@ impl AgentManager {
resets_ms: None,
retry: None,
background: Box::default(),
mcp_overrides: req.mcp_overrides,
};
let handle = self.register(TaskFile {
task: task.clone(),
@@ -916,6 +929,7 @@ impl AgentManager {
resets_ms: None,
retry: None,
background: Box::default(),
mcp_overrides: req.mcp_overrides,
config,
};
let handle = self.register(TaskFile {
@@ -1117,9 +1131,11 @@ impl AgentManager {
if !live.capabilities.fork || (keep < total && !live.capabilities.rollback) {
return Err(IdeError::invalid("this agent can't copy a conversation from there"));
}
let cwd = source.state.lock().task.cwd.0.clone();
let provider_id = source.state.lock().task.provider.clone();
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init);
let (cwd, provider_id, mcp_overrides) = {
let s = source.state.lock();
(s.task.cwd.0.clone(), s.task.provider.clone(), s.task.mcp_overrides.clone())
};
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
let reply: Value = live
.peer
@@ -1603,6 +1619,43 @@ impl AgentManager {
.await
}
/// Updates per-session MCP server enable/disable overrides (`server_name` -> `enabled`).
/// When the task is idle and holds a resumable live session without running background tasks,
/// stops the idle process so the next turn reloads the session with the updated MCP servers;
/// when busy, schedules the reload for as soon as the turn finishes.
pub fn set_mcp_overrides(&self, id: &str, overrides: BTreeMap<String, bool>) -> IdeResult<AgentTask> {
let task = self.task(id)?;
let cleaned: BTreeMap<String, bool> = overrides
.into_iter()
.filter_map(|(k, v)| {
let k = k.trim();
(!k.is_empty()).then(|| (k.to_owned(), v))
})
.collect();
let (changed, busy, has_bg, out) = {
let mut s = task.state.lock();
if s.task.status == AgentStatus::Archived {
return Err(IdeError::invalid("the task is archived"));
}
let changed = s.task.mcp_overrides != cleaned;
if changed {
s.task.mcp_overrides = cleaned;
s.task.updated_ms = now_ms();
}
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
};
if changed {
task.persist();
task.emit_task();
if busy || has_bg || !task.permissions.lock().is_empty() {
task.mcp_reload_pending.store(true, Ordering::Release);
} else {
task.recycle_resumable_session();
}
}
Ok(out)
}
/// Stops every agent (project closed).
pub fn shutdown(&self) {
for task in self.tasks.read().values() {
@@ -1647,6 +1700,7 @@ impl Task {
turn_started: AtomicBool::new(false),
turns: AtomicU64::new(0),
idle_epoch: AtomicU64::new(0),
mcp_reload_pending: AtomicBool::new(false),
config_sent: Mutex::new(HashSet::new()),
dirty: Mutex::new(BTreeSet::new()),
streamed: Mutex::new(HashMap::new()),
@@ -1704,7 +1758,7 @@ impl Task {
fn emit_task(&self) {
let task = self.state.lock().task.clone();
self.shared.emit(AgentEvent::Task { task });
self.shared.emit(AgentEvent::Task { task: Box::new(task) });
}
/// Shows (or clears) the agent's pending retry; emitted only when it changes.
@@ -1894,6 +1948,12 @@ impl Task {
if stop != "cancelled" {
self.emit_attention(AgentAttentionReason::Finished);
}
if self.mcp_reload_pending.swap(false, Ordering::AcqRel)
&& self.state.lock().background_tasks.is_empty()
{
self.recycle_resumable_session();
return;
}
return self.release_when_idle();
}
(None, Err(failure)) => return self.fail(failure),
@@ -1901,6 +1961,20 @@ impl Task {
}
}
/// Drops an idle resumable live session so the next turn reloads it with fresh MCP servers.
fn recycle_resumable_session(&self) {
self.mcp_reload_pending.store(false, Ordering::Release);
let live = {
let mut live = self.live.lock();
if live.as_ref().is_some_and(|l| l.resumable && !l.peer.is_closed()) { live.take() } else { None }
};
if let Some(live) = live {
tracing::debug!("agent task {}: restarting idle resumable session for MCP override update", self.id);
live.peer.kill();
self.clear_shown_background();
}
}
/// Stops the agent's process once the task has stayed idle for [`IDLE_RELEASE`], so
/// finished tasks don't keep an agent (and what it started) running. Only an agent that
/// reloads its session: the next message starts it again with the conversation intact.
@@ -2231,7 +2305,8 @@ impl Task {
let sign_in_message = spec.sign_in_message(&init.auth_methods);
let can_load = init.load_session();
let (capabilities, embedded) = capabilities_of(&init);
let mcp_servers = self.shared.mcp_servers_for_session(provider_id, &init);
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
let mcp_servers = self.shared.mcp_servers_for_session(provider_id, &init, &mcp_overrides);
// Agents that compare canonical paths fail in a symlinked directory (macOS `/tmp`).
let cwd_s = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()).to_string_lossy().into_owned();
@@ -3047,9 +3122,13 @@ fn embeddable(path: &Path) -> Option<String> {
/// A task file from before a field existed, with that field's empty value.
fn upgrade(mut file: Value) -> Value {
if let Some(task) = file.get_mut("task").and_then(Value::as_object_mut) {
for (key, empty) in
[("config", json!([])), ("commands", json!([])), ("usage", Value::Null), ("queue", json!([]))]
{
for (key, empty) in [
("config", json!([])),
("commands", json!([])),
("usage", Value::Null),
("queue", json!([])),
("mcpOverrides", json!({})),
] {
task.entry(key).or_insert(empty);
}
}
+822 -64
Переглянути файл
@@ -1,13 +1,24 @@
//! Model Context Protocol (MCP) server configurations stored in OpenIDEA's own settings
//! (global `settings.toml` and project `.openidea/settings.toml`), passed to ACP agents in
//! `session/new`, `session/load`, and `session/fork`, plus one-way import from `.mcp.json` /
//! `.vscode/mcp.json`.
//! `session/new`, `session/load`, and `session/fork`, plus discovery and one-way import from
//! external CLI and workspace MCP configuration files.
use crate::acp::Negotiated;
use crate::{AgentMcpServer, McpKeyValue, McpScope, McpServer, McpServerInput, McpTransport};
use crate::{
AgentMcpServer, McpDiscoveredServer, McpExternalSource, McpImportSelection, McpKeyValue, McpProbeResult, McpScope,
McpServer, McpServerInput, McpToolSummary, McpTransport,
};
use ide_core::IpcPath;
use serde_json::{Value, json};
use std::collections::{BTreeMap, HashSet};
use std::path::Path;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
/// Reserved server name for OpenIDEA's built-in IDE MCP server in per-session overrides.
pub const BUILTIN_MCP_NAME: &str = "openidea";
const PROBE_TIMEOUT: Duration = Duration::from_secs(12);
const PROBE_PROTOCOL_VERSION: &str = "2024-11-05";
/// Stable ID for a server in a given scope (`"user::<name>"` or `"workspace::<name>"`).
pub fn server_id(scope: McpScope, name: &str) -> String {
@@ -56,6 +67,7 @@ fn to_mcp_server(scope: McpScope, name: &str, cfg: &AgentMcpServer) -> McpServer
url: cfg.url.clone(),
headers: cfg.headers.iter().map(|(k, v)| McpKeyValue { name: k.clone(), value: v.clone() }).collect(),
agents: cfg.agents.clone(),
unapproved: false,
}
}
@@ -75,8 +87,15 @@ fn matches_agent(agents: &[String], provider: &str) -> bool {
}
/// Builds the ACP `mcpServers` array for `session/new`, `session/load`, and `session/fork`.
/// Workspace entries take precedence over User entries with the same name.
pub(crate) fn acp_mcp_servers(all: &[McpServer], provider: &str, init: &Negotiated) -> Vec<Value> {
/// Workspace entries take precedence over User entries with the same name. Per-session
/// `overrides` (`server_name` -> `enabled`) can enable a disabled server or disable an enabled one
/// for this session only.
pub(crate) fn acp_mcp_servers(
all: &[McpServer],
provider: &str,
init: &Negotiated,
overrides: &BTreeMap<String, bool>,
) -> Vec<Value> {
let supports_stdio = init.mcp_stdio();
let supports_http = init.mcp("http");
let supports_sse = init.mcp("sse");
@@ -87,7 +106,16 @@ pub(crate) fn acp_mcp_servers(all: &[McpServer], provider: &str, init: &Negotiat
all.iter().filter(|s| s.scope == McpScope::Workspace).chain(all.iter().filter(|s| s.scope == McpScope::User));
for srv in ordered {
if !srv.enabled || !matches_agent(&srv.agents, provider) || !seen.insert(srv.name.clone()) {
if srv.unapproved {
continue;
}
let explicit = overrides.get(&srv.name).copied();
let active = explicit.unwrap_or(srv.enabled);
if !active || !seen.insert(srv.name.clone()) {
continue;
}
// An explicit per-session enable (`Some(true)`) overrides the server's default agent filter.
if explicit != Some(true) && !matches_agent(&srv.agents, provider) {
continue;
}
match srv.transport {
@@ -276,6 +304,306 @@ pub fn apply_import(workspace: &mut BTreeMap<String, AgentMcpServer>, workspace_
added
}
/// Parses a raw MCP JSON snippet pasted by the user and merges its servers into `user` or
/// `workspace`. Supports `{"mcpServers": {...}}`, `{"servers": {...}}`, top-level server maps
/// (`{"my-server": {"command": ...}}`), and single-server objects when `fallback_name` is given.
pub fn apply_save_json(
user: &mut BTreeMap<String, AgentMcpServer>,
workspace: &mut BTreeMap<String, AgentMcpServer>,
has_workspace: bool,
scope: McpScope,
raw_json: &str,
fallback_name: Option<&str>,
agents: Vec<String>,
) -> Result<Vec<String>, String> {
if scope == McpScope::Workspace && !has_workspace {
return Err("Open a project to configure workspace MCP servers".into());
}
let parsed = parse_mcp_json_text(raw_json, fallback_name)?;
if parsed.is_empty() {
return Err("No valid MCP servers found in JSON".into());
}
let normalized_agents = normalize_agents_list(agents);
let target = match scope {
McpScope::User => user,
McpScope::Workspace => workspace,
};
let mut saved_names = Vec::with_capacity(parsed.len());
for (name, mut srv) in parsed {
if srv.agents.is_empty() && !normalized_agents.is_empty() {
srv.agents = normalized_agents.clone();
}
saved_names.push(name.clone());
target.insert(name, srv);
}
Ok(saved_names)
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum SourceFormat {
Jsonc,
CodexToml,
}
#[derive(Clone)]
struct SourceSpec {
id: &'static str,
label: &'static str,
path: PathBuf,
format: SourceFormat,
suggested_scope: McpScope,
native_provider: Option<&'static str>,
claude_project_lookup: bool,
}
fn external_source_specs(home_dir: Option<&Path>, workspace_root: Option<&Path>) -> Vec<SourceSpec> {
let mut specs = Vec::new();
if let Some(root) = workspace_root {
specs.push(SourceSpec {
id: "workspace-mcp",
label: "Project (.mcp.json)",
path: root.join(".mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: Some("claude"),
claude_project_lookup: false,
});
specs.push(SourceSpec {
id: "vscode-mcp",
label: "VS Code (.vscode/mcp.json)",
path: root.join(".vscode").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: None,
claude_project_lookup: false,
});
specs.push(SourceSpec {
id: "cursor-project",
label: "Cursor Project (.cursor/mcp.json)",
path: root.join(".cursor").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: Some("cursor"),
claude_project_lookup: false,
});
specs.push(SourceSpec {
id: "codex-project",
label: "Codex Project (.codex/config.toml)",
path: root.join(".codex").join("config.toml"),
format: SourceFormat::CodexToml,
suggested_scope: McpScope::Workspace,
native_provider: Some("codex"),
claude_project_lookup: false,
});
specs.push(SourceSpec {
id: "gemini-project",
label: "Gemini Project (.gemini/settings.json)",
path: root.join(".gemini").join("settings.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: Some("gemini"),
claude_project_lookup: false,
});
}
if let Some(home) = home_dir {
specs.push(SourceSpec {
id: "copilot-cli",
label: "GitHub Copilot CLI",
path: home.join(".copilot").join("mcp-config.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("copilot"),
claude_project_lookup: false,
});
specs.push(SourceSpec {
id: "claude-code",
label: "Claude Code",
path: home.join(".claude.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("claude"),
claude_project_lookup: true,
});
specs.push(SourceSpec {
id: "codex",
label: "Codex",
path: home.join(".codex").join("config.toml"),
format: SourceFormat::CodexToml,
suggested_scope: McpScope::User,
native_provider: Some("codex"),
claude_project_lookup: false,
});
specs.push(SourceSpec {
id: "cursor",
label: "Cursor",
path: home.join(".cursor").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("cursor"),
claude_project_lookup: false,
});
specs.push(SourceSpec {
id: "gemini",
label: "Gemini CLI",
path: home.join(".gemini").join("settings.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("gemini"),
claude_project_lookup: false,
});
specs.push(SourceSpec {
id: "jetbrains-air",
label: "JetBrains Air",
path: home.join(".jetbrains").join("mcp").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: None,
claude_project_lookup: false,
});
specs.push(SourceSpec {
id: "copilot-intellij",
label: "GitHub Copilot (JetBrains)",
path: home.join(".config").join("github-copilot").join("intellij").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: None,
claude_project_lookup: false,
});
}
specs
}
fn read_source_servers(spec: &SourceSpec, workspace_root: Option<&Path>) -> BTreeMap<String, AgentMcpServer> {
let Ok(text) = std::fs::read_to_string(&spec.path) else {
return BTreeMap::new();
};
if spec.format == SourceFormat::CodexToml {
return parse_codex_toml_servers(&text);
}
let Ok(root) = parse_jsonc_value(&text) else {
return BTreeMap::new();
};
let mut servers = extract_servers_from_root(&root, None);
if spec.claude_project_lookup
&& let Some(ws) = workspace_root
&& let Some(projects) = root.get("projects").and_then(Value::as_object)
{
let ws_canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.to_path_buf());
for (proj_key, proj_val) in projects {
let matches = Path::new(proj_key) == ws || dunce::canonicalize(proj_key).is_ok_and(|c| c == ws_canon);
if matches {
for (name, srv) in extract_servers_from_root(proj_val, None) {
servers.insert(name, srv);
}
}
}
}
servers
}
fn parse_codex_toml_servers(text: &str) -> BTreeMap<String, AgentMcpServer> {
let Ok(doc) = toml::from_str::<toml::Value>(text) else {
return BTreeMap::new();
};
let Ok(json_doc) = serde_json::to_value(doc) else {
return BTreeMap::new();
};
let Some(table) = json_doc.get("mcp_servers").or_else(|| json_doc.get("mcpServers")).and_then(Value::as_object)
else {
return BTreeMap::new();
};
let mut out = BTreeMap::new();
for (name, raw) in table {
let name = name.trim();
let Some(mut obj) = raw.as_object().cloned().filter(|_| !name.is_empty()) else {
continue;
};
if !obj.contains_key("headers")
&& let Some(http_headers) = obj.remove("http_headers")
{
obj.insert("headers".to_owned(), http_headers);
}
if let Some(srv) = parse_one_server_def(&obj) {
out.insert(name.to_owned(), srv);
}
}
out
}
/// Discovers external MCP configuration files on disk (without exposing secret values).
pub fn discover_external_sources(home_dir: Option<&Path>, workspace_root: Option<&Path>) -> Vec<McpExternalSource> {
let mut out = Vec::new();
for spec in external_source_specs(home_dir, workspace_root) {
let map = read_source_servers(&spec, workspace_root);
if map.is_empty() {
continue;
}
let servers = map
.into_iter()
.map(|(name, cfg)| McpDiscoveredServer {
name,
transport: cfg.transport,
enabled: cfg.enabled,
command: cfg.command,
args: cfg.args,
url: cfg.url,
env_keys: cfg.env.into_keys().collect(),
header_keys: cfg.headers.into_keys().collect(),
})
.collect();
out.push(McpExternalSource {
id: spec.id.to_owned(),
label: spec.label.to_owned(),
path: IpcPath(spec.path),
suggested_scope: spec.suggested_scope,
native_provider: spec.native_provider.map(str::to_owned),
servers,
});
}
out
}
/// Imports selected `(source_id, name)` entries from discovered external MCP config files into
/// `user` or `workspace` without modifying the external files. Returns imported server names.
pub fn apply_import_selected(
user: &mut BTreeMap<String, AgentMcpServer>,
workspace: &mut BTreeMap<String, AgentMcpServer>,
home_dir: Option<&Path>,
workspace_root: Option<&Path>,
scope: McpScope,
selections: &[McpImportSelection],
overwrite: bool,
) -> Result<Vec<String>, String> {
if scope == McpScope::Workspace && workspace_root.is_none() {
return Err("Open a project to import workspace MCP servers".into());
}
let specs = external_source_specs(home_dir, workspace_root);
let mut by_source: BTreeMap<&str, BTreeMap<String, AgentMcpServer>> = BTreeMap::new();
for spec in &specs {
if selections.iter().any(|s| s.source_id == spec.id) {
by_source.insert(spec.id, read_source_servers(spec, workspace_root));
}
}
let target = match scope {
McpScope::User => user,
McpScope::Workspace => workspace,
};
let mut imported = Vec::new();
for sel in selections {
let Some(source_map) = by_source.get(sel.source_id.as_str()) else {
continue;
};
let Some(srv) = source_map.get(&sel.name) else {
continue;
};
if overwrite || !target.contains_key(&sel.name) {
target.insert(sel.name.clone(), srv.clone());
imported.push(sel.name.clone());
}
}
Ok(imported)
}
fn normalize_agents_list(agents: Vec<String>) -> Vec<String> {
let mut out = Vec::new();
for a in agents {
@@ -287,73 +615,376 @@ fn normalize_agents_list(agents: Vec<String>) -> Vec<String> {
out
}
fn read_external_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
let Ok(bytes) = std::fs::read(path) else {
return BTreeMap::new();
};
let Ok(root) = serde_json::from_slice::<Value>(&bytes) else {
return BTreeMap::new();
};
let Some(servers_obj) = root.get("mcpServers").or_else(|| root.get("servers")).and_then(Value::as_object) else {
return BTreeMap::new();
/// Strips `//` line comments, `/* ... */` block comments, and trailing commas before `}` or `]`
/// outside JSON string literals so JSONC config files parse cleanly with `serde_json`.
pub(crate) fn strip_jsonc(input: &str) -> String {
let bytes = input.as_bytes();
let mut out = String::with_capacity(input.len());
let mut i = 0;
let mut in_str = false;
while i < bytes.len() {
if in_str {
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
if ch == '\\' && i < bytes.len() {
let next = input[i..].chars().next().unwrap();
out.push(next);
i += next.len_utf8();
} else if ch == '"' {
in_str = false;
}
continue;
}
if bytes[i] == b'"' {
in_str = true;
out.push('"');
i += 1;
continue;
}
if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'/' {
i += 2;
while i < bytes.len() && bytes[i] != b'\n' {
i += 1;
}
continue;
}
if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'*' {
i += 2;
while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
if bytes[i] == b'\n' {
out.push('\n');
i += 1;
} else {
let ch = input[i..].chars().next().unwrap();
i += ch.len_utf8();
}
}
i = (i + 2).min(bytes.len());
continue;
}
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
}
remove_trailing_commas(&out)
}
fn remove_trailing_commas(input: &str) -> String {
let bytes = input.as_bytes();
let mut out = String::with_capacity(input.len());
let mut i = 0;
let mut in_str = false;
while i < bytes.len() {
if in_str {
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
if ch == '\\' && i < bytes.len() {
let next = input[i..].chars().next().unwrap();
out.push(next);
i += next.len_utf8();
} else if ch == '"' {
in_str = false;
}
continue;
}
if bytes[i] == b'"' {
in_str = true;
out.push('"');
i += 1;
continue;
}
if bytes[i] == b',' {
let mut j = i + 1;
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
j += 1;
}
if j < bytes.len() && (bytes[j] == b'}' || bytes[j] == b']') {
i += 1;
continue;
}
}
let ch = input[i..].chars().next().unwrap();
out.push(ch);
i += ch.len_utf8();
}
out
}
fn parse_jsonc_value(raw: &str) -> Result<Value, String> {
let trimmed = raw.trim().trim_start_matches('\u{feff}');
serde_json::from_str::<Value>(trimmed)
.or_else(|_| serde_json::from_str::<Value>(&strip_jsonc(trimmed)))
.map_err(|e| format!("Invalid JSON: {e}"))
}
pub fn parse_mcp_json_text(raw: &str, fallback_name: Option<&str>) -> Result<BTreeMap<String, AgentMcpServer>, String> {
let root = parse_jsonc_value(raw)?;
Ok(extract_servers_from_root(&root, fallback_name))
}
fn is_server_def_object(obj: &serde_json::Map<String, Value>) -> bool {
obj.get("command").and_then(Value::as_str).is_some_and(|s| !s.trim().is_empty())
|| obj.get("url").and_then(Value::as_str).is_some_and(|s| !s.trim().is_empty())
|| obj.get("serverUrl").and_then(Value::as_str).is_some_and(|s| !s.trim().is_empty())
}
fn parse_one_server_def(obj: &serde_json::Map<String, Value>) -> Option<AgentMcpServer> {
let disabled = obj.get("disabled").and_then(Value::as_bool).unwrap_or(false)
|| obj.get("enabled").and_then(Value::as_bool) == Some(false);
let type_str = obj.get("type").and_then(Value::as_str).unwrap_or_default().to_ascii_lowercase();
let url = obj
.get("url")
.or_else(|| obj.get("serverUrl"))
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_owned);
let command =
obj.get("command").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned);
let transport = match type_str.as_str() {
"sse" => McpTransport::Sse,
"http" | "streamable-http" | "streamable_http" => McpTransport::Http,
"stdio" | "local" => McpTransport::Stdio,
_ if url.is_some() && command.is_none() => McpTransport::Http,
_ => McpTransport::Stdio,
};
match transport {
McpTransport::Stdio => command.as_ref()?,
McpTransport::Http | McpTransport::Sse => url.as_ref()?,
};
let args = obj
.get("args")
.and_then(Value::as_array)
.map(|arr| arr.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect())
.unwrap_or_default();
let agents = obj
.get("agents")
.and_then(Value::as_array)
.map(|arr| normalize_agents_list(arr.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect()))
.unwrap_or_default();
Some(AgentMcpServer {
transport,
enabled: !disabled,
command,
args,
env: parse_key_values_map(obj.get("env")),
url,
headers: parse_key_values_map(obj.get("headers")),
agents,
})
}
fn extract_servers_from_root(root: &Value, fallback_name: Option<&str>) -> BTreeMap<String, AgentMcpServer> {
let mut out = BTreeMap::new();
for (name, def) in servers_obj {
let name = name.trim();
let Some(obj) = def.as_object().filter(|_| !name.is_empty()) else {
continue;
};
let disabled = obj.get("disabled").and_then(Value::as_bool).unwrap_or(false)
|| obj.get("enabled").and_then(Value::as_bool) == Some(false);
let type_str = obj.get("type").and_then(Value::as_str).unwrap_or_default().to_ascii_lowercase();
let url = obj
.get("url")
.or_else(|| obj.get("serverUrl"))
let Some(root_obj) = root.as_object() else {
return out;
};
// Single server definition object pasted directly (`{"command": "npx", ...}`).
if is_server_def_object(root_obj) {
let name = root_obj
.get("name")
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_owned);
let command =
obj.get("command").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned);
let transport = match type_str.as_str() {
"sse" => McpTransport::Sse,
"http" | "streamable-http" | "streamable_http" => McpTransport::Http,
"stdio" | "local" => McpTransport::Stdio,
_ if url.is_some() && command.is_none() => McpTransport::Http,
_ => McpTransport::Stdio,
};
match transport {
McpTransport::Stdio if command.is_none() => continue,
McpTransport::Http | McpTransport::Sse if url.is_none() => continue,
_ => {}
.or_else(|| fallback_name.map(str::trim).filter(|s| !s.is_empty()));
if let (Some(name), Some(srv)) = (name, parse_one_server_def(root_obj)) {
out.insert(name.to_owned(), srv);
}
return out;
}
let args = obj
.get("args")
.and_then(Value::as_array)
.map(|arr| arr.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect())
.unwrap_or_default();
let servers_obj =
root_obj.get("mcpServers").or_else(|| root_obj.get("servers")).and_then(Value::as_object).unwrap_or(root_obj);
out.insert(
name.to_owned(),
AgentMcpServer {
transport,
enabled: !disabled,
command,
args,
env: parse_key_values_map(obj.get("env")),
url,
headers: parse_key_values_map(obj.get("headers")),
agents: Vec::new(),
},
);
for (name, def) in servers_obj {
let name = name.trim();
if name.is_empty() || matches!(name, "$schema" | "inputs" | "version") {
continue;
}
let Some(obj) = def.as_object() else {
continue;
};
if !is_server_def_object(obj) {
continue;
}
if let Some(srv) = parse_one_server_def(obj) {
out.insert(name.to_owned(), srv);
}
}
out
}
fn read_external_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
let Ok(text) = std::fs::read_to_string(path) else {
return BTreeMap::new();
};
let Ok(root) = parse_jsonc_value(&text) else {
return BTreeMap::new();
};
extract_servers_from_root(&root, None)
}
/// Probes a stdio MCP server by launching its command, performing the MCP `initialize` handshake,
/// and requesting `tools/list`. For HTTP/SSE servers, use `ide-host`'s HTTP probe helper.
pub async fn probe_stdio_server(server: &AgentMcpServer, cwd: &Path) -> McpProbeResult {
let started = Instant::now();
let elapsed_ms = || u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
let Some(raw_cmd) = server.command.as_deref().map(str::trim).filter(|s| !s.is_empty()) else {
return McpProbeResult {
ok: false,
server_name: None,
server_version: None,
protocol_version: None,
tools: Vec::new(),
duration_ms: elapsed_ms(),
error: Some("Command is empty".into()),
};
};
let mut env: Vec<(String, String)> = ide_core::process::shell_env()
.map(|(k, v)| (k.to_string_lossy().into_owned(), v.to_string_lossy().into_owned()))
.collect();
for (k, v) in &server.env {
if let Some((_, existing)) = env.iter_mut().find(|(ek, _)| ek == k) {
*existing = v.clone();
} else {
env.push((k.clone(), v.clone()));
}
}
let search_path = env
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
.map(|(_, v)| std::ffi::OsString::from(v))
.or_else(|| ide_core::process::host_var_os("PATH"))
.unwrap_or_default();
let program = ide_core::process::find_executable(raw_cmd, &search_path)
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|| raw_cmd.to_owned());
let stderr_lines = std::sync::Arc::new(parking_lot::Mutex::new(Vec::<String>::new()));
let stderr_capture = stderr_lines.clone();
let on_stderr: Box<dyn Fn(String) + Send + Sync> = Box::new(move |line| {
let mut guard = stderr_capture.lock();
if guard.len() < 12 && !line.trim().is_empty() {
guard.push(line);
}
});
let peer = match ide_jsonrpc::Peer::spawn_framed(
&program,
&server.args,
cwd,
&env,
std::sync::Arc::new(ide_jsonrpc::NoopHandler),
on_stderr,
ide_jsonrpc::Framing::Lines,
) {
Ok(peer) => peer,
Err(e) => {
return McpProbeResult {
ok: false,
server_name: None,
server_version: None,
protocol_version: None,
tools: Vec::new(),
duration_ms: elapsed_ms(),
error: Some(format!("Failed to launch `{raw_cmd}`: {e}")),
};
}
};
let outcome = tokio::time::timeout(PROBE_TIMEOUT, async {
let init: Value = peer
.request(
"initialize",
json!({
"protocolVersion": PROBE_PROTOCOL_VERSION,
"capabilities": {},
"clientInfo": crate::client_info(),
}),
None,
)
.await
.map_err(|e| e.to_string())?;
let _ = peer.notify("notifications/initialized", json!({}));
let tools_reply: Value = peer.request("tools/list", json!({}), None).await.unwrap_or_else(|_| json!({}));
Ok::<(Value, Value), String>((init, tools_reply))
})
.await;
peer.kill();
match outcome {
Ok(Ok((init, tools_reply))) => parse_probe_payloads(&init, &tools_reply, elapsed_ms()),
Ok(Err(err)) => {
let tail = stderr_lines.lock().join("\n");
let error = if tail.is_empty() { err } else { format!("{err}\n{tail}") };
McpProbeResult {
ok: false,
server_name: None,
server_version: None,
protocol_version: None,
tools: Vec::new(),
duration_ms: elapsed_ms(),
error: Some(error),
}
}
Err(_) => {
let tail = stderr_lines.lock().join("\n");
let error = if tail.is_empty() {
format!("Timed out after {}s waiting for MCP handshake", PROBE_TIMEOUT.as_secs())
} else {
format!("Timed out after {}s waiting for MCP handshake:\n{tail}", PROBE_TIMEOUT.as_secs())
};
McpProbeResult {
ok: false,
server_name: None,
server_version: None,
protocol_version: None,
tools: Vec::new(),
duration_ms: elapsed_ms(),
error: Some(error),
}
}
}
}
pub fn parse_probe_payloads(init: &Value, tools_reply: &Value, duration_ms: u32) -> McpProbeResult {
let server_name = init.pointer("/serverInfo/name").and_then(Value::as_str).map(str::to_owned);
let server_version = init.pointer("/serverInfo/version").and_then(Value::as_str).map(str::to_owned);
let protocol_version = init.get("protocolVersion").and_then(Value::as_str).map(str::to_owned);
let tools = tools_reply
.get("tools")
.and_then(Value::as_array)
.map(|arr| {
arr.iter()
.filter_map(|t| {
let name = t.get("name")?.as_str()?.trim();
if name.is_empty() {
return None;
}
let description = t
.get("description")
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_owned);
Some(McpToolSummary { name: name.to_owned(), description })
})
.collect()
})
.unwrap_or_default();
McpProbeResult { ok: true, server_name, server_version, protocol_version, tools, duration_ms, error: None }
}
fn parse_key_values_map(val: Option<&Value>) -> BTreeMap<String, String> {
match val {
Some(Value::Object(map)) => map
@@ -457,22 +1088,29 @@ mod tests {
let init_http = Negotiated::from_initialize(&json!({
"agentCapabilities": { "mcpCapabilities": { "http": true, "sse": false } }
}));
let claude_servers = acp_mcp_servers(&list, "claude-acp", &init_http);
let empty_overrides = BTreeMap::new();
let claude_servers = acp_mcp_servers(&list, "claude-acp", &init_http, &empty_overrides);
assert_eq!(claude_servers.len(), 2);
assert_eq!(claude_servers[0]["name"], "shared");
assert_eq!(claude_servers[0]["args"], json!(["-y", "workspace-pkg"]));
assert_eq!(claude_servers[1]["name"], "claude-http");
assert_eq!(claude_servers[1]["type"], "http");
let codex_servers = acp_mcp_servers(&list, "codex", &init_http);
let codex_servers = acp_mcp_servers(&list, "codex", &init_http, &empty_overrides);
assert_eq!(codex_servers.len(), 1);
assert_eq!(codex_servers[0]["name"], "shared");
// Per-session overrides can disable an enabled server or enable an agent-scoped server.
let overrides = BTreeMap::from([("shared".to_owned(), false), ("claude-http".to_owned(), true)]);
let codex_overridden = acp_mcp_servers(&list, "codex", &init_http, &overrides);
assert_eq!(codex_overridden.len(), 1);
assert_eq!(codex_overridden[0]["name"], "claude-http");
// Disable workspace `shared` and remove user `claude-http`.
apply_set_enabled(&mut user, &mut workspace, "workspace::shared", false).unwrap();
apply_remove(&mut user, &mut workspace, "user::claude-http").unwrap();
let list = servers_from_settings(&user, &workspace);
let after = acp_mcp_servers(&list, "claude", &init_http);
let after = acp_mcp_servers(&list, "claude", &init_http, &empty_overrides);
assert_eq!(after.len(), 1);
assert_eq!(after[0]["args"], json!(["-y", "user-pkg"]));
}
@@ -504,4 +1142,124 @@ mod tests {
assert_eq!(std::fs::read_to_string(&mcp_json).unwrap(), raw_mcp);
assert_eq!(std::fs::read_to_string(&vscode_mcp).unwrap(), raw_vscode);
}
#[test]
fn discovers_cli_sources_top_level_maps_and_jsonc_and_imports_selected() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
let proj = tmp.path().join("project");
std::fs::create_dir_all(home.join(".copilot")).unwrap();
std::fs::create_dir_all(home.join(".codex")).unwrap();
std::fs::create_dir_all(home.join(".gemini")).unwrap();
std::fs::create_dir_all(home.join(".jetbrains").join("mcp")).unwrap();
std::fs::create_dir_all(home.join(".config").join("github-copilot").join("intellij")).unwrap();
std::fs::create_dir_all(&proj).unwrap();
std::fs::write(
home.join(".copilot").join("mcp-config.json"),
r#"{"mcpServers":{"github":{"type":"http","url":"https://api.githubcopilot.com/mcp/","headers":{"Authorization":"Bearer tok"}},"slack":{"type":"local","command":"npx","args":["-y","slack-mcp"],"env":{"SLACK_TOKEN":"xoxb"}}}}"#,
)
.unwrap();
// Codex `~/.codex/config.toml` `[mcp_servers]` format.
std::fs::write(
home.join(".codex").join("config.toml"),
"[mcp_servers.postgres]\ncommand = \"npx\"\nargs = [\"-y\", \"@modelcontextprotocol/server-postgres\"]\n\n[mcp_servers.remote_api]\nurl = \"https://mcp.example.com/sse\"\ntype = \"sse\"\nhttp_headers = { Authorization = \"Bearer codex-tok\" }\n",
)
.unwrap();
// Gemini `~/.gemini/settings.json` with unrelated top-level settings alongside `mcpServers`.
std::fs::write(
home.join(".gemini").join("settings.json"),
r#"{"theme":"Default","mcpServers":{"fetch":{"command":"uvx","args":["mcp-server-fetch"]}}}"#,
)
.unwrap();
// JetBrains Air top-level server map (not nested under `mcpServers`).
std::fs::write(
home.join(".jetbrains").join("mcp").join("mcp.json"),
r#"{"linear":{"type":"stdio","command":"npx","args":["-y","mcp-remote","https://mcp.linear.app/mcp"]}}"#,
)
.unwrap();
// JSONC comments + trailing commas.
std::fs::write(
home.join(".config").join("github-copilot").join("intellij").join("mcp.json"),
"// comment with https://url/inside\n{\n /* block comment */\n \"servers\": {\n \"docs\": { \"command\": \"uvx\", \"args\": [\"docs-mcp\",], },\n },\n}\n",
)
.unwrap();
let sources = discover_external_sources(Some(&home), Some(&proj));
assert_eq!(sources.len(), 5);
let copilot = sources.iter().find(|s| s.id == "copilot-cli").unwrap();
assert_eq!(copilot.native_provider.as_deref(), Some("copilot"));
assert_eq!(copilot.servers.len(), 2);
let gh_srv = copilot.servers.iter().find(|s| s.name == "github").unwrap();
assert_eq!(gh_srv.header_keys, vec!["Authorization".to_string()]);
let codex = sources.iter().find(|s| s.id == "codex").unwrap();
assert_eq!(codex.native_provider.as_deref(), Some("codex"));
assert_eq!(codex.servers.len(), 2);
let gemini = sources.iter().find(|s| s.id == "gemini").unwrap();
assert_eq!(gemini.servers[0].name, "fetch");
let air = sources.iter().find(|s| s.id == "jetbrains-air").unwrap();
assert_eq!(air.servers[0].name, "linear");
let ij = sources.iter().find(|s| s.id == "copilot-intellij").unwrap();
assert_eq!(ij.servers[0].name, "docs");
let mut user = BTreeMap::new();
let mut workspace = BTreeMap::new();
let imported = apply_import_selected(
&mut user,
&mut workspace,
Some(&home),
Some(&proj),
McpScope::User,
&[
McpImportSelection { source_id: "copilot-cli".into(), name: "github".into() },
McpImportSelection { source_id: "jetbrains-air".into(), name: "linear".into() },
],
false,
)
.unwrap();
assert_eq!(imported, vec!["github".to_string(), "linear".to_string()]);
assert_eq!(user["github"].headers.get("Authorization").map(String::as_str), Some("Bearer tok"));
assert_eq!(user["linear"].command.as_deref(), Some("npx"));
}
#[test]
fn apply_save_json_accepts_mcp_servers_map_and_single_server_object() {
let mut user = BTreeMap::new();
let mut workspace = BTreeMap::new();
let names = apply_save_json(
&mut user,
&mut workspace,
true,
McpScope::User,
r#"{"mcpServers":{"playwright":{"command":"npx","args":["@playwright/mcp@latest"]}}}"#,
None,
vec!["copilot".into(), "claude".into()],
)
.unwrap();
assert_eq!(names, vec!["playwright".to_string()]);
assert_eq!(user["playwright"].agents, vec!["copilot".to_string(), "claude".to_string()]);
let single = apply_save_json(
&mut user,
&mut workspace,
true,
McpScope::Workspace,
r#"{"type":"sse","serverUrl":"https://sse.example.com/events"}"#,
Some("events-sse"),
Vec::new(),
)
.unwrap();
assert_eq!(single, vec!["events-sse".to_string()]);
assert_eq!(workspace["events-sse"].transport, McpTransport::Sse);
assert_eq!(workspace["events-sse"].url.as_deref(), Some("https://sse.example.com/events"));
}
}
+76 -3
Переглянути файл
@@ -50,12 +50,13 @@ pub struct AgentCapabilities {
pub read_only: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum Isolation {
/// A new git worktree on its own branch.
Worktree,
/// The project's own checkout.
#[default]
Local,
}
@@ -107,6 +108,9 @@ pub struct AgentTask {
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
#[serde(default)]
pub background: Box<Vec<AgentBackgroundTask>>,
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub mcp_overrides: BTreeMap<String, bool>,
}
/// A task the agent runs in the background while the conversation goes on.
@@ -592,7 +596,7 @@ pub struct AgentProbe {
pub error: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct NewAgentTask {
/// Validated by the host; defaults to the window project root.
@@ -605,6 +609,9 @@ pub struct NewAgentTask {
pub isolation: Isolation,
/// Branch to start the worktree from; the current branch when `None`.
pub base: Option<String>,
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`).
#[serde(default)]
pub mcp_overrides: BTreeMap<String, bool>,
}
/// A file the task changed: against [`AgentTask::base_commit`], or against `HEAD` in the
@@ -676,7 +683,7 @@ pub struct AgentModelCatalog {
pub enum AgentEvent {
/// A task was created or its metadata changed.
Task {
task: AgentTask,
task: Box<AgentTask>,
},
Removed {
id: String,
@@ -756,6 +763,9 @@ pub struct McpServer {
/// Agent provider ids this server is enabled for; empty means enabled for all agents.
#[serde(default)]
pub agents: Vec<String>,
/// True when this Workspace server was added outside OpenIDEA and has not been approved yet.
#[serde(default)]
pub unapproved: bool,
}
/// Payload for creating or updating a user or workspace MCP server.
@@ -788,6 +798,69 @@ fn default_true() -> bool {
true
}
/// An external MCP configuration file discovered on disk (user CLI config or workspace file).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct McpExternalSource {
/// Stable source identifier (e.g. `"copilot-cli"`, `"jetbrains-air"`, `"claude-code"`, `"cursor"`, `"workspace-mcp"`, `"vscode-mcp"`).
pub id: String,
/// Human-readable source label (e.g. `"GitHub Copilot CLI"`).
pub label: String,
/// Absolute path of the discovered configuration file.
pub path: IpcPath,
/// Suggested target scope when importing this source into OpenIDEA settings.
pub suggested_scope: McpScope,
/// Agent provider ID this external CLI reads natively (`Some("copilot")`, `Some("claude")`, `Some("cursor")`, or `None`).
pub native_provider: Option<String>,
/// Servers found inside this external configuration file (values omitted for safety; imported directly on the host).
pub servers: Vec<McpDiscoveredServer>,
}
/// Summary of one server discovered inside an external MCP configuration file.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct McpDiscoveredServer {
pub name: String,
pub transport: McpTransport,
pub enabled: bool,
pub command: Option<String>,
pub args: Vec<String>,
pub url: Option<String>,
/// Environment variable names declared on this server (values stay on the host).
pub env_keys: Vec<String>,
/// HTTP header names declared on this server (values stay on the host).
pub header_keys: Vec<String>,
}
/// Selection of one server from an external MCP configuration source to import.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct McpImportSelection {
pub source_id: String,
pub name: String,
}
/// One tool advertised by an MCP server during `tools/list`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct McpToolSummary {
pub name: String,
pub description: Option<String>,
}
/// Result of testing/probing an MCP server (`initialize` + `tools/list`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct McpProbeResult {
pub ok: bool,
pub server_name: Option<String>,
pub server_version: Option<String>,
pub protocol_version: Option<String>,
pub tools: Vec<McpToolSummary>,
pub duration_ms: u32,
pub error: Option<String>,
}
/// Payload for creating a custom ACP agent (always the ACP driver); the id
/// becomes the `<config>/agents/<id>.toml` file name.
#[derive(Clone, Debug, Deserialize, Type)]
+1
Переглянути файл
@@ -64,6 +64,7 @@ async fn create(mgr: &AgentManager, provider: &str, prompt: &str) -> String {
config: config(provider),
isolation: Isolation::Local,
base: None,
..Default::default()
};
mgr.create(req).await.unwrap().id
}
+149 -1
Переглянути файл
@@ -54,6 +54,8 @@ struct FakeAgent {
/// Advertises steering as OMP does (`_meta.steering` at the top of `initialize`)
/// instead of `_meta.openidea.steer`.
session_steering: bool,
/// Records the `mcpServers` array passed to `session/new`, `session/load`, and `session/fork`.
mcp_calls: Mutex<Vec<(String, Vec<String>)>>,
}
impl FakeAgent {
@@ -153,6 +155,18 @@ impl Handler for FakeAgent {
// Let the prompt's permission request reach the task before the mode changes.
std::thread::sleep(Duration::from_millis(100));
}
if matches!(method, "session/new" | "session/load" | "session/fork") {
let names = params
.get("mcpServers")
.and_then(Value::as_array)
.map(|arr| {
arr.iter()
.filter_map(|v| v.get("name").and_then(Value::as_str).map(str::to_owned))
.collect::<Vec<_>>()
})
.unwrap_or_default();
self.mcp_calls.lock().push((method.to_owned(), names));
}
let session = params.get("sessionId").and_then(Value::as_str).unwrap_or("s1").to_owned();
match method {
"initialize" => {
@@ -456,6 +470,7 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -649,6 +664,7 @@ async fn authentication_failures_name_the_session_executable_at_start_and_during
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -699,6 +715,7 @@ async fn sign_in_errors_preserve_details_and_leave_unrelated_errors_unchanged()
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -754,6 +771,7 @@ async fn registry_sign_in_errors_use_the_advertised_terminal_login() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -801,6 +819,7 @@ async fn authenticates_and_retries_session_setup_once_on_auth_error() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -883,6 +902,7 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -923,6 +943,7 @@ async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metada
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -981,6 +1002,7 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
config: vec![AgentConfigChoice { id: "model".into(), value: "small".into() }],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1104,6 +1126,7 @@ async fn steers_through_session_steering() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1140,6 +1163,7 @@ async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1195,6 +1219,7 @@ async fn subagents_get_their_own_conversation() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1290,6 +1315,7 @@ async fn claude_questions_keep_the_answer_object_as_the_option_id() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1339,6 +1365,7 @@ async fn qwen_questions_answer_by_index_beside_the_submit_option() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1407,6 +1434,7 @@ async fn skipped_qwen_questions_cancel_the_request() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1446,6 +1474,7 @@ async fn cancelling_resolves_the_open_permission_and_delete_forgets_the_task() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1467,7 +1496,8 @@ async fn cancelling_resolves_the_open_permission_and_delete_forgets_the_task() {
provider: "codex".into(),
config: vec![],
isolation: Isolation::Local,
base: None
base: None,
..Default::default()
})
.await
.is_err()
@@ -1516,6 +1546,7 @@ async fn real_claude_task_in_a_worktree() {
config: vec![AgentConfigChoice { id: "model".into(), value: "haiku".into() }],
isolation: Isolation::Worktree,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1566,6 +1597,7 @@ async fn renamed_titles_survive_updates_forks_and_restart() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1603,6 +1635,7 @@ async fn forks_rollbacks_and_steering() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
};
let task = mgr.create(new("again")).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
@@ -1682,6 +1715,7 @@ async fn usage_limits_and_late_settings() {
config: vec![AgentConfigChoice { id: "effort".into(), value: "high".into() }],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1735,6 +1769,7 @@ async fn remembered_settings_drop_per_model_choices_for_the_next_task() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1769,6 +1804,7 @@ async fn thinking_levels_are_remembered_per_provider_and_model() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1815,6 +1851,7 @@ async fn changing_an_idle_tasks_settings_keeps_its_models_effort_levels() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1856,6 +1893,7 @@ async fn upfront_effort_is_validated_after_changing_model_before_the_prompt() {
],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1887,6 +1925,7 @@ async fn unreported_model_switch_does_not_cache_the_previous_models_levels() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1911,6 +1950,7 @@ async fn cached_effort_is_not_sent_without_real_session_options() {
config,
isolation: Isolation::Local,
base: None,
..Default::default()
};
let warm = mgr.create(new(vec![])).await.unwrap();
wait_for(&mgr, &warm.id, AgentStatus::Ready).await;
@@ -1946,6 +1986,7 @@ async fn reported_levels_refresh_even_without_a_model_option() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1999,6 +2040,7 @@ async fn cursor_approval_switch_resolves_pending_and_survives_restart() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
};
let task = mgr.create(new()).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
@@ -2052,6 +2094,7 @@ async fn bypass_approvals_keeps_both_question_dialects_pending_but_allows_permis
},
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -2113,6 +2156,7 @@ async fn an_agent_form_is_answered_declined_or_cancelled_even_when_approvals_are
config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -2155,6 +2199,7 @@ async fn cursor_approval_choice_applies_before_first_prompt() {
config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -2179,6 +2224,7 @@ async fn a_full_access_mode_approves_tool_requests() {
config: vec![AgentConfigChoice { id: "mode".into(), value: "full-access".into() }],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -2200,6 +2246,7 @@ async fn a_full_access_mode_approves_tool_requests() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -2228,6 +2275,7 @@ async fn a_late_full_access_option_approves_a_pending_request() {
config: vec![AgentConfigChoice { id: "mode".into(), value: "full-access".into() }],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -2275,6 +2323,7 @@ async fn an_allow_all_permissions_option_approves_tool_requests() {
config: vec![AgentConfigChoice { id: "allow_all".into(), value: "on".into() }],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -2302,6 +2351,7 @@ async fn archived_tasks_can_be_restored_and_continue_their_session() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -2354,6 +2404,7 @@ async fn task_project_root_controls_local_and_worktree_repositories() {
config: vec![],
isolation,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -2560,6 +2611,7 @@ async fn idle_agents_stop_and_resume_their_session_on_the_next_message() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
};
let live =
|mgr: &AgentManager, id: &str| mgr.task(id).unwrap().live.lock().as_ref().is_some_and(|l| !l.peer.is_closed());
@@ -2638,6 +2690,7 @@ async fn an_idle_agent_waits_for_its_background_tasks_before_it_stops() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
};
let tmp = tempfile::tempdir().unwrap();
@@ -2672,6 +2725,7 @@ async fn the_task_shows_what_runs_in_the_background() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -2724,6 +2778,7 @@ async fn a_background_task_is_stopped_on_its_own() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -2811,6 +2866,7 @@ async fn delete_running_agent(no_load: bool) {
config: vec![],
isolation: Isolation::Worktree,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -2926,6 +2982,7 @@ async fn config_choice_shows_before_the_agent_answers() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3031,6 +3088,7 @@ async fn rolling_back_restores_the_start_of_the_task_and_keeps_the_users_own_edi
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3137,6 +3195,7 @@ impl Checkout {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3343,6 +3402,7 @@ async fn security_policy_auto_approves_whitelist_and_rejects_blacklist() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3373,6 +3433,7 @@ async fn security_policy_auto_approves_whitelist_and_rejects_blacklist() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3410,6 +3471,7 @@ async fn security_policy_never_auto_approves_a_request_that_only_reads_like_a_co
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3447,6 +3509,7 @@ async fn ephemeral_tasks_stay_in_memory_only() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3461,6 +3524,7 @@ async fn ephemeral_tasks_stay_in_memory_only() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
},
&source.id,
)
@@ -3562,6 +3626,7 @@ async fn ephemeral_tasks_deny_write_permissions() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3587,6 +3652,7 @@ async fn ephemeral_tasks_deny_write_permissions() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
},
&source.id,
)
@@ -3659,6 +3725,7 @@ async fn attention_finished_not_cancelled() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3674,6 +3741,7 @@ async fn attention_finished_not_cancelled() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3710,6 +3778,7 @@ async fn attention_failed() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3735,6 +3804,7 @@ async fn attention_input_not_auto_bypass() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3752,6 +3822,7 @@ async fn attention_input_not_auto_bypass() {
config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3778,6 +3849,7 @@ async fn attention_not_emitted_on_restore() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3794,6 +3866,80 @@ async fn attention_not_emitted_on_restore() {
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
mgr.set_mcp_servers_hook(Box::new(|| {
vec![
McpServer {
id: "user::github".into(),
name: "github".into(),
scope: McpScope::User,
transport: McpTransport::Stdio,
enabled: true,
command: Some("npx".into()),
args: vec!["gh-mcp".into()],
env: Vec::new(),
url: None,
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
},
McpServer {
id: "user::slack".into(),
name: "slack".into(),
scope: McpScope::User,
transport: McpTransport::Stdio,
enabled: true,
command: Some("npx".into()),
args: vec!["slack-mcp".into()],
env: Vec::new(),
url: None,
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
},
]
}));
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let first_mcp = agent.mcp_calls.lock().last().cloned().unwrap();
assert_eq!(first_mcp.0, "session/new");
assert!(first_mcp.1.contains(&"github".to_string()));
assert!(!first_mcp.1.contains(&"slack".to_string()));
// Toggle `slack` back on and `github` off while idle -> recycles the resumable session,
// so the next prompt calls `session/load` with the updated MCP servers.
let updated =
mgr.set_mcp_overrides(&task.id, BTreeMap::from([("github".into(), false), ("slack".into(), true)])).unwrap();
assert_eq!(updated.mcp_overrides.get("github"), Some(&false));
assert_eq!(updated.mcp_overrides.get("slack"), Some(&true));
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let reloaded = agent.mcp_calls.lock().last().cloned().unwrap();
assert_eq!(reloaded.0, "session/load");
assert!(!reloaded.1.contains(&"github".to_string()));
assert!(reloaded.1.contains(&"slack".to_string()));
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails() {
#[derive(Clone, Copy)]
@@ -3893,6 +4039,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
config: vec![AgentConfigChoice { id: "context_tier".into(), value: "long_context".into() }],
isolation: Isolation::Local,
base: None,
mcp_overrides: BTreeMap::new(),
})
.await
.unwrap();
@@ -3916,6 +4063,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
config: vec![],
isolation: Isolation::Local,
base: None,
mcp_overrides: BTreeMap::new(),
})
.await
.unwrap();
+297 -21
Переглянути файл
@@ -8,7 +8,8 @@ use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCommand, AgentEntry,
AgentEvent, AgentModelCatalog, AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentTask, CustomAgentInput,
ExternalSession, McpScope, McpServer, McpServerInput, NewAgentTask,
ExternalSession, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput,
McpTransport, NewAgentTask,
};
use ide_core::error::ErrorKind;
use ide_core::{IdeError, IdeEvent, IdeResult, IpcPath, RequestId, SharedSink, TaskId};
@@ -477,19 +478,21 @@ fn persist_mcp_map(
Ok(())
}
fn update_mcp_maps<F>(host: &Host, window: &str, approve: Option<&str>, f: F) -> IdeResult<Vec<McpServer>>
fn update_mcp_maps<F>(host: &Host, window: &str, approve: &[String], f: F) -> IdeResult<Vec<McpServer>>
where
F: FnOnce(&mut McpServerMap, &mut McpServerMap, Option<&std::path::Path>) -> Result<(), String>,
F: FnOnce(&mut McpServerMap, &mut McpServerMap, Option<&std::path::Path>) -> Result<Vec<String>, String>,
{
let (mut user, mut workspace, project) = mcp_maps(host, window);
let prev_user = user.clone();
let prev_workspace = workspace.clone();
let project_root = project.as_ref().map(|p| p.root.as_path());
f(&mut user, &mut workspace, project_root).map_err(IdeError::invalid)?;
if let (Some(name), Some(p)) = (approve, &project)
&& let Some(server) = workspace.get(name)
{
host.mcp_approvals.approve(&p.root, name, server)?;
let extra_approved = f(&mut user, &mut workspace, project_root).map_err(IdeError::invalid)?;
if let Some(p) = &project {
for name in approve.iter().chain(extra_approved.iter()) {
if let Some(server) = workspace.get(name.as_str()) {
host.mcp_approvals.approve(&p.root, name, server)?;
}
}
}
if workspace != prev_workspace {
persist_mcp_map(host, project.as_ref(), McpScope::Workspace, &workspace)?;
@@ -507,11 +510,22 @@ fn listed(
user: &McpServerMap,
workspace: McpServerMap,
) -> Vec<McpServer> {
let raw_workspace = workspace.clone();
let workspace = match project {
Some(p) => host.mcp_approvals.apply(&p.root, workspace),
None => workspace,
};
ide_agent::mcp::servers_from_settings(user, &workspace)
let mut out = ide_agent::mcp::servers_from_settings(user, &workspace);
if let Some(p) = project {
for srv in &mut out {
if srv.scope == McpScope::Workspace
&& let Some(raw) = raw_workspace.get(&srv.name)
{
srv.unapproved = !host.mcp_approvals.approved(&p.root, &srv.name, raw);
}
}
}
out
}
/// The MCP servers agent sessions of the project at `root` get: the user's, values filled in, and
@@ -525,7 +539,8 @@ pub(crate) fn session_mcp_servers(
use ide_workspace::settings::SettingsScope;
let mut user = settings.layer(SettingsScope::Global).agents.mcp_servers;
fill_mcp_values(secrets, &mut user);
let workspace = approvals.apply(root, settings.layer(SettingsScope::Project).agents.mcp_servers);
let mut workspace = settings.layer(SettingsScope::Project).agents.mcp_servers;
workspace.retain(|name, srv| approvals.approved(root, name, srv));
ide_agent::mcp::servers_from_settings(&user, &workspace)
}
@@ -538,39 +553,289 @@ pub fn mcp_list(host: &Host, window: &str) -> IdeResult<Vec<McpServer>> {
/// Creates or updates a User or Workspace MCP server and returns the updated list. A Workspace
/// server saved here is one the user turned on.
pub fn mcp_save(host: &Host, window: &str, input: McpServerInput) -> IdeResult<Vec<McpServer>> {
let approve = (input.scope == McpScope::Workspace).then(|| input.name.trim().to_owned());
update_mcp_maps(host, window, approve.as_deref(), |user, workspace, project_root| {
ide_agent::mcp::apply_save(user, workspace, project_root.is_some(), input)
let approve: Vec<String> =
(input.scope == McpScope::Workspace).then(|| input.name.trim().to_owned()).into_iter().collect();
update_mcp_maps(host, window, &approve, |user, workspace, project_root| {
ide_agent::mcp::apply_save(user, workspace, project_root.is_some(), input).map(|()| Vec::new())
})
}
/// Parses and saves one or more MCP servers from a pasted JSON snippet (`{"mcpServers": {...}}` or
/// single server object). Workspace servers explicitly saved here by the user are approved.
pub fn mcp_save_json(
host: &Host,
window: &str,
scope: McpScope,
raw_json: String,
fallback_name: Option<String>,
agents: Vec<String>,
) -> IdeResult<Vec<McpServer>> {
update_mcp_maps(host, window, &[], |user, workspace, project_root| {
let saved = ide_agent::mcp::apply_save_json(
user,
workspace,
project_root.is_some(),
scope,
&raw_json,
fallback_name.as_deref(),
agents,
)?;
Ok(if scope == McpScope::Workspace { saved } else { Vec::new() })
})
}
/// Enables or disables an MCP server and returns the updated list.
pub fn mcp_set_enabled(host: &Host, window: &str, id: String, enabled: bool) -> IdeResult<Vec<McpServer>> {
let approve = ide_agent::mcp::parse_server_id(&id)
let approve: Vec<String> = ide_agent::mcp::parse_server_id(&id)
.filter(|(scope, _)| enabled && *scope == McpScope::Workspace)
.map(|(_, name)| name.to_owned());
update_mcp_maps(host, window, approve.as_deref(), |user, workspace, _| {
ide_agent::mcp::apply_set_enabled(user, workspace, &id, enabled).map(|_| ())
.map(|(_, name)| name.to_owned())
.into_iter()
.collect();
update_mcp_maps(host, window, &approve, |user, workspace, _| {
ide_agent::mcp::apply_set_enabled(user, workspace, &id, enabled).map(|_| Vec::new())
})
}
/// Removes a User or Workspace MCP server and returns the updated list.
pub fn mcp_remove(host: &Host, window: &str, id: String) -> IdeResult<Vec<McpServer>> {
update_mcp_maps(host, window, None, |user, workspace, _| {
ide_agent::mcp::apply_remove(user, workspace, &id).map(|_| ())
update_mcp_maps(host, window, &[], |user, workspace, _| {
ide_agent::mcp::apply_remove(user, workspace, &id).map(|_| Vec::new())
})
}
/// Copies MCP servers from `.mcp.json` and `.vscode/mcp.json` into the workspace settings once;
/// they stay off until the user turns them on.
pub fn mcp_import(host: &Host, window: &str) -> IdeResult<Vec<McpServer>> {
update_mcp_maps(host, window, None, |_, workspace, project_root| {
update_mcp_maps(host, window, &[], |_, workspace, project_root| {
let root = project_root.ok_or_else(|| "Open a project to import workspace MCP servers".to_string())?;
ide_agent::mcp::apply_import(workspace, root);
Ok(())
Ok(Vec::new())
})
}
/// Discovers external MCP configuration files on disk (CLI user configs + workspace `.mcp.json`).
pub async fn mcp_discover_sources(host: &Host, window: &str) -> IdeResult<Vec<McpExternalSource>> {
let project_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
let home = dirs::home_dir();
tokio::task::spawn_blocking(move || {
ide_agent::mcp::discover_external_sources(home.as_deref(), project_root.as_deref())
})
.await
.map_err(|e| IdeError::internal(e.to_string()))
}
/// Imports selected servers from discovered external MCP configuration files into User or Workspace scope.
/// Imported Workspace entries remain unapproved (disabled) until the user explicitly enables them.
pub async fn mcp_import_selected(
host: &Host,
window: &str,
scope: McpScope,
selections: Vec<McpImportSelection>,
overwrite: bool,
) -> IdeResult<Vec<McpServer>> {
let home = dirs::home_dir();
update_mcp_maps(host, window, &[], move |user, workspace, project_root| {
ide_agent::mcp::apply_import_selected(
user,
workspace,
home.as_deref(),
project_root,
scope,
&selections,
overwrite,
)?;
Ok(Vec::new())
})
}
/// Tests an MCP server by connecting (`initialize`) and listing its tools (`tools/list`).
pub async fn mcp_test(host: &Host, window: &str, id: String) -> IdeResult<McpProbeResult> {
host.require_trust(window)?;
let (user, workspace, project) = mcp_maps(host, window);
let (scope, name) = ide_agent::mcp::parse_server_id(&id)
.ok_or_else(|| IdeError::not_found(format!("MCP server `{id}` not found")))?;
let server = match scope {
McpScope::User => user.get(name),
McpScope::Workspace => workspace.get(name),
}
.cloned()
.ok_or_else(|| IdeError::not_found(format!("MCP server `{name}` not found")))?;
if scope == McpScope::Workspace {
let p = project.as_ref().ok_or_else(|| IdeError::invalid("Open a project to test workspace MCP servers"))?;
if !host.mcp_approvals.approved(&p.root, name, &server) {
return Err(IdeError::invalid("Enable this workspace MCP server first before testing it"));
}
}
let cwd = project.as_ref().map(|p| p.root.clone()).or_else(dirs::home_dir).unwrap_or_else(std::env::temp_dir);
match server.transport {
McpTransport::Stdio => Ok(ide_agent::mcp::probe_stdio_server(&server, &cwd).await),
McpTransport::Http | McpTransport::Sse => Ok(probe_http_mcp_server(&server).await),
}
}
async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> McpProbeResult {
let started = std::time::Instant::now();
let elapsed_ms = || u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
let Some(url) = server.url.as_deref().map(str::trim).filter(|u| !u.is_empty()) else {
return McpProbeResult {
ok: false,
server_name: None,
server_version: None,
protocol_version: None,
tools: Vec::new(),
duration_ms: elapsed_ms(),
error: Some("URL is empty".into()),
};
};
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
reqwest::header::ACCEPT,
reqwest::header::HeaderValue::from_static("application/json, text/event-stream"),
);
for (k, v) in &server.headers {
if let (Ok(name), Ok(val)) =
(reqwest::header::HeaderName::from_bytes(k.as_bytes()), reqwest::header::HeaderValue::from_str(v))
{
headers.insert(name, val);
}
}
let client =
match reqwest::Client::builder().default_headers(headers).timeout(std::time::Duration::from_secs(12)).build() {
Ok(c) => c,
Err(e) => {
return McpProbeResult {
ok: false,
server_name: None,
server_version: None,
protocol_version: None,
tools: Vec::new(),
duration_ms: elapsed_ms(),
error: Some(format!("HTTP client error: {e}")),
};
}
};
let post_rpc = |session_id: Option<String>, body: serde_json::Value| {
let client = client.clone();
let url = url.to_owned();
async move {
let mut req =
client.post(&url).header(reqwest::header::CONTENT_TYPE, "application/json").body(body.to_string());
if let Some(sid) = session_id.as_deref() {
req = req.header("Mcp-Session-Id", sid);
}
let resp = req.send().await.map_err(|e| format!("Request to `{url}` failed: {e}"))?;
let status = resp.status();
let next_session =
resp.headers().get("mcp-session-id").and_then(|v| v.to_str().ok()).map(str::to_owned).or(session_id);
let text = resp.text().await.map_err(|e| format!("Failed reading response: {e}"))?;
if !status.is_success() {
let detail = text.trim();
let msg = if detail.is_empty() {
format!("HTTP {status}")
} else {
format!("HTTP {status}: {}", detail.chars().take(240).collect::<String>())
};
return Err(msg);
}
Ok((next_session, parse_mcp_http_response(&text)?))
}
};
let init_req = serde_json::json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": { "name": "OpenIDEA", "version": env!("CARGO_PKG_VERSION") },
}
});
let (session_id, init_res) = match post_rpc(None, init_req).await {
Ok(v) => v,
Err(err) => {
return McpProbeResult {
ok: false,
server_name: None,
server_version: None,
protocol_version: None,
tools: Vec::new(),
duration_ms: elapsed_ms(),
error: Some(err),
};
}
};
// Best-effort `notifications/initialized` + `tools/list`.
let mut not_req = client.post(url).header(reqwest::header::CONTENT_TYPE, "application/json").body(
serde_json::json!({
"jsonrpc": "2.0",
"method": "notifications/initialized",
"params": {},
})
.to_string(),
);
if let Some(sid) = session_id.as_deref() {
not_req = not_req.header("Mcp-Session-Id", sid);
}
let _ = not_req.send().await;
let tools_res = post_rpc(
session_id,
serde_json::json!({
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
"params": {},
}),
)
.await
.map(|(_, v)| v)
.unwrap_or_else(|_| serde_json::json!({}));
ide_agent::mcp::parse_probe_payloads(&init_res, &tools_res, elapsed_ms())
}
fn parse_mcp_http_response(body: &str) -> Result<serde_json::Value, String> {
let trimmed = body.trim();
if trimmed.is_empty() {
return Ok(serde_json::json!({}));
}
if let Ok(msg) = serde_json::from_str::<serde_json::Value>(trimmed) {
if let Some(err) = msg.get("error") {
let em = err.get("message").and_then(serde_json::Value::as_str).unwrap_or("JSON-RPC error");
return Err(em.to_owned());
}
return Ok(msg.get("result").cloned().unwrap_or(msg));
}
// Streamable HTTP SSE frames (`data: {...}`).
for line in trimmed.lines() {
if let Some(rest) = line.strip_prefix("data:")
&& let Ok(msg) = serde_json::from_str::<serde_json::Value>(rest.trim())
&& (msg.get("result").is_some() || msg.get("error").is_some())
{
if let Some(err) = msg.get("error") {
let em = err.get("message").and_then(serde_json::Value::as_str).unwrap_or("JSON-RPC error");
return Err(em.to_owned());
}
return Ok(msg.get("result").cloned().unwrap_or(msg));
}
}
Err("Unexpected non-JSON MCP response".into())
}
/// Updates per-session MCP server enable/disable overrides on task `task`.
pub fn set_mcp_overrides(
host: &Host,
window: &str,
task: String,
overrides: std::collections::BTreeMap<String, bool>,
) -> IdeResult<AgentTask> {
host.project(window)?.agents.set_mcp_overrides(&task, overrides)
}
/// Commands of this module the remote server answers.
pub(crate) fn register(d: &mut Dispatcher) {
d.add("agent_subscribe", |c| async move { subscribe(&c.host, &c.window, c.channel("onEvent")?) });
@@ -587,12 +852,23 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("agent_registry_remove", |c| async move { registry_remove(&c.host, &c.window, c.arg("id")?).await });
d.add("agent_mcp_list", |c| async move { mcp_list(&c.host, &c.window) });
d.add("agent_mcp_save", |c| async move { mcp_save(&c.host, &c.window, c.arg("input")?) });
d.add("agent_mcp_save_json", |c| async move {
mcp_save_json(&c.host, &c.window, c.arg("scope")?, c.arg("rawJson")?, c.arg("fallbackName")?, c.arg("agents")?)
});
d.add(
"agent_mcp_set_enabled",
|c| async move { mcp_set_enabled(&c.host, &c.window, c.arg("id")?, c.arg("enabled")?) },
);
d.add("agent_mcp_remove", |c| async move { mcp_remove(&c.host, &c.window, c.arg("id")?) });
d.add("agent_mcp_import", |c| async move { mcp_import(&c.host, &c.window) });
d.add("agent_mcp_discover_sources", |c| async move { mcp_discover_sources(&c.host, &c.window).await });
d.add("agent_mcp_import_selected", |c| async move {
mcp_import_selected(&c.host, &c.window, c.arg("scope")?, c.arg("selections")?, c.arg("overwrite")?).await
});
d.add("agent_mcp_test", |c| async move { mcp_test(&c.host, &c.window, c.arg("id")?).await });
d.add("agent_set_mcp_overrides", |c| async move {
set_mcp_overrides(&c.host, &c.window, c.arg("task")?, c.arg("overrides")?)
});
d.add("agent_commands", |c| async move { commands(&c.host, &c.window, c.arg("provider")?, c.arg("task")?).await });
d.add("agent_entries", |c| async move { entries(&c.host, &c.window, c.arg("task")?, c.arg("subagent")?) });
d.add("agent_create", |c| async move { create(&c.host, &c.window, c.arg("request")?).await });
+151
Переглянути файл
@@ -1173,6 +1173,122 @@ pub async fn lsp_hierarchy_refactor(
.await
}
/// The signature of the method at `pos`, for Change Signature.
pub async fn lsp_signature_info(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
pos: Pos,
) -> IdeResult<MethodSignature> {
let project = host.project(window)?;
let cancel = host.begin_request(request);
let result = project.lsp.change_signature_info(doc, pos, cancel).await;
host.end_request(request);
result
}
/// Checks changing the method at `pos` to `signature` and computes the edit without applying it.
#[allow(clippy::too_many_arguments)]
pub async fn lsp_change_signature(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
pos: Pos,
signature: MethodSignature,
delegate: bool,
confirmation: Option<String>,
) -> IdeResult<ServerRefactored> {
let project = host.project(window)?;
let documents = project.documents.clone();
let version = blocking(move || documents.version(doc)).await?;
let cancel = host.begin_request(request);
let result = project.lsp.change_signature(doc, pos, signature, delegate, confirmation, cancel).await;
host.end_request(request);
let mut changed = result?;
blocking(move || {
if project.documents.version(doc)? != version {
return Err(ide_core::IdeError::new(
ide_core::error::ErrorKind::OutOfSync,
"document changed while computing the refactoring; request it again",
));
}
if let Some(edit) = &mut changed.edit {
project.documents.prepare_workspace_edit(edit)?;
}
Ok(changed)
})
.await
}
fn json_argument(args: &str) -> IdeResult<serde_json::Value> {
serde_json::from_str(args).map_err(|e| IdeError::invalid(format!("invalid move arguments: {e}")))
}
fn json_strings(values: Vec<serde_json::Value>) -> Vec<String> {
values.iter().map(serde_json::Value::to_string).collect()
}
/// Where a Java Move code action of `kind` can go; `args` (JSON) carries the code action's own
/// arguments back unchanged, and each destination comes back as JSON.
pub async fn lsp_java_move_destinations(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
kind: String,
args: String,
) -> IdeResult<Vec<String>> {
let args = json_argument(&args)?;
let project = host.project(window)?;
let cancel = host.begin_request(request);
let result = project.lsp.java_move_destinations(doc, kind, args, cancel).await;
host.end_request(request);
result.map(json_strings)
}
/// The project's Java source types, for moving a member or type into a class.
pub async fn lsp_java_source_types(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
project_name: Option<String>,
) -> IdeResult<Vec<String>> {
let project = host.project(window)?;
let cancel = host.begin_request(request);
let result = project.lsp.java_source_types(doc, project_name, cancel).await;
host.end_request(request);
result.map(json_strings)
}
/// Checks a Java move and computes its edit without applying it.
#[allow(clippy::too_many_arguments)]
pub async fn lsp_java_move(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
kind: String,
args: String,
confirmation: Option<String>,
) -> IdeResult<ServerRefactored> {
let args = json_argument(&args)?;
let project = host.project(window)?;
let cancel = host.begin_request(request);
let result = project.lsp.java_move(doc, kind, args, confirmation, cancel).await;
host.end_request(request);
let mut moved = result?;
blocking(move || {
if let Some(edit) = &mut moved.edit {
project.documents.prepare_workspace_edit(edit)?;
}
Ok(moved)
})
.await
}
pub async fn lsp_rename(
host: &Host,
window: &str,
@@ -1896,6 +2012,41 @@ pub(crate) fn register(d: &mut Dispatcher) {
)
.await
});
d.add("lsp_signature_info", |c| async move {
lsp_signature_info(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("pos")?).await
});
d.add("lsp_change_signature", |c| async move {
lsp_change_signature(
&c.host,
&c.window,
c.arg("request")?,
c.arg("doc")?,
c.arg("pos")?,
c.arg("signature")?,
c.arg("delegate")?,
c.arg("confirmation")?,
)
.await
});
d.add("lsp_java_move_destinations", |c| async move {
lsp_java_move_destinations(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("kind")?, c.arg("args")?)
.await
});
d.add("lsp_java_source_types", |c| async move {
lsp_java_source_types(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("projectName")?).await
});
d.add("lsp_java_move", |c| async move {
lsp_java_move(
&c.host,
&c.window,
c.arg("request")?,
c.arg("doc")?,
c.arg("kind")?,
c.arg("args")?,
c.arg("confirmation")?,
)
.await
});
d.add("lsp_format", |c| async move {
lsp_format(&c.host, &c.window, c.arg("doc")?, c.arg("range")?, c.arg("options")?).await
});
+4
Переглянути файл
@@ -547,9 +547,13 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
| "agent_registry_remove"
| "agent_mcp_list"
| "agent_mcp_save"
| "agent_mcp_save_json"
| "agent_mcp_set_enabled"
| "agent_mcp_remove"
| "agent_mcp_import"
| "agent_mcp_discover_sources"
| "agent_mcp_import_selected"
| "agent_set_mcp_overrides"
| "coverage_import"
| "system_font_families"
| "user_font_data"
+2
Переглянути файл
@@ -22,7 +22,9 @@ pub(crate) mod configuration;
mod formatter;
mod hierarchy;
pub(crate) mod jvm_inspect;
mod move_refactoring;
pub(crate) mod reserved_names;
mod signature;
pub use formatter::configure_formatter;
/// First start imports the Maven / Gradle model, which can take minutes.
const READY_TIMEOUT: Duration = Duration::from_secs(240);
+116
Переглянути файл
@@ -0,0 +1,116 @@
//! Move (F6) through jdtls' own requests. jdtls offers Move as code actions whose command the
//! client runs (`java.action.applyRefactoringCommand` with `moveFile`, `moveType`,
//! `moveStaticMember` or `moveInstanceMethod`); the UI picks the destination from
//! `java/getMoveDestinations` or `java/searchSymbols` and `java/move` checks the move and
//! computes the edit, which the UI applies itself. Requests carry the code action's own
//! arguments back unchanged.
use super::COMMAND_TIMEOUT;
use super::signature::{RefactorEdit, changed};
use crate::types::ServerRefactored;
use crate::{LspManager, convert};
use ide_core::{CancellationToken, DocId, IdeError, IdeResult};
use serde_json::{Value, json};
const FEATURE: &str = "Move";
/// What `java/getMoveDestinations` and `java/move` accept as `moveKind`.
const KINDS: [&str; 6] =
["moveResource", "moveInstanceMethod", "moveStaticMember", "moveTypeToNewFile", "moveTypeToClass", "moveType"];
fn move_params(kind: &str, request: &Value) -> IdeResult<Value> {
if !KINDS.contains(&kind) {
return Err(IdeError::invalid(format!("unknown move kind `{kind}`")));
}
let mut params = json!({
"moveKind": kind,
"sourceUris": request.get("sourceUris").cloned().unwrap_or(json!([])),
"params": request.get("params").cloned().unwrap_or(Value::Null),
});
if let Some(destination) = request.get("destination").filter(|d| !d.is_null()) {
params["destination"] = destination.clone();
}
Ok(params)
}
impl LspManager {
/// Where the move of `kind` can go (packages, or the fields and parameters an instance
/// method can move to); an invalid-input error carries jdtls' reason when there is none.
pub async fn java_move_destinations(
&self,
doc: DocId,
kind: String,
request: Value,
cancel: CancellationToken,
) -> IdeResult<Vec<Value>> {
let (_, t) = self.jdtls_target(doc, FEATURE).await?;
let params = move_params(&kind, &request)?;
let answer: Value = self.call(&t, "java/getMoveDestinations", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if let Some(message) = answer.get("errorMessage").and_then(Value::as_str).filter(|m| !m.is_empty()) {
return Err(IdeError::invalid(message.to_owned()));
}
Ok(answer.get("destinations").and_then(Value::as_array).cloned().unwrap_or_default())
}
/// The project's source types (`java/searchSymbols`), for moving a member or type into a class.
pub async fn java_source_types(
&self,
doc: DocId,
project: Option<String>,
cancel: CancellationToken,
) -> IdeResult<Vec<Value>> {
let (_, t) = self.jdtls_target(doc, FEATURE).await?;
let params = json!({ "query": "*", "projectName": project, "sourceOnly": true });
let answer: Option<Vec<Value>> =
self.call(&t, "java/searchSymbols", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
Ok(answer.unwrap_or_default())
}
/// Checks the move and computes the edit without applying it; `confirmation` accepts the
/// warnings an earlier check returned with it.
pub async fn java_move(
&self,
doc: DocId,
kind: String,
request: Value,
confirmation: Option<String>,
cancel: CancellationToken,
) -> IdeResult<ServerRefactored> {
let (_, t) = self.jdtls_target(doc, FEATURE).await?;
let mut params = move_params(&kind, &request)?;
params["updateReferences"] = json!(true);
if let Some(token) = confirmation {
params["confirmationToken"] = json!(token);
}
let answer: Option<RefactorEdit> = self.call(&t, "java/move", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let conv = self.conv(t.enc());
Ok(changed(answer.unwrap_or_default(), |e| convert::workspace_edit(&conv, e)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn passes_the_code_action_arguments_back_for_known_kinds_only() {
let request = json!({
"sourceUris": ["file:///p/A.java"],
"params": { "textDocument": { "uri": "file:///p/A.java" } },
"destination": { "displayName": "com.example" },
});
let params = move_params("moveResource", &request).unwrap();
assert_eq!(params["moveKind"], "moveResource");
assert_eq!(params["sourceUris"][0], "file:///p/A.java");
assert_eq!(params["destination"]["displayName"], "com.example");
assert!(move_params("moveResource", &json!({})).unwrap().get("destination").is_none());
assert!(move_params("deleteEverything", &request).is_err());
}
}
+181
Переглянути файл
@@ -0,0 +1,181 @@
//! Change Signature through jdtls' own requests: `java/getChangeSignatureInfo` reads the method at
//! a position, `java/getRefactorEdit` (`changeSignature`) checks the new signature and computes the
//! edit. The UI edits the signature and applies the edit itself.
use super::{COMMAND_TIMEOUT, SERVER};
use crate::types::{MethodSignature, ProblemSeverity, RefactoringProblem, ServerRefactored};
use crate::{DocSnap, LspManager, Target, convert};
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Pos};
use serde::Deserialize;
use serde_json::{Value, json};
const FEATURE: &str = "Change Signature";
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Info {
#[serde(flatten)]
signature: Option<MethodSignature>,
error_message: Option<String>,
}
#[derive(Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct RefactorEdit {
edit: Option<lsp_types::WorkspaceEdit>,
error_message: Option<String>,
confirmation_token: Option<String>,
}
/// A `java/getRefactorEdit` or `java/move` answer as the result: an error message alone is fatal;
/// with a confirmation token it lists warnings to accept before the edit is computed.
pub(super) fn changed(
answer: RefactorEdit,
convert_edit: impl FnOnce(lsp_types::WorkspaceEdit) -> ide_core::WorkspaceEdit,
) -> ServerRefactored {
let problem = |severity| {
answer
.error_message
.as_deref()
.filter(|m| !m.trim().is_empty())
.map(|message| RefactoringProblem { severity, message: message.trim().to_owned() })
};
if let Some(token) = answer.confirmation_token {
return ServerRefactored {
problems: problem(ProblemSeverity::Warning).into_iter().collect(),
edit: None,
confirmation: Some(token),
};
}
match answer.edit {
Some(edit) if answer.error_message.is_none() => {
ServerRefactored { problems: Vec::new(), edit: Some(convert_edit(edit)), confirmation: None }
}
_ => ServerRefactored {
problems: problem(ProblemSeverity::Fatal).into_iter().collect(),
edit: None,
confirmation: None,
},
}
}
impl LspManager {
pub(super) async fn jdtls_target(&self, doc: DocId, feature: &str) -> IdeResult<(DocSnap, Target)> {
let (snap, targets) = self.doc_targets(doc, feature, |_| true).await?;
let t = targets
.into_iter()
.find(|t| t.server.name == SERVER)
.ok_or_else(|| IdeError::unavailable(format!("{feature} needs the Java language server (jdtls)")))?;
Ok((snap, t))
}
fn signature_context(snap: &DocSnap, t: &Target, pos: Pos) -> Value {
let at = snap.position(t, pos);
json!({
"textDocument": { "uri": snap.uri },
"range": { "start": at, "end": at },
"context": { "diagnostics": [] },
})
}
/// The signature of the method at `pos`; an invalid-input error says why it can't be changed.
pub async fn change_signature_info(
&self,
doc: DocId,
pos: Pos,
cancel: CancellationToken,
) -> IdeResult<MethodSignature> {
let (snap, t) = self.jdtls_target(doc, FEATURE).await?;
let params = Self::signature_context(&snap, &t, pos);
let info: Option<Info> =
self.call(&t, "java/getChangeSignatureInfo", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
match info {
Some(Info { error_message: Some(message), .. }) => Err(IdeError::invalid(message)),
Some(Info { signature: Some(signature), .. }) => Ok(signature),
_ => Err(IdeError::invalid("Caret should be on a method declaration")),
}
}
/// Checks changing the method at `pos` to `signature` and computes the edit without applying it.
/// `confirmation` accepts the warnings an earlier check returned with it.
pub async fn change_signature(
&self,
doc: DocId,
pos: Pos,
signature: MethodSignature,
delegate: bool,
confirmation: Option<String>,
cancel: CancellationToken,
) -> IdeResult<ServerRefactored> {
let (snap, t) = self.jdtls_target(doc, FEATURE).await?;
let MethodSignature { method_identifier, modifier, return_type, method_name, parameters, exceptions } =
signature;
let mut params = json!({
"command": "changeSignature",
"context": Self::signature_context(&snap, &t, pos),
"options": { "tabSize": 4, "insertSpaces": true },
"commandArguments": [
method_identifier, delegate, method_name, modifier, return_type, parameters, exceptions, false
],
});
if let Some(token) = confirmation {
params["confirmationToken"] = json!(token);
}
let answer: Option<RefactorEdit> =
self.call(&t, "java/getRefactorEdit", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let answer = answer.unwrap_or_default();
let conv = self.conv(t.enc());
Ok(changed(answer, |e| convert::workspace_edit(&conv, e)))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn answer(v: Value) -> RefactorEdit {
serde_json::from_value(v).unwrap()
}
fn no_edit(_: lsp_types::WorkspaceEdit) -> ide_core::WorkspaceEdit {
ide_core::WorkspaceEdit::default()
}
#[test]
fn reads_the_signature_or_why_there_is_none() {
let info: Info = serde_json::from_value(json!({
"methodIdentifier": "=p/src<p{A.java[A~m~I",
"modifier": "public",
"returnType": "void",
"methodName": "m",
"parameters": [{ "type": "int", "name": "a", "defaultValue": "null", "originalIndex": 0 }],
"exceptions": [{ "type": "java.io.IOException", "typeHandleIdentifier": "=x" }],
"errorMessage": null,
}))
.unwrap();
let s = info.signature.unwrap();
assert_eq!((s.method_name.as_str(), s.parameters[0].type_name.as_str()), ("m", "int"));
assert_eq!(s.exceptions[0].type_name, "java.io.IOException");
let refused: Info = serde_json::from_value(json!({ "errorMessage": "Cannot change signature." })).unwrap();
assert!(refused.signature.is_none());
assert_eq!(refused.error_message.as_deref(), Some("Cannot change signature."));
}
#[test]
fn errors_are_fatal_and_tokens_ask_for_confirmation() {
let fatal = changed(answer(json!({ "errorMessage": "Duplicate parameter name" })), no_edit);
assert_eq!(fatal.problems[0].severity, ProblemSeverity::Fatal);
assert!(fatal.edit.is_none() && fatal.confirmation.is_none());
let warn = changed(answer(json!({ "errorMessage": "Overrides a method", "confirmationToken": "t1" })), no_edit);
assert_eq!(warn.problems[0].severity, ProblemSeverity::Warning);
assert_eq!(warn.confirmation.as_deref(), Some("t1"));
let ok = changed(answer(json!({ "edit": { "changes": {} } })), no_edit);
assert!(ok.problems.is_empty() && ok.edit.is_some());
}
}
+45
Переглянути файл
@@ -504,6 +504,51 @@ pub struct HierarchyRefactored {
pub edit: Option<WorkspaceEdit>,
}
/// A parameter in Change Signature: its type, name, the value passed at existing calls when it is
/// added, and its index in the current signature (-1 for an added one).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SignatureParameter {
#[serde(rename = "type")]
pub type_name: String,
pub name: String,
pub default_value: String,
pub original_index: i32,
}
/// A declared exception (`throws`), with the server's handle of its type.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SignatureException {
#[serde(rename = "type")]
pub type_name: String,
pub type_handle_identifier: String,
}
/// The signature of the method at a position, as Change Signature edits it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MethodSignature {
/// The server's handle of the method, passed back unchanged.
pub method_identifier: String,
/// `public`, `protected`, `private`, or empty for package-private.
pub modifier: String,
pub return_type: String,
pub method_name: String,
pub parameters: Vec<SignatureParameter>,
pub exceptions: Vec<SignatureException>,
}
/// A refactoring checked by the server (Change Signature, Move): problems to show, the edit when
/// none is fatal, and the token that confirms going on despite warnings.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ServerRefactored {
pub problems: Vec<RefactoringProblem>,
pub edit: Option<WorkspaceEdit>,
pub confirmation: Option<String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CallHierarchy {
+9
Переглянути файл
@@ -121,6 +121,15 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
**Settings › Tools › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
### External MCP servers
**Settings › Agents › External MCP Servers** configures MCP servers across three persistent levels, while the composer's **MCP** picker (or `/mcp`) controls them per session:
- **Global (`User`)**: saved in `settings.toml` with environment variable and HTTP header values stored in the OS credential store, shared across projects and agents (or scoped to selected agents).
- **Project (`Workspace`)**: saved in `.openidea/settings.toml`; entries with the same name override Global servers, and servers added outside OpenIDEA stay off until approved.
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json`, `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
- **Per-session (`MCP` / `/mcp`)**: in both **New Agent Task** and active task conversations, open **MCP** in the composer toolbar (or run `/mcp`) to enable or disable individual servers—including the built-in `openidea` server—for that task only, or click **Reset** to return to the inherited defaults.
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply. **Settings › Agents › Working Status** can show playful words for what it does there instead; they are off by default. Once turned on, they take turns from the moment the work changes, or only after the agent reports nothing new for a number of seconds (0 to 600, 0 by default); screen readers still hear what the agent is doing. Each word stays eight seconds while the agent keeps at the same work, and at least three when it moves on, so the line doesn't flicker. The same page replaces the words: pick what the status says (**Reading…**, **Running a command…**…) and add or remove its words. **Restore Built-in Words** brings back OpenIDEA's; an activity left without words keeps its plain status.
## Add a custom agent
+3
Переглянути файл
@@ -52,6 +52,7 @@ Language servers that support LSP inline completion show a grey suggestion at th
| **Go to Type Declaration** | `⇧⌘B` | `Ctrl+Shift+B` |
| **Super Method** | `⌘U` | `Ctrl+U` |
| **Navigate › Test** | `⇧⌘T` | `Ctrl+Shift+T` |
| **Navigate › Related Symbol…** | `⌃⌘↑` | `Ctrl+Alt+Home` |
| **Back** / **Forward** | `⌘[` / `⌘]` | `Ctrl+Alt+Left` / `Ctrl+Alt+Right` |
| **Next Method** / **Previous Method** | `⌃⇧↓` / `⌃⇧↑` | `Alt+Down` / `Alt+Up` |
@@ -59,6 +60,8 @@ Language servers that support LSP inline completion show a grey suggestion at th
- Hold `⌘` / `Ctrl` and hover over a name to see it underlined as a link, with brief information about it.
- Gutter icons mark types and methods that are implemented or overridden (↓) and methods that implement or override another (↑). Click one to go there.
- **Navigate › Test** jumps between a class and its tests by naming convention and offers **Create New Test…** when there is none.
- **Navigate › Related Symbol…** goes to the files tied to the current one by convention: a C, C++ or Objective-C header and its source file, and in Rails a controller action and its views, a view and its action, a controller and its helper and model, a model and its controller and migrations. With several targets it shows a chooser.
- In Rails, **Go to Declaration** also follows method symbols in callbacks (`before_action :load_user`, `if: :admin?`) to their `def`, and controller actions in `config/routes.rb` (`to: "users#index"`, `resources :users`) to the controller.
Going to files, classes and symbols by name is covered in [Search and navigation](/en/guide/search).
+7 -3
Переглянути файл
@@ -18,7 +18,7 @@ The **Refactor** menu has IntelliJ IDEA's refactorings with their usual shortcut
| Refactoring | macOS | Windows / Linux | Works through |
| ------------------------ | ----- | --------------- | ------------------------------------------------------ |
| **Rename…** | `⇧F6` | `Shift+F6` | Language server; local variables also without one |
| **Change Signature…** | `⌘F6` | `Ctrl+F6` | Language server |
| **Change Signature…** | `⌘F6` | `Ctrl+F6` | Java (dialog); other languages: language server |
| **Introduce Variable…** | `⌥⌘V` | `Ctrl+Alt+V` | Language server; simple cases also without one |
| **Introduce Constant…** | `⌥⌘C` | `Ctrl+Alt+C` | Language server; simple cases also without one |
| **Introduce Field…** | `⌥⌘F` | `Ctrl+Alt+F` | Language server |
@@ -63,7 +63,7 @@ When the language server cannot help, Introduce Variable and Introduce Constant
In the Project view, **Rename…** (`⇧F6` / `Shift+F6`), **Move…** (`F6`, drag and drop, or cut and paste) and **Copy…** (`F5`, copy and paste, or `⌥`-drag / `Alt`-drag) open a dialog. With **Search for references** on, references to the file are updated through the language servers that support it (for example imports in TypeScript); **Search in comments and strings** also looks there. The changes are shown in a preview first.
In the editor, **Move…** on a symbol runs the server's move refactoring, where the language has one.
In the editor, **Move…** on a symbol runs the server's move refactoring, where the language has one. In Java it asks where to: a top-level class goes to another package (its package declaration, imports and every reference follow), a static member or nested class to another class, an instance method to the class of one of its fields or parameters; warnings are confirmed in **Problems Detected** first.
## Safe Delete
@@ -82,6 +82,10 @@ In the editor, **Move…** on a symbol runs the server's move refactoring, where
These move fields and methods between a class and its superclasses or subclasses, in Java and, with Phoxite as the PHP server, in PHP (methods, properties and constants). A dialog lets you pick the members and the destination; problems the move would cause are listed in **Problems Detected** before you continue. For Java they are provided by the extension bundled with OpenIDEA, for PHP by Phoxite; they are not available for other languages or other PHP servers.
## Change Signature
In Java, **Change Signature…** (`⌘F6`) on a method opens a dialog to change its visibility, return type and name, and to add, remove and reorder its parameters. A new parameter needs a default value, which is passed at every existing call; **Delegate via overloading method** keeps the old signature as an overload that calls the new one. The preview line shows the resulting declaration. **Refactor** updates the method, its overrides and all calls in one step; **Preview** lists the changes first. In other languages it appears when the server offers a signature rewrite as a code action.
## Undo
A refactoring is one undo step, even when it changed several files. After a multi-file refactoring, a notification offers **Undo** (and then **Redo**).
@@ -89,5 +93,5 @@ A refactoring is one undo step, even when it changed several files. After a mult
## Limits
- Refactorings other than Rename, Safe Delete and the syntax-based fallbacks need a running language server that offers them. Check the **Language Services** widget in the status bar if one is missing.
- Change Signature appears only when the server offers a signature rewrite as a code action.
- Outside Java, Change Signature appears only when the server offers a signature rewrite as a code action.
- There is no structural search-and-replace refactoring in this menu; see **Edit › Find › Replace Structurally…** in [Inspections](/en/guide/inspections).
+1
Переглянути файл
@@ -38,6 +38,7 @@ Some shortcuts depend on where the focus is. For example `⌘N` / `Alt+Insert` i
| Go to Type Declaration | `⇧⌘B` / `⌃⇧B` | `Ctrl+Shift+B` |
| Navigate › Super Method | `⌘U` | `Ctrl+U` |
| Navigate › Test | `⇧⌘T` | `Ctrl+Shift+T` |
| Navigate › Related Symbol… | `⌃⌘↑` | `Ctrl+Alt+Home` |
| Find Usages | `⌥F7` | `Alt+F7` |
| Show Usages | `⌥⌘F7` | `Ctrl+Alt+F7` |
| Highlight Usages in File | `⇧⌘F7` | `Ctrl+Shift+F7` |
+9
Переглянути файл
@@ -121,6 +121,15 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
**设置 › 工具 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
### 外部 MCP 服务器
**设置 › 智能体 › 外部 MCP 服务器** 按三个持久层级管理 MCP 服务器,输入框底部的 **MCP** 选择器(或 `/mcp` 命令)则按单个会话控制它们:
- **全局(`用户`)**:保存在 `settings.toml` 中,环境变量与 HTTP 请求头的值保存在系统凭据存储里,跨项目与各智能体共享(也可限定给选定的智能体)。
- **项目(`工作区`)**:保存在 `.openidea/settings.toml` 中,同名服务器覆盖全局配置;在 OpenIDEA 外部写入的项目服务器在批准启用前保持关闭。
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
- **按会话覆盖(`MCP` / `/mcp`)**:在 **新建 Agent 任务** 和进行中的任务对话中,单击输入框工具栏的 **MCP**(或输入 `/mcp`),即可仅针对当前任务开启或关闭任意服务器(包括内置的 `openidea` 服务器),或点击 **重置** 恢复继承的默认状态。
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。在 **设置 › 智能体 › 工作状态** 中可以让这里改为显示与当前工作相关的趣味文字,默认关闭。开启后,工作一变化就轮换显示,也可以设置在 agent 无新进展多少秒后才显示(0 到 600,默认 0);屏幕阅读器读出的仍是 agent 实际在做的事。agent 持续做同一类工作时,每条文字停留八秒;转向其他工作时也至少停留三秒,状态行不会频繁跳动。同一页面还可以替换这些文字:选择状态(**正在读取…**、**正在运行命令…**…),再添加或移除对应的文字。**恢复内置文字** 会换回 OpenIDEA 自带的文字;没有任何文字的状态只显示实际进展。
## 添加自定义 agent
+3
Переглянути файл
@@ -52,6 +52,7 @@ description: "代码补全、导航、查找用法、文档、层次结构与文
| **转到类型声明** | `⇧⌘B` | `Ctrl+Shift+B` |
| **超方法** | `⌘U` | `Ctrl+U` |
| **导航 › 测试** | `⇧⌘T` | `Ctrl+Shift+T` |
| **导航 › 相关符号…** | `⌃⌘↑` | `Ctrl+Alt+Home` |
| **后退** / **前进** | `⌘[` / `⌘]` | `Ctrl+Alt+Left` / `Ctrl+Alt+Right` |
| **下一个方法** / **上一个方法** | `⌃⇧↓` / `⌃⇧↑` | `Alt+Down` / `Alt+Up` |
@@ -59,6 +60,8 @@ description: "代码补全、导航、查找用法、文档、层次结构与文
- 按住 `⌘` / `Ctrl` 把鼠标悬停在名称上,名称会显示为链接,并附带简要信息。
- 装订区域的图标标出被实现或被重写的类型和方法(↓),以及实现或重写了其他方法的方法(↑),单击即可跳转。
- **导航 › 测试** 按命名约定在类和它的测试之间跳转;还没有测试时会提供 **创建新测试…**。
- **导航 › 相关符号…** 跳到按约定与当前文件相关的文件:C、C++、Objective-C 的头文件和源文件,以及 Rails 中控制器动作与其视图、视图与其动作、控制器与其辅助模块和模型、模型与其控制器和迁移。有多个目标时显示选择列表。
- 在 Rails 中,**转到声明** 还能从回调里的方法符号(`before_action :load_user`、`if: :admin?`)跳到对应的 `def`,从 `config/routes.rb` 里的控制器动作(`to: "users#index"`、`resources :users`)跳到控制器。
按名称跳转到文件、类和符号,见 [搜索与导航](/zh/guide/search)。
+7 -3
Переглянути файл
@@ -18,7 +18,7 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
| 重构 | macOS | Windows / Linux | 实现方式 |
| ------------- | ----- | --------------- | --------------------------------------- |
| **重命名…** | `⇧F6` | `Shift+F6` | 语言服务器;局部变量没有服务器也可以 |
| **更改签名…** | `⌘F6` | `Ctrl+F6` | 语言服务器 |
| **更改签名…** | `⌘F6` | `Ctrl+F6` | Java(对话框);其他语言:语言服务器 |
| **引入变量…** | `⌥⌘V` | `Ctrl+Alt+V` | 语言服务器;简单情况没有服务器也可以 |
| **引入常量…** | `⌥⌘C` | `Ctrl+Alt+C` | 语言服务器;简单情况没有服务器也可以 |
| **引入字段…** | `⌥⌘F` | `Ctrl+Alt+F` | 语言服务器 |
@@ -58,7 +58,7 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
在项目视图中,**重命名…**(`⇧F6` / `Shift+F6`)、**移动…**(`F6`、拖放或剪切后粘贴)和 **复制…**(`F5`、复制后粘贴,或按住 `⌥` / `Alt` 拖动)会打开对话框。勾选 **搜索引用** 后,支持此功能的语言服务器会更新对该文件的引用(例如 TypeScript 的 import);**在注释和字符串中搜索** 会把注释和字符串也算进去。改动会先显示预览。
在编辑器中对符号执行 **移动…**,会调用该语言服务器的移动重构(如果有的话)。
在编辑器中对符号执行 **移动…**,会调用该语言服务器的移动重构(如果有的话)。在 Java 中会先询问目标:顶层类移动到其他包(包声明、import 和所有引用随之更新),静态成员或嵌套类移动到其他类,实例方法移动到其某个字段或形参的类;有警告时先在 **检测到问题** 中确认。
## 安全删除
@@ -75,6 +75,10 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
用于在类和它的父类或子类之间移动字段和方法:支持 Java,以及使用 Phoxite 作为 PHP 服务器时的 PHP(方法、属性和常量)。在对话框中选择成员和目标类;移动会引起的问题会先在 **检测到问题** 中列出,再决定是否继续。Java 由 OpenIDEA 自带的扩展提供,PHP 由 Phoxite 提供;其他语言和其他 PHP 服务器不可用。
## 更改签名
在 Java 方法上执行 **更改签名…**(`⌘F6`)会打开对话框,可以修改可见性、返回类型和方法名,添加、删除和调整形参顺序。新形参需要填写默认值,所有已有调用处都会传入这个值;勾选 **通过重载方法委托** 会保留旧签名作为重载并调用新方法。签名预览显示修改后的声明。**重构** 会一次更新方法本身、覆盖它的方法和所有调用;**预览** 先列出改动。其他语言在服务器把签名重写作为代码操作提供时才会出现。
## 撤销
一次重构就是一步撤销,即使它改了多个文件。多文件重构完成后,通知中会提供 **撤消**(撤销后变为 **重做**)。
@@ -82,5 +86,5 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
## 限制
- 除了重命名、安全删除和基于语法树的兜底实现,其他重构都需要语言服务器运行并提供相应功能。缺少时先看状态栏的 **语言服务** 微件。
- 只有当服务器把签名重写作为代码操作提供时,才会出现更改签名。
- 除 Java 外,只有当服务器把签名重写作为代码操作提供时,才会出现更改签名。
- 这个菜单里没有结构化搜索替换;见 [代码检查](/zh/guide/inspections) 中的 **编辑 › 查找 › 结构化替换…**。
+1
Переглянути файл
@@ -38,6 +38,7 @@ macOS 符号:`⌘` Command、`⌥` Option、`⌃` Control、`⇧` Shift、`↵
| 转到类型声明 | `⇧⌘B` / `⌃⇧B` | `Ctrl+Shift+B` |
| 导航 › super 方法 | `⌘U` | `Ctrl+U` |
| 导航 › 测试 | `⇧⌘T` | `Ctrl+Shift+T` |
| 导航 › 相关符号… | `⌃⌘↑` | `Ctrl+Alt+Home` |
| 查找用法 | `⌥F7` | `Alt+F7` |
| 显示用法 | `⌥⌘F7` | `Ctrl+Alt+F7` |
| 高亮文件中的用法 | `⇧⌘F7` | `Ctrl+Shift+F7` |
+344
Переглянути файл
@@ -0,0 +1,344 @@
import type {
AgentEntry,
AgentProvider,
AgentTask,
McpExternalSource,
McpProbeResult,
McpServer,
} from "../src/bindings";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const copilotProvider: AgentProvider = {
id: "copilot",
name: "GitHub Copilot",
command: "copilot",
program: "copilot",
args: [],
defaultProgram: "copilot",
defaultArgs: [],
loginHint: null,
commandOverridden: false,
commandEditable: true,
commandReadOnlyReason: null,
installed: true,
env: {},
commands: [],
source: { kind: "builtin" },
config: [
{
id: "model",
category: "model",
name: "Model",
description: null,
current: "claude-sonnet-4.6",
via: "option",
values: [{ value: "claude-sonnet-4.6", name: "Claude Sonnet 4.6", description: null }],
},
{
id: "mode",
category: "mode",
name: "Mode",
description: null,
current: "agent",
via: "option",
values: [
{ value: "agent", name: "Agent", description: null },
{ value: "plan", name: "Plan", description: null },
],
},
],
thoughtLevels: {},
};
const sampleTask: AgentTask = {
id: "mcp-session-1",
title: "Investigate authentication service latency",
provider: "copilot",
status: "ready",
isolation: "local",
model: "claude-sonnet-4.6",
cwd: "/dev/acme-api",
branch: "main",
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: copilotProvider.config,
commands: [],
usage: null,
queue: [],
mcpOverrides: {},
};
const initialServers: McpServer[] = [
{
id: "user::github-mcp-server",
name: "github-mcp-server",
scope: "user",
transport: "http",
enabled: true,
command: null,
args: [],
env: [],
url: "https://api.githubcopilot.com/mcp/",
headers: [{ name: "Authorization", value: "Bearer ***" }],
agents: [],
unapproved: false,
},
{
id: "user::slack-official",
name: "slack-official",
scope: "user",
transport: "stdio",
enabled: true,
command: "npx",
args: ["-y", "mcp-remote", "https://mcp.slack.com/mcp"],
env: [],
url: null,
headers: [],
agents: [],
unapproved: false,
},
{
id: "workspace::postgres-local",
name: "postgres-local",
scope: "workspace",
transport: "stdio",
enabled: true,
command: "npx",
args: ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/acme"],
env: [{ name: "PGPASSWORD", value: "***" }],
url: null,
headers: [],
agents: [],
unapproved: false,
},
];
const discoveredSources: McpExternalSource[] = [
{
id: "copilot-cli",
label: "GitHub Copilot CLI",
path: "/Users/dev/.copilot/mcp-config.json",
suggestedScope: "user",
nativeProvider: "copilot",
servers: [
{
name: "workiq",
transport: "stdio",
enabled: true,
command: "npx",
args: ["-y", "@microsoft/workiq", "mcp"],
url: null,
envKeys: [],
headerKeys: [],
},
{
name: "datadog",
transport: "http",
enabled: true,
command: null,
args: [],
url: "https://mcp.datadoghq.com/api/unstable/mcp-server/mcp",
envKeys: [],
headerKeys: ["DD-API-KEY"],
},
],
},
{
id: "jetbrains-air",
label: "JetBrains Air",
path: "/Users/dev/.jetbrains/mcp/mcp.json",
suggestedScope: "user",
nativeProvider: null,
servers: [
{
name: "linear",
transport: "stdio",
enabled: true,
command: "npx",
args: ["-y", "mcp-remote", "https://mcp.linear.app/mcp"],
url: null,
envKeys: [],
headerKeys: [],
},
],
},
];
const probeResult: McpProbeResult = {
ok: true,
serverName: "github-mcp-server",
serverVersion: "0.18.2",
protocolVersion: "2024-11-05",
durationMs: 68,
error: null,
tools: [
{ name: "search_issues", description: "Search issues across GitHub repositories using semantic matching" },
{ name: "pull_request_read", description: "Read pull request details, diff, reviews, and CI check runs" },
{ name: "list_commits", description: "List commits on a branch in a GitHub repository" },
],
};
test("manages multi-level MCP servers in Settings and per-session overrides via Composer /mcp", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1280, height: 840 });
await stubDesktop(page);
await page.evaluate(
async ({ copilotProvider, sampleTask, initialServers, discoveredSources, probeResult }) => {
const storeModule = "/src/features/agents/store.ts";
const store = await import(/* @vite-ignore */ storeModule);
const projectModule = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const prevSettings = useProject.getState().settings ?? {};
useProject.setState({
settings: {
...prevSettings,
mcpServer: { ...(prevSettings as { mcpServer?: object }).mcpServer, enabled: true },
} as never,
});
let servers = structuredClone(initialServers);
let currentTask = structuredClone(sampleTask);
const entries: AgentEntry[] = [
{ type: "user", text: "Can you check why p95 latency spiked on /v1/token?", attachments: [] },
{
type: "agent",
text: "I inspected the token endpoint traces and local Postgres pool configuration. Ready for follow-up.",
},
];
const handlers = window.__ipc.handlers;
handlers.agent_subscribe = () => [currentTask];
handlers.agent_providers = () => [copilotProvider];
handlers.agent_refresh_models = () => ({
provider: copilotProvider.id,
config: copilotProvider.config,
thoughtLevels: {},
refreshing: false,
refreshedAtMs: Date.now(),
retryAtMs: null,
error: null,
});
handlers.agent_probe = () => null;
handlers.agent_commands = () => [];
handlers.agent_entries = () => entries;
handlers.agent_changes = () => [];
handlers.agent_grouped_changes = () => ({ uncommitted: [], commits: [] });
handlers.vcs_branch_info = () => ({ head: "main" });
handlers.vcs_branches = () => [];
handlers.agent_mcp_list = () => servers;
handlers.agent_mcp_discover_sources = () => discoveredSources;
handlers.agent_mcp_test = () => probeResult;
handlers.agent_mcp_set_enabled = ({ id, enabled }) => {
servers = servers.map((s) => (s.id === id ? { ...s, enabled: Boolean(enabled) } : s));
return servers;
};
handlers.agent_mcp_import_selected = ({ scope, selections }) => {
for (const sel of selections as Array<{ sourceId: string; name: string }>) {
const src = discoveredSources.find((d) => d.id === sel.sourceId);
const srv = src?.servers.find((d) => d.name === sel.name);
if (!srv) continue;
const id = `${String(scope)}::${srv.name}`;
if (!servers.some((s) => s.id === id)) {
servers = [
...servers,
{
id,
name: srv.name,
scope: scope as "user" | "workspace",
transport: srv.transport,
enabled: true,
command: srv.command,
args: srv.args,
env: [],
url: srv.url,
headers: [],
agents: [],
unapproved: false,
},
];
}
}
return servers;
};
handlers.agent_set_mcp_overrides = ({ overrides }) => {
currentTask = { ...currentTask, mcpOverrides: overrides as Record<string, boolean> };
return currentTask;
};
await store.connect();
store.openTask(currentTask.id);
},
{ copilotProvider, sampleTask, initialServers, discoveredSources, probeResult },
);
// 1. Open per-session MCP picker via `/mcp` in the active session composer.
const composerBox = page.getByRole("textbox", { name: "Message" });
await expect(composerBox).toBeVisible();
await composerBox.click();
await page.keyboard.type("/mc");
await expect(page.getByRole("listbox", { name: "Commands" })).toContainText("/mcp");
await page.keyboard.press("Enter");
const sessionPopup = page.getByRole("dialog", { name: "Session MCP Servers" });
await expect(sessionPopup).toBeVisible();
await expect(sessionPopup).toContainText("openidea");
await expect(sessionPopup).toContainText("postgres-local");
await expect(sessionPopup).toContainText("github-mcp-server");
await expect(sessionPopup).toContainText("workiq");
// Disable `slack-official` for this session only and verify IPC call + `Session` badge.
await sessionPopup.getByRole("switch", { name: "Enable slack-official for this session" }).click();
await expect(sessionPopup).toContainText("Session");
const overrideCalls = await ipcCalls(page, "agent_set_mcp_overrides");
expect(overrideCalls.at(-1)?.overrides).toEqual({ "slack-official": false });
const screenshotDir = process.env.CAPTURE_MCP_SCREENSHOTS;
if (screenshotDir) {
await page.screenshot({ path: `${screenshotDir}/mcp-session-picker.png` });
}
await sessionPopup.getByRole("button", { name: "Reset" }).click();
await expect(sessionPopup.getByRole("button", { name: "Reset" })).toHaveCount(0);
// 2. Jump directly from the session MCP popover's gear button to Settings › External MCP Servers.
await sessionPopup.getByRole("button", { name: "External MCP Servers…" }).click();
const settingsDialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(settingsDialog).toBeVisible();
await expect(settingsDialog.getByRole("heading", { name: "External MCP Servers" })).toBeVisible();
// Probe `github-mcp-server` and inspect discovered tools inside the expandable card.
await settingsDialog.getByRole("button", { name: "Test github-mcp-server" }).click();
await expect(settingsDialog.getByText("Tools (3)")).toBeVisible();
await expect(settingsDialog.getByText("pull_request_read")).toBeVisible();
if (screenshotDir) {
await settingsDialog
.getByRole("heading", { name: "External MCP Servers" })
.evaluate((el) => el.scrollIntoView({ block: "start" }));
await settingsDialog.screenshot({ path: `${screenshotDir}/mcp-hub-levels.png` });
await settingsDialog.getByRole("button", { name: "Add from JSON" }).click();
const addDialog = page.getByRole("dialog", { name: "Add MCP Server" });
await expect(addDialog).toBeVisible();
await addDialog.screenshot({ path: `${screenshotDir}/mcp-hub-add-json.png` });
await addDialog.getByRole("button", { name: "Cancel" }).click();
}
// Switch to `Agent Configs` tab and verify discovered Copilot CLI + JetBrains Air configs.
await settingsDialog.getByRole("tab", { name: /Agent Configs/ }).click();
await expect(settingsDialog.getByText("GitHub Copilot CLI")).toBeVisible();
await expect(settingsDialog.getByText("JetBrains Air")).toBeVisible();
if (screenshotDir) {
await settingsDialog.screenshot({ path: `${screenshotDir}/mcp-hub-agent-configs.png` });
}
await settingsDialog.getByRole("checkbox", { name: "Select linear" }).click();
await settingsDialog.getByRole("button", { name: "Import Selected (1)" }).click();
await expect(settingsDialog.getByText("Imported 1 MCP servers into Global settings.")).toBeVisible();
});
+3
Переглянути файл
@@ -36,6 +36,9 @@ bundles = []
# Library classes open as `jdt://` virtual documents (`java/classFileContents`).
classFileContentsSupport = true
resolveAdditionalTextEditsSupport = true
# Move (F6) code actions run the client-side refactoring command; the IDE asks for the
# destination and requests the edit (`java/getMoveDestinations`, `java/move`).
moveRefactoringSupport = true
[language-servers.initialization-options.settings.java]
autobuild = { enabled = true }
+59 -1
Переглянути файл
@@ -5,7 +5,8 @@ use ide_agent::registry::AgentRegistry;
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCommand, AgentEntry,
AgentEvent, AgentModelCatalog, AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentTask, CustomAgentInput,
ExternalSession, McpServer, McpServerInput, NewAgentTask,
ExternalSession, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput,
NewAgentTask,
};
use ide_core::{IdeResult, IpcPath, RequestId};
use ide_host::ops::agent;
@@ -174,6 +175,63 @@ pub fn agent_mcp_import(window: Window, state: State<'_, AppState>) -> IdeResult
agent::mcp_import(&state.host, window.label())
}
/// Parses and saves one or more MCP servers from a pasted JSON snippet (`{"mcpServers": {...}}` or
/// single server object).
#[tauri::command]
#[specta::specta]
pub fn agent_mcp_save_json(
window: Window,
state: State<'_, AppState>,
scope: McpScope,
raw_json: String,
fallback_name: Option<String>,
agents: Vec<String>,
) -> IdeResult<Vec<McpServer>> {
agent::mcp_save_json(&state.host, window.label(), scope, raw_json, fallback_name, agents)
}
/// Discovers external MCP configuration files on disk (CLI user configs + workspace `.mcp.json`).
#[tauri::command]
#[specta::specta]
pub async fn agent_mcp_discover_sources(
window: Window,
state: State<'_, AppState>,
) -> IdeResult<Vec<McpExternalSource>> {
agent::mcp_discover_sources(&state.host, window.label()).await
}
/// Imports selected servers from discovered external MCP configuration files into User or Workspace scope.
#[tauri::command]
#[specta::specta]
pub async fn agent_mcp_import_selected(
window: Window,
state: State<'_, AppState>,
scope: McpScope,
selections: Vec<McpImportSelection>,
overwrite: bool,
) -> IdeResult<Vec<McpServer>> {
agent::mcp_import_selected(&state.host, window.label(), scope, selections, overwrite).await
}
/// Tests an MCP server by connecting (`initialize`) and listing its tools (`tools/list`).
#[tauri::command]
#[specta::specta]
pub async fn agent_mcp_test(window: Window, state: State<'_, AppState>, id: String) -> IdeResult<McpProbeResult> {
agent::mcp_test(&state.host, window.label(), id).await
}
/// Updates per-session MCP server enable/disable overrides on `task`.
#[tauri::command]
#[specta::specta]
pub fn agent_set_mcp_overrides(
window: Window,
state: State<'_, AppState>,
task: String,
overrides: std::collections::BTreeMap<String, bool>,
) -> IdeResult<AgentTask> {
agent::set_mcp_overrides(&state.host, window.label(), task, overrides)
}
/// Slash commands to complete for `provider` in `task`'s directory, or in the project
/// before a task exists (skills and custom commands on disk included).
#[tauri::command]
+78
Переглянути файл
@@ -317,6 +317,84 @@ pub async fn lsp_hierarchy_refactor(
.await
}
#[tauri::command]
#[specta::specta]
pub async fn lsp_signature_info(
window: Window,
state: State<'_, AppState>,
request: RequestId,
doc: DocId,
pos: Pos,
) -> IdeResult<MethodSignature> {
ide_host::ops::lsp::lsp_signature_info(&state.host, window.label(), request, doc, pos).await
}
#[tauri::command]
#[specta::specta]
#[allow(clippy::too_many_arguments)]
pub async fn lsp_change_signature(
window: Window,
state: State<'_, AppState>,
request: RequestId,
doc: DocId,
pos: Pos,
signature: MethodSignature,
delegate: bool,
confirmation: Option<String>,
) -> IdeResult<ServerRefactored> {
ide_host::ops::lsp::lsp_change_signature(
&state.host,
window.label(),
request,
doc,
pos,
signature,
delegate,
confirmation,
)
.await
}
#[tauri::command]
#[specta::specta]
pub async fn lsp_java_move_destinations(
window: Window,
state: State<'_, AppState>,
request: RequestId,
doc: DocId,
kind: String,
args: String,
) -> IdeResult<Vec<String>> {
ide_host::ops::lsp::lsp_java_move_destinations(&state.host, window.label(), request, doc, kind, args).await
}
#[tauri::command]
#[specta::specta]
pub async fn lsp_java_source_types(
window: Window,
state: State<'_, AppState>,
request: RequestId,
doc: DocId,
project_name: Option<String>,
) -> IdeResult<Vec<String>> {
ide_host::ops::lsp::lsp_java_source_types(&state.host, window.label(), request, doc, project_name).await
}
#[tauri::command]
#[specta::specta]
#[allow(clippy::too_many_arguments)]
pub async fn lsp_java_move(
window: Window,
state: State<'_, AppState>,
request: RequestId,
doc: DocId,
kind: String,
args: String,
confirmation: Option<String>,
) -> IdeResult<ServerRefactored> {
ide_host::ops::lsp::lsp_java_move(&state.host, window.label(), request, doc, kind, args, confirmation).await
}
#[tauri::command]
#[specta::specta]
pub async fn lsp_format(
+10
Переглянути файл
@@ -137,9 +137,14 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
agent::agent_registry_remove,
agent::agent_mcp_list,
agent::agent_mcp_save,
agent::agent_mcp_save_json,
agent::agent_mcp_set_enabled,
agent::agent_mcp_remove,
agent::agent_mcp_import,
agent::agent_mcp_discover_sources,
agent::agent_mcp_import_selected,
agent::agent_mcp_test,
agent::agent_set_mcp_overrides,
agent::agent_commands,
agent::agent_entries,
agent::agent_create,
@@ -297,6 +302,11 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
lsp::lsp_rename,
lsp::lsp_hierarchy_members,
lsp::lsp_hierarchy_refactor,
lsp::lsp_signature_info,
lsp::lsp_change_signature,
lsp::lsp_java_move_destinations,
lsp::lsp_java_source_types,
lsp::lsp_java_move,
lsp::lsp_format,
lsp::lsp_inlay_hints,
lsp::lsp_semantic_tokens,
+1
Переглянути файл
@@ -466,6 +466,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("navigate.typeDeclaration", "Type Declaration"),
act("navigate.superMethod", "Super Method"),
act("navigate.gotoTest", "Test"),
act("navigate.relatedSymbol", "Related Symbol…"),
SEP,
act("navigate.fileStructure", "File Structure"),
act("navigate.showFilePath", "File Path"),
+10
Переглянути файл
@@ -17,11 +17,15 @@ agent_external_sessions trusted project_host bin
agent_fork trusted project_host bindings async
agent_grouped_changes trusted project_host bindings async
agent_import_session trusted project_host bindings async
agent_mcp_discover_sources always project_host bindings async
agent_mcp_import always project_host bindings sync
agent_mcp_import_selected always project_host bindings async
agent_mcp_list always project_host bindings sync
agent_mcp_remove always project_host bindings sync
agent_mcp_save always project_host bindings sync
agent_mcp_save_json always project_host bindings sync
agent_mcp_set_enabled always project_host bindings sync
agent_mcp_test trusted project_host bindings async
agent_probe trusted project_host bindings async
agent_prompt trusted project_host bindings async
agent_providers trusted project_host bindings sync
@@ -37,6 +41,7 @@ agent_send_queued_now trusted project_host bin
agent_set_command trusted project_host bindings sync
agent_set_config trusted project_host bindings async
agent_set_env trusted project_host bindings sync
agent_set_mcp_overrides always project_host bindings sync
agent_stop_background always project_host bindings async
agent_subscribe always project_host bindings sync
agent_unarchive always project_host bindings sync
@@ -292,6 +297,7 @@ log_frontend always desktop bin
lsp_apply_code_action trusted project_host bindings async
lsp_call_hierarchy trusted project_host bindings async
lsp_can_download_sources trusted project_host bindings async
lsp_change_signature trusted project_host bindings async
lsp_code_action_query trusted project_host bindings async
lsp_code_actions trusted project_host bindings async
lsp_code_lens trusted project_host bindings async
@@ -309,6 +315,9 @@ lsp_hover trusted project_host bin
lsp_implementations trusted project_host bindings async
lsp_inlay_hints trusted project_host bindings async
lsp_inline_completion trusted project_host bindings async
lsp_java_move trusted project_host bindings async
lsp_java_move_destinations trusted project_host bindings async
lsp_java_source_types trusted project_host bindings async
lsp_library_sources trusted project_host bindings async
lsp_prepare_rename trusted project_host bindings async
lsp_prepare_type_hierarchy trusted project_host bindings async
@@ -324,6 +333,7 @@ lsp_restart_named trusted desktop bin
lsp_semantic_tokens trusted project_host bindings async
lsp_servers always project_host bindings sync
lsp_signature_help trusted project_host bindings async
lsp_signature_info trusted project_host bindings async
lsp_type_hierarchy trusted project_host bindings async
lsp_virtual_document trusted project_host bindings async
lsp_workspace_symbols trusted project_host bindings async
+206 -15
Переглянути файл
@@ -145,7 +145,7 @@ export const commands = {
/** Routes frontend logs into the backend `tracing` pipeline. */
logFrontend: (level: LogLevel, message: string) => __TAURI_INVOKE<void>("log_frontend", { level, message }),
/** Streams the project's agent events to this window; returns every task. */
agentSubscribe: (onEvent: Channel<AgentEvent>) => typedError<AgentTask[], IdeError>(__TAURI_INVOKE("agent_subscribe", { onEvent })),
agentSubscribe: (onEvent: Channel<AgentEvent_Deserialize>) => typedError<AgentTask_Serialize[], IdeError>(__TAURI_INVOKE("agent_subscribe", { onEvent })),
agentProviders: () => typedError<AgentProvider[], IdeError>(__TAURI_INVOKE("agent_providers")),
/** Refreshes the model catalog; force bypasses freshness, not the cooldown. */
agentRefreshModels: (provider: string, force: boolean) => typedError<AgentModelCatalog, IdeError>(__TAURI_INVOKE("agent_refresh_models", { provider, force })),
@@ -184,12 +184,25 @@ export const commands = {
agentMcpList: () => typedError<McpServer[], IdeError>(__TAURI_INVOKE("agent_mcp_list")),
/** Creates or updates a User or Workspace MCP server and returns the updated list. */
agentMcpSave: (input: McpServerInput) => typedError<McpServer[], IdeError>(__TAURI_INVOKE("agent_mcp_save", { input })),
/**
* Parses and saves one or more MCP servers from a pasted JSON snippet (`{"mcpServers": {...}}` or
* single server object).
*/
agentMcpSaveJson: (scope: McpScope, rawJson: string, fallbackName: string | null, agents: string[]) => typedError<McpServer[], IdeError>(__TAURI_INVOKE("agent_mcp_save_json", { scope, rawJson, fallbackName, agents })),
/** Enables or disables an MCP server and returns the updated list. */
agentMcpSetEnabled: (id: string, enabled: boolean) => typedError<McpServer[], IdeError>(__TAURI_INVOKE("agent_mcp_set_enabled", { id, enabled })),
/** Removes a User or Workspace MCP server and returns the updated list. */
agentMcpRemove: (id: string) => typedError<McpServer[], IdeError>(__TAURI_INVOKE("agent_mcp_remove", { id })),
/** Copies MCP servers from `.mcp.json` and `.vscode/mcp.json` into the workspace settings once. */
agentMcpImport: () => typedError<McpServer[], IdeError>(__TAURI_INVOKE("agent_mcp_import")),
/** Discovers external MCP configuration files on disk (CLI user configs + workspace `.mcp.json`). */
agentMcpDiscoverSources: () => typedError<McpExternalSource[], IdeError>(__TAURI_INVOKE("agent_mcp_discover_sources")),
/** Imports selected servers from discovered external MCP configuration files into User or Workspace scope. */
agentMcpImportSelected: (scope: McpScope, selections: McpImportSelection[], overwrite: boolean) => typedError<McpServer[], IdeError>(__TAURI_INVOKE("agent_mcp_import_selected", { scope, selections, overwrite })),
/** Tests an MCP server by connecting (`initialize`) and listing its tools (`tools/list`). */
agentMcpTest: (id: string) => typedError<McpProbeResult, IdeError>(__TAURI_INVOKE("agent_mcp_test", { id })),
/** Updates per-session MCP server enable/disable overrides on `task`. */
agentSetMcpOverrides: (task: string, overrides: { [key in string]: boolean }) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_set_mcp_overrides", { task, overrides })),
/**
* Slash commands to complete for `provider` in `task`'s directory, or in the project
* before a task exists (skills and custom commands on disk included).
@@ -197,11 +210,11 @@ export const commands = {
agentCommands: (provider: string, task: string | null) => typedError<AgentCommand[], IdeError>(__TAURI_INVOKE("agent_commands", { provider, task })),
/** Entries of `task`'s conversation, or of its subagent `subagent`'s. */
agentEntries: (task: string, subagent: string | null) => typedError<AgentEntry[], IdeError>(__TAURI_INVOKE("agent_entries", { task, subagent })),
agentCreate: (request: NewAgentTask) => typedError<AgentTask, IdeError>(__TAURI_INVOKE("agent_create", { request })),
agentCreate: (request: NewAgentTask) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_create", { request })),
/** Sessions of the project on this machine that no task holds yet, newest first. */
agentExternalSessions: () => typedError<ExternalSession[], IdeError>(__TAURI_INVOKE("agent_external_sessions")),
/** Imports an external session as a task: its first turn loads and replays it. */
agentImportSession: (provider: string, sessionId: string) => typedError<AgentTask, IdeError>(__TAURI_INVOKE("agent_import_session", { provider, sessionId })),
agentImportSession: (provider: string, sessionId: string) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_import_session", { provider, sessionId })),
/** Sends a message; while the agent works it is queued, or with `now` it interrupts the turn. */
agentPrompt: (task: string, prompt: AgentPrompt, now: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("agent_prompt", { task, prompt, now })),
/** Drops a queued message and returns it (to edit it). */
@@ -211,12 +224,12 @@ export const commands = {
/** Changes a session setting (model, mode, thinking effort…). */
agentSetConfig: (task: string, option: string, value: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_set_config", { task, option, value })),
/** Copies the task's conversation into a new task, up to its first `turns` turns (all when `None`). */
agentFork: (task: string, turns: number | null) => typedError<AgentTask, IdeError>(__TAURI_INVOKE("agent_fork", { task, turns })),
agentFork: (task: string, turns: number | null) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_fork", { task, turns })),
/**
* Creates a temporary side conversation of `source`: lives in memory only, never
* persisted, not listed, and its session starts with the first message sent to it.
*/
agentCreateEphemeral: (request: NewAgentTask, source: string) => typedError<AgentTask, IdeError>(__TAURI_INVOKE("agent_create_ephemeral", { request, source })),
agentCreateEphemeral: (request: NewAgentTask, source: string) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_create_ephemeral", { request, source })),
/** Drops the task's turns after its first `turns`; returns the message of the first dropped one. */
agentRollback: (task: string, turns: number) => typedError<{
text: string,
@@ -629,6 +642,11 @@ export const commands = {
lspHierarchyMembers: (request: RequestId, doc: DocId, pos: Pos, kind: HierarchyRefactoring) => typedError<HierarchyMembers, IdeError>(__TAURI_INVOKE("lsp_hierarchy_members", { request, doc, pos, kind })),
/** Checks Pull Members Up / Push Members Down and computes the edit without applying it. */
lspHierarchyRefactor: (request: RequestId, doc: DocId, pos: Pos, kind: HierarchyRefactoring, target: string | null, choices: HierarchyChoice[]) => typedError<HierarchyRefactored, IdeError>(__TAURI_INVOKE("lsp_hierarchy_refactor", { request, doc, pos, kind, target, choices })),
lspSignatureInfo: (request: RequestId, doc: DocId, pos: Pos) => typedError<MethodSignature, IdeError>(__TAURI_INVOKE("lsp_signature_info", { request, doc, pos })),
lspChangeSignature: (request: RequestId, doc: DocId, pos: Pos, signature: MethodSignature, delegate: boolean, confirmation: string | null) => typedError<ServerRefactored, IdeError>(__TAURI_INVOKE("lsp_change_signature", { request, doc, pos, signature, delegate, confirmation })),
lspJavaMoveDestinations: (request: RequestId, doc: DocId, kind: string, args: string) => typedError<string[], IdeError>(__TAURI_INVOKE("lsp_java_move_destinations", { request, doc, kind, args })),
lspJavaSourceTypes: (request: RequestId, doc: DocId, projectName: string | null) => typedError<string[], IdeError>(__TAURI_INVOKE("lsp_java_source_types", { request, doc, projectName })),
lspJavaMove: (request: RequestId, doc: DocId, kind: string, args: string, confirmation: string | null) => typedError<ServerRefactored, IdeError>(__TAURI_INVOKE("lsp_java_move", { request, doc, kind, args, confirmation })),
lspFormat: (doc: DocId, range: {
start: Pos,
end: Pos,
@@ -2111,26 +2129,51 @@ form?: AgentForm | null;
chosen: string | null } | { type: "error"; message: string };
/** Streamed to the window that subscribed (`AgentManager::subscribe`). */
export type AgentEvent =
export type AgentEvent = AgentEvent_Serialize | AgentEvent_Deserialize;
/** Streamed to the window that subscribed (`AgentManager::subscribe`). */
export type AgentEvent_Deserialize =
/** A task was created or its metadata changed. */
{ type: "task"; task: AgentTask } | { type: "removed"; id: string } |
({ type: "task"; task: AgentTask_Deserialize }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; limits?: never; provider?: never; reason?: never; subagent?: never; text?: never } | ({ type: "removed"; id: string }) & { catalog?: never; entry?: never; eventId?: never; from?: never; index?: never; length?: never; limits?: never; provider?: never; reason?: never; subagent?: never; task?: never; text?: never } |
/** The task's conversation was cut to its first `length` entries (turns rolled back). */
{ type: "truncated"; task: string; length: number } |
({ type: "truncated"; task: string; length: number }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; limits?: never; provider?: never; reason?: never; subagent?: never; text?: never } |
/** Entry `index` of `task` (of its subagent `subagent`) was added or replaced. */
{ type: "entry"; task: string; subagent: string | null; index: number; entry: AgentEntry } |
({ type: "entry"; task: string; subagent: string | null; index: number; entry: AgentEntry }) & { catalog?: never; eventId?: never; from?: never; id?: never; length?: never; limits?: never; provider?: never; reason?: never; text?: never } |
/**
* Text was appended to entry `index` (an agent message or a thought): it read the first
* `from` UTF-16 units of its text when the previous event for it was sent.
*/
{ type: "append"; task: string; subagent: string | null; index: number; from: number; text: string } |
({ type: "append"; task: string; subagent: string | null; index: number; from: number; text: string }) & { catalog?: never; entry?: never; eventId?: never; id?: never; length?: never; limits?: never; provider?: never; reason?: never } |
/** An agent reported the usage limits of its account (shared by every task of `provider`). */
{ type: "limits"; provider: string; limits: AgentLimit[] } |
({ type: "limits"; provider: string; limits: AgentLimit[] }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; reason?: never; subagent?: never; task?: never; text?: never } |
/** A model lookup started or completed, including unsuccessful lookups. */
{ type: "modelCatalog"; catalog: AgentModelCatalog } |
({ type: "modelCatalog"; catalog: AgentModelCatalog }) & { entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; limits?: never; provider?: never; reason?: never; subagent?: never; task?: never; text?: never } |
/** The installed or configured agent providers changed. */
{ type: "providers" } |
({ type: "providers" }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; limits?: never; provider?: never; reason?: never; subagent?: never; task?: never; text?: never } |
/** The task needs attention once (finished turn, explicit input, or failure). */
{ type: "attention"; task: string; eventId: string; reason: AgentAttentionReason };
({ type: "attention"; task: string; eventId: string; reason: AgentAttentionReason }) & { catalog?: never; entry?: never; from?: never; id?: never; index?: never; length?: never; limits?: never; provider?: never; subagent?: never; text?: never };
/** Streamed to the window that subscribed (`AgentManager::subscribe`). */
export type AgentEvent_Serialize =
/** A task was created or its metadata changed. */
({ type: "task"; task: AgentTask_Serialize }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; limits?: never; provider?: never; reason?: never; subagent?: never; text?: never } | ({ type: "removed"; id: string }) & { catalog?: never; entry?: never; eventId?: never; from?: never; index?: never; length?: never; limits?: never; provider?: never; reason?: never; subagent?: never; task?: never; text?: never } |
/** The task's conversation was cut to its first `length` entries (turns rolled back). */
({ type: "truncated"; task: string; length: number }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; limits?: never; provider?: never; reason?: never; subagent?: never; text?: never } |
/** Entry `index` of `task` (of its subagent `subagent`) was added or replaced. */
({ type: "entry"; task: string; subagent: string | null; index: number; entry: AgentEntry }) & { catalog?: never; eventId?: never; from?: never; id?: never; length?: never; limits?: never; provider?: never; reason?: never; text?: never } |
/**
* Text was appended to entry `index` (an agent message or a thought): it read the first
* `from` UTF-16 units of its text when the previous event for it was sent.
*/
({ type: "append"; task: string; subagent: string | null; index: number; from: number; text: string }) & { catalog?: never; entry?: never; eventId?: never; id?: never; length?: never; limits?: never; provider?: never; reason?: never } |
/** An agent reported the usage limits of its account (shared by every task of `provider`). */
({ type: "limits"; provider: string; limits: AgentLimit[] }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; reason?: never; subagent?: never; task?: never; text?: never } |
/** A model lookup started or completed, including unsuccessful lookups. */
({ type: "modelCatalog"; catalog: AgentModelCatalog }) & { entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; limits?: never; provider?: never; reason?: never; subagent?: never; task?: never; text?: never } |
/** The installed or configured agent providers changed. */
({ type: "providers" }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; limits?: never; provider?: never; reason?: never; subagent?: never; task?: never; text?: never } |
/** The task needs attention once (finished turn, explicit input, or failure). */
({ type: "attention"; task: string; eventId: string; reason: AgentAttentionReason }) & { catalog?: never; entry?: never; from?: never; id?: never; index?: never; length?: never; limits?: never; provider?: never; subagent?: never; text?: never };
/** A form the agent asks the user to fill in (ACP `elicitation/create`, form mode). */
export type AgentForm = {
@@ -2478,7 +2521,9 @@ export type AgentSubagentStatus = "running" |
/** One of its requests (a permission) waits for an answer. */
"needsInput" | "done" | "cancelled" | "failed";
export type AgentTask = {
export type AgentTask = AgentTask_Serialize | AgentTask_Deserialize;
export type AgentTask_Deserialize = {
/** Original project folder; absent in tasks saved before per-task roots. */
projectRoot?: IpcPath | null,
id: string,
@@ -2522,6 +2567,56 @@ export type AgentTask = {
retry?: AgentRetry | null,
/** What the agent runs in the background (shells, subagents, monitors), oldest first. */
background?: AgentBackgroundTask[],
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */
mcpOverrides?: { [key in string]: boolean },
};
export type AgentTask_Serialize = {
/** Original project folder; absent in tasks saved before per-task roots. */
projectRoot: IpcPath | null,
id: string,
title: string,
/** [`AgentProvider::id`]. */
provider: string,
/** Model the task runs on (its `model` setting), when known. */
model: string | null,
status: AgentStatus,
isolation: Isolation,
/** Directory the agent works in (the worktree, or the project root). */
cwd: IpcPath,
/** Branch of the task's worktree. */
branch: string | null,
/** Branch (or revision) the worktree was created from. */
base: string | null,
/** Commit the task's changes are compared against (worktree tasks; local ones use `HEAD`). */
baseCommit: string | null,
/** Why the task failed, when it did. */
error: string | null,
createdMs: number | null,
updatedMs: number | null,
/**
* The session's settings (model, mode, thinking effort…) as last reported, with the
* user's choices applied.
*/
config: AgentConfigOption[],
/** Slash commands the agent offers. */
commands: AgentCommand[],
/** Context window use, when the agent reports it. */
usage: AgentUsage | null,
/** Messages waiting for the current turn to end, oldest first. */
queue: AgentQueued[],
capabilities: AgentCapabilities,
/** When a [`AgentStatus::Limited`] task's limit resets (ms since the epoch), if the agent said. */
resetsMs: number | null,
/**
* The agent is retrying a failed API request (connection lost, overloaded…); cleared
* by its next output or any status change.
*/
retry: AgentRetry | null,
/** What the agent runs in the background (shells, subagents, monitors), oldest first. */
background: AgentBackgroundTask[],
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */
mcpOverrides?: { [key in string]: boolean },
};
/** Token pricing (Credits per 1M tokens) and context window capacity for one tier. */
@@ -7646,12 +7741,59 @@ export type MavenSettings = {
delegateBuild?: boolean,
};
/** Summary of one server discovered inside an external MCP configuration file. */
export type McpDiscoveredServer = {
name: string,
transport: McpTransport,
enabled: boolean,
command: string | null,
args: string[],
url: string | null,
/** Environment variable names declared on this server (values stay on the host). */
envKeys: string[],
/** HTTP header names declared on this server (values stay on the host). */
headerKeys: string[],
};
/** An external MCP configuration file discovered on disk (user CLI config or workspace file). */
export type McpExternalSource = {
/** Stable source identifier (e.g. `"copilot-cli"`, `"jetbrains-air"`, `"claude-code"`, `"cursor"`, `"workspace-mcp"`, `"vscode-mcp"`). */
id: string,
/** Human-readable source label (e.g. `"GitHub Copilot CLI"`). */
label: string,
/** Absolute path of the discovered configuration file. */
path: IpcPath,
/** Suggested target scope when importing this source into OpenIDEA settings. */
suggestedScope: McpScope,
/** Agent provider ID this external CLI reads natively (`Some("copilot")`, `Some("claude")`, `Some("cursor")`, or `None`). */
nativeProvider: string | null,
/** Servers found inside this external configuration file (values omitted for safety; imported directly on the host). */
servers: McpDiscoveredServer[],
};
/** Selection of one server from an external MCP configuration source to import. */
export type McpImportSelection = {
sourceId: string,
name: string,
};
/** A named environment variable or HTTP header for an MCP server. */
export type McpKeyValue = {
name: string,
value: string,
};
/** Result of testing/probing an MCP server (`initialize` + `tools/list`). */
export type McpProbeResult = {
ok: boolean,
serverName: string | null,
serverVersion: string | null,
protocolVersion: string | null,
tools: McpToolSummary[],
durationMs: number,
error: string | null,
};
/** Where an MCP server configuration is stored (`settings.toml` vs `.openidea/settings.toml`). */
export type McpScope = "user" | "workspace";
@@ -7669,6 +7811,8 @@ export type McpServer = {
headers: McpKeyValue[],
/** Agent provider ids this server is enabled for; empty means enabled for all agents. */
agents?: string[],
/** True when this Workspace server was added outside OpenIDEA and has not been approved yet. */
unapproved?: boolean,
};
/** Payload for creating or updating a user or workspace MCP server. */
@@ -7742,6 +7886,12 @@ export type McpServerStatus = {
stdioCommand: string[],
};
/** One tool advertised by an MCP server during `tools/list`. */
export type McpToolSummary = {
name: string,
description: string | null,
};
/** Transport of an MCP server configured in Settings › Agents › MCP Servers. */
export type McpTransport = "stdio" | "http" | "sse";
@@ -7847,6 +7997,18 @@ export type MethodBody =
/** Anything else. */
{ kind: "other" };
/** The signature of the method at a position, as Change Signature edits it. */
export type MethodSignature = {
/** The server's handle of the method, passed back unchanged. */
methodIdentifier: string,
/** `public`, `protected`, `private`, or empty for package-private. */
modifier: string,
returnType: string,
methodName: string,
parameters: SignatureParameter[],
exceptions: SignatureException[],
};
/** Per-function totals (a recursive function's samples count once in `total`). */
export type MethodStat = {
frame: number,
@@ -7922,6 +8084,8 @@ export type NewAgentTask = {
isolation: Isolation,
/** Branch to start the worktree from; the current branch when `None`. */
base: string | null,
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`). */
mcpOverrides?: { [key in string]: boolean },
};
/** The approvals new agent tasks start with. */
@@ -9890,6 +10054,16 @@ export type ServerInfo = {
label?: string | null,
};
/**
* A refactoring checked by the server (Change Signature, Move): problems to show, the edit when
* none is fatal, and the token that confirms going on despite warnings.
*/
export type ServerRefactored = {
problems: RefactoringProblem[],
edit: WorkspaceEdit | null,
confirmation: string | null,
};
export type ServerStatus = "starting" | "ready" | "busy" | "crashed" | "stopped" | "missing" |
/**
* Not started: its configuration can't launch it (e.g. no JDK new enough);
@@ -10139,12 +10313,29 @@ export type Signature = {
parameters: ([number, number])[],
};
/** A declared exception (`throws`), with the server's handle of its type. */
export type SignatureException = {
type: string,
typeHandleIdentifier: string,
};
export type SignatureHelp = {
signatures: Signature[],
activeSignature: number,
activeParameter: number,
};
/**
* A parameter in Change Signature: its type, name, the value passed at existing calls when it is
* added, and its index in the current signature (-1 for an added one).
*/
export type SignatureParameter = {
type: string,
name: string,
defaultValue: string,
originalIndex: number,
};
/**
* Where the sizes of instances came from.
*
+1
Переглянути файл
@@ -917,6 +917,7 @@ export class EditorController implements SlotHost {
{ kind: "action", action: "navigate.implementation", label: "Implementation(s)" },
{ kind: "action", action: "navigate.typeDeclaration", label: "Type Declaration" },
{ kind: "action", action: "navigate.superMethod", label: "Super Method" },
{ kind: "action", action: "navigate.relatedSymbol", label: "Related Symbol…" },
{ kind: "action", action: "navigate.gotoTest", label: "Test" },
{ kind: "separator" },
{ kind: "action", action: "find.usages", label: "Find Usages" },
+9 -2
Переглянути файл
@@ -22,7 +22,7 @@ import { diagnosticsExtension, installDiagnosticsEvents } from "./diagnostics";
import { hoverExtension } from "./hover";
import { parameterTabKeys, signatureExtension } from "./signature";
import { navigationExtension } from "./navigation";
import { intentionsExtension } from "./intentions";
import { intentionsExtension, registerClientCommand } from "./intentions";
import { inlayExtension } from "./inlay";
import { inlineCompletionExtension, registerInlineCompletionActions } from "./inlineCompletion";
import { semanticExtension } from "./semantic";
@@ -42,7 +42,12 @@ import { DOCUMENTATION_WINDOW } from "./docs";
import { prefetchMarkdown } from "./markdown";
import { outsideProjectBanner } from "./outsideProject";
import { implementationGutter, registerNavigationActions } from "@/editor/navigation";
import { HierarchyDialog } from "@/editor/refactor";
import {
ChangeSignatureDialog,
HierarchyDialog,
JAVA_REFACTORING_COMMAND,
runJavaRefactoringCommand,
} from "@/editor/refactor";
export function lspExtensions(ctx: EditorDocContext): Extension[] {
return [
@@ -116,6 +121,8 @@ export function activate(): () => void {
registerEditorContribution({ id: "lsp.parameterTab", order: 95, extensions: () => parameterTabKeys }),
registerOverlay({ id: "editor-lsp.popups", component: LspPopups }),
registerOverlay({ id: "editor-lsp.hierarchyDialog", component: HierarchyDialog }),
registerOverlay({ id: "editor-lsp.changeSignatureDialog", component: ChangeSignatureDialog }),
registerClientCommand(JAVA_REFACTORING_COMMAND, runJavaRefactoringCommand),
registerEditorBanner(outsideProjectBanner),
registerStatusItem({ id: "editor-lsp.usagesStatus", align: "left", priority: 10, component: UsagesStatus }),
// IDEA's Documentation tool window: right side, listed once F1 moved documentation there.
+24
Переглянути файл
@@ -202,6 +202,28 @@ export async function applyQuickFix(view: EditorView) {
showHint(view, "No quick fixes available");
}
/**
* Commands a server leaves to the client (jdtls' `java.action.applyRefactoringCommand`, which
* opens a dialog or asks for a destination). A handler returns false for arguments it doesn't take.
*/
type ClientCommand = (view: EditorView, args: readonly unknown[]) => Promise<boolean>;
const clientCommands = new Map<string, ClientCommand>();
export function registerClientCommand(name: string, run: ClientCommand): () => void {
clientCommands.set(name, run);
return () => {
if (clientCommands.get(name) === run) clientCommands.delete(name);
};
}
function parseArgument(arg: string): unknown {
try {
return JSON.parse(arg);
} catch {
return arg;
}
}
export async function applyCodeAction(view: EditorView, action: EditorQuickFix) {
if ("run" in action) return action.run();
const doc = docOf(view);
@@ -210,6 +232,8 @@ export async function applyCodeAction(view: EditorView, action: EditorQuickFix)
showHint(view, action.disabledReason);
return;
}
const client = !action.edit && action.command ? clientCommands.get(action.command.command) : undefined;
if (client && (await client(view, action.command!.arguments.map(parseArgument)))) return;
const before = view.state.doc;
try {
if (!(await runInteractiveCodeAction(doc.doc, action))) return;
+31
Переглянути файл
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vitest";
import { counterpartNames, headerSourceItems, rankCounterparts } from "./headerSource";
describe("header / source counterparts", () => {
it("names the other side by stem", () => {
expect(counterpartNames("/p/src/foo.cpp")?.names).toContain("foo.h");
expect(counterpartNames("/p/src/foo.cpp")?.group).toBe("Header");
expect(counterpartNames("/p/include/foo.hpp")?.names).toEqual(expect.arrayContaining(["foo.cc", "foo.mm"]));
expect(counterpartNames("/p/include/foo.HPP")?.group).toBe("Source");
expect(counterpartNames("/p/main.rs")).toBeNull();
expect(counterpartNames("/p/Makefile")).toBeNull();
});
it("prefers the same folder, else the nearest", () => {
expect(rankCounterparts("/p/src/a/foo.cpp", ["/p/include/foo.h", "/p/src/a/foo.h", "/p/src/a/foo.hpp"])).toEqual([
"/p/src/a/foo.h",
"/p/src/a/foo.hpp",
]);
expect(rankCounterparts("/p/src/a/foo.cpp", ["/x/foo.h", "/p/include/foo.h", "/p/src/b/foo.h"])).toEqual([
"/p/src/b/foo.h",
"/p/include/foo.h",
"/x/foo.h",
]);
});
it("collects the matches of every counterpart name", async () => {
const files: Record<string, string[]> = { "foo.h": ["/p/foo.h"], "foo.hpp": ["/q/foo.hpp"] };
const items = await headerSourceItems("/p/foo.c", async (n) => files[n] ?? []);
expect(items).toEqual([{ path: "/p/foo.h", group: "Header" }]);
});
});
+53
Переглянути файл
@@ -0,0 +1,53 @@
/** Related Symbol for C, C++, Objective-C and CUDA: a header and its source files, by name. */
import type { RelatedItem } from "@/editor/relatedProviders";
import { tx } from "@/platform/i18n";
const HEADERS = ["h", "hh", "hpp", "hxx", "h++", "cuh"];
const SOURCES = ["c", "cc", "cpp", "cxx", "c++", "m", "mm", "cu"];
function split(path: string): { dir: string; stem: string; ext: string } | null {
const slash = path.lastIndexOf("/");
const name = path.slice(slash + 1);
const dot = name.lastIndexOf(".");
if (dot <= 0) return null;
return { dir: path.slice(0, slash), stem: name.slice(0, dot), ext: name.slice(dot + 1).toLowerCase() };
}
/** The file names whose stem matches `path`'s on the other side (header ↔ source), or none. */
export function counterpartNames(path: string): { names: string[]; group: string } | null {
const parts = split(path);
if (!parts) return null;
if (HEADERS.includes(parts.ext)) return { names: SOURCES.map((e) => `${parts.stem}.${e}`), group: tx("Source") };
if (SOURCES.includes(parts.ext)) return { names: HEADERS.map((e) => `${parts.stem}.${e}`), group: tx("Header") };
return null;
}
function sharedPrefix(a: string, b: string): number {
const x = a.split("/");
const y = b.split("/");
let n = 0;
while (n < x.length && n < y.length && x[n] === y[n]) n++;
return n;
}
/**
* The counterparts of `path` among `candidates`: those in its own folder when there are any
* (the pair to switch to), else all of them, nearest folders first.
*/
export function rankCounterparts(path: string, candidates: readonly string[]): string[] {
const dir = split(path)?.dir ?? "";
const unique = [...new Set(candidates)].filter((c) => c !== path);
const local = unique.filter((c) => split(c)?.dir === dir);
if (local.length) return local;
return unique.sort((a, b) => sharedPrefix(path, b) - sharedPrefix(path, a) || a.localeCompare(b));
}
export async function headerSourceItems(
path: string,
findNamed: (name: string) => Promise<string[]>,
): Promise<RelatedItem[]> {
const counterpart = counterpartNames(path);
if (!counterpart) return [];
const found = await Promise.all(counterpart.names.map((n) => findNamed(n).catch(() => [] as string[])));
return rankCounterparts(path, found.flat()).map((p) => ({ path: p, group: counterpart.group }));
}
+59 -4
Переглянути файл
@@ -1,6 +1,6 @@
/**
* Navigate › Test / Test Subject (⇧⌘T), Super Method (⌘U), Next / Previous
* Method (⌃⇧↓ / ⌃⇧↑). Editor-side like editor/lsp (whose popups it uses);
* Navigate › Test / Test Subject (⇧⌘T), Super Method (⌘U), Related Symbol (⌃⌘↑), Next /
* Previous Method (⌃⇧↓ / ⌃⇧↑). Editor-side like editor/lsp (whose popups it uses);
* the file templates are reached through the `templates.newFromTemplate` action.
*/
import { EditorSelection } from "@codemirror/state";
@@ -13,12 +13,14 @@ import { dedupeLocations, locationItems, navigateTo } from "@/editor/lsp/navigat
import { showHint } from "@/editor/lsp/hint";
import { registerActions, executeAction, type Action } from "@/platform/actions";
import { call, commands, isCancelled, type Location, type OutlineItem, type Pos } from "@/platform/ipc";
import { basename, useProject } from "@/platform/project";
import { basename, relativePath, useProject } from "@/platform/project";
import { currentRoots } from "@/platform/projectRoots";
import { isVirtualUri } from "@/platform/virtualDocs";
import { editorService } from "@/workbench/contributions";
import { fileIconName } from "@/ui";
import { registerRelatedProvider, relatedItems } from "@/editor/relatedProviders";
import { gotoTestOrSubject, type TestNavDeps } from "./gotoTest";
import { headerSourceItems } from "./headerSource";
import { projectPythonHierarchy, pythonSuperDeps } from "./pythonHierarchy";
import { baseName, memberAt, methodStop, superMethods, type SuperDeps } from "./structureNav";
import { tx } from "@/platform/i18n";
@@ -195,15 +197,68 @@ function editorAction(
};
}
/** Navigate › Related Symbol: one target opens, several open a chooser. */
async function gotoRelated(view: EditorView) {
const ctx = docOf(view);
if (!ctx || isVirtualUri(ctx.path)) return;
const head = view.state.selection.main.head;
const items = await relatedItems({
path: ctx.path,
language: ctx.language,
text: view.state.doc.toString(),
offset: head,
});
if (!items.length) {
showHint(view, tx("No related symbols"), { tone: "error" });
return;
}
const open = (item: (typeof items)[number]) =>
editorService().openFile(item.path, {
selection: item.line === undefined ? undefined : { line: item.line, col: item.col ?? 0 },
focus: true,
});
if (items.length === 1) {
await open(items[0]!);
return;
}
const root = useProject.getState().project?.root ?? "";
openPopup({
kind: "list",
anchor: caretAnchor(view, head),
title: tx("Choose Target"),
items: items.map((item, i) => {
const where = relativePath(root, item.path) + (item.line === undefined ? "" : `:${item.line + 1}`);
return {
id: `${i}`,
label: item.label ?? basename(item.path),
detail: `${item.group} · ${where}`,
icon: fileIconName(basename(item.path), item.path),
location: { path: item.path, line: item.line ?? 0 },
run: () => open(item),
};
}),
});
}
const findFilesNamed = async (name: string) => call(commands.findFilesNamed(name));
export function registerNavigationActions(): () => void {
return registerActions([
const unregisterHeaders = registerRelatedProvider((ctx) => headerSourceItems(ctx.path, findFilesNamed));
const unregister = registerActions([
editorAction("navigate.gotoTest", "Test", gotoTest, { keywords: ["go to test", "test subject", "create test"] }),
editorAction("navigate.superMethod", "Super Method", superMethod, {
keywords: ["go to super", "overridden", "parent"],
}),
editorAction("navigate.nextMethod", "Next Method", (v) => gotoMethod(v, 1)),
editorAction("navigate.previousMethod", "Previous Method", (v) => gotoMethod(v, -1)),
editorAction("navigate.relatedSymbol", "Related Symbol…", gotoRelated, {
keywords: ["go to related", "header", "source", "switch header source", "view", "controller"],
}),
]);
return () => {
unregister();
unregisterHeaders();
};
}
export { implementationGutter } from "./implementationGutter";
+111
Переглянути файл
@@ -0,0 +1,111 @@
.dialog [data-dialog-body] {
display: flex;
flex-direction: column;
overflow: hidden;
}
.body {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: 14px;
font-size: var(--fs-ui);
color: var(--fg);
}
.header {
flex: none;
display: grid;
grid-template-columns: 150px 1fr 1fr;
gap: var(--space-3);
}
.field {
flex: none;
display: flex;
flex-direction: column;
gap: var(--space-1-5);
min-width: 0;
}
.parameters {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
border: 1px solid var(--border);
border-radius: 4px;
}
.toolbar {
flex: none;
display: flex;
gap: var(--space-1);
padding: 2px 4px;
border-bottom: 1px solid var(--border);
}
.table {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
}
.head,
.row {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
align-items: center;
gap: var(--space-2);
padding: 0 8px;
min-height: var(--h-list-row);
}
.head {
color: var(--fg-muted);
border-bottom: 1px solid var(--border);
}
.rows {
flex: 1 1 auto;
min-height: 0;
overflow: auto;
}
.row:hover {
background: var(--bg-hover);
}
.row[aria-selected="true"] {
background: var(--bg-selected);
}
.preview {
margin: 0;
padding: 6px 8px;
border: 1px solid var(--border);
border-radius: 4px;
font-family: var(--font-mono);
font-size: var(--fs-code);
white-space: pre-wrap;
overflow-wrap: anywhere;
color: var(--fg);
background: var(--bg-input);
}
.busy {
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
color: var(--fg-muted);
}
.error {
flex: none;
color: var(--danger);
font-size: var(--fs-small);
overflow-wrap: anywhere;
}
+202
Переглянути файл
@@ -0,0 +1,202 @@
/** IDEA's Change Signature dialog for Java methods (`signature.ts`). */
import { useState } from "react";
import type { MethodSignature } from "@/bindings";
import { Checkbox, Dialog, IconButton, Input, Select, Spinner, T, Toolbar } from "@/ui";
import { useTx } from "@/platform/i18n";
import {
VISIBILITIES,
changeSignature,
newParameter,
parameterRow,
signatureChanged,
signatureProblem,
signatureText,
useSignatureDialog,
type ParameterRow,
type SignatureRequest,
} from "./signature";
import styles from "./ChangeSignatureDialog.module.css";
export function ChangeSignatureDialog() {
const request = useSignatureDialog((s) => s.request);
if (!request) return null;
return <ChangeSignatureDialogInner key={request.seq} request={request} />;
}
function ChangeSignatureDialogInner({ request }: { request: SignatureRequest }) {
const tx = useTx();
const { info } = request;
const [modifier, setModifier] = useState(info.modifier);
const [returnType, setReturnType] = useState(info.returnType);
const [methodName, setMethodName] = useState(info.methodName);
const [rows, setRows] = useState<ParameterRow[]>(() => info.parameters.map(parameterRow));
const [selected, setSelected] = useState(0);
const [delegate, setDelegate] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const signature: MethodSignature = {
...info,
modifier,
returnType: returnType.trim(),
methodName: methodName.trim(),
parameters: rows.map(({ key: _, ...p }) => ({ ...p, type: p.type.trim(), name: p.name.trim() })),
};
const problem = signatureProblem(signature);
const ready = !busy && !problem && signatureChanged(info, signature);
const current = Math.min(selected, rows.length - 1);
const close = () => {
useSignatureDialog.setState({ request: null });
request.view.focus();
};
const update = (key: number, change: Partial<ParameterRow>) =>
setRows((all) => all.map((r) => (r.key === key ? { ...r, ...change } : r)));
const add = () => {
setRows((all) => [...all, newParameter()]);
setSelected(rows.length);
};
const remove = () => {
if (current < 0) return;
setRows((all) => all.filter((_, i) => i !== current));
};
const move = (by: -1 | 1) => {
const to = current + by;
if (current < 0 || to < 0 || to >= rows.length) return;
setRows((all) => {
const next = [...all];
[next[current], next[to]] = [next[to]!, next[current]!];
return next;
});
setSelected(to);
};
const submit = async (preview: boolean) => {
if (!ready) return;
setBusy(true);
setError(null);
const outcome = await changeSignature(request, signature, delegate, preview);
if (useSignatureDialog.getState().request !== request) return;
setBusy(false);
if (outcome.status === "done") close();
else if (outcome.error) setError(outcome.error);
};
return (
<Dialog
open
onClose={close}
title="Change Signature"
className={styles.dialog}
width={640}
minHeight={380}
maxHeight={640}
resizable="both"
buttons={[
{ label: "Preview", role: "extra", disabled: !ready, onClick: () => void submit(true) },
{ label: "Refactor", role: "default", disabled: !ready, onClick: () => void submit(false) },
{ label: "Cancel", role: "cancel" },
]}
footerStart={
busy ? (
<span className={styles.busy}>
<Spinner size={12} />
<T>Checking for conflicts…</T>
</span>
) : undefined
}
>
<div className={styles.body}>
<div className={styles.header}>
<label className={styles.field}>
<T>Visibility:</T>
<Select
aria-label="Visibility"
value={modifier}
options={VISIBILITIES.map((v) => ({ value: v, label: v || tx("package-private") }))}
onChange={setModifier}
/>
</label>
<label className={styles.field}>
<T>Return type:</T>
<Input mono value={returnType} onChange={(e) => setReturnType(e.target.value)} />
</label>
<label className={styles.field}>
<T>Name:</T>
<Input mono autoFocus autoSelect value={methodName} onChange={(e) => setMethodName(e.target.value)} />
</label>
</div>
<div className={styles.parameters}>
<Toolbar aria-label={tx("Parameters")} className={styles.toolbar}>
<IconButton icon="plus" title={tx("Add")} onClick={add} />
<IconButton icon="minus" title={tx("Remove")} disabled={current < 0} onClick={remove} />
<IconButton icon="arrow-up" title={tx("Move Up")} disabled={current <= 0} onClick={() => move(-1)} />
<IconButton
icon="arrow-down"
title={tx("Move Down")}
disabled={current < 0 || current >= rows.length - 1}
onClick={() => move(1)}
/>
</Toolbar>
<div className={styles.table} role="table" aria-label={tx("Parameters")}>
<div className={styles.head} role="row">
<span role="columnheader">
<T>Type</T>
</span>
<span role="columnheader">
<T>Name</T>
</span>
<span role="columnheader">
<T>Default value</T>
</span>
</div>
<div className={styles.rows}>
{rows.map((row, i) => (
<div
key={row.key}
className={styles.row}
role="row"
aria-selected={i === current}
onFocusCapture={() => setSelected(i)}
>
<Input
mono
variant="bare"
aria-label={tx("Type")}
value={row.type}
autoFocus={row.originalIndex < 0 && !row.type}
onChange={(e) => update(row.key, { type: e.target.value })}
/>
<Input
mono
variant="bare"
aria-label={tx("Name")}
value={row.name}
onChange={(e) => update(row.key, { name: e.target.value })}
/>
<Input
mono
variant="bare"
aria-label={tx("Default value")}
value={row.originalIndex < 0 ? row.defaultValue : ""}
disabled={row.originalIndex >= 0}
onChange={(e) => update(row.key, { defaultValue: e.target.value })}
/>
</div>
))}
</div>
</div>
</div>
<Checkbox checked={delegate} onChange={setDelegate} label={<T>Delegate via overloading method</T>} />
<div className={styles.field}>
<T>Signature Preview</T>
<pre className={styles.preview}>{signatureText(signature)}</pre>
</div>
{(error ?? (signatureChanged(info, signature) ? problem : null)) && (
<span className={styles.error} role="alert">
{tx(error ?? problem!)}
</span>
)}
</div>
</Dialog>
);
}
+2
Переглянути файл
@@ -1,4 +1,6 @@
export { refactorThis, runRefactoring, showNothingHere } from "./refactorThis";
export { askUsagesDetected, fileUsages, safeDelete, viewUsages } from "./safeDelete";
export { startHierarchyRefactoring } from "./hierarchy";
export { ChangeSignatureDialog } from "./ChangeSignatureDialog";
export { JAVA_REFACTORING_COMMAND, runJavaRefactoringCommand } from "./javaMove";
export { HierarchyDialog } from "./HierarchyDialog";
+28
Переглянути файл
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import { packageRow, runJavaRefactoringCommand, targetTypes } from "./javaMove";
describe("java move", () => {
it("shows packages by name and marks the current one", () => {
expect(packageRow({ displayName: "com.example", path: "/app/src/main/java/com/example" })).toEqual({
label: "com.example",
detail: "/app/src/main/java/com/example",
current: false,
});
expect(packageRow({ displayName: "", isParentOfSelectedFile: true }).label).toBe("(default package)");
expect(packageRow({ isParentOfSelectedFile: true }).current).toBe(true);
});
it("offers every source type but the member's own, sorted by name", () => {
const types = [
{ name: "Order", containerName: "com.example.orders" },
{ name: "App", containerName: "com.example.orders" },
{ name: "Strings", containerName: "com.example.util" },
{ name: "" },
];
expect(targetTypes(types, new Set(["com.example.orders.App"])).map((t) => t.name)).toEqual(["Order", "Strings"]);
});
it("leaves commands it doesn't know to the server", async () => {
expect(await runJavaRefactoringCommand({} as never, ["extractInterface"])).toBe(false);
});
});
+256
Переглянути файл
@@ -0,0 +1,256 @@
/**
* Java Move (F6) and Change Signature from jdtls' client-side refactoring command
* (`java.action.applyRefactoringCommand`): Move asks for the destination (a package, a class,
* or the field or parameter an instance method moves to), then jdtls checks the move and
* computes the edit, which is applied as one change after its problems are confirmed.
*/
import type { EditorView } from "@codemirror/view";
import type { ServerRefactored } from "@/bindings";
import { whenSynced } from "@/editor/api";
import { docOf, isUnavailable, lspRequest } from "@/editor/lsp/lsp";
import { showHint } from "@/editor/lsp/hint";
import { caretAnchor, openPopup, type ListPopupItem } from "@/editor/lsp/popupStore";
import { tx } from "@/platform/i18n";
import { commands, isCancelled, nextRequestId, unavailableText } from "@/platform/ipc";
import { cannotPerform } from "./catalog";
import { applyEdit, confirmProblems, startChangeSignature } from "./signature";
export const JAVA_REFACTORING_COMMAND = "java.action.applyRefactoringCommand";
type Json = Record<string, unknown>;
const record = (v: unknown): Json => (v && typeof v === "object" ? (v as Json) : {});
const text = (v: unknown): string => (typeof v === "string" ? v : "");
/** The file of the code action's parameters. */
const sourceOf = (params: unknown): string[] => {
const uri = text(record(record(params).textDocument).uri);
return uri ? [uri] : [];
};
/** What a Move request sends: the code action's parameters, its file and the destination. */
export interface MoveRequest {
sourceUris: string[];
params: unknown;
destination?: unknown;
}
/** A package from `java/getMoveDestinations` (moveResource) as a chooser row. */
export function packageRow(p: Json): { label: string; detail: string; current: boolean } {
return {
label: text(p.displayName) || "(default package)",
detail: text(p.path),
current: !!p.isParentOfSelectedFile,
};
}
/** The classes a member or type can move into: every source type but its own and itself, by name. */
export function targetTypes(types: readonly unknown[], exclude: ReadonlySet<string>): Json[] {
return types
.map(record)
.filter((t) => {
const name = text(t.name);
const container = text(t.containerName);
return name && !exclude.has(container ? `${container}.${name}` : name);
})
.sort((a, b) => text(a.name).localeCompare(text(b.name)));
}
function errorText(e: unknown): string {
if (isUnavailable(e)) return unavailableText(e, "No language server available");
return e instanceof Error ? e.message : String(e);
}
function choose(view: EditorView, title: string, items: ListPopupItem[]) {
openPopup({ kind: "list", anchor: caretAnchor(view, view.state.selection.main.head), title, items });
}
/** Asks jdtls to move, confirming its warnings, and applies the edit. */
async function move(view: EditorView, kind: string, request: MoveRequest) {
const ctx = docOf(view);
if (!ctx) return;
let confirmation: string | null = null;
let moved: ServerRefactored;
try {
for (;;) {
await whenSynced(view);
const token: string | null = confirmation;
moved = await lspRequest(() =>
commands.lspJavaMove(nextRequestId(), ctx.doc, kind, JSON.stringify(request), token),
);
const fatal = moved.problems.find((p) => p.severity === "fatal");
if (fatal || (!moved.edit && !moved.confirmation)) {
showHint(view, cannotPerform(fatal?.message ?? "Nothing to change"));
return;
}
if (!moved.confirmation) break;
if (!(await confirmProblems(moved.problems.map((p) => p.message)))) return;
confirmation = moved.confirmation;
}
} catch (e) {
if (!isCancelled(e)) showHint(view, cannotPerform(errorText(e)));
return;
}
await applyEdit(view, moved.edit!);
}
async function destinations(view: EditorView, kind: string, request: MoveRequest): Promise<Json[] | null> {
const ctx = docOf(view);
if (!ctx) return null;
try {
const found = await lspRequest(() =>
commands.lspJavaMoveDestinations(nextRequestId(), ctx.doc, kind, JSON.stringify(request)),
);
return found.map((d) => record(JSON.parse(d)));
} catch (e) {
if (!isCancelled(e)) showHint(view, cannotPerform(errorText(e)));
return null;
}
}
async function chooseClass(view: EditorView, title: string, info: Json, exclude: Set<string>, run: (t: Json) => void) {
const ctx = docOf(view);
if (!ctx) return;
let types: unknown[];
try {
const project = text(info.projectName) || null;
const found = await lspRequest(() => commands.lspJavaSourceTypes(nextRequestId(), ctx.doc, project));
types = found.map((t) => JSON.parse(t) as unknown);
} catch (e) {
if (!isCancelled(e)) showHint(view, cannotPerform(errorText(e)));
return;
}
const targets = targetTypes(types, exclude);
if (!targets.length) {
showHint(view, cannotPerform("No classes to move to"));
return;
}
choose(
view,
title,
targets.map((t, i) => ({
id: `${i}`,
label: text(t.name),
detail: text(t.containerName),
symbol: "class",
run: () => run(t),
})),
);
}
async function moveFile(view: EditorView, info: Json) {
const uri = text(info.uri);
if (!uri) return;
const request: MoveRequest = { sourceUris: [uri], params: null };
const packages = await destinations(view, "moveResource", request);
if (!packages) return;
if (!packages.length) {
showHint(view, cannotPerform("No packages to move the file to"));
return;
}
const name = decodeURIComponent(uri.slice(uri.lastIndexOf("/") + 1));
choose(
view,
tx`Move ${name} to Package`,
packages.map((p, i) => {
const row = packageRow(p);
return {
id: `${i}`,
label: row.label,
detail: row.detail,
icon: "package",
disabled: row.current ? tx("Current package") : null,
run: () => void move(view, "moveResource", { ...request, destination: p }),
};
}),
);
}
async function moveInstanceMethod(view: EditorView, params: unknown, info: Json) {
const request: MoveRequest = { sourceUris: sourceOf(params), params };
const targets = await destinations(view, "moveInstanceMethod", request);
if (!targets) return;
if (!targets.length) {
showHint(view, cannotPerform("No fields or parameters to move the method to"));
return;
}
choose(
view,
tx`Move Instance Method ${text(info.displayName)}`,
targets.map((d, i) => ({
id: `${i}`,
label: `${text(d.type)} ${text(d.name)}`,
detail: d.isField ? tx("Field") : tx("Parameter"),
run: () => void move(view, "moveInstanceMethod", { ...request, destination: d }),
})),
);
}
function excluded(info: Json, nestedType: boolean): Set<string> {
const exclude = new Set<string>();
const enclosing = text(info.enclosingTypeName);
if (enclosing) {
exclude.add(enclosing);
if (nestedType) exclude.add(`${enclosing}.${text(info.displayName)}`);
}
return exclude;
}
async function moveStaticMember(view: EditorView, params: unknown, info: Json) {
// 55, 71, 81: a class, enum or annotation type (JDT element kinds).
const nested = [55, 71, 81].includes(Number(info.memberType));
await chooseClass(
view,
tx`Move ${text(info.displayName)} to Class`,
info,
excluded(info, nested),
(t) => void move(view, "moveStaticMember", { sourceUris: sourceOf(params), params, destination: t }),
);
}
async function moveType(view: EditorView, params: unknown, info: Json) {
const name = text(info.displayName);
const kinds = Array.isArray(info.supportedDestinationKinds) ? info.supportedDestinationKinds.map(text) : [];
const request: MoveRequest = { sourceUris: sourceOf(params), params };
const toClass = () =>
chooseClass(
view,
tx`Move ${name} to Class`,
info,
excluded(info, true),
(t) => void move(view, "moveTypeToClass", { ...request, destination: t }),
);
const items: ListPopupItem[] = [];
if (kinds.includes("newFile"))
items.push({
id: "file",
label: tx`Move ${name} to a new file`,
run: () => void move(view, "moveTypeToNewFile", request),
});
if (kinds.includes("class"))
items.push({ id: "class", label: tx`Move ${name} to another class`, run: () => void toClass() });
if (items.length === 1) return void items[0]!.run();
if (items.length) choose(view, tx("Move"), items);
}
/** `java.action.applyRefactoringCommand`: the refactorings jdtls leaves to the client. */
export async function runJavaRefactoringCommand(view: EditorView, args: readonly unknown[]): Promise<boolean> {
const [command, params, info] = [text(args[0]), args[1], record(args[2])];
switch (command) {
case "changeSignature":
await startChangeSignature(view);
return true;
case "moveFile":
await moveFile(view, info);
return true;
case "moveInstanceMethod":
await moveInstanceMethod(view, params, info);
return true;
case "moveStaticMember":
await moveStaticMember(view, params, info);
return true;
case "moveType":
await moveType(view, params, info);
return true;
default:
return false;
}
}
+12 -3
Переглянути файл
@@ -40,6 +40,7 @@ import {
} from "./serverIntroduce";
import { safeDelete } from "./safeDelete";
import { startHierarchyRefactoring } from "./hierarchy";
import { SIGNATURE_LANGUAGES, startChangeSignature } from "./signature";
/** Languages with a server that runs the class-hierarchy refactorings (the app-owned JDT extension; Phoxite for PHP). */
const HIERARCHY_LANGUAGES = new Set(["java", "php"]);
@@ -153,6 +154,10 @@ export async function runRefactoring(view: EditorView, id: RefactoringId): Promi
showHint(view, cannotPerform("The file is read-only"));
return;
}
if (id === "changeSignature" && SIGNATURE_LANGUAGES.has(ctx.language)) {
await startChangeSignature(view);
return;
}
// IDEA picks the expression first (and the server then extracts exactly that one).
if (EXPRESSION_REFACTORINGS.has(id) && view.state.selection.main.empty) {
if (await chooseExpressionFirst(view, () => runRefactoring(view, id))) return;
@@ -219,11 +224,12 @@ async function expressionAtCaret(view: EditorView, signal: AbortSignal): Promise
export function refactorThisItems(
view: EditorView,
answer: ServerAnswer,
facts: { symbol: boolean; expression: boolean; hierarchy?: boolean },
facts: { symbol: boolean; expression: boolean; hierarchy?: boolean; signature?: boolean },
run: {
rename: (view: EditorView) => unknown;
safeDelete: (view: EditorView) => unknown;
hierarchy?: (view: EditorView, kind: "pullUp" | "pushDown") => unknown;
signature?: (view: EditorView) => unknown;
},
): ListPopupItem[] {
const { mapped, other } = groupActions(answer.status === "ok" ? answer.query.actions : []);
@@ -237,6 +243,8 @@ export function refactorThisItems(
// With only a caret the expression is chosen first, then the server asked for it.
if (expression && caretOnly && serverUsable && (actions.length || facts.expression))
go = () => runRefactoring(view, r.id);
else if (r.id === "changeSignature" && facts.signature && serverUsable && run.signature)
go = () => run.signature!(view);
else if (actions.length) go = () => runActions(view, r.label.replace(/…$/, ""), actions, r.id);
else if (r.id === "rename" && facts.symbol) go = () => run.rename(view);
else if (r.id === "safeDelete" && facts.symbol && !docOf(view)?.readOnly) go = () => run.safeDelete(view);
@@ -278,11 +286,12 @@ export async function refactorThis(view: EditorView, rename: (view: EditorView)
expressionAtCaret(view, run.signal),
]);
const hierarchy = HIERARCHY_LANGUAGES.has(ctx.language) && !ctx.readOnly;
const signature = SIGNATURE_LANGUAGES.has(ctx.language) && !ctx.readOnly && symbol;
items = refactorThisItems(
view,
answer,
{ symbol, expression, hierarchy },
{ rename, safeDelete, hierarchy: startHierarchyRefactoring },
{ symbol, expression, hierarchy, signature },
{ rename, safeDelete, hierarchy: startHierarchyRefactoring, signature: startChangeSignature },
);
} catch (e) {
if (isCancelled(e)) return;
+43
Переглянути файл
@@ -0,0 +1,43 @@
import { describe, expect, it } from "vitest";
import type { MethodSignature } from "@/bindings";
import { signatureChanged, signatureProblem, signatureText } from "./signature";
const info: MethodSignature = {
methodIdentifier: "=p/src<p{A.java[A~sum~I~I",
modifier: "public",
returnType: "int",
methodName: "sum",
parameters: [
{ type: "int", name: "a", defaultValue: "null", originalIndex: 0 },
{ type: "int", name: "b", defaultValue: "null", originalIndex: 1 },
],
exceptions: [{ type: "java.io.IOException", typeHandleIdentifier: "=x" }],
};
describe("change signature", () => {
it("previews the signature like the declaration", () => {
expect(signatureText(info)).toBe("public int sum(int a, int b) throws java.io.IOException");
expect(signatureText({ ...info, modifier: "", parameters: [], exceptions: [] })).toBe("int sum()");
});
it("tells what keeps the signature from being submitted", () => {
expect(signatureProblem(info)).toBeNull();
expect(signatureProblem({ ...info, methodName: "2x" })).toBe("Method name is not a valid identifier");
expect(signatureProblem({ ...info, returnType: " " })).toBe("Return type is not specified");
const dup = { ...info, parameters: [info.parameters[0]!, { ...info.parameters[1]!, name: "a" }] };
expect(signatureProblem(dup)).toBe("Duplicate parameter name");
const added = {
...info,
parameters: [...info.parameters, { type: "String", name: "s", defaultValue: "", originalIndex: -1 }],
};
expect(signatureProblem(added)).toBe("Default value is not specified for a new parameter");
added.parameters[2]!.defaultValue = '""';
expect(signatureProblem(added)).toBeNull();
});
it("notices changes, including reordered parameters", () => {
expect(signatureChanged(info, { ...info })).toBe(false);
expect(signatureChanged(info, { ...info, parameters: [...info.parameters].reverse() })).toBe(true);
expect(signatureChanged(info, { ...info, modifier: "private" })).toBe(true);
});
});
+199
Переглянути файл
@@ -0,0 +1,199 @@
/**
* Change Signature (⌘F6) for Java: jdtls reads the method at the caret, the dialog
* (`ChangeSignatureDialog.tsx`) edits its visibility, return type, name and parameters, and
* jdtls checks the new signature and computes the edit for the method, its overrides and
* every call. Problems are confirmed like IDEA's "Problems Detected".
*/
import type { Text } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { create } from "zustand";
import type { MethodSignature, Pos, ServerRefactored, SignatureParameter, WorkspaceEdit } from "@/bindings";
import { whenAllSynced, whenSynced } from "@/editor/api";
import { docOf, isUnavailable, lspRequest, reportLspError } from "@/editor/lsp/lsp";
import { offsetToPos } from "@/editor/lsp/positions";
import { showHint } from "@/editor/lsp/hint";
import { openPopup } from "@/editor/lsp/popupStore";
import { summarizeWorkspaceEdit } from "@/editor/lsp/workspaceEdit";
import { tx } from "@/platform/i18n";
import { commands, isCancelled, nextRequestId, unavailableText } from "@/platform/ipc";
import { ask } from "@/workbench/messages";
import { cannotPerform } from "./catalog";
/** Languages whose server changes signatures through the dialog. */
export const SIGNATURE_LANGUAGES = new Set(["java"]);
/** IDEA's visibility choices; jdtls spells package-private as the empty string. */
export const VISIBILITIES = ["public", "protected", "", "private"] as const;
/** A parameter row; `key` keeps React rows stable while they move. */
export interface ParameterRow extends SignatureParameter {
key: number;
}
let rowKeys = 0;
export const parameterRow = (p: SignatureParameter): ParameterRow => ({ ...p, key: ++rowKeys });
/** IDEA's new parameter: an empty type and name, `null` passed at existing calls. */
export const newParameter = (): ParameterRow =>
parameterRow({ type: "", name: "", defaultValue: "", originalIndex: -1 });
/** `public int sum(int a, int b) throws IOException`, as the dialog's preview shows it. */
export function signatureText(sig: {
modifier: string;
returnType: string;
methodName: string;
parameters: readonly SignatureParameter[];
exceptions?: readonly { type: string }[];
}): string {
const params = sig.parameters.map((p) => `${p.type} ${p.name}`.trim()).join(", ");
const head = [sig.modifier, sig.returnType, `${sig.methodName}(${params})`].filter(Boolean).join(" ");
const throws = sig.exceptions?.length ? ` throws ${sig.exceptions.map((e) => e.type).join(", ")}` : "";
return head + throws;
}
const JAVA_NAME = /^[A-Za-z_$][\w$]*$/;
/** Why the edited signature can't be submitted yet, or null. */
export function signatureProblem(sig: MethodSignature): string | null {
if (!JAVA_NAME.test(sig.methodName)) return "Method name is not a valid identifier";
if (!sig.returnType.trim()) return "Return type is not specified";
const seen = new Set<string>();
for (const p of sig.parameters) {
if (!p.type.trim()) return "Parameter type is not specified";
if (!JAVA_NAME.test(p.name)) return "Parameter name is not a valid identifier";
if (seen.has(p.name)) return "Duplicate parameter name";
seen.add(p.name);
if (p.originalIndex < 0 && !p.defaultValue.trim()) return "Default value is not specified for a new parameter";
}
return null;
}
/** Whether `sig` differs from the method's current signature. */
export function signatureChanged(original: MethodSignature, sig: MethodSignature): boolean {
const same = (a: SignatureParameter, b: SignatureParameter) =>
a.type === b.type && a.name === b.name && a.originalIndex === b.originalIndex;
return (
original.modifier !== sig.modifier ||
original.returnType !== sig.returnType ||
original.methodName !== sig.methodName ||
original.parameters.length !== sig.parameters.length ||
original.parameters.some((p, i) => !same(p, sig.parameters[i]!))
);
}
export interface SignatureRequest {
seq: number;
view: EditorView;
doc: number;
pos: Pos;
/** The document `pos` refers to. */
text: Text;
info: MethodSignature;
}
export const useSignatureDialog = create<{ request: SignatureRequest | null }>(() => ({ request: null }));
let seq = 0;
let running: AbortController | null = null;
function errorText(e: unknown): string {
if (isUnavailable(e)) return unavailableText(e, "No language server available");
return e instanceof Error ? e.message : String(e);
}
/** Change Signature…: reads the method at the caret, then opens the dialog. */
export async function startChangeSignature(view: EditorView): Promise<void> {
const ctx = docOf(view);
if (!ctx) return;
if (ctx.readOnly) {
showHint(view, cannotPerform("The file is read-only"));
return;
}
running?.abort();
const run = (running = new AbortController());
await whenSynced(view);
const state = view.state;
const pos = offsetToPos(state.doc, state.selection.main.head);
const request = nextRequestId();
const abort = () => void commands.cancelRequest(request);
run.signal.addEventListener("abort", abort);
try {
const info = await lspRequest(() => commands.lspSignatureInfo(request, ctx.doc, pos));
if (run.signal.aborted || view.state.doc !== state.doc) return;
useSignatureDialog.setState({ request: { seq: ++seq, view, doc: ctx.doc, pos, text: state.doc, info } });
} catch (e) {
if (isCancelled(e) || run.signal.aborted) return;
showHint(view, cannotPerform(errorText(e)));
} finally {
run.signal.removeEventListener("abort", abort);
if (running === run) running = null;
}
}
export async function applyEdit(view: EditorView, edit: WorkspaceEdit) {
try {
await whenAllSynced();
await lspRequest(() => commands.applyWorkspaceEdit(edit));
} catch (e) {
reportLspError(view, e, true);
}
}
export async function confirmProblems(messages: readonly string[]): Promise<boolean> {
const { button } = await ask({
title: "Problems Detected",
icon: "warning",
body: messages.join("\n"),
buttons: [
{ id: "continue", label: "Continue", primary: true },
{ id: "cancel", label: "Cancel" },
],
});
return button === "continue";
}
export type SignatureOutcome = { status: "done" } | { status: "stay"; error?: string };
/** Checks the new signature, confirms its problems and applies the edit, or previews it with `preview`. */
export async function changeSignature(
request: SignatureRequest,
signature: MethodSignature,
delegate: boolean,
preview: boolean,
): Promise<SignatureOutcome> {
const { view } = request;
if (view.state.doc !== request.text) return { status: "stay", error: "The file changed; open the dialog again" };
let confirmation: string | null = null;
let changed: ServerRefactored;
try {
for (;;) {
await whenSynced(view);
const token: string | null = confirmation;
changed = await lspRequest(() =>
commands.lspChangeSignature(nextRequestId(), request.doc, request.pos, signature, delegate, token),
);
const fatal = changed.problems.find((p) => p.severity === "fatal");
if (fatal || (!changed.edit && !changed.confirmation))
return { status: "stay", error: fatal?.message ?? "Nothing to change" };
if (!changed.confirmation) break;
if (!(await confirmProblems(changed.problems.map((p) => p.message)))) return { status: "stay" };
confirmation = changed.confirmation;
}
} catch (e) {
if (isCancelled(e)) return { status: "stay" };
return { status: "stay", error: errorText(e) };
}
const edit = changed.edit!;
const summary = summarizeWorkspaceEdit(edit);
if (!summary.files) return { status: "stay", error: "Nothing to change" };
if (preview) {
openPopup({
kind: "preview",
title: tx`Change Signature of '${request.info.methodName}'`,
summary,
confirmLabel: "Do Refactor",
onConfirm: () => void applyEdit(view, edit),
});
} else {
await applyEdit(view, edit);
}
return { status: "done" };
}
+47
Переглянути файл
@@ -0,0 +1,47 @@
/**
* Navigate › Related Symbol (⌃⌘↑): files and places tied to the current one by a language's or
* framework's conventions (a C header and its source, a Rails action and its views). Features
* register providers; the action merges what they find.
*/
export interface RelatedContext {
path: string;
language: string;
text: string;
/** The caret offset in `text`. */
offset: number;
}
export interface RelatedItem {
path: string;
/** 0-based; the file's start when absent. */
line?: number;
col?: number;
/** What the chooser shows (else the file name). */
label?: string;
/** The kind of relation shown after the label, e.g. "Header" or "View". */
group: string;
}
type Provider = (ctx: RelatedContext) => Promise<RelatedItem[]>;
const providers = new Set<Provider>();
export function registerRelatedProvider(provider: Provider): () => void {
providers.add(provider);
return () => {
providers.delete(provider);
};
}
/** Every provider's items, the first of each place kept; a failing provider adds nothing. */
export async function relatedItems(ctx: RelatedContext): Promise<RelatedItem[]> {
const found = await Promise.all([...providers].map((p) => p(ctx).catch(() => [] as RelatedItem[])));
const seen = new Set<string>();
return found.flat().filter((item) => {
const key = `${item.path}:${item.line ?? 0}`;
if (item.path === ctx.path && item.line === undefined) return false;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
+27 -2
Переглянути файл
@@ -131,6 +131,8 @@ export interface ComposerProps {
onConfig?: (option: string, value: string) => void;
/** `now`: send even while the agent works, into its turn (by default ⌘↵). */
onSubmit: (now: boolean) => void;
/** Opens the per-session MCP servers picker when `/mcp` is run. */
onOpenMcp?: () => void;
disabled?: boolean;
autoFocus?: boolean;
/** A request from this host to focus its input without changing the selection. */
@@ -468,9 +470,21 @@ export function Composer(props: ComposerProps) {
...rest,
];
}
const availableCommands =
props.onOpenMcp && completion.query.length > 0 && !props.commands.some((c) => c.name === "mcp")
? [
{
name: "mcp",
description: tx("Configure MCP servers for this session"),
hint: null,
source: "command" as const,
},
...props.commands,
]
: props.commands;
const out: Item[] = [];
let source: "command" | "skill" | undefined;
for (const command of matchCommands(props.commands, completion.query)) {
for (const command of matchCommands(availableCommands, completion.query)) {
const next = command.source ?? "command";
if (source !== next) {
source = next;
@@ -479,7 +493,7 @@ export function Composer(props: ComposerProps) {
out.push({ kind: "command", command });
}
return out;
}, [completion, files, props.commands]);
}, [completion, files, props.commands, props.onOpenMcp, tx]);
const activeIndex = items[active] && !isSection(items[active]!) ? active : firstSelectable(items, isSection);
const open = !!completion && items.some((item) => !isSection(item));
const anchorAt = open ? completion.to : null;
@@ -552,6 +566,11 @@ export function Composer(props: ComposerProps) {
}
const next = applyCompletion(current, completion, mentionOf(rel));
setText(next.text, next.caret);
} else if (item.command.name === "mcp" && props.onOpenMcp) {
replace(completion.from, completion.to, "");
setCompletion(null);
props.onOpenMcp();
return;
} else {
const next = applyCompletion(current, completion, `/${item.command.name}`);
setText(next.text, next.caret);
@@ -886,6 +905,12 @@ export function Composer(props: ComposerProps) {
}
const send = sendKeyAction(e, sendWith, whileRunning);
if (send) {
if (props.onOpenMcp && view.state.doc.toString().trim() === "/mcp") {
setText("");
setCompletion(null);
props.onOpenMcp();
return handled();
}
if (!props.disabled) props.onSubmit(send === "now");
recalled.current = { index: -1, stash: "" };
return handled();
+12
Переглянути файл
@@ -13,6 +13,7 @@ import { Composer } from "./Composer";
import { SubmitButton } from "./SubmitButton";
import { canSend, emptyDraft } from "./composerModel";
import { ConfigPickers } from "./ConfigPickers";
import { McpPicker } from "./McpPicker";
import { useEffortFocus } from "./effortFocus";
import { useAgentFontZoomSurface } from "./fontZoom";
import { HOME_KEY, providerIcon } from "./model";
@@ -23,6 +24,7 @@ import {
draftConfig,
refreshProviders,
refreshModels,
setDraftMcpOverrides,
setDraftOption,
startTask,
updateDraft,
@@ -57,6 +59,7 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
const current = repoState?.root === root ? repoState.current : null;
const [error, setError] = useState<string | null>(null);
const [starting, setStarting] = useState(false);
const [mcpOpenRequest, setMcpOpenRequest] = useState(0);
// Agents installed in Settings (its own window) show up when this one is back in front.
useEffect(() => {
@@ -228,6 +231,7 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
config={config}
onConfig={setDraftOption}
onSubmit={start}
onOpenMcp={() => setMcpOpenRequest((n) => n + 1)}
disabled={!canStart}
toolbar={
<>
@@ -255,6 +259,14 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
: undefined
}
/>
{provider && (
<McpPicker
provider={provider.id}
overrides={draft.mcpOverrides}
onChange={setDraftMcpOverrides}
openRequest={mcpOpenRequest}
/>
)}
</>
}
actions={
+213
Переглянути файл
@@ -0,0 +1,213 @@
.trigger {
display: inline-flex;
align-items: center;
gap: var(--space-1);
height: var(--h-control);
min-width: 0;
padding: 0 6px;
border: 0;
border-radius: var(--radius-control);
background: transparent;
color: var(--fg-secondary);
font: inherit;
white-space: nowrap;
cursor: pointer;
transition: background var(--dur-fast) var(--ease);
}
.trigger:hover,
.trigger[aria-expanded="true"] {
background: var(--bg-toolbar-hover);
color: var(--fg-strong);
}
.triggerLabel {
font-size: var(--fs-ui);
}
.triggerCount {
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.overrideDot {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--accent);
flex-shrink: 0;
}
.popup {
width: min(352px, calc(100vw - 24px));
display: flex;
flex-direction: column;
padding: 8px 0 6px;
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding: 0 10px 6px 12px;
border-bottom: 1px solid var(--border);
}
.title {
font-weight: 600;
color: var(--fg-strong);
}
.headerActions {
display: flex;
align-items: center;
gap: var(--space-1);
}
.resetBtn {
padding: 2px 6px;
border: 0;
border-radius: var(--radius-small, 3px);
background: transparent;
color: var(--link);
font: inherit;
font-size: var(--fs-small);
cursor: pointer;
}
.resetBtn:hover {
background: var(--bg-hover);
}
.searchWrap {
padding: 6px 10px 2px;
}
.list {
display: flex;
flex-direction: column;
max-height: 340px;
overflow-y: auto;
padding: 4px 0;
}
.groupLabel {
padding: 6px 12px 2px;
color: var(--fg-muted);
font-size: var(--fs-tiny);
font-weight: 600;
letter-spacing: 0.03em;
text-transform: uppercase;
}
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding: 5px 10px 5px 12px;
}
.row:hover {
background: var(--bg-hover);
}
.rowInfo {
display: flex;
flex-direction: column;
gap: 1px;
min-width: 0;
flex: 1;
}
.rowTitle {
display: flex;
align-items: center;
gap: var(--space-1);
min-width: 0;
flex-wrap: wrap;
}
.name {
font-weight: 500;
color: var(--fg-strong);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.sub {
color: var(--fg-muted);
font-size: var(--fs-tiny);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.pill {
display: inline-flex;
align-items: center;
height: 16px;
padding: 0 5px;
border-radius: var(--radius-small, 3px);
background: var(--bg-floating-toolbar);
color: var(--fg-secondary);
font-size: 10px;
font-weight: 500;
}
.pillSession {
background: color-mix(in srgb, var(--accent) 20%, var(--bg-elev));
color: var(--link);
}
.rowControls {
display: flex;
align-items: center;
gap: var(--space-1-5);
flex-shrink: 0;
}
.dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--control-off);
flex-shrink: 0;
}
.dotOn {
background: var(--success);
}
.inlineLink {
padding: 2px 6px;
border: 0;
border-radius: var(--radius-small, 3px);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border-button);
color: var(--fg-secondary);
font: inherit;
font-size: var(--fs-tiny);
cursor: pointer;
}
.inlineLink:hover {
background: var(--bg-hover);
color: var(--fg-strong);
}
.empty {
padding: 12px;
color: var(--fg-muted);
font-size: var(--fs-small);
text-align: center;
}
.footer {
padding: 6px 12px 2px;
border-top: 1px solid var(--border);
color: var(--fg-muted);
font-size: var(--fs-tiny);
}
+155
Переглянути файл
@@ -0,0 +1,155 @@
import { useState } from "react";
import { describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { McpExternalSource, McpServer } from "@/bindings";
import { McpPicker } from "./McpPicker";
import type { McpBackend } from "./mcpModel";
const SERVERS: McpServer[] = [
{
id: "user::shared",
name: "shared",
scope: "user",
transport: "stdio",
enabled: true,
command: "npx",
args: ["user-shared"],
env: [],
url: null,
headers: [],
agents: [],
unapproved: false,
},
{
id: "workspace::shared",
name: "shared",
scope: "workspace",
transport: "stdio",
enabled: true,
command: "npx",
args: ["workspace-shared"],
env: [],
url: null,
headers: [],
agents: [],
unapproved: false,
},
{
id: "user::claude-only",
name: "claude-only",
scope: "user",
transport: "http",
enabled: true,
command: null,
args: [],
env: [],
url: "https://mcp.example.com",
headers: [],
agents: ["claude"],
unapproved: false,
},
];
const SOURCES: McpExternalSource[] = [
{
id: "copilot-cli",
label: "GitHub Copilot CLI",
path: "/Users/dev/.copilot/mcp-config.json",
suggestedScope: "user",
nativeProvider: "copilot",
servers: [
{
name: "workiq",
transport: "stdio",
enabled: true,
command: "npx",
args: ["-y", "@microsoft/workiq", "mcp"],
url: null,
envKeys: [],
headerKeys: [],
},
],
},
];
function Harness({
provider = "copilot",
openRequest = 0,
backend,
}: {
provider?: string;
openRequest?: number;
backend?: McpBackend;
}) {
const [overrides, setOverrides] = useState<Record<string, boolean>>({});
return (
<McpPicker
provider={provider}
overrides={overrides}
onChange={setOverrides}
openRequest={openRequest}
backend={backend}
testData={{
servers: SERVERS,
sources: SOURCES,
ideMcpEnabled: true,
}}
/>
);
}
describe("McpPicker", () => {
it("resolves IDE, Project override over Global, agent-scoped defaults, and native CLI configs", async () => {
render(<Harness provider="copilot" />);
// Active by default for copilot: openidea (IDE) + shared (Project) + workiq (Copilot CLI) = 3 of 4 (claude-only is off).
const trigger = screen.getByRole("button", { name: "MCP servers" });
expect(trigger).toHaveTextContent("MCP3/4");
fireEvent.click(trigger);
expect(await screen.findByText("Session MCP Servers")).toBeInTheDocument();
expect(screen.getByText("Overrides Global")).toBeInTheDocument();
expect(screen.getByText("workiq")).toBeInTheDocument();
expect(screen.getByText("Active via GitHub Copilot CLI")).toBeInTheDocument();
// Toggle `shared` off and `claude-only` on for this session only, then Reset.
const sharedSwitch = screen.getByRole("switch", { name: "Enable shared for this session" });
const claudeSwitch = screen.getByRole("switch", { name: "Enable claude-only for this session" });
expect(sharedSwitch).toHaveAttribute("aria-checked", "true");
expect(claudeSwitch).toHaveAttribute("aria-checked", "false");
fireEvent.click(sharedSwitch);
fireEvent.click(claudeSwitch);
expect(sharedSwitch).toHaveAttribute("aria-checked", "false");
expect(claudeSwitch).toHaveAttribute("aria-checked", "true");
expect(screen.getAllByText("Session")).toHaveLength(2);
fireEvent.click(screen.getByRole("button", { name: "Reset" }));
expect(sharedSwitch).toHaveAttribute("aria-checked", "true");
expect(claudeSwitch).toHaveAttribute("aria-checked", "false");
expect(screen.queryByRole("button", { name: "Reset" })).toBeNull();
});
it("opens automatically when openRequest increments (e.g. /mcp slash command)", async () => {
const importSelected = vi.fn(async () => SERVERS);
const backend: McpBackend = {
list: async () => SERVERS,
save: async () => SERVERS,
setEnabled: async () => SERVERS,
remove: async () => SERVERS,
importWorkspace: async () => SERVERS,
importSelected,
};
const { rerender } = render(<Harness provider="copilot" openRequest={0} backend={backend} />);
expect(screen.queryByText("Session MCP Servers")).toBeNull();
rerender(<Harness provider="copilot" openRequest={1} backend={backend} />);
expect(await screen.findByText("Session MCP Servers")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Import" }));
await waitFor(() =>
expect(importSelected).toHaveBeenCalledWith("user", [{ sourceId: "copilot-cli", name: "workiq" }], false),
);
});
});
+407
Переглянути файл
@@ -0,0 +1,407 @@
/**
* Per-session MCP picker for the New Task and Session composers: shows inherited IDE, Project,
* Global, and Agent-Native CLI MCP servers, lets the user toggle servers for this session only,
* reset session overrides, or jump to Settings › Agents › External MCP Servers.
*/
import clsx from "clsx";
import { useEffect, useMemo, useRef, useState } from "react";
import type { McpExternalSource, McpServer } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { formatMessage, useTx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { Icon, IconButton, Popup, SearchField, T, Toggle } from "@/ui";
import {
IDE_MCP_SETTINGS_PAGE,
defaultMcpBackend,
nextSessionOverrides,
refreshMcpCatalog,
resolveSessionMcp,
useMcpCatalog,
useMcpCatalogSync,
type McpBackend,
type NativeCliMcpItem,
type SessionMcpItem,
} from "./mcpModel";
import { MCP_PAGE } from "./model";
import styles from "./McpPicker.module.css";
export interface McpPickerProps {
provider: string;
overrides: Readonly<Record<string, boolean>> | undefined;
onChange: (nextOverrides: Record<string, boolean>) => void;
disabled?: boolean;
/** True while the session is actively running a turn (changes apply on the next turn). */
busy?: boolean;
/** Bumped when `/mcp` is invoked from the composer to open this popover. */
openRequest?: number;
/** Optional overrides for unit tests. */
backend?: McpBackend;
testData?: {
servers: readonly McpServer[];
sources?: readonly McpExternalSource[];
ideMcpEnabled?: boolean;
};
}
export function McpPicker({
provider,
overrides,
onChange,
disabled = false,
busy = false,
openRequest = 0,
backend = defaultMcpBackend,
testData,
}: McpPickerProps) {
const tx = useTx();
useMcpCatalogSync();
const catalogServers = useMcpCatalog((s) => s.servers);
const catalogSources = useMcpCatalog((s) => s.sources);
const projectIdeMcp = useProject((s) => s.settings?.mcpServer?.enabled ?? false);
const servers = testData?.servers ?? catalogServers;
const sources = testData?.sources ?? catalogSources;
const ideMcpEnabled = testData?.ideMcpEnabled ?? projectIdeMcp;
const [open, setOpen] = useState(false);
const [seenOpenRequest, setSeenOpenRequest] = useState(openRequest);
const [query, setQuery] = useState("");
const [importingKey, setImportingKey] = useState<string | null>(null);
const anchor = useRef<HTMLButtonElement>(null);
if (openRequest !== seenOpenRequest) {
setSeenOpenRequest(openRequest);
if (openRequest > 0 && !disabled) setOpen(true);
}
useEffect(() => {
if (openRequest > 0 && !disabled && !testData) {
void refreshMcpCatalog();
}
}, [openRequest, disabled, testData]);
const toggleOpen = () => {
const next = !open;
if (next && !testData) void refreshMcpCatalog();
if (!next) setQuery("");
setOpen(next);
};
const resolved = useMemo(
() => resolveSessionMcp(servers, sources, ideMcpEnabled, provider, overrides ?? {}),
[servers, sources, ideMcpEnabled, provider, overrides],
);
const q = query.trim().toLowerCase();
const matchesQuery = (name: string, detail?: string) =>
!q || name.toLowerCase().includes(q) || (detail ?? "").toLowerCase().includes(q);
const showIde = matchesQuery(resolved.ide.name, "openidea ide");
const filteredWorkspace = resolved.workspace.filter((i) =>
matchesQuery(i.name, i.server?.command ?? i.server?.url ?? undefined),
);
const filteredUser = resolved.user.filter((i) =>
matchesQuery(i.name, i.server?.command ?? i.server?.url ?? undefined),
);
const filteredNative = resolved.nativeCli.filter((i) => matchesQuery(i.name, i.sourceLabel));
const totalRows = 1 + resolved.workspace.length + resolved.user.length + resolved.nativeCli.length;
const countLabel =
resolved.totalCount === 0
? "0"
: resolved.activeCount === resolved.totalCount
? String(resolved.activeCount)
: `${resolved.activeCount}/${resolved.totalCount}`;
const handleToggleItem = (item: SessionMcpItem, nextEnabled: boolean) => {
onChange(nextSessionOverrides(overrides, item, nextEnabled));
};
const handleImportNative = async (item: NativeCliMcpItem) => {
if (!backend.importSelected) return;
const key = `${item.sourceId}::${item.name}`;
setImportingKey(key);
try {
const next = await backend.importSelected("user", [{ sourceId: item.sourceId, name: item.name }], false);
if (!testData) {
useMcpCatalog.setState({ servers: next, loaded: true });
}
} finally {
setImportingKey(null);
}
};
return (
<>
<button
ref={anchor}
type="button"
disabled={disabled}
className={styles.trigger}
title={
resolved.overrideCount > 0
? formatMessage(tx("MCP servers ({active}/{total} active · {overrides} session overrides)"), {
active: resolved.activeCount,
total: resolved.totalCount,
overrides: resolved.overrideCount,
})
: formatMessage(tx("MCP servers ({active}/{total} active)"), {
active: resolved.activeCount,
total: resolved.totalCount,
})
}
aria-label={tx("MCP servers")}
aria-haspopup="dialog"
aria-expanded={open}
onClick={toggleOpen}
>
<Icon name="plugin" size={13} />
<span className={styles.triggerLabel}>MCP</span>
<span className={styles.triggerCount}>{countLabel}</span>
{resolved.overrideCount > 0 && <span className={styles.overrideDot} aria-hidden />}
</button>
<Popup
open={open}
anchor={anchor}
placement="top-start"
offset={6}
onClose={() => {
setOpen(false);
setQuery("");
}}
aria-label={tx("Session MCP Servers")}
className={styles.popup}
>
<div className={styles.header}>
<span className={styles.title}>
<T>Session MCP Servers</T>
</span>
<div className={styles.headerActions}>
{resolved.overrideCount > 0 && (
<button type="button" className={styles.resetBtn} onClick={() => onChange({})}>
<T>Reset</T>
</button>
)}
<IconButton
icon="settings"
size="small"
title={tx("External MCP Servers…")}
aria-label={tx("External MCP Servers…")}
onClick={() => {
setOpen(false);
void executeAction("file.settings", MCP_PAGE);
}}
/>
</div>
</div>
{totalRows > 5 && (
<div className={styles.searchWrap}>
<SearchField
value={query}
onChange={setQuery}
placeholder={tx("Filter MCP servers…")}
aria-label={tx("Filter MCP servers")}
/>
</div>
)}
<div className={styles.list}>
{showIde && (
<>
<div className={styles.groupLabel}>
<T>IDE</T>
</div>
<div className={styles.row}>
<div className={styles.rowInfo}>
<div className={styles.rowTitle}>
<span className={styles.name}>openidea</span>
{resolved.ide.overridden && (
<span className={clsx(styles.pill, styles.pillSession)}>
<T>Session</T>
</span>
)}
</div>
<span className={styles.sub}>
<T>Built-in IDE tools</T>
</span>
</div>
<div className={styles.rowControls}>
{resolved.ide.lockedReason === "ideDisabled" ? (
<button
type="button"
className={styles.inlineLink}
onClick={() => {
setOpen(false);
void executeAction("file.settings", IDE_MCP_SETTINGS_PAGE);
}}
>
<T>Enable in Settings</T>
</button>
) : (
<>
<Toggle
checked={resolved.ide.enabled}
aria-label={tx("Enable openidea for this session")}
onChange={(on) => handleToggleItem(resolved.ide, on)}
/>
<span className={clsx(styles.dot, resolved.ide.enabled && styles.dotOn)} aria-hidden />
</>
)}
</div>
</div>
</>
)}
{filteredWorkspace.length > 0 && (
<>
<div className={styles.groupLabel}>
<T>Project</T>
</div>
{filteredWorkspace.map((item) => (
<SessionServerRow
key={`ws:${item.name}`}
item={item}
onToggle={(on) => handleToggleItem(item, on)}
onOpenSettings={() => {
setOpen(false);
void executeAction("file.settings", MCP_PAGE);
}}
/>
))}
</>
)}
{filteredUser.length > 0 && (
<>
<div className={styles.groupLabel}>
<T>Global</T>
</div>
{filteredUser.map((item) => (
<SessionServerRow
key={`user:${item.name}`}
item={item}
onToggle={(on) => handleToggleItem(item, on)}
onOpenSettings={() => {
setOpen(false);
void executeAction("file.settings", MCP_PAGE);
}}
/>
))}
</>
)}
{filteredNative.length > 0 && (
<>
<div className={styles.groupLabel}>
<T>Agent Config</T>
</div>
{filteredNative.map((item) => {
const key = `${item.sourceId}::${item.name}`;
return (
<div key={key} className={styles.row}>
<div className={styles.rowInfo}>
<div className={styles.rowTitle}>
<span className={styles.name}>{item.name}</span>
<span className={styles.pill}>{item.server.transport.toUpperCase()}</span>
</div>
<span className={styles.sub} title={item.sourcePath}>
{formatMessage(tx("Active via {source}"), { source: item.sourceLabel })}
</span>
</div>
<div className={styles.rowControls}>
{backend.importSelected && (
<button
type="button"
disabled={importingKey === key}
className={styles.inlineLink}
title={tx("Import into Global settings to toggle per session and share across agents")}
onClick={() => void handleImportNative(item)}
>
<T>Import</T>
</button>
)}
<span className={clsx(styles.dot, styles.dotOn)} aria-hidden />
</div>
</div>
);
})}
</>
)}
{!showIde && filteredWorkspace.length === 0 && filteredUser.length === 0 && filteredNative.length === 0 && (
<div className={styles.empty}>
<T>No matching MCP servers.</T>
</div>
)}
</div>
<div className={styles.footer}>
{busy ? <T>Changes apply on the next message.</T> : <T>Toggles here apply to this session only.</T>}
</div>
</Popup>
</>
);
}
function SessionServerRow({
item,
onToggle,
onOpenSettings,
}: {
item: SessionMcpItem;
onToggle: (enabled: boolean) => void;
onOpenSettings: () => void;
}) {
const tx = useTx();
const srv = item.server!;
const sub =
srv.transport === "stdio"
? [srv.command, ...srv.args].filter(Boolean).join(" ")
: (srv.url ?? srv.transport.toUpperCase());
return (
<div className={styles.row}>
<div className={styles.rowInfo}>
<div className={styles.rowTitle}>
<span className={styles.name}>{item.name}</span>
<span className={styles.pill}>{srv.transport.toUpperCase()}</span>
{item.shadowsGlobal && (
<span className={styles.pill}>
<T>Overrides Global</T>
</span>
)}
{item.overridden && (
<span className={clsx(styles.pill, styles.pillSession)}>
<T>Session</T>
</span>
)}
</div>
{sub && (
<span className={styles.sub} title={sub}>
{sub}
</span>
)}
</div>
<div className={styles.rowControls}>
{item.lockedReason === "unapproved" ? (
<button type="button" className={styles.inlineLink} onClick={onOpenSettings}>
<T>Approve…</T>
</button>
) : (
<>
<Toggle
checked={item.enabled}
aria-label={formatMessage(tx("Enable {name} for this session"), { name: item.name })}
onChange={onToggle}
/>
<span className={clsx(styles.dot, item.enabled && styles.dotOn)} aria-hidden />
</>
)}
</div>
</div>
);
}
+424 -23
Переглянути файл
@@ -1,7 +1,7 @@
.page {
display: flex;
flex-direction: column;
gap: 10px;
gap: var(--space-2);
font-size: var(--fs-ui);
color: var(--fg-strong);
}
@@ -10,13 +10,15 @@
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
flex-wrap: wrap;
gap: var(--space-2);
}
.headerActions {
display: flex;
align-items: center;
gap: var(--space-2);
flex-wrap: wrap;
gap: var(--space-1-5);
}
.title {
@@ -45,50 +47,95 @@
text-decoration: underline;
}
.topControls {
display: flex;
flex-direction: column;
gap: var(--space-2);
}
.tabBar {
border-bottom: 1px solid var(--border);
}
.search {
width: 100%;
}
.error {
display: flex;
align-items: center;
align-items: flex-start;
gap: var(--space-1-5);
padding: 6px 8px;
border-radius: var(--radius-control);
background: color-mix(in srgb, var(--danger) 12%, transparent);
color: var(--danger);
font-size: var(--fs-small);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.notice {
display: flex;
align-items: center;
gap: var(--space-1-5);
padding: 6px 8px;
justify-content: space-between;
gap: var(--space-2);
padding: 6px 10px;
border-radius: var(--radius-control);
background: var(--accent-soft);
background: color-mix(in srgb, var(--accent) 14%, var(--bg-elev));
color: var(--fg);
font-size: var(--fs-small);
}
.noticeMain {
display: flex;
align-items: center;
gap: var(--space-1-5);
min-width: 0;
}
.builtinCard {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
padding: 8px 12px;
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
}
.builtinMain {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
min-width: 0;
}
.builtinHeader {
display: flex;
align-items: center;
gap: var(--space-1-5);
flex-wrap: wrap;
}
.sections {
display: flex;
flex-direction: column;
border-top: 1px solid var(--border);
gap: var(--space-3);
}
.section {
display: flex;
flex-direction: column;
border-bottom: 1px solid var(--border);
gap: var(--space-1-5);
}
.sectionBar {
display: flex;
align-items: center;
justify-content: space-between;
min-height: 32px;
padding: 2px 4px;
min-height: 28px;
padding: 2px 2px;
gap: var(--space-2);
}
@@ -108,10 +155,6 @@
cursor: pointer;
}
.sectionToggle:hover {
color: var(--fg-strong);
}
.chevron {
color: var(--fg-muted);
flex-shrink: 0;
@@ -122,6 +165,12 @@
font-weight: 600;
}
.sectionHint {
color: var(--fg-muted);
font-size: var(--fs-small);
font-weight: 400;
}
.badge {
display: inline-flex;
align-items: center;
@@ -140,31 +189,64 @@
.sectionBody {
display: flex;
flex-direction: column;
padding: 2px 0 6px;
gap: var(--space-1-5);
}
.sectionNote {
margin: 0;
padding: 2px 24px 6px;
padding: 0 4px 2px 20px;
color: var(--fg-muted);
font-size: var(--fs-small);
line-height: 1.4;
}
.row {
.emptyBox {
padding: 12px 14px;
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
color: var(--fg-muted);
font-size: var(--fs-small);
}
/* Cline-inspired expandable server card with OpenIDEA multi-level badges. */
.card {
display: flex;
flex-direction: column;
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
overflow: hidden;
}
.cardHeader {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
padding: 6px 8px 6px 22px;
border-radius: var(--radius-control);
gap: var(--space-2);
padding: 8px 10px;
}
.row:hover {
.cardHeader:hover {
background: var(--bg-hover);
}
.rowMain {
.cardExpandBtn {
display: flex;
align-items: center;
gap: var(--space-2);
flex: 1;
min-width: 0;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
text-align: left;
cursor: pointer;
}
.cardMain {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
@@ -172,6 +254,14 @@
flex: 1;
}
.cardTitleRow {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
min-width: 0;
}
.serverName {
font-weight: 600;
color: var(--fg-strong);
@@ -180,8 +270,38 @@
white-space: nowrap;
}
.tag {
display: inline-flex;
align-items: center;
gap: var(--space-1);
height: 18px;
padding: 0 6px;
border-radius: var(--radius-small, 3px);
background: var(--bg-floating-toolbar);
color: var(--fg-secondary);
font-size: var(--fs-tiny);
font-weight: 500;
white-space: nowrap;
}
.tagAccent {
background: color-mix(in srgb, var(--accent) 18%, var(--bg-elev));
color: var(--link);
}
.tagWarning {
background: color-mix(in srgb, var(--warning) 18%, var(--bg-elev));
color: var(--warning);
}
.tagSuccess {
background: color-mix(in srgb, var(--success) 18%, var(--bg-elev));
color: var(--success);
}
.subtitle {
color: var(--fg-muted);
font-family: var(--font-mono);
font-size: var(--fs-small);
overflow: hidden;
text-overflow: ellipsis;
@@ -195,6 +315,283 @@
flex-shrink: 0;
}
.statusDot {
width: 8px;
height: 8px;
border-radius: 50%;
flex-shrink: 0;
background: var(--control-off);
}
.statusOn {
background: var(--success);
}
.statusProbing {
background: var(--warning);
}
.statusError {
background: var(--danger);
}
.cardDrawer {
display: flex;
flex-direction: column;
gap: var(--space-2);
padding: 8px 12px 10px 28px;
border-top: 1px solid var(--border);
background: var(--bg-app);
font-size: var(--fs-small);
}
.metaGrid {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
gap: var(--space-1) var(--space-3);
align-items: baseline;
}
.metaLabel {
color: var(--fg-muted);
white-space: nowrap;
}
.metaValue {
color: var(--fg);
font-family: var(--font-mono);
overflow-wrap: anywhere;
}
.toolsPanel {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
padding-top: 4px;
border-top: 1px solid var(--border);
}
.toolsHeader {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
color: var(--fg-secondary);
font-weight: 600;
}
.toolsMeta {
color: var(--fg-muted);
font-weight: 400;
}
.toolsList {
display: flex;
flex-direction: column;
gap: var(--space-1);
max-height: 220px;
overflow-y: auto;
padding-right: 2px;
}
.toolRow {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
padding: 5px 8px;
border-radius: var(--radius-small, 3px);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
}
.toolName {
font-family: var(--font-mono);
font-weight: 600;
color: var(--fg-strong);
}
.toolDesc {
color: var(--fg-muted);
line-height: 1.35;
}
.drawerFooter {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--space-2);
padding-top: 4px;
}
.drawerButtons {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
}
/* Discovered external agent CLI sources. */
.importToolbar {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--space-2);
padding: 8px 10px;
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
}
.importControls {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-2);
}
.sourceCard {
display: flex;
flex-direction: column;
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
overflow: hidden;
}
.sourceHeader {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--space-2);
padding: 8px 12px;
border-bottom: 1px solid var(--border);
}
.sourceTitleGroup {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
min-width: 0;
}
.sourceTitleRow {
display: flex;
align-items: center;
gap: var(--space-1-5);
font-weight: 600;
}
.sourcePath {
color: var(--fg-muted);
font-family: var(--font-mono);
font-size: var(--fs-tiny);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.discoveredList {
display: flex;
flex-direction: column;
}
.discoveredRow {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding: 6px 12px;
}
.discoveredRow + .discoveredRow {
border-top: 1px solid var(--border);
}
.discoveredMain {
display: flex;
align-items: center;
gap: var(--space-2);
min-width: 0;
flex: 1;
}
.discoveredInfo {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
min-width: 0;
}
/* Modal Form / JSON switcher and agent pills. */
.modalModeBar {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding: 8px 16px 0;
}
.segmented {
display: inline-flex;
padding: 2px;
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
}
.segmentBtn {
padding: 3px 10px;
border: 0;
border-radius: var(--radius-small, 3px);
background: transparent;
color: var(--fg-muted);
font: inherit;
font-size: var(--fs-small);
font-weight: 500;
cursor: pointer;
}
.segmentActive {
background: var(--bg-selected);
color: var(--fg-strong);
}
.agentPicker {
display: flex;
flex-wrap: wrap;
gap: var(--space-1);
}
.agentChip {
display: inline-flex;
align-items: center;
gap: var(--space-1);
height: 24px;
padding: 0 8px;
border: 0;
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border-button);
color: var(--fg-secondary);
font: inherit;
font-size: var(--fs-small);
cursor: pointer;
}
.agentChip:hover {
background: var(--bg-hover);
color: var(--fg-strong);
}
.agentChipSelected {
background: var(--bg-selected);
box-shadow: inset 0 0 0 1px var(--accent);
color: var(--fg-strong);
}
/* Server form: a label column, controls filling the rest. */
.form {
display: grid;
@@ -247,6 +644,10 @@
transition: box-shadow var(--dur-fast) var(--ease);
}
.jsonArea {
min-height: 168px;
}
.textarea::placeholder {
color: var(--fg-faint);
}
File diff suppressed because it is too large. Load diff
+25 -1
Переглянути файл
@@ -80,6 +80,7 @@ import {
workTime,
} from "./composerModel";
import { ConfigPickers } from "./ConfigPickers";
import { McpPicker } from "./McpPicker";
import { useEffortFocus } from "./effortFocus";
import { useAgentFontZoomSurface } from "./fontZoom";
import { findRanges, formatDuration, formatSentAt, isFindRangeShown } from "./conversation";
@@ -147,6 +148,7 @@ import {
sendMessage,
sendQueuedNow,
setTaskConfig,
setTaskMcpOverrides,
useAgentCommands,
useAgents,
} from "./store";
@@ -2868,6 +2870,7 @@ function SessionComposer({
const project = useProject((s) => s.project);
const composer = useAgents((s) => s.composers.get(task.id)) ?? emptyDraft();
const [sending, setSending] = useState(false);
const [mcpOpenRequest, setMcpOpenRequest] = useState(0);
const agentCommands = useAgentCommands(task.provider, task.id, task.commands);
const busy = isBusy(task.status);
// ↑ recalls this conversation's messages, newest first.
@@ -2955,8 +2958,29 @@ function SessionComposer({
config={task.config}
onConfig={setOption}
onSubmit={send}
onOpenMcp={() => setMcpOpenRequest((n) => n + 1)}
disabled={task.status === "archived"}
toolbar={<ConfigPickers config={task.config} onChange={setOption} />}
toolbar={
<>
<ConfigPickers config={task.config} onChange={setOption} />
<McpPicker
provider={task.provider}
overrides={task.mcpOverrides}
disabled={task.status === "archived"}
busy={busy}
openRequest={mcpOpenRequest}
onChange={(next) =>
void setTaskMcpOverrides(task.id, next).catch((e: unknown) =>
notifications().notify({
level: "error",
title: "Couldn't change the setting",
body: String(e),
}),
)
}
/>
</>
}
actions={
<>
{busy && <IconButton icon="stop" title="Stop" onClick={() => void cancelTask(task.id)} />}
+12
Переглянути файл
@@ -170,6 +170,18 @@ describe("New Task composer commands", () => {
expect((await screen.findByRole("listbox", { name: "Commands" })).textContent).toBe("Commands/compact");
});
it("opens the per-session MCP picker when /mcp is completed in the composer", async () => {
agentCommands.mockResolvedValue({ status: "ok", data: [] });
render(<HomeEditor />);
const box = screen.getByRole("textbox");
typeIn(box, "/mc");
const list = await screen.findByRole("listbox", { name: "Commands" });
expect(within(list).getByRole("option", { selected: true })).toHaveTextContent("/mcp");
fireEvent.keyDown(box, { key: "Enter" });
expect(textOf(box)).toBe("");
expect(await screen.findByText("Session MCP Servers")).toBeInTheDocument();
});
it("names the icon-only Start action and disables it while starting", async () => {
agentCommands.mockResolvedValue({ status: "ok", data: [] });
let finish!: (value: unknown) => void;
+251
Переглянути файл
@@ -0,0 +1,251 @@
/**
* Shared MCP server model, multi-level inheritance resolution (IDE -> Project -> Global -> Agent CLI),
* and reactive cache for Settings › Agents › External MCP Servers and the Composer MCP picker.
*/
import { useEffect } from "react";
import { create } from "zustand";
import type {
McpDiscoveredServer,
McpExternalSource,
McpImportSelection,
McpProbeResult,
McpScope,
McpServer,
McpServerInput,
} from "@/bindings";
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
export const BUILTIN_MCP_NAME = "openidea";
export const IDE_MCP_SETTINGS_PAGE = "agents.mcpServer";
export interface McpBackend {
list(): Promise<McpServer[]>;
save(input: McpServerInput): Promise<McpServer[]>;
saveJson?(scope: McpScope, rawJson: string, fallbackName: string | null, agents: string[]): Promise<McpServer[]>;
setEnabled(id: string, enabled: boolean): Promise<McpServer[]>;
remove(id: string): Promise<McpServer[]>;
importWorkspace(): Promise<McpServer[]>;
discoverSources?(): Promise<McpExternalSource[]>;
importSelected?(scope: McpScope, selections: McpImportSelection[], overwrite: boolean): Promise<McpServer[]>;
testServer?(id: string): Promise<McpProbeResult>;
}
export const defaultMcpBackend: McpBackend = {
list: () => (typeof commands.agentMcpList === "function" ? call(commands.agentMcpList()) : Promise.resolve([])),
save: (input) => call(commands.agentMcpSave(input)),
saveJson: (scope, rawJson, fallbackName, agents) =>
call(commands.agentMcpSaveJson(scope, rawJson, fallbackName, agents)),
setEnabled: (id, enabled) => call(commands.agentMcpSetEnabled(id, enabled)),
remove: (id) => call(commands.agentMcpRemove(id)),
importWorkspace: () => call(commands.agentMcpImport()),
discoverSources: () =>
typeof commands.agentMcpDiscoverSources === "function"
? call(commands.agentMcpDiscoverSources())
: Promise.resolve([]),
importSelected: (scope, selections, overwrite) => call(commands.agentMcpImportSelected(scope, selections, overwrite)),
testServer: (id) => call(commands.agentMcpTest(id)),
};
export const normalizeProviderId = (id: string): string => (id.endsWith("-acp") ? id.slice(0, -4) : id);
export function matchesAgentProvider(agents: readonly string[] | undefined, provider: string): boolean {
if (!agents || agents.length === 0) return true;
const target = normalizeProviderId(provider);
return agents.some((raw) => {
const trimmed = raw.trim();
return trimmed === provider || normalizeProviderId(trimmed) === target;
});
}
export interface SessionMcpItem {
name: string;
level: "ide" | "workspace" | "user";
server?: McpServer;
/** Default state inherited from IDE / Project / Global settings for `provider`. */
defaultEnabled: boolean;
/** Effective state for this session after applying `overrides`. */
enabled: boolean;
/** True when `overrides` explicitly diverges from `defaultEnabled`. */
overridden: boolean;
/** True when a Project server shadows a Global server of the same name. */
shadowsGlobal: boolean;
/** Cannot be toggled in-session (e.g. IDE MCP server is off globally, or unapproved Project server). */
lockedReason: "ideDisabled" | "unapproved" | null;
}
export interface NativeCliMcpItem {
name: string;
sourceId: string;
sourceLabel: string;
sourcePath: string;
server: McpDiscoveredServer;
}
export interface ResolvedSessionMcp {
ide: SessionMcpItem;
workspace: SessionMcpItem[];
user: SessionMcpItem[];
nativeCli: NativeCliMcpItem[];
activeCount: number;
totalCount: number;
overrideCount: number;
}
/**
* Resolves the effective MCP servers for a session running `provider` across all levels:
* 1. Built-in IDE MCP server (`openidea`)
* 2. Project (`workspace` scope — overrides `user` servers with the same name)
* 3. Global (`user` scope)
* 4. Agent-native CLI config directories not yet imported into OpenIDEA (`~/.copilot/...`, `~/.claude.json`, etc.)
*/
export function resolveSessionMcp(
servers: readonly McpServer[],
sources: readonly McpExternalSource[],
ideMcpEnabled: boolean,
provider: string,
overrides: Readonly<Record<string, boolean>> = {},
): ResolvedSessionMcp {
const ideOverride = overrides[BUILTIN_MCP_NAME];
const ideEffective = ideMcpEnabled ? (ideOverride ?? true) : false;
const ide: SessionMcpItem = {
name: BUILTIN_MCP_NAME,
level: "ide",
defaultEnabled: ideMcpEnabled,
enabled: ideEffective,
overridden: ideMcpEnabled && ideOverride !== undefined && ideOverride !== ideMcpEnabled,
shadowsGlobal: false,
lockedReason: ideMcpEnabled ? null : "ideDisabled",
};
const userNames = new Set(servers.filter((s) => s.scope === "user").map((s) => s.name));
const seenNames = new Set<string>([BUILTIN_MCP_NAME]);
const workspace: SessionMcpItem[] = [];
const user: SessionMcpItem[] = [];
for (const srv of servers.filter((s) => s.scope === "workspace")) {
seenNames.add(srv.name);
const unapproved = !!srv.unapproved;
const defaultEnabled = !unapproved && srv.enabled && matchesAgentProvider(srv.agents, provider);
const explicit = overrides[srv.name];
const enabled = unapproved ? false : (explicit ?? defaultEnabled);
workspace.push({
name: srv.name,
level: "workspace",
server: srv,
defaultEnabled,
enabled,
overridden: !unapproved && explicit !== undefined && explicit !== defaultEnabled,
shadowsGlobal: userNames.has(srv.name),
lockedReason: unapproved ? "unapproved" : null,
});
}
for (const srv of servers.filter((s) => s.scope === "user")) {
if (seenNames.has(srv.name)) continue;
seenNames.add(srv.name);
const defaultEnabled = srv.enabled && matchesAgentProvider(srv.agents, provider);
const explicit = overrides[srv.name];
const enabled = explicit ?? defaultEnabled;
user.push({
name: srv.name,
level: "user",
server: srv,
defaultEnabled,
enabled,
overridden: explicit !== undefined && explicit !== defaultEnabled,
shadowsGlobal: false,
lockedReason: null,
});
}
const normalizedProvider = normalizeProviderId(provider);
const nativeCli: NativeCliMcpItem[] = [];
for (const src of sources) {
if (!src.nativeProvider || normalizeProviderId(src.nativeProvider) !== normalizedProvider) continue;
for (const srv of src.servers) {
if (seenNames.has(srv.name) || !srv.enabled) continue;
seenNames.add(srv.name);
nativeCli.push({
name: srv.name,
sourceId: src.id,
sourceLabel: src.label,
sourcePath: src.path,
server: srv,
});
}
}
const controllable = [...(ideMcpEnabled ? [ide] : []), ...workspace.filter((i) => !i.lockedReason), ...user];
const activeCount = controllable.filter((i) => i.enabled).length + nativeCli.length;
const totalCount = controllable.length + nativeCli.length;
const overrideCount = controllable.filter((i) => i.overridden).length;
return { ide, workspace, user, nativeCli, activeCount, totalCount, overrideCount };
}
/** Computes the minimal `mcpOverrides` map after toggling `name` to `nextEnabled`. */
export function nextSessionOverrides(
current: Readonly<Record<string, boolean>> | undefined,
item: SessionMcpItem,
nextEnabled: boolean,
): Record<string, boolean> {
const next = { ...(current ?? {}) };
if (nextEnabled === item.defaultEnabled) {
delete next[item.name];
} else {
next[item.name] = nextEnabled;
}
return next;
}
/** Shared window-level cache of configured MCP servers and discovered external CLI configs. */
interface McpCatalogState {
servers: McpServer[];
sources: McpExternalSource[];
loaded: boolean;
probes: Record<string, McpProbeResult>;
probing: Record<string, boolean>;
}
export const useMcpCatalog = create<McpCatalogState>(() => ({
servers: [],
sources: [],
loaded: false,
probes: {},
probing: {},
}));
let listenerAttached = false;
export async function refreshMcpCatalog(): Promise<void> {
if (!isTauri()) return;
const [servers, sources] = await Promise.all([
defaultMcpBackend.list().catch(() => null),
defaultMcpBackend.discoverSources?.().catch(() => null) ?? Promise.resolve(null),
]);
useMcpCatalog.setState((prev) => ({
servers: servers ?? prev.servers,
sources: sources ?? prev.sources,
loaded: true,
}));
}
export function useMcpCatalogSync(): void {
const root = useProject((s) => s.project?.root);
useEffect(() => {
if (!isTauri()) return;
void refreshMcpCatalog();
const onFocus = () => void refreshMcpCatalog();
window.addEventListener("focus", onFocus);
if (!listenerAttached && typeof onIdeEvent === "function") {
listenerAttached = true;
onIdeEvent("settingsChanged", (e) => {
if (!e.key || e.key.startsWith("agents.mcpServers") || e.key.startsWith("mcpServer")) {
void refreshMcpCatalog();
}
});
}
return () => window.removeEventListener("focus", onFocus);
}, [root]);
}
+157 -8
Переглянути файл
@@ -1,6 +1,13 @@
import { describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import type { McpServer, McpServerInput } from "@/bindings";
import type {
McpExternalSource,
McpImportSelection,
McpProbeResult,
McpScope,
McpServer,
McpServerInput,
} from "@/bindings";
import { McpServersPage, type McpBackend } from "./McpServersPage";
const server = (partial: Partial<McpServer> & Pick<McpServer, "id" | "name" | "scope">): McpServer => ({
@@ -12,6 +19,7 @@ const server = (partial: Partial<McpServer> & Pick<McpServer, "id" | "name" | "s
env: [],
headers: [],
agents: [],
unapproved: false,
...partial,
});
@@ -29,18 +37,45 @@ const INITIAL_SERVERS: McpServer[] = [
}),
];
const INITIAL_SOURCES: McpExternalSource[] = [
{
id: "copilot-cli",
label: "GitHub Copilot CLI",
path: "/Users/dev/.copilot/mcp-config.json",
suggestedScope: "user",
nativeProvider: "copilot",
servers: [
{
name: "github-mcp-server",
transport: "http",
enabled: true,
command: null,
args: [],
url: "https://api.githubcopilot.com/mcp/",
envKeys: [],
headerKeys: ["Authorization"],
},
],
},
];
class FakeMcpBackend implements McpBackend {
servers: McpServer[] = [...INITIAL_SERVERS];
sources: McpExternalSource[] = [...INITIAL_SOURCES];
toggled: Array<{ id: string; enabled: boolean }> = [];
saved: McpServerInput[] = [];
savedJson: Array<{ scope: McpScope; rawJson: string; agents: string[] }> = [];
importedSelected: Array<{ scope: McpScope; selections: McpImportSelection[]; overwrite: boolean }> = [];
removed: string[] = [];
imported = 0;
list = vi.fn(async () => this.servers);
discoverSources = vi.fn(async () => this.sources);
setEnabled = vi.fn(async (id: string, enabled: boolean) => {
this.toggled.push({ id, enabled });
this.servers = this.servers.map((s) => (s.id === id ? { ...s, enabled } : s));
this.servers = this.servers.map((s) => (s.id === id ? { ...s, enabled, unapproved: false } : s));
return this.servers;
});
@@ -63,6 +98,62 @@ class FakeMcpBackend implements McpBackend {
return this.servers;
});
saveJson = vi.fn(async (scope: McpScope, rawJson: string, _fallback: string | null, agents: string[]) => {
this.savedJson.push({ scope, rawJson, agents });
const parsed = JSON.parse(rawJson) as { mcpServers?: Record<string, { command?: string; args?: string[] }> };
for (const [name, cfg] of Object.entries(parsed.mcpServers ?? {})) {
this.servers = [
...this.servers.filter((s) => s.id !== `${scope}::${name}`),
server({
id: `${scope}::${name}`,
name,
scope,
transport: "stdio",
command: cfg.command ?? "npx",
args: cfg.args ?? [],
url: null,
agents,
}),
];
}
return this.servers;
});
importSelected = vi.fn(async (scope: McpScope, selections: McpImportSelection[], overwrite: boolean) => {
this.importedSelected.push({ scope, selections, overwrite });
for (const sel of selections) {
const src = this.sources.find((s) => s.id === sel.sourceId);
const found = src?.servers.find((s) => s.name === sel.name);
if (!found) continue;
this.servers = [
...this.servers.filter((s) => s.id !== `${scope}::${found.name}`),
server({
id: `${scope}::${found.name}`,
name: found.name,
scope,
transport: found.transport,
command: found.command,
args: found.args,
url: found.url,
}),
];
}
return this.servers;
});
testServer = vi.fn(async (_id: string): Promise<McpProbeResult> => ({
ok: true,
serverName: "mock-mcp",
serverVersion: "1.2.0",
protocolVersion: "2024-11-05",
durationMs: 42,
error: null,
tools: [
{ name: "search_issues", description: "Search issues across repositories" },
{ name: "create_pr", description: "Open a pull request" },
],
}));
remove = vi.fn(async (id: string) => {
this.removed.push(id);
this.servers = this.servers.filter((s) => s.id !== id);
@@ -80,7 +171,6 @@ class FakeMcpBackend implements McpBackend {
args: ["-y", "@modelcontextprotocol/server-filesystem", "."],
url: null,
});
// Like the backend, a server already in the workspace is not imported again.
if (!this.servers.some((s) => s.id === importedServer.id)) this.servers = [...this.servers, importedServer];
return this.servers;
});
@@ -112,17 +202,76 @@ describe("McpServersPage", () => {
expect(screen.queryByText("slack-official")).not.toBeInTheDocument();
});
it("toggles server enabled state via its checkbox", async () => {
it("toggles server enabled state via its switch", async () => {
const backend = new FakeMcpBackend();
render(<McpServersPage backend={backend} />);
await waitFor(() => expect(screen.getByText("slack-official")).toBeInTheDocument());
const box = screen.getByRole("checkbox", { name: "Enable slack-official" });
expect(box).toBeChecked();
const sw = screen.getByRole("switch", { name: "Enable slack-official" });
expect(sw).toHaveAttribute("aria-checked", "true");
fireEvent.click(box);
fireEvent.click(sw);
await waitFor(() => expect(backend.toggled).toEqual([{ id: "user::slack-official", enabled: false }]));
expect(screen.getByRole("checkbox", { name: "Enable slack-official" })).not.toBeChecked();
expect(screen.getByRole("switch", { name: "Enable slack-official" })).toHaveAttribute("aria-checked", "false");
});
it("probes a server and displays discovered tools inside its expandable card", async () => {
const backend = new FakeMcpBackend();
render(<McpServersPage backend={backend} />);
await waitFor(() => expect(screen.getByText("slack-official")).toBeInTheDocument());
fireEvent.click(screen.getByRole("button", { name: "Test slack-official" }));
await waitFor(() => expect(backend.testServer).toHaveBeenCalledWith("user::slack-official"));
expect(await screen.findByText("search_issues")).toBeInTheDocument();
expect(screen.getByText("Search issues across repositories")).toBeInTheDocument();
expect(screen.getByText("Tools (2)")).toBeInTheDocument();
});
it("discovers external agent CLI configs and imports into Global settings", async () => {
const backend = new FakeMcpBackend();
render(<McpServersPage backend={backend} />);
await waitFor(() => expect(screen.getByText("slack-official")).toBeInTheDocument());
fireEvent.click(screen.getByRole("button", { name: "Review & Import" }));
expect(await screen.findByText("GitHub Copilot CLI")).toBeInTheDocument();
expect(screen.getByText("github-mcp-server")).toBeInTheDocument();
fireEvent.click(screen.getByRole("checkbox", { name: "Select github-mcp-server" }));
fireEvent.click(screen.getByRole("button", { name: "Import Selected (1)" }));
await waitFor(() => expect(backend.importedSelected).toHaveLength(1));
expect(backend.importedSelected[0]).toEqual({
scope: "user",
selections: [{ sourceId: "copilot-cli", name: "github-mcp-server" }],
overwrite: false,
});
});
it("saves servers from pasted mcpServers JSON with selected agent chips", async () => {
const backend = new FakeMcpBackend();
render(<McpServersPage backend={backend} />);
await waitFor(() => expect(screen.getByText("slack-official")).toBeInTheDocument());
fireEvent.click(screen.getByRole("button", { name: "Add from JSON" }));
const dialog = await screen.findByRole("dialog");
const jsonField = within(dialog).getByLabelText("JSON:");
fireEvent.change(jsonField, {
target: {
value: JSON.stringify({
mcpServers: {
playwright: { command: "npx", args: ["@playwright/mcp@latest"] },
},
}),
},
});
fireEvent.click(within(dialog).getByRole("button", { name: "GitHub Copilot" }));
fireEvent.click(within(dialog).getByRole("button", { name: "Add" }));
await waitFor(() => expect(backend.savedJson).toHaveLength(1));
expect(backend.savedJson[0]?.agents).toEqual(["copilot"]);
await waitFor(() => expect(screen.getByText("playwright")).toBeInTheDocument());
});
it("adds a new workspace MCP server with optional agent filter", async () => {
+21
Переглянути файл
@@ -75,6 +75,8 @@ export interface Draft {
isolationChosen?: boolean;
/** `null`: the current branch. */
base: string | null;
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`) for the next task. */
mcpOverrides?: Record<string, boolean>;
}
/** Composer key of the New Task page; sessions use their task id. */
@@ -984,6 +986,7 @@ export async function startTask(
config,
isolation,
base: isolation === "worktree" ? draft.base : null,
mcpOverrides: draft.mcpOverrides ?? {},
}),
);
if (generation !== started) return;
@@ -1235,6 +1238,7 @@ export async function startSideConversation(task: string, text: string): Promise
config: source.config.filter((o) => o.current != null).map((o) => ({ id: o.id, value: o.current as string })),
isolation: "local" as const,
base: null,
mcpOverrides: source.mcpOverrides ?? {},
},
task,
),
@@ -1413,6 +1417,23 @@ export const sendQueuedNow = (task: string, queued: string) => call(commands.age
export const setTaskConfig = (task: string, option: string, value: string) =>
call(commands.agentSetConfig(task, option, value));
export function setDraftMcpOverrides(mcpOverrides: Record<string, boolean>) {
updateDraft({ mcpOverrides });
}
export async function setTaskMcpOverrides(task: string, overrides: Record<string, boolean>): Promise<void> {
const prev = useAgents.getState().tasks.get(task);
if (prev) {
useAgents.setState((s) => ({
tasks: new Map(s.tasks).set(task, { ...prev, mcpOverrides: overrides }),
}));
}
const updated = await call(commands.agentSetMcpOverrides(task, overrides));
useAgents.setState((s) => ({
tasks: new Map(s.tasks).set(task, updated),
}));
}
/** The composer the user is looking at: the Agents surface on show, else the one typed in last. */
function activeComposerKey(): string {
const s = useAgents.getState();
+2
Переглянути файл
@@ -49,6 +49,7 @@ import { activate as services } from "./services";
import { activate as github, activateSettingsPages as githubPages } from "./github";
import { activate as httpClient } from "./http-client";
import { activate as cucumber } from "./cucumber";
import { activate as rails } from "./rails";
import { activate as thymeleaf } from "./thymeleaf";
import { activate as database, activateSettingsPages as databasePages } from "./database";
import { activate as graphql } from "./graphql";
@@ -102,6 +103,7 @@ const features: Array<[string, Activate]> = [
["github", github],
["http-client", httpClient],
["cucumber", cucumber],
["rails", rails],
["thymeleaf", thymeleaf],
["database", database],
["graphql", graphql],
+101
Переглянути файл
@@ -0,0 +1,101 @@
import { describe, expect, it } from "vitest";
import { actionAt, controllerName, pluralize, railsFile, railsTargets, singularize, type RailsFs } from "./conventions";
const CONTROLLER = `class Admin::UsersController < ApplicationController
before_action :load_user
def index
@users = User.all
end
def show
end
end
`;
const files: Record<string, string[]> = {
"/app/app/views/admin/users": ["index.html.erb", "show.html.erb", "_form.html.erb"],
"/app/app/helpers/admin": ["users_helper.rb"],
"/app/app/models": ["user.rb"],
"/app/app/controllers/admin": ["users_controller.rb"],
"/app/app/controllers": ["people_controller.rb", "users_controller.rb"],
"/app/db/migrate": [
"20240101000000_create_users.rb",
"20240102000000_add_email_to_users.rb",
"20240103_create_posts.rb",
],
};
const texts: Record<string, string> = {
"/app/app/controllers/admin/users_controller.rb": CONTROLLER,
"/app/app/controllers/users_controller.rb": "class UsersController\nend\n",
};
const fs: RailsFs = { list: async (d) => files[d] ?? null, read: async (p) => texts[p] ?? null };
describe("rails conventions", () => {
it("inflects and names", () => {
expect(pluralize("user")).toBe("users");
expect(pluralize("category")).toBe("categories");
expect(pluralize("box")).toBe("boxes");
expect(pluralize("person")).toBe("people");
expect(singularize("users")).toBe("user");
expect(singularize("categories")).toBe("category");
expect(singularize("addresses")).toBe("address");
expect(singularize("people")).toBe("person");
expect(controllerName("admin/order_items")).toBe("Admin::OrderItemsController");
});
it("classifies files under app/", () => {
expect(railsFile("/app/app/controllers/admin/users_controller.rb")).toEqual({
kind: "controller",
root: "/app",
resource: "admin/users",
});
expect(railsFile("/app/app/views/users/index.html.erb")).toMatchObject({ kind: "view", file: "index.html.erb" });
expect(railsFile("/app/app/views/layouts/application.html.erb")).toBeNull();
expect(railsFile("/app/app/controllers/application_controller.rb")).toBeNull();
expect(railsFile("/app/app/models/concerns/taggable.rb")).toBeNull();
expect(railsFile("/app/lib/tasks/x.rb")).toBeNull();
});
it("finds the action at the caret", () => {
expect(actionAt(CONTROLLER, CONTROLLER.indexOf("User.all"))).toBe("index");
expect(actionAt(CONTROLLER, CONTROLLER.indexOf("before_action"))).toBeNull();
});
it("goes from an action to its views, and from a controller to all of them, its helper and model", async () => {
const at = CONTROLLER.indexOf("User.all");
const path = "/app/app/controllers/admin/users_controller.rb";
expect(await railsTargets(path, CONTROLLER, at, fs)).toEqual([
{ path: "/app/app/views/admin/users/index.html.erb", group: "view" },
{ path: "/app/app/helpers/admin/users_helper.rb", group: "helper", label: undefined },
{ path: "/app/app/models/user.rb", group: "model", label: undefined },
]);
const all = await railsTargets(path, CONTROLLER, 0, fs);
expect(all.filter((t) => t.group === "view").map((t) => t.path.split("/").pop())).toEqual([
"_form.html.erb",
"index.html.erb",
"show.html.erb",
]);
});
it("goes from a view to its action", async () => {
const [target] = await railsTargets("/app/app/views/admin/users/show.html.erb", "", 0, fs);
expect(target).toEqual({
path: "/app/app/controllers/admin/users_controller.rb",
group: "controller",
line: 7,
label: "Admin::UsersController#show",
});
const [partial] = await railsTargets("/app/app/views/admin/users/_form.html.erb", "", 0, fs);
expect(partial).toMatchObject({ line: undefined, label: "Admin::UsersController" });
});
it("goes from a model to its controller and migrations", async () => {
const targets = await railsTargets("/app/app/models/user.rb", "", 0, fs);
expect(targets.map((t) => [t.group, t.path.split("/").pop()])).toEqual([
["controller", "users_controller.rb"],
["migration", "20240101000000_create_users.rb"],
["migration", "20240102000000_add_email_to_users.rb"],
]);
});
});
+153
Переглянути файл
@@ -0,0 +1,153 @@
/**
* Rails' file conventions for Navigate › Related Symbol: a controller (and the action at the
* caret) with its views, helper and model; a view with its controller action; a model with its
* controller and migrations.
*/
export interface RailsFs {
/** The file names in `dir`, or null when it doesn't exist. */
list(dir: string): Promise<string[] | null>;
read(path: string): Promise<string | null>;
}
export type RailsGroup = "view" | "controller" | "helper" | "model" | "migration";
export interface RailsTarget {
path: string;
group: RailsGroup;
line?: number;
label?: string;
}
type RailsFile =
| { kind: "controller"; root: string; resource: string }
| { kind: "helper"; root: string; resource: string }
| { kind: "view"; root: string; resource: string; file: string }
| { kind: "model"; root: string; model: string };
const IRREGULAR: Record<string, string> = { person: "people", man: "men", woman: "women", child: "children" };
const IRREGULAR_SINGULAR = Object.fromEntries(Object.entries(IRREGULAR).map(([s, p]) => [p, s]));
export function pluralize(word: string): string {
if (IRREGULAR[word]) return IRREGULAR[word];
if (/[^aeiou]y$/.test(word)) return `${word.slice(0, -1)}ies`;
if (/(?:s|x|z|ch|sh)$/.test(word)) return `${word}es`;
return `${word}s`;
}
export function singularize(word: string): string {
if (IRREGULAR_SINGULAR[word]) return IRREGULAR_SINGULAR[word];
if (/[^aeiou]ies$/.test(word)) return `${word.slice(0, -3)}y`;
if (/(?:ss|x|z|ch|sh)es$/.test(word)) return word.slice(0, -2);
if (/[^s]s$/.test(word)) return word.slice(0, -1);
return word;
}
const camel = (s: string) => s.replace(/(?:^|_)([a-z0-9])/g, (_, c: string) => c.toUpperCase());
/** `admin/users` → `Admin::UsersController`. */
export function controllerName(resource: string): string {
return `${resource.split("/").map(camel).join("::")}Controller`;
}
export function railsFile(path: string): RailsFile | null {
const m = /^(.*)\/app\/(controllers|views|helpers|models)\/(.+)$/.exec(path);
if (!m) return null;
const [, root, dir, rest] = m as unknown as [string, string, string, string];
if (dir === "controllers") {
const c = /^(.+)_controller\.rb$/.exec(rest);
return c && c[1] !== "application" ? { kind: "controller", root, resource: c[1]! } : null;
}
if (dir === "helpers") {
const h = /^(.+)_helper\.rb$/.exec(rest);
return h && h[1] !== "application" ? { kind: "helper", root, resource: h[1]! } : null;
}
if (dir === "views") {
const slash = rest.lastIndexOf("/");
if (slash < 0) return null;
const resource = rest.slice(0, slash);
if (resource === "layouts" || resource.startsWith("layouts/")) return null;
return { kind: "view", root, resource, file: rest.slice(slash + 1) };
}
const model = /^(.+)\.rb$/.exec(rest);
return model && !model[1]!.startsWith("concerns/") ? { kind: "model", root, model: model[1]! } : null;
}
const DEF = /^\s*def\s+(?:self\.)?([A-Za-z_]\w*[!?]?)/;
/** The method whose `def` is nearest above `offset` (the action at the caret), if any. */
export function actionAt(text: string, offset: number): string | null {
const lines = text.slice(0, offset).split("\n");
for (let i = lines.length - 1; i >= 0; i--) {
const m = DEF.exec(lines[i]!);
if (m) return m[1]!;
if (/^\s*class\s/.test(lines[i]!)) return null;
}
return null;
}
/** The 0-based line of `def name` in `text`. */
export function defLine(text: string, name: string): number | undefined {
const i = text.split("\n").findIndex((l) => DEF.exec(l)?.[1] === name);
return i < 0 ? undefined : i;
}
/** The view's action: its name up to the first dot; partials (`_form`) have none. */
const viewAction = (file: string) => (file.startsWith("_") ? null : file.split(".")[0]!);
async function views(fs: RailsFs, root: string, resource: string, action: string | null): Promise<RailsTarget[]> {
const dir = `${root}/app/views/${resource}`;
const names = (await fs.list(dir)) ?? [];
return names
.filter((n) => action === null || n.startsWith(`${action}.`))
.sort()
.map((n) => ({ path: `${dir}/${n}`, group: "view" }));
}
async function existing(fs: RailsFs, path: string, group: RailsGroup, label?: string): Promise<RailsTarget[]> {
const dir = path.slice(0, path.lastIndexOf("/"));
const names = await fs.list(dir);
return names?.includes(path.slice(dir.length + 1)) ? [{ path, group, label }] : [];
}
async function controller(fs: RailsFs, root: string, resource: string, action: string | null): Promise<RailsTarget[]> {
const path = `${root}/app/controllers/${resource}_controller.rb`;
const text = await fs.read(path);
if (text === null) return [];
const line = action ? defLine(text, action) : undefined;
const name = controllerName(resource);
return [{ path, group: "controller", line, label: line === undefined ? name : `${name}#${action}` }];
}
const lastSegment = (resource: string) => resource.slice(resource.lastIndexOf("/") + 1);
export async function railsTargets(path: string, text: string, offset: number, fs: RailsFs): Promise<RailsTarget[]> {
const file = railsFile(path);
if (!file) return [];
const { root } = file;
switch (file.kind) {
case "controller": {
const action = actionAt(text, offset);
return [
...(await views(fs, root, file.resource, action)),
...(await existing(fs, `${root}/app/helpers/${file.resource}_helper.rb`, "helper")),
...(await existing(fs, `${root}/app/models/${singularize(lastSegment(file.resource))}.rb`, "model")),
];
}
case "view":
return [
...(await controller(fs, root, file.resource, viewAction(file.file))),
...(await existing(fs, `${root}/app/helpers/${file.resource}_helper.rb`, "helper")),
];
case "helper":
return [...(await controller(fs, root, file.resource, null)), ...(await views(fs, root, file.resource, null))];
case "model": {
const table = pluralize(lastSegment(file.model));
const migrations = ((await fs.list(`${root}/db/migrate`)) ?? [])
.filter((n) => new RegExp(`^\\d+_\\w*(?:create|to)_${table}\\.rb$`).test(n))
.sort()
.map((n): RailsTarget => ({ path: `${root}/db/migrate/${n}`, group: "migration" }));
return [...(await controller(fs, root, table, null)), ...migrations];
}
}
}
+87
Переглянути файл
@@ -0,0 +1,87 @@
/**
* Rails: Navigate › Related Symbol between controllers, actions, views, helpers, models and
* migrations; Go to Declaration on callback method symbols and on routes' controller actions.
*/
import { Text } from "@codemirror/state";
import { docOf } from "@/editor/lsp/lsp";
import { offsetsToRange } from "@/editor/lsp/positions";
import { registerNavigationProvider } from "@/editor/navigationProviders";
import { registerRelatedProvider } from "@/editor/relatedProviders";
import { tx } from "@/platform/i18n";
import { call, commands, type Location } from "@/platform/ipc";
import { controllerName, defLine, railsTargets, type RailsFs, type RailsGroup } from "./conventions";
import { railsReferenceAt } from "./references";
const fs: RailsFs = {
list: async (dir) => {
try {
return (await call(commands.fsReadDir(dir))).filter((e) => e.kind !== "dir").map((e) => e.name);
} catch {
return null;
}
},
read: async (path) => {
try {
return await call(commands.fsReadText(path));
} catch {
return null;
}
},
};
const GROUPS: Record<RailsGroup, () => string> = {
view: () => tx("View"),
controller: () => tx("Controller"),
helper: () => tx("Helper"),
model: () => tx("Model"),
migration: () => tx("Migration"),
};
/** The `def name` in `text` as a navigation target, at the method name. */
function method(path: string, text: string, name: string, label?: string): (Location & { name?: string }) | null {
const line = defLine(text, name);
if (line === undefined) return null;
const doc = Text.of(text.split("\n"));
const at = doc.line(line + 1);
const col = at.text.indexOf(name, at.text.indexOf("def") + 3);
return { path, range: offsetsToRange(doc, at.from + col, at.from + col + name.length), name: label };
}
const ROUTES = /\/config\/routes(?:\/[^/]+)?\.rb$/;
export function activate(): () => void {
const unregisterRelated = registerRelatedProvider(async (ctx) => {
const targets = await railsTargets(ctx.path, ctx.text, ctx.offset, fs);
return targets.map((t) => ({ path: t.path, line: t.line, label: t.label, group: GROUPS[t.group]() }));
});
const unregisterNavigation = registerNavigationProvider(async (view, offset) => {
const doc = docOf(view);
if (!doc || doc.virtual || !doc.path.endsWith(".rb")) return null;
const routes = ROUTES.exec(doc.path);
const text = view.state.doc.toString();
const ref = railsReferenceAt(text, offset, !!routes);
if (!ref) return null;
if (ref.kind === "method") {
const own = method(doc.path, text, ref.name);
const app = doc.path.match(/^(.*)\/app\/(controllers|models)\//);
const base =
app && !own ? `${app[1]}/app/${app[2]}/application_${app[2] === "models" ? "record" : "controller"}.rb` : null;
const baseText = base ? await fs.read(base) : null;
const target = own ?? (base && baseText !== null ? method(base, baseText, ref.name) : null);
return target ? { from: ref.from, to: ref.to, targets: [target] } : null;
}
const root = doc.path.slice(0, routes!.index);
const path = `${root}/app/controllers/${ref.resource}_controller.rb`;
const controller = await fs.read(path);
if (controller === null) return null;
const name = controllerName(ref.resource);
const target = ref.action
? method(path, controller, ref.action, `${name}#${ref.action}`)
: { path, range: offsetsToRange(Text.of([""]), 0, 0), name };
return target ? { from: ref.from, to: ref.to, targets: [target] } : null;
});
return () => {
unregisterNavigation();
unregisterRelated();
};
}
+34
Переглянути файл
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { railsReferenceAt } from "./references";
const at = (text: string, routes = false) => railsReferenceAt(text.replace("|", ""), text.indexOf("|"), routes);
describe("rails references", () => {
it("reads method symbols in callbacks", () => {
expect(at(" before_action :load_|user, only: [:show]")).toEqual({
kind: "method",
name: "load_user",
from: 17,
to: 26,
});
expect(at(" before_action :load_user, if: :ad|min?")).toMatchObject({ name: "admin?" });
expect(at(" skip_before_action :auth|enticate!")).toMatchObject({ name: "authenticate!" });
expect(at(" helper_method :current|_user")).toMatchObject({ name: "current_user" });
expect(at(" validate :email_|format")).toMatchObject({ name: "email_format" });
expect(at(" has_many :po|sts")).toBeNull();
expect(at(" before_action Foo::Ba|r")).toBeNull();
});
it("reads controller actions in routes", () => {
expect(at(' get "login", to: "sess|ions#new"', true)).toMatchObject({ resource: "sessions", action: "new" });
expect(at(" get '/x' => 'admin/rep|orts#index'", true)).toMatchObject({
resource: "admin/reports",
action: "index",
});
expect(at(" resources :pho|tos", true)).toMatchObject({ resource: "photos", action: null });
expect(at(" resources :users, :pos|ts", true)).toMatchObject({ resource: "posts" });
expect(at(" resource :prof|ile", true)).toMatchObject({ resource: "profiles" });
expect(at(" root 'pages#ho|me'", true)).toMatchObject({ resource: "pages", action: "home" });
expect(at(" mount Sidekiq::W|eb", true)).toBeNull();
});
});
+62
Переглянути файл
@@ -0,0 +1,62 @@
/**
* Rails references navigated with Go to Declaration: method symbols in callbacks
* (`before_action :load_user`, `if: :admin?`) and controller actions in `config/routes.rb`
* (`to: "users#index"`, `resources :users`).
*/
import { pluralize } from "./conventions";
export type RailsReference =
| { kind: "method"; name: string; from: number; to: number }
| { kind: "action"; resource: string; action: string | null; from: number; to: number };
/** Class-level calls whose symbol arguments name methods of the class. */
const CALLBACK =
/^\s*(?:(?:prepend|append|skip)_)?(?:before|after|around)_[a-z_]+\b|^\s*(?:helper_method|validate|rescue_from|after_commit|after_rollback)\b/;
const SYMBOL = /(^|[^\w:]):([A-Za-z_]\w*[!?]?)/g;
const ACTION_STRING = /(["'])((?:[a-z0-9_]+\/)*[a-z0-9_]+)#([a-z_]\w*[!?]?)\1/g;
const RESOURCES = /^\s*(resources?)\s+((?::[a-z_]\w*\s*,\s*)*:[a-z_]\w*)/;
function lineAt(text: string, offset: number): { line: string; start: number } {
const start = text.lastIndexOf("\n", offset - 1) + 1;
const end = text.indexOf("\n", offset);
return { line: text.slice(start, end < 0 ? text.length : end), start };
}
export function railsReferenceAt(text: string, offset: number, routes: boolean): RailsReference | null {
const { line, start } = lineAt(text, offset);
const col = offset - start;
if (routes) {
for (const m of line.matchAll(ACTION_STRING)) {
if (col > m.index && col < m.index + m[0].length - 1)
return {
kind: "action",
resource: m[2]!,
action: m[3]!,
from: start + m.index + 1,
to: start + m.index + m[0].length - 1,
};
}
const r = RESOURCES.exec(line);
if (r) {
for (const s of r[2]!.matchAll(/:([a-z_]\w*)/g)) {
const from = r.index + r[0].length - r[2]!.length + s.index;
if (col >= from && col < from + s[0].length)
return {
kind: "action",
resource: r[1] === "resource" ? pluralize(s[1]!) : s[1]!,
action: null,
from: start + from + 1,
to: start + from + s[0].length,
};
}
}
return null;
}
if (!CALLBACK.test(line)) return null;
for (const m of line.matchAll(SYMBOL)) {
const at = m.index + m[1]!.length;
if (col >= at && col < m.index + m[0].length)
return { kind: "method", name: m[2]!, from: start + at + 1, to: start + m.index + m[0].length };
}
return null;
}
+1
Переглянути файл
@@ -8,6 +8,7 @@ export const IDEA_ACTIONS: Readonly<Record<string, string>> = {
GotoTypeDeclaration: "navigate.typeDeclaration",
GotoSuperMethod: "navigate.superMethod",
GotoTest: "navigate.gotoTest",
GotoRelated: "navigate.relatedSymbol",
GotoClass: "navigate.gotoClass",
GotoFile: "navigate.gotoFile",
GotoSymbol: "navigate.gotoSymbol",
+1
Переглянути файл
@@ -56,6 +56,7 @@ export const intellijMacos: Record<string, string[]> = {
"navigate.nextEditLocation": [],
"navigate.gotoTest": ["Meta+Shift+T"],
"navigate.superMethod": ["Meta+U"],
"navigate.relatedSymbol": ["Ctrl+Meta+Up"],
"navigate.nextMethod": ["Ctrl+Shift+Down"],
"navigate.previousMethod": ["Ctrl+Shift+Up"],
"navigate.nextOccurrence": ["Meta+Alt+Down"],
+1
Переглянути файл
@@ -57,6 +57,7 @@ export const intellijWindows: Record<string, string[]> = {
"navigate.nextEditLocation": [],
"navigate.gotoTest": ["Ctrl+Shift+T"],
"navigate.superMethod": ["Ctrl+U"],
"navigate.relatedSymbol": ["Ctrl+Alt+Home"],
"navigate.nextMethod": ["Alt+Down"],
"navigate.previousMethod": ["Alt+Up"],
"navigate.nextOccurrence": ["Ctrl+Alt+Down"],
+108 -2
Переглянути файл
@@ -1306,7 +1306,6 @@
"sse (Server-Sent Events)": "sse (Server-Sent Events)",
"One KEY=VALUE entry per line.": "One KEY=VALUE entry per line.",
"One Header=Value entry per line.": "One Header=Value entry per line.",
"Leave empty to enable for all agents, or list agent IDs separated by commas.": "Leave empty to enable for all agents, or list agent IDs separated by commas.",
"External MCP Servers…": "External MCP Servers…",
"Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.": "Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.",
"No matching remote branches": "No matching remote branches",
@@ -2033,5 +2032,112 @@
"Create Step Definition": "Create Step Definition",
"Create step definition '{text}'": "Create step definition '{text}'",
"Undefined step": "Undefined step",
"Reports steps of a .feature file that no step definition of the project matches (Cucumber expressions and regular expressions, in JavaScript, TypeScript, Java and Kotlin files). Projects without step definitions in those files are not checked. Alt+Enter creates the definition.": "Reports steps of a .feature file that no step definition of the project matches (Cucumber expressions and regular expressions, in JavaScript, TypeScript, Java and Kotlin files). Projects without step definitions in those files are not checked. Alt+Enter creates the definition."
"Reports steps of a .feature file that no step definition of the project matches (Cucumber expressions and regular expressions, in JavaScript, TypeScript, Java and Kotlin files). Projects without step definitions in those files are not checked. Alt+Enter creates the definition.": "Reports steps of a .feature file that no step definition of the project matches (Cucumber expressions and regular expressions, in JavaScript, TypeScript, Java and Kotlin files). Projects without step definitions in those files are not checked. Alt+Enter creates the definition.",
"Configure MCP servers for this session": "Configure MCP servers for this session",
"MCP servers ({active}/{total} active · {overrides} session overrides)": "MCP servers ({active}/{total} active · {overrides} session overrides)",
"MCP servers ({active}/{total} active)": "MCP servers ({active}/{total} active)",
"MCP servers": "MCP servers",
"Session MCP Servers": "Session MCP Servers",
"Filter MCP servers…": "Filter MCP servers…",
"Filter MCP servers": "Filter MCP servers",
"Session": "Session",
"Built-in IDE tools": "Built-in IDE tools",
"Enable in Settings": "Enable in Settings",
"Enable openidea for this session": "Enable openidea for this session",
"Agent Config": "Agent Config",
"Active via {source}": "Active via {source}",
"Import into Global settings to toggle per session and share across agents": "Import into Global settings to toggle per session and share across agents",
"No matching MCP servers.": "No matching MCP servers.",
"Changes apply on the next message.": "Changes apply on the next message.",
"Toggles here apply to this session only.": "Toggles here apply to this session only.",
"Overrides Global": "Overrides Global",
"Approve…": "Approve…",
"Enable {name} for this session": "Enable {name} for this session",
"Shared across projects · secrets stored in Keychain": "Shared across projects · secrets stored in Keychain",
".openidea/settings.toml · overrides Global by name": ".openidea/settings.toml · overrides Global by name",
"Copied {name} to Global MCP servers.": "Copied {name} to Global MCP servers.",
"Copied {name} to Project MCP servers.": "Copied {name} to Project MCP servers.",
"Selected MCP servers are already configured in that scope.": "Selected MCP servers are already configured in that scope.",
"Imported {count} MCP servers into Global settings.": "Imported {count} MCP servers into Global settings.",
"Imported {count} MCP servers into Project settings.": "Imported {count} MCP servers into Project settings.",
"Edit as JSON…": "Edit as JSON…",
"Copy to Global": "Copy to Global",
"Copy to Project": "Copy to Project",
"Add Server": "Add Server",
"Add from JSON": "Add from JSON",
"MCP configuration levels": "MCP configuration levels",
"All Levels": "All Levels",
"Agent Configs": "Agent Configs",
"Built-in IDE": "Built-in IDE",
"All agents": "All agents",
"Exposes OpenIDEA's code intelligence, diagnostics, refactorings, and run configurations to coding agents. Can also be toggled per session from the composer MCP menu.": "Exposes OpenIDEA's code intelligence, diagnostics, refactorings, and run configurations to coding agents. Can also be toggled per session from the composer MCP menu.",
"IDE MCP Settings": "IDE MCP Settings",
"Overridden by Project": "Overridden by Project",
"Needs Approval": "Needs Approval",
"{count} MCP tools": "{count} MCP tools",
"Test {name}": "Test {name}",
"Testing connection…": "Testing connection…",
"Connection failed": "Connection failed",
"Env vars": "Env vars",
"Tools ({count})": "Tools ({count})",
"Tools & Connection": "Tools & Connection",
"Connecting and listing tools…": "Connecting and listing tools…",
"Connected, no tools advertised by this server.": "Connected, no tools advertised by this server.",
"Click Test Connection to run MCP handshake and inspect available tools.": "Click Test Connection to run MCP handshake and inspect available tools.",
"Test Connection": "Test Connection",
"Retry Connection": "Retry Connection",
"Detected {count} MCP servers in external agent config directories ({sources}).": "Detected {count} MCP servers in external agent config directories ({sources}).",
"Review & Import": "Review & Import",
"Import target scope": "Import target scope",
"Import into Global (settings.toml)": "Import into Global (settings.toml)",
"Import into Project (.openidea/settings.toml)": "Import into Project (.openidea/settings.toml)",
"Overwrite existing": "Overwrite existing",
"Rescan": "Rescan",
"Import Selected ({count})": "Import Selected ({count})",
"Import Selected": "Import Selected",
"No external MCP configuration files found in ~/.copilot, ~/.claude.json, ~/.codex, ~/.cursor, ~/.gemini, ~/.jetbrains/mcp, or the current project.": "No external MCP configuration files found in ~/.copilot, ~/.claude.json, ~/.codex, ~/.cursor, ~/.gemini, ~/.jetbrains/mcp, or the current project.",
"Native to {agent}": "Native to {agent}",
"In Global": "In Global",
"In Project": "In Project",
"{count} env": "{count} env",
"{count} headers": "{count} headers",
"Configure via structured fields or paste a standard mcpServers JSON snippet.": "Configure via structured fields or paste a standard mcpServers JSON snippet.",
"Editor mode": "Editor mode",
"JSON:": "JSON:",
"Accepts mcpServers, servers, or a single server JSON object.": "Accepts mcpServers, servers, or a single server JSON object.",
"Leave empty to enable for all agents, or pick specific coding agents.": "Leave empty to enable for all agents, or pick specific coding agents.",
"Related Symbol…": "Related Symbol…",
"Choose Target": "Choose Target",
"No related symbols": "No related symbols",
"Header": "Header",
"Controller": "Controller",
"Helper": "Helper",
"Model": "Model",
"Migration": "Migration",
"Change Signature": "Change Signature",
"Visibility:": "Visibility:",
"Return type:": "Return type:",
"package-private": "package-private",
"Delegate via overloading method": "Delegate via overloading method",
"Signature Preview": "Signature Preview",
"Method name is not a valid identifier": "Method name is not a valid identifier",
"Return type is not specified": "Return type is not specified",
"Parameter type is not specified": "Parameter type is not specified",
"Parameter name is not a valid identifier": "Parameter name is not a valid identifier",
"Duplicate parameter name": "Duplicate parameter name",
"Default value is not specified for a new parameter": "Default value is not specified for a new parameter",
"Visibility": "Visibility",
"Change Signature of '{name}'": "Change Signature of '{name}'",
"Move {name} to Package": "Move {name} to Package",
"Current package": "Current package",
"No packages to move the file to": "No packages to move the file to",
"No fields or parameters to move the method to": "No fields or parameters to move the method to",
"Move Instance Method {name}": "Move Instance Method {name}",
"Move {name} to Class": "Move {name} to Class",
"No classes to move to": "No classes to move to",
"Move {name} to a new file": "Move {name} to a new file",
"Move {name} to another class": "Move {name} to another class",
"(default package)": "(default package)",
"Field": "Field",
"Move": "Move"
}
+105 -3
Переглянути файл
@@ -1548,7 +1548,7 @@
"Implement Members": "实现成员",
"Implementation(s)": "实现",
"Imports": "导入",
"In Project": "在项目",
"In Project": "已在项目",
"Include": "包括",
"Include non-project items": "包括非项目项",
"Include untracked files": "包括未跟踪的文件",
@@ -7700,7 +7700,6 @@
"sse (Server-Sent Events)": "sse(服务器发送事件)",
"One KEY=VALUE entry per line.": "每行一个 KEY=VALUE 条目。",
"One Header=Value entry per line.": "每行一个 Header=Value 条目。",
"Leave empty to enable for all agents, or list agent IDs separated by commas.": "留空则为所有代理启用,或用逗号分隔列出代理 ID。",
"Maven project could not be configured": "无法配置 Maven 项目",
"External MCP Servers…": "外部 MCP 服务器…",
"Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.": "打开“设置 › 智能体 › 外部 MCP 服务器”:配置编程智能体使用的用户级和工作区级 MCP 服务器。",
@@ -8420,5 +8419,108 @@
"Create Step Definition": "创建步骤定义",
"Create step definition '{text}'": "创建步骤定义“{text}”",
"Undefined step": "未定义的步骤",
"Reports steps of a .feature file that no step definition of the project matches (Cucumber expressions and regular expressions, in JavaScript, TypeScript, Java and Kotlin files). Projects without step definitions in those files are not checked. Alt+Enter creates the definition.": "报告 .feature 文件中项目里没有任何步骤定义匹配的步骤(按 JavaScript、TypeScript、Java 和 Kotlin 文件中的 Cucumber 表达式和正则表达式匹配)。这些文件里没有步骤定义的项目不做检查。按 Alt+Enter 可创建定义。"
"Reports steps of a .feature file that no step definition of the project matches (Cucumber expressions and regular expressions, in JavaScript, TypeScript, Java and Kotlin files). Projects without step definitions in those files are not checked. Alt+Enter creates the definition.": "报告 .feature 文件中项目里没有任何步骤定义匹配的步骤(按 JavaScript、TypeScript、Java 和 Kotlin 文件中的 Cucumber 表达式和正则表达式匹配)。这些文件里没有步骤定义的项目不做检查。按 Alt+Enter 可创建定义。",
"Configure MCP servers for this session": "配置当前会话的 MCP 服务器",
"MCP servers ({active}/{total} active · {overrides} session overrides)": "MCP 服务器(已启用 {active}/{total} · {overrides} 项会话覆盖)",
"MCP servers ({active}/{total} active)": "MCP 服务器(已启用 {active}/{total})",
"MCP servers": "MCP 服务器",
"Session MCP Servers": "会话 MCP 服务器",
"Filter MCP servers…": "筛选 MCP 服务器…",
"Filter MCP servers": "筛选 MCP 服务器",
"Session": "会话",
"Built-in IDE tools": "内置 IDE 工具",
"Enable in Settings": "在设置中启用",
"Enable openidea for this session": "在当前会话启用 openidea",
"Agent Config": "智能体配置",
"Active via {source}": "通过 {source} 生效",
"Import into Global settings to toggle per session and share across agents": "导入到全局设置以支持按会话开关并在所有智能体间共享",
"No matching MCP servers.": "没有匹配的 MCP 服务器。",
"Changes apply on the next message.": "更改将在下一条消息生效。",
"Toggles here apply to this session only.": "此处的开关仅对当前会话生效。",
"Overrides Global": "覆盖全局配置",
"Approve…": "批准…",
"Enable {name} for this session": "在当前会话启用 {name}",
"Shared across projects · secrets stored in Keychain": "跨项目共享 · 密钥保存在系统钥匙串中",
".openidea/settings.toml · overrides Global by name": ".openidea/settings.toml · 同名项覆盖全局配置",
"Copied {name} to Global MCP servers.": "已将 {name} 复制到全局 MCP 服务器。",
"Copied {name} to Project MCP servers.": "已将 {name} 复制到项目 MCP 服务器。",
"Selected MCP servers are already configured in that scope.": "所选 MCP 服务器已在该作用域中配置。",
"Imported {count} MCP servers into Global settings.": "已将 {count} 个 MCP 服务器导入到全局设置。",
"Imported {count} MCP servers into Project settings.": "已将 {count} 个 MCP 服务器导入到项目设置。",
"Edit as JSON…": "以 JSON 编辑…",
"Copy to Global": "复制到全局",
"Add Server": "添加服务器",
"Add from JSON": "从 JSON 添加",
"MCP configuration levels": "MCP 配置层级",
"All Levels": "全部层级",
"Agent Configs": "智能体配置",
"Built-in IDE": "内置 IDE",
"All agents": "所有智能体",
"Exposes OpenIDEA's code intelligence, diagnostics, refactorings, and run configurations to coding agents. Can also be toggled per session from the composer MCP menu.": "向编码智能体提供 OpenIDEA 的代码智能、诊断、重构和运行配置能力。也可在输入框的 MCP 菜单中按会话单独开关。",
"IDE MCP Settings": "IDE MCP 设置",
"Overridden by Project": "已被项目覆盖",
"Needs Approval": "需批准",
"{count} MCP tools": "{count} 个 MCP 工具",
"Test {name}": "测试 {name}",
"Testing connection…": "正在测试连接…",
"Connection failed": "连接失败",
"Env vars": "环境变量",
"Tools ({count})": "工具({count})",
"Tools & Connection": "工具与连接",
"Connecting and listing tools…": "正在连接并获取工具列表…",
"Connected, no tools advertised by this server.": "已连接,该服务器未声明任何工具。",
"Click Test Connection to run MCP handshake and inspect available tools.": "点击“测试连接”以执行 MCP 握手并查看可用工具。",
"Retry Connection": "重试连接",
"Detected {count} MCP servers in external agent config directories ({sources}).": "在外部智能体配置目录({sources})中检测到 {count} 个 MCP 服务器。",
"Review & Import": "查看并导入",
"Import target scope": "导入目标作用域",
"Import into Global (settings.toml)": "导入到全局(settings.toml)",
"Import into Project (.openidea/settings.toml)": "导入到项目(.openidea/settings.toml)",
"Overwrite existing": "覆盖已有同名项",
"Rescan": "重新扫描",
"Import Selected ({count})": "导入所选({count})",
"Import Selected": "导入所选",
"No external MCP configuration files found in ~/.copilot, ~/.claude.json, ~/.codex, ~/.cursor, ~/.gemini, ~/.jetbrains/mcp, or the current project.": "在 ~/.copilot、~/.claude.json、~/.codex、~/.cursor、~/.gemini、~/.jetbrains/mcp 或当前项目中未发现外部 MCP 配置文件。",
"Native to {agent}": "原生归属 {agent}",
"In Global": "已在全局",
"{count} env": "{count} 项环境变量",
"{count} headers": "{count} 项请求头",
"Configure via structured fields or paste a standard mcpServers JSON snippet.": "可通过表单字段配置,也可直接粘贴标准 mcpServers JSON 片段。",
"Editor mode": "编辑模式",
"JSON:": "JSON:",
"Accepts mcpServers, servers, or a single server JSON object.": "支持 mcpServers、servers 或单个服务器 JSON 对象。",
"Leave empty to enable for all agents, or pick specific coding agents.": "留空则对所有智能体启用,也可选择特定的编码智能体。",
"Related Symbol…": "相关符号…",
"Choose Target": "选择目标",
"No related symbols": "没有相关符号",
"Header": "头文件",
"Controller": "控制器",
"Helper": "辅助模块",
"Model": "模型",
"Migration": "迁移",
"Change Signature": "更改签名",
"Visibility:": "可见性:",
"Return type:": "返回类型:",
"package-private": "包私有",
"Delegate via overloading method": "通过重载方法委托",
"Signature Preview": "签名预览",
"Method name is not a valid identifier": "方法名不是有效的标识符",
"Return type is not specified": "未指定返回类型",
"Parameter type is not specified": "未指定形参类型",
"Parameter name is not a valid identifier": "形参名不是有效的标识符",
"Duplicate parameter name": "形参名重复",
"Default value is not specified for a new parameter": "未给新形参指定默认值",
"Visibility": "可见性",
"Change Signature of '{name}'": "更改 '{name}' 的签名",
"Move {name} to Package": "将 {name} 移动到包",
"Current package": "当前包",
"No packages to move the file to": "没有可移动到的包",
"No fields or parameters to move the method to": "没有可移动到的字段或形参",
"Move Instance Method {name}": "移动实例方法 {name}",
"Move {name} to Class": "将 {name} 移动到类",
"No classes to move to": "没有可移动到的类",
"Move {name} to a new file": "将 {name} 移动到新文件",
"Move {name} to another class": "将 {name} 移动到其他类",
"(default package)": "(默认包)",
"Field": "字段"
}